Class Database<ADAPTER>

Database abstraction. Use createSession() to create a work session with transaction support.

Using this class in your code indicates that you can work with common and most basic database semantics. This means that you can use the deepkit/type database API that works across a variety of database engines like MySQL, PostgreSQL, SQLite, and MongoDB.

Reflection

never

Type Parameters

Hierarchy

  • Database

Constructors

Properties

adapter: ADAPTER
entityRegistry: DatabaseEntityRegistry = ...

The entity schema registry.

eventDispatcher: EventDispatcher = ...

Reflection

never

logger: DatabaseLogger = ...
name: string = 'default'
pluginRegistry: DatabasePluginRegistry = ...
query: ReturnType<ADAPTER["queryFactory"]>["createQuery"]

Creates a new DatabaseQuery instance which can be used to query data.

  • Entity instances ARE NOT cached or tracked.

Use a DatabaseSession (createSession()) with its query() in your workflow to enable identity map.

const session = database.createSession();

const item = await session.query(MyType).findOne();
item.name = 'changed';
await session.commit(); //only necessary when you changed items received by this session
raw: ReturnType<ADAPTER["rawFactory"]>["create"]
stopwatch?: Stopwatch
virtualForeignKeyConstraint: VirtualForeignKeyConstraint = ...

If set, all created Database instances are registered here.

Methods

  • Creates a new database session. This is the preferred way of working with the database and to enjoy all ORM features. Call DatabaseSession.commit to persist changes all at once in the most performant way possible. The creation of a DatabaseSession is very low cost, so creating many or often is the preferred way. * All entity instances fetched/stored during this session are cached and tracked automatically.

    Note: This is not equal to a database transaction. A session means a work block where you need to fetch, change, and save entity instances. Every instance fetched stays in the identity-map of that session and keeps it alive, so make sure to not keep a session for too long (especially not cross requests).

    Example

    const database = new Database(...);

    express.on('request', async (req) => {
    const session = database.createSession();
    const user = session.query(User).filter({id: req.params.id}).findOne();
    user.name = req.params.name;
    await session.commit(); //session will be garbage collected and should NOT be stored for the next request
    });

    Returns DatabaseSession<ADAPTER>

  • Tells the adapter to disconnect. It reconnects automatically when necessary.

    Parameters

    • Optional force: boolean

    Returns void

  • Creates a new reference.

    If you work with a DatabaseSession, use DatabaseSession.getReference instead to maintain object identity.

    const user = database.getReference(User, 1);
    

    Type Parameters

    • T

    Parameters

    • classType: ReflectionClass<any> | ClassType<T>
    • primaryKey: PrimaryKeyFields<T>

    Returns T

  • Type Parameters

    • T extends EventToken<any, T>

    • DEPS extends any[]

    Parameters

    • eventToken: T
    • callback: EventListenerCallback<T["event"]>
    • order: number = 0

    Returns EventDispatcherUnsubscribe

  • Makes sure the schemas types, indices, uniques, etc are reflected in the database.

    WARNING: DON'T USE THIS IN PRODUCTION AS THIS CAN CAUSE EASILY DATA LOSS. SEE THE MIGRATION DOCUMENTATION TO UNDERSTAND ITS IMPLICATIONS.

    Returns Promise<void>

  • Simple direct persist. The persistence layer (batch) inserts or updates the record depending on the state of the given items. This is different to createSession()+add() in a way that DatabaseSession.add adds the given items to the queue (which is then committed using commit()) while this database.persist just simply inserts/updates the given items immediately, completely bypassing the advantages of the unit of work for multiple items.

    You should prefer the add/remove and commit() workflow to fully utilizing database performance.

    Parameters

    Returns Promise<void>

  • Type Parameters

    • T

    Parameters

    • Optional options: EntityOptions
    • Optional type: ReceiveType<T>

    Returns Database<ADAPTER>

  • Registers a new entity to this database. This is mainly used for db migration utilities and active record. If you want to use active record, you have to assign your entities first to a database using this method.

    Parameters

    • Rest ...entities: (AbstractClassType<any> | Type | ReflectionClass<any>)[]

    Returns void

  • Simple direct remove. The persistence layer (batch) removes all given items. This is different to createSession()+remove() in a way that DatabaseSession.remove adds the given items to the queue (which is then committed using commit()) while this database.remove just simply removes the given items immediately, completely bypassing the advantages of the unit of work for multiple items.

    You should prefer the add/remove and commit() workflow to fully utilizing database performance.

    Parameters

    Returns Promise<void>

  • Executes given callback in a new session and automatically commits it when executed successfully. This has the same semantics as createSession.

    Type Parameters

    • T

    Parameters

    Returns Promise<T>

  • Executes an async callback inside of a new transactional session. If the callback succeeds (not throwing), the session is automatically committed (and thus its transaction committed and all changes flushed). If the callback throws, the session executes rollback() automatically, and the error is rethrown.

    await database.transaction(async (session) => {
    await session.query(...);
    session.add(...);

    //...
    });

    Type Parameters

    • T

    Parameters

    Returns Promise<T>

  • Type Parameters

    Parameters

    • name: string
    • adapter: T
    • schemas: (ClassType<any> | ReflectionClass<any>)[] = []

    Returns ClassType<Database<T>>

Generated using TypeDoc