Skip to content

Instantly share code, notes, and snippets.

@AlecKazakova
Last active February 7, 2021 15:36
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AlecKazakova/6a6b33c7a961756ed038408df4858be3 to your computer and use it in GitHub Desktop.
Save AlecKazakova/6a6b33c7a961756ed038408df4858be3 to your computer and use it in GitHub Desktop.
Extension functions on SQLBrite's BriteDatabase to make working with SQLDelight easier
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.")
}
}
}
CREATE TABLE user (
name TEXT NOT NULL,
age INTEGER AS Integer NOT NULL
);
selectUsersForName:
SELECT *
FROM user
WHERE name = ?;
insertUser:
INSERT INTO user
VALUES (?, ?);
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)
}
}
@Naitbit
Copy link

Naitbit commented Mar 3, 2017

@AlecStrong What is the license of the extension function?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment