package com.vgmlr.kerf
import android.content.Context
import androidx.room.*
import kotlinx.coroutines.flow.Flow
@Entity(tableName = "notes")
data class Note(
@PrimaryKey(autoGenerate = true) val id: Int = 0,
val title: String,
val content: String,
val replies: String? = null,
val lastShared: Long? = null,
val lastCopied: Long? = null,
val isPinned: Boolean = false,
val isImported: Boolean = false,
val createdAt: Long = System.currentTimeMillis(),
val updatedAt: Long = System.currentTimeMillis()
)
@Dao
interface NoteDao {
@Query("SELECT * FROM notes ORDER BY isPinned DESC, updatedAt DESC")
fun getAll(): Flow<List<Note>>
@Query("SELECT * FROM notes WHERE id = :id")
fun getByIdFlow(id: Int): Flow<Note?>
@Query("SELECT * FROM notes WHERE id = :id")
suspend fun getById(id: Int): Note?
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insert(note: Note): Long
@Update
suspend fun update(note: Note)
@Query("DELETE FROM notes WHERE id = :id")
suspend fun deleteById(id: Int)
}
@Database(entities = [Note::class], version = 9, exportSchema = false)
abstract class AppDb : RoomDatabase() {
abstract fun dao(): NoteDao
companion object {
@Volatile
private var INSTANCE: AppDb? = null
fun getDatabase(context: Context): AppDb {
return INSTANCE ?: synchronized(this) {
val instance = Room.databaseBuilder(
context.applicationContext,
AppDb::class.java,
"kerf-db"
).fallbackToDestructiveMigration().build()
INSTANCE = instance
instance
}
}
}
}