Database Access
Connecting to the database and setting up the persistence context is the first step in using KIST ORM effectively.
Persistence Context
The PersistenceContext object acts as the central hub for database configuration and connection management.
Initialization
You must initialize the connection before performing any database operations. This usually happens in your application's main() function or startup logic.
import io.knative.kist.config.PersistenceContext
import io.knative.kist.config.SqlLiteFileConfig
// Import the generated processAnnotations method (often in a specific package, check your generated code or docs)
// Typically acts as an extension or static call
import io.knative.kist.processed.KistRegister.processAnnotations
fun initDatabase() {
// 1. Create Connection
PersistenceContext.createConnection(
SqlLiteFileConfig(
dbName = "app.db",
path = "/var/lib/myapp/db/", // Optional: defaults to working dir if omitted
createStatements = listOf(
"CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT)",
"CREATE TABLE IF NOT EXISTS pets (id INTEGER PRIMARY KEY, name TEXT, owner_id INTEGER)"
)
)
)
// 2. Process Annotations (Register Generated Code)
// This step is critical. It loads the metadata generated by KSP so the framework knows about your Entities and DAOs.
PersistenceContext.processAnnotations()
}
Configuration Options
SqlLiteFileConfig
Used for standard, persistent file-based SQLite databases.
dbName: The name of the database file (e.g.,data.sqlite).path: Directory path where the file is stored.createStatements: A list of SQL statements to execute immediately after opening the connection. This is the recommended place to define your schema (CREATE TABLE, etc.) if you don't use an external migration tool.
InMemoryConfig
Used primarily for unit testing or temporary data storage that should not persist after the application closes.
import io.knative.kist.config.InMemoryConfig
PersistenceContext.createConnection(
InMemoryConfig(
dbName = "test.db",
createStatements = schemaSqlList
)
)
Accessing the Connection
While you will primarily interact with the database through DAOs, you can access the underlying connection directly for advanced use cases or raw SQL execution.
val connection = PersistenceContext.connection
// Execute a raw statement
connection.withStatement("INSERT INTO logs (msg) VALUES (?)") {
bindString(1, "Log message")
execute()
}
Transactions
KIST provides basic transaction support. (Refer to specific Transactional helpers or direct connection API if available in your version).
// Example placeholder for transaction context
// Transactional.runInTransaction {
// dao.insert(item1)
// dao.insert(item2)
// }