SQLite Database
Every PAM Native application can use a private SQLite database without
installing anything. Pam\Native\Database\SQLite sends SQL and bound values to
a serial native worker, so the UI thread never waits for disk and your PHP code
never blocks while a query runs. Results come back to a callback as plain PHP
arrays.
Use SQLite for structured records you need to filter, sort, or page through:
messages, drafts, catalog snapshots, an offline outbox. For a handful of
settings use Storage; for secrets use
secure storage.
Running statements
Section titled “Running statements”Every call names a database file. The file is created on first use inside the application’s private database directory.
<?php
declare(strict_types=1);
namespace App\Notes;
use Closure;use Pam\Native\Database\SQLite;
final class NotesTable{ private const DB = 'app.db';
public static function create(?Closure $done = null): void { SQLite::execute( self::DB, 'CREATE TABLE IF NOT EXISTS notes ( id INTEGER PRIMARY KEY, title TEXT NOT NULL, body TEXT NOT NULL DEFAULT \'\', pinned INTEGER NOT NULL DEFAULT 0, updated_at INTEGER NOT NULL )', [], $done, ); }
public static function insert(string $title, string $body, ?Closure $done = null): void { SQLite::execute( self::DB, 'INSERT INTO notes (title, body, updated_at) VALUES (?, ?, ?)', [$title, $body, time()], $done, ); }
/** @param Closure(list<array<string, string|int|float|bool|null>>): void $callback */ public static function latest(int $limit, int $offset, Closure $callback): void { SQLite::query( self::DB, 'SELECT id, title, pinned, updated_at FROM notes ORDER BY pinned DESC, updated_at DESC LIMIT ? OFFSET ?', [$limit, $offset], $callback, ); }}| Method | Use it for | Callback receives |
|---|---|---|
SQLite::execute($db, $sql, $arguments = [], $callback = null) |
DDL, INSERT, UPDATE, DELETE |
nothing |
SQLite::query($db, $sql, $arguments, $callback) |
SELECT |
a list of rows (associative arrays) |
SQLite::executeMany($db, $sql, $argumentSets, $callback = null) |
One statement, many rows | nothing |
SQLite::transaction($db, $statements, $callback = null) |
Several statements atomically | nothing |
Each method returns the native call ID immediately. A native failure — a SQL
error, a constraint violation, a limit — is raised as a RuntimeException on
the callback path.
Binding values
Section titled “Binding values”Always pass values through ? placeholders; PAM binds them natively and never
interpolates them into SQL. Arguments must be JSON scalars: string, int,
float, bool, or null. Booleans are stored as 1 and 0.
// Good: bound.SQLite::query('app.db', 'SELECT * FROM notes WHERE title LIKE ?', ["%{$term}%"], $callback);
// Never do this.SQLite::query('app.db', "SELECT * FROM notes WHERE title LIKE '%{$term}%'", [], $callback);Reading rows
Section titled “Reading rows”Rows are associative arrays keyed by column name. INTEGER columns arrive as
int, REAL as float, TEXT as string, NULL as null, and BLOB
values as base64-encoded strings. Select only the columns the screen shows.
Bulk writes
Section titled “Bulk writes”executeMany() compiles one statement once and runs it for every argument set
inside a single native transaction — far faster than a loop of execute()
calls, and atomic.
use Pam\Native\Database\SQLite;
SQLite::executeMany( 'app.db', 'INSERT OR REPLACE INTO products (id, name, price_cents) VALUES (?, ?, ?)', array_map( static fn (array $product): array => [$product['id'], $product['name'], $product['price_cents']], $products, ), fn () => $this->imported = count($products),);An executeMany() call accepts 1 to 10,000 argument sets. Split larger imports
into chunks.
Transactions
Section titled “Transactions”transaction() runs different statements atomically: either all of them
commit or none do. Each entry has sql plus either arguments (one row) or
argumentSets (many rows).
use Pam\Native\Database\SQLite;
SQLite::transaction('app.db', [ [ 'sql' => 'INSERT INTO orders (id, customer, total_cents, created_at) VALUES (?, ?, ?, ?)', 'arguments' => [$orderId, 'Alice', 4_590, time()], ], [ 'sql' => 'INSERT INTO order_items (order_id, product_id, quantity) VALUES (?, ?, ?)', 'argumentSets' => [ [$orderId, 17, 1], [$orderId, 42, 3], ], ], [ 'sql' => 'DELETE FROM cart_items', ],], function (): void { $this->orderPlaced = true;});A transaction holds 1 to 10,000 statements.
Migrations
Section titled “Migrations”PAM does not impose a migration framework; a small versioned table is enough. Run this once at startup, before the first query that depends on the schema.
<?php
declare(strict_types=1);
namespace App\Database;
use Closure;use Pam\Native\Database\SQLite;
final class Migrator{ private const DB = 'app.db';
/** @return array<int, list<string>> version => statements */ private static function migrations(): array { return [ 1 => [ 'CREATE TABLE notes (id INTEGER PRIMARY KEY, title TEXT NOT NULL, updated_at INTEGER NOT NULL)', ], 2 => [ 'ALTER TABLE notes ADD COLUMN pinned INTEGER NOT NULL DEFAULT 0', 'CREATE INDEX notes_pinned_updated ON notes (pinned, updated_at)', ], ]; }
public static function run(Closure $ready): void { SQLite::execute( self::DB, 'CREATE TABLE IF NOT EXISTS schema_migrations (version INTEGER PRIMARY KEY)', [], static function () use ($ready): void { SQLite::query( self::DB, 'SELECT COALESCE(MAX(version), 0) AS version FROM schema_migrations', [], static function (array $rows) use ($ready): void { self::applyFrom((int) ($rows[0]['version'] ?? 0), $ready); }, ); }, ); }
private static function applyFrom(int $current, Closure $ready): void { $statements = []; foreach (self::migrations() as $version => $sql) { if ($version <= $current) { continue; } foreach ($sql as $statement) { $statements[] = ['sql' => $statement]; } $statements[] = [ 'sql' => 'INSERT INTO schema_migrations (version) VALUES (?)', 'arguments' => [$version], ]; }
if ($statements === []) { $ready();
return; }
// All pending migrations commit together or not at all. SQLite::transaction(self::DB, $statements, $ready); }}use App\Database\Migrator;
Migrator::run(static function (): void { // Schema is current; start loading data.});Paginate large results
Section titled “Paginate large results”A single query() returns at most 1,000 rows and 256 columns; a query that
would return more fails instead of silently truncating. This keeps every
result small enough to cross the bridge without a memory spike. Page with
LIMIT/OFFSET, or better, keyset pagination, and feed pages to a
virtualized list:
SQLite::query( 'app.db', 'SELECT id, title, updated_at FROM notes WHERE updated_at < ? ORDER BY updated_at DESC LIMIT 50', [$this->oldestLoadedAt], fn (array $rows) => $this->appendPage($rows),);Load the next page when the list reaches its end, not all rows up front.
Engine settings and limits
Section titled “Engine settings and limits”PAM opens each database once and keeps it open for the process lifetime with:
- write-ahead logging (
WAL) andsynchronous=NORMAL; foreign_keys=ON;busy_timeout=5000andtemp_store=MEMORY.
| Limit | Value |
|---|---|
| Database name | [A-Za-z0-9_.-], 1–128 characters |
| SQL text | 1 byte to 1 MiB |
| Rows per query | 1,000 (paginate beyond that) |
| Columns per query | 256 |
| Argument sets / statements per batch | 1 to 10,000 |
Statements for all databases run on one serial native queue in the order you issue them, so a write followed by a read observes the write.
Beyond raw SQL
Section titled “Beyond raw SQL”- Global store — replicate a
store into SQLite or a server with
StoreReplica. - Nitro — an offline-first data engine for large local datasets.
- Offline Sync and Laravel Sync — outbox, cursors, and conflict resolution against a Laravel backend.
Next steps
Section titled “Next steps”- Storage — preferences, files, caches, and secrets.
- HTTP networking — fetch the data you store.
- Scroll and lists — render large result sets efficiently.