Database and validation
Configuration
config.php'db' => [
'dsn' => 'sqlite:' . INK_ROOT . '/storage/db.sqlite',
// 'dsn' => 'pgsql:host=127.0.0.1;dbname=app',
// 'dsn' => 'mysql:host=127.0.0.1;dbname=app;charset=utf8mb4',
'user' => env('DB_USER'),
'pass' => env('DB_PASS'),
],
The connection opens on first use. If it fails the response is 503; the reason is logged, never shown.
PDO only, plain SQL
$rows = all('SELECT id, name FROM users WHERE active = ? ORDER BY id', [1]);
$user = one('SELECT * FROM users WHERE id = ?', [$id]); // none → null
$n = val('SELECT COUNT(*) FROM users'); // first column of the first row
q('UPDATE users SET name = ? WHERE id = ?', [$name, $id]); // returns the PDOStatement
$id = tx(function () use ($name): int { // transaction: rolled back on exception
q('INSERT INTO users (name) VALUES (?)', [$name]);
return (int) db()->lastInsertId();
});
Values always go in the params array: never build SQL strings. PostgreSQL's RETURNING and ::jsonb just work. There is no ORM and no query builder.
Migrations
-- migrations/001_users.sql (first line: which pages use this table)
CREATE TABLE users (id INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR(40) NOT NULL);
php bin/ink migrate applies files in name order, each in a transaction, and records them in ink_migrations. To change a table, add a new migration; never edit old ones.
validate()
[$clean, $errors] = validate(input(), [
'name' => 'required|max:40',
'email' => 'required|email',
'age' => 'int|min:0|max:150',
'plan' => 'required|in:basic,pro',
]);
Rules: required email int numeric url bool min:N max:N in:a,b regex:/…/ array. Strings are trimmed first, '0' counts as present, empty optional fields become null. $clean holds only fields with rules, and int values become integers. Error messages follow the current locale (zh/en).