Last active
February 7, 2021 15:36
-
-
Save AlecKazakova/6a6b33c7a961756ed038408df4858be3 to your computer and use it in GitHub Desktop.
Extension functions on SQLBrite's BriteDatabase to make working with SQLDelight easier
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fun BriteDatabase.createQuery(query: SqlDelightStatement) = createQuery(query.tables, query.statement, *query.args) | |
inline fun <T: SqlDelightCompiledStatement> BriteDatabase.bindAndExecute(compiledStatement: T, bind: T.() -> Unit): Long { | |
synchronized(compiledStatement) { | |
compiledStatement.bind() | |
return when (compiledStatement) { | |
is SqlDelightCompiledStatement.Insert -> { | |
executeInsert(compiledStatement.table, compiledStatement.program) | |
} | |
is SqlDelightCompiledStatement.Update -> { | |
executeUpdateDelete(compiledStatement.table, compiledStatement.program).toLong() | |
} | |
is SqlDelightCompiledStatement.Delete -> { | |
executeUpdateDelete(compiledStatement.table, compiledStatement.program).toLong() | |
} | |
else -> throw IllegalStateException("Call execute() on non-mutating compiled statements.") | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
CREATE TABLE user ( | |
name TEXT NOT NULL, | |
age INTEGER AS Integer NOT NULL | |
); | |
selectUsersForName: | |
SELECT * | |
FROM user | |
WHERE name = ?; | |
insertUser: | |
INSERT INTO user | |
VALUES (?, ?); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class UserManager(openHelper: SQLiteOpenHelper, val briteDatabase: BriteDatabase) { | |
private val insertUser: UserModel.InsertUser by lazy { | |
UserModel.InsertUser(openHelper.writableDatabase) | |
} | |
fun insert(name: String, age: Int): Long { | |
return briteDatabase.bindAndExecute(insertUser) { | |
bind(name, age) | |
} | |
} | |
fun users(name: String): Observable<List<User>> { | |
return briteDatabase.createQuery(User.FACTORY.selectUsersForName(name)) | |
.mapToList(User.FACTORY.selectUsersForNameMapper::map) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@AlecStrong What is the license of the extension function?