// Originally based on contributions to DefinitelyTyped: // Definitions by: Qubo // Pablo Rodríguez // Matt R. Wilson // Satana Charuwichitratana // Shrey Jain // TypeScript Version: 4.1 import tarn = require('tarn'); import events = require('events'); import stream = require('stream'); import ResultTypes = require('./result'); import { Tables } from './tables'; import { Stream } from 'stream'; import { ConnectionOptions } from 'tls'; // # Generic type-level utilities // If T is object then make it a partial otherwise fallback to any // // This is primarily to prevent type incompatibilities where target can be unknown. // While unknown can be assigned to any, Partial can't be. type SafePartial = Partial>; type MaybeArray = T | T[]; type StrKey = string & keyof T; // If T is unknown then convert to any, else retain original type UnknownToAny = unknown extends T ? any : T; type CurlyCurlyToAny = T extends unknown // distribute ? (() => U extends T ? 0 : 1) extends () => U extends {} ? 0 : 1 ? any : T : never; type UnknownOrCurlyCurlyToAny = [UnknownToAny | CurlyCurlyToAny][0]; type AnyToUnknown = unknown extends T ? unknown : T; type AnyOrUnknownToOther = unknown extends T1 ? T2 : T1; // Intersection conditionally applied only when TParams is non-empty // This is primarily to keep the signatures more intuitive. type AugmentParams = TParams extends {} ? keyof TParams extends never ? TTarget : {} & TTarget & TParams : TTarget; // Check if provided keys (expressed as a single or union type) are members of TBase type AreKeysOf = Boxed extends Boxed ? true : false; // https://stackoverflow.com/a/50375286/476712 type UnionToIntersection = (U extends any ? (k: U) => void : never) extends ( k: infer I ) => void ? I : never; type ComparisonOperator = '=' | '>' | '>=' | '<' | '<=' | '<>'; // If T is an array, get the type of member, else fall back to never type ArrayMember = T extends (infer M)[] ? M : never; // If T is an array, get the type of member, else retain original type UnwrapArrayMember = T extends (infer M)[] ? M : T; // Wrap a type in a container, making it an object type. // This is primarily useful in circumventing special handling of union/intersection in typescript interface Boxed { _value: T; } // If T can't be assigned to TBase fallback to an alternate type TAlt type IncompatibleToAlt = T extends TBase ? T : TAlt; type ArrayIfAlready = AnyToUnknown extends any[] ? T2[] : T2; // Boxing is necessary to prevent distribution of conditional types: // https://lorefnon.tech/2019/05/02/using-boxing-to-prevent-distribution-of-conditional-types/ type PartialOrAny = Boxed extends Boxed ? {} : Boxed extends Boxed ? SafePick : any; // Retain the association of original keys with aliased keys at type level // to facilitates type-safe aliasing for object syntax type MappedAliasType = {} & { [K in keyof TAliasMapping]: TAliasMapping[K] extends keyof TBase ? TBase[TAliasMapping[K]] : any; }; // Container type for situations when we want a partial/intersection eventually // but the keys being selected or additional properties being augmented are not // all known at once and we would want to effectively build up a partial/intersection // over multiple steps. type DeferredKeySelection< // The base of selection. In intermediate stages this may be unknown. // If it remains unknown at the point of resolution, the selection will fall back to any TBase, // Union of keys to be selected // In intermediate stages this may be never. TKeys extends string, // Changes how the resolution should behave if TKeys is never. // If true, then we assume that some keys were selected, and if TKeys is never, we will fall back to any. // If false, and TKeys is never, then we select TBase in its entirety THasSelect extends true | false = false, // Mapping of aliases -> TAliasMapping extends {} = {}, // If enabled, then instead of extracting a partial, during resolution // we will pick just a single property. TSingle extends boolean = false, // Extra props which will be intersected with the result TIntersectProps extends {} = {}, // Extra props which will be unioned with the result TUnionProps = never > = { // These properties are not actually used, but exist simply because // typescript doesn't end up happy when type parameters are unused _base: TBase; _hasSelection: THasSelect; _keys: TKeys; _aliases: TAliasMapping; _single: TSingle; _intersectProps: TIntersectProps; _unionProps: TUnionProps; }; // An companion namespace for DeferredKeySelection which provides type operators // to build up participants of intersection/partial over multiple invocations // and for final resolution. // // While the comments use wordings such as replacement and addition, it is important // to keep in mind that types are always immutable and all type operators return new altered types. declare namespace DeferredKeySelection { type Any = DeferredKeySelection; // Replace the Base if already a deferred selection. // If not, create a new deferred selection with specified base. type SetBase = TSelection extends DeferredKeySelection< any, infer TKeys, infer THasSelect, infer TAliasMapping, infer TSingle, infer TIntersectProps, infer TUnionProps > ? DeferredKeySelection< TBase, TKeys, THasSelect, TAliasMapping, TSingle, TIntersectProps, TUnionProps > : DeferredKeySelection; // If TSelection is already a deferred selection, then replace the base with TBase // If unknown, create a new deferred selection with TBase as the base // Else, retain original // // For practical reasons applicable to current context, we always return arrays of // deferred selections. So, this particular operator may not be useful in generic contexts. type ReplaceBase = UnwrapArrayMember extends DeferredKeySelection.Any ? ArrayIfAlready< TSelection, DeferredKeySelection.SetBase, TBase> > : unknown extends UnwrapArrayMember ? ArrayIfAlready> : TSelection; // Type operators to substitute individual type parameters: type SetSingle< TSelection, TSingle extends boolean > = TSelection extends DeferredKeySelection< infer TBase, infer TKeys, infer THasSelect, infer TAliasMapping, any, infer TIntersectProps, infer TUnionProps > ? DeferredKeySelection< TBase, TKeys, THasSelect, TAliasMapping, TSingle, TIntersectProps, TUnionProps > : never; type AddKey< TSelection, TKey extends string > = TSelection extends DeferredKeySelection< infer TBase, infer TKeys, any, infer TAliasMapping, infer TSingle, infer TIntersectProps, infer TUnionProps > ? DeferredKeySelection< TBase, TKeys | TKey, true, TAliasMapping, TSingle, TIntersectProps, TUnionProps > : DeferredKeySelection; type AddAliases< TSelection, T extends {} > = TSelection extends DeferredKeySelection< infer TBase, infer TKeys, infer THasSelect, infer TAliasMapping, infer TSingle, infer TIntersectProps, infer TUnionProps > ? DeferredKeySelection< TBase, TKeys, THasSelect, TAliasMapping & T, TSingle, TIntersectProps, TUnionProps > : DeferredKeySelection; type AddUnionMember = TSelection extends DeferredKeySelection< infer TBase, infer TKeys, infer THasSelect, infer TAliasMapping, infer TSingle, infer TIntersectProps, infer TUnionProps > ? DeferredKeySelection< TBase, TKeys, THasSelect, TAliasMapping, TSingle, TIntersectProps, TUnionProps | T > : DeferredKeySelection; // Convenience utility to set base, keys and aliases in a single type // application type Augment< T, TBase, TKey extends string, TAliasMapping extends {} = {} > = AddAliases, TKey>, TAliasMapping>; // Core resolution logic -- Refer to docs for DeferredKeySelection for specifics type ResolveOne = TSelection extends DeferredKeySelection< infer TBase, infer TKeys, infer THasSelect, infer TAliasMapping, infer TSingle, infer TIntersectProps, infer TUnionProps > ? UnknownOrCurlyCurlyToAny< // ^ We convert final result to any if it is unknown for backward compatibility. // Historically knex typings have been liberal with returning any and changing // default return type to unknown would be a major breaking change for users. // // So we compromise on type safety here and return any. | AugmentParams< AnyToUnknown extends {} ? // ^ Conversion of any -> unknown is needed here to prevent distribution // of any over the conditional TSingle extends true ? TKeys extends keyof TBase ? TBase[TKeys] : any : AugmentParams< true extends THasSelect ? PartialOrAny : TBase, MappedAliasType > : unknown, TIntersectProps > | TUnionProps > : TSelection; type Resolve = TSelection extends DeferredKeySelection.Any ? Knex.ResolveTableType> : TSelection extends DeferredKeySelection.Any[] ? Knex.ResolveTableType>[] : TSelection extends (infer I)[] ? UnknownOrCurlyCurlyToAny>[] : UnknownOrCurlyCurlyToAny>; } type AggregationQueryResult< TResult, TIntersectProps2 extends {} > = ArrayIfAlready< TResult, UnwrapArrayMember extends DeferredKeySelection< infer TBase, infer TKeys, infer THasSelect, infer TAliasMapping, infer TSingle, infer TIntersectProps, infer TUnionProps > ? true extends THasSelect ? DeferredKeySelection< TBase, TKeys, THasSelect, TAliasMapping, TSingle, TIntersectProps & TIntersectProps2, TUnionProps > : DeferredKeySelection<{}, never, true, {}, false, TIntersectProps2> : TIntersectProps2 >; // If we have more categories of deferred selection in future, // this will combine all of them type ResolveResult = DeferredKeySelection.Resolve; // # Type-aliases for common type combinations type Callback = Function; type Client = Function; type Dict = { [k: string]: T }; type SafePick = T extends {} ? Pick : any; type TableOptions = PgTableOptions; interface PgTableOptions { only?: boolean; } interface DMLOptions { includeTriggerModifications?: boolean; } interface Knex extends Knex.QueryInterface, events.EventEmitter { ( tableName: TTable, options?: TableOptions ): Knex.QueryBuilder< Knex.TableType, DeferredKeySelection>, never>[] >; < TRecord2 extends {} = TRecord, TResult2 = DeferredKeySelection[] >( tableName?: Knex.TableDescriptor | Knex.AliasDict, options?: TableOptions ): Knex.QueryBuilder; VERSION: string; __knex__: string; raw: Knex.RawBuilder; transactionProvider( config?: Knex.TransactionConfig ): Knex.TransactionProvider; transaction(config?: Knex.TransactionConfig): Promise; transaction( transactionScope?: null, config?: Knex.TransactionConfig ): Promise; transaction( transactionScope: (trx: Knex.Transaction) => Promise | void, config?: Knex.TransactionConfig ): Promise; initialize(config?: Knex.Config): void; destroy(callback: Function): void; destroy(): Promise; batchInsert( tableName: Knex.TableDescriptor, data: TRecord2 extends Knex.CompositeTableType ? ReadonlyArray> : ReadonlyArray>, chunkSize?: number ): Knex.BatchInsertBuilder; schema: Knex.SchemaBuilder; queryBuilder< TRecord2 extends {} = TRecord, TResult2 = TResult >(): Knex.QueryBuilder; client: any; migrate: Knex.Migrator; seed: Knex.Seeder; fn: Knex.FunctionHelper; ref: Knex.RefBuilder; userParams: Record; withUserParams(params: Record): Knex; isTransaction?: boolean; } declare function knex( config: Knex.Config | string ): Knex; declare namespace knex { export { knex, knex as default, Knex }; export class QueryBuilder { static extend( methodName: string, fn: ( this: Knex.QueryBuilder, ...args: any[] ) => | Knex.QueryBuilder | Promise< | Knex.QueryBuilder | DeferredKeySelection.Resolve > ): void; } export class TableBuilder { static extend( methodName: string, fn: (this: T, ...args: any[]) => B ): void; } export class ViewBuilder { static extend( methodName: string, fn: (this: T, ...args: any[]) => B ): void; } export class SchemaBuilder { static extend( methodName: string, fn: (this: T, ...args: any[]) => B ): void; } export class ColumnBuilder { static extend( methodName: string, fn: (this: T, ...args: any[]) => B ): void; } export class KnexTimeoutError extends Error {} export const Client: typeof Knex.Client; } declare namespace Knex { // // Utility Types // type Value = | string | number | boolean | null | Date | Array | Array | Array | Array | Buffer | object | Knex.Raw; interface ValueDict extends Dict {} interface AliasDict extends Dict {} type ColumnDescriptor = | string | Knex.Raw | Knex.QueryBuilder | Dict; type InferrableColumnDescriptor = | keyof TRecord | Knex.Ref | Dict; type TableDescriptor = string | Knex.Raw | Knex.QueryBuilder; type Lookup< TRegistry extends {}, TKey extends string, TDefault = never > = TKey extends keyof TRegistry ? TRegistry[TKey] : TDefault; type MaybeRawColumn = TColumn | Raw; type MaybeRawRecord = { [K in keyof TRecord]: MaybeRawColumn; }; type DbColumn = Readonly>; type DbRecord = Readonly>>; type DbRecordArr = Readonly>>; export type CompositeTableType< TBase, TInsert = TBase, TUpdate = Partial, TUpsert = Partial > = { base: TBase; insert: TInsert; update: TUpdate; upsert: TUpsert; }; type TableNames = keyof Tables; type TableInterfaceScope = keyof CompositeTableType; type TableType = Tables[TTable]; type ResolveTableType< TCompositeTableType, TScope extends TableInterfaceScope = 'base' > = TCompositeTableType extends CompositeTableType<{}> ? TCompositeTableType[TScope] : TCompositeTableType; interface OnConflictQueryBuilder { ignore(): QueryBuilder; merge( mergeColumns?: (keyof ResolveTableType)[] ): QueryBuilder; merge( data?: Extract>, object> ): QueryBuilder; } // // QueryInterface // type ClearStatements = | 'with' | 'select' | 'columns' | 'hintComments' | 'where' | 'union' | 'using' | 'join' | 'group' | 'order' | 'having' | 'limit' | 'offset' | 'counter' | 'counters'; interface QueryInterface { select: Select; as: As; columns: Select; column: Select; comment: Comment; hintComment: HintComment; from: Table; fromRaw: Table; into: Table; table: Table; distinct: Distinct; distinctOn: DistinctOn; // Joins join: Join; joinRaw: JoinRaw; innerJoin: Join; leftJoin: Join; leftOuterJoin: Join; rightJoin: Join; rightOuterJoin: Join; outerJoin: Join; fullOuterJoin: Join; crossJoin: Join; // Json manipulation jsonExtract: JsonExtract; jsonSet: JsonSet; jsonInsert: JsonInsert; jsonRemove: JsonRemove; // Using using: Using; // Withs with: With; withMaterialized: With; withNotMaterialized: With; withRecursive: With; withRaw: WithRaw; withSchema: WithSchema; withWrapped: WithWrapped; // Wheres where: Where; andWhere: Where; orWhere: Where; whereNot: Where; andWhereNot: Where; orWhereNot: Where; whereRaw: WhereRaw; orWhereRaw: WhereRaw; andWhereRaw: WhereRaw; whereWrapped: WhereWrapped; havingWrapped: WhereWrapped; whereExists: WhereExists; orWhereExists: WhereExists; whereNotExists: WhereExists; orWhereNotExists: WhereExists; whereIn: WhereIn; orWhereIn: WhereIn; whereNotIn: WhereIn; orWhereNotIn: WhereIn; whereLike: Where; andWhereLike: Where; orWhereLike: Where; whereILike: Where; andWhereILike: Where; orWhereILike: Where; whereNull: WhereNull; orWhereNull: WhereNull; whereNotNull: WhereNull; orWhereNotNull: WhereNull; whereBetween: WhereBetween; orWhereBetween: WhereBetween; andWhereBetween: WhereBetween; whereNotBetween: WhereBetween; orWhereNotBetween: WhereBetween; andWhereNotBetween: WhereBetween; whereJsonObject: WhereJsonObject; orWhereJsonObject: WhereJsonObject; andWhereJsonObject: WhereJsonObject; whereNotJsonObject: WhereJsonObject; orWhereNotJsonObject: WhereJsonObject; andWhereNotJsonObject: WhereJsonObject; whereJsonPath: WhereJsonPath; orWhereJsonPath: WhereJsonPath; andWhereJsonPath: WhereJsonPath; whereJsonSupersetOf: WhereJsonObject; orWhereJsonSupersetOf: WhereJsonObject; andWhereJsonSupersetOf: WhereJsonObject; whereJsonNotSupersetOf: WhereJsonObject; orWhereJsonNotSupersetOf: WhereJsonObject; andWhereJsonNotSupersetOf: WhereJsonObject; whereJsonSubsetOf: WhereJsonObject; orWhereJsonSubsetOf: WhereJsonObject; andWhereJsonSubsetOf: WhereJsonObject; whereJsonNotSubsetOf: WhereJsonObject; orWhereJsonNotSubsetOf: WhereJsonObject; andWhereJsonNotSubsetOf: WhereJsonObject; // Group by groupBy: GroupBy; groupByRaw: RawQueryBuilder; // Order by orderBy: OrderBy; orderByRaw: RawQueryBuilder; // Partition by partitionBy: PartitionBy; // Unions union: Union; unionAll: Union; intersect: Intersect; except: Except; // Having having: Having; andHaving: Having; havingRaw: RawQueryBuilder; orHaving: Having; orHavingRaw: RawQueryBuilder; havingIn: HavingRange; orHavingNotBetween: HavingRange; havingNotBetween: HavingRange; orHavingBetween: HavingRange; havingBetween: HavingRange; havingNotIn: HavingRange; andHavingNotIn: HavingRange; orHavingNotIn: HavingRange; havingNull: HavingNull; havingNotNull: HavingNull; orHavingNull: HavingNull; orHavingNotNull: HavingNull; // Clear clearSelect(): QueryBuilder< TRecord, UnwrapArrayMember extends DeferredKeySelection< infer TBase, infer TKeys, true, any, any, any, any > ? DeferredKeySelection[] : TResult >; clearWhere(): QueryBuilder; clearGroup(): QueryBuilder; clearOrder(): QueryBuilder; clearHaving(): QueryBuilder; clearCounters(): QueryBuilder; clear(statement: ClearStatements): QueryBuilder; // Paging offset( offset: number, options?: boolean | Readonly<{ skipBinding?: boolean }> ): QueryBuilder; limit( limit: number, options?: string | Readonly<{ skipBinding?: boolean }> ): QueryBuilder; // Aggregation count: AsymmetricAggregation< TRecord, TResult, Lookup >; countDistinct: AsymmetricAggregation< TRecord, TResult, Lookup >; min: TypePreservingAggregation; max: TypePreservingAggregation; sum: TypePreservingAggregation; sumDistinct: TypePreservingAggregation; avg: TypePreservingAggregation; avgDistinct: TypePreservingAggregation; increment( columnName: keyof TRecord, amount?: number ): QueryBuilder; increment( columnName: string, amount?: number ): QueryBuilder; increment(columns: { [column in keyof TRecord]: number; }): QueryBuilder; decrement( columnName: keyof TRecord, amount?: number ): QueryBuilder; decrement( columnName: string, amount?: number ): QueryBuilder; decrement(columns: { [column in keyof TRecord]: number; }): QueryBuilder; // Analytics rank: AnalyticFunction; denseRank: AnalyticFunction; rowNumber: AnalyticFunction; // Others first: Select< TRecord, DeferredKeySelection.AddUnionMember, undefined> >; pluck( column: K ): QueryBuilder; pluck(column: string): QueryBuilder; insert( data: TRecord extends CompositeTableType ? | ResolveTableType | ReadonlyArray> : DbRecordArr | ReadonlyArray>, returning: '*', options?: DMLOptions ): QueryBuilder[]>; insert< TKey extends StrKey>, TResult2 = DeferredKeySelection.Augment< UnwrapArrayMember, ResolveTableType, TKey >[] >( data: TRecord extends CompositeTableType ? | ResolveTableType | ReadonlyArray> : DbRecordArr | ReadonlyArray>, returning: TKey, options?: DMLOptions ): QueryBuilder; insert< TKey extends StrKey>, TResult2 = DeferredKeySelection.Augment< UnwrapArrayMember, ResolveTableType, TKey >[] >( data: TRecord extends CompositeTableType ? | ResolveTableType | ReadonlyArray> : DbRecordArr | ReadonlyArray>, returning: readonly TKey[], options?: DMLOptions ): QueryBuilder; insert< TKey extends string, TResult2 = DeferredKeySelection.Augment< UnwrapArrayMember, TRecord, TKey >[] >( data: TRecord extends CompositeTableType ? | ResolveTableType | ReadonlyArray> : DbRecordArr | ReadonlyArray>, returning: TKey, options?: DMLOptions ): QueryBuilder; insert< TKey extends string, TResult2 = DeferredKeySelection.Augment< UnwrapArrayMember, TRecord, TKey >[] >( data: TRecord extends CompositeTableType ? | ResolveTableType | ReadonlyArray> : DbRecordArr | ReadonlyArray>, returning: readonly TKey[], options?: DMLOptions ): QueryBuilder; insert( data: TRecord extends CompositeTableType ? | ResolveTableType | ReadonlyArray> : DbRecordArr | ReadonlyArray> ): QueryBuilder; upsert( data: TRecord extends CompositeTableType ? | ResolveTableType | ReadonlyArray> : DbRecordArr | ReadonlyArray>, returning: '*', options?: DMLOptions ): QueryBuilder[]>; upsert< TKey extends StrKey>, TResult2 = DeferredKeySelection.Augment< UnwrapArrayMember, ResolveTableType, TKey >[] >( data: TRecord extends CompositeTableType ? | ResolveTableType | ReadonlyArray> : DbRecordArr | ReadonlyArray>, returning: TKey, options?: DMLOptions ): QueryBuilder; upsert< TKey extends StrKey>, TResult2 = DeferredKeySelection.Augment< UnwrapArrayMember, ResolveTableType, TKey >[] >( data: TRecord extends CompositeTableType ? | ResolveTableType | ReadonlyArray> : DbRecordArr | ReadonlyArray>, returning: readonly TKey[], options?: DMLOptions ): QueryBuilder; upsert< TKey extends string, TResult2 = DeferredKeySelection.Augment< UnwrapArrayMember, TRecord, TKey >[] >( data: TRecord extends CompositeTableType ? | ResolveTableType | ReadonlyArray> : DbRecordArr | ReadonlyArray>, returning: TKey, options?: DMLOptions ): QueryBuilder; upsert< TKey extends string, TResult2 = DeferredKeySelection.Augment< UnwrapArrayMember, TRecord, TKey >[] >( data: TRecord extends CompositeTableType ? | ResolveTableType | ReadonlyArray> : DbRecordArr | ReadonlyArray>, returning: readonly TKey[], options?: DMLOptions ): QueryBuilder; upsert( data: TRecord extends CompositeTableType ? | ResolveTableType | ReadonlyArray> : DbRecordArr | ReadonlyArray> ): QueryBuilder; modify( callback: QueryCallbackWithArgs, ...args: any[] ): QueryBuilder; update< K1 extends StrKey>, K2 extends StrKey>, TResult2 = DeferredKeySelection.Augment< UnwrapArrayMember, ResolveTableType, K2 >[] >( columnName: K1, value: DbColumn[K1]>, returning: K2, options?: DMLOptions ): QueryBuilder; update< K1 extends StrKey>, K2 extends StrKey>, TResult2 = DeferredKeySelection.Augment< UnwrapArrayMember, ResolveTableType, K2 >[] >( columnName: K1, value: DbColumn[K1]>, returning: readonly K2[], options?: DMLOptions ): QueryBuilder; update( columnName: K, value: DbColumn ): QueryBuilder; update[]>( columnName: string, value: Value, returning: string | readonly string[], options?: DMLOptions ): QueryBuilder; update( data: DbRecordArr, returning: '*', options?: DMLOptions ): QueryBuilder[]>; update< TKey extends StrKey>, TResult2 = DeferredKeySelection.Augment< UnwrapArrayMember, ResolveTableType, TKey >[] >( data: TRecord extends CompositeTableType ? ResolveTableType : DbRecordArr, returning: TKey, options?: DMLOptions ): QueryBuilder; update< TKey extends StrKey>, TResult2 = DeferredKeySelection.Augment< UnwrapArrayMember, ResolveTableType, TKey >[] >( data: TRecord extends CompositeTableType ? ResolveTableType : DbRecordArr, returning: readonly TKey[], options?: DMLOptions ): QueryBuilder; update< TKey extends string = string, TResult2 extends {}[] = DeferredKeySelection.Augment< UnwrapArrayMember, TRecord, TKey >[] >( data: TRecord extends CompositeTableType ? ResolveTableType : DbRecordArr, returning: TKey | readonly TKey[], options?: DMLOptions ): QueryBuilder; update< TKey extends string, TResult2 extends {}[] = DeferredKeySelection.Augment< UnwrapArrayMember, TRecord, TKey >[] >( data: TRecord extends CompositeTableType ? ResolveTableType : DbRecordArr, returning: readonly TKey[], options?: DMLOptions ): QueryBuilder; update( data: TRecord extends CompositeTableType ? ResolveTableType : DbRecordArr ): QueryBuilder; update( columnName: string, value: Value ): QueryBuilder; returning( column: '*', options?: DMLOptions ): QueryBuilder[]>; returning< TKey extends StrKey>, TResult2 = DeferredKeySelection.Augment< UnwrapArrayMember, ResolveTableType, TKey >[] >( column: TKey, options?: DMLOptions ): QueryBuilder; returning< TKey extends StrKey>, TResult2 = DeferredKeySelection.SetSingle< DeferredKeySelection.Augment< UnwrapArrayMember, ResolveTableType, TKey >, false >[] >( columns: readonly TKey[], options?: DMLOptions ): QueryBuilder; returning[]>( column: string | readonly (string | Raw)[] | Raw, options?: DMLOptions ): QueryBuilder; onConflict>>( column: TKey ): OnConflictQueryBuilder; onConflict>>( columns: readonly TKey[] ): OnConflictQueryBuilder; onConflict(columns: string): OnConflictQueryBuilder; onConflict(columns: string[]): OnConflictQueryBuilder; onConflict(raw: Raw): OnConflictQueryBuilder; onConflict(): OnConflictQueryBuilder; updateFrom: Table; del( returning: '*', options?: DMLOptions ): QueryBuilder[]>; del< TKey extends StrKey, TResult2 = DeferredKeySelection.Augment< UnwrapArrayMember, TRecord, TKey >[] >( returning: TKey, options?: DMLOptions ): QueryBuilder; del< TKey extends StrKey, TResult2 = DeferredKeySelection.Augment< UnwrapArrayMember, TRecord, TKey >[] >( returning: readonly TKey[], options?: DMLOptions ): QueryBuilder; del[]>( returning: string | readonly string[], options?: DMLOptions ): QueryBuilder; del(): QueryBuilder; delete( returning: '*', options?: DMLOptions ): QueryBuilder[]>; delete< TKey extends StrKey>, TResult2 = DeferredKeySelection.Augment< UnwrapArrayMember, ResolveTableType, TKey >[] >( returning: TKey, options?: DMLOptions ): QueryBuilder; delete< TKey extends StrKey, TResult2 = DeferredKeySelection.Augment< UnwrapArrayMember, TRecord, TKey >[] >( returning: readonly TKey[], options?: DMLOptions ): QueryBuilder; delete( returning: string | readonly (string | Raw)[] | Raw, options?: DMLOptions ): QueryBuilder; delete(): QueryBuilder; truncate(): QueryBuilder; } interface As { (columnName: keyof TRecord): QueryBuilder; (columnName: string): QueryBuilder; } type IntersectAliases = UnionToIntersection< IncompatibleToAlt< AliasUT extends (infer I)[] ? I extends Ref ? TMapping : I : never, Dict, {} > > & {}; // filters out `null` and `undefined` interface AliasQueryBuilder { < AliasUT extends InferrableColumnDescriptor>[], TResult2 = ArrayIfAlready< TResult, DeferredKeySelection.Augment< UnwrapArrayMember, ResolveTableType, IncompatibleToAlt, string, never>, IntersectAliases > > >( ...aliases: AliasUT ): QueryBuilder; < AliasUT extends InferrableColumnDescriptor>[], TResult2 = ArrayIfAlready< TResult, DeferredKeySelection.Augment< UnwrapArrayMember, ResolveTableType, IncompatibleToAlt, string, never>, IntersectAliases > > >( aliases: AliasUT ): QueryBuilder; < AliasUT extends (Dict | string)[], TResult2 = ArrayIfAlready< TResult, DeferredKeySelection.Augment< UnwrapArrayMember, ResolveTableType, IncompatibleToAlt, string, never>, IntersectAliases > > >( ...aliases: AliasUT ): QueryBuilder; < AliasUT extends (Dict | string)[], TResult2 = ArrayIfAlready< TResult, DeferredKeySelection.Augment< UnwrapArrayMember, TRecord, IncompatibleToAlt, string, never>, IntersectAliases > > >( aliases: AliasUT ): QueryBuilder; } interface Select extends AliasQueryBuilder, ColumnNameQueryBuilder { (): QueryBuilder; < TResult2 = ArrayIfAlready, TInnerRecord extends {} = any, TInnerResult = any >( ...subQueryBuilders: readonly QueryBuilder[] ): QueryBuilder; < TResult2 = ArrayIfAlready, TInnerRecord extends {} = any, TInnerResult = any >( subQueryBuilders: readonly QueryBuilder[] ): QueryBuilder; } interface JsonExtraction { column: string | Raw | QueryBuilder; path: string; alias?: string; singleValue?: boolean; } interface JsonExtract { ( column: string | Raw | QueryBuilder, path: string, alias?: string, singleValue?: boolean ): QueryBuilder; (column: JsonExtraction[] | any[][], singleValue?: boolean): QueryBuilder< TRecord, TResult >; } interface JsonSet { ( column: string | Raw | QueryBuilder, path: string, value: any, alias?: string ): QueryBuilder; } interface JsonInsert { ( column: string | Raw | QueryBuilder, path: string, value: any, alias?: string ): QueryBuilder; } interface JsonRemove { ( column: string | Raw | QueryBuilder, path: string, alias?: string ): QueryBuilder; } interface Comment { (comment: string): QueryBuilder; } interface HintComment { (hint: string): QueryBuilder; (hints: readonly string[]): QueryBuilder; } interface Table { < TTable extends TableNames, TRecord2 extends {} = TableType, TResult2 = DeferredKeySelection.ReplaceBase< TResult, ResolveTableType > >( tableName: TTable, options?: TableOptions ): QueryBuilder; < TRecord2 extends {} = {}, TResult2 = DeferredKeySelection.ReplaceBase >( tableName: TableDescriptor | AliasDict, options?: TableOptions ): QueryBuilder; < TRecord2 extends {} = {}, TResult2 = DeferredKeySelection.ReplaceBase >( callback: Function, options?: TableOptions ): QueryBuilder; < TRecord2 extends {} = {}, TResult2 = DeferredKeySelection.ReplaceBase >( raw: Raw, options?: TableOptions ): QueryBuilder; } interface Distinct extends ColumnNameQueryBuilder {} interface DistinctOn { ( ...columnNames: readonly ColNameUT[] ): QueryBuilder; ( columnNames: readonly ColNameUT[] ): QueryBuilder; (...columnNames: readonly string[]): QueryBuilder; (columnNames: readonly string[]): QueryBuilder; } interface JoinCallback { (this: JoinClause, join: JoinClause): void; } interface Join { < TJoinTargetRecord extends {} = any, TRecord2 extends {} = TRecord & TJoinTargetRecord, TResult2 = DeferredKeySelection.ReplaceBase >( raw: Raw ): QueryBuilder; < TTable extends TableNames, TRecord2 extends {} = ResolveTableType & ResolveTableType>, TResult2 = DeferredKeySelection.ReplaceBase >( tableName: TTable, clause: JoinCallback ): QueryBuilder; < TJoinTargetRecord extends {} = any, TRecord2 extends {} = TRecord & TJoinTargetRecord, TResult2 = DeferredKeySelection.ReplaceBase >( tableName: TableDescriptor | AliasDict | QueryCallback, clause: JoinCallback ): QueryBuilder; < TJoinTargetRecord extends {} = any, TRecord2 extends {} = TRecord & TJoinTargetRecord, TResult2 = DeferredKeySelection.ReplaceBase >( tableName: TableDescriptor | AliasDict | QueryCallback, columns: { [key: string]: string | number | boolean | Raw } ): QueryBuilder; < TJoinTargetRecord extends {} = any, TRecord2 extends {} = TRecord & TJoinTargetRecord, TResult2 = DeferredKeySelection.ReplaceBase >( tableName: TableDescriptor | AliasDict | QueryCallback, raw: Raw ): QueryBuilder; < TTable1 extends TableNames, TTable2 extends TableNames, TKey1 extends StrKey>> & StrKey, TKey2 extends StrKey>>, TRecord1 = ResolveTableType, TRecord2 extends {} = TRecord1 & ResolveTableType>, TResult2 = DeferredKeySelection.ReplaceBase >( tableName: TTable2, column1: `${TTable1}.${TKey1}`, column2: `${TTable2}.${TKey2}` ): QueryBuilder; < TTable1 extends TableNames, TTable2 extends TableNames, TKey1 extends StrKey>> & StrKey, TKey2 extends StrKey>>, TRecord1 = ResolveTableType, TRecord2 extends {} = TRecord1 & ResolveTableType>, TResult2 = DeferredKeySelection.ReplaceBase >( tableName: TTable2, column1: `${TTable2}.${TKey2}`, column2: `${TTable1}.${TKey1}` ): QueryBuilder; < TJoinTargetRecord extends {} = any, TRecord2 extends {} = TRecord & TJoinTargetRecord, TResult2 = DeferredKeySelection.ReplaceBase >( tableName: TableDescriptor | AliasDict | QueryCallback, column1: string, column2: string ): QueryBuilder; < TJoinTargetRecord extends {} = any, TRecord2 extends {} = TRecord & TJoinTargetRecord, TResult2 = DeferredKeySelection.ReplaceBase >( tableName: TableDescriptor | AliasDict | QueryCallback, column1: string, raw: Raw ): QueryBuilder; < TTable1 extends TableNames, TTable2 extends TableNames, TKey1 extends StrKey>> & StrKey, TKey2 extends StrKey>>, TRecord1 = ResolveTableType, TRecord2 extends {} = TRecord1 & ResolveTableType>, TResult2 = DeferredKeySelection.ReplaceBase >( tableName: TTable2, column1: `${TTable1}.${TKey1}`, operator: string, column2: `${TTable2}.${TKey2}` ): QueryBuilder; < TTable1 extends TableNames, TTable2 extends TableNames, TKey1 extends StrKey>> & StrKey, TKey2 extends StrKey>>, TRecord1 = ResolveTableType, TRecord2 extends {} = TRecord1 & ResolveTableType>, TResult2 = DeferredKeySelection.ReplaceBase >( tableName: TTable2, column1: `${TTable2}.${TKey2}`, operator: string, column2: `${TTable1}.${TKey1}` ): QueryBuilder; < TJoinTargetRecord extends {} = any, TRecord2 extends {} = TRecord & TJoinTargetRecord, TResult2 = DeferredKeySelection.ReplaceBase >( tableName: TableDescriptor | AliasDict | QueryCallback, column1: string, operator: string, column2: string ): QueryBuilder; } interface JoinClause { on(raw: Raw): JoinClause; on(callback: JoinCallback): JoinClause; on(columns: { [key: string]: string | Raw }): JoinClause; on(column1: string, column2: string): JoinClause; on(column1: string, raw: Raw): JoinClause; on(column1: string, operator: string, column2: string | Raw): JoinClause; andOn(raw: Raw): JoinClause; andOn(callback: JoinCallback): JoinClause; andOn(columns: { [key: string]: string | Raw }): JoinClause; andOn(column1: string, column2: string): JoinClause; andOn(column1: string, raw: Raw): JoinClause; andOn(column1: string, operator: string, column2: string | Raw): JoinClause; orOn(raw: Raw): JoinClause; orOn(callback: JoinCallback): JoinClause; orOn(columns: { [key: string]: string | Raw }): JoinClause; orOn(column1: string, column2: string): JoinClause; orOn(column1: string, raw: Raw): JoinClause; orOn(column1: string, operator: string, column2: string | Raw): JoinClause; onVal(column1: string, value: Value): JoinClause; onVal(column1: string, operator: string, value: Value): JoinClause; andOnVal(column1: string, value: Value): JoinClause; andOnVal(column1: string, operator: string, value: Value): JoinClause; orOnVal(column1: string, value: Value): JoinClause; orOnVal(column1: string, operator: string, value: Value): JoinClause; onIn(column1: string, values: readonly any[] | Raw): JoinClause; andOnIn(column1: string, values: readonly any[] | Raw): JoinClause; orOnIn(column1: string, values: readonly any[] | Raw): JoinClause; onNotIn(column1: string, values: readonly any[] | Raw): JoinClause; andOnNotIn(column1: string, values: readonly any[] | Raw): JoinClause; orOnNotIn(column1: string, values: readonly any[] | Raw): JoinClause; onNull(column1: string): JoinClause; andOnNull(column1: string): JoinClause; orOnNull(column1: string): JoinClause; onNotNull(column1: string): JoinClause; andOnNotNull(column1: string): JoinClause; orOnNotNull(column1: string): JoinClause; onExists(callback: QueryCallback): JoinClause; andOnExists(callback: QueryCallback): JoinClause; orOnExists(callback: QueryCallback): JoinClause; onNotExists(callback: QueryCallback): JoinClause; andOnNotExists(callback: QueryCallback): JoinClause; orOnNotExists(callback: QueryCallback): JoinClause; onBetween(column1: string, range: readonly [any, any]): JoinClause; andOnBetween(column1: string, range: readonly [any, any]): JoinClause; orOnBetween(column1: string, range: readonly [any, any]): JoinClause; onNotBetween(column1: string, range: readonly [any, any]): JoinClause; andOnNotBetween(column1: string, range: readonly [any, any]): JoinClause; orOnNotBetween(column1: string, range: readonly [any, any]): JoinClause; onJsonPathEquals( columnFirst: string, jsonPathFirst: string, columnSecond: string, jsonPathSecond: string ): JoinClause; orOnJsonPathEquals( columnFirst: string, jsonPathFirst: string, columnSecond: string, jsonPathSecond: string ): JoinClause; using( column: string | readonly string[] | Raw | { [key: string]: string | Raw } ): JoinClause; type(type: string): JoinClause; } interface JoinRaw { (tableName: string, binding?: Value | Value[] | ValueDict): QueryBuilder< TRecord, TResult >; } interface Using { (tables: string[]): QueryBuilder; } interface With extends WithRaw, WithWrapped {} interface WithRaw { (alias: string, raw: Raw | QueryBuilder): QueryBuilder; ( alias: string, sql: string, bindings?: readonly Value[] | Object ): QueryBuilder; ( alias: string, columnList: string[], raw: Raw | QueryBuilder ): QueryBuilder; ( alias: string, columnList: string[], sql: string, bindings?: readonly Value[] | Object ): QueryBuilder; } interface WithSchema { (schema: string): QueryBuilder; } interface WithWrapped { (alias: string, queryBuilder: QueryBuilder): QueryBuilder; ( alias: string, callback: (queryBuilder: QueryBuilder) => any ): QueryBuilder; ( alias: string, columnList: string[], queryBuilder: QueryBuilder ): QueryBuilder; ( alias: string, columnList: string[], callback: (queryBuilder: QueryBuilder) => any ): QueryBuilder; } interface Where extends WhereRaw, WhereWrapped, WhereNull { (raw: Raw): QueryBuilder; (callback: QueryCallback): QueryBuilder; (object: DbRecord>): QueryBuilder< TRecord, TResult >; (object: Readonly): QueryBuilder; >( columnName: T, value: DbColumn[T]> | null ): QueryBuilder; (columnName: string, value: Value | null): QueryBuilder; >( columnName: T, operator: ComparisonOperator, value: DbColumn[T]> | null ): QueryBuilder; (columnName: string, operator: string, value: Value | null): QueryBuilder< TRecord, TResult >; < T extends keyof ResolveTableType, TRecordInner extends {}, TResultInner >( columnName: T, operator: ComparisonOperator, value: QueryBuilder ): QueryBuilder; ( columnName: string, operator: string, value: QueryBuilder ): QueryBuilder; (left: Raw, operator: string, right: Value | null): QueryBuilder< TRecord, TResult >; ( left: Raw, operator: string, right: QueryBuilder ): QueryBuilder; } interface WhereRaw extends RawQueryBuilder { (condition: boolean): QueryBuilder; } interface WhereWrapped { (callback: QueryCallback): QueryBuilder; } interface WhereNull { (columnName: keyof TRecord): QueryBuilder; (columnName: string): QueryBuilder; } interface WhereBetween { ( columnName: K, range: readonly [DbColumn, DbColumn] ): QueryBuilder; (columnName: string, range: readonly [Value, Value]): QueryBuilder< TRecord, TResult >; } interface WhereExists { (callback: QueryCallback): QueryBuilder; ( query: QueryBuilder ): QueryBuilder; } interface WhereJsonObject { (columnName: keyof ResolveTableType, value: any): QueryBuilder< TRecord, TResult >; } interface WhereJsonPath { ( columnName: keyof ResolveTableType, jsonPath: string, operator: string, value: any ): QueryBuilder; } interface WhereIn { >( columnName: K, values: readonly DbColumn[K]>[] | QueryCallback ): QueryBuilder; ( columnName: string, values: readonly Value[] | QueryCallback ): QueryBuilder; >( columnNames: readonly K[], values: | readonly (readonly DbColumn[K]>[])[] | QueryCallback ): QueryBuilder; ( columnNames: readonly string[], values: readonly Value[][] | QueryCallback ): QueryBuilder; ( columnName: K, values: QueryBuilder ): QueryBuilder; ( columnName: string, values: Value[] | QueryBuilder ): QueryBuilder; ( columnNames: readonly K[], values: QueryBuilder ): QueryBuilder; ( columnNames: readonly string[], values: QueryBuilder ): QueryBuilder; } // Note: Attempting to unify AsymmetricAggregation & TypePreservingAggregation // by extracting out a common base interface will not work because order of overloads // is significant. interface AsymmetricAggregation< TRecord extends {} = any, TResult = unknown[], TValue = any > { < TOptions extends { as: string }, TResult2 = AggregationQueryResult< TResult, { [k in TOptions['as']]: TValue } > >( columnName: Readonly>, options: Readonly ): QueryBuilder; >>( ...columnNames: readonly (keyof ResolveTableType)[] ): QueryBuilder; < TAliases extends {} = Record, TResult2 = AggregationQueryResult< TResult, { [k in keyof TAliases]?: TValue } > >( aliases: TAliases ): QueryBuilder; >>( ...columnNames: ReadonlyArray< | Readonly> | Knex.Raw | string > ): QueryBuilder; } interface TypePreservingAggregation< TRecord extends {} = any, TResult = unknown[], TValue = any > { < TKey extends keyof ResolveTableType, TOptions extends { as: string }, TResult2 = AggregationQueryResult< TResult, { [k in TOptions['as']]: ResolveTableType[TKey]; } > >( columnName: TKey, options: Readonly ): QueryBuilder; < TKey extends keyof ResolveTableType, TResult2 = AggregationQueryResult< TResult, Dict[TKey]> > >( ...columnNames: readonly TKey[] ): QueryBuilder; < TAliases extends {} = Readonly< Record >, TResult2 = AggregationQueryResult< TResult, { // We have optional here because in most dialects aggregating by multiple keys simultaneously // causes rest of the keys to be dropped and only first to be considered [K in keyof TAliases]?: K extends keyof TRecord ? TRecord[K] : TValue; } > >( aliases: TAliases ): QueryBuilder; >>( ...columnNames: ReadonlyArray< | Readonly> | Knex.Raw | string > ): QueryBuilder; } interface AnalyticFunction { < TAlias extends string, TResult2 = AggregationQueryResult >( alias: TAlias, raw: Raw | QueryCallback ): QueryBuilder; < TAlias extends string, TKey extends keyof ResolveTableType, TResult2 = AggregationQueryResult >( alias: TAlias, orderBy: | TKey | TKey[] | { column: TKey; order?: 'asc' | 'desc'; nulls?: 'first' | 'last'; }, partitionBy?: TKey | TKey[] | { column: TKey; order?: 'asc' | 'desc' } ): QueryBuilder; } interface GroupBy extends RawQueryBuilder, ColumnNameQueryBuilder {} interface OrderBy { ( columnName: keyof TRecord | QueryBuilder, order?: 'asc' | 'desc', nulls?: 'first' | 'last' ): QueryBuilder; ( columnName: string | QueryBuilder, order?: string, nulls?: string ): QueryBuilder; ( columnDefs: Array< | keyof TRecord | Readonly<{ column: keyof TRecord | QueryBuilder; order?: 'asc' | 'desc'; nulls?: 'first' | 'last'; }> > ): QueryBuilder; ( columnDefs: Array< | string | Readonly<{ column: string | QueryBuilder; order?: string; nulls?: string; }> > ): QueryBuilder; } interface PartitionBy extends OrderBy {} interface Intersect { ( callback: MaybeArray | Raw>, wrap?: boolean ): QueryBuilder; ( ...callbacks: readonly (QueryCallback | Raw | QueryBuilder)[] ): QueryBuilder; } interface Except extends Intersect {} interface Union extends Intersect {} interface Having extends WhereWrapped { ( column: K, operator: ComparisonOperator, value: DbColumn ): QueryBuilder; ( column: string | Raw, operator: string, value: Value | QueryBuilder | null ): QueryBuilder; (raw: Raw): QueryBuilder; } interface HavingRange { ( columnName: K, values: readonly DbColumn[] ): QueryBuilder; (columnName: string, values: readonly Value[]): QueryBuilder< TRecord, TResult >; } interface HavingNull { (columnName: keyof TRecord): QueryBuilder; (columnName: string): QueryBuilder; } // commons interface ColumnNameQueryBuilder< TRecord extends {} = any, TResult = unknown[] > { // When all columns are known to be keys of original record, // we can extend our selection by these columns (columnName: '*'): QueryBuilder< TRecord, ArrayIfAlready> >; < ColNameUT extends keyof ResolveTableType, TResult2 = DeferredKeySelection.Augment< UnwrapArrayMember, ResolveTableType, ColNameUT & string >[] >( ...columnNames: readonly ColNameUT[] ): QueryBuilder; < ColNameUT extends keyof ResolveTableType, TResult2 = DeferredKeySelection.Augment< UnwrapArrayMember, ResolveTableType, ColNameUT & string >[] >( columnNames: readonly ColNameUT[] ): QueryBuilder; // For non-inferrable column selection, we will allow consumer to // specify result type and if not widen the result to entire record type with any omissions permitted < TResult2 = DeferredKeySelection.Augment< UnwrapArrayMember, SafePartial, keyof TRecord & string >[] >( ...columnNames: readonly ColumnDescriptor[] ): QueryBuilder; < TResult2 = DeferredKeySelection.Augment< UnwrapArrayMember, SafePartial, keyof TRecord & string >[] >( columnNames: readonly ColumnDescriptor[] ): QueryBuilder; } type RawBinding = Value | QueryBuilder; interface RawQueryBuilder { ( sql: string, bindings?: readonly RawBinding[] | ValueDict | RawBinding ): QueryBuilder; (raw: Raw): QueryBuilder; } // Raw interface Raw extends events.EventEmitter, ChainableInterface> { timeout(ms: number, options?: { cancel?: boolean }): Raw; wrap(before: string, after: string): Raw; toSQL(): Sql; queryContext(context: any): Raw; queryContext(): any; } interface RawBuilder { (value: Value): Raw; (sql: string, binding: RawBinding): Raw; ( sql: string, bindings: readonly RawBinding[] | ValueDict ): Raw; } const RefMemberTag: unique symbol; interface Ref extends Raw { // TypeScript can behave weirdly if type parameters are not // actually used in the members of type. // // See: https://github.com/knex/knex/issues/3932 // // We simply need to propagate the type context so that we can extract // them later, but we just add a "phantom" property so that typescript // doesn't think that these parameters are unused // // Because unique symbol is used here, there is no way to actually // access this at runtime [RefMemberTag]: { src: TSrc; mapping: TMapping; }; withSchema(schema: string): this; as( alias: TAlias ): Ref; } interface RefBuilder { (src: TSrc): Ref; } interface BatchInsertBuilder extends Promise> { transacting(trx: Transaction): this; // see returning methods from QueryInterface returning( column: '*' ): BatchInsertBuilder[]>; returning< TKey extends StrKey>, TResult2 = DeferredKeySelection.Augment< UnwrapArrayMember, ResolveTableType, TKey >[] >( column: TKey ): BatchInsertBuilder; returning< TKey extends StrKey>, TResult2 = DeferredKeySelection.SetSingle< DeferredKeySelection.Augment< UnwrapArrayMember, ResolveTableType, TKey >, false >[] >( columns: readonly TKey[] ): BatchInsertBuilder; // if data with specific type passed, exclude this method returning[]>( column: unknown extends TRecord ? string | readonly (string | Raw)[] | Raw : never ): BatchInsertBuilder; } // // QueryBuilder // type QueryCallback = ( this: QueryBuilder, builder: QueryBuilder ) => void; type QueryCallbackWithArgs = ( this: QueryBuilder, builder: QueryBuilder, ...args: any[] ) => void; interface QueryBuilder extends QueryInterface, ChainableInterface> { client: Client; or: QueryBuilder; not: QueryBuilder; and: QueryBuilder; // TODO: Promise? columnInfo( column: keyof DeferredKeySelection.Resolve ): Promise; columnInfo(): Promise< Record, ColumnInfo> >; forUpdate(...tableNames: string[]): QueryBuilder; forUpdate(tableNames: readonly string[]): QueryBuilder; forShare(...tableNames: string[]): QueryBuilder; forShare(tableNames: readonly string[]): QueryBuilder; forNoKeyUpdate(...tableNames: string[]): QueryBuilder; forNoKeyUpdate( tableNames: readonly string[] ): QueryBuilder; forKeyShare(...tableNames: string[]): QueryBuilder; forKeyShare(tableNames: readonly string[]): QueryBuilder; skipLocked(): QueryBuilder; noWait(): QueryBuilder; toSQL(): Sql; on(event: string, callback: Function): QueryBuilder; queryContext(context: any): QueryBuilder; queryContext(): any; clone(): QueryBuilder; timeout( ms: number, options?: { cancel?: boolean } ): QueryBuilder; } interface Sql { method: string; options: any; bindings: readonly Value[]; sql: string; toNative(): SqlNative; } interface SqlNative { bindings: readonly Value[]; sql: string; } // // Chainable interface // type ExposedPromiseKeys = 'then' | 'catch' | 'finally'; interface StringTagSupport { readonly [Symbol.toStringTag]: string; } interface ChainableInterface extends Pick, keyof Promise & ExposedPromiseKeys>, StringTagSupport { generateDdlCommands(): Promise<{ pre: string[]; sql: string[]; check: string | null; post: string[]; }>; toQuery(): string; options(options: Readonly<{ [key: string]: any }>): this; connection(connection: any): this; debug(enabled: boolean): this; transacting(trx: Transaction): this; stream(handler: (readable: stream.PassThrough) => any): Promise; stream( options: Readonly<{ [key: string]: any }>, handler: (readable: stream.PassThrough) => any ): Promise; stream( options?: Readonly<{ [key: string]: any }> ): stream.PassThrough & AsyncIterable>; pipe( writable: T, options?: Readonly<{ [key: string]: any }> ): stream.PassThrough; asCallback(callback: Function): Promise; } // Not all of these are possible for all drivers, notably, sqlite doesn't support any of these type IsolationLevels = | 'read uncommitted' | 'read committed' | 'snapshot' | 'repeatable read' | 'serializable'; interface TransactionConfig { isolationLevel?: IsolationLevels; userParams?: Record; doNotRejectOnRollback?: boolean; connection?: any; readOnly?: boolean; } interface Transaction extends Knex { executionPromise: Promise; parentTransaction?: Transaction; isCompleted: () => boolean; query( conn: any, sql: any, status: any, value: any ): QueryBuilder; savepoint(transactionScope: (trx: Transaction) => any): Promise; commit(value?: any): QueryBuilder; rollback(error?: any): QueryBuilder; } type TransactionProvider = () => Promise; // // Schema builder // interface SchemaBuilder extends ChainableInterface { // Views createView( viewName: string, callback: (viewBuilder: ViewBuilder) => any ): SchemaBuilder; createViewOrReplace( viewName: string, callback: (viewBuilder: ViewBuilder) => any ): SchemaBuilder; createMaterializedView( viewName: string, callback: (viewBuilder: ViewBuilder) => any ): SchemaBuilder; refreshMaterializedView( viewName: string, concurrently?: boolean ): SchemaBuilder; dropView(viewName: string): SchemaBuilder; dropViewIfExists(viewName: string): SchemaBuilder; dropMaterializedView(viewName: string): SchemaBuilder; dropMaterializedViewIfExists(viewName: string): SchemaBuilder; renameView(oldViewName: string, newViewName: string): SchemaBuilder; view( viewName: string, callback: (viewBuilder: AlterViewBuilder) => any ): SchemaBuilder; alterView( viewName: string, callback: (tableBuilder: AlterViewBuilder) => any ): SchemaBuilder; // Tables createTable( tableName: string, callback: (tableBuilder: CreateTableBuilder) => any ): SchemaBuilder; createTableIfNotExists( tableName: string, callback: (tableBuilder: CreateTableBuilder) => any ): SchemaBuilder; createTableLike( tableName: string, tableNameLike: string, callback?: (tableBuilder: CreateTableBuilder) => any ): SchemaBuilder; alterTable( tableName: string, callback: (tableBuilder: CreateTableBuilder) => any ): SchemaBuilder; renameTable(oldTableName: string, newTableName: string): Promise; dropTable(tableName: string): SchemaBuilder; hasTable(tableName: string): Promise; table( tableName: string, callback: (tableBuilder: AlterTableBuilder) => any ): SchemaBuilder; dropTableIfExists(tableName: string): SchemaBuilder; // Schema createSchema(schemaName: string): SchemaBuilder; createSchemaIfNotExists(schemaName: string): SchemaBuilder; dropSchema(schemaName: string, cascade?: boolean): SchemaBuilder; dropSchemaIfExists(schemaName: string, cascade?: boolean): SchemaBuilder; withSchema(schemaName: string): SchemaBuilder; // Others hasColumn(tableName: string, columnName: string): Promise; raw(statement: string): SchemaBuilder; queryContext(context: any): SchemaBuilder; toString(): string; toSQL(): Sql[]; } interface TableBuilder { increments( columnName?: string, options?: { primaryKey?: boolean } ): ColumnBuilder; bigIncrements( columnName?: string, options?: { primaryKey?: boolean } ): ColumnBuilder; dropColumn(columnName: string): TableBuilder; dropColumns(...columnNames: string[]): TableBuilder; renameColumn(from: string, to: string): TableBuilder; integer(columnName: string, length?: number): ColumnBuilder; tinyint(columnName: string, length?: number): ColumnBuilder; smallint(columnName: string): ColumnBuilder; mediumint(columnName: string): ColumnBuilder; bigint(columnName: string): ColumnBuilder; bigInteger(columnName: string): ColumnBuilder; text(columnName: string, textType?: string): ColumnBuilder; string(columnName: string, length?: number): ColumnBuilder; float( columnName: string, precision?: number, scale?: number ): ColumnBuilder; double( columnName: string, precision?: number, scale?: number ): ColumnBuilder; decimal( columnName: string, precision?: number | null, scale?: number ): ColumnBuilder; boolean(columnName: string): ColumnBuilder; date(columnName: string): ColumnBuilder; dateTime( columnName: string, options?: Readonly<{ useTz?: boolean; precision?: number }> ): ColumnBuilder; datetime( columnName: string, options?: Readonly<{ useTz?: boolean; precision?: number }> ): ColumnBuilder; time(columnName: string): ColumnBuilder; timestamp( columnName: string, options?: Readonly<{ useTz?: boolean; precision?: number }> ): ColumnBuilder; /** @deprecated */ timestamp( columnName: string, withoutTz?: boolean, precision?: number ): ColumnBuilder; timestamps( useTimestamps?: boolean, defaultToNow?: boolean, useCamelCase?: boolean ): ColumnBuilder; timestamps( options?: Readonly<{ useTimestamps?: boolean; defaultToNow?: boolean; useCamelCase?: boolean; }> ): void; geometry(columnName: string): ColumnBuilder; geography(columnName: string): ColumnBuilder; point(columnName: string): ColumnBuilder; binary(columnName: string, length?: number): ColumnBuilder; enum( columnName: string, values: readonly Value[] | null, options?: EnumOptions ): ColumnBuilder; enu( columnName: string, values: readonly Value[] | null, options?: EnumOptions ): ColumnBuilder; json(columnName: string): ColumnBuilder; jsonb(columnName: string): ColumnBuilder; uuid( columnName: string, options?: Readonly<{ useBinaryUuid?: boolean; primaryKey?: boolean }> ): ColumnBuilder; comment(val: string): void; specificType(columnName: string, type: string): ColumnBuilder; primary( columnNames: readonly string[], options?: Readonly<{ constraintName?: string; deferrable?: deferrableType; }> ): TableBuilder; /** @deprecated */ primary( columnNames: readonly string[], constraintName?: string ): TableBuilder; index( columnNames: string | readonly (string | Raw)[], indexName?: string, indexType?: string ): TableBuilder; index( columnNames: string | readonly (string | Raw)[], indexName?: string, options?: Readonly<{ indexType?: string; storageEngineIndexType?: storageEngineIndexType; predicate?: QueryBuilder; }> ): TableBuilder; setNullable(column: string): TableBuilder; dropNullable(column: string): TableBuilder; unique( columnNames: string | readonly (string | Raw)[], options?: Readonly<{ indexName?: string; storageEngineIndexType?: string; deferrable?: deferrableType; useConstraint?: boolean; predicate?: QueryBuilder; }> ): TableBuilder; /** @deprecated */ unique( columnNames: string | readonly (string | Raw)[], indexName?: string ): TableBuilder; foreign(column: string, foreignKeyName?: string): ForeignConstraintBuilder; foreign( columns: readonly string[], foreignKeyName?: string ): MultikeyForeignConstraintBuilder; check( checkPredicate: string, bindings?: Record, constraintName?: string ): TableBuilder; dropForeign( columnNames: string | readonly string[], foreignKeyName?: string ): TableBuilder; dropUnique( columnNames: readonly (string | Raw)[], indexName?: string ): TableBuilder; dropPrimary(constraintName?: string): TableBuilder; dropIndex( columnNames: string | readonly (string | Raw)[], indexName?: string ): TableBuilder; dropTimestamps(useCamelCase?: boolean): TableBuilder; dropChecks(checkConstraintNames: string | string[]): TableBuilder; queryContext(context: any): TableBuilder; } interface ViewBuilder { columns(columns: any): ViewBuilder; as(selectQuery: QueryBuilder): ViewBuilder; checkOption(): Promise; localCheckOption(): Promise; cascadedCheckOption(): Promise; queryContext(context: any): ViewBuilder; } interface CreateTableBuilder extends TableBuilder { engine(val: string): CreateTableBuilder; charset(val: string): CreateTableBuilder; collate(val: string): CreateTableBuilder; inherits(val: string): CreateTableBuilder; } interface AlterTableBuilder extends TableBuilder {} interface AlterColumnView extends ViewBuilder { rename(newName: string): AlterColumnView; defaultTo(defaultValue: string): AlterColumnView; } interface AlterViewBuilder extends ViewBuilder { column(column: string): AlterColumnView; } type deferrableType = 'not deferrable' | 'immediate' | 'deferred'; type storageEngineIndexType = 'hash' | 'btree'; type lengthOperator = '>' | '<' | '<=' | '>=' | '!=' | '='; interface ColumnBuilder { index(indexName?: string): ColumnBuilder; primary( options?: Readonly<{ constraintName?: string; deferrable?: deferrableType; }> ): ColumnBuilder; /** @deprecated */ primary(constraintName?: string): ColumnBuilder; unique( options?: Readonly<{ indexName?: string; deferrable?: deferrableType }> ): ColumnBuilder; /** @deprecated */ unique(indexName?: string): ColumnBuilder; references(columnName: string): ReferencingColumnBuilder; defaultTo(value: Value | null, options?: DefaultToOptions): ColumnBuilder; unsigned(): ColumnBuilder; notNullable(): ColumnBuilder; nullable(): ColumnBuilder; comment(value: string): ColumnBuilder; alter( options?: Readonly<{ alterNullable?: boolean; alterType?: boolean }> ): ColumnBuilder; queryContext(context: any): ColumnBuilder; after(columnName: string): ColumnBuilder; first(): ColumnBuilder; checkPositive(constraintName?: string): ColumnBuilder; checkNegative(constraintName?: string): ColumnBuilder; checkIn(values: string[], constraintName?: string): ColumnBuilder; checkNotIn(values: string[], constraintName?: string): ColumnBuilder; checkBetween( values: any[] | any[][], constraintName?: string ): ColumnBuilder; checkLength( operator: lengthOperator, length: number, constraintName?: string ): ColumnBuilder; checkRegex(regex: string, constraintName?: string): ColumnBuilder; collate(collation: string): ColumnBuilder; } interface ForeignConstraintBuilder { references(columnName: string): ReferencingColumnBuilder; } interface MultikeyForeignConstraintBuilder { references(columnNames: readonly string[]): ReferencingColumnBuilder; } interface PostgreSqlColumnBuilder extends ColumnBuilder { index( indexName?: string, options?: Readonly<{ indexType?: string; predicate?: QueryBuilder }> ): ColumnBuilder; index(indexName?: string, indexType?: string): ColumnBuilder; } interface SqlLiteColumnBuilder extends ColumnBuilder { index( indexName?: string, options?: Readonly<{ predicate?: QueryBuilder }> ): ColumnBuilder; } interface MsSqlColumnBuilder extends ColumnBuilder { index( indexName?: string, options?: Readonly<{ predicate?: QueryBuilder }> ): ColumnBuilder; } interface MySqlColumnBuilder extends ColumnBuilder { index( indexName?: string, options?: Readonly<{ indexType?: string; storageEngineIndexType?: storageEngineIndexType; }> ): ColumnBuilder; } // patched ColumnBuilder methods to return ReferencingColumnBuilder with new methods // relies on ColumnBuilder returning only ColumnBuilder type ReferencingColumnBuilder = { [K in keyof ColumnBuilder]: ( ...args: Parameters ) => ReferencingColumnBuilder; } & { inTable(tableName: string): ReferencingColumnBuilder; deferrable(type: deferrableType): ReferencingColumnBuilder; withKeyName(keyName: string): ReferencingColumnBuilder; onDelete(command: string): ReferencingColumnBuilder; onUpdate(command: string): ReferencingColumnBuilder; }; interface AlterColumnBuilder extends ColumnBuilder {} interface MySqlAlterColumnBuilder extends AlterColumnBuilder { first(): AlterColumnBuilder; after(columnName: string): AlterColumnBuilder; } // // Configurations // interface ColumnInfo { defaultValue: Value; type: string; maxLength: number; nullable: boolean; } interface Config { debug?: boolean; client?: string | typeof Client; dialect?: string; jsonbSupport?: boolean; version?: string; connection?: string | StaticConnectionConfig | ConnectionConfigProvider; pool?: PoolConfig; migrations?: MigratorConfig; postProcessResponse?: (result: any, queryContext: any) => any; wrapIdentifier?: ( value: string, origImpl: (value: string) => string, queryContext: any ) => string; seeds?: SeederConfig; acquireConnectionTimeout?: number; useNullAsDefault?: boolean; searchPath?: string | readonly string[]; asyncStackTraces?: boolean; log?: Logger; compileSqlOnError?: boolean; fetchAsString?: string[]; } type StaticConnectionConfig = | ConnectionConfig | MariaSqlConnectionConfig | MySqlConnectionConfig | MySql2ConnectionConfig | MsSqlConnectionConfig | OracleDbConnectionConfig | PgConnectionConfig | RedshiftConnectionConfig | Sqlite3ConnectionConfig | BetterSqlite3ConnectionConfig | SocketConnectionConfig; type ConnectionConfigProvider = | SyncConnectionConfigProvider | AsyncConnectionConfigProvider; type SyncConnectionConfigProvider = () => StaticConnectionConfig; type AsyncConnectionConfigProvider = () => Promise; interface ConnectionConfig { host: string; user: string; password: string; database: string; domain?: string; instanceName?: string; debug?: boolean; requestTimeout?: number; } type MsSqlAuthenticationTypeOptions = | 'default' | 'ntlm' | 'azure-active-directory-password' | 'azure-active-directory-access-token' | 'azure-active-directory-msi-vm' | 'azure-active-directory-msi-app-service' | 'azure-active-directory-service-principal-secret'; interface MsSqlDefaultAuthenticationConfig extends MsSqlConnectionConfigBase { type?: 'default' | never; } interface MsSqlAzureActiveDirectoryMsiAppServiceAuthenticationConfig extends MsSqlConnectionConfigBase { type: 'azure-active-directory-msi-app-service'; /** * If you user want to connect to an Azure app service using a specific client account * they need to provide `clientId` asscoiate to their created idnetity. * * This is optional for retrieve token from azure web app service */ clientId?: string; /** * A msi app service environment need to provide `msiEndpoint` for retriving the accesstoken. */ msiEndpoint?: string; /** * A msi app service environment need to provide `msiSecret` for retriving the accesstoken. */ msiSecret?: string; } interface MsSqlAzureActiveDirectoryMsiVmAuthenticationConfig extends MsSqlConnectionConfigBase { type: 'azure-active-directory-msi-vm'; /** * If you user want to connect to an Azure app service using a specific client account * they need to provide `clientId` asscoiate to their created idnetity. * * This is optional for retrieve token from azure web app service */ clientId?: string; /** * A user need to provide `msiEndpoint` for retriving the accesstoken. */ msiEndpoint?: string; } interface MsSqlAzureActiveDirectoryAccessTokenAuthenticationConfig extends MsSqlConnectionConfigBase { type: 'azure-active-directory-access-token'; /** * A user-provided access token */ token: string; } interface MsSqlAzureActiveDirectoryPasswordAuthenticationConfig extends MsSqlConnectionConfigBase { type: 'azure-active-directory-password'; /** * Optional parameter for specific Azure tenant ID */ domain: string; userName: string; password: string; } interface MsSqlAzureActiveDirectoryServicePrincipalSecretConfig extends MsSqlConnectionConfigBase { type: 'azure-active-directory-service-principal-secret'; /** * Application (`client`) ID from your registered Azure application */ clientId: string; /** * The created `client secret` for this registered Azure application */ clientSecret: string; /** * Directory (`tenant`) ID from your registered Azure application */ tenantId: string; } interface MsSqlNtlmAuthenticationConfig extends MsSqlConnectionConfigBase { type: 'ntlm'; /** * Once you set domain for ntlm authentication type, driver will connect to SQL Server using domain login. * * This is necessary for forming a connection using ntlm type */ domain: string; userName: string; password: string; } type MsSqlConnectionConfig = | MsSqlDefaultAuthenticationConfig | MsSqlNtlmAuthenticationConfig | MsSqlAzureActiveDirectoryAccessTokenAuthenticationConfig | MsSqlAzureActiveDirectoryMsiAppServiceAuthenticationConfig | MsSqlAzureActiveDirectoryMsiVmAuthenticationConfig | MsSqlAzureActiveDirectoryPasswordAuthenticationConfig | MsSqlAzureActiveDirectoryServicePrincipalSecretConfig; // Config object for tedious: see http://tediousjs.github.io/tedious/api-connection.html interface MsSqlConnectionConfigBase { type?: MsSqlAuthenticationTypeOptions; driver?: string; userName?: string; // equivalent to knex "user" password?: string; server: string; // equivalent to knex "host" port?: number; domain?: string; database: string; connectionTimeout?: number; requestTimeout?: number; stream?: boolean; parseJSON?: boolean; expirationChecker?(): boolean; options?: Readonly<{ encrypt?: boolean; instanceName?: string; useUTC?: boolean; tdsVersion?: string; appName?: string; abortTransactionOnError?: boolean; trustedConnection?: boolean; enableArithAbort?: boolean; isolationLevel?: | 'READ_UNCOMMITTED' | 'READ_COMMITTED' | 'REPEATABLE_READ' | 'SERIALIZABLE' | 'SNAPSHOT'; maxRetriesOnTransientErrors?: number; multiSubnetFailover?: boolean; packetSize?: number; trustServerCertificate?: boolean; mapBinding?: (value: any) => { value: any; type: any } | undefined; }>; pool?: Readonly<{ min?: number; max?: number; idleTimeoutMillis?: number; maxWaitingClients?: number; testOnBorrow?: boolean; acquireTimeoutMillis?: number; fifo?: boolean; priorityRange?: number; autostart?: boolean; evictionRunIntervalMillis?: number; numTestsPerRun?: number; softIdleTimeoutMillis?: number; Promise?: any; }>; } // Config object for mariasql: https://github.com/mscdex/node-mariasql#client-methods interface MariaSqlConnectionConfig { user?: string; password?: string; host?: string; port?: number; unixSocket?: string; protocol?: string; db?: string; keepQueries?: boolean; multiStatements?: boolean; connTimeout?: number; pingInterval?: number; secureAuth?: boolean; compress?: boolean; ssl?: boolean | MariaSslConfiguration; local_infile?: boolean; read_default_file?: string; read_default_group?: string; charset?: string; streamHWM?: number; expirationChecker?(): boolean; } interface MariaSslConfiguration { key?: string; cert?: string; ca?: string; capath?: string; cipher?: string; rejectUnauthorized?: boolean; expirationChecker?(): boolean; } // Config object for mysql: https://github.com/mysqljs/mysql#connection-options interface MySqlConnectionConfig { host?: string; port?: number; localAddress?: string; socketPath?: string; user?: string; password?: string; database?: string; charset?: string; timezone?: string; connectTimeout?: number; stringifyObjects?: boolean; insecureAuth?: boolean; typeCast?: any; queryFormat?: (query: string, values: any) => string; supportBigNumbers?: boolean; bigNumberStrings?: boolean; dateStrings?: boolean; debug?: boolean; trace?: boolean; multipleStatements?: boolean; flags?: string; ssl?: string | MariaSslConfiguration; decimalNumbers?: boolean; expirationChecker?(): boolean; } // Config object for mysql2: https://github.com/sidorares/node-mysql2/blob/master/lib/connection_config.js // Some options for connection pooling and MySQL server API are excluded. interface MySql2ConnectionConfig extends MySqlConnectionConfig { authPlugins?: { [pluginName: string]: (pluginMetadata: any) => (pluginData: any) => any; }; authSwitchHandler?: (data: any, callback: () => void) => any; charsetNumber?: number; compress?: boolean; connectAttributes?: { [attrNames: string]: any }; enableKeepAlive?: boolean; keepAliveInitialDelay?: number; maxPreparedStatements?: number; namedPlaceholders?: boolean; nestTables?: boolean | string; passwordSha1?: string; rowsAsArray?: boolean; stream?: boolean | ((opts: any) => Stream) | Stream; uri?: string; } interface OracleDbConnectionConfig { host: string; user: string; password?: string; database?: string; domain?: string; instanceName?: string; debug?: boolean; requestTimeout?: number; connectString?: string; expirationChecker?(): boolean; } // Config object for pg: https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/pg/index.d.ts interface PgConnectionConfig { user?: string; database?: string; password?: string | (() => string | Promise); port?: number; host?: string; connectionString?: string; keepAlive?: boolean; stream?: () => stream.Duplex | stream.Duplex | undefined; statement_timeout?: false | number; parseInputDatesAsUTC?: boolean; ssl?: boolean | ConnectionOptions; query_timeout?: number; keepAliveInitialDelayMillis?: number; idle_in_transaction_session_timeout?: number; application_name?: string; connectionTimeoutMillis?: number; types?: PgCustomTypesConfig; options?: string; expirationChecker?(): boolean; } type PgGetTypeParser = (oid: number, format: string) => any; interface PgCustomTypesConfig { getTypeParser: PgGetTypeParser; } type RedshiftConnectionConfig = PgConnectionConfig; /** Used with SQLite3 adapter */ interface Sqlite3ConnectionConfig { filename: string; flags?: string[]; debug?: boolean; expirationChecker?(): boolean; } /** Used with `better-sqlite3` adapter */ interface BetterSqlite3ConnectionConfig { filename: string; options?: { nativeBinding?: string; readonly?: boolean; }; } interface SocketConnectionConfig { socketPath: string; user: string; password: string; database: string; debug?: boolean; expirationChecker?(): boolean; } interface PoolConfig { name?: string; afterCreate?: Function; min?: number; max?: number; refreshIdle?: boolean; idleTimeoutMillis?: number; reapIntervalMillis?: number; returnToHead?: boolean; priorityRange?: number; log?: (message: string, logLevel: string) => void; // tarn configs propagateCreateError?: boolean; createRetryIntervalMillis?: number; createTimeoutMillis?: number; destroyTimeoutMillis?: number; acquireTimeoutMillis?: number; } type LogFn = (message: any) => void; interface Logger { warn?: LogFn; error?: LogFn; debug?: LogFn; inspectionDepth?: number; enableColors?: boolean; deprecate?: (method: string, alternative: string) => void; } interface Migration { up: (knex: Knex) => PromiseLike; down?: (knex: Knex) => PromiseLike; } interface MigrationSource { getMigrations(loadExtensions: readonly string[]): Promise; getMigrationName(migration: TMigrationSpec): string; getMigration(migration: TMigrationSpec): Promise; } interface MigratorConfig { database?: string; directory?: string | readonly string[]; extension?: string; stub?: string; tableName?: string; schemaName?: string; disableTransactions?: boolean; disableMigrationsListValidation?: boolean; sortDirsSeparately?: boolean; loadExtensions?: readonly string[]; migrationSource?: MigrationSource; name?: string; } interface Migrator { make(name: string, config?: MigratorConfig): Promise; latest(config?: MigratorConfig): Promise; rollback(config?: MigratorConfig, all?: boolean): Promise; status(config?: MigratorConfig): Promise; currentVersion(config?: MigratorConfig): Promise; list(config?: MigratorConfig): Promise; up(config?: MigratorConfig): Promise; down(config?: MigratorConfig): Promise; forceFreeMigrationsLock(config?: MigratorConfig): Promise; } interface Seed { seed: (knex: Knex) => PromiseLike; } interface SeedSource { getSeeds(config: SeederConfig): Promise; getSeed(seed: TSeedSpec): Promise; } interface SeederConfig { extension?: string; directory?: string | readonly string[]; loadExtensions?: readonly string[]; specific?: string; timestampFilenamePrefix?: boolean; recursive?: boolean; sortDirsSeparately?: boolean; stub?: string; variables?: V; seedSource?: SeedSource; } class Seeder { constructor(knex: Knex); setConfig(config: SeederConfig): SeederConfig; run(config?: SeederConfig): Promise<[string[]]>; make(name: string, config?: SeederConfig): Promise; } interface FunctionHelper { now(precision?: number): Raw; uuid(): Raw; uuidToBin(uuid: string, ordered?: boolean): Buffer; binToUuid(bin: Buffer, ordered?: boolean): string; } interface EnumOptions { useNative: boolean; existingType?: boolean; schemaName?: string; enumName: string; } interface DefaultToOptions { // only supported by mssql driver constraintName?: string; } class Client extends events.EventEmitter { constructor(config: Config); config: Config; dialect: string; driverName: string; connectionSettings: object; acquireRawConnection(): Promise; destroyRawConnection(connection: any): Promise; validateConnection(connection: any): Promise; logger: Logger; version?: string; connectionConfigProvider: any; connectionConfigExpirationChecker: null | (() => boolean); valueForUndefined: any; formatter(builder: any): any; queryBuilder(): QueryBuilder; queryCompiler(builder: any): any; schemaBuilder(): SchemaBuilder; schemaCompiler(builder: SchemaBuilder): any; tableBuilder( type: any, tableName: any, tableNameLike: any, fn: any ): TableBuilder; tableCompiler(tableBuilder: any): any; columnBuilder(tableBuilder: any, type: any, args: any): ColumnBuilder; columnCompiler(tableBuilder: any, columnBuilder: any): any; runner(builder: any): any; transaction(container: any, config: any, outerTx: any): Transaction; raw(...args: any[]): any; ref(...args: any[]): Ref; query(connection: any, obj: any): any; stream(connection: any, obj: any, stream: any, options: any): any; prepBindings(bindings: any): any; positionBindings(sql: any): any; postProcessResponse(resp: any, queryContext: any): any; wrapIdentifier(value: any, queryContext: any): any; customWrapIdentifier(value: any, origImpl: any, queryContext: any): any; wrapIdentifierImpl(value: any): string; initializeDriver(): void; driver: any; poolDefaults(): { min: number; max: number; propagateCreateError: boolean; }; getPoolSettings(poolConfig: any): any; initializePool(config?: {}): void; pool: tarn.Pool | undefined; acquireConnection(): any; releaseConnection(connection: any): any; destroy(callback: any): any; database(): any; canCancelQuery: boolean; assertCanCancelQuery(): void; cancelQuery(): void; } } export = knex;