fontcolor_theme
package

API @deepkit/postgres

npm install @deepkit/postgres
import { PostgresDatabaseAdapter } from '@deepkit/mongo';
import { Database } from '@deepkit/orm';

const adapter = new PostgresDatabaseAdapter('postgres://user:password@localhost/mydatabase');
// const adapter = new PostgresDatabaseAdapter({ host: 'localhost', database: 'postgres', user: 'postgres' });

const database = new Database(adapter);

Classes

PostgresStatement [source]
export class PostgresStatement extends SQLStatement {
    constructor(protected logger: Logger, protected sql: string, protected client: PostgresClientConnection, protected stopwatch?: Stopwatch, protected reusable: boolean = false);
    async get(params: any[] = []);
    async all(params: any[] = []);
    release();
}
PostgresConnection [source]
export class PostgresConnection extends SQLConnection {
    lastReturningRows: any[];
    constructor(connectionPool: PostgresConnectionPool, public connection: PostgresClientConnection, logger: Logger, transaction?: DatabaseTransaction, stopwatch?: Stopwatch);
    async prepare(sql: string);
    override execAndReturnSingle(sql: string, params?: any[]): Promise<any>;
    override execAndReturnAll(sql: string, params?: any[]): Promise<any>;
    override execAndMapAll<T>(sql: string, params: any[] | undefined, map: (row: any) => T): Promise<T[]>;
    async run(sql: string, params: any[] = [], reusable: boolean = false);
    async getChanges(): Promise<number>;
}
PostgresDatabaseTransaction [source]
export class PostgresDatabaseTransaction extends DatabaseTransaction {
    connection?: PostgresConnection;
    setTransaction?: TransactionTypes;
    /**
     * This is the default for mysql databases.
     */
    repeatableRead(): this;
    readCommitted(): this;
    serializable(): this;
    async begin();
    async commit();
    async rollback();
}
PostgresConnectionPool [source]
export class PostgresConnectionPool extends SQLConnectionPool {
    constructor(protected client: PostgresClient, protected logger: Logger, protected stopwatch?: Stopwatch);
    /**
     * @param shared The connection is only used for short queries and may be shared with others when
     * all connections are busy. Anything else holds a connection for itself, as everything queued behind
     * a slow query on a connection has to wait for it.
     */
    override getConnection(transaction?: PostgresDatabaseTransaction, shared: boolean = false): Promise<PostgresConnection>;
    release(connection: PostgresConnection);
}
PostgresPersistence [source]
export class PostgresPersistence extends SQLPersistence {
    constructor(protected platform: DefaultPlatform, public connectionPool: PostgresConnectionPool, session: DatabaseSession<any>);
    override handleSpecificError(error: Error): Error;
    async batchUpdate<T extends OrmEntity>(entity: PreparedEntity, changeSets: DatabasePersistenceChangeSet<T>[]): Promise<void>;
}
PostgresSQLQueryResolver [source]
export class PostgresSQLQueryResolver<T extends OrmEntity> extends SQLQueryResolver<T> {
    async delete(model: SQLQueryModel<T>, deleteResult: DeleteResult<T>): Promise<void>;
    override handleSpecificError(error: Error): Error;
    async patch(model: SQLQueryModel<T>, changes: Changes<T>, patchResult: PatchResult<T>): Promise<void>;
}
PostgresSQLDatabaseQuery [source]
export class PostgresSQLDatabaseQuery<T extends OrmEntity> extends SQLDatabaseQuery<T> {
}
PostgresSQLDatabaseQueryFactory [source]
export class PostgresSQLDatabaseQueryFactory extends SQLDatabaseQueryFactory {
    createQuery<T extends OrmEntity>(type?: ReceiveType<T> | ClassType<T> | AbstractClassType<T> | ReflectionClass<T>): PostgresSQLDatabaseQuery<T>;
}
PostgresDatabaseAdapter [source]
export class PostgresDatabaseAdapter extends SQLDatabaseAdapter {
    connectionPool: PostgresConnectionPool;
    platform;
    closed;
    constructor(options: PostgresClientOptions | string, additional: Partial<PostgresClientOptions> = {});
    setLogger(logger: Logger);
    getName(): string;
    getSchemaName(): string;
    createPersistence(session: DatabaseSession<this>): SQLPersistence;
    createTransaction(session: DatabaseSession<this>): PostgresDatabaseTransaction;
    queryFactory(session: DatabaseSession<any>): SQLDatabaseQueryFactory;
    disconnect(force?: boolean): void;
}
PostgresPlaceholderStrategy [source]
export class PostgresPlaceholderStrategy extends SqlPlaceholderStrategy {
    override getPlaceholder();
}
PostgresPlatform [source]
export class PostgresPlatform extends DefaultPlatform {
    override annotationId;
    override readonly serializer: Serializer;
    override schemaParserType;
    override placeholderStrategy;
    constructor();
    override getSqlTypeCaster(type: Type): (placeholder: string) => string;
    override getAggregateSelect(tableName: string, property: ReflectionProperty, func: string);
    override createSqlFilterBuilder(adapter: PreparedAdapter, schema: ReflectionClass<any>, tableName: string): PostgreSQLFilterBuilder;
    override getDeepColumnAccessor(table: string, column: string, path: string);
    override quoteValue(value: any): string;
    override getColumnDDL(column: Column);
    getModifyColumnDDL(diff: ColumnDiff): string;
    getDefaultExpression(column: Column): string;
    getUniqueDDL(unique: IndexModel): string;
    supportsInlineForeignKey(): boolean;
    supportsAggregatedAlterTable(): boolean;
    supportsSelectFor(): boolean;
    getAutoIncrement();
    getDropTableDDL(table: Table): string;
    getUseSchemaDDL(table: Table);
    getResetSchemaDDL(table: Table): string;
}
PostgresSchemaParser [source]
export class PostgresSchemaParser extends SchemaParser {
    async parse(database: DatabaseModel, limitTableNames?: string[]);
}
PostgresClient [source]
export class PostgresClient {
    readonly options: ResolvedPostgresOptions;
    /**  How many statements each new connection keeps on the server, 0 turns it off. */
    maxPreparedStatements: number;
    constructor(options: PostgresClientOptions = {});
    /**  Connections that are open or being opened. */
    get size(): number;
    /**
     * Returns a connection without waiting when one is available, as an idle one or on an existing connection
     * through pipelining. Has to be given back with release.
     */
    tryAcquire(exclusive: boolean): PostgresClientConnection | undefined;
    /**  Returns a connection that is ready to use and has to be given back with release. */
    acquire(exclusive: boolean = true): Promise<PostgresClientConnection>;
    /**  Gives up the use of a connection acquired with acquire or tryAcquire. */
    release(connection: PostgresClientConnection): void;
    close(): void;
}

Pool of connections to one server.

An idle connection is used first. When there is none a new one is opened up to max, and only after that connections are shared via pipelining up to maxPipelineDepth. A user that needs the connection for itself, like a transaction or a long running read, asks for it to be exclusive and waits for a free one.

PostgresClientConnection [source]
export class PostgresClientConnection implements PoolableConnection, PostgresMessageHandler {
    load: number;
    exclusive: boolean;
    idleSince: number;
    /**  Server settings the server reported, like server_version or TimeZone. */
    readonly parameters;
    onNotice?: (notice: PostgresError) => void;
    onNotification?: (channel: string, payload: string, pid: number) => void;
    /**  I for idle, T in a transaction, E in a failed transaction. */
    transactionStatus: number;
    constructor(protected options: ResolvedPostgresOptions, protected encoder: PostgresEncoder, protected onClose: (connection: PostgresClientConnection) => void, maxPreparedStatements: number);
    connect(): Promise<void>;
    isConnected(): boolean;
    /**  True while the connection has an open or failed transaction. */
    inTransaction(): boolean;
    close(): void;
    onDataRow(data: Uint8Array, start: number): void;
    onCommandComplete(data: Uint8Array, start: number, end: number): void;
    onReadyForQuery(data: Uint8Array, start: number): void;
    /**
     * Runs a query. Without parameters the simple protocol is used, which allows several statements at once.
     *
     * @param reusable Keeps the statement on the server and uses binary results for it from the second run on.
     */
    query(sql: string, params?: any[], mode: RowMode = RowMode.object, reusable: boolean = false): Promise<QueryResult>;
    /**  Like query, but resolves with only the rows. */
    queryRows(sql: string, params?: any[], mode: RowMode = RowMode.object, reusable: boolean = false): Promise<any[]>;
    /**
     * Like queryRows, but resolves with what map returns for each row. The row is only valid during the call, all
     * rows are decoded into the same object: a query allocates no object per row besides what map creates.
     * When map throws, the query fails with that error.
     */
    queryMapped<T>(sql: string, params: any[] | undefined, map: (row: any) => T, reusable: boolean = false): Promise<T[]>;
    /**  Like query, but resolves with only the first row, undefined if there is none. */
    queryRow(sql: string, params?: any[], mode: RowMode = RowMode.object, reusable: boolean = false): Promise<any>;
    /**
     * Runs the queries of one caller with a single Sync. Each one runs after the other in the same implicit
     * transaction: when one fails none of them are committed and the promise is rejected, with a batchIndex.
     */
    batch(queries: {
        sql: string;
        params?: any[];
    }[]): Promise<QueryResult[]>;
    /**
     * Runs COPY ... FROM STDIN and sends the chunks. Needs a connection of its own, as nothing else
     * can run while it is in progress. Resolves with the number of rows.
     */
    copyFrom(sql: string, source: Iterable<string | Uint8Array> | AsyncIterable<string | Uint8Array>): Promise<number>;
    /**
     * Rejects the running query at the head when it is past its deadline, and asks the server to stop it.
     * Its replies are still read and ignored, as they would otherwise be attributed to the next query.
     */
    checkTimeout(now: number): void;
    /**
     * Asks the server to stop whatever this connection is currently executing, via a separate connection.
     * Everything queued behind it on this connection keeps running.
     */
    cancel(): Promise<void>;
}

Errors

PostgresError [source]
export class PostgresError extends DatabaseError {
    severity?: string;
    /**  SQLSTATE of the server, or the code of the socket error for PostgresConnectionError. */
    code?: string;
    detail?: string;
    hint?: string;
    position?: string;
    internalPosition?: string;
    internalQuery?: string;
    where?: string;
    schema?: string;
    table?: string;
    column?: string;
    dataType?: string;
    constraint?: string;
    file?: string;
    line?: string;
    routine?: string;
    /**  For a query that was part of a batch, its index there. */
    batchIndex?: number;
}

An error reported by the server. The field names are the ones of the pg driver, so that existing code keeps working, for example handleSpecificError reading table and detail.

PostgresConnectionError [source]
export class PostgresConnectionError extends PostgresError {
}

The connection was refused, lost, or the stream could not be used anymore.

Const

postgresSerializer [source]
PostgresSerializer

Functions

parseConnectionString [source]
(url: string): PostgresClientOptions
parseErrorResponse [source]
(data: Uint8Array, offset: number, end: number): PostgresError

The message of an error response, read from the fields of an E or N message starting at offset.

parsePostgresConnectionString [source]
(connectionString: string): PostgresClientOptions

Parses a URL into options. Query parameters that are not known are ignored.

resolvePostgresOptions [source]
(input?: PostgresClientOptions): ResolvedPostgresOptions

Applies connection string, environment variables and defaults, in that order of precedence.

Types

TransactionTypes [source]
type TransactionTypes = 'REPEATABLE READ' | 'READ COMMITTED' | 'SERIALIZABLE';
QueryResult [source]
interface QueryResult {
    /** undefined when several statements were executed at once, the same as rowCount. */
    rows: any[];
    rowCount: number | null;
    fields: PostgresColumn[];
}
PostgresPassword [source]
type PostgresPassword = string | (() => string | Promise<string>);
PostgresClientOptions [source]
interface PostgresClientOptions {
    user?: string;
    database?: string;
    password?: PostgresPassword;
    port?: number;
    /** A directory starting with / connects via unix socket. */
    host?: string;
    /** A postgres:// URL, its values take precedence over the other options. */
    connectionString?: string;
    keepAlive?: boolean;
    keepAliveInitialDelayMillis?: number;
    statement_timeout?: false | number;
    lock_timeout?: false | number;
    idle_in_transaction_session_timeout?: false | number;
    /** Client side timeout. On expiry the query is rejected and cancelled on the server. */
    query_timeout?: number;
    parseInputDatesAsUTC?: boolean;
    ssl?: boolean | TlsConnectionOptions;
    application_name?: string;
    fallback_application_name?: string;
    options?: string;
    /** Also limits the wait for a free connection of the pool. */
    connectionTimeoutMillis?: number;
    max?: number;
    min?: number;
    idleTimeoutMillis?: number;
    /**
     * When all connections are busy, how many users may share one by pipelining.
     * 1 or less turns pipelining off, then callers wait for a free connection.
     */
    maxPipelineDepth?: number;
    /**
     * Queries that can be shared go on a connection busy with fewer than this many before an idle one is used.
     * Fewer backends do more per round trip. 1 prefers idle connections.
     */
    preferPipelineDepth?: number;
    /** Not used. Accepted for compatibility. */
    client_encoding?: string;
    allowExitOnIdle?: boolean;
    maxUses?: number;
}

Options of the former driver are accepted under the same names.

ResolvedPostgresOptions [source]
interface ResolvedPostgresOptions {
    user: string;
    database: string;
    password?: PostgresPassword;
    port: number;
    host: string;
    /** Path of the unix socket, when host is a directory. */
    socketPath?: string;
    keepAlive: boolean;
    keepAliveInitialDelayMillis: number;
    queryTimeout: number;
    parseInputDatesAsUTC: boolean;
    ssl?: TlsConnectionOptions;
    startupParameters: { [name: string]: string };
    connectionTimeoutMillis: number;
    max: number;
    min: number;
    idleTimeoutMillis: number;
    maxPipelineDepth: number;
    preferPipelineDepth: number;
}

English中文 (Chinese)한국어 (Korean)日本語 (Japanese)Deutsch (German)