55 lines
1.7 KiB
Kotlin
Raw Normal View History

2019-06-04 12:12:40 +10:00
package org.thoughtcrime.securesms.loki
import android.content.ContentValues
2019-06-04 12:12:40 +10:00
import net.sqlcipher.Cursor
import net.sqlcipher.database.SQLiteDatabase
2019-06-24 14:10:09 +10:00
import org.whispersystems.signalservice.internal.util.Base64
2019-06-04 12:12:40 +10:00
fun <T> SQLiteDatabase.get(table: String, query: String, arguments: Array<String>, get: (Cursor) -> T): T? {
var cursor: Cursor? = null
try {
2019-06-19 15:45:40 +10:00
cursor = query(table, null, query, arguments, null, null, null)
2019-06-04 12:12:40 +10:00
if (cursor != null && cursor.moveToFirst()) { return get(cursor) }
} catch (e: Exception) {
// Do nothing
} finally {
cursor?.close()
}
return null
}
fun <T> SQLiteDatabase.getAll(table: String, query: String, arguments: Array<String>, get: (Cursor) -> T): List<T> {
var list = mutableListOf<T>()
var cursor: Cursor? = null
try {
cursor = query(table, null, query, arguments, null, null, null)
while (cursor != null && cursor.moveToNext()) {
list.add(get(cursor))
}
return list
} catch (e: Exception) {
// Do nothing
} finally {
cursor?.close()
}
return listOf()
}
2019-06-24 14:10:09 +10:00
fun SQLiteDatabase.insertOrUpdate(table: String, values: ContentValues, query: String, arguments: Array<String>) {
2019-06-19 15:45:40 +10:00
val id = insertWithOnConflict(table, null, values, SQLiteDatabase.CONFLICT_IGNORE).toInt()
if (id == -1) {
2019-06-24 14:10:09 +10:00
update(table, values, query, arguments)
}
}
2019-06-04 12:12:40 +10:00
fun Cursor.getInt(columnName: String): Int {
2019-06-19 15:45:40 +10:00
return getInt(getColumnIndexOrThrow(columnName))
2019-06-04 12:12:40 +10:00
}
fun Cursor.getString(columnName: String): String {
2019-06-19 15:45:40 +10:00
return getString(getColumnIndexOrThrow(columnName))
2019-06-04 12:12:40 +10:00
}
fun Cursor.getBase64EncodedData(columnName: String): ByteArray {
2019-06-19 15:45:40 +10:00
return Base64.decode(getString(columnName))
2019-06-04 12:12:40 +10:00
}