Options
All
  • Public
  • Public/Protected
  • All
Menu

Provides access to a PostgreSQL 9.5 (or later) database server. Supports connection pooling and query iteration. Supports SQL operations as well as NoSQL operations using the JSONB data type.

The Postgres connection string has the following general form: postgres://<user>:<password>@<hostname>:<port>/<database>?ssl=true&application_name=PGAPPNAME&fallback_application_name=false

PostgreSQL supports the following connection options (with the given default values):

{
// database host
host: process.env.PGHOST || 'localhost',

// database user's name
user: process.env.PGUSER || process.env.USER

// name of database to connect
database: process.env.PGDATABASE || process.env.USER

// database user's password
password: process.env.PGPASSWORD || null,

// database port
port: process.env.PGPORT || 5432,

// number of rows to return at a time from a prepared statement's
// portal. 0 will return all rows at once
rows: 0,

// binary result mode
binary: false,

client_encoding: "",

ssl: false,

// TCP keep alive: this should help with backends incorrectly considering
// idle clients to be dead and prematurely disconnecting them.
keepAlive: false,

application_name: undefined,

fallback_application_name: undefined,

parseInputDatesAsUTC: false

// Pool Options (see also https://github.com/brianc/node-pg-pool and https://github.com/coopernurse/node-pool)

// maximum number of resources to create at any given time optional (default=1)
max: 10

// minimum number of resources to keep in pool at any given time
// if this is set >= max, the pool will silently set the min
// to factory.max - 1 (Note: min==max case is expected to change in v3 release)
// optional (default=0)
min: 0

// max milliseconds a resource can go unused before it should be destroyed
// (default 30000)
idleTimeoutMillis: 30000

// return an error after given milliseconds if connection could not be established
connectionTimeoutMillis: 1000

// If true, logs pool activities to console; can also be a function.
// Note: true doesn't work properly in a Node.js process, use a function instead.
log: true/false or function(msg: string, level: string) => {}

}

This adapter supports the following adapter configuration options:

{
// The default chunk size of chunking fetch operations such as findObjects
// or iquery (default 100). This value can be overridden in individual
// fetch operations by specifying the DbObjectFilter.fetchSize property.
defaultFetchSize: 100
}

This adapter supports the following extensions for creating/deleting users and databases dynamically:

createUser
deleteUser
initDatabase
createDatabase
deleteDatabase

Note that these operations must be performed on a database context with administrative privileges, i.e. the connection info must specify a user/pwd with administration rights.

Hierarchy

Index

Constructors

constructor

Properties

Protected connectionInfo

connectionInfo: DbConnectionInfo

Methods

addCollection

  • addCollection(name: string): Promise<void>

addStore

  • addStore(name: string): Promise<any>
  • Add a new store with the given name if it doesn't exist.

    Returns a promise that is fulfilled if the operation succeeded. The promise is rejected if an error occurred.

    Parameters

    • name: string

    Returns Promise<any>

aggregateObjects

  • Aggregates values of the given object property in the collection for objects which match the given filter. Depending on the aggregation operator specified either numeric or boolean values are yielded. The value type of the given object property must match the aggregation operator specified.

    If the filter is empty or not specified all objects are considered for aggregation. If the filter matches no objects at all the aggregated value returned is undefined. Returns a promise that if fulfilled yields the aggregated value of matching object properties. The promise is rejected if an error occurred.

    The object property to be applied for aggregation is specified either in dot notation or array notation. In dot notation, the name of the object property is specified as a string (e.g. "volume"). It may include dots (.) to access nested properties of subobjects (e.g. "message.size"). If a single property name contains dots itself, you obviously cannot use dot notation. Instead, specify the property or nested properties as an array of strings (e.g. ["property.with.dots", "subproperty.with.dots"]).

    Parameters

    Returns Promise<number | boolean>

callExtension

  • callExtension(name: string, ...params: any[]): Promise<any>
  • Invoke the extension method by the given name and returns the result as a promise. Returns a rejected promise if the extension method doesn't exist or throws an error.

    Parameters

    • name: string

      name of registered extension method

    • Rest ...params: any[]

      parameters to be applied to extension method

    Returns Promise<any>

clearCollection

  • clearCollection(name: string): Promise<void>

clearValues

  • clearValues(store?: string): Promise<any>
  • Deletes all key-value pairs in the default store or the store specified.

    Returns a promise that is fulfilled if the delete operation succeeded. The promise is rejected if an error occurred.

    Parameters

    • Optional store: string

    Returns Promise<any>

close

  • close(): Promise<any>
  • Closes the local database. By closing, any file locks on the database file are removed. The database is reopened again when operations are invoked after the database has been closed.

    Returns a promise that is fulfilled if the close operation succeeded. The promise is rejected if an error occurred.

    Returns Promise<any>

countObjects

  • countObjects(collectionName: string, filter?: DbObjectFilter): Promise<number>
  • Counts objects in the collection which match the given filter. If the filter is empty or not specified counts the total number of objects in the collection. Returns a promise that if fulfilled yields the number of matching objects. The promise is rejected if an error occurred.

    Parameters

    Returns Promise<number>

createDatabase

  • createDatabase(name: string, owner: string, comment?: string): Promise<boolean>
  • Create a new database of the given name if it doesn't already exist.

    Returns a promise that if fulfilled yields true if the database has been created, false otherwise. The promise is rejected if an error occurs. To create a database the specified owner must be a superuser. To issue this command, the client should connect to the postgres database.

    Note that this operation cannot be executed inside a transaction block.

    Parameters

    • name: string

      the name of the database to create

    • owner: string

      the owner (superuser) of the database, see createUser extension

    • Optional comment: string

      a comment to associate with the created database

    Returns Promise<boolean>

createUser

  • createUser(name: string, password: string, comment?: string): Promise<boolean>
  • Create a user (role) with the given name if it doesn't already exist.

    Returns a promise that is fullfilled if the user has been created or already exists. The promise is rejected if an error occurs. You must have CREATEROLE privilege or be a database superuser to use this command. To issue this command, the client should connect to the postgres database.

    Parameters

    • name: string

      the name of the user to create

    • password: string

      the plain or md5 encoded password

    • Optional comment: string

      a comment on the user

    Returns Promise<boolean>

deleteDatabase

  • deleteDatabase(name: string): Promise<void>
  • Drops the given database if it exists.

    Returns a promise that is fullfilled if the database has been deleted or didn't exist. The promise is rejected if an error occurs. Note that an error occurs if you try to delete a database that has active client connections. This command can only be executed by the database owner. To issue this command, the client should connect to the postgres database.

    Note that this operation cannot be executed inside a transaction block.

    Parameters

    • name: string

      the name of the database to delete

    Returns Promise<void>

deleteObjects

  • deleteObjects(collectionName: string, filter?: DbObjectFilter): Promise<number>
  • Deletes objects from the collection which match the given filter. If the filter is empty or not specified all objects in the collection are deleted. Returns a promise that if fulfilled yields the number of objects deleted. The promise is rejected if an error occurred. In this case it is guaranteed that none of the requested objects has been deleted.

    Parameters

    Returns Promise<number>

deleteObjectsById

  • deleteObjectsById(collectionName: string, objectIds: string | string[]): Promise<string[]>
  • Deletes an object or multiple objects with the given object IDs from the collection. Objects which are not contained in the collection are ignored. Returns a promise that if fulfilled yields an array of object IDs of deleted objects. The promise is rejected if an error occurred. In this case it is guaranteed that none of the requested objects has been deleted.

    Parameters

    • collectionName: string
    • objectIds: string | string[]

    Returns Promise<string[]>

deleteUser

  • deleteUser(name: string): Promise<void>
  • Drop the given user (role).

    Returns a promise that is fullfilled if the user has been deleted. The promise is rejected if an error occurs. You must have CREATEROLE privilege or be a database superuser to use this command. To issue this command, the client should connect to the postgres database.

    Parameters

    • name: string

      the name of the user to remove

    Returns Promise<void>

deleteValue

  • deleteValue(key: string, store?: string): Promise<any>
  • Deletes the key-value pair for the given key in the default store or the store specified.

    Returns a promise that is fulfilled if the delete operation succeeded. The promise is rejected if an error occurred.

    Parameters

    • key: string
    • Optional store: string

    Returns Promise<any>

findObjectById

  • findObjectById<T>(collectionName: string, id: string, isExternalId?: boolean): Promise<T>
  • Finds the first object with the given object ID or external ID in the collection. Returns a promise that if fulfilled yields the first found object or undefined if no object with the given ID is contained in the collection. The promise is rejected if an error occurred.

    If the isExternalId parameter is not specified, the given id is interpreted as object ID.

    Type parameters

    Parameters

    • collectionName: string
    • id: string
    • isExternalId: boolean = false

    Returns Promise<T>

findObjects

  • Finds objects in the collection which match the given object filter. If the filter is empty or not specified all objects in the collection are retrieved.

    Optional join conditions can be specified to augment result objects by resolving object references to related objects and storing them as extra properties.

    The result can be iterated one by one or in batches to avoid memory overrun when the result contains a large number of objects.

    Returns a promise that if fulfilled yields an iterator for iterating the resulting objects. The promise is rejected if an error occurred.

    Type parameters

    Parameters

    Returns Promise<IQueryIterator<T>>

getValue

  • getValue(key: string, store?: string): Promise<any>
  • Gets the value for the given key in the default store or the store specified.

    Returns a promise that if fulfilled yields the value for the key. If the given key doesn't exist, the promise yields undefined. The promise is rejected if an error occurred.

    Parameters

    • key: string
    • Optional store: string

    Returns Promise<any>

getValues

  • getValues(store?: string): Promise<any>
  • Gets an object with all key-value pairs in the default store or the store specified.

    Returns a promise that if fulfilled yields an object of key-value pairs. The promise is rejected if an error occurred.

    Parameters

    • Optional store: string

    Returns Promise<any>

initDatabase

  • initDatabase(dbInfo: DbConnectionInfo, collections?: string[], clearCollections?: boolean): Promise<number>
  • Initialize a database from the given connection info. The database and database user is created if it not yet exists. Then, collections are added if needed from the given collection names. Optionally, the collections can be cleared initially. This can be useful in test scenarios where collection data from a previous run should be removed.

    Returns a promise that is resolved if the database and collections have been created successfully, and rejected if an error occurs.

    Note that the database context on which this extension method is invoked must connect to the postgres database with superuser admin permissions.

    Parameters

    • dbInfo: DbConnectionInfo

      connection info for database operations

    • Optional collections: string[]

      an array of database collection names

    • clearCollections: boolean = false

      determines whether collection data should be cleared initially

    Returns Promise<number>

insertObjects

  • insertObjects(collectionName: string, objects: CoatyObject | CoatyObject[], shouldReplaceExisting: boolean): Promise<string[]>
  • Inserts a single object or multiple objects into the specified collection. If an object with the same object ID is already contained in the collection, the object to be inserted can be skipped or can replace the existing one, depending on the shouldReplaceExisting option (defaults to true).

    If no error occurs a fullfilled promise is returned that yields an array of object IDs of inserted or replaced objects. Otherwise, a rejected promise is returned. In this case, it is guaranteed that none of the specified objects has been inserted into the collection.

    Parameters

    Returns Promise<string[]>

iquery

  • Execute an SQL query defined by the given query builder and retrieve the results iteratively.

    Use the predefined query builder functions SQL or RAW to formulate your parameterized SQL query.

    The result can be iterated one by one or in batches to avoid memory overrun when the result contains a large number of rows. Usually, this is implemented by using a cursor. The fetch size of the cursor can be adjusted in the specified query options.

    Returns a promise that if fulfilled yields an iterator for iterating the resulting row data. The promise is rejected if an error occurs.

    If you know that a query only returns a very limited number of rows, it might be more convenient to use the query operation to retrieve all rows at once.

    Note that the iquery operation might not be supported by a specific database adapter. In this case, the returned promise yields an "operation not supported" error.

    Parameters

    Returns Promise<IQueryIterator<any>>

query

  • Execute an SQL query defined by the given query builder and retrieve the results as one set of row data.

    Use the predefined query builder functions SQL or RAW to formulate your parameterized SQL query.

    Returns a promise that if fulfilled yields all the query results as one set of row data. The promise is rejected if the query yields an error.

    Note that the query first retrieves all result rows and stores them in memory. For queries that have potentially large result sets, consider to use the iquery operation instead of this one.

    Parameters

    Returns Promise<SqlQueryResultSet>

Protected registerExtension

  • registerExtension(extensionName: string): void

Protected rejectNotSupported

  • rejectNotSupported(operationName: string): Promise<any>

removeCollection

  • removeCollection(name: string): Promise<void>

removeStore

  • removeStore(name: string): Promise<any>
  • Remove a store with the given name if it exists.

    Returns a promise that is fulfilled if the operation succeeded. The promise is rejected if an error occurred.

    Parameters

    • name: string

    Returns Promise<any>

setValue

  • setValue(key: string, value: any, store?: string): Promise<any>
  • Sets the value for the given key in the default store or the store specified.

    You can pass in any JavaScript object that can be represented in JSON format.

    Returns a promise that is fulfilled if the set operation succeeded. The promise is rejected if an error occurred.

    Parameters

    • key: string
    • value: any
    • Optional store: string

    Returns Promise<any>

transaction

  • transaction<T>(action: (transactionContext: DbContext) => Promise<T>): Promise<T>
  • Execute async operations in the given action callback inside a database transaction block. The action callback must return a promise that is fulfilled if all operations have executed without errors, and that is rejected if any of the operations fail. All transactional operations must be invoked on the transaction context passed in the action callback.

    Returns a promise that if fulfilled signals that the transaction has been committed. In this case, the promise resolves to the value of the resolved action callback. The promise is rejected if the transaction is rolled back because the action callback's returned promise has been rejected.

    Type parameters

    • T

    Parameters

    • action: (transactionContext: DbContext) => Promise<T>
        • Parameters

          Returns Promise<T>

    Returns Promise<T>

updateObjectProperty

  • updateObjectProperty(collectionName: string, objectIds: string | string[], property: string, value: any, shouldCreateMissing?: boolean): Promise<any>
  • Updates or deletes the property value of a single object or multiple objects with the given object IDs in the specified collection. Objects which are not contained in the collection are ignored. The shouldCreateMissing parameter controls whether the property value pair is added to an object if the property does not exist (defaults to true). Specify an undefined value to delete the property value pair from the object(s).

    Returns a promise that is resolved if the update is successful. The promise is rejected if an error occurred. In this case it is guaranteed that none of the objects has been updated.

    Parameters

    • collectionName: string
    • objectIds: string | string[]
    • property: string
    • value: any
    • shouldCreateMissing: boolean = true

    Returns Promise<any>

updateObjects

  • Updates a single object or multiple objects on the specified collection. If an object with the same object ID is not contained in the collection, this object is ignored.

    Returns a promise that if fulfilled yields an array of object IDs of updated objects. The promise is rejected if an error occurred. In this case it is guaranteed that none of the objects has been updated.

    Parameters

    Returns Promise<string[]>

Generated using TypeDoc