UNPKG

2.63 kBJavaScriptView Raw
1const Raw = require('./raw');
2const Client = require('./client');
3const QueryBuilder = require('./query/builder');
4const QueryInterface = require('./query/methods');
5
6const makeKnex = require('./util/make-knex');
7const parseConnection = require('./util/parse-connection');
8const { KnexTimeoutError } = require('./util/timeout');
9const fakeClient = require('./util/fake-client');
10const { SUPPORTED_CLIENTS } = require('./constants');
11const { resolveClientNameWithAliases } = require('./helpers');
12
13function Knex(config) {
14 // If config is a string, try to parse it
15 if (typeof config === 'string') {
16 const parsedConfig = Object.assign(parseConnection(config), arguments[2]);
17 return new Knex(parsedConfig);
18 }
19
20 let Dialect;
21 // If user provided no relevant parameters, use generic client
22 if (arguments.length === 0 || (!config.client && !config.dialect)) {
23 Dialect = Client;
24 }
25
26 // If user provided Client constructor as a parameter, use it
27 else if (
28 typeof config.client === 'function' &&
29 config.client.prototype instanceof Client
30 ) {
31 Dialect = config.client;
32 }
33
34 // If neither applies, let's assume user specified name of a client or dialect as a string
35 else {
36 const clientName = config.client || config.dialect;
37 if (!SUPPORTED_CLIENTS.includes(clientName)) {
38 throw new Error(
39 `knex: Unknown configuration option 'client' value ${clientName}. Note that it is case-sensitive, check documentation for supported values.`
40 );
41 }
42
43 const resolvedClientName = resolveClientNameWithAliases(clientName);
44 Dialect = require(`./dialects/${resolvedClientName}/index.js`);
45 }
46
47 // If config connection parameter is passed as string, try to parse it
48 if (typeof config.connection === 'string') {
49 config = Object.assign({}, config, {
50 connection: parseConnection(config.connection).connection,
51 });
52 }
53 const newKnex = makeKnex(new Dialect(config));
54 if (config.userParams) {
55 newKnex.userParams = config.userParams;
56 }
57 return newKnex;
58}
59
60// Expose Client on the main Knex namespace.
61Knex.Client = Client;
62
63Knex.KnexTimeoutError = KnexTimeoutError;
64
65Knex.QueryBuilder = {
66 extend: function (methodName, fn) {
67 QueryBuilder.extend(methodName, fn);
68 QueryInterface.push(methodName);
69 },
70};
71
72/* eslint no-console:0 */
73
74// Run a "raw" query, though we can't do anything with it other than put
75// it in a query statement.
76Knex.raw = (sql, bindings) => {
77 console.warn(
78 'global Knex.raw is deprecated, use knex.raw (chain off an initialized knex object)'
79 );
80 return new Raw(fakeClient).set(sql, bindings);
81};
82
83module.exports = Knex;