Skip to content

Database Layer

Kirak’s database layer provides fully asynchronous database access and abstracts SQL dialect variations behind a unified interface. Switching between MySQL, PostgreSQL, and SQLite requires changing only a single setting: database.type in kirak.json.

flowchart TD
A["Kirak Facade<br/>(fetch, create, update, delete, etc.)"] --> B["DatabaseDriver Factory<br/>(create_database_driver)"]
B --> C["Async Connection Pool<br/>(asyncmy / asyncpg / sqlite3)"]
C --> D["Dialect Translation Engine"]
D --> E["MySQL 8.0.13+<br/>(%s placeholders, lastrowid)"]
D --> F["PostgreSQL 13+<br/>($N placeholders, RETURNING id, ILIKE)"]
D --> G["SQLite 3.35+<br/>(?N placeholders, RETURNING id, WAL)"]

Database Driver Extra database.type Setting Default Port
MySQL 8.0.13+ pip install "kirak[mysql]" mysql 3306
PostgreSQL 13+ pip install "kirak[postgres]" postgres or postgresql 5432
SQLite 3.35+ Native sqlite3 module (built-in) sqlite N/A (Local file)

Install all drivers for multi-database test environments:

Terminal window
pip install "kirak[all-databases]"

Configure database settings in kirak.json:

{
"database": {
"type": "postgres",
"host": "localhost",
"port": 5432,
"user": "myuser",
"name": "myapp",
"pool_min": 2,
"pool_max": 20,
"pool_recycle_seconds": 3600
}
}

The database password is a secret loaded from the DB_PASSWORD environment variable. database.name is the only required key; server startup raises ConfigurationError if it is empty.

For SQLite, database.name specifies the relative path to the database file. host, port, user, and DB_PASSWORD are ignored:

{
"database": {
"type": "sqlite",
"name": "myapp.db"
}
}

Kirak establishes an asynchronous connection pool at startup (kirak.connect()) and closes it on shutdown (kirak.disconnect()):

  • MySQL (asyncmy): Utilizes connection recycling via pool_recycle_seconds to prevent idle connection termination by MySQL’s wait_timeout.
  • PostgreSQL (asyncpg): Native connection pool. Open transactions are rolled back when connections return to the pool.
  • SQLite (sqlite3): Maintains pool_max connections to the database file in WAL mode, each allocated its own worker thread.

All framework datetime columns (created_at, updated_at, deleted_at, and datetime/timestamp fields) store naive UTC timestamps:

  • Timezone-aware Python datetime objects passed to filters or writes are automatically normalized to UTC before querying.
  • Data returned from queries arrives as naive UTC datetime objects.

Kirak automatically abstracts dialect differences across all queries:

Feature MySQL PostgreSQL SQLite
Placeholders %s $1, $2, … ?1, ?2, …
Insert Returning ID cursor.lastrowid RETURNING id clause RETURNING id clause
Case-Insensitive LIKE LOWER(field) LIKE LOWER(?) Native field ILIKE ? LOWER(field) LIKE LOWER(?)
Case-Sensitive LIKE field LIKE ? field LIKE ? field GLOB ? (auto-converted pattern)
Boolean Types TINYINT(1) BOOLEAN BOOLEAN (stored as 0 / 1)
Auto-Increment AUTO_INCREMENT BIGSERIAL INTEGER PRIMARY KEY AUTOINCREMENT
JSON Columns TEXT JSONB TEXT
Default Timestamps CURRENT_TIMESTAMP NOW() CURRENT_TIMESTAMP
Row Locking FOR UPDATE FOR UPDATE Database write lock

Kirak’s migration engine diffs models/ against a recorded snapshot (migrations/models_snapshot.json) and generates multi-dialect SQL migration files containing MySQL, PostgreSQL, and SQLite DDL.

Every model’s indexes must declare at least one entry (see Models: indexes); kirak validate reports a model with none as index_missing. The primary key and unique fields are indexed automatically and do not count. A query on a column with no index scans the whole table on every dialect, and on the Workers/D1 free tier that scan is billed per row read.

Terminal window
# 1. Initialize migration system for a new project
kirak db init
# 2. Generate an incremental migration after editing models
kirak db makemigrations add-user-profile
# 3. Preview SQL changes without writing files
kirak db makemigrations --dry-run
# 4. Check migration status
kirak db status
# 5. Apply pending migrations
kirak db migrate

Generated files are placed in migrations/{timestamp}_{name}.sql:

-- Kirak Migration: 20261106120000_add_user_profile
-- Generated: 2026-11-06T12:00:00Z
-- BEGIN:MYSQL
ALTER TABLE `users` ADD COLUMN `bio` TEXT NULL;
-- END:MYSQL
-- BEGIN:POSTGRESQL
ALTER TABLE "users" ADD COLUMN "bio" TEXT NULL;
-- END:POSTGRESQL
-- BEGIN:SQLITE
ALTER TABLE "users" ADD COLUMN "bio" TEXT NULL;
-- END:SQLITE

Only the section matching database.type executes during kirak db migrate.


SQLite is ideal for development, automated testing, and single-instance production deployments. Keep these constraints in mind:

  1. Single Writer Concurrency: Readers execute concurrently in WAL mode, but writes are serialized. Transactions acquire a write lock; other write attempts wait up to 5 seconds before returning a timeout error.
  2. Windows Single Worker Requirement: On Windows, running multiple Uvicorn worker processes against a single SQLite file can lead to thread deadlock. Use uvicorn --workers 1 on Windows when running SQLite.
  3. Database Backups: Always back up active databases using SQLite’s online backup API rather than copying raw files:
    Terminal window
    sqlite3 myapp.db ".backup backup.db"