UNPKG

pg-mem

Version:

A memory version of postgres

1,600 lines (1,573 loc) 573 kB
(function(e, a) { for(var i in a) e[i] = a[i]; }(exports, /******/ (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] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.l = 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; /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { enumerable: true, get: getter }); /******/ } /******/ }; /******/ /******/ // define __esModule on exports /******/ __webpack_require__.r = function(exports) { /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); /******/ } /******/ Object.defineProperty(exports, '__esModule', { value: true }); /******/ }; /******/ /******/ // create a fake namespace object /******/ // mode & 1: value is a module id, require it /******/ // mode & 2: merge all properties of value into the ns /******/ // mode & 4: return value when already ns object /******/ // mode & 8|1: behave like require /******/ __webpack_require__.t = function(value, mode) { /******/ if(mode & 1) value = __webpack_require__(value); /******/ if(mode & 8) return value; /******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value; /******/ var ns = Object.create(null); /******/ __webpack_require__.r(ns); /******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value }); /******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key)); /******/ return ns; /******/ }; /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 38); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __exportStar = (this && this.__exportStar) || function(m, exports) { for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); }; Object.defineProperty(exports, "__esModule", { value: true }); exports.NewColumn = exports.EmtpyTable = exports.GLOBAL_VARS = void 0; exports.getId = getId; exports.setId = setId; exports.asIndex = asIndex; exports.asType = asType; exports.asSeq = asSeq; exports.asTable = asTable; exports.asSelectable = asSelectable; exports.asView = asView; const interfaces_1 = __webpack_require__(3); const immutable_1 = __webpack_require__(17); __exportStar(__webpack_require__(3), exports); exports.GLOBAL_VARS = Symbol('_global_vars'); // export type PrimaryKey = string | number; const ID = Symbol('_id'); function getId(item) { if (!item) { return ''; } const got = item[ID]; if (!got) { throw new Error('Unexpected: cannot get an ID of something which is not a record'); } return got; } function setId(item, id) { const got = item[ID]; if (got === id) { return item; } if (got) { throw new Error('Unexpected: Cannot update an ID'); } item[ID] = id; return item; } exports.EmtpyTable = (0, immutable_1.Record)({ serials: (0, immutable_1.Map)(), it: 0, indexByHash: (0, immutable_1.Map)(), indexByName: (0, immutable_1.Map)(), columnsByName: (0, immutable_1.Map)(), }); exports.NewColumn = (0, immutable_1.Record)({ default: null, notNull: false, usedInIndexes: (0, immutable_1.Set)(), type: null, name: null, }); function asIndex(o) { if (!o) { return null; } if (o.type === 'index') { return o; } throw new interfaces_1.QueryError(`"${o.name}" is not an index`); } function asType(o) { if (!o) { return null; } if (o.type === 'type') { return o; } throw new interfaces_1.QueryError(`"${o.name}" is not a type`); } function asSeq(o) { if (!o) { return null; } if (o.type === 'sequence') { return o; } throw new interfaces_1.QueryError(`"${o.name}" is not a sequence`); } function asTable(o, nullIfNotType) { if (!o) { return null; } if (o.type === 'table') { return o; } if (nullIfNotType) { return null; } throw new interfaces_1.QueryError(`"${o.name}" is not a table`); } function asSelectable(o, nullIfNotType) { if (!o) { return null; } if (o.type === 'table' || o.type === 'view') { return o; } if (nullIfNotType) { return null; } throw new interfaces_1.QueryError(`"${o.name}" is not selectable`); } function asView(o, nullIfNotType) { if (!o) { return null; } if (o.type === 'view') { return o; } if (nullIfNotType) { return null; } throw new interfaces_1.QueryError({ code: '42809', error: `"${o.name}" is not a view`, }); } /***/ }), /* 1 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.AsyncQueue = exports.delay = exports.IteratorHelper = exports.doRequire = void 0; exports.trimNullish = trimNullish; exports.watchUse = watchUse; exports.deepEqual = deepEqual; exports.deepCompare = deepCompare; exports.queryJson = queryJson; exports.buildLikeMatcher = buildLikeMatcher; exports.nullIsh = nullIsh; exports.hasNullish = hasNullish; exports.sum = sum; exports.deepCloneSimple = deepCloneSimple; exports.isSelectAllArgList = isSelectAllArgList; exports.ignore = ignore; exports.combineSubs = combineSubs; exports.executionCtx = executionCtx; exports.hasExecutionCtx = hasExecutionCtx; exports.isTopLevelExecutionContext = isTopLevelExecutionContext; exports.pushExecutionCtx = pushExecutionCtx; exports.indexHash = indexHash; exports.randomString = randomString; exports.schemaOf = schemaOf; exports.isType = isType; exports.suggestColumnName = suggestColumnName; exports.findTemplate = findTemplate; exports.compareVersions = compareVersions; exports.intervalToSec = intervalToSec; exports.parseRegClass = parseRegClass; exports.parseTime = parseTime; exports.colByName = colByName; exports.colToStr = colToStr; exports.qnameToStr = qnameToStr; exports.asSingleName = asSingleName; exports.asSingleQName = asSingleQName; exports.errorMessage = errorMessage; exports.it = it; exports.fromEntries = fromEntries; exports.notNil = notNil; exports.modifyIfNecessary = modifyIfNecessary; exports.lazySync = lazySync; exports.timeoutOrImmediate = timeoutOrImmediate; const moment_1 = __importDefault(__webpack_require__(18)); const immutable_1 = __webpack_require__(17); const interfaces_private_1 = __webpack_require__(0); const pgsql_ast_parser_1 = __webpack_require__(12); const interfaces_1 = __webpack_require__(3); const buffer_node_1 = __webpack_require__(19); exports.doRequire = typeof require !== 'undefined' ? require : false ? undefined : __webpack_require__(41); function trimNullish(value, depth = 5) { if (depth < 0) return value; if (value instanceof Array) { value.forEach(x => trimNullish(x, depth - 1)); } if (typeof value !== 'object' || value instanceof Date || moment_1.default.isMoment(value) || moment_1.default.isDuration(value)) return value; if (!value) { return value; } for (const k of Object.keys(value)) { const val = value[k]; if (nullIsh(val)) delete value[k]; else trimNullish(val, depth - 1); } return value; } function watchUse(rootValue) { var _c, _d; if (!rootValue || typeof globalThis !== 'undefined' && ((_d = (_c = globalThis === null || globalThis === void 0 ? void 0 : globalThis.process) === null || _c === void 0 ? void 0 : _c.env) === null || _d === void 0 ? void 0 : _d['NOCHECKFULLQUERYUSAGE']) === 'true') { return { checked: rootValue }; } if (typeof rootValue !== 'object') { throw new interfaces_private_1.NotSupported(); } if (Array.isArray(rootValue)) { throw new interfaces_private_1.NotSupported(); } const toUse = new Map(); function recurse(value, stack = (0, immutable_1.List)()) { if (!value || typeof value !== 'object') { return value; } if (Array.isArray(value)) { return value .map((x, i) => recurse(x, stack.push(`[${i}]`))); } // watch object const ret = {}; for (const [k, _v] of Object.entries(value)) { if (k[0] === '_') { // ignore properties starting with '_' ret[k] = _v; continue; } const nstack = stack.push('.' + k); let v = recurse(_v, nstack); const nstackKey = nstack.join(''); toUse.set(nstackKey, _v); Object.defineProperty(ret, k, { get() { toUse.delete(nstackKey); return v; }, enumerable: true, }); } return ret; } const final = recurse(rootValue); const check = function () { if (toUse.size) { return `The query you ran generated an AST which parts have not been read by the query planner. \ This means that those parts could be ignored: ⇨ ` + [...toUse.entries()] .map(([k, v]) => k + ' (' + JSON.stringify(v) + ')') .join('\n ⇨ '); } return null; }; return { checked: final, check }; } function deepEqual(a, b, strict, depth = 10, numberDelta = 0.0001) { return deepCompare(a, b, strict, depth, numberDelta) === 0; } function deepCompare(a, b, strict, depth = 10, numberDelta = 0.0001) { if (depth < 0) { throw new interfaces_private_1.NotSupported('Comparing too deep entities'); } if (a === b) { return 0; } if (!strict) { // should not use '==' because it could call .toString() on objects when compared to strings. // ... which is not ok. Especially when working with translatable objects, which .toString() returns a transaltion (a string, thus) if (!a && !b) { return 0; } } if (Array.isArray(a)) { if (!Array.isArray(b)) { return -1; // [] < {} } if (a.length !== b.length) { return a.length > b.length ? 1 : -1; } for (let i = 0; i < a.length; i++) { const inner = deepCompare(a[i], b[i], strict, depth - 1, numberDelta); if (inner) return inner; } return 0; } if (Array.isArray(b)) { return 1; } if ((0, buffer_node_1.isBuf)(a) || (0, buffer_node_1.isBuf)(b)) { if (!(0, buffer_node_1.isBuf)(a)) { return 1; } if (!(0, buffer_node_1.isBuf)(b)) { return -1; } return (0, buffer_node_1.bufCompare)(a, b); } // handle dates if (a instanceof Date || b instanceof Date || moment_1.default.isMoment(a) || moment_1.default.isMoment(b)) { const am = (0, moment_1.default)(a); const bm = (0, moment_1.default)(b); if (am.isValid() !== bm.isValid()) { return am.isValid() ? -1 : 1; } const diff = am.diff(bm, 'seconds'); if (Math.abs(diff) < 0.001) { return 0; } return diff > 0 ? 1 : -1; } // handle durations if (moment_1.default.isDuration(a) || moment_1.default.isDuration(b)) { const da = moment_1.default.duration(a); const db = moment_1.default.duration(b); if (da.isValid() !== db.isValid()) { return da.isValid() ? -1 : 1; } const diff = da.asMilliseconds() - db.asMilliseconds(); if (Math.abs(diff) < 1) { return 0; } return diff > 0 ? 1 : -1; } const fa = Number.isFinite(a); const fb = Number.isFinite(b); if (fa && fb) { if (Math.abs(a - b) <= numberDelta) { return 0; } return a > b ? 1 : -1; } else if (fa && b) { return -1; } else if (fb && a) { return 1; } // === handle plain objects if (typeof a !== 'object') { return 1; // objects are at the end } if (typeof b !== 'object') { return -1; // objects are at the end } if (!a || !b) { return 0; // nulls } const ak = Object.keys(a); const bk = Object.keys(b); if (strict && ak.length !== bk.length) { // longer objects at the end return ak.length > bk.length ? 1 : -1; } const set = strict ? Object.keys(a) : new Set([...Object.keys(a), ...Object.keys(b)]); for (const k of set) { const inner = deepCompare(a[k], b[k], strict, depth - 1, numberDelta); if (inner) { return inner; } } return 0; } function queryJson(a, b) { if (!a || !b) { return (a !== null && a !== void 0 ? a : null) === (b !== null && b !== void 0 ? b : null); } if (a === b) { return true; } if (typeof a === 'string' || typeof b === 'string') { return false; } if (typeof a === 'number' || typeof b === 'number') { return false; } if (Array.isArray(a)) { // expecting array if (!Array.isArray(b)) { return false; } // => must match all those criteria const toMatch = [...a]; for (const be of b) { for (let i = 0; i < toMatch.length; i++) { if (queryJson(toMatch[i], be)) { // matched this criteria toMatch.splice(i, 1); break; } } if (!toMatch.length) { break; } } return !toMatch.length; } if (Array.isArray(b)) { return false; } if ((typeof a === 'object') !== (typeof b === 'object')) { return false; } const akeys = Object.keys(a); const bkeys = Object.keys(b); if (akeys.length > bkeys.length) { return false; } for (const ak of akeys) { if (!(ak in b)) { return false; } if (!queryJson(a[ak], b[ak])) { return false; } } return true; } function buildLikeMatcher(likeCondition, caseSensitive = true) { // Escape regex characters from likeCondition likeCondition = likeCondition.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&'); let likeRegexString = likeCondition.replace(/\%/g, ".*").replace(/_/g, '.'); likeRegexString = "^" + likeRegexString + "$"; const reg = new RegExp(likeRegexString, caseSensitive ? '' : 'i'); return (stringToMatch) => { if (nullIsh(stringToMatch)) { return null; } if (typeof stringToMatch != "string") { stringToMatch = stringToMatch.toString(); } return reg.test(stringToMatch); }; } function nullIsh(v) { return v === null || v === undefined; } function hasNullish(...vals) { return vals.some(v => nullIsh(v)); } function sum(v) { return v.reduce((sum, el) => sum + el, 0); } function deepCloneSimple(v, noSymbols) { if (!v || typeof v !== 'object' || v instanceof Date) { return v; } if (Array.isArray(v)) { return v.map(x => deepCloneSimple(x)); } if ((0, buffer_node_1.isBuf)(v)) { return (0, buffer_node_1.bufClone)(v); } const ret = {}; for (const k of Object.keys(v)) { ret[k] = deepCloneSimple(v[k]); } if (!noSymbols) { for (const k of Object.getOwnPropertySymbols(v)) { ret[k] = v[k]; // no need to deep clone that } } return ret; } function isSelectAllArgList(select) { const [first] = select; return select.length === 1 && first.type === 'ref' && first.name === '*' && !first.table; } function ignore(...val) { for (const v of val) { if (!v) { continue; } if (Array.isArray(v)) { ignore(...v); continue; } if (typeof v !== 'object') { continue; } ignore(...Object.values(v)); } } function combineSubs(...vals) { return { unsubscribe: () => { vals.forEach(u => u === null || u === void 0 ? void 0 : u.unsubscribe()); }, }; } const curCtx = []; function executionCtx() { if (!curCtx.length) { throw new Error('No execution context available'); } return curCtx[curCtx.length - 1]; } function hasExecutionCtx() { return curCtx.length > 0; } function isTopLevelExecutionContext() { return curCtx.length <= 1; } function pushExecutionCtx(ctx, act) { try { curCtx.push(ctx); return act(); } finally { curCtx.pop(); } } function indexHash(vals) { return vals.map(x => typeof x === 'string' ? x : x.hash).sort().join('|'); } function randomString(length = 8, chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ') { var result = ''; for (var i = length; i > 0; --i) result += chars[Math.floor(Math.random() * chars.length)]; return result; } function schemaOf(t) { if (t.kind === 'array') { return schemaOf(t.arrayOf); } return t.schema; } function isType(t) { return !!(t === null || t === void 0 ? void 0 : t[isType.TAG]); } isType.TAG = Symbol(); function suggestColumnName(expr) { if (!expr) { return null; } // suggest a column result name switch (expr.type) { case 'call': return expr.function.name; case 'ref': return expr.name; case 'keyword': return expr.keyword; case 'cast': return (0, interfaces_1.typeDefToStr)(expr.to); } return null; } function findTemplate(selection, t, template, columns) { // === Build an SQL AST expression that matches // this template let expr; for (const [k, v] of Object.entries(template !== null && template !== void 0 ? template : {})) { let right; if (nullIsh(v)) { // handle { myprop: null } right = { type: 'unary', op: 'IS NULL', operand: { type: 'ref', name: k, }, }; } else { let value; let op = '='; switch (typeof v) { case 'number': // handle {myprop: 42} value = Number.isInteger(v) ? { type: 'integer', value: v } : { type: 'numeric', value: v }; break; case 'string': // handle {myprop: 'blah'} value = { type: 'string', value: v }; break; case 'object': // handle {myprop: new Date()} if (moment_1.default.isMoment(v)) { value = { type: 'string', value: v.toISOString() }; } else if (v instanceof Date) { value = { type: 'string', value: (0, moment_1.default)(v).toISOString() }; } else { // handle {myprop: {obj: "test"}} op = '@>'; value = { type: 'string', value: JSON.stringify(v), }; } break; default: throw new Error(`Object type of property "${k}" not supported in template`); } right = { type: 'binary', op, left: { type: 'ref', name: k, }, right: value }; } expr = !expr ? right : { type: 'binary', op: 'AND', left: expr, right, }; } // === perform filter let ret = selection .filter(expr); if (columns) { ret = ret.select(columns.map(x => ({ expr: { type: 'ref', name: x }, }))); } return ret.enumerate(t); } function ver(v) { if (!v || !/^\d+(\.\d+)+$/.test(v)) { throw new Error('Invalid semver ' + v); } return v.split(/\./g).map(x => parseInt(x, 10)); } function compareVersions(_a, _b) { const a = ver(_a); const b = ver(_b); const m = Math.max(a.length, b.length); for (let i = 0; i < m; i++) { const d = (b[i] || 0) - (a[i] || 0); if (d !== 0) { return d; } } return 0; } function intervalToSec(v) { var _c, _d, _e, _f, _g, _h, _j; return ((_c = v.milliseconds) !== null && _c !== void 0 ? _c : 0) / 1000 + ((_d = v.seconds) !== null && _d !== void 0 ? _d : 0) + ((_e = v.minutes) !== null && _e !== void 0 ? _e : 0) * 60 + ((_f = v.hours) !== null && _f !== void 0 ? _f : 0) * 3600 + ((_g = v.days) !== null && _g !== void 0 ? _g : 0) * 3600 * 24 + ((_h = v.months) !== null && _h !== void 0 ? _h : 0) * 3600 * 24 * 30 + ((_j = v.years) !== null && _j !== void 0 ? _j : 0) * 3600 * 24 * 30 * 12; } function parseRegClass(_reg) { let reg = _reg; if (typeof reg === 'string' && /^\d+$/.test(reg)) { reg = parseInt(reg); } if (typeof reg === 'number') { return reg; } // todo remove casts after next pgsql-ast-parser release try { const ret = (0, pgsql_ast_parser_1.parse)(reg, 'qualified_name'); return ret; } catch (e) { return { name: reg }; } } const timeReg = /^(\d+):(\d+)(:(\d+))?(\.\d+)?$/; function parseTime(str) { var _c; const [_, a, b, __, c, d] = (_c = timeReg.exec(str)) !== null && _c !== void 0 ? _c : []; if (!_) { throw new interfaces_1.QueryError(`Invalid time format: ` + str); } const ms = d ? parseFloat(d) * 1000 : undefined; let ret; if (c) { ret = moment_1.default.utc({ h: parseInt(a, 10), m: parseInt(b, 10), s: parseInt(c, 10), ms, }); } else { if (d) { ret = moment_1.default.utc({ m: parseInt(a, 10), s: parseInt(b, 10), ms, }); } else { ret = moment_1.default.utc({ h: parseInt(a, 10), m: parseInt(b, 10), ms, }); } } if (!ret.isValid()) { throw new interfaces_1.QueryError(`Invalid time format: ` + str); } return ret; } function colByName(refs, ref, nullIfNotFound) { const nm = typeof ref === 'string' ? ref : !ref.table ? ref.name : null; const got = nm ? refs.get(nm) : null; if (!got && !nullIfNotFound) { throw new interfaces_1.ColumnNotFound(colToStr(ref)); } return got; } function colToStr(col) { if (typeof col === 'string') { return col; } if (!col.table) { return col.name; } return col.table.name + '.' + col.name; } function qnameToStr(col) { if (typeof col === 'string') { return col; } if (!col.schema) { return col.name; } return col.schema + '.' + col.name; } function asSingleName(col) { if (typeof col === 'string') { return col; } if (col.table) { return null; } return col.name; } function asSingleQName(col, allowedSchema) { if (typeof col === 'string') { return col; } if (col.schema && col.schema !== allowedSchema) { return null; } return col.name; } function errorMessage(error) { if (typeof error === 'string') { return error; } if (typeof error !== 'object') { return 'Unkown error message'; } return error === null || error === void 0 ? void 0 : error.message; } function it(iterable) { return iterable instanceof IteratorHelper ? iterable : new IteratorHelper(() => iterable); } class IteratorHelper { constructor(underlying) { this.underlying = underlying; } [Symbol.iterator]() { return this.underlying()[Symbol.iterator](); } flatten() { const that = this; function* wrap() { var _c; for (const v of (_c = that.underlying()) !== null && _c !== void 0 ? _c : []) { for (const x of v) { yield x; } } } return new IteratorHelper(wrap); } reduce(callbackfn, initialValue) { let acc = initialValue; let i = 0; for (const v of this.underlying()) { acc = callbackfn(acc, v, i); i++; } return acc; } } exports.IteratorHelper = IteratorHelper; function fromEntries(iterable) { const ret = new Map(); for (const [k, v] of iterable) { ret.set(k, v); } return ret; } function notNil(value) { return (value !== null && value !== void 0 ? value : []).filter((x) => !nullIsh(x)); } /** Modify an array if necessary */ function modifyIfNecessary(values, mapper) { let ret; for (let i = 0; i < values.length; i++) { const mapped = mapper(values[i]); if (nullIsh(mapped)) { continue; } if (!ret) { ret = [...values]; } ret[i] = mapped; } return ret !== null && ret !== void 0 ? ret : values; } function lazySync(ctor) { let cached; let retreived = false; const ret = () => { if (retreived) { return cached; } cached = ctor(); retreived = true; return cached; }; ret.invalidate = () => { retreived = false; cached = undefined; }; return ret; } // see https://github.com/oguimbal/pg-mem/issues/170 function timeoutOrImmediate(fn, time) { if (time || typeof setImmediate === 'undefined') { return setTimeout(fn, time); } // nothing to wait for, but still executing "later" // in case calling code relies on some actual async behavior return setImmediate(fn); } const delay = (time) => new Promise(done => timeoutOrImmediate(done, time !== null && time !== void 0 ? time : 0)); exports.delay = delay; class AsyncQueue { constructor() { this.queue = []; this.processing = false; } // Enqueue a task enqueue(task) { this.queue.push(task); if (!this.processing) { this.processQueue(); } } // Process the queue async processQueue() { if (this.processing) { return; } this.processing = true; while (this.queue.length > 0) { const task = this.queue.shift(); if (task) { try { await task(); } catch (error) { console.error('Error processing task:', error); } } } this.processing = false; } } exports.AsyncQueue = AsyncQueue; /***/ }), /* 2 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __exportStar = (this && this.__exportStar) || function(m, exports) { for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); }; Object.defineProperty(exports, "__esModule", { value: true }); __exportStar(__webpack_require__(14), exports); /***/ }), /* 3 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.PermissionDeniedError = exports.RecordExists = exports.TypeNotFound = exports.RelationNotFound = exports.AmbiguousColumn = exports.ColumnNotFound = exports.CastError = exports.QueryError = exports.NotSupported = exports.AdvancedResult = exports.DataType = void 0; exports.typeDefToStr = typeDefToStr; // todo support all types https://www.postgresql.org/docs/9.5/datatype.html var DataType; (function (DataType) { DataType["inet"] = "inet"; DataType["record"] = "record"; DataType["uuid"] = "uuid"; DataType["text"] = "text"; DataType["citext"] = "citext"; DataType["array"] = "array"; DataType["list"] = "list"; DataType["bigint"] = "bigint"; DataType["float"] = "float"; DataType["decimal"] = "decimal"; DataType["integer"] = "integer"; DataType["jsonb"] = "jsonb"; DataType["regtype"] = "regtype"; DataType["regclass"] = "regclass"; DataType["json"] = "json"; DataType["bytea"] = "bytea"; DataType["interval"] = "interval"; DataType["timestamp"] = "timestamp"; DataType["timestamptz"] = "timestamptz"; DataType["date"] = "date"; DataType["time"] = "time"; DataType["timetz"] = "timetz"; DataType["null"] = "null"; DataType["bool"] = "bool"; DataType["point"] = "point"; DataType["line"] = "line"; DataType["lseg"] = "lseg"; DataType["box"] = "box"; DataType["path"] = "path"; DataType["polygon"] = "polygon"; DataType["circle"] = "circle"; })(DataType || (exports.DataType = DataType = {})); class AdvancedResult { constructor(result, outArgs) { this.result = result; } } exports.AdvancedResult = AdvancedResult; class NotSupported extends Error { constructor(what) { super('🔨 Not supported 🔨 ' + (what ? ': ' + what : '')); } static never(value, msg) { return new NotSupported(`${msg !== null && msg !== void 0 ? msg : ''} ${JSON.stringify(value)}`); } } exports.NotSupported = NotSupported; class QueryError extends Error { constructor(err, code) { super(typeof err === 'string' ? err : errDataToStr(err)); if (typeof err === 'string') { this.data = { error: err, code }; this.code = code; } else { this.data = err; this.code = err.code; } } } exports.QueryError = QueryError; function errDataToStr(data) { const ret = ['ERROR: ' + data.error]; if (data.details) { ret.push('DETAIL: ' + data.details); } if (data.hint) { ret.push('HINT: ' + data.hint); } return ret.join('\n'); } class CastError extends QueryError { constructor(from, to, inWhat) { super(`cannot cast type ${typeof from === 'string' ? from : from.name} to ${typeof to === 'string' ? to : to.name}` + (inWhat ? ' in ' + inWhat : '')); } } exports.CastError = CastError; class ColumnNotFound extends QueryError { constructor(col) { super(`column "${col}" does not exist`); } } exports.ColumnNotFound = ColumnNotFound; class AmbiguousColumn extends QueryError { constructor(col) { super(`column reference "${col}" is ambiguous`); } } exports.AmbiguousColumn = AmbiguousColumn; class RelationNotFound extends QueryError { constructor(tableName) { super(`relation "${tableName}" does not exist`); } } exports.RelationNotFound = RelationNotFound; class TypeNotFound extends QueryError { constructor(t) { super(`type "${typeof t !== 'object' ? t : typeDefToStr(t)}" does not exist`); } } exports.TypeNotFound = TypeNotFound; class RecordExists extends QueryError { constructor() { super('Records already exists'); } } exports.RecordExists = RecordExists; class PermissionDeniedError extends QueryError { constructor(what) { super(what ? `permission denied: "${what}" is a system catalog` : 'permission denied'); } } exports.PermissionDeniedError = PermissionDeniedError; function typeDefToStr(t) { var _a; if (t.kind === 'array') { return typeDefToStr(t.arrayOf) + '[]'; } let ret = t.name; if (t.schema) { ret = t.schema + '.' + ret; } if ((_a = t.config) === null || _a === void 0 ? void 0 : _a.length) { ret = ret + '(' + t.config.join(',') + ')'; } return ret; } /***/ }), /* 4 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.withNameResolver = exports.withParameters = exports.withStatement = exports.withSelection = void 0; exports.buildCtx = buildCtx; exports.withBindingScope = withBindingScope; exports.resolveName = resolveName; const interfaces_private_1 = __webpack_require__(0); class StackOf { constructor(name) { this.name = name; this.stack = []; this.usingValue = (value, act) => { this.stack.push(value); try { return act(); } finally { this.stack.pop(); } }; } get current() { if (!this.stack.length) { throw new Error(`No ${this.name} available`); } return this.stack[this.stack.length - 1]; } get currentOrNil() { return this.stack[this.stack.length - 1]; } } const _selectionStack = new StackOf('build context'); const _statementStack = new StackOf('execution statement'); const _tempBindings = new StackOf('binding context'); const _parametersStack = new StackOf('parameter context'); const _nameResolver = new StackOf('name resolver'); class Context { constructor() { this.onFinishExecution = (callback) => { _statementStack.current.onExecuted(callback); }; this.getTempBinding = (name) => { var _a; const ret = (_a = _tempBindings.currentOrNil) === null || _a === void 0 ? void 0 : _a.get(name); if (ret === 'no returning') { throw new interfaces_private_1.QueryError(`WITH query "${name}" does not have a RETURNING clause`); } return ret; }; this.setTempBinding = (name, boundTo) => { if (_tempBindings.current.has(name)) { throw new interfaces_private_1.QueryError(`WITH query name "${name}" specified more than once`); } _tempBindings.current.set(name, boundTo.isExecutionWithNoResult ? 'no returning' : boundTo); }; this.getParameter = (nameOrPosition) => { var _a; const params = _parametersStack.currentOrNil; if (!params) { return null; } if (typeof nameOrPosition === 'number') { const ret = params[nameOrPosition]; if (!ret) { // not ideal... (duplicated error message) throw new interfaces_private_1.QueryError(`bind message supplies ${params.length} parameters, but prepared statement "" requires ${nameOrPosition}`, '08P01'); } return ret.value; } return (_a = params.find(p => { var _a; return ((_a = p.value) === null || _a === void 0 ? void 0 : _a.id) === nameOrPosition; })) === null || _a === void 0 ? void 0 : _a.value; }; this.setParameterType = (position, type) => { const params = _parametersStack.currentOrNil; if (!params || !params[position]) { throw new Error(`Parameter ${position} not found`); } params[position].inferedType = type; }; } get selection() { return _selectionStack.current; } get db() { return _selectionStack.current.db; } get schema() { // remove the concept of selection schema ? // (does not make much sens, if you think about it) return _selectionStack.current.ownerSchema; } } const _buildCtx = new Context(); function buildCtx() { return _buildCtx; } exports.withSelection = _selectionStack.usingValue; exports.withStatement = _statementStack.usingValue; function withBindingScope(act) { return _tempBindings.usingValue(new Map(), act); } exports.withParameters = _parametersStack.usingValue; exports.withNameResolver = _nameResolver.usingValue; function resolveName(name) { for (let i = _nameResolver.stack.length - 1; i >= 0; i--) { const resolver = _nameResolver.stack[i]; const found = resolver.resolve(name); if (found) { return found; } if (resolver.isolated) { return null; } } return null; } /***/ }), /* 5 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.FilterBase = exports.TransformBase = exports.DataSourceBase = void 0; exports.initialize = initialize; const restrictive_index_1 = __webpack_require__(52); let fns; function initialize(init) { fns = init; } class DataSourceBase { isAggregation() { return false; } // abstract get name(): string; get db() { return this.ownerSchema.db; } constructor(ownerSchema) { this.ownerSchema = ownerSchema; } listColumns() { return this.columns; } listSelectableIdentities() { return this.columns; } select(select) { let sel; if (select === null || select === void 0 ? void 0 : select.some(v => typeof v === 'string')) { sel = select.map(v => typeof v !== 'string' ? v : { expr: { type: 'ref', name: v }, }); } else { sel = select; } return fns.buildSelection(this, sel); } selectAlias(alias) { return null; } filter(filter) { if (!filter) { return this; } const plan = fns.buildFilter(this, filter, 'WHERE'); return plan; } groupBy(grouping) { if (!(grouping === null || grouping === void 0 ? void 0 : grouping.length)) { return this; } const plan = fns.buildGroupBy(this, grouping); return plan; } setAlias(alias) { return fns.buildAlias(this, alias); } limit(limit) { if (!(limit === null || limit === void 0 ? void 0 : limit.limit) && !(limit === null || limit === void 0 ? void 0 : limit.offset)) { return this; } return fns.buildLimit(this, limit); } orderBy(orderBy) { if (!(orderBy === null || orderBy === void 0 ? void 0 : orderBy.length)) { return this; } return fns.buildOrderBy(this, orderBy); } distinct(exprs) { return fns.buildDistinct(this, exprs); } union(right) { return fns.buildUnion(this, right); } } exports.DataSourceBase = DataSourceBase; class TransformBase extends DataSourceBase { constructor(base) { super(base.ownerSchema); this.base = base; } get isExecutionWithNoResult() { return false; } entropy(t) { return this.base.entropy(t); } isOriginOf(a) { var _a; return a.origin === this || ((_a = this.base) === null || _a === void 0 ? void 0 : _a.isOriginOf(a)); } } exports.TransformBase = TransformBase; class FilterBase extends TransformBase { isAggregation() { return false; } constructor(_base) { super(_base); } get columns() { return this.base.columns; } selectAlias(alias) { // this is a filter... that the alias returned by the unfiltered datasource will // be valid for the filtered datasource (aliases are only listing columns) return this.base.selectAlias(alias); } getColumn(column, nullIfNotFound) { if (!this.base) { // istanbul ignore next throw new Error('Should not call .getColumn() on join'); } if (!('columns' in this.base)) { // istanbul ignore next throw new Error('Should not call getColumn() on table'); } return this.base.getColumn(column, nullIfNotFound); } getIndex(...forValue) { const index = this.base.getIndex(...forValue); if (!index) { return null; } return new restrictive_index_1.RestrictiveIndex(index, this); } } exports.FilterBase = FilterBase; /***/ }), /* 6 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.buildValue = buildValue; exports.uncache = uncache; exports.buildBinaryValue = buildBinaryValue; exports.sqlSubstring = sqlSubstring; const utils_1 = __webpack_require__(1); const interfaces_1 = __webpack_require__(3); const object_hash_1 = __importDefault(__webpack_require__(15)); const evaluator_1 = __webpack_require__(13); const datatypes_1 = __webpack_require__(2); const lru_cache_1 = __importDefault(__webpack_require__(22)); const aggregation_1 = __webpack_require__(23); const moment_1 = __importDefault(__webpack_require__(18)); const clean_results_1 = __webpack_require__(16); const context_1 = __webpack_require__(4); const select_1 = __webpack_require__(11); const builtLru = new lru_cache_1.default({ max: 30, }); function buildValue(val) { const ret = _buildValue(val); checkNotUntypedArray(ret); return ret; } function checkNotUntypedArray(value) { // A bit ugly: check that this is not a non typed array (empty array) // see https://github.com/oguimbal/pg-mem/issues/64 // + corresponding UTs const type = value.type; if (type instanceof datatypes_1.ArrayType && type.of == datatypes_1.Types.null) { throw new interfaces_1.QueryError(`cannot determine type of empty array`); } } function uncache(data) { builtLru.del(data); } function _buildValue(val) { // cache expressions build (they almost are always rebuilt several times in a row) const data = (0, context_1.buildCtx)().selection; let selLru = builtLru.get(data !== null && data !== void 0 ? data : null); let got; if (selLru) { got = selLru.get(val); if (got) { return got; } } got = _buildValueReal(val); if (data.isAggregation()) { got = data.checkIfIsKey(got); } if (!selLru) { builtLru.set(data !== null && data !== void 0 ? data : null, selLru = new lru_cache_1.default({ max: 50, })); } selLru.set(val, got); return got; } function _buildValueReal(val) { var _a; const { schema, getParameter, setParameterType, selection } = (0, context_1.buildCtx)(); switch (val.type) { case 'binary': if (val.op === 'IN' || val.op === 'NOT IN') { return buildIn(val.left, val.right, val.op === 'IN'); } return buildBinary(val); case 'unary': return buildUnary(val.op, val.operand); case 'ref': // try to get a column reference // todo refactor getColumn() to NameResolvers const found = selection.getColumn(val, true); if (found) { return found; } // try to get a parameter reference const arg = !val.table && getParameter(val.name); if (arg) { return arg; } // try to select an aliased record (= a table) const alias = !val.table && selection.selectAlias(val.name); if (alias) { return buildRecord(alias); } throw new interfaces_1.ColumnNotFound((0, utils_1.colToStr)(val)); case 'string': return evaluator_1.Value.text(val.value); case 'null': return evaluator_1.Value.null(); case 'list': case 'array': const vals = val.expressions.map(x => _buildValue(x)); return val.type === 'list' ? evaluator_1.Value.list(vals) : evaluator_1.Value.array(vals); case 'numeric': return evaluator_1.Value.number(val.value); case 'integer': return evaluator_1.Value.number(val.value, datatypes_1.Types.integer); case 'call': return _buildCall(val); case 'cast': return _buildValue(val.operand) .cast(schema.getType(val.to)); case 'case': return buildCase(val); case 'member': return buildMember(val); case 'arrayIndex': return buildArrayIndex(val); case 'boolean': return evaluator_1.Value.bool(val.value); case 'ternary': return buildTernary(val); case 'select': case 'union': case 'union all': case 'with': case 'with recursive': case 'values': return buildSelectAsArray(val); case 'array select': return buildSelectAsArray(val.select); case 'constant': return evaluator_1.Value.constant(val.dataType, val.value); case 'keyword': return buildKeyword(val, []); case 'parameter': const [_, n] = (_a = /^\$(\d+)$/.exec(val.name)) !== null && _a !== void 0 ? _a : []; if (!n) { throw new Error('Unexpected parameter ref shape: ' + val.name); } const idx = parseInt(n) - 1; const p = getParameter(idx); if (!p) { return new evaluator_1.Evaluator(datatypes_1.Types.text(), null, Math.random().toString() // must not be indexable => always different hash , [] // no dependency , () => { var _a; const value = (_a = (0, utils_1.executionCtx)().parametersValues) === null || _a === void 0 ? void 0 : _a[idx]; if (value === undefined) { throw new interfaces_1.QueryError(`Parameter $${n} not found`, '42P02'); } return value; }, { forceNotConstant: true, actAsConstantLiteral: true, unpure: true, onCast: toType => { // register the type of the parameter setParameterType(idx, toType); } }); } return p; case 'extract': return