UNPKG

waterline-postgresql

Version:
1,707 lines (1,398 loc) 618 kB
(function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(require("lodash"), require("bluebird")); else if(typeof define === 'function' && define.amd) define(["lodash", "bluebird"], factory); else if(typeof exports === 'object') exports["Knex"] = factory(require("lodash"), require("bluebird")); else root["Knex"] = factory(root["_"], root["Promise"]); })(this, function(__WEBPACK_EXTERNAL_MODULE_11__, __WEBPACK_EXTERNAL_MODULE_12__) { return /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ // Load entry module and return exports /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {'use strict'; var Raw = __webpack_require__(1); var warn = __webpack_require__(2).warn; var Client = __webpack_require__(3); var makeClient = __webpack_require__(4); var makeKnex = __webpack_require__(5); var parseConnection = __webpack_require__(6); var assign = __webpack_require__(29); function Knex(config) { if (typeof config === 'string') { return new Knex(assign(parseConnection(config), arguments[2])); } var Dialect; if (arguments.length === 0 || !config.client && !config.dialect) { Dialect = makeClient(Client); } else { var clientName = config.client || config.dialect; Dialect = makeClient(__webpack_require__(7)("./" + (aliases[clientName] || clientName) + '/index.js')); } if (typeof config.connection === 'string') { config = assign({}, config, { connection: parseConnection(config.connection).connection }); } return makeKnex(new Dialect(config)); } // Expose Client on the main Knex namespace. Knex.Client = Client; // Run a "raw" query, though we can't do anything with it other than put // it in a query statement. Knex.raw = function (sql, bindings) { return new Raw({}).set(sql, bindings); }; // Create a new "knex" instance with the appropriate configured client. Knex.initialize = function (config) { warn('knex.initialize is deprecated, pass your config object directly to the knex module'); return new Knex(config); }; // Bluebird Knex.Promise = __webpack_require__(8); // The client names we'll allow in the `{name: lib}` pairing. var aliases = { 'mariadb': 'maria', 'mariasql': 'maria', 'pg': 'postgres', 'postgresql': 'postgres', 'sqlite': 'sqlite3' }; // Doing this ensures Browserify works. Still need to figure out // the best way to do some of this. if (process.browser) { __webpack_require__(9); } module.exports = Knex; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(10))) /***/ }, /* 1 */ /***/ function(module, exports, __webpack_require__) { // Raw // ------- 'use strict'; var inherits = __webpack_require__(47); var EventEmitter = __webpack_require__(43).EventEmitter; var assign = __webpack_require__(29); var reduce = __webpack_require__(30); var isPlainObject = __webpack_require__(31); var _ = __webpack_require__(11); function Raw(client) { this.client = client; this.sql = ''; this.bindings = []; this._cached = undefined; // Todo: Deprecate this._wrappedBefore = undefined; this._wrappedAfter = undefined; this._debug = client && client.config && client.config.debug; } inherits(Raw, EventEmitter); assign(Raw.prototype, { set: function set(sql, bindings) { this._cached = undefined; this.sql = sql; this.bindings = _.isObject(bindings) || _.isUndefined(bindings) ? bindings : [bindings]; return this; }, // Wraps the current sql with `before` and `after`. wrap: function wrap(before, after) { this._cached = undefined; this._wrappedBefore = before; this._wrappedAfter = after; return this; }, // Calls `toString` on the Knex object. toString: function toString() { return this.toQuery(); }, // Returns the raw sql for the query. toSQL: function toSQL() { if (this._cached) return this._cached; if (Array.isArray(this.bindings)) { this._cached = replaceRawArrBindings(this); } else if (this.bindings && isPlainObject(this.bindings)) { this._cached = replaceKeyBindings(this); } else { this._cached = { method: 'raw', sql: this.sql, bindings: this.bindings }; } if (this._wrappedBefore) { this._cached.sql = this._wrappedBefore + this._cached.sql; } if (this._wrappedAfter) { this._cached.sql = this._cached.sql + this._wrappedAfter; } this._cached.options = reduce(this._options, assign, {}); return this._cached; } }); function replaceRawArrBindings(raw) { var expectedBindings = raw.bindings.length; var values = raw.bindings; var client = raw.client; var index = 0; var bindings = []; var sql = raw.sql.replace(/\\?\?\??/g, function (match) { if (match === '\\?') { return match; } var value = values[index++]; if (value && typeof value.toSQL === 'function') { var bindingSQL = value.toSQL(); if (bindingSQL.bindings !== undefined) { bindings = bindings.concat(bindingSQL.bindings); } return bindingSQL.sql; } if (match === '??') { return client.formatter().columnize(value); } bindings.push(value); return '?'; }); if (expectedBindings !== index) { throw new Error('Expected ' + expectedBindings + ' bindings, saw ' + index); } return { method: 'raw', sql: sql, bindings: bindings }; } function replaceKeyBindings(raw) { var values = raw.bindings; var client = raw.client; var sql = raw.sql, bindings = []; var regex = new RegExp('(^|\\s)(\\:\\w+\\:?)', 'g'); sql = raw.sql.replace(regex, function (full) { var key = full.trim(); var isIdentifier = key[key.length - 1] === ':'; var value = isIdentifier ? values[key.slice(1, -1)] : values[key.slice(1)]; if (value === undefined) return ''; if (value && typeof value.toSQL === 'function') { var bindingSQL = value.toSQL(); if (bindingSQL.bindings !== undefined) { bindings = bindings.concat(bindingSQL.bindings); } return full.replace(key, bindingSQL.sql); } if (isIdentifier) { return full.replace(key, client.formatter().columnize(value)); } bindings.push(value); return full.replace(key, '?'); }); return { method: 'raw', sql: sql, bindings: bindings }; } // Allow the `Raw` object to be utilized with full access to the relevant // promise API. __webpack_require__(13)(Raw); module.exports = Raw; /***/ }, /* 2 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {'use strict'; var _ = __webpack_require__(11); var chalk = __webpack_require__(44); var helpers = { // Pick off the attributes from only the current layer of the object. skim: function skim(data) { return _.map(data, function (obj) { return _.pick(obj, _.keys(obj)); }); }, // Check if the first argument is an array, otherwise // uses all arguments as an array. normalizeArr: function normalizeArr() { var args = new Array(arguments.length); for (var i = 0; i < args.length; i++) { args[i] = arguments[i]; } if (Array.isArray(args[0])) { return args[0]; } return args; }, error: function error(msg) { console.log(chalk.red('Knex:Error ' + msg)); }, // Used to signify deprecated functionality. deprecate: function deprecate(method, alternate) { helpers.warn(method + ' is deprecated, please use ' + alternate); }, // Used to warn about incorrect use, without error'ing warn: function warn(msg) { console.log(chalk.yellow("Knex:warning - " + msg)); }, exit: function exit(msg) { console.log(chalk.red(msg)); process.exit(); } }; module.exports = helpers; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(10))) /***/ }, /* 3 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _ = __webpack_require__(11); var Promise = __webpack_require__(8); var helpers = __webpack_require__(2); var Raw = __webpack_require__(1); var Runner = __webpack_require__(14); var Formatter = __webpack_require__(15); var Transaction = __webpack_require__(16); var QueryBuilder = __webpack_require__(17); var QueryCompiler = __webpack_require__(18); var SchemaBuilder = __webpack_require__(19); var SchemaCompiler = __webpack_require__(20); var TableBuilder = __webpack_require__(21); var TableCompiler = __webpack_require__(22); var ColumnBuilder = __webpack_require__(23); var ColumnCompiler = __webpack_require__(24); var Pool2 = __webpack_require__(25); var inherits = __webpack_require__(47); var EventEmitter = __webpack_require__(43).EventEmitter; var SqlString = __webpack_require__(26); var assign = __webpack_require__(29); var uniqueId = __webpack_require__(33); var cloneDeep = __webpack_require__(32); var debug = __webpack_require__(48)('knex:client'); var debugQuery = __webpack_require__(48)('knex:query'); // The base client provides the general structure // for a dialect specific client object. function Client() { var config = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; this.config = config; this.connectionSettings = cloneDeep(config.connection || {}); if (this.driverName && config.connection) { this.initializeDriver(); if (!config.pool || config.pool && config.pool.max !== 0) { this.initializePool(config); } } this.valueForUndefined = this.raw('DEFAULT'); if (config.useNullAsDefault) { this.valueForUndefined = null; } } inherits(Client, EventEmitter); assign(Client.prototype, { Formatter: Formatter, formatter: function formatter() { return new this.Formatter(this); }, QueryBuilder: QueryBuilder, queryBuilder: function queryBuilder() { return new this.QueryBuilder(this); }, QueryCompiler: QueryCompiler, queryCompiler: function queryCompiler(builder) { return new this.QueryCompiler(this, builder); }, SchemaBuilder: SchemaBuilder, schemaBuilder: function schemaBuilder() { return new this.SchemaBuilder(this); }, SchemaCompiler: SchemaCompiler, schemaCompiler: function schemaCompiler(builder) { return new this.SchemaCompiler(this, builder); }, TableBuilder: TableBuilder, tableBuilder: function tableBuilder(type, tableName, fn) { return new this.TableBuilder(this, type, tableName, fn); }, TableCompiler: TableCompiler, tableCompiler: function tableCompiler(tableBuilder) { return new this.TableCompiler(this, tableBuilder); }, ColumnBuilder: ColumnBuilder, columnBuilder: function columnBuilder(tableBuilder, type, args) { return new this.ColumnBuilder(this, tableBuilder, type, args); }, ColumnCompiler: ColumnCompiler, columnCompiler: function columnCompiler(tableBuilder, columnBuilder) { return new this.ColumnCompiler(this, tableBuilder, columnBuilder); }, Runner: Runner, runner: function runner(connection) { return new this.Runner(this, connection); }, SqlString: SqlString, Transaction: Transaction, transaction: function transaction(container, config, outerTx) { return new this.Transaction(this, container, config, outerTx); }, Raw: Raw, raw: function raw() { var raw = new this.Raw(this); return raw.set.apply(raw, arguments); }, query: function query(connection, obj) { var _this = this; if (typeof obj === 'string') obj = { sql: obj }; this.emit('query', assign({ __knexUid: connection.__knexUid }, obj)); debugQuery(obj.sql); return this._query.call(this, connection, obj)['catch'](function (err) { err.message = SqlString.format(obj.sql, obj.bindings) + ' - ' + err.message; _this.emit('query-error', err, obj); throw err; }); }, stream: function stream(connection, obj, _stream, options) { if (typeof obj === 'string') obj = { sql: obj }; this.emit('query', assign({ __knexUid: connection.__knexUid }, obj)); debugQuery(obj.sql); return this._stream.call(this, connection, obj, _stream, options); }, prepBindings: function prepBindings(bindings) { return _.map(bindings, function (binding) { return binding === undefined ? this.valueForUndefined : binding; }, this); }, wrapIdentifier: function wrapIdentifier(value) { return value !== '*' ? '"' + value.replace(/"/g, '""') + '"' : '*'; }, initializeDriver: function initializeDriver() { try { this.driver = this._driver(); } catch (e) { helpers.exit('Knex: run\n$ npm install ' + this.driverName + ' --save' + '\n' + e.stack); } }, Pool: Pool2, initializePool: function initializePool(config) { if (this.pool) this.destroy(); this.pool = new this.Pool(assign(this.poolDefaults(config.pool || {}), config.pool)); this.pool.on('error', function (err) { helpers.error('Pool2 - ' + err); }); this.pool.on('warn', function (msg) { helpers.warn('Pool2 - ' + msg); }); }, poolDefaults: function poolDefaults(poolConfig) { var dispose, client = this; if (poolConfig.destroy) { helpers.deprecate('config.pool.destroy', 'config.pool.dispose'); dispose = poolConfig.destroy; } return { min: 2, max: 10, acquire: function acquire(callback) { client.acquireRawConnection().tap(function (connection) { connection.__knexUid = uniqueId('__knexUid'); if (poolConfig.afterCreate) { return Promise.promisify(poolConfig.afterCreate)(connection); } }).nodeify(callback); }, dispose: function dispose(connection, callback) { if (poolConfig.beforeDestroy) { poolConfig.beforeDestroy(connection, function () { if (connection !== undefined) { client.destroyRawConnection(connection, callback); } }); } else if (connection !== void 0) { client.destroyRawConnection(connection, callback); } } }; }, // Acquire a connection from the pool. acquireConnection: function acquireConnection() { var client = this; return new Promise(function (resolver, rejecter) { if (!client.pool) { return rejecter(new Error('There is no pool defined on the current client')); } client.pool.acquire(function (err, connection) { if (err) return rejecter(err); debug('acquiring connection from pool: %s', connection.__knexUid); resolver(connection); }); }); }, // Releases a connection back to the connection pool, // returning a promise resolved when the connection is released. releaseConnection: function releaseConnection(connection) { var pool = this.pool; return new Promise(function (resolver) { debug('releasing connection to pool: %s', connection.__knexUid); pool.release(connection); resolver(); }); }, // Destroy the current connection pool for the client. destroy: function destroy(callback) { var client = this; var promise = new Promise(function (resolver) { if (!client.pool) return resolver(); client.pool.end(function () { client.pool = undefined; resolver(); }); }); // Allow either a callback or promise interface for destruction. if (typeof callback === 'function') { promise.nodeify(callback); } else { return promise; } }, // Return the database being used by this client. database: function database() { return this.connectionSettings.database; }, toString: function toString() { return '[object KnexClient]'; } }); module.exports = Client; /***/ }, /* 4 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var assign = __webpack_require__(29); var inherits = __webpack_require__(47); // Ensure the client has fresh objects so we can tack onto // the prototypes without mutating them globally. module.exports = function makeClient(ParentClient) { if (typeof ParentClient.prototype === 'undefined') { throw new Error('A valid parent client must be passed to makeClient'); } function Client(config) { ParentClient.call(this, config); } inherits(Client, ParentClient); function Formatter(client) { Formatter.super_.call(this, client); } inherits(Formatter, ParentClient.prototype.Formatter); function QueryBuilder(client) { QueryBuilder.super_.call(this, client); } inherits(QueryBuilder, ParentClient.prototype.QueryBuilder); function SchemaBuilder(client) { SchemaBuilder.super_.call(this, client); } inherits(SchemaBuilder, ParentClient.prototype.SchemaBuilder); function SchemaCompiler(client, builder) { SchemaCompiler.super_.call(this, client, builder); } inherits(SchemaCompiler, ParentClient.prototype.SchemaCompiler); function TableBuilder(client, method, tableName, fn) { TableBuilder.super_.call(this, client, method, tableName, fn); } inherits(TableBuilder, ParentClient.prototype.TableBuilder); function TableCompiler(client, tableBuilder) { TableCompiler.super_.call(this, client, tableBuilder); } inherits(TableCompiler, ParentClient.prototype.TableCompiler); function ColumnBuilder(client, tableBuilder, type, args) { ColumnBuilder.super_.call(this, client, tableBuilder, type, args); } inherits(ColumnBuilder, ParentClient.prototype.ColumnBuilder); function ColumnCompiler(client, tableCompiler, columnBuilder) { ColumnCompiler.super_.call(this, client, tableCompiler, columnBuilder); } inherits(ColumnCompiler, ParentClient.prototype.ColumnCompiler); assign(Client.prototype, { Formatter: Formatter, QueryBuilder: QueryBuilder, SchemaBuilder: SchemaBuilder, SchemaCompiler: SchemaCompiler, TableBuilder: TableBuilder, TableCompiler: TableCompiler, ColumnBuilder: ColumnBuilder, ColumnCompiler: ColumnCompiler }); return Client; }; /***/ }, /* 5 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var EventEmitter = __webpack_require__(43).EventEmitter; var assign = __webpack_require__(29); var Migrator = __webpack_require__(25); var Seeder = __webpack_require__(25); var FunctionHelper = __webpack_require__(27); var QueryInterface = __webpack_require__(28); var helpers = __webpack_require__(2); var Promise = __webpack_require__(8); var _ = __webpack_require__(11); module.exports = function makeKnex(client) { // The object we're potentially using to kick off an initial chain. function knex(tableName) { var qb = knex.queryBuilder(); if (!tableName) { helpers.warn('calling knex without a tableName is deprecated. Use knex.queryBuilder() instead.'); } return tableName ? qb.table(tableName) : qb; } assign(knex, { Promise: __webpack_require__(8), // A new query builder instance queryBuilder: function queryBuilder() { return client.queryBuilder(); }, raw: function raw() { return client.raw.apply(client, arguments); }, batchInsert: function batchInsert(table, batch) { var chunkSize = arguments.length <= 2 || arguments[2] === undefined ? 1000 : arguments[2]; if (!_.isNumber(chunkSize) || chunkSize < 1) { throw new TypeError("Invalid chunkSize: " + chunkSize); } return this.transaction(function (tr) { //Avoid unnecessary call if (chunkSize !== 1) { batch = _.chunk(batch, chunkSize); } return Promise.all(batch.map(function (items) { return tr(table).insert(items); })); }); }, // Runs a new transaction, taking a container and returning a promise // for when the transaction is resolved. transaction: function transaction(container, config) { return client.transaction(container, config); }, // Typically never needed, initializes the pool for a knex client. initialize: function initialize(config) { return client.initialize(config); }, // Convenience method for tearing down the pool. destroy: function destroy(callback) { return client.destroy(callback); } }); // The `__knex__` is used if you need to duck-type check whether this // is a knex builder, without a full on `instanceof` check. knex.VERSION = knex.__knex__ = '0.10.0'; // Hook up the "knex" object as an EventEmitter. var ee = new EventEmitter(); for (var key in ee) { knex[key] = ee[key]; } // Allow chaining methods from the root object, before // any other information is specified. QueryInterface.forEach(function (method) { knex[method] = function () { var builder = knex.queryBuilder(); return builder[method].apply(builder, arguments); }; }); knex.client = client; Object.defineProperties(knex, { schema: { get: function get() { return client.schemaBuilder(); } }, migrate: { get: function get() { return new Migrator(knex); } }, seed: { get: function get() { return new Seeder(knex); } }, fn: { get: function get() { return new FunctionHelper(client); } } }); // Passthrough all "start" and "query" events to the knex object. client.on('start', function (obj) { knex.emit('start', obj); }); client.on('query', function (obj) { knex.emit('query', obj); }); client.on('query-error', function (err, obj) { knex.emit('query-error', err, obj); }); client.makeKnex = function (client) { return makeKnex(client); }; return knex; }; /***/ }, /* 6 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); exports['default'] = parseConnectionString; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _url = __webpack_require__(45); var _url2 = _interopRequireDefault(_url); var _pgConnectionString = __webpack_require__(46); function parseConnectionString(str) { var parsed = _url2['default'].parse(str); var protocol = parsed.protocol; if (protocol && protocol.indexOf('maria') === 0) { protocol = 'maria'; } if (protocol === null) { return { client: 'sqlite3', connection: { filename: str } }; } if (protocol.slice(-1) === ':') { protocol = protocol.slice(0, -1); } return { client: protocol, connection: protocol === 'postgres' ? (0, _pgConnectionString.parse)(str) : connectionObject(parsed) }; } function connectionObject(parsed) { var connection = {}; var db = parsed.pathname; if (db[0] === '/') { db = db.slice(1); } if (parsed.protocol.indexOf('maria') === 0) { connection.db = db; } else { connection.database = db; } if (parsed.hostname) { connection.host = parsed.hostname; } if (parsed.port) { connection.port = parsed.port; } if (parsed.auth) { var idx = parsed.auth.indexOf(':'); if (idx !== -1) { connection.user = parsed.auth.slice(0, idx); if (idx < parsed.auth.length - 1) { connection.password = parsed.auth.slice(idx + 1); } } } return connection; } module.exports = exports['default']; /***/ }, /* 7 */ /***/ function(module, exports, __webpack_require__) { var map = { "./maria/index.js": 34, "./mssql/index.js": 35, "./mysql/index.js": 36, "./mysql2/index.js": 37, "./oracle/index.js": 38, "./postgres/index.js": 39, "./sqlite3/index.js": 40, "./strong-oracle/index.js": 41, "./websql/index.js": 9 }; function webpackContext(req) { return __webpack_require__(webpackContextResolve(req)); }; function webpackContextResolve(req) { return map[req] || (function() { throw new Error("Cannot find module '" + req + "'.") }()); }; webpackContext.keys = function webpackContextKeys() { return Object.keys(map); }; webpackContext.resolve = webpackContextResolve; module.exports = webpackContext; webpackContext.id = 7; /***/ }, /* 8 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var Promise = __webpack_require__(12); var deprecate = __webpack_require__(2).deprecate; // Incase we're using an older version of bluebird Promise.prototype.asCallback = Promise.prototype.nodeify; Promise.prototype.exec = function (cb) { deprecate('.exec', '.nodeify or .asCallback'); return this.nodeify(cb); }; module.exports = Promise; /***/ }, /* 9 */ /***/ function(module, exports, __webpack_require__) { // WebSQL // ------- 'use strict'; var inherits = __webpack_require__(47); var _ = __webpack_require__(11); var Transaction = __webpack_require__(42); var Client_SQLite3 = __webpack_require__(40); var Promise = __webpack_require__(8); var assign = __webpack_require__(29); function Client_WebSQL(config) { Client_SQLite3.call(this, config); this.name = config.name || 'knex_database'; this.version = config.version || '1.0'; this.displayName = config.displayName || this.name; this.estimatedSize = config.estimatedSize || 5 * 1024 * 1024; } inherits(Client_WebSQL, Client_SQLite3); assign(Client_WebSQL.prototype, { Transaction: Transaction, dialect: 'websql', // Get a raw connection from the database, returning a promise with the connection object. acquireConnection: function acquireConnection() { var client = this; return new Promise(function (resolve, reject) { try { /*jslint browser: true*/ var db = openDatabase(client.name, client.version, client.displayName, client.estimatedSize); db.transaction(function (t) { t.__knexUid = _.uniqueId('__knexUid'); resolve(t); }); } catch (e) { reject(e); } }); }, // Used to explicitly close a connection, called internally by the pool // when a connection times out or the pool is shutdown. releaseConnection: function releaseConnection() { return Promise.resolve(); }, // Runs the query on the specified connection, // providing the bindings and any other necessary prep work. _query: function _query(connection, obj) { return new Promise(function (resolver, rejecter) { if (!connection) return rejecter(new Error('No connection provided.')); connection.executeSql(obj.sql, obj.bindings, function (trx, response) { obj.response = response; return resolver(obj); }, function (trx, err) { rejecter(err); }); }); }, _stream: function _stream(connection, sql, stream) { var client = this; return new Promise(function (resolver, rejecter) { stream.on('error', rejecter); stream.on('end', resolver); return client._query(connection, sql).then(function (obj) { return client.processResponse(obj); }).map(function (row) { stream.write(row); })['catch'](function (err) { stream.emit('error', err); }).then(function () { stream.end(); }); }); }, processResponse: function processResponse(obj, runner) { var resp = obj.response; if (obj.output) return obj.output.call(runner, resp); switch (obj.method) { case 'pluck': case 'first': case 'select': var results = []; for (var i = 0, l = resp.rows.length; i < l; i++) { results[i] = _.clone(resp.rows.item(i)); } if (obj.method === 'pluck') results = _.pluck(results, obj.pluck); return obj.method === 'first' ? results[0] : results; case 'insert': return [resp.insertId]; case 'delete': case 'update': case 'counter': return resp.rowsAffected; default: return resp; } } }); module.exports = Client_WebSQL; /***/ }, /* 10 */ /***/ function(module, exports, __webpack_require__) { // shim for using process in browser var process = module.exports = {}; var queue = []; var draining = false; function drainQueue() { if (draining) { return; } draining = true; var currentQueue; var len = queue.length; while(len) { currentQueue = queue; queue = []; var i = -1; while (++i < len) { currentQueue[i](); } len = queue.length; } draining = false; } process.nextTick = function (fun) { queue.push(fun); if (!draining) { setTimeout(drainQueue, 0); } }; process.title = 'browser'; process.browser = true; process.env = {}; process.argv = []; process.version = ''; // empty string to avoid regexp issues process.versions = {}; function noop() {} process.on = noop; process.addListener = noop; process.once = noop; process.off = noop; process.removeListener = noop; process.removeAllListeners = noop; process.emit = noop; process.binding = function (name) { throw new Error('process.binding is not supported'); }; // TODO(shtylman) process.cwd = function () { return '/' }; process.chdir = function (dir) { throw new Error('process.chdir is not supported'); }; process.umask = function() { return 0; }; /***/ }, /* 11 */ /***/ function(module, exports, __webpack_require__) { module.exports = __WEBPACK_EXTERNAL_MODULE_11__; /***/ }, /* 12 */ /***/ function(module, exports, __webpack_require__) { module.exports = __WEBPACK_EXTERNAL_MODULE_12__; /***/ }, /* 13 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var helpers = __webpack_require__(2); module.exports = function (Target) { var _ = __webpack_require__(11); Target.prototype.toQuery = function (tz) { var data = this.toSQL(this._method); if (!_.isArray(data)) data = [data]; return _.map(data, function (statement) { return this._formatQuery(statement.sql, statement.bindings, tz); }, this).join(';\n'); }; // Format the query as sql, prepping bindings as necessary. Target.prototype._formatQuery = function (sql, bindings, tz) { if (this.client && this.client.prepBindings) { bindings = this.client.prepBindings(bindings, tz); } return this.client.SqlString.format(sql, bindings, tz); }; // Create a new instance of the `Runner`, passing in the current object. Target.prototype.then = function () /* onFulfilled, onRejected */{ var result = this.client.runner(this).run(); return result.then.apply(result, arguments); }; // Add additional "options" to the builder. Typically used for client specific // items, like the `mysql` and `sqlite3` drivers. Target.prototype.options = function (opts) { this._options = this._options || []; this._options.push(_.clone(opts) || {}); this._cached = undefined; return this; }; // Sets an explicit "connnection" we wish to use for this query. Target.prototype.connection = function (connection) { this._connection = connection; return this; }; // Set a debug flag for the current schema query stack. Target.prototype.debug = function (enabled) { this._debug = arguments.length ? enabled : true; return this; }; // Set the transaction object for this query. Target.prototype.transacting = function (t) { if (t && t.client) { if (!t.client.transacting) { helpers.warn('Invalid transaction value: ' + t.client); } else { this.client = t.client; } } return this; }; // Initializes a stream. Target.prototype.stream = function (options) { return this.client.runner(this).stream(options); }; // Initialize a stream & pipe automatically. Target.prototype.pipe = function (writable, options) { return this.client.runner(this).pipe(writable, options); }; // Creates a method which "coerces" to a promise, by calling a // "then" method on the current `Target` _.each(['bind', 'catch', 'finally', 'asCallback', 'spread', 'map', 'reduce', 'tap', 'thenReturn', 'return', 'yield', 'ensure', 'nodeify', 'exec'], function (method) { Target.prototype[method] = function () { var then = this.then(); then = then[method].apply(then, arguments); return then; }; }); }; /***/ }, /* 14 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _ = __webpack_require__(11); var Promise = __webpack_require__(8); var assign = __webpack_require__(29); var PassThrough; // The "Runner" constructor takes a "builder" (query, schema, or raw) // and runs through each of the query statements, calling any additional // "output" method provided alongside the query and bindings. function Runner(client, builder) { this.client = client; this.builder = builder; this.queries = []; // The "connection" object is set on the runner when // "run" is called. this.connection = void 0; } assign(Runner.prototype, { // "Run" the target, calling "toSQL" on the builder, returning // an object or array of queries to run, each of which are run on // a single connection. run: function run() { var runner = this; return Promise.using(this.ensureConnection(), function (connection) { runner.connection = connection; runner.client.emit('start', runner.builder); runner.builder.emit('start', runner.builder); var sql = runner.builder.toSQL(); if (runner.builder._debug) { console.log(sql); } if (_.isArray(sql)) { return runner.queryArray(sql); } return runner.query(sql); }) // If there are any "error" listeners, we fire an error event // and then re-throw the error to be eventually handled by // the promise chain. Useful if you're wrapping in a custom `Promise`. ['catch'](function (err) { if (runner.builder._events && runner.builder._events.error) { runner.builder.emit('error', err); } throw err; }) // Fire a single "end" event on the builder when // all queries have successfully completed. .tap(function () { runner.builder.emit('end'); }); }, // Stream the result set, by passing through to the dialect's streaming // capabilities. If the options are stream: function stream(options, handler) { // If we specify stream(handler).then(... if (arguments.length === 1) { if (typeof options === 'function') { handler = options; options = {}; } } // Determines whether we emit an error or throw here. var hasHandler = typeof handler === 'function'; // Lazy-load the "PassThrough" dependency. PassThrough = PassThrough || __webpack_require__(111).PassThrough; var runner = this; var stream = new PassThrough({ objectMode: true }); var promise = Promise.using(this.ensureConnection(), function (connection) { runner.connection = connection; var sql = runner.builder.toSQL(); var err = new Error('The stream may only be used with a single query statement.'); if (_.isArray(sql)) { if (hasHandler) throw err; stream.emit('error', err); } return runner.client.stream(runner.connection, sql, stream, options); }); // If a function is passed to handle the stream, send the stream // there and return the promise, otherwise just return the stream // and the promise will take care of itsself. if (hasHandler) { handler(stream); return promise; } return stream; }, // Allow you to pipe the stream to a writable stream. pipe: function pipe(writable, options) { return this.stream(options).pipe(writable); }, // "Runs" a query, returning a promise. All queries specified by the builder are guaranteed // to run in sequence, and on the same connection, especially helpful when schema building // and dealing with foreign key constraints, etc. query: Promise.method(function (obj) { this.builder.emit('query', assign({ __knexUid: this.connection.__knexUid }, obj)); var runner = this; return this.client.query(this.connection, obj).then(function (resp) { return runner.client.processResponse(resp, runner); }); }), // In the case of the "schema builder" we call `queryArray`, which runs each // of the queries in sequence. queryArray: function queryArray(queries) { return queries.length === 1 ? this.query(queries[0]) : Promise.bind(this)['return'](queries).reduce(function (memo, query) { return this.query(query).then(function (resp) { memo.push(resp); return memo; }); }, []); }, // Check whether there's a transaction flag, and that it has a connection. ensureConnection: function ensureConnection() { var runner = this; var acquireConnectionTimeout = runner.client.config.acquireConnectionTimeout || 60000; return Promise['try'](function () { return runner.connection || new Promise(function (resolver, rejecter) { runner.client.acquireConnection().timeout(acquireConnectionTimeout).then(resolver)['catch'](Promise.TimeoutError, function (error) { var timeoutError = new Error('Knex: Timeout acquiring a connection. The pool is probably full. Are you missing a .transacting(trx) call?'); var additionalErrorInformation = { timeoutStack: error.stack }; if (runner.builder) { additionalErrorInformation.sql = runner.builder.sql; additionalErrorInformation.bindings = runner.builder.bindings; } assign(timeoutError, additionalErrorInformation); rejecter(timeoutError); })['catch'](rejecter); }); }).disposer(function () { if (runner.connection.__knex__disposed) return; runner.client.releaseConnection(runner.connection); }); } }); module.exports = Runner; /***/ }, /* 15 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var QueryBuilder = __webpack_require__(17); var Raw = __webpack_require__(1); var assign = __webpack_require__(29); var transform = __webpack_require__(58); function Formatter(client) { this.client = client; this.bindings = []; } assign(Formatter.prototype, { // Accepts a string or array of columns to wrap as appropriate. columnize: function columnize(target) { var columns = typeof target === 'string' ? [target] : target; var str = '', i = -1; while (++i < columns.length) { if (i > 0) str += ', '; str += this.wrap(columns[i]); } return str; }, // Turns a list of values into a list of ?'s, joining them with commas unless // a "joining" value is specified (e.g. ' and ') parameterize: function parameterize(values, notSetValue) { if (typeof values === 'function') return this.parameter(values); values = Array.isArray(values) ? values : [values]; var str = '', i = -1; while (++i < values.length) { if (i > 0) str += ', '; str += this.parameter(values[i] === undefined ? notSetValue : values[i]); } return str; }, // Checks whether a value is a function... if it is, we compile it // otherwise we check whether it's a raw parameter: function parameter(value) { if (typeof value === 'function') { return this.outputQuery(this.compileCallback(value), true); } return this.unwrapRaw(value, true) || '?'; }, unwrapRaw: function unwrapRaw(value, isParameter) { var query; if (value instanceof QueryBuilder) { query = this.client.queryCompiler(value).toSQL(); if (query.bindings) { this.bindings = this.bindings.concat(query.bindings); } return this.outputQuery(query, isParameter); } if (value instanceof Raw) { value.client = this.client; query = value.toSQL(); if (query.bindings) { this.bindings = this.bindings.concat(query.bindings); } return query.sql; } if (isParameter) { this.bindings.push(value); } }, rawOrFn: function rawOrFn(value, method) { if (typeof value === 'function') { return this.outputQuery(this.compileCallback(value, method)); } return this.unwrapRaw(value) || ''; }, // Puts the appropriate wrapper around a value depending on the database // engine, unless it's a knex.raw value, in which case it's left alone. wrap: function wrap(value) { var raw; if (typeof value === 'function') { return this.outputQuery(this.compileCallback(value), true); } raw = this.unwrapRaw(value); if (raw) return raw; if (typeof value === 'number') return value; return this._wrapString(value + ''); }, wrapAsIdentifier: function wrapAsIdentifier(value) { return this.client.wrapIdentifier((value || '').trim()); }, alias: function alias(first, second) { return first + ' as ' + second; }, // The operator method takes a value and returns something or other. operator: function operator(value) { var raw = this.unwrapRaw(value); if (raw) return raw; if (operators[(value || '').toLowerCase()] !== true) { throw new TypeError('The operator "' + value + '" is not permitted'); } return value; }, // Specify the direction of the ordering. direction: function direction(value) { var raw = this.unwrapRaw(value); if (raw) return raw; return orderBys.indexOf((value || '').toLowerCase()) !== -1 ? value : 'asc'; }, // Compiles a callback using the query builder. compileCallback: function compileCallback(callback, method) { var client = this.client; // Build the callback var builder = client.queryBuilder(); callback.call(builder, builder); // Compile the callback, using the current formatter (to track all bindings). var compiler = client.queryCompiler(builder); compiler.formatter = this; // Return the compiled & parameterized sql. return compiler.toSQL(method || 'select'); }, // Ensures the query is aliased if necessary. outputQuery: function outputQuery(compiled, isParameter) { var sql = compiled.sql || ''; if (sql) { if (compiled.method === 'select' && (isParameter || compiled.as)) { sql = '(' + sql + ')'; if (compiled.as) return this.alias(sql, this.wrap(compiled.as)); } } return sql; }, // Coerce to string to prevent strange errors when it's not a string. _wrapString: function _wrapString(value) { var segments, asIndex = value.toLowerCase().indexOf(' as '); if (asIndex !== -1) { var first = value.slice(0, asIndex); var second = value.slice(asIndex + 4); return this.alias(this.wrap(first), this.wrapAsIdentifier(second)); } var i = -1, wrapped = []; segments = value.split('.'); while (++i < segments.length) { value = segments[i]; if (i === 0 && segments.length > 1) { wrapped.push(this.wrap((value || '').trim())); } else { wrapped.push(this.client.wrapIdentifier((value || '').trim())); } } return wrapped.join('.'); } }); // Valid values for the `order by` clause generation. var orderBys = ['asc', 'desc']; // Turn this into a lookup map var operators = transform(['=', '<', '>', '<=', '>=', '<>', '!=', 'like', 'not like', 'between', 'ilike', '&', '|', '^', '<<', '>>', 'rlike', 'regexp', 'not regexp', '~', '~*', '!~', '!~*', '#', '&&', '@>', '<@', '||'], function (obj, key) { obj[key] = true; }, Object.create(null)); module.exports = Formatter; /***/ }, /* 16 */ /***/ function(module, exports, __webpack_require__) { // Transaction // ------- 'use strict'; var Promise = __webpack_require__(8); var EventEmitter = __webpack_require__(43).EventEmitter; var inherits = __webpack_require__(47); var makeKnex = __webpack_require__(5); var assign = __webpack_require__(29); var uniqueId = __webpack_require__(33); var debug = __webpack_require__(48)('knex:tx'); // Acts as a facade for a Promise, keeping the internal state // and managing any child transactions. function Transaction(client, container, config, outerTx) { var _this = this; var txid = this.txid = uniqueId('trx'); this.client = client; this.outerTx = outerTx; this.trxClient = undefined; this._debug = client.config && client.config.debug; debug('%s: Starting %s transaction', txid, outerTx ? 'nested' : 'top level'); this._promise = Promise.using(this.acquireConnection(client, config, txid), function (connection) { var trxClient = _this.trxClient = makeTxClient(_this, client, connection); var init = client.transacting ? _this.savepoint(connection) : _this.begin(connection); init.then(function () { return makeTransactor(_this, connection, trxClient); }).then(function (transactor) { var result = container(transactor); // If we've returned a "thenable" from the transaction container, // and it's got the transaction object we're running for this, assume // the rollback and commit are chained to this object's success / failure. if (result && result.then && typeof result.then === 'function') { result.then(function (val) { transactor.commit(val); })['catch'](function (err) { transactor.rollback(err); }); } })['catch'](function (e) { return _this._rejecter(e); }); return new Promise(function (resolver, rejecter) { _this._resolver = resolver; _this._rejecter = rejecter; }); }); this._completed = false; // If there is more than one child transaction, // we queue them, executing each when the previous completes. this._childQueue = []; // The queue is a noop unless we have child promises. this._queue = this._queue || Promise.resolve(true); // If there's a wrapping transaction, we need to see if there are // any current children in the pending queue. if (outerTx) { // If there are other promises pending, we just wait until that one // settles (commit or rollback) and then we can continue. if (outerTx._childQueue.length > 0) { this._queue = this._queue.then(function () { return Promise.settle(outerTx._childQueue[outerTx._childQueue.length - 1]); }); } // Push the current promise onto the queue of promises. outerTx._childQueue.push(this._promise); } } inherits(Transaction, EventEmitter); assign(Transaction.prototype, { isCompleted: function isCompleted() { return this._completed || this.outerTx && this.outerTx.isCompleted() || false; }, begin: function begin(conn) { return this.query(conn, 'BEGIN;'); }, savepoint: function savepoint(conn) { return this.query(conn, 'SAVEPOINT ' + this.txid + ';'); }, commit: function commit(conn, value) { return this.query(conn, 'COMMIT;', 1, value); }, release: function release(conn, value) { return this.query(conn, 'RELEASE SAVEPOINT ' + this.txid + ';', 1, value); }, rollback: function rollback(conn, error) { return this.query(conn, 'ROLLBACK;', 2, error); }, rollbackTo: function rollbackTo(conn, error) { return this.query(conn, 'ROLLBACK TO SAVEPOINT ' + this.txid, 2, error); }, query: function query(conn, sql, status, value) { var _this2 = this; var q = this.trxClient.query(conn, sql)['catch'](function (err) { status = 2; value = err; _this2._completed = true; debug('%s error running transaction query', _this2.txid); }).tap(function () { if (sta