From 20178e9c55f922235bf9297330cd6f19e318a7af Mon Sep 17 00:00:00 2001 From: "Matt R. Wilson" Date: Thu, 14 Mar 2019 13:41:52 -0600 Subject: [PATCH 1/2] Remove @types/knex. Self bundles types since 0.16.0 --- notNeededPackages.json | 6 + types/knex/index.d.ts | 732 ----------------------- types/knex/knex-tests.ts | 1223 -------------------------------------- types/knex/tsconfig.json | 24 - types/knex/tslint.json | 7 - 5 files changed, 6 insertions(+), 1986 deletions(-) delete mode 100644 types/knex/index.d.ts delete mode 100644 types/knex/knex-tests.ts delete mode 100644 types/knex/tsconfig.json delete mode 100644 types/knex/tslint.json diff --git a/notNeededPackages.json b/notNeededPackages.json index 812d1f9f1b..2030aa189f 100644 --- a/notNeededPackages.json +++ b/notNeededPackages.json @@ -1032,6 +1032,12 @@ "sourceRepoURL": "https://github.com/keycloak/keycloak", "asOfVersion": "3.4.1" }, + { + "libraryName": "knex", + "typingsPackageName": "knex", + "sourceRepoURL": "https://github.com/tgriesser/knex", + "asOfVersion": "0.16.1" + }, { "libraryName": "knockout-paging", "typingsPackageName": "knockout-paging", diff --git a/types/knex/index.d.ts b/types/knex/index.d.ts deleted file mode 100644 index 7888559827..0000000000 --- a/types/knex/index.d.ts +++ /dev/null @@ -1,732 +0,0 @@ -// Type definitions for Knex.js 0.15 -// Project: https://github.com/tgriesser/knex, https://knexjs.org -// Definitions by: Qubo -// Pablo Rodríguez -// Matt R. Wilson -// Satana Charuwichitratana -// Shrey Jain -// Joel Shepherd -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.8 - -/// - -import events = require("events"); -import stream = require ("stream"); -import Bluebird = require("bluebird"); - -type Callback = (...args: any[]) => void; -type Client = (...args: any[]) => void; -type Value = string | number | boolean | Date | string[] | number[] | Date[] | boolean[] | Buffer | Knex.Raw; -interface ValueMap { [key: string]: Value | Knex.QueryBuilder; } -type ColumnName = string | Knex.Raw | Knex.QueryBuilder | {[key: string]: string }; -type TableName = string | Knex.Raw | Knex.QueryBuilder; -interface Identifier { [alias: string]: string; } - -interface Knex extends Knex.QueryInterface { - (tableName?: TableName | Identifier): Knex.QueryBuilder; - VERSION: string; - __knex__: string; - - raw: Knex.RawBuilder; - transaction(transactionScope: (trx: Knex.Transaction) => Promise | Bluebird | void): Bluebird; - destroy(callback: (...args: any[]) => void): void; - destroy(): Bluebird; - batchInsert(tableName: TableName, data: any[], chunkSize?: number): Knex.QueryBuilder; - schema: Knex.SchemaBuilder; - queryBuilder(): Knex.QueryBuilder; - - client: any; - migrate: Knex.Migrator; - seed: any; - fn: Knex.FunctionHelper; - on(eventName: string, callback: (...args: any[]) => void): Knex.QueryBuilder; -} - -declare function Knex(config: Knex.Config): Knex; - -declare namespace Knex { - // - // QueryInterface - // - - interface QueryInterface { - select: Select; - as: As; - columns: Select; - column: Select; - from: Table; - into: Table; - table: Table; - distinct: Distinct; - - // Joins - join: Join; - joinRaw: JoinRaw; - innerJoin: Join; - leftJoin: Join; - leftOuterJoin: Join; - rightJoin: Join; - rightOuterJoin: Join; - outerJoin: Join; - fullOuterJoin: Join; - crossJoin: Join; - - // Withs - with: 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; - whereNull: WhereNull; - orWhereNull: WhereNull; - whereNotNull: WhereNull; - orWhereNotNull: WhereNull; - whereBetween: WhereBetween; - orWhereBetween: WhereBetween; - andWhereBetween: WhereBetween; - whereNotBetween: WhereBetween; - orWhereNotBetween: WhereBetween; - andWhereNotBetween: WhereBetween; - - // Group by - groupBy: GroupBy; - groupByRaw: RawQueryBuilder; - - // Order by - orderBy: OrderBy; - orderByRaw: RawQueryBuilder; - - // Union - union: Union; - unionAll(callback: QueryCallback): QueryBuilder; - - // Having - having: Having; - andHaving: Having; - havingRaw: RawQueryBuilder; - orHaving: Having; - orHavingRaw: RawQueryBuilder; - havingIn: HavingIn; - - // Clear - clearOrder(): QueryBuilder; - clearSelect(): QueryBuilder; - clearWhere(): QueryBuilder; - - // Paging - offset(offset: number): QueryBuilder; - limit(limit: number): QueryBuilder; - - // Aggregation - count(...columnNames: string[]): QueryBuilder; - count(columnName: Record | Raw): QueryBuilder; - countDistinct(columnName: string | Record | Raw): QueryBuilder; - min(columnName: string, ...columnNames: string[]): QueryBuilder; - min(columnName: Record | Raw): QueryBuilder; - max(columnName: string, ...columnNames: string[]): QueryBuilder; - max(columnName: Record | Raw): QueryBuilder; - sum(columnName: string, ...columnNames: string[]): QueryBuilder; - sum(columnName: Record | Raw): QueryBuilder; - sumDistinct(columnName: string | Record | Raw): QueryBuilder; - avg(columnName: string, ...columnNames: string[]): QueryBuilder; - avg(columnName: Record | Raw): QueryBuilder; - avgDistinct(columnName: string | Record | Raw): QueryBuilder; - increment(columnName: string, amount?: number): QueryBuilder; - decrement(columnName: string, amount?: number): QueryBuilder; - - // Others - first: Select; - - pluck(column: string): QueryBuilder; - - insert(data: any, returning?: string | string[]): QueryBuilder; - modify(callback: QueryCallbackWithArgs, ...args: any[]): QueryBuilder; - update(data: any, returning?: string | string[]): QueryBuilder; - update(columnName: string, value: Value, returning?: string | string[]): QueryBuilder; - returning(column: string | string[]): QueryBuilder; - - del(returning?: string | string[]): QueryBuilder; - delete(returning?: string | string[]): QueryBuilder; - truncate(): QueryBuilder; - - clone(): QueryBuilder; - } - - interface As { - (columnName: string): QueryBuilder; - } - - interface Select extends ColumnNameQueryBuilder { - (aliases: { [alias: string]: string }): QueryBuilder; - } - - interface Table { - // tslint:disable-next-line ban-types - (tableName: TableName | Identifier | Function | Raw): QueryBuilder; - } - - // tslint:disable-next-line no-empty-interface - interface Distinct extends ColumnNameQueryBuilder { - } - - interface JoinCallback { - (this: JoinClause, join: JoinClause): void; - } - - interface Join { - (raw: Raw): QueryBuilder; - (tableName: TableName | QueryCallback, clause: JoinCallback): QueryBuilder; - (tableName: TableName | QueryCallback, columns: { [key: string]: string | number | Raw }): QueryBuilder; - (tableName: TableName | QueryCallback, raw: Raw): QueryBuilder; - (tableName: TableName | QueryCallback, column1: string, column2: string): QueryBuilder; - (tableName: TableName | QueryCallback, column1: string, raw: Raw): QueryBuilder; - (tableName: TableName | 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; - onIn(column1: string, values: any[]): JoinClause; - andOnIn(column1: string, values: any[]): JoinClause; - orOnIn(column1: string, values: any[]): JoinClause; - onNotIn(column1: string, values: any[]): JoinClause; - andOnNotIn(column1: string, values: any[]): JoinClause; - orOnNotIn(column1: string, values: any[]): 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: [any, any]): JoinClause; - andOnBetween(column1: string, range: [any, any]): JoinClause; - orOnBetween(column1: string, range: [any, any]): JoinClause; - onNotBetween(column1: string, range: [any, any]): JoinClause; - andOnNotBetween(column1: string, range: [any, any]): JoinClause; - orOnNotBetween(column1: string, range: [any, any]): JoinClause; - using(column: string | string[] | Raw | { [key: string]: string | Raw }): JoinClause; - type(type: string): JoinClause; - } - - interface JoinRaw { - (tableName: string, binding?: Value): QueryBuilder; - } - - interface With extends WithRaw, WithWrapped { - } - - interface WithRaw { - (alias: string, raw: Raw): QueryBuilder; - (alias: string, sql: string, bindings?: Value[] | object): QueryBuilder; - } - - interface WithSchema { - (schema: string): QueryBuilder; - } - - interface WithWrapped { - (alias: string, queryBuilder: QueryBuilder): QueryBuilder; - (alias: string, callback: (queryBuilder: QueryBuilder) => any): QueryBuilder; - } - - interface Where extends WhereRaw, WhereWrapped, WhereNull { - (raw: Raw): QueryBuilder; - (callback: QueryCallback): QueryBuilder; - (object: object): QueryBuilder; - (columnName: string, value: Value | null): QueryBuilder; - (columnName: string, operator: string, value: Value | QueryBuilder | null): QueryBuilder; - (left: Raw, operator: string, right: Value | QueryBuilder | null): QueryBuilder; - } - - interface WhereRaw extends RawQueryBuilder { - (condition: boolean): QueryBuilder; - } - - interface WhereWrapped { - (callback: QueryCallback): QueryBuilder; - } - - interface WhereNull { - (columnName: string): QueryBuilder; - } - - interface WhereBetween { - (columnName: string, range: [Value, Value]): QueryBuilder; - } - - interface WhereExists { - (callback: QueryCallback): QueryBuilder; - (query: QueryBuilder): QueryBuilder; - } - - interface WhereNull { - (columnName: string): QueryBuilder; - } - - interface WhereIn { - (columnName: string, values: Value[] | QueryBuilder | QueryCallback): QueryBuilder; - (columnNames: string[], values: Value[][] | QueryBuilder | QueryCallback): QueryBuilder; - } - - interface GroupBy extends RawQueryBuilder, ColumnNameQueryBuilder { - } - - interface OrderBy { - (columnName: string, direction?: string): QueryBuilder; - } - - interface Union { - (callback: QueryCallback | QueryBuilder | Raw, wrap?: boolean): QueryBuilder; - (callbacks: Array, wrap?: boolean): QueryBuilder; - (...callbacks: Array): QueryBuilder; - // (...callbacks: QueryCallback[], wrap?: boolean): QueryInterface; - } - - interface Having extends RawQueryBuilder, WhereWrapped { - (tableName: string, column1: string, operator: string, column2: string): QueryBuilder; - } - - interface HavingIn { - (columnName: string, values: Value[]): QueryBuilder; - } - - // commons - - interface ColumnNameQueryBuilder { - (...columnNames: ColumnName[]): QueryBuilder; - (columnNames: ColumnName[]): QueryBuilder; - } - - interface RawQueryBuilder { - (sql: string, ...bindings: Array): QueryBuilder; - (sql: string, bindings: Array | ValueMap): QueryBuilder; - (raw: Raw): QueryBuilder; - } - - // Raw - - interface Raw extends events.EventEmitter, ChainableInterface { - wrap(before: string, after: string): Raw; - } - - interface RawBuilder { - (value: Value): Raw; - (sql: string, ...bindings: Array): Raw; - (sql: string, bindings: Array | ValueMap): Raw; - } - - // - // QueryBuilder - // - - type QueryCallback = (this: QueryBuilder, builder: QueryBuilder) => void; - type QueryCallbackWithArgs = (this: QueryBuilder, builder: QueryBuilder, ...args: any[]) => void; - - interface QueryBuilder extends QueryInterface, ChainableInterface { - or: QueryBuilder; - and: QueryBuilder; - - // TODO: Promise? - columnInfo(column?: string): Bluebird; - - forUpdate(): QueryBuilder; - forShare(): QueryBuilder; - - toSQL(): Sql; - - on(event: string, callback: (...args: any[]) => void): QueryBuilder; - } - - interface Sql { - method: string; - options: any; - bindings: Value[]; - sql: string; - } - - // - // Chainable interface - // - - interface ChainableInterface extends Bluebird { - toQuery(): string; - options(options: { [key: string]: any }): this; - connection(connection: any): this; - debug(enabled: boolean): this; - transacting(trx: Transaction): this; - stream(handler: (readable: stream.PassThrough) => any): Bluebird; - stream(options: { [key: string]: any }, handler: (readable: stream.PassThrough) => any): Bluebird; - stream(options?: { [key: string]: any }): stream.PassThrough; - // tslint:disable-next-line no-unnecessary-generics - pipe(writable: T, options?: { [key: string]: any }): stream.PassThrough; - } - - interface Transaction extends Knex { - savepoint(transactionScope: (trx: Transaction) => any): Bluebird; - commit(value?: any): QueryBuilder; - rollback(error?: any): QueryBuilder; - } - - // - // Schema builder - // - - interface SchemaBuilder extends ChainableInterface { - createTable(tableName: string, callback: (tableBuilder: CreateTableBuilder) => any): SchemaBuilder; - createTableIfNotExists(tableName: string, callback: (tableBuilder: CreateTableBuilder) => any): SchemaBuilder; - alterTable(tableName: string, callback: (tableBuilder: CreateTableBuilder) => any): SchemaBuilder; - renameTable(oldTableName: string, newTableName: string): Bluebird; - dropTable(tableName: string): SchemaBuilder; - hasTable(tableName: string): Bluebird; - hasColumn(tableName: string, columnName: string): Bluebird; - table(tableName: string, callback: (tableBuilder: AlterTableBuilder) => any): Bluebird; - dropTableIfExists(tableName: string): SchemaBuilder; - raw(statement: string): SchemaBuilder; - withSchema(schemaName: string): SchemaBuilder; - } - - interface TableBuilder { - increments(columnName?: string): ColumnBuilder; - bigIncrements(columnName?: string): ColumnBuilder; - dropColumn(columnName: string): TableBuilder; - dropColumns(...columnNames: string[]): TableBuilder; - renameColumn(from: string, to: string): ColumnBuilder; - integer(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; - decimal(columnName: string, precision?: number | null, scale?: number): ColumnBuilder; - boolean(columnName: string): ColumnBuilder; - date(columnName: string): ColumnBuilder; - dateTime(columnName: string): ColumnBuilder; - time(columnName: string): ColumnBuilder; - timestamp(columnName: string, standard?: boolean): ColumnBuilder; - timestamps(useTimestampType?: boolean, makeDefaultNow?: boolean): ColumnBuilder; - binary(columnName: string, length?: number): ColumnBuilder; - enum(columnName: string, values: Value[], options?: EnumOptions): ColumnBuilder; - enu(columnName: string, values: Value[], options?: EnumOptions): ColumnBuilder; - json(columnName: string): ColumnBuilder; - jsonb(columnName: string): ColumnBuilder; - uuid(columnName: string): ColumnBuilder; - comment(val: string): TableBuilder; - specificType(columnName: string, type: string): ColumnBuilder; - primary(columnNames: string[]): TableBuilder; - index(columnNames: Array, indexName?: string, indexType?: string): TableBuilder; - unique(columnNames: Array, indexName?: string): TableBuilder; - foreign(column: string, foreignKeyName?: string): ForeignConstraintBuilder; - foreign(columns: string[], foreignKeyName?: string): MultikeyForeignConstraintBuilder; - dropForeign(columnNames: string[], foreignKeyName?: string): TableBuilder; - dropUnique(columnNames: Array, indexName?: string): TableBuilder; - dropPrimary(constraintName?: string): TableBuilder; - dropIndex(columnNames: Array, indexName?: string): TableBuilder; - dropTimestamps(): ColumnBuilder; - } - - // tslint:disable-next-line no-empty-interface - interface CreateTableBuilder extends TableBuilder { - } - - interface MySqlTableBuilder extends CreateTableBuilder { - engine(val: string): CreateTableBuilder; - charset(val: string): CreateTableBuilder; - collate(val: string): CreateTableBuilder; - } - - // tslint:disable-next-line no-empty-interface - interface AlterTableBuilder extends TableBuilder { - } - - // tslint:disable-next-line no-empty-interface - interface MySqlAlterTableBuilder extends AlterTableBuilder { - } - - interface ColumnBuilder { - index(indexName?: string): ColumnBuilder; - primary(constraintName?: string): ColumnBuilder; - unique(indexName?: string): ColumnBuilder; - references(columnName: string): ReferencingColumnBuilder; - onDelete(command: string): ColumnBuilder; - onUpdate(command: string): ColumnBuilder; - defaultTo(value: Value): ColumnBuilder; - unsigned(): ColumnBuilder; - notNullable(): ColumnBuilder; - nullable(): ColumnBuilder; - comment(value: string): ColumnBuilder; - alter(): ColumnBuilder; - } - - interface ForeignConstraintBuilder { - references(columnName: string): ReferencingColumnBuilder; - } - - interface MultikeyForeignConstraintBuilder { - references(columnNames: string[]): ReferencingColumnBuilder; - } - - interface PostgreSqlColumnBuilder extends ColumnBuilder { - index(indexName?: string, indexType?: string): ColumnBuilder; - } - - interface ReferencingColumnBuilder extends ColumnBuilder { - inTable(tableName: string): ColumnBuilder; - } - - // tslint:disable-next-line no-empty-interface - interface AlterColumnBuilder extends ColumnBuilder { - } - - interface MySqlAlterColumnBuilder extends AlterColumnBuilder { - first(): AlterColumnBuilder; - after(columnName: string): AlterColumnBuilder; - } - - interface EnumOptions { - useNative: boolean; - enumName: string; - } - - // - // Configurations - // - - interface ColumnInfo { - defaultValue: Value; - type: string; - maxLength: number; - nullable: boolean; - } - - interface Config { - debug?: boolean; - client?: string | typeof Client; - dialect?: string; - version?: string; - connection?: string | ConnectionConfig | MariaSqlConnectionConfig | - MySqlConnectionConfig | MsSqlConnectionConfig | Sqlite3ConnectionConfig | SocketConnectionConfig; - pool?: PoolConfig; - migrations?: MigratorConfig; - postProcessResponse?: (result: any, queryContext: any) => any; - wrapIdentifier?: (value: string, origImpl: (value: string) => string, queryContext: any) => string; - seeds?: SeedsConfig; - acquireConnectionTimeout?: number; - useNullAsDefault?: boolean; - searchPath?: string | string[]; - asyncStackTraces?: boolean; - } - - interface ConnectionConfig { - host: string; - user: string; - password: string; - database: string; - domain?: string; - instanceName?: string; - debug?: boolean; - requestTimeout?: number; - } - - interface MsSqlConnectionConfig { - user: string; - password: string; - server: string; - database: string; - options: MsSqlOptionsConfig; - } - - // 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; - } - - interface MariaSslConfiguration { - key?: string; - cert?: string; - ca?: string; - capath?: string; - cipher?: string; - rejectUnauthorized?: 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; - } - - /** Used with SQLite3 adapter */ - interface Sqlite3ConnectionConfig { - filename: string; - debug?: boolean; - } - - interface MsSqlOptionsConfig { - encrypt?: boolean; - port?: number; - domain?: string; - connectionTimeout?: number; - requestTimeout?: number; - stream?: boolean; - parseJSON?: boolean; - pool?: PoolConfig; - } - - interface SocketConnectionConfig { - socketPath: string; - user: string; - password: string; - database: string; - debug?: boolean; - } - - interface PoolConfig { - name?: string; - create?: (...args: any[]) => void; - afterCreate?: (...args: any[]) => void; - destroy?: (...args: any[]) => void; - beforeDestroy?: (...args: any[]) => void; - min?: number; - max?: number; - refreshIdle?: boolean; - idleTimeoutMillis?: number; - reapIntervalMillis?: number; - returnToHead?: boolean; - priorityRange?: number; - validate?: (...args: any[]) => void; - log?: boolean; - - // generic-pool v3 configs - maxWaitingClients?: number; - testOnBorrow?: boolean; - acquireTimeoutMillis?: number; - fifo?: boolean; - autostart?: boolean; - evictionRunIntervalMillis?: number; - numTestsPerRun?: number; - softIdleTimeoutMillis?: number; - Promise?: any; - } - - interface MigratorConfig { - database?: string; - directory?: string; - extension?: string; - tableName?: string; - disableTransactions?: boolean; - } - - interface SeedsConfig { - directory?: string; - } - - interface Migrator { - make(name: string, config?: MigratorConfig): Bluebird; - latest(config?: MigratorConfig): Bluebird; - rollback(config?: MigratorConfig): Bluebird; - status(config?: MigratorConfig): Bluebird; - currentVersion(config?: MigratorConfig): Bluebird; - } - - interface FunctionHelper { - now(): Raw; - } - - // - // Clients - // - - 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; - } -} - -export = Knex; diff --git a/types/knex/knex-tests.ts b/types/knex/knex-tests.ts deleted file mode 100644 index 1ff232e4a7..0000000000 --- a/types/knex/knex-tests.ts +++ /dev/null @@ -1,1223 +0,0 @@ -import Knex = require('knex'); -import { WriteStream } from 'fs'; - -// Initializing the Library -let knex = Knex({ - client: 'sqlite3', - connection: { - filename: "./mydb.sqlite" - } -}); - -knex = Knex({ - debug: true, - client: 'mysql', - connection: { - socketPath : '/path/to/socket.sock', - user : 'your_database_user', - password : 'your_database_password', - database : 'myapp_test' - } -}); - -knex = Knex({ - debug: true, - client: 'pg', - version: '9.5', - connection: { - user : 'your_database_user', - password: 'your_database_password', - server : 'your_database_server', - options : { - database: 'myapp_test' - } - } -}); - -knex = Knex({ - debug: true, - client: 'mssql', - connection: { - user : 'your_database_user', - password: 'your_database_password', - server : 'your_database_server', - options : { - database: 'myapp_test' - } - } -}); - -// Mariasql configuration -knex = Knex({ - debug: true, - client: 'mariasql', - connection: { - host : '127.0.0.1', - user : 'your_database_user', - password : 'your_database_password', - db : 'myapp_test' - } -}); - -// Mysql configuration -knex = Knex({ - debug: true, - client: 'mysql', - connection: { - host : '127.0.0.1', - user : 'your_database_user', - password : 'your_database_password', - db : 'myapp_test', - trace: false - } -}); - -// Pooling -knex = Knex({ - client: "mysql", - connection: { - host: "127.0.0.1", - user: "your_database_user", - password: "your_database_password", - database: "myapp_test" - }, - pool: { - min: 0, - max: 7, - afterCreate: (connection: any, callback: (...args: any[]) => void) => callback(null, connection), - beforeDestroy: (connection: any, callback: (...args: any[]) => void) => callback(null, connection) - } -}); - -// acquireConnectionTimeout -knex = Knex({ - debug: true, - client: 'mysql', - connection: { - socketPath : '/path/to/socket.sock', - user : 'your_database_user', - password : 'your_database_password', - database : 'myapp_test' - }, - acquireConnectionTimeout: 60000, -}); - -// Pure Query Builder without a connection -knex = Knex({}); - -// Pure Query Builder without a connection, using a specific flavour of SQL -knex = Knex({ - client: 'pg' -}); - -// searchPath -knex = Knex({ - client: 'pg', - searchPath: 'public', -}); -knex = Knex({ - client: 'pg', - searchPath: ['public', 'private'], -}); - -// postProcessResponse -knex = Knex({ - client: 'pg', - postProcessResponse(result, queryContext) { - return result; - } -}); - -// wrapIdentifier -knex = Knex({ - client: 'pg', - wrapIdentifier(value, origImpl, queryContext) { - return origImpl(value + 'foo'); - } -}); - -// useNullAsDefault -knex = Knex({ - client: 'sqlite', - useNullAsDefault: true, -}); - -// Using custom client -class TestClient extends Knex.Client {} - -knex = Knex({ - client: TestClient, -}); - -knex('books').insert({title: 'Test'}).returning('*').toString(); - -// Migrations -knex = Knex({ - client: 'mysql', - connection: { - host : '127.0.0.1', - user : 'your_database_user', - password : 'your_database_password', - database : 'myapp_test' - }, - migrations: { - tableName: 'migrations' - }, - seeds: { - directory: 'seeds' - } -}); - -// Knex Query Builder -knex.select('title', 'author', 'year').from('books'); -knex.select({ name: 'title', writer: 'author' }).from(knex.raw('books')); -knex.select().table('books'); - -knex.avg('sum_column1').from(function() { - this.sum('column1 as sum_column1').from('t1').groupBy('column1').as('t1'); -}).as('ignored_alias'); - -knex.column('title', 'author', 'year').select().from('books'); -knex.column(['title', 'author', 'year']).select().from('books'); -knex.column('title', { by: 'author' }, 'year').select().from('books'); -knex.column({ title: 'title', by: 'author', published: 'year' }).select().from('books'); -knex.select('*').from('users'); - -knex('users').where({ - first_name: 'Test', - last_name: 'User' -}).select('id'); - -knex('users').where('id', 1); - -knex('users').where(function() { - this.where('id', 1).orWhere('id', '>', 10); -}).orWhere({name: 'Tester'}); - -knex('users').where('votes', '>', 100); - -// Let null be used in a two or 3 parameter where filter -knex('users').where('votes', null); -knex('users').where('votes', 'is not', null); - -// Using Raw in where -knex('users').where(knex.raw('votes + 1'), '>', 101); -knex('users').where(knex.raw('votes + 1'), '>', knex.raw('100 + 1')); -knex('users').where('votes', '>', knex.raw('100 + 1')); - -let subquery = knex('users').where('votes', '>', 100).andWhere('status', 'active').orWhere('name', 'John').select('id'); -knex('accounts').where('id', 'in', subquery); - -knex.select('name').from('users') - .whereIn('id', [1, 2, 3]) - .orWhereIn('id', [4, 5, 6]); - -subquery = knex.select('id').from('accounts'); -knex.select('name').from('users') - .whereIn('account_id', subquery); - -knex('users') - .where('name', '=', 'John') - .orWhere(function() { - this.where('votes', '>', 100).andWhere('title', '<>', 'Admin'); - }); - -knex('users').whereNotIn('id', [1, 2, 3]); - -knex('users').where('name', 'like', '%Test%').orWhereNotIn('id', [1, 2, 3]); - -knex('users').whereNull('updated_at'); - -knex('users').whereNotNull('created_at'); - -knex('users').whereExists(function() { - this.select('*').from('accounts').whereRaw('users.account_id = accounts.id'); -}); - -knex('users').whereExists(knex.select('*').from('accounts').whereRaw('users.account_id = accounts.id')); - -knex('users').whereNotExists(function() { - this.select('*').from('accounts').whereRaw('users.account_id = accounts.id'); -}); - -knex('users').whereBetween('votes', [1, 100]); - -knex('users').whereNotBetween('votes', [1, 100]); - -knex('users').whereRaw('id = ?', [1]); -knex('users').whereRaw('id = :id', { id: 1 }); -knex('users').whereRaw('id = :id', { id: knex('users').select('id').limit(1) }); - -// Aggregate functions can use string/object parameters -knex('users').count(); -knex('users').count('*'); -knex('users').count('id', 'votes'); -knex('users').count({count: '*'}); -knex('users').count({count: ['id', 'votes']}); -knex('users').count({count: knex.raw('*')}); -knex('users').count(knex.raw('id')); - -knex('users').countDistinct('votes'); -knex('users').countDistinct(knex.raw('votes')); -knex('users').countDistinct({votes: 'votes'}); -knex('users').countDistinct({votes: knex.raw('votes')}); - -knex('users').avg('id'); -knex('users').avg('id', 'votes'); -knex('users').avg({avg: 'id'}); -knex('users').avg({avg: ['id', 'votes']}); -knex('users').avg({ab: knex.raw('a + b')}); -knex('users').avg(knex.raw('votes')); - -knex('users').avgDistinct('votes'); -knex('users').avgDistinct(knex.raw('votes')); -knex('users').avgDistinct({votes: 'votes'}); -knex('users').avgDistinct({votes: knex.raw('votes')}); - -knex('users').max('id'); -knex('users').max('id', 'votes'); -knex('users').max({max: 'id'}); -knex('users').max({max: ['id', 'votes']}); -knex('users').max({ab: knex.raw('a + b')}); -knex('users').max(knex.raw('votes')); - -knex('users').min('id'); -knex('users').min('id', 'votes'); -knex('users').min({min: 'id'}); -knex('users').min({min: ['id', 'votes']}); -knex('users').min({ab: knex.raw('a + b')}); -knex('users').min(knex.raw('votes')); - -knex('users').sum('id'); -knex('users').sum('id', 'votes'); -knex('users').sum({sum: 'id'}); -knex('users').sum({sum: ['id', 'votes']}); -knex('users').sum({ab: knex.raw('a + b')}); -knex('users').sum(knex.raw('votes')); - -knex('users').sumDistinct('votes'); -knex('users').sumDistinct(knex.raw('votes')); -knex('users').sumDistinct({votes: 'votes'}); -knex('users').sumDistinct({votes: knex.raw('votes')}); - -// Join methods -knex('users') - .join('contacts', 'users.id', '=', 'contacts.user_id') - .select('users.id', 'contacts.phone'); - -knex('users') - .join('contacts', { 'users.id': 12355 }) - .select('users.id', 'contacts.phone'); - -knex('users') - .join('contacts', 'users.id', 'contacts.user_id') - .select('users.id', 'contacts.phone'); - -knex('users') - .join(knex('contacts').select('user_id', 'phone').as('contacts'), 'users.id', 'contacts.user_id') - .select('users.id', 'contacts.phone'); - -knex('users') - .join(knex('contacts').select('user_id', 'phone').as('contacts'), { 'users.id': 'contacts.user_id' }) - .select('users.id', 'contacts.phone'); - -knex.select('*').from('users').join(knex('accounts').select('id', 'owner_id').as('accounts'), function() { - this.on('accounts.id', '=', 'users.account_id').orOn('accounts.owner_id', '=', 'users.id'); -}); - -knex.select('*').from('users').join('accounts', function() { - this.on('accounts.id', '=', 'users.account_id').orOn('accounts.owner_id', '=', 'users.id'); -}); - -knex.select('*').from('users').join('accounts', function(join: Knex.JoinClause) { - if (this !== join) { - throw new Error("join() callback call semantics wrong"); - } - this.on('accounts.id', '=', 'users.account_id').orOn('accounts.owner_id', '=', 'users.id'); - join.on('accounts.id', '=', 'users.account_id').orOn('accounts.owner_id', '=', 'users.id'); -}); - -knex.select('*').from('user').join('contacts', function() { - this.on('users.id', '=', knex.raw(7)); -}); - -knex.select('*').from('users').join('contacts', function() { - this.on('users.id', '=', 'contacts.id').onIn('contacts.id', [7, 15, 23, 41]); -}); - -knex.select('*').from('users').join('contacts', function() { - this.on('users.id', '=', 'contacts.id').andOnIn('contacts.id', [7, 15, 23, 41]); -}); - -knex.select('*').from('users').join('contacts', function() { - this.on('users.id', '=', 'contacts.id').orOnIn('contacts.id', [7, 15, 23, 41]); -}); - -knex.select('*').from('users').join('contacts', function() { - this.on('users.id', '=', 'contacts.id').onNotIn('contacts.id', [7, 15, 23, 41]); -}); - -knex.select('*').from('users').join('contacts', function() { - this.on('users.id', '=', 'contacts.id').andOnNotIn('contacts.id', [7, 15, 23, 41]); -}); - -knex.select('*').from('users').join('contacts', function() { - this.on('users.id', '=', 'contacts.id').orOnNotIn('contacts.id', [7, 15, 23, 41]); -}); - -knex.select('*').from('users').join('contacts', function() { - this.on('users.id', '=', 'contacts.id').onNull('contacts.email'); -}); - -knex.select('*').from('users').join('contacts', function() { - this.on('users.id', '=', 'contacts.id').andOnNull('contacts.email'); -}); - -knex.select('*').from('users').join('contacts', function() { - this.on('users.id', '=', 'contacts.id').orOnNull('contacts.email'); -}); - -knex.select('*').from('users').join('contacts', function() { - this.on('users.id', '=', 'contacts.id').onNotNull('contacts.email'); -}); - -knex.select('*').from('users').join('contacts', function() { - this.on('users.id', '=', 'contacts.id').andOnNotNull('contacts.email'); -}); - -knex.select('*').from('users').join('contacts', function() { - this.on('users.id', '=', 'contacts.id').orOnNotNull('contacts.email'); -}); - -knex.select('*').from('users').join('contacts', function() { - this.on('users.id', '=', 'contacts.id').onExists(function() { - this.select('*').from('accounts').whereRaw('users.account_id = accounts.id'); - }); -}); - -knex.select('*').from('users').join('contacts', function() { - this.on('users.id', '=', 'contacts.id').andOnExists(function() { - this.select('*').from('accounts').whereRaw('users.account_id = accounts.id'); - }); -}); - -knex.select('*').from('users').join('contacts', function() { - this.on('users.id', '=', 'contacts.id').orOnExists(function() { - this.select('*').from('accounts').whereRaw('users.account_id = accounts.id'); - }); -}); - -knex.select('*').from('users').join('contacts', function() { - this.on('users.id', '=', 'contacts.id').onNotExists(function() { - this.select('*').from('accounts').whereRaw('users.account_id = accounts.id'); - }); -}); - -knex.select('*').from('users').join('contacts', function() { - this.on('users.id', '=', 'contacts.id').andOnNotExists(function() { - this.select('*').from('accounts').whereRaw('users.account_id = accounts.id'); - }); -}); - -knex.select('*').from('users').join('contacts', function() { - this.on('users.id', '=', 'contacts.id').orOnNotExists(function() { - this.select('*').from('accounts').whereRaw('users.account_id = accounts.id'); - }); -}); - -knex.select('*').from('users').join('contacts', function() { - this.on('users.id', '=', 'contacts.id').onBetween('contacts.id', [5, 30]); -}); - -knex.select('*').from('users').join('contacts', function() { - this.on('users.id', '=', 'contacts.id').andOnBetween('contacts.id', [5, 30]); -}); - -knex.select('*').from('users').join('contacts', function() { - this.on('users.id', '=', 'contacts.id').orOnBetween('contacts.id', [5, 30]); -}); - -knex.select('*').from('users').join('contacts', function() { - this.on('users.id', '=', 'contacts.id').onNotBetween('contacts.id', [5, 30]); -}); - -knex.select('*').from('users').join('contacts', function() { - this.on('users.id', '=', 'contacts.id').andOnNotBetween('contacts.id', [5, 30]); -}); - -knex.select('*').from('users').join('contacts', function() { - this.on('users.id', '=', 'contacts.id').orOnNotBetween('contacts.id', [5, 30]); -}); - -knex.select('*').from('users').join('contacts', function() { - this.on('users.id', '=', 'contacts.id').onNotExists(function() { - this.select('*').from('accounts').whereRaw('users.account_id = accounts.id'); - }); -}); - -knex.select('*').from('users').join('accounts', (join: Knex.JoinClause) => { - join.on('accounts.id', '=', 'users.account_id').orOn('accounts.owner_id', '=', 'users.id'); -}); - -knex.select('*').from('users').join('accounts', 'accounts.type', knex.raw('?', ['admin'])); - -knex.raw('? ON CONFLICT DO NOTHING', [knex('account').insert([{}])]); -knex.raw('select * from users where id = ? OR id = ?', - 1, - knex('users').select('id').limit(1), -); -knex.raw('select * from users where id = :user_id', { user_id: 1 }); -knex.raw('select * from users where id = :user_id_query', { - user_id_query: knex('ids').select('id').limit(1) -}); - -knex.from('users').innerJoin('accounts', 'users.id', 'accounts.user_id'); - -knex.table('users').innerJoin('accounts', 'users.id', '=', 'accounts.user_id'); - -knex('users').innerJoin('accounts', function() { - this.on('accounts.id', '=', 'users.account_id').orOn('accounts.owner_id', '=', 'users.id'); -}); - -knex('users').innerJoin('accounts', (join: Knex.JoinClause) => { - join.on('accounts.id', '=', 'users.account_id').orOn('accounts.owner_id', '=', 'users.id'); -}); - -knex.select('*').from('users').leftJoin('accounts', 'users.id', 'accounts.user_id'); - -knex.select('*').from('users').leftJoin('accounts', function() { - this.on('accounts.id', '=', 'users.account_id').orOn('accounts.owner_id', '=', 'users.id'); -}); - -knex.select('*').from('users').leftJoin('accounts', (join: Knex.JoinClause) => { - join.on('accounts.id', '=', 'users.account_id').orOn('accounts.owner_id', '=', 'users.id'); -}); - -knex.select('*').from('users').leftJoin('accounts', (join) => { - join.on('accounts.id', '=', 'users.account_id').orOn('accounts.owner_id', '=', 'users.id') - .andOn((join2) => { - join2.on('col1', 'col2').orOn('col3', 'col4'); - }); -}); - -knex.select('*').from('users').leftOuterJoin('accounts', 'users.id', 'accounts.user_id'); - -knex.select('*').from('users').leftOuterJoin('accounts', function() { - this.on('accounts.id', '=', 'users.account_id').orOn('accounts.owner_id', '=', 'users.id'); -}); - -knex.select('*').from('users').rightJoin('accounts', 'users.id', 'accounts.user_id'); - -knex.select('*').from('users').rightJoin('accounts', function() { - this.on('accounts.id', '=', 'users.account_id').orOn('accounts.owner_id', '=', 'users.id'); -}); - -knex.select('*').from('users').rightJoin('accounts', (join: Knex.JoinClause) => { - join.on('accounts.id', '=', 'users.account_id').orOn('accounts.owner_id', '=', 'users.id'); -}); - -knex.select('*').from('users').rightOuterJoin('accounts', 'users.id', 'accounts.user_id'); - -knex.select('*').from('users').rightOuterJoin('accounts', function() { - this.on('accounts.id', '=', 'users.account_id').orOn('accounts.owner_id', '=', 'users.id'); -}); - -knex.select('*').from('users').outerJoin('accounts', 'users.id', 'accounts.user_id'); - -knex.select('*').from('users').outerJoin('accounts', function() { - this.on('accounts.id', '=', 'users.account_id').orOn('accounts.owner_id', '=', 'users.id'); -}); - -knex.select('*').from('users').outerJoin('accounts', (join: Knex.JoinClause) => { - join.on('accounts.id', '=', 'users.account_id').orOn('accounts.owner_id', '=', 'users.id'); -}); - -knex.select('*').from('users').fullOuterJoin('accounts', 'users.id', 'accounts.user_id'); - -knex.select('*').from('users').fullOuterJoin('accounts', function() { - this.on('accounts.id', '=', 'users.account_id').orOn('accounts.owner_id', '=', 'users.id'); -}); - -knex.select('*').from('users').fullOuterJoin('accounts', (join: Knex.JoinClause) => { - join.on('accounts.id', '=', 'users.account_id').orOn('accounts.owner_id', '=', 'users.id'); -}); - -knex.select('*').from('users').crossJoin('accounts', 'users.id', 'accounts.user_id'); - -knex.select('*').from('accounts').joinRaw('natural full join table1').where('id', 1); - -knex.select('*').from('accounts').join(knex.raw('natural full join table1')).where('id', 1); - -knex.select('*').from('accounts') - .join(function() { - this.select('*').from('accounts').as('special_accounts'); - }, 'special_accounts.a', '=', 'accounts.b'); -knex.select('*').from('accounts') - .leftJoin(function() { - this.select('*').from('accounts').as('special_accounts'); - }, 'special_accounts.a', '=', 'accounts.b'); -knex.select('*').from('accounts') - .leftOuterJoin(function() { - this.select('*').from('accounts').as('special_accounts'); - }, 'special_accounts.a', '=', 'accounts.b'); -knex.select('*').from('accounts') - .rightJoin(function() { - this.select('*').from('accounts').as('special_accounts'); - }, 'special_accounts.a', '=', 'accounts.b'); -knex.select('*').from('accounts') - .rightOuterJoin(function() { - this.select('*').from('accounts').as('special_accounts'); - }, 'special_accounts.a', '=', 'accounts.b'); -knex.select('*').from('accounts') - .innerJoin(function() { - this.select('*').from('accounts').as('special_accounts'); - }, 'special_accounts.a', '=', 'accounts.b'); -knex.select('*').from('accounts') - .crossJoin(function() { - this.select('*').from('accounts').as('special_accounts'); - }, 'special_accounts.a', '=', 'accounts.b'); -knex.select('*').from('accounts') - .fullOuterJoin(function() { - this.select('*').from('accounts').as('special_accounts'); - }, 'special_accounts.a', '=', 'accounts.b'); -knex.select('*').from('accounts') - .outerJoin(function() { - this.select('*').from('accounts').as('special_accounts'); - }, 'special_accounts.a', '=', 'accounts.b'); - -knex('customers') - .distinct('first_name', 'last_name') - .select(); - -knex('users').groupBy('count'); - -knex.select('year', knex.raw('SUM(profit)')).from('sales').groupByRaw('year WITH ROLLUP'); - -knex('users').orderBy('name', 'desc'); - -knex.select('*').from('table').orderByRaw('col NULLS LAST DESC'); - -knex('books').insert({title: 'Slaughterhouse Five'}); - -knex('coords').insert([{x: 20}, {y: 30}, {x: 10, y: 20}]); - -knex.insert([{title: 'Great Gatsby'}, {title: 'Fahrenheit 451'}], 'id').into('books'); -knex.insert([{title: 'Great Gatsby'}, {title: 'Fahrenheit 451'}], ['id', 'title']).into('books'); - -knex('books') - .returning('id') - .insert({title: 'Slaughterhouse Five'}); - -knex('books') - .returning('id') - .insert([{title: 'Great Gatsby'}, {title: 'Fahrenheit 451'}]); - -knex.batchInsert('books', [{title: 'Great Gatsby'}, {title: 'Fahrenheit 451'}], 200); -knex.batchInsert('books', [{title: 'Catcher In The Rye'}, {title: 'Pride And Prejudice'}]); -knex.queryBuilder().table('books'); - -knex('books').where('published_date', '<', 2000).update({status: 'archived'}); -knex('books').where('published_date', '<', 2000).update({status: 'archived'}, 'id'); -knex('books').where('published_date', '<', 2000).update({status: 'archived'}, ['id', 'title']); - -knex('books').update('title', 'Slaughterhouse Five'); -knex('books').update('title', 'Slaughterhouse Five', 'id'); -knex('books').update('title', 'Slaughterhouse Five', ['id', 'title']); - -knex('accounts').where('activated', false).del(); -knex('accounts').where('activated', false).del('id'); -knex('accounts').where('activated', false).del(['id', 'title']); -knex('accounts').where('activated', false).delete(); -knex('accounts').where('activated', false).delete('id'); -knex('accounts').where('activated', false).delete(['id', 'title']); - -knex.with('old_books', (qb) => { - qb.select('*').from('books').where('published_date', '<', 1970); -}).select('*').from('old_books'); - -knex.with('new_books', knex.raw('select * from books where published_date >= 2016')) - .select('*').from('new_books'); - -knex.with('new_books', 'select * from books where published_date >= :year', { year: 2016 }) - .select('*').from('new_books'); - -knex.with('new_books', 'select * from books where published_date >= ?', [2016]) - .select('*').from('new_books'); - -knex.with('new_books', knex.select('*').from('books').where("published_date", ">=", 2016)) - .select('*').from('new_books'); - -knex.withRaw('recent_books', 'select * from books where published_date >= :year', { year: 2013 }) - .select('*').from('recent_books'); - -knex.withRaw('recent_books', knex.raw('select * from books where published_date >= ?', [2013])) - .select('*').from('recent_books'); - -knex.withWrapped("antique_books", (qb) => { - qb.select('*').from('books').where('published_date', '<', 1899); -}).select('*').from('antique_books'); - -knex.withWrapped('new_books', knex.select('*').from('books').where("published_date", ">=", 2016)) - .select('*').from('new_books'); - -const someExternalMethod: (...args: any[]) => void = () => {}; - -knex.transaction((trx) => { - knex('books').transacting(trx).insert({name: 'Old Books'}) - .then((resp) => { - const id = resp[0]; - someExternalMethod(id, trx); - }) - .then(trx.commit) - .catch(trx.rollback); -}).then(() => { - console.log('Transaction complete.'); -}).catch((err) => { - console.error(err); -}); - -knex.transaction((trx) => { - knex('tableName') - .transacting(trx) - .forUpdate() - .select('*'); - - knex('tableName') - .transacting(trx) - .forShare() - .select('*'); -}); - -const transactionReturnValue = knex.transaction((trx) => { - return knex("table") - .insert({ foo: "bar" }) - .returning(["id"]) - .then((result) => { - return result[0].id as number; - }); -}); - -// Tests that the transaction has kept the type of its return value by referencing a method of number -transactionReturnValue.then(value => value.toExponential); - -knex('users').count('active'); - -knex('users').min('age'); - -knex('users').min('age as a'); - -knex('users').max('age'); - -knex('users').max('age as a'); - -knex('users').sum('products'); - -knex('users').sum('products as p'); - -knex('users').avg('age'); - -knex('users').avg('age as a'); - -knex('accounts') - .where('userid', '=', 1) - .increment('balance', 10); - -knex('accounts').where('userid', '=', 1).decrement('balance', 5); - -knex('accounts').truncate(); - -knex.table('users').first('id').then((ids) => { - console.log(ids); -}); - -knex.table('users').first('id', 'name').then((row) => { - console.log(row); -}); - -knex.table('users').first(knex.raw('round(sum(products)) as p')).then((row) => { - console.log(row); -}); - -knex.table('users').orderBy('name', 'desc').clearOrder().orderBy('id', 'asc').then((rows) => { - console.log(rows); -}); - -knex.table('users').select('*').clearSelect().select('id').then((rows) => { - console.log(rows); -}); - -knex('accounts').where('userid', '=', 1).clearWhere().select().then((rows) => { - console.log(rows); -}); - -// Using trx as a query builder: -knex.transaction((trx) => { - const info: any = {}; - const books: any[] = [ - {title: 'Canterbury Tales'}, - {title: 'Moby Dick'}, - {title: 'Hamlet'} - ]; - - return trx - .insert({name: 'Old Books'}, 'id') - .into('catalogues') - .then((ids) => { - return Promise.all(books.map((book: any) => { - book.catalogue_id = ids[0]; - // Some validation could take place here. - return trx.insert(info).into('books'); - })); - }); -}) -.then((inserts) => { - console.log(inserts.length + ' new books saved.'); -}) -.catch((error) => { - // If we get here, that means that neither the 'Old Books' catalogues insert, - // nor any of the books inserts will have taken place. - console.error(error); -}); - -// Using trx as a transaction object: -knex.transaction<{ length: number }>((trx) => { - trx.raw(''); - - trx.on('query-error', (error: Error) => { - console.error(error); - }); - - trx.savepoint((nestedTrx) => { - nestedTrx.rollback(new Error('something went terribly wrong')); - }); - - trx.transaction((nestedTrx) => { - nestedTrx.commit(); - }); - - const info: any = {}; - const books: any[] = [ - {title: 'Canterbury Tales'}, - {title: 'Moby Dick'}, - {title: 'Hamlet'} - ]; - - knex.insert({name: 'Old Books'}, 'id') - .into('catalogues') - .transacting(trx) - .then((ids) => { - return Promise.all(books.map((book: any) => { - book.catalogue_id = ids[0]; - - // Some validation could take place here. - - return knex.insert(info).into('books').transacting(trx); - })); - }) - .then(trx.commit) - .catch(trx.rollback); -}) -.then((inserts) => { - console.log(inserts.length + ' new books saved.'); -}) -.catch((error) => { - // If we get here, that means that neither the 'Old Books' catalogues insert, - // nor any of the books inserts will have taken place. - console.error(error); -}); - -// transacting handles undefined -knex.insert({ name: 'Old Books'}).transacting(undefined); - -knex.schema.withSchema("public").hasTable("table"); // $ExpectType Bluebird - -knex.schema.createTable('users', (table) => { - table.increments(); - table.string('name'); - table.enu('favorite_color', ['red', 'blue', 'green']); - table.timestamps(); - table.timestamp('created_at').defaultTo(knex.fn.now()); - table.timestamps(true, true); -}); - -knex.schema.alterTable('users', (table) => { - table.string('role').nullable(); -}); - -knex.schema.renameTable('users', 'old_users'); - -knex.schema.dropTable('users'); - -knex.schema.hasTable('users').then((exists) => { - if (!exists) { - return knex.schema.createTable('users', (t) => { - t.increments('id').primary(); - t.string('first_name', 100); - t.string('last_name', 100); - t.text('bio'); - }); - } -}); - -const tableName = ''; -const columnName = ''; -knex.schema.hasColumn(tableName, columnName); - -knex.schema.dropTableIfExists('users'); - -knex.schema.table('users', (table) => { - table.dropColumn('name'); - table.string('first_name'); - table.string('last_name'); -}); - -knex.schema.raw("SET sql_mode='TRADITIONAL'") -.table('users', (table) => { - table.dropColumn('name'); - table.string('first_name'); - table.string('last_name'); - table.dropUnique(["name1", "name2"], "index_name"); - table.dropUnique(["name1", "name2"]); - table.dropPrimary(); - table.dropPrimary("constraint_name"); -}); - -knex('users') - .select(knex.raw('count(*) as user_count, status')) - .where(knex.raw(1)) - .orWhere(knex.raw('status <> ?', [1])) - .groupBy('status'); - -knex.raw('select * from users where id = ?', [1]).then((resp) => { - // ... - }); - -(() => { - const subcolumn = knex.raw('select avg(salary) from employee where dept_no = e.dept_no') - .wrap('(', ') avg_sal_dept'); - - knex.select('e.lastname', 'e.salary', subcolumn) - .from('employee as e') - .whereRaw('dept_no = e.dept_no'); -})(); - -(() => { - const subcolumn = knex.avg('salary') - .from('employee') - .whereRaw('dept_no = e.dept_no') - .as('avg_sal_dept'); - - knex.select('e.lastname', 'e.salary', subcolumn) - .from('employee as e') - .whereRaw('dept_no = e.dept_no'); -})(); - -const x = 1; -knex.select('name').from('users') - .where('id', '>', 20) - .andWhere('id', '<', 200) - .limit(10) - .offset(x) - .then((rows) => { - return rows.map((r: any) => r.name); - }) - .then((names: any) => { - return knex.select('id').from('nicknames').whereIn('nickname', names); - }) - .then((rows) => { - console.log(rows); - }) - .catch((error) => { - console.error(error); - }); - -knex.select('*').from('users').where({name: 'Tim'}) - .then((rows) => { - return knex.insert({user_id: rows[0].id, name: 'Test'}, 'id').into('accounts'); - }).then((id) => { - console.log('Inserted Account ' + id); - }).catch((error) => { - console.error(error); - }); - -knex.insert({id: 1, name: 'Test'}, 'id').into('accounts') - .catch((error) => { - console.error(error); - }).then(() => { - return knex.select('*').from('accounts').where('id', 1); - }).then((rows) => { - console.log(rows[0]); - }).catch((error) => { - console.error(error); - }); - -const query: any = () => {}; -query.then((x: any) => { - // doSideEffectsHere(x); - return x; -}); - -knex.select('name').from('users').limit(10).then((rows: any[]): string[] => { - return rows.map((row: any): string => { - return row.name; - }); -}).then((names: string[]) => { - console.log(names); -}).catch((e: Error) => { - console.error(e); -}); - -knex.select('name').from('users').limit(10).then((rows: any[]) => { - return rows.reduce((memo: any, row: any) => { - memo.names.push(row.name); - memo.count++; - return memo; - }, {count: 0, names: []}); -}).then((obj: any) => { - console.log(obj); -}).catch((e: Error) => { - console.error(e); -}); - -knex.select('name').from('users') - .limit(10) - .then(console.log.bind(console)) - .catch(console.error.bind(console)); - -const values: any[] = []; - -knex.insert(values).into('users') - .then(() => { - return {inserted: true}; - }); - -knex.select('name').from('users') - .where('id', '>', 20) - .andWhere('id', '<', 200) - .limit(10) - .offset(x); - -// Retrieve the stream: -let stream = knex.select('*').from('users').stream(); -const writableStream: NodeJS.WritableStream = new WriteStream(); -stream.pipe(writableStream); - -// With options: -stream = knex.select('*').from('users').stream({highWaterMark: 5}); -stream.pipe(writableStream); - -// Use as a promise: -(() => { - knex - .select("*") - .from("users") - .where(knex.raw("id = ?", [1])) - .stream((stream: any) => { - stream.pipe(writableStream); - }) - .then(() => { - // ... - }) - .catch((e: Error) => { - console.error(e); - }); -})(); - -stream = knex.select('*').from('users').pipe(writableStream); -const app: any = () => {}; - -knex.select('*') - .from('users') - .on('query', (data: any) => { - app.log(data); - }) - .then(() => { - // ... - }); - -knex.select('*').from('users').where(knex.raw('id = ?', [1])).toString(); - -knex.select('*').from('users').where(knex.raw('id = ?', [1])).toSQL(); - -// -// Callback functions -// -knex('users') - .select('*') - .join('contacts', function(builder) { - this.on(function(builder: any) { - let self: Knex.JoinClause = this; - self = builder; - }).andOn(function(builder: any) { - let self: Knex.JoinClause = this; - self = builder; - }).orOn(function(builder: any) { - let self: Knex.JoinClause = this; - self = builder; - }).onExists(function(builder: any) { - let self: Knex.QueryBuilder = this; - self = builder; - }).orOnExists(function(builder: any) { - let self: Knex.QueryBuilder = this; - self = builder; - }).andOnExists(function(builder: any) { - let self: Knex.QueryBuilder = this; - self = builder; - }).onNotExists(function(builder: any) { - let self: Knex.QueryBuilder = this; - self = builder; - }).andOnNotExists(function(builder: any) { - let self: Knex.QueryBuilder = this; - self = builder; - }).orOnNotExists(function(builder: any) { - let self: Knex.QueryBuilder = this; - self = builder; - }); - }).where(function(builder) { - let self: Knex.QueryBuilder = this; - self = builder; - }).orWhere(function(builder) { - let self: Knex.QueryBuilder = this; - self = builder; - }).andWhere(function(builder) { - let self: Knex.QueryBuilder = this; - self = builder; - }).whereIn('column', function(builder) { - let self: Knex.QueryBuilder = this; - self = builder; - }).orWhereIn('column', function(builder) { - let self: Knex.QueryBuilder = this; - self = builder; - }).whereNotIn('column', function(builder) { - let self: Knex.QueryBuilder = this; - self = builder; - }).orWhereNotIn('column', function(builder) { - let self: Knex.QueryBuilder = this; - self = builder; - }).whereWrapped(function(builder) { - let self: Knex.QueryBuilder = this; - self = builder; - }).union(function(builder) { - let self: Knex.QueryBuilder = this; - self = builder; - }).unionAll(function(builder) { - let self: Knex.QueryBuilder = this; - self = builder; - }).modify(function(builder, aBool) { - let self: Knex.QueryBuilder = this; - self = builder; - }, true); - -// -// Migrations -// -const name = "test"; -const config = { - directory: "./migrations", - extension: "js", - tableName: "knex_migrations", - disableTransactions: false -}; -knex.migrate.make(name, config); -knex.migrate.make(name); - -knex.migrate.latest(config); -knex.migrate.latest(); - -knex.migrate.rollback(config); -knex.migrate.rollback(); - -knex.migrate.currentVersion(config); -knex.migrate.currentVersion(); - -knex.seed.make(name, config); -knex.seed.make(name); - -knex.seed.run(config); -knex.seed.run(); - -knex.schema - .dropTableIfExists('A') - .createTable('A', table => { - table.integer('C').unsigned().references('B.id').notNullable(); - table.integer('D').primary('PK').notNullable(); - table.string('E').unique('UX').nullable(); - table.foreign('E', 'FK').references('F.id'); - table.timestamp('T', false).notNullable(); - }); - -// creating table in MySQL with binary primary key with known field length -knex.schema.createTable('testTable', (table) => { - table.binary('binaryKey', 16).primary(); // will make table with binaryKey type BINARY(16) -}); - -// allow creating decimal column that can store that can store numbers of any -// precision and scale. (Only supported for Oracle, SQLite, Postgres) -knex = Knex({ - client: 'pg' -}); - -knex.schema - .dropTableIfExists('testTable') - .createTable('testTable', (table) => { - table.decimal('dec', null); - }) - .dropTable('testTable'); - -// allow specifying an alias for a table name -knex.schema - .dropTableIfExists('foo') - .dropTableIfExists('bar') - .createTable('foo', (table) => { - table.uuid('id').primary(); - }) - .createTable('bar', (table) => { - table.uuid('id').primary(); - }); - -knex({ - table1: 'foo', - table2: 'bar' -}) - .select({ - table1Id: 'table1.id', - table2Id: 'table2.id' - }); - -knex('characters') - .select() - .whereIn(['name', 'class'], [['Bar', 'Fighter'], ['Foo', 'Druid']]); - -knex('characters') - .select() - .whereIn('name', knex('characters').select('name')); -knex('characters') - .select() - .whereIn(['name', 'class'], knex('characters').select('name', 'class')); - -knex('characters') - .select() - .whereIn('name', function() { - this.select('name').from('characters'); - }); -knex('characters') - .select() - .whereIn(['name', 'class'], function() { - this.select('name', 'class').from('characters'); - }); - -knex('characters') - .select() - .where({ name: 'Bar', class: 'Fighter' }) - .union(knex('characters').select().where({ name: 'Foo', class: 'Druid' })); -knex('characters') - .select() - .where({ name: 'Bar', class: 'Fighter' }) - .union([knex('characters').select().where({ name: 'Foo', class: 'Druid' })]); -knex('characters') - .select() - .where({ name: 'Bar', class: 'Fighter' }) - .union( - knex('characters').select().where({ name: 'Foo', class: 'Druid' }), - knex('characters').select().where({ name: 'Baz', class: 'Paladin' }) - ); diff --git a/types/knex/tsconfig.json b/types/knex/tsconfig.json deleted file mode 100644 index 8f0b7771d9..0000000000 --- a/types/knex/tsconfig.json +++ /dev/null @@ -1,24 +0,0 @@ -{ - "compilerOptions": { - "module": "commonjs", - "lib": [ - "es6", - "dom" - ], - "noImplicitAny": true, - "noImplicitThis": false, - "strictNullChecks": false, - "strictFunctionTypes": true, - "baseUrl": "../", - "typeRoots": [ - "../" - ], - "types": [], - "noEmit": true, - "forceConsistentCasingInFileNames": true - }, - "files": [ - "index.d.ts", - "knex-tests.ts" - ] -} \ No newline at end of file diff --git a/types/knex/tslint.json b/types/knex/tslint.json deleted file mode 100644 index 604d5950cf..0000000000 --- a/types/knex/tslint.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "extends": "dtslint/dt.json", - "rules": { - "unified-signatures": false, - "callable-types": false - } -} From 68e69031cd0e28214e879a65548fa039f15decf9 Mon Sep 17 00:00:00 2001 From: "Matt R. Wilson" Date: Thu, 14 Mar 2019 16:35:37 -0600 Subject: [PATCH 2/2] Add knex as dependency for needing packages. Allows these types to still require knex now that it self bundles its types. --- types/bookshelf/package.json | 6 ++++++ types/knex-postgis/package.json | 6 ++++++ types/mock-knex/package.json | 6 ++++++ types/schwifty/package.json | 1 + 4 files changed, 19 insertions(+) create mode 100644 types/bookshelf/package.json create mode 100644 types/knex-postgis/package.json create mode 100644 types/mock-knex/package.json diff --git a/types/bookshelf/package.json b/types/bookshelf/package.json new file mode 100644 index 0000000000..7bd76f13f8 --- /dev/null +++ b/types/bookshelf/package.json @@ -0,0 +1,6 @@ +{ + "private": true, + "dependencies": { + "knex": "^0.16.1" + } +} diff --git a/types/knex-postgis/package.json b/types/knex-postgis/package.json new file mode 100644 index 0000000000..7bd76f13f8 --- /dev/null +++ b/types/knex-postgis/package.json @@ -0,0 +1,6 @@ +{ + "private": true, + "dependencies": { + "knex": "^0.16.1" + } +} diff --git a/types/mock-knex/package.json b/types/mock-knex/package.json new file mode 100644 index 0000000000..7bd76f13f8 --- /dev/null +++ b/types/mock-knex/package.json @@ -0,0 +1,6 @@ +{ + "private": true, + "dependencies": { + "knex": "^0.16.1" + } +} diff --git a/types/schwifty/package.json b/types/schwifty/package.json index 01df4a95e3..4361a26f8b 100644 --- a/types/schwifty/package.json +++ b/types/schwifty/package.json @@ -1,6 +1,7 @@ { "private": true, "dependencies": { + "knex": "^0.16.1", "objection": "^1.1.9" } }