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)"]Supported Databases
Section titled “Supported Databases”| 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:
pip install "kirak[all-databases]"Connection Configuration
Section titled “Connection Configuration”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.
SQLite File Configuration
Section titled “SQLite File Configuration”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" }}Connection Pooling
Section titled “Connection Pooling”Kirak establishes an asynchronous connection pool at startup (kirak.connect()) and closes it on shutdown (kirak.disconnect()):
- MySQL (
asyncmy): Utilizes connection recycling viapool_recycle_secondsto prevent idle connection termination by MySQL’swait_timeout. - PostgreSQL (
asyncpg): Native connection pool. Open transactions are rolled back when connections return to the pool. - SQLite (
sqlite3): Maintainspool_maxconnections to the database file in WAL mode, each allocated its own worker thread.
Datetime Handling Across Dialects
Section titled “Datetime Handling Across Dialects”All framework datetime columns (created_at, updated_at, deleted_at, and datetime/timestamp fields) store naive UTC timestamps:
- Timezone-aware Python
datetimeobjects passed to filters or writes are automatically normalized to UTC before querying. - Data returned from queries arrives as naive UTC
datetimeobjects.
Dialect Differences Reference
Section titled “Dialect Differences Reference”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 |
Migrations
Section titled “Migrations”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.
Workflow Commands
Section titled “Workflow Commands”# 1. Initialize migration system for a new projectkirak db init
# 2. Generate an incremental migration after editing modelskirak db makemigrations add-user-profile
# 3. Preview SQL changes without writing fileskirak db makemigrations --dry-run
# 4. Check migration statuskirak db status
# 5. Apply pending migrationskirak db migrateMulti-Dialect Migration Files
Section titled “Multi-Dialect Migration Files”Generated files are placed in migrations/{timestamp}_{name}.sql:
-- Kirak Migration: 20261106120000_add_user_profile-- Generated: 2026-11-06T12:00:00Z
-- BEGIN:MYSQLALTER TABLE `users` ADD COLUMN `bio` TEXT NULL;-- END:MYSQL
-- BEGIN:POSTGRESQLALTER TABLE "users" ADD COLUMN "bio" TEXT NULL;-- END:POSTGRESQL
-- BEGIN:SQLITEALTER TABLE "users" ADD COLUMN "bio" TEXT NULL;-- END:SQLITEOnly the section matching database.type executes during kirak db migrate.
SQLite Operational Considerations
Section titled “SQLite Operational Considerations”SQLite is ideal for development, automated testing, and single-instance production deployments. Keep these constraints in mind:
- 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.
- Windows Single Worker Requirement: On Windows, running multiple Uvicorn worker processes against a single SQLite file can lead to thread deadlock. Use
uvicorn --workers 1on Windows when running SQLite. - 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"