How ORMs work with SQLite
How entities map to rows, what a query builder and driver do, and how migrations change a database on a device.
A notes app might represent a note in JavaScript as { id: 7, title: 'Packing list' }. SQLite stores that note as a row in a table. Object-relational mapping describes how the object's fields correspond to the table's columns. An ORM uses that mapping to read and write records.
Entities, keys, and relationships
An entity represents something the app stores, such as a note or a folder. A primary key identifies a row. If you change the title of note 7, the ORM can use that key to update the same row.
A note can belong to a folder. In SQLite, a notes.folder_id column can reference folders.id. In application code, the mapping can expose the relationship as note.folder. The library can load the folder with a join or a separate query. SQLite enforces the relationship when the database declares a foreign key and the connection enables foreign key enforcement. See tables and values.
Entity operations and query builders
An entity-oriented ORM lets you ask a repository for notes or save them through an entity manager. A repository handles one entity type. An entity manager can work with several types. TypeORM and MikroORM both support working with entities.
A query builder lets you choose the table, columns, and filters in TypeScript. For example, a query for the notes in one folder can produce the following SQL.
SELECT id, title FROM notes WHERE folder_id = ? ORDER BY id;The driver binds the folder ID to ?. Drizzle ORM offers a SQL-like query builder based on table declarations. Kysely is a typed query builder. With Kysely you describe the tables to TypeScript, build the query, and receive the selected rows.
Dialects, drivers, and connections
A dialect tells the library how to express a query in SQLite's SQL syntax. A driver executes the SQL with its bound parameters and returns the result. In these integrations, Nitro SQLite provides the native connection to the database file on the device. See databases and connections.
Schema changes and transactions
Adding folderId to a TypeScript type changes what the compiler accepts. An existing database on a user's device still has its original columns. A migration is a recorded change to the schema or data, such as adding folder_id to the notes table. Some ORMs can synchronize tables from entity definitions during development. Versioned migrations let an app upgrade an existing file in a known order.
A transaction groups writes that must succeed together. If the app creates a folder and moves notes into it, both changes belong in one transaction. Run both through the transaction's connection or entity manager so SQLite can roll them back together. See transactions and atomicity.
To install a library and run your first query, follow ORMs and query builders.