Documentation chapters


A session is akin to a Unit of Work. It keeps track of everything you do and automatically persists changes once you call commit(). It's the preferred way to execute inserts and updates to your database, since it batches inserts and updates in a way that makes it very fast. A session is very lightweight and can easily be created in a request-response life-cycle, for example.

import { SQLiteDatabaseAdapter } from '@deepkit/sqlite';
import { entity, PrimaryKey, AutoIncrement } from '@deepkit/type';
import { Database } from '@deepkit/orm';

async function main() {'user')
    class User {
        id: number & PrimaryKey & AutoIncrement = 0;
        created: Date = new Date;

        constructor(public name: string) {

    const database = new Database(new SQLiteDatabaseAdapter(':memory:'), [User]);
    await database.migrate();

    const session = database.createSession();
    session.add(new User('User1'), new User('User2'), new User('User3'));

    await session.commit();

    const users = await session.query(User).find();


Add new entity instances to the session via session.add(T), or remove already existing instances via session.remove(T). Once you are done with the session object, simply dereference it everywhere so that the garbage collector can remove it.

Modifications are automatically detected for entity instances that are only fetched via the session object.

const users = await session.query(User).find();
for (const user of users) { += ' changed';
await session.commit();   // magic!

Every time you call commit, all fetched entity instances are checked for changes, added entity instances via add() are inserted to the database, and removed entity instances via remove() are deleted.

Identity map

Sessions provide an Identity map, which ensures that there is only ever one javascript object per database id. For example, if you execute session.query(User).find() twice within the same session, you get two different arrays but with the same entity instances in it. If you add a new entity using session.add(entity1) and fetch it again, you receive the very same entity instance entity1.

Important: once you start using sessions, you should use its Session.query method instead of Database.query. Only session queries have the identity map feature activated.

Made in Germany