UNPKG

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