UNPKG

trilogy

Version:

TypeScript SQLite layer with support for both native C++ & pure JavaScript drivers.

358 lines (357 loc) 16.7 kB
import * as knex from 'knex'; import Model from './model'; import { Pool } from 'generic-pool'; import { Database } from 'sql.js'; import * as hooks from './hooks'; import * as types from './types'; /** * Initialize a new datastore instance, creating a SQLite database file at * the provided path if it does not yet exist, or reading it if it does. * * It's recommended to use the {@link connect} function to create instances * rather than instantiating this class directly. * * @remarks * If path is exactly `':memory:'`, no file will be created and a memory-only * store will be used. This doesn't persist any of the data. */ export declare class Trilogy { /** * Indicates whether the database is using the `sqlite3` client (`true`) or * the `sql.js` (`false`) backend. */ isNative: boolean; /** * The knex instance used for building queries. */ knex: knex; /** * Normalized configuration of this trilogy instance. */ options: types.Defined<types.TrilogyOptions> & { connection: { filename: string; }; }; /** * Connection pool for managing a sql.js instance. * * @internal */ pool?: Pool<Database>; private _definitions; /** * @param path File path or `':memory:'` for in-memory storage * @param options Configuration for this trilogy instance */ constructor(path: string, options?: types.TrilogyOptions); /** * Array of all model names defined on the instance. */ get models(): string[]; /** * Define a new model with the provided schema, or return the existing * model if one is already defined with the given name. * * @param name Name of the model * @param schema Object defining the schema of the model * @param options Configuration for this model instance */ model<D extends types.ReturnDict = types.LooseObject>(name: string, schema: types.SchemaRaw<D>, options?: types.ModelOptions): Promise<Model<D>>; /** * Synchronously retrieve a model if it exists. If that model doesn't exist * an error will be thrown. * * @param name Name of the model * * @throws if `name` has not already been defined */ getModel<D extends types.ReturnDict = types.LooseObject>(name: string): Model<D> | never; /** * First checks if the model's been defined with trilogy, then runs an * existence query on the database, returning `true` if the table exists * or `false` if it doesn't. * * @param name Name of the model */ hasModel(name: string): Promise<boolean>; /** * Removes the specified model from trilogy's definition and the database. * * @param name Name of the model to remove */ dropModel(name: string): Promise<boolean>; /** * Allows running any arbitrary query generated by trilogy's `knex` instance. * If the result is needed, pass `true` as the second argument, otherwise the * number of affected rows will be returned ( if applicable ). * * @param query Any query built with `knex` * @param [needResponse] Whether to return the result of the query */ raw<T = any>(query: knex.QueryBuilder | knex.Raw, needResponse?: boolean): Promise<T>; /** * Drains the connection pools and releases connections to any open database * files. This should always be called at the end of your program to * gracefully shut down, and only once since the connection can't be reopened. */ close(): Promise<void>; /** * Create an object on the given model. `object` should match the model's * defined schema but values will cast into types as needed. * * @param modelName Name of the existing model where the object will be created * @param object Data to insert * @param options */ create<T = types.LooseObject>(modelName: string, object: types.LooseObject, options?: types.LooseObject): Promise<T>; /** * Find all objects matching a given criteria. * * @param location Model name and an optional column in dot-notation * @param criteria Criteria used to restrict selection * @param options */ find<T = types.LooseObject>(location: string, criteria?: types.Criteria, options?: types.FindOptions): Promise<T[]>; /** * Find a single object matching a given criteria. The first matching * object is returned. * * @param location Model name and an optional column in dot-notation * @param criteria Criteria used to restrict selection * @param options */ findOne<T = types.LooseObject>(location: string, criteria?: types.Criteria, options?: types.FindOptions): Promise<T>; /** * Find a matching object based on the given criteria, or create it if it * doesn't exist. When creating the object, a merged object created from * `criteria` and `creation` will be used, with the properties from * `creation` taking precedence. * * @param modelName Name of the model * @param criteria Criteria to search for * @param creation Data used to create the object if it doesn't exist * @param options */ findOrCreate<T = types.LooseObject>(modelName: string, criteria: types.Criteria, creation?: types.LooseObject, options?: types.FindOptions): Promise<T>; /** * Modify the properties of an existing object. While optional, if `data` * contains no properties no update queries will be run. * * @param modelName Name of the model * @param criteria Criteria used to restrict selection * @param data Updates to be made on matching objects * @param options */ update(modelName: string, criteria: types.Criteria, data: types.LooseObject, options?: types.UpdateOptions): Promise<Record<string, any>[]>; /** * Update an existing object or create it if it doesn't exist. If creation * is necessary a merged object created from `criteria` and `data` will be * used, with the properties from `data` taking precedence. * * @param modelName Name of the model * @param criteria Criteria used to restrict selection * @param data Updates to be made on matching objects * @param options */ updateOrCreate(modelName: string, criteria: types.Criteria, data: types.LooseObject, options?: types.CreateOptions & types.UpdateOptions): Promise<Record<string, any>[]>; /** * Works similarly to the `get` methods in lodash, underscore, etc. Returns * the value at `column` or, if it does not exist, the supplied `defaultValue`. * Essentially a useful shorthand for some `find` scenarios. * * @param location Model name and a column in dot-notation * @param criteria Criteria used to restrict selection * @param defaultValue Value returned if the result doesn't exist */ get<T = types.ReturnType>(location: string, criteria: types.Criteria, defaultValue?: T): Promise<T>; /** * Works similarly to the `set` methods in lodash, underscore, etc. Updates * the value at `column` to be `value` where the given criteria is met. * * @param location Model name and a column in dot-notation * @param criteria Criteria used to restrict selection * @param value Value returned if the result doesn't exist */ set<T>(location: string, criteria: types.Criteria, value: T): Promise<Record<string, any>[]>; /** * Works exactly like `get` but bypasses getters and retrieves the raw database value. * * @param location Model name and a column in dot-notation * @param criteria Criteria used to restrict selection * @param defaultValue Value returned if the result doesn't exist */ getRaw<T>(location: string, criteria: types.Criteria, defaultValue: T): Promise<T>; getRaw(location: string, criteria: types.Criteria): Promise<types.ReturnType>; getRaw<T extends Record<string, unknown>, K extends keyof T = keyof T>(location: string, criteria: types.Criteria): Promise<T[K]>; /** * Works exactly like `set` but bypasses setters when updating the target value. * * @param location Model name and a column in dot-notation * @param criteria Criteria used to restrict selection * @param value Value returned if the result doesn't exist */ setRaw<T>(location: string, criteria: types.Criteria, value: T): Promise<Record<string, any>[]>; /** * Increment the value of a given model's property by the specified amount, * which defaults to `1` if not provided. * * @param location Model name and a column in dot-notation * @param criteria Criteria used to restrict selection * @param amount */ increment(location: string, criteria: types.Criteria, amount?: number): Promise<Record<string, any>[]>; /** * Decrement the value of a given model's property by the specified amount, * which defaults to `1` if not provided. * * @param location Model name and a column in dot-notation * @param criteria Criteria used to restrict selection * @param amount */ decrement(location: string, criteria: types.Criteria, amount?: number, allowNegative?: boolean): Promise<Record<string, any>[]>; /** * Delete objects matching `criteria` from the given model. * * @remarks * If `criteria` is empty or absent, nothing will be done. This is a safeguard * against unintentionally deleting everything in the model. Use `clear` if * you really want to remove all rows. * * @param modelName Name of the model * @param criteria Criteria used to restrict selection */ remove(modelName: string, criteria: types.Criteria): Promise<Record<string, any>[]>; /** * Delete all objects from the given model. * * @param modelName Name of the model */ clear(modelName: string): Promise<number>; /** * Count the number of objects in the given model. * * @param location Model name and an optional column in dot-notation * @param criteria Criteria used to restrict selection * @param options */ count(location?: string, criteria?: types.Criteria, options?: types.AggregateOptions): Promise<number>; /** * Find the minimum value contained in the model, comparing all values in * `column` that match the given criteria. * * @param location Model name and a column in dot-notation * @param criteria Criteria used to restrict selection * @param options */ min(location: string, criteria: types.Criteria, options?: types.AggregateOptions): Promise<number | undefined>; /** * Find the maximum value contained in the model, comparing all values in * `column` that match the given criteria. * * @param location Model name and a column in dot-notation * @param criteria Criteria used to restrict selection * @param options */ max(location: string, criteria: types.Criteria, options?: types.AggregateOptions): Promise<number | undefined>; /** * The `onQuery` hook is called each time a query is run on the database, * and receives the query in string form. * * @param [modelName] Optional, name of the model this subscriber will attach to * @param fn Function called when the hook is triggered * @param options * * @returns Unsubscribe function that removes the subscriber when called */ onQuery(...args: [hooks.OnQueryCallback, hooks.OnQueryOptions?] | [string, hooks.OnQueryCallback, hooks.OnQueryOptions?]): types.Fn<[], boolean>; /** * Before an object is created, the beforeCreate hook is called with the * object. * * @remarks * This hook occurs before casting, so if a subscriber to this hook * modifies the incoming object those changes will be subject to casting. * It's also possible to prevent the object from being created entirely * by returning the EventCancellation symbol from a subscriber callback. * * @param [modelName] Optional, name of the model this subscriber will attach to * @param fn Function called when the hook is triggered * * @returns Unsubscribe function that removes the subscriber when called */ beforeCreate<D extends types.ReturnDict = types.LooseObject>(...args: [hooks.BeforeCreateCallback<D>] | [string, hooks.BeforeCreateCallback<D>]): types.Fn<[], boolean>; /** * When an object is created, that object is returned to you and the * `afterCreate` hook is called with it. * * @param [modelName] Optional, name of the model this subscriber will attach to * @param fn Function called when the hook is triggered * * @returns Unsubscribe function that removes the subscriber when called */ afterCreate<D extends types.ReturnDict = types.LooseObject>(...args: [hooks.AfterCreateCallback<D>] | [string, hooks.AfterCreateCallback<D>]): types.Fn<[], boolean>; /** * Prior to an object being updated the `beforeUpdate` hook is called with the * update delta, or the incoming changes to be made, as well as the criteria. * * @remarks * Casting occurs after this hook. A subscriber could choose to cancel the * update by returning the EventCancellation symbol or alter the selection * criteria. * * @param [modelName] Optional, name of the model this subscriber will attach to * @param fn Function called when the hook is triggered * * @returns Unsubscribe function that removes the subscriber when called */ beforeUpdate<D extends types.ReturnDict = types.LooseObject>(...args: [hooks.BeforeUpdateCallback<D>] | [string, hooks.BeforeUpdateCallback<D>]): types.Fn<[], boolean>; /** * Subscribers to the `afterUpdate` hook receive modified objects after they * are updated. * * @param [modelName] Optional, name of the model this subscriber will attach to * @param fn Function called when the hook is triggered * * @returns Unsubscribe function that removes the subscriber when called */ afterUpdate<D extends types.ReturnDict = types.LooseObject>(...args: [hooks.AfterUpdateCallback<D>] | [string, hooks.AfterUpdateCallback<D>]): types.Fn<[], boolean>; /** * Before object removal, the criteria for selecting those objects is passed * to the `beforeRemove` hook. * * @remarks * Casting occurs after this hook. Subscribers can modify the selection * criteria or prevent the removal entirely by returning the `EventCancellation` * symbol. * * @param [modelName] Optional, name of the model this subscriber will attach to * @param fn Function called when the hook is triggered * * @returns Unsubscribe function that removes the subscriber when called */ beforeRemove<D extends types.ReturnDict = types.LooseObject>(...args: [hooks.BeforeRemoveCallback<D>] | [string, hooks.BeforeRemoveCallback<D>]): types.Fn<[], boolean>; /** * A list of any removed objects is passed to the `afterRemove` hook. * * @param [modelName] Optional, name of the model this subscriber will attach to * @param fn Function called when the hook is triggered * * @returns Unsubscribe function that removes the subscriber when called */ afterRemove<D extends types.ReturnDict = types.LooseObject>(...args: [hooks.AfterRemoveCallback<D>] | [string, hooks.AfterRemoveCallback<D>]): types.Fn<[], boolean>; } export { EventCancellation, OnQueryOptions, OnQueryCallback, BeforeCreateCallback, AfterCreateCallback, BeforeUpdateCallback, AfterUpdateCallback, BeforeRemoveCallback, AfterRemoveCallback, HookCallback } from './hooks'; export { default as Model } from './model'; export * from './types'; /** * Initialize a new datastore instance, creating a SQLite database file at * the provided path if it does not yet exist, or reading it if it does. * * @param path File path or `':memory:'` for memory-only storage * @param options Configuration for this trilogy instance */ export declare const connect: (path: string, options?: { client?: "sqlite3" | "sql.js" | undefined; dir?: string | undefined; } | undefined) => Trilogy;