Documentation chapters
You're looking at legacy documentation.
New multi-language documentation available at https://docs.deepkit.io
ORM

Entity

Deepkit ORM is based on @deepkit/type and uses its type definition capabilities. It already has everything needed to decorate your entity with information necessary to describe database tables/collections. Make sure that @deepkit/type is correctly installed and configured.

An entity is a class or (experimental) interface with at least one property declared as primary key.

Class

The entity name (first argument in @entity.name()) is also the table/collection name, by default. To change the table/collection name, use .collectionName('users').

import { entity, integer, PrimaryKey, AutoIncrement, MinLength, MaxLength } from '@deepkit/type';
            
@entity.name('user')
export class User {
    id: integer & PrimaryKey & AutoIncrement = 0;
    created: Date = new Date;

    firstName?: string & MaxLength<64>;
    lastName?: string & MaxLength<64>;

    constructor(public username: string & MinLength<3> & MaxLength<24> & Unique) {
    }
}

The class itself can now be used with the Database object.

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

class User {
    //....
}

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

await database.persist(new User('Peter'));
        
const allUsers = await database.query(User).find();
console.log('all users', allUsers);

Interface

Pure interfaces are currently supported as experimental feature.

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

interface User {
    id: number & PrimaryKey & AutoIncrement;
    created: Date;
    name: string;
}
        
const database = new Database(new SQLiteDatabaseAdapter(':memory:'))
    .register<User>({collection: 'users');
await database.migrate();
        
const user: User = {id: 0, created: new Date, name: 'Peter'};
await database.persist(user);
        
const allUsers = await database.query<User>().find();
console.log('all users', allUsers);

Database types

Each database adapter has its mapping of TypeScript types to database engine types.

Runtime typeSQLiteMySQLPostgreSQLMongo
stringtextlongtexttextstring
numberfloatdoubledouble precisionint/number
booleaninteger(1)booleanbooleanboolean
datetextdatetimetimestampdatetime
arraytextjsonjsonbarray
maptextjsonjsonbobject
maptextjsonjsonbobject
uniontextjsonjsonbT
uuidblobbinary(16)uuidbinary
ArrayBuffer/Uint8Array/...bloblongblobbyteabinary

To change the mapped type to something else, use its database decorator type. For example for MySQL it's MySQL<{type: 'VARCHAR(255)'}>. The type needs to be a valid SQL type statement that is passed as is to the migration system.

DatabaseDecorator
SQLite
import { SQLite } from '@deepkit/type';
interface User {
    title: string & SQLite<{type: 'text'}>;
}
Mysql
import { MySQL } from '@deepkit/type';
interface User {
    title: string & MySQL<{type: 'text'}>;
}
PostgreSQL
import { Postgres } from '@deepkit/type';
interface User {
    title: string & Postgres<{type: 'text'}>;
}
All databases With DatabaseField its possible to define database field options for a new unknown or all database adapters.
import { DatabaseField } from '@deepkit/type';
interface User {
    title: string & DatabaseField<{type: 'text'}>;
}

Primary

A primary field is annotated using the PrimaryKey type decorator. At the moment only one primary key is supported.

Optional

Optional fields are annotated using title?: string or title: string | null as property type. You should use only one, usually the optional ? syntax that works with undefined. Both decorators result in having the column NULLABLE for SQL adapters. In any case a null or undefined value is represented in the database as NULL, and only converted to undefined or null at runtime. So the only difference between those decorators is that they are represent different values at runtime.

In the following example, the modified field is optional and can thus be undefined in runtime, although in the database it's always represented as null.

import { PrimaryKey } from '@deepkit/type';

class User {
    id: number & PrimaryKey = 0;
    modified?: Date;
}

This example shows how the nullable decorator works. In both the database and in the javascript runtime, null will be used. This is more verbose than modified?: Date and is not frequently used.

import { PrimaryKey } from '@deepkit/type';

class User {
    id: number & PrimaryKey = 0;
    modified: Date | null = null;
}

Auto increment

Fields that should be auto-incremented on insert are annotated using the AutoIncrement decorator. All adapters support auto increment values. The MongoDB adapter uses an additional collection to track the uto increment counter.

Auto increment fields get a new value on insertion automatically.

import { PrimaryKey, AutoIncrement } from '@deepkit/type';

class User {
    id: number & PrimaryKey & AutoIncrement = 0;
}

MongoDB ObjectID

Fields that should be of type ObjectID in MongoDB are annotated using the MongoId type decorator. The runtime type is string and in the database itself ObjectId (binary).

MongoID fields get a new value on insertion automatically.

import { PrimaryKey, MongoId } from '@deepkit/type';

class User {
    _id: MongoId & PrimaryKey = '';
}

UUID

Fields that should be of type UUID (v4) are declared using the UUID special type. The runtime type is string and databases usually store them in a binary type. Use the uuid() function to generate a new UUID v4.

import { uuid, UUID, PrimaryKey } from '@deepkit/type';

class User {
    id: UUID & PrimaryKey = uuid();
}

Relations

References (foreign keys) are annotated using the Reference type decorator. For more information please read the ORM Relations chapter.

More

There are many more schema definition decorators available like integers, indexes, name mapping, and validators. See the section Type: Special types or Type: Validation for more information.

Made in Germany