DatabaseGetting Started

IX · Database

Database: Getting Started

  • @marmeon/database
On this page

Introduction

Almost every app keeps its data in a database. Marmeon talks to it through Kysely, a query builder that knows every table and column of your app as a type. A new app runs on SQLite, which Node brings along, so there is nothing to install and no server to start. Postgres works the same way once you install its driver.

The default connection is a service. Ask for Database in a constructor and query it:

modules/notes/controllers/ListNotesController.ts
import type { Authenticated } from '@marmeon/auth';
import { Database } from '@marmeon/database';
import { Controller, type HttpContext } from '@marmeon/http';

export class ListNotesController extends Controller {
  readonly #db: Database;

  constructor(db: Database) {
    super();
    this.#db = db;
  }

  async handle(ctx: HttpContext<Authenticated>) {
    const notes = await this.#db
      .selectFrom('notes')
      .select(['id', 'title', 'updated_at'])
      .where('user_id', '=', ctx.user.id)
      .orderBy('updated_at', 'desc')
      .execute();
    return this.view('notes/Index', { notes });
  }
}

The table names, the columns and the result's type come from your migrations. A misspelt column is a compile error, and notes is typed as a list of { id, title, updated_at }. The repositories and queries page shows how to write queries, and how a repository keeps them in one place.

Configuration

The default connection reads these variables, checked when the app starts like all configuration:

VariableDefaultEffect
DB_DRIVERsqliteThe driver: sqlite or pgsql.
DB_DATABASEstorage/database.sqlite for SQLite, none for PostgresSQLite: the file, relative to the app's root, or :memory:. Postgres: the database's name, required unless DB_URL is set.
DB_HOST127.0.0.1Postgres: the server: a name, an IPv4 or IPv6 address (::1), or the directory of a Unix socket (/var/run/postgresql).
DB_PORT5432Postgres: its port.
DB_USERNAMEpostgresPostgres: the user.
DB_PASSWORDemptyPostgres: the password.
DB_URLnonePostgres: the whole address instead, postgres://user:secret@host:5432/app.
DB_POOL_MAX10Postgres: the most connections the app's pool opens.
DB_INFRA_POOL_MAX4Postgres: the most connections of the small pool the cache, the sessions and uploads use. See infrastructure connections.
DB_MANAGEDtruefalse when another tool manages the database's tables. See a database another tool manages.

The database stores of the framework's packages (the cache, sessions, queue, live updates, authentication, notifications and uploads) run on these two drivers only. A connection of another driver is refused with D29, before the first statement.

Opening a Postgres connection fails after ten seconds, instead of waiting for a host that does not answer; this holds for the app's pools and for the connection marmeon migrate takes its lock on. Set ?connect_timeout=<seconds> in DB_URL for a server that needs longer: whole seconds from 0 to 2147483, anything else fails the start naming DB_URL; 0 waits without a limit, as before. The error is D11 with the connection named. The same limit applies to the wait for a free connection of a full pool: that failure says that no connection was free within the timeout, and the cure is a larger DB_POOL_MAX or shorter transactions, not the network. A connection always runs in UTC: options in the URL (?options=-c%20search_path%3Dapp) are kept, and a TimeZone among them is replaced by UTC.

A Postgres server is either the five variables DB_HOST, DB_PORT, DB_DATABASE, DB_USERNAME and DB_PASSWORD, or its whole address in DB_URL. When DB_URL is set, it wins: the five are not read. DB_URL must start with postgres:// or postgresql://, and the start fails with every wrong value named at once.

Postgres has no default database name: without DB_DATABASE, or a DB_URL with the database's name in its path, the start fails with K6, because two apps on one server that fell back to the same name would share every table, from users and sessions to the cache. An empty DB_DATABASE= counts as not set.

[marmeon:K6] Invalid configuration — the application cannot start:
  • database: DB_DATABASE — set DB_DATABASE, or DB_URL with the database's name in its path — apps on one Postgres server share their tables otherwise (docs/database.md#configuration)

An app whose tables are in a database named marmeon sets DB_DATABASE=marmeon.

.env
DB_DRIVER=pgsql
DB_HOST=db.internal
DB_PORT=5432
DB_DATABASE=notes
DB_USERNAME=notes
DB_PASSWORD=secret

SQLite

SQLite runs on node:sqlite, which is part of Node: no native addon, nothing to build. The file is created on the first query. Its directory must exist, so the app checks it when it starts and stops with the path when it is missing:

[marmeon:D11] The directory of the SQLite database for connection "default" does not exist: /srv/app/storage (sqlite storage/database.sqlite).

A file database runs in WAL mode, so the development server and a command such as migrate can work at the same time. A statement that finds the file locked waits up to five seconds before it fails. A transaction takes the write lock when it begins (begin immediate), so a worker, a scheduler and a web process on one file wait for each other instead of failing midway with SQLITE_BUSY. That lock is taken even by a transaction that only reads, and other processes' writes wait for it, up to the busy timeout: keep transactions short, and read outside a transaction when nothing is written. DB_DATABASE=:memory: keeps the database in memory, which the .env.test of a new app does for its tests.

SQLite has one writer at a time, and the app's file has one connection. The transactions page explains what that means inside a transaction.

Postgres

Postgres needs the pg driver in your app:

pnpm add pg@^8

Install it as a dependency, not a dev dependency. Without it, the first query fails and names the command. With DB_URL=postgres://app:secret@db:5432/app, the message reads:

[marmeon:D11] Could not connect to the database connection "default" (pgsql postgres://app:***@db:5432/app): DB_DRIVER=pgsql needs the "pg" package, which is not installed in this app: pnpm add pg@^8

A connection of your own names itself instead: The Postgres connection "reporting" needs the "pg" package, ….

Give every package of your workspace that uses @marmeon/database the same pg version as the app. Otherwise pnpm installs @marmeon/database twice, see One copy of a framework package.

The app does not connect to Postgres when it starts, so a command that sends no query works without a running server. The first query connects, and a deployment's marmeon migrate --force is that first query, so it finds a missing driver or a wrong address before any request does. The deployment page lists every driver an app may need.

Values come back as the same JavaScript types on both drivers, so code and tests do not change with the database:

  • A bigint column is read as a number. A value beyond Number.MAX_SAFE_INTEGER throws a RangeError instead of losing digits. Cast it to text in the query if you need such numbers.
  • A timestamp is read as an ISO-8601 string in UTC, such as 2026-10-01T12:00:00.000Z. The connection runs in UTC.
  • A date is read as YYYY-MM-DD, as stored.

An error message names the connection and where it points, with the password masked. When the server drops an idle connection, the pool replaces it and the log says so with a warning.

MySQL

MySQL cannot be selected yet: DB_DRIVER takes sqlite or pgsql, and a connection definition cannot return mysql. What is described here is what the framework's own tests run against. What Marmeon reads of a MySQL database, and which privileges the role needs, is under the catalog of MySQL; how migrations run on it is under Migrations on MySQL.

MySQL needs the mysql2 driver in your app, as a dependency like pg:

pnpm add mysql2@^3

Version 3.x from 3.24.6 on: the first query refuses any other and names the command.

Marmeon supports MySQL 8.4 (the long-term-support release) and newer. MariaDB is not supported, and neither are TiDB and Vitess: they speak the protocol but are other databases. Every new connection reads the server's version and refuses one that is not supported with D28, and closes it:

[marmeon:D28] The MySQL connection "default" was refused: the server is MariaDB; Marmeon supports MySQL 8.4 or newer, not MariaDB (server "11.4.2-MariaDB")

A server that reports a MySQL 8.4 version without naming itself, such as a proxy, cannot be told apart by name; the checks of the session below are what remain.

The address is mysql://user:secret@host:3306/app. Its query string takes ssl-mode (DISABLED, REQUIRED, VERIFY_CA or VERIFY_IDENTITY), ssl-ca, ssl-cert and ssl-key (paths of files), connect_timeout (seconds, as on Postgres) and socket (the path of a Unix socket). Any other parameter makes the connection fail, so a URL cannot switch on multipleStatements or the client's flags; the message names the parameter only when it is an option of the driver. Without ssl-mode the connection is not encrypted. REQUIRED encrypts without verifying the server; VERIFY_CA checks the certificate against ssl-ca (or the system's authorities); VERIFY_IDENTITY checks that the certificate is made for the host name of the URL as well, so its host must be the server's name: an IP address fails the connection, since there is no name to check. ssl-ca, ssl-cert and ssl-key need a ssl-mode other than DISABLED: without one the connection fails with a message that names them. A file that cannot be read fails it with the error code, never the path.

Every connection of the pool is set up before its first query, and read back:

  • The character set is utf8mb4 and the collation utf8mb4_0900_bin, which is binary: 'A' = 'a' is false, as on SQLite and Postgres. The record of migrations is created in that collation, and a database you create yourself should be.
  • The time zone is UTC, so a datetime is read and written as UTC.
  • The sql_mode is ONLY_FULL_GROUP_BY, STRICT_TRANS_TABLES, STRICT_ALL_TABLES, NO_ZERO_IN_DATE, NO_ZERO_DATE, ERROR_FOR_DIVISION_BY_ZERO, NO_ENGINE_SUBSTITUTION, PIPES_AS_CONCAT and ANSI_QUOTES: invalid values are errors instead of being cut, 'a' || 'b' is 'ab' and "x" is a name, as in SQL on the other drivers. NO_BACKSLASH_ESCAPES is not part of it, and a session that has it is refused: Kysely escapes a backslash in a literal and in a JSON path, which that mode would store doubled.
  • completion_type is NO_CHAIN, so that a commit or rollback never starts another transaction, and session_track_system_variables names time_zone, autocommit, character_set_client, character_set_results, character_set_connection and completion_type: the server then reports in the answer when a statement of yours changes one of them, which the checks of a lease read.
  • A session that does not report these values, or does not autocommit, is refused with D28.

The session is set up when a connection is opened and read back. A connection that goes back to the pool is reset with COM_RESET_CONNECTION, which the server answers with an open transaction rolled back and the session's variables, user variables, lock tables and get_lock locks, sql_select_limit, foreign_key_checks and prepared statements back at their defaults; then it is set up again, read in full, and only a connection that reads as Marmeon set it goes back. Any failure of these steps closes it. A reset does not change the database: one that a statement moved with use is closed instead of returned. The database a connection must return in is the one the server reported when it was opened, so a name written in another case in the URL is no problem. Each return costs three round trips: the reset, the set-up and the reading.

A value never becomes part of a statement's text. A statement with parameters is prepared on the server (COM_STMT_PREPARE) and run with the values (COM_STMT_EXECUTE), so no sql_mode, client character set or version of the driver's formatter can make a value SQL. A statement without parameters goes over the text protocol, and the text protocol never formats a value. This has these consequences:

  • The server counts the placeholders with its own parser, in the session's mode. When its count is not the number of values, nothing is run and the call throws a TypeError: MySQL sees 1 placeholders in the statement and 2 parameters were given; a ? inside a comment, a string or a "name" is not one. A ? inside a string, a comment, a /*+ */ hint or (with ANSI_QUOTES) a "name" is no placeholder; one inside /*! … */ is, and it binds a value like any other.
  • MySQL cannot prepare some statements (LOCK TABLES, BEGIN, SAVEPOINT, USE, XA, HANDLER, LOAD DATA, PREPARE). They run without parameters, as before. With one, MySQL answers ER_UNSUPPORTED_PS, and nothing is retried as text.
  • A connection holds at most 16 prepared statements; the least recently used is closed beyond that. The reset when the connection goes back closes them all, so none is left between leases. The server's max_prepared_stmt_count (16382 by default) counts the statements of all clients together, and a pool of many connections can reach it with a limit of 16 each.
  • Statement text that MySQL reads is still the one Kysely writes: names, JSON paths and sql.lit() / sql.raw() text. A change the app makes to its own session inside a lease (sql_mode, set names) holds until the connection goes back and then affects only that text, never a value. So an answer that says that the session has NO_BACKSLASH_ESCAPES, or names a client character set other than utf8mb4 (set names latin1, set names gbk; the server tells so with its session tracking, which Marmeon sets on every connection: session_track_system_variables names the six variables listed above), makes every later statement of the lease fail with D28, with nothing sent, and the connection is closed. The same holds for an answer that says autocommit is OFF, or completion_type is not NO_CHAIN (every connection is set to it): a commit would chain a new transaction, and the next statement is refused before it goes out, so nothing is committed. See Transactions on MySQL. A lease in which an answer said so is not given back either, so the next one is not refused. Only what an answer says counts. A routine that sets the mode and sets it back stays unnoticed when the flag is gone from the answer of its call, and so does a failed statement that sent no OK packet: nothing is affected but the text Kysely writes. The same holds for a lease that empties session_track_system_variables itself, which tells nothing about what it changes afterwards; the way back resets it. A routine that sets the mode only inside itself can leave the bit on in its answer and make the rest of the lease fail, which fails closed. A value is a value in any case. Another time zone is not refused inside a lease; the connection is reset when it goes back, and one that a use moved is replaced.
  • A statement prepared before a use keeps reading the database it was prepared in. When the server tells of the change of database (Marmeon sets session_track_schema = 1 on every connection), the statements of the lease are prepared anew; if a lease switches that off, or a proxy keeps no session state, a statement text that was used before use still reads the old database in that lease.

The way back of a released connection has the connect timeout as its limit, statements that still run before the reset included: a connection that does not answer by then is closed. A statement that you wait for has no limit of its own.

A parameter is a string, a number, a bigint, a boolean, a Date, a Uint8Array or null, the same as on SQLite. Anything else throws a TypeError naming the parameter before the statement is sent: an object, an array (JSON.stringify a JSON value), undefined, a number that is not finite, an invalid Date and a Date outside the years 0 to 9999. A bigint is sent as a 64-bit integer, unsigned beyond 2^63 − 1; one outside −2^63 to 2^64 − 1 throws. A statement holds one SQL statement, and LOAD DATA LOCAL INFILE is switched off.

Values come back as on the other drivers:

  • A boolean column (tinyint(1)) is read as a boolean.
  • A bigint column is read as a number; a value beyond Number.MAX_SAFE_INTEGER throws a RangeError once the whole result has been read, and the connection goes on. Cast it to text to read it.
  • A float column is read with 6 significant digits, as MySQL's text protocol writes it (1.1, 1.23457 for 1.2345678, 16777200 for 2^24 + 1), the same from both protocols; use double for more. A time is read as text without trailing zeros of its fraction (12:00:00.25).
  • A datetime or timestamp is read as an ISO-8601 string in UTC, such as 2026-10-01T12:00:00.000Z. Write it as a Date or as text without the Z (2026-10-01 12:00:00.000): MySQL refuses an insert of a literal with the Z.
  • A date is read as YYYY-MM-DD, a decimal as text ('12.50'), json parsed as JSON.parse does (an integer beyond 2^53 is a rounded number, as on the other drivers), and a blob as bytes.

More connections

Another database is a definition with a name. It reads its own variables, which are checked at the start like all configuration. This one gives the cache and the sessions a SQLite file of their own:

config/database.ts
import { env } from '@marmeon/core';
import { defineConnection } from '@marmeon/database';

export const SystemDatabase = defineConnection('system', {
  env: env({
    SYSTEM_DB_DATABASE: env.string().default('storage/system.sqlite'),
  }),
  resolve: (e) => ({ driver: 'sqlite', database: e.SYSTEM_DB_DATABASE }),
});

List the definition in config of defineApplication() in bootstrap/app.ts, or of the module that needs it. resolve returns { driver: 'sqlite', database } or a Postgres server. Like the default connection, a Postgres server is its parts, host, port, database, username and password, or the whole address in url, which wins when both are given. Without url, the parts default to 127.0.0.1, 5432, postgres and no password, and database is required. poolMax and infrastructurePoolMax size its pools, 10 and 4 by default. A reporting database that reads both ways:

config/reporting.ts
import { env } from '@marmeon/core';
import { defineConnection } from '@marmeon/database';

export const ReportingDatabase = defineConnection('reporting', {
  env: env({
    REPORTING_DB_HOST: env.string().default('127.0.0.1'),
    REPORTING_DB_PORT: env.port().default(5432),
    REPORTING_DB_DATABASE: env.string().default('reporting'),
    REPORTING_DB_USERNAME: env.string().default('postgres'),
    REPORTING_DB_PASSWORD: env.string().default(''),
    REPORTING_DB_URL: env.url({ protocols: ['postgres', 'postgresql'] }).optional(),
  }),
  resolve: (e) => ({
    driver: 'pgsql',
    url: e.REPORTING_DB_URL,
    host: e.REPORTING_DB_HOST,
    port: e.REPORTING_DB_PORT,
    database: e.REPORTING_DB_DATABASE,
    username: e.REPORTING_DB_USERNAME,
    password: e.REPORTING_DB_PASSWORD,
    poolMax: 5,
  }),
});

default is the name of the connection of DB_DRIVER, and defineConnection('default', …) throws. Ask Connections for any connection by its name:

modules/reports/MonthlyReport.ts
import { Connections, type Connection } from '@marmeon/database';
import type { ReportingTables } from './tables.ts';

export class MonthlyReport {
  readonly #reporting: Connection<ReportingTables>;

  constructor(connections: Connections) {
    this.#reporting = connections.get<ReportingTables>('reporting');
  }

  totals() {
    return this.#reporting.selectFrom('orders').select(['month', 'total']).orderBy('month').execute();
  }
}

Without a type argument, get() types the connection with your app's tables. A name that no definition has throws at once, with the names it knows:

[marmeon:D11] Database connection "reporting" is not configured. Known: default, system. Add one with defineConnection('reporting', …) in the app's config.

Connections open on their first query and close when the app shuts down. Migrations and repositories can work on another connection too.

Infrastructure connections

Some writes must never be part of your app's transaction. A failed sign-in counted inside a transaction that rolls back would be uncounted, and the next guess would get through. A lock taken inside one would be invisible to other processes until the commit. So the database drivers of the cache, the sessions, uploads and live updates write on a connection that never joins a transaction:

Their connectionWhat they getInside an open transaction of the app
PostgresA small pool of its own to the same database, opened on first use: DB_INFRA_POOL_MAX connections, or infrastructurePoolMax of a defineConnection().Works. Their writes are committed at once and survive a rollback.
SQLite, a file of its ownThat file.Works.
SQLite, the app's own fileThe file's one connection, shared.Every statement throws an InfrastructureTransactionError, which says what to do.

The pool of its own on Postgres keeps transactions that wait for a rate limit from taking every connection that the rate limit needs. On SQLite a second connection to the app's file would wait for the open transaction's lock, forever if the transaction waits for it. So on SQLite give the cache, the sessions and uploads a file of their own, as config/database.ts above does, and point them at it with CACHE_CONNECTION=system, SESSION_CONNECTION=system, LIVE_CONNECTION=system and UPLOADS_CONNECTION=system. Outside a transaction the app's own file works as well. Never point two connection names at the same SQLite file: a transaction of either holds the file for both. On Postgres there is nothing to configure.

Kysely and its version

The query builder is Kysely, and the framework pins it to one exact version. You write its builder through @marmeon/database and never install or import the kysely package yourself, so the app and the framework use the same copy. Only @marmeon/database depends on it; the other packages of the framework take the builder and its types from there, as your app does. A Kysely update that changes the builder's shape comes only in a major version of Marmeon. The releases page lists what else it promises.

Inspecting a connection

marmeon db:show prints where a connection points, its server's version and its tables with their number of columns and rows:

pnpm marmeon db:show
pnpm marmeon db:show --database=system

The password in the address is masked. --database names a connection, default without it.

The target shows the host, port and database, the user name, and of the query string only host, port, sslmode and application_name. The password, every other parameter (a key path, an options string) and the fragment never reach the output, whether the address came from DB_URL, from DB_PASSWORD or from a connection's password option.

--json prints a machine-readable document: format, connection, driver (sqlite, pgsql or, for a test of the framework, mysql; see the catalog of MySQL), target (as in the text, without the driver in front), server, tables (each with name, schema — null for SQLite and MySQL — columns and rows) and warnings.

Querying a connection

marmeon db:query runs one read-only query and prints the rows as a table, or as a document with --json:

pnpm marmeon db:query "select id, email from users order by id"
echo "select count(*) from orders" | pnpm marmeon db:query --stdin --json
pnpm marmeon db:query "select * from things" --database=system --limit=20

Pass the SQL as one argument or, with --stdin, on standard input (at most 64 KiB, read to its end) — one of the two, not both. --database names a connection, default without it. --limit is the number of rows to keep, 1 to 1000, 100 without it; one row more is read to tell whether there were others. --timeout is the seconds Postgres may work on the query, 1 to 60, 10 without it. A wrong call (both or neither of the SQL and --stdin, a value out of range) ends with exit code 2; a query the database cannot run ends with exit code 1, and a query the command refuses (a write, a secret column, a connection that --managed-only rules out, a record of migrations that cannot say which columns are secret) with exit code 3 — in both the reason is on stderr and nothing on stdout, with --json as well. The reason of a refusal is one line, the last that starts with db:query refused:.

A connection with managed: false has no known secret columns, so every column of it is readable. --managed-only makes the command refuse such a connection before it runs anything; the MCP query tool passes it.

The command runs only with NODE_ENV=development or NODE_ENV=test, where there is a development database to look into; with any other value, and with none, it ends with exit code 1 before it reads anything. For a running production app, tinker is the tool.

It never goes through the app's connection pool. It opens a connection of its own and the database keeps that one read-only: SQLite opens the file read-only and refuses everything but a plain SELECT through its authorizer; Postgres runs the statement in a READ ONLY transaction of the REPEATABLE READ level, as one statement through the extended protocol, after EXPLAIN has shown the plan Postgres will run and the plan has been checked. What is refused, as a list of classes:

  • every statement that is not one SELECT, WITH … SELECT, VALUES or TABLE: writes, schema changes, transaction control, PRAGMA, COPY, SET, locking clauses such as FOR UPDATE, a second statement after the first;
  • functions with side effects: on Postgres every volatile function (nextval, set_config, pg_terminate_backend, pg_advisory_lock, pg_notify, …) and a list of others that read the server's files, settings or other databases (pg_read_file, current_setting, dblink, lo_*, table_to_xml, query_to_xml, …); on SQLite load_extension and the tokenizer registration;
  • relations that hold copies of values or credentials: on Postgres pg_statistic (and so pg_stats), pg_authid, pg_user_mapping, pg_subscription, pg_largeobject, pg_db_role_setting and pg_settings, and the TOAST tables; on SQLite sqlite_stat*;
  • the secret columns of the migrations (secret()), however they are reached: named, through select *, in a WHERE or a function call, through a subquery, a view, an alias that selects the whole row, a generated column or a full-text index over them. The message names the column, as users.password. A column stays secret while a pending migration renames or drops it: the database still holds it until migrate has run. When the record of migrations cannot say which columns are secret — the database has tables and no record, a migration that ran has no file, its file changed, or it has no recorded checksum — the query is refused (exit code 3) and the message names what to fix. A column of the database that no migration that ran describes — a table made by raw SQL, or one whose migration the record lost — counts as secret too, until migrate or a migration describes it.

Which statements, functions and relations are refused may grow in any release: it is a security boundary, and the command's name, options and document stay as they are.

The answer is limited and masked before it leaves the process:

  • text cells are masked by the app's redactor and cut at 4096 characters (cut counts the cells that were); binary cells are written as [binary N bytes]; big integers and dates are text;
  • A result stops at 4 MiB (as JSON, after the cutting) on both drivers, with truncated: true; the first row is always returned. Postgres reads it through a cursor. On Postgres text, varchar, json, jsonb and xml values are cut on the server, bytea becomes its size, and any other value above 64 KiB arrives as NULL and counts in cut. The server still computes each value in full (repeat('x', 1e9)); only --timeout bounds that;
  • the text output writes the control characters of a cell or a column name out (\u001b), as all console output does.

--json prints a machine-readable document: format, connection, driver (sqlite or pgsql), columns (each with name and type: the declared type on SQLite — null for an expression — and the type's name on Postgres), rows (arrays in the order of columns), truncated (there were more rows than --limit, or the 4 MiB were reached), cut and warnings.

The limits that stay open, on purpose:

  • The record of migrations is trusted. Which columns are secret is read from the migrations the record says ran. A record that lost rows while their migrations' changes stayed in the database (edited by hand, or a crash between a migration and its row) can make a column that a lost migration marked secret look like the one an earlier migration described under the same name. marmeon migrate:status shows such a migration as pending.
  • Functions and views of the database are trusted. On Postgres a function that is not volatile, a view, an operator and a cast that already exist in the database run as they are: a PL/pgSQL function marked STABLE can hide a volatile statement, and a view or function may read what the migrations mark secret on its own. A materialized view over a secret column is refused, but one over a function that reads a secret table is not: pg_depend does not know what a function's body reads. A function of the app marked IMMUTABLE or STABLE may already run while EXPLAIN plans the query, before the check looks at it.
  • Virtual tables made by raw SQL are refused whole, a full-text table among them, like any table no migration describes: what they keep is not known, and a trigger may have copied a secret into them. Full-text shadow tables are withheld too, and an FTS4 table declared with content=<table> cannot be read on the read-only connection at all. Generated columns of a table with a secret column count as secret themselves.
  • On Postgres a table in another schema with the name of a migrated table is held to that table's description: its columns of the same names are read as described, since tables are matched by their bare name.
  • Values over 1 MiB are refused on SQLite: ask for length() or substr() instead.
  • A connection set to managed: false knows no secret column: every column is readable, because the secret columns come from the migrations.
  • --timeout bounds Postgres only. SQLite has no way to interrupt the query: the process limit of whoever runs the command (the shell's timeout, the tool that starts it) is the bound.
  • The connection is the one .env names. When the development .env points at a shared or production database, the command reads that database, read-only but readable. Rows are personal data: whatever prints them — a terminal, a log, an agent's transcript — holds them.

When a table is missing

A query on a table that does not exist yet fails like any error. In development, the error page names the cause: the migrations that have not run yet, and the command that runs them, marmeon migrate. When every migration has run, it suggests a migration that creates the table. The migrations page explains both commands.

Where the secret columns and soft deletes come from

A connection learns which columns are secret and which tables have soft deletes and timestamps from your migrations: the schema they describe is computed from the migration files (what the migrations describe), not read from tables of the database. The database is asked which migrations ran, and only that. When it lacks one the code has, because the app started before marmeon migrate or after a rollback, the connection refuses every query with a MigrationStateError (D2) that names the missing migrations, and it answers again within a second of marmeon migrate. When the record of migrations is of a newer release, or there is none next to tables, it refuses with D1. How the migrator keeps track lists the states: a password hash or a deleted row is never shown because a migration was missing.

A database another tool manages

Marmeon refuses to guess. A connection that has tables but no record of migrations, which Marmeon's own migrate writes, is refused with error D1: without the migrations the app cannot tell which columns are secret or which rows are soft-deleted, and it never reads that as "none". That includes a database whose tables are made by another tool, a restore that lost the record, and a Postgres role without privileges on it. A MySQL role without privileges on migrations does not see the table at all: a managed connection then sees tables without a record and is refused (D1), and a connection with managed: false is not refused for the record it cannot see. See the catalog of MySQL.

For your own database that Marmeon is to migrate from now on, do not use managed: false: run marmeon migrate, which writes the record of migrations and runs the migrations. Tables it did not make stay as they are and unknown to Marmeon: migrate names them, and a table has no secret columns, soft deletes or timestamps unless a migration creates it. For a database that another tool owns, say so on the connection:

bootstrap/app.ts
defineConnection('legacy', {
  env: env({ LEGACY_URL: env.url() }),
  resolve: (e) => ({ driver: 'pgsql', url: e.LEGACY_URL, managed: false }),
});

The default connection takes DB_MANAGED=false instead. With managed: false the connection reads no migrations, but the database's catalog, as it always did: it knows every table and column that exists, their foreign keys and unique indexes, and no secret columns, no soft deletes, no timestamps; the query builder treats every column as an ordinary one. A change another tool makes to the tables is known to the connection after the schema change it made itself, or after a restart. marmeon migrate, migrate:fresh and the other migration commands refuse to touch it, and a migration cannot run on it. A connection that Marmeon migrates and reads through a role with privileges on the record of migrations stays the default. A connection that has the record of migrations Marmeon writes (a table migrations with the columns batch, checksum, id, module, name, or batch, id, module, name as 0.3 wrote them) is refused with managed: false as well (D1): Marmeon migrates it, so the option would hide its secret columns. A migrations table of another shape is another tool's.

The generated file knows no table of such a connection, so PrimaryKeyOf<'orders'> is never and a repository's find() refuses every key until you declare it, once per table, next to your types for the tables:

bootstrap/keys.d.ts
declare module '@marmeon/database' {
  interface PrimaryKeys {
    orders: 'id';
  }
}

At run time the repository reads the key from the database's catalog. See primary keys.

The catalog of MySQL

MySQL cannot be selected yet (see MySQL); what follows is what the framework's own tests run against.

Marmeon reads the tables of the database the connection's URL names from information_schema: columns, single-column foreign keys, unique indexes and the primary key. It does so on a connection with managed: false, and in the check after a migration. What it cannot read exactly it leaves out, as the other drivers do: a foreign key over several columns, a foreign key to a table of another database or to a column that is no unique key of its own, a primary key or unique index on a prefix of a column or on an expression (a prefix index compares only the first characters, and under a collation such as utf8mb4_0900_ai_ci, the default of MySQL 8, two values that = calls equal can have different prefixes: the index lets both in, and a lookup through it misses one; the collation of the column counts, not that of the connection), and views.

The role must see every table. MySQL shows a role only the tables it has a privilege on, and a table it does not show does not exist as far as Marmeon can tell. That has three consequences:

  • A migration's check after it ran counts the table as missing and fails the migration (on MySQL the steps that ran stay: every create and alter commits at once, so nothing is rolled back).
  • A foreign key to a table the role does not see, or to a column it does not see, gives no relation. Neither does a table of which the role does not see every indexed column: its foreign keys are left out whole, because a key it sees one column of may be a longer one. A key of several columns is never read as a key of one. Grant a privilege on the whole table, not on single columns, or the relations are missing.
  • On a connection with managed: false, a role that does not see migrations is not told that Marmeon migrates the database (error D1), and no secret column is known. Give such a role select on every table of the database.

migrate:fresh drops all tables with one drop table, with the foreign key checks on, and the views after them: the keys between the tables are no obstacle. A key from a table of another database is an obstacle: the server refuses (error 3730) and, on InnoDB, drops none of the tables, and the views stay too. Drop that table, or its key, first. Another storage engine may drop table by table. A table the role does not see is not dropped, and a view of another database that reads a dropped table stays and fails when it is read. A drop commits an open transaction on MySQL.

db:show prints the server as MySQL and its version; its tables carry no schema.

Readiness

The app's readiness check, /up/ready, sends select 1 to every configured connection. One that does not answer makes the instance "not ready" and is named in the answer, also when the database lacks migrations the code has (D2) or its record of migrations cannot be read (D1). The health checks page explains readiness.

Testing

createTestApp(application, { database: 'refresh' }) of @marmeon/testing gives each test a real database, migrated once and rolled back after every test. The database testing page explains it.