node-pg-migrate
Advanced tools
Comparing version 3.11.0 to 3.12.0
# Change Log | ||
## [3.12.0](2018-10-24) | ||
### Added | ||
- Shorthand can reference other shorthands [#346](https://github.com/salsita/node-pg-migrate/pull/346) | ||
## [3.11.0](2018-09-11) | ||
@@ -4,0 +10,0 @@ |
"use strict"; | ||
function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; } | ||
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } | ||
function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } | ||
/* | ||
This file just manages the database connection and provides a query method | ||
*/ | ||
const pg = require("pg"); | ||
// or native libpq bindings | ||
const pg = require("pg"); // or native libpq bindings | ||
// const pg = require("pg/native"); | ||
module.exports = (connectionString, log = console.error) => { | ||
const client = new pg.Client(connectionString); | ||
let clientActive = false; | ||
@@ -24,2 +24,3 @@ const beforeCloseListeners = []; | ||
} | ||
clientActive = true; | ||
@@ -29,5 +30,8 @@ return resolve(); | ||
const query = (() => { | ||
const query = | ||
/*#__PURE__*/ | ||
function () { | ||
var _ref = _asyncToGenerator(function* (...args) { | ||
yield createConnection(); | ||
try { | ||
@@ -38,4 +42,4 @@ return yield client.query(...args); | ||
position = err.position; | ||
const string = args[0].text || args[0]; | ||
const string = args[0].text || args[0]; | ||
if (message && position >= 1) { | ||
@@ -60,2 +64,3 @@ const endLineWrapIndexOf = string.indexOf("\n", position); | ||
} | ||
throw err; | ||
@@ -68,10 +73,11 @@ } | ||
}; | ||
})(); | ||
}(); | ||
const select = (() => { | ||
const select = | ||
/*#__PURE__*/ | ||
function () { | ||
var _ref2 = _asyncToGenerator(function* (string) { | ||
var _ref3 = yield query(string); | ||
const _ref3 = yield query(string), | ||
rows = _ref3.rows; | ||
const rows = _ref3.rows; | ||
return rows; | ||
@@ -83,8 +89,9 @@ }); | ||
}; | ||
})(); | ||
const column = (() => { | ||
}(); | ||
const column = | ||
/*#__PURE__*/ | ||
function () { | ||
var _ref4 = _asyncToGenerator(function* (string, columnName) { | ||
return (yield select(string)).map(function (r) { | ||
return r[columnName]; | ||
}); | ||
return (yield select(string)).map(r => r[columnName]); | ||
}); | ||
@@ -95,3 +102,3 @@ | ||
}; | ||
})(); | ||
}(); | ||
@@ -102,13 +109,8 @@ return { | ||
column, | ||
addBeforeCloseListener: listener => beforeCloseListeners.push(listener), | ||
close: function () { | ||
var _close = _asyncToGenerator(function* () { | ||
yield beforeCloseListeners.reduce((promise, listener) => promise.then(listener).catch(err => log(err.stack || err)), Promise.resolve()); | ||
clientActive = false; | ||
close: (() => { | ||
var _ref5 = _asyncToGenerator(function* () { | ||
yield beforeCloseListeners.reduce(function (promise, listener) { | ||
return promise.then(listener).catch(function (err) { | ||
return log(err.stack || err); | ||
}); | ||
}, Promise.resolve()); | ||
clientActive = false; | ||
if (client) { | ||
@@ -120,6 +122,6 @@ client.end(); | ||
return function close() { | ||
return _ref5.apply(this, arguments); | ||
return _close.apply(this, arguments); | ||
}; | ||
})() | ||
}() | ||
}; | ||
}; |
@@ -13,35 +13,46 @@ "use strict"; | ||
*/ | ||
const _require = require("./utils"), | ||
PgLiteral = _require.PgLiteral; | ||
var _require = require("./utils"); | ||
const extensions = require("./operations/extensions"); | ||
const PgLiteral = _require.PgLiteral; | ||
const indexes = require("./operations/indexes"); | ||
const tables = require("./operations/tables"); | ||
const extensions = require("./operations/extensions"); | ||
const indexes = require("./operations/indexes"); | ||
const tables = require("./operations/tables"); | ||
const types = require("./operations/types"); | ||
const roles = require("./operations/roles"); | ||
const functions = require("./operations/functions"); | ||
const triggers = require("./operations/triggers"); | ||
const schemas = require("./operations/schemas"); | ||
const domains = require("./operations/domains"); | ||
const sequences = require("./operations/sequences"); | ||
const operators = require("./operations/operators"); | ||
const policies = require("./operations/policies"); | ||
const views = require("./operations/views"); | ||
const mViews = require("./operations/viewsMaterialized"); | ||
const other = require("./operations/other"); | ||
/* eslint-disable security/detect-non-literal-fs-filename */ | ||
/* eslint-disable security/detect-non-literal-fs-filename */ | ||
module.exports = class MigrationBuilder { | ||
constructor(typeShorthands, db) { | ||
this._steps = []; | ||
this._REVERSE_MODE = false; | ||
// by default, all migrations are wrapped in a transaction | ||
this._use_transaction = true; | ||
this._REVERSE_MODE = false; // by default, all migrations are wrapped in a transaction | ||
// this function wraps each operation within a function that either | ||
this._use_transaction = true; // this function wraps each operation within a function that either | ||
// calls the operation or its reverse, and appends the result (array of sql statements) | ||
// to the steps array | ||
const wrap = operation => (...args) => { | ||
@@ -52,11 +63,11 @@ if (this._REVERSE_MODE && typeof operation.reverse !== "function") { | ||
} | ||
this._steps = this._steps.concat(this._REVERSE_MODE ? operation.reverse(...args) : operation(...args)); | ||
}; | ||
}; // defines the methods that are accessible via pgm in each migrations | ||
// there are some convenience aliases to make usage easier | ||
// defines the methods that are accessible via pgm in each migrations | ||
// there are some convenience aliases to make usage easier | ||
this.createExtension = wrap(extensions.createExtension); | ||
this.dropExtension = wrap(extensions.dropExtension); | ||
this.addExtension = this.createExtension; | ||
this.createTable = wrap(tables.createTable(typeShorthands)); | ||
@@ -66,3 +77,2 @@ this.dropTable = wrap(tables.dropTable); | ||
this.alterTable = wrap(tables.alterTable); | ||
this.addColumns = wrap(tables.addColumns(typeShorthands)); | ||
@@ -74,3 +84,2 @@ this.dropColumns = wrap(tables.dropColumns); | ||
this.dropColumn = this.dropColumns; | ||
this.addConstraint = wrap(tables.addConstraint); | ||
@@ -80,3 +89,2 @@ this.dropConstraint = wrap(tables.dropConstraint); | ||
this.createConstraint = this.addConstraint; | ||
this.createType = wrap(types.createType(typeShorthands)); | ||
@@ -92,7 +100,5 @@ this.dropType = wrap(types.dropType); | ||
this.addTypeValue = wrap(types.addTypeValue); | ||
this.createIndex = wrap(indexes.createIndex); | ||
this.dropIndex = wrap(indexes.dropIndex); | ||
this.addIndex = this.createIndex; | ||
this.createRole = wrap(roles.createRole); | ||
@@ -102,15 +108,11 @@ this.dropRole = wrap(roles.dropRole); | ||
this.renameRole = wrap(roles.renameRole); | ||
this.createFunction = wrap(functions.createFunction(typeShorthands)); | ||
this.dropFunction = wrap(functions.dropFunction(typeShorthands)); | ||
this.renameFunction = wrap(functions.renameFunction(typeShorthands)); | ||
this.createTrigger = wrap(triggers.createTrigger(typeShorthands)); | ||
this.dropTrigger = wrap(triggers.dropTrigger); | ||
this.renameTrigger = wrap(triggers.renameTrigger); | ||
this.createSchema = wrap(schemas.createSchema); | ||
this.dropSchema = wrap(schemas.dropSchema); | ||
this.renameSchema = wrap(schemas.renameSchema); | ||
this.createDomain = wrap(domains.createDomain(typeShorthands)); | ||
@@ -120,3 +122,2 @@ this.dropDomain = wrap(domains.dropDomain); | ||
this.renameDomain = wrap(domains.renameDomain); | ||
this.createSequence = wrap(sequences.createSequence(typeShorthands)); | ||
@@ -126,3 +127,2 @@ this.dropSequence = wrap(sequences.dropSequence); | ||
this.renameSequence = wrap(sequences.renameSequence); | ||
this.createOperator = wrap(operators.createOperator); | ||
@@ -138,3 +138,2 @@ this.dropOperator = wrap(operators.dropOperator); | ||
this.removeFromOperatorFamily = wrap(operators.removeFromOperatorFamily(typeShorthands)); | ||
this.createPolicy = wrap(policies.createPolicy); | ||
@@ -144,3 +143,2 @@ this.dropPolicy = wrap(policies.dropPolicy); | ||
this.renamePolicy = wrap(policies.renamePolicy); | ||
this.createView = wrap(views.createView); | ||
@@ -151,3 +149,2 @@ this.dropView = wrap(views.dropView); | ||
this.renameView = wrap(views.renameView); | ||
this.createMaterializedView = wrap(mViews.createMaterializedView); | ||
@@ -159,11 +156,8 @@ this.dropMaterializedView = wrap(mViews.dropMaterializedView); | ||
this.refreshMaterializedView = wrap(mViews.refreshMaterializedView); | ||
this.sql = wrap(other.sql); | ||
// Other utilities which may be useful | ||
this.sql = wrap(other.sql); // Other utilities which may be useful | ||
// .func creates a string which will not be escaped | ||
// common uses are for PG functions, ex: { ... default: pgm.func('NOW()') } | ||
this.func = PgLiteral.create; | ||
// expose DB so we can access database within transaction | ||
this.func = PgLiteral.create; // expose DB so we can access database within transaction | ||
const wrapDB = operation => (...args) => { | ||
@@ -173,4 +167,6 @@ if (this._REVERSE_MODE) { | ||
} | ||
return operation(...args); | ||
}; | ||
this.db = { | ||
@@ -204,3 +200,4 @@ query: wrapDB(db.query), | ||
} | ||
}; | ||
/* eslint-enable security/detect-non-literal-fs-filename */ |
"use strict"; | ||
function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; } | ||
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } | ||
function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } | ||
/* | ||
@@ -12,5 +14,6 @@ A new Migration is instantiated for each migration file. | ||
*/ | ||
const fs = require("fs"); | ||
const fs = require("fs"); | ||
const mkdirp = require("mkdirp"); | ||
const path = require("path"); | ||
@@ -20,9 +23,6 @@ | ||
var _require = require("./utils"); | ||
const _require = require("./utils"), | ||
getMigrationTableSchema = _require.getMigrationTableSchema; | ||
const getMigrationTableSchema = _require.getMigrationTableSchema; | ||
const SEPARATOR = "_"; | ||
module.exports = class Migration { | ||
@@ -32,17 +32,16 @@ // class method that creates a new migration file by cloning the migration template | ||
// ensure the migrations directory exists | ||
mkdirp.sync(directory); | ||
mkdirp.sync(directory); // file name looks like migrations/1391877300255_migration-title.js | ||
// file name looks like migrations/1391877300255_migration-title.js | ||
const newFile = `${directory}/${Date.now()}${SEPARATOR}${name}.${language}`; | ||
const newFile = `${directory}/${Date.now()}${SEPARATOR}${name}.${language}`; // copy the default migration template to the new file location | ||
// eslint-disable-next-line security/detect-non-literal-fs-filename | ||
// copy the default migration template to the new file location | ||
// eslint-disable-next-line security/detect-non-literal-fs-filename | ||
fs.createReadStream(path.resolve(__dirname, `./migration-template.${language}`) | ||
// eslint-disable-next-line security/detect-non-literal-fs-filename | ||
fs.createReadStream(path.resolve(__dirname, `./migration-template.${language}`) // eslint-disable-next-line security/detect-non-literal-fs-filename | ||
).pipe(fs.createWriteStream(newFile)); | ||
return new Migration(newFile, directory); | ||
} | ||
constructor(db, migrationPath, { up, down } = {}, options = {}, typeShorthands, log = console.log) { | ||
constructor(db, migrationPath, { | ||
up, | ||
down | ||
} = {}, options = {}, typeShorthands, log = console.log) { | ||
this.db = db; | ||
@@ -68,5 +67,7 @@ this.path = migrationPath; | ||
return `DELETE FROM "${schema}"."${migrationsTable}" WHERE name='${name}';`; | ||
case this.up: | ||
this.log(`### MIGRATION ${this.name} (UP) ###`); | ||
return `INSERT INTO "${schema}"."${migrationsTable}" (name, run_on) VALUES ('${name}', NOW());`; | ||
default: | ||
@@ -82,5 +83,3 @@ throw new Error("Unknown direction"); | ||
if (action.length === 2) { | ||
yield new Promise(function (resolve) { | ||
return action(pgm, resolve); | ||
}); | ||
yield new Promise(resolve => action(pgm, resolve)); | ||
} else { | ||
@@ -91,3 +90,2 @@ yield action(pgm); | ||
const sqlSteps = pgm.getSqlSteps(); | ||
sqlSteps.push(_this._getMarkAsRun(action)); | ||
@@ -102,2 +100,3 @@ | ||
_this.log("#> WARNING: Need to break single transaction! <"); | ||
sqlSteps.unshift("COMMIT;"); | ||
@@ -111,7 +110,3 @@ sqlSteps.push("BEGIN;"); | ||
return sqlSteps.reduce(function (promise, sql) { | ||
return promise.then(function () { | ||
return _this.options.dryRun || _this.db.query(sql); | ||
}); | ||
}, Promise.resolve()); | ||
return sqlSteps.reduce((promise, sql) => promise.then(() => _this.options.dryRun || _this.db.query(sql)), Promise.resolve()); | ||
})(); | ||
@@ -142,2 +137,3 @@ } | ||
const pgm = new MigrationBuilder(this.typeShorthands, this.db); | ||
const action = this._getAction(direction); | ||
@@ -156,2 +152,3 @@ | ||
} | ||
}; |
"use strict"; | ||
var _require = require("../utils"); | ||
const template = _require.template, | ||
const _require = require("../utils"), | ||
template = _require.template, | ||
applyType = _require.applyType, | ||
escapeValue = _require.escapeValue; | ||
function dropDomain(domainName, { ifExists, cascade } = {}) { | ||
function dropDomain(domainName, { | ||
ifExists, | ||
cascade | ||
} = {}) { | ||
const ifExistsStr = ifExists ? " IF EXISTS" : ""; | ||
@@ -23,10 +24,12 @@ const cascadeStr = cascade ? " CASCADE" : ""; | ||
constraintName = options.constraintName; | ||
const constraints = []; | ||
const constraints = []; | ||
if (collation) { | ||
constraints.push(`COLLATE ${collation}`); | ||
} | ||
if (defaultValue !== undefined) { | ||
constraints.push(`DEFAULT ${escapeValue(defaultValue)}`); | ||
} | ||
if (notNull && check) { | ||
@@ -38,2 +41,3 @@ throw new Error('"notNull" and "check" can\'t be specified together'); | ||
} | ||
if (notNull) { | ||
@@ -47,8 +51,8 @@ constraints.push("NOT NULL"); | ||
const constraintsStr = constraints.length ? ` ${constraints.join(" ")}` : ""; | ||
const typeStr = applyType(type, typeShorthands).type; | ||
return template`CREATE DOMAIN "${domainName}" AS ${typeStr}${constraintsStr};`; | ||
}; | ||
_create.reverse = (domainName, type, options) => dropDomain(domainName, options); | ||
return _create; | ||
@@ -63,4 +67,4 @@ } | ||
constraintName = options.constraintName; | ||
const actions = []; | ||
const actions = []; | ||
if (defaultValue === null) { | ||
@@ -71,2 +75,3 @@ actions.push("DROP DEFAULT"); | ||
} | ||
if (notNull) { | ||
@@ -77,2 +82,3 @@ actions.push("SET NOT NULL"); | ||
} | ||
if (check) { | ||
@@ -92,3 +98,2 @@ actions.push(`${constraintName ? `CONSTRAINT ${constraintName} ` : ""}CHECK (${check})`); | ||
renameDomain.reverse = undoRename; | ||
module.exports = { | ||
@@ -95,0 +100,0 @@ dropDomain, |
@@ -5,20 +5,25 @@ "use strict"; | ||
var _require = require("../utils"); | ||
const _require = require("../utils"), | ||
template = _require.template; | ||
const template = _require.template; | ||
function createExtension(extensions, { | ||
ifNotExists, | ||
schema | ||
} = {}) { | ||
if (!_.isArray(extensions)) extensions = [extensions]; // eslint-disable-line no-param-reassign | ||
function createExtension(extensions, { ifNotExists, schema } = {}) { | ||
if (!_.isArray(extensions)) extensions = [extensions]; // eslint-disable-line no-param-reassign | ||
return _.map(extensions, extension => template`CREATE EXTENSION${ifNotExists ? " IF NOT EXISTS" : ""} "${extension}"${schema ? ` SCHEMA "${schema}"` : ""};`); | ||
} | ||
function dropExtension(extensions, { ifExists, cascade } = {}) { | ||
function dropExtension(extensions, { | ||
ifExists, | ||
cascade | ||
} = {}) { | ||
if (!_.isArray(extensions)) extensions = [extensions]; // eslint-disable-line no-param-reassign | ||
return _.map(extensions, extension => template`DROP EXTENSION${ifExists ? " IF EXISTS" : ""} "${extension}"${cascade ? " CASCADE" : ""};`); | ||
} | ||
} // setup reverse functions | ||
// setup reverse functions | ||
createExtension.reverse = dropExtension; | ||
module.exports = { | ||
@@ -25,0 +30,0 @@ createExtension, |
"use strict"; | ||
var _require = require("../utils"); | ||
const template = _require.template, | ||
const _require = require("../utils"), | ||
template = _require.template, | ||
escapeValue = _require.escapeValue, | ||
formatParams = _require.formatParams; | ||
function dropFunction(typeShorthands) { | ||
return (functionName, functionParams = [], { ifExists, cascade } = {}) => { | ||
return (functionName, functionParams = [], { | ||
ifExists, | ||
cascade | ||
} = {}) => { | ||
const ifExistsStr = ifExists ? " IF EXISTS" : ""; | ||
@@ -21,16 +22,17 @@ const cascadeStr = cascade ? " CASCADE" : ""; | ||
const _create = (functionName, functionParams = [], functionOptions = {}, definition) => { | ||
const replace = functionOptions.replace; | ||
var _functionOptions$retu = functionOptions.returns; | ||
const returns = _functionOptions$retu === undefined ? "void" : _functionOptions$retu, | ||
const replace = functionOptions.replace, | ||
_functionOptions$retu = functionOptions.returns, | ||
returns = _functionOptions$retu === void 0 ? "void" : _functionOptions$retu, | ||
language = functionOptions.language, | ||
window = functionOptions.window; | ||
var _functionOptions$beha = functionOptions.behavior; | ||
const behavior = _functionOptions$beha === undefined ? "VOLATILE" : _functionOptions$beha, | ||
window = functionOptions.window, | ||
_functionOptions$beha = functionOptions.behavior, | ||
behavior = _functionOptions$beha === void 0 ? "VOLATILE" : _functionOptions$beha, | ||
onNull = functionOptions.onNull, | ||
parallel = functionOptions.parallel; | ||
const options = []; | ||
const options = []; | ||
if (behavior) { | ||
options.push(behavior); | ||
} | ||
if (language) { | ||
@@ -41,8 +43,11 @@ options.push(`LANGUAGE ${language}`); | ||
} | ||
if (window) { | ||
options.push("WINDOW"); | ||
} | ||
if (onNull) { | ||
options.push("RETURNS NULL ON NULL INPUT"); | ||
} | ||
if (parallel) { | ||
@@ -54,3 +59,2 @@ options.push(`PARALLEL ${parallel}`); | ||
const paramsStr = formatParams(functionParams, typeShorthands); | ||
return template`CREATE${replaceStr} FUNCTION "${functionName}"${paramsStr} | ||
@@ -63,3 +67,2 @@ RETURNS ${returns} | ||
_create.reverse = dropFunction(typeShorthands); | ||
return _create; | ||
@@ -66,0 +69,0 @@ } |
@@ -5,7 +5,5 @@ "use strict"; | ||
var _require = require("../utils"); | ||
const _require = require("../utils"), | ||
template = _require.template; | ||
const template = _require.template; | ||
function generateIndexName(table, columns, options) { | ||
@@ -45,3 +43,2 @@ return options.name ? options.name : ((tableName, cols, uniq) => template`${tableName}_${cols}${uniq}_index`)(table, _.isArray(columns) ? columns.join("_") : columns, options.unique ? "_unique" : ""); | ||
const opclass = options.opclass ? ` ${options.opclass}` : ""; | ||
return template`CREATE ${unique} INDEX ${concurrently} "${indexName}" ON "${tableName}"${method} (${columnsString}${opclass})${where};`; | ||
@@ -54,3 +51,2 @@ } | ||
cascade = options.cascade; | ||
const concurrentlyStr = concurrently ? " CONCURRENTLY" : ""; | ||
@@ -60,9 +56,7 @@ const ifExistsStr = ifExists ? " IF EXISTS" : ""; | ||
const cascadeStr = cascade ? " CASCADE" : ""; | ||
return `DROP INDEX${concurrentlyStr}${ifExistsStr} "${indexName}"${cascadeStr};`; | ||
} | ||
} // setup reverse functions | ||
// setup reverse functions | ||
createIndex.reverse = dropIndex; | ||
module.exports = { | ||
@@ -69,0 +63,0 @@ createIndex, |
"use strict"; | ||
var _require = require("../utils"); | ||
const opSchemalize = _require.opSchemalize, | ||
const _require = require("../utils"), | ||
opSchemalize = _require.opSchemalize, | ||
schemalize = _require.schemalize, | ||
@@ -10,3 +9,2 @@ formatParams = _require.formatParams, | ||
const createOperator = (operatorName, options = {}) => { | ||
@@ -22,30 +20,37 @@ const procedure = options.procedure, | ||
merges = options.merges; | ||
const defs = []; | ||
defs.push(`PROCEDURE = ${schemalize(procedure)}`); | ||
if (left) { | ||
defs.push(`LEFTARG = ${schemalize(left)}`); | ||
} | ||
if (right) { | ||
defs.push(`RIGHTARG = ${schemalize(right)}`); | ||
} | ||
if (commutator) { | ||
defs.push(`COMMUTATOR = ${opSchemalize(commutator)}`); | ||
} | ||
if (negator) { | ||
defs.push(`NEGATOR = ${opSchemalize(negator)}`); | ||
} | ||
if (restrict) { | ||
defs.push(`RESTRICT = ${schemalize(restrict)}`); | ||
} | ||
if (join) { | ||
defs.push(`JOIN = ${schemalize(join)}`); | ||
} | ||
if (hashes) { | ||
defs.push("HASHES"); | ||
} | ||
if (merges) { | ||
defs.push("MERGES"); | ||
} | ||
return `CREATE OPERATOR ${opSchemalize(operatorName)} (${defs.join(", ")});`; | ||
@@ -59,11 +64,7 @@ }; | ||
right = options.right; | ||
const operatorNameStr = schemalize(operatorName); | ||
const leftStr = schemalize(left || "none"); | ||
const rightStr = schemalize(right || "none"); | ||
const ifExistsStr = ifExists ? " IF EXISTS" : ""; | ||
const cascadeStr = cascade ? " CASCADE" : ""; | ||
return `DROP OPERATOR${ifExistsStr} ${operatorNameStr}(${leftStr}, ${rightStr})${cascadeStr};`; | ||
@@ -77,3 +78,6 @@ }; | ||
function dropOperatorFamily(operatorFamilyName, indexMethod, { ifExists, cascade } = {}) { | ||
function dropOperatorFamily(operatorFamilyName, indexMethod, { | ||
ifExists, | ||
cascade | ||
} = {}) { | ||
const operatorFamilyNameStr = schemalize(operatorFamilyName); | ||
@@ -95,5 +99,5 @@ const ifExistsStr = ifExists ? " IF EXISTS" : ""; | ||
} | ||
const nameStr = schemalize(name); | ||
const paramsStr = params.length > 0 ? formatParams(params, typeShorthands) : ""; | ||
return `OPERATOR ${number} ${nameStr}${paramsStr}`; | ||
@@ -114,9 +118,10 @@ } | ||
const operatorListStr = operatorList.map(operatorMap(typeShorthands)).join(",\n "); | ||
return `ALTER OPERATOR FAMILY ${operatorFamilyNameStr} USING ${indexMethod} ${op} | ||
${operatorListStr};`; | ||
}; | ||
if (reverse) { | ||
method.reverse = reverse(typeShorthands); | ||
} | ||
return method; | ||
@@ -131,3 +136,2 @@ }; | ||
const newOperatorFamilyNameStr = schemalize(newOperatorFamilyName); | ||
return `ALTER OPERATOR FAMILY ${oldOperatorFamilyNameStr} USING ${indexMethod} RENAME TO ${newOperatorFamilyNameStr};`; | ||
@@ -138,7 +142,9 @@ } | ||
function dropOperatorClass(operatorClassName, indexMethod, { ifExists, cascade } = {}) { | ||
function dropOperatorClass(operatorClassName, indexMethod, { | ||
ifExists, | ||
cascade | ||
} = {}) { | ||
const operatorClassNameStr = schemalize(operatorClassName); | ||
const ifExistsStr = ifExists ? " IF EXISTS" : ""; | ||
const cascadeStr = cascade ? " CASCADE" : ""; | ||
return `DROP OPERATOR CLASS ${ifExistsStr} ${operatorClassNameStr} USING ${indexMethod}${cascadeStr};`; | ||
@@ -151,3 +157,2 @@ } | ||
family = options.family; | ||
const operatorClassNameStr = schemalize(operatorClassName); | ||
@@ -159,7 +164,8 @@ const defaultStr = isDefault ? " DEFAULT" : ""; | ||
const operatorListStr = operatorList.map(operatorMap(typeShorthands)).join(",\n "); | ||
return `CREATE OPERATOR CLASS ${operatorClassNameStr}${defaultStr} FOR TYPE ${typeStr} USING ${indexMethodStr} ${familyStr} AS | ||
${operatorListStr};`; | ||
}; | ||
_create.reverse = (operatorClassName, type, indexMethod, operatorList, options) => dropOperatorClass(operatorClassName, indexMethod, options); | ||
return _create; | ||
@@ -171,9 +177,8 @@ } | ||
const newOperatorClassNameStr = schemalize(newOperatorClassName); | ||
return `ALTER OPERATOR CLASS ${oldOperatorClassNameStr} USING ${indexMethod} RENAME TO ${newOperatorClassNameStr};`; | ||
} | ||
const undoRenameOperatorClass = (oldOperatorClassName, indexMethod, newOperatorClassName) => renameOperatorClass(newOperatorClassName, indexMethod, oldOperatorClassName); | ||
const undoRenameOperatorClass = (oldOperatorClassName, indexMethod, newOperatorClassName) => renameOperatorClass(newOperatorClassName, indexMethod, oldOperatorClassName); // setup reverse functions | ||
// setup reverse functions | ||
createOperator.reverse = dropOperator; | ||
@@ -183,3 +188,2 @@ createOperatorFamily.reverse = dropOperatorFamily; | ||
renameOperatorClass.reverse = undoRenameOperatorClass; | ||
module.exports = { | ||
@@ -186,0 +190,0 @@ createOperator, |
"use strict"; | ||
var _require = require("../utils"); | ||
const _require = require("../utils"), | ||
t = _require.t; | ||
const t = _require.t; | ||
function sql(...args) { | ||
// applies some very basic templating using the utils.p | ||
let s = t(...args); | ||
// add trailing ; if not present | ||
let s = t(...args); // add trailing ; if not present | ||
if (s.lastIndexOf(";") !== s.length - 1) { | ||
s += ";"; | ||
} | ||
return s; | ||
@@ -16,0 +15,0 @@ } |
"use strict"; | ||
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; | ||
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; } | ||
var _require = require("../utils"); | ||
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } | ||
const template = _require.template; | ||
const _require = require("../utils"), | ||
template = _require.template; | ||
const makeClauses = ({ role, using, check }) => { | ||
const makeClauses = ({ | ||
role, | ||
using, | ||
check | ||
}) => { | ||
const roles = (Array.isArray(role) ? role : [role]).join(", "); | ||
const clauses = []; | ||
if (roles) { | ||
clauses.push(`TO ${roles}`); | ||
} | ||
if (using) { | ||
clauses.push(`USING (${using})`); | ||
} | ||
if (check) { | ||
clauses.push(`WITH CHECK (${check})`); | ||
} | ||
return clauses; | ||
@@ -26,5 +34,6 @@ }; | ||
function createPolicy(tableName, policyName, options = {}) { | ||
const createOptions = _extends({}, options, { | ||
const createOptions = _objectSpread({}, options, { | ||
role: options.role || "PUBLIC" | ||
}); | ||
const clauses = [`FOR ${options.command || "ALL"}`, ...makeClauses(createOptions)]; | ||
@@ -40,3 +49,5 @@ const clausesStr = clauses.join(" "); | ||
function dropPolicy(tableName, policyName, { ifExists } = {}) { | ||
function dropPolicy(tableName, policyName, { | ||
ifExists | ||
} = {}) { | ||
const ifExistsStr = ifExists ? " IF EXISTS" : ""; | ||
@@ -50,8 +61,7 @@ return template`DROP POLICY${ifExistsStr} "${policyName}" ON "${tableName}";`; | ||
const undoRename = (tableName, policyName, newPolicyName) => renamePolicy(tableName, newPolicyName, policyName); | ||
const undoRename = (tableName, policyName, newPolicyName) => renamePolicy(tableName, newPolicyName, policyName); // setup reverse functions | ||
// setup reverse functions | ||
createPolicy.reverse = dropPolicy; | ||
renamePolicy.reverse = undoRename; | ||
module.exports = { | ||
@@ -58,0 +68,0 @@ createPolicy, |
"use strict"; | ||
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; | ||
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; } | ||
var _require = require("lodash"); | ||
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } | ||
const isArray = _require.isArray; | ||
const _require = require("lodash"), | ||
isArray = _require.isArray; | ||
var _require2 = require("../utils"); | ||
const template = _require2.template, | ||
const _require2 = require("../utils"), | ||
template = _require2.template, | ||
escapeValue = _require2.escapeValue; | ||
const formatRoleOptions = (roleOptions = {}) => { | ||
const options = []; | ||
if (roleOptions.superuser !== undefined) { | ||
options.push(roleOptions.superuser ? "SUPERUSER" : "NOSUPERUSER"); | ||
} | ||
if (roleOptions.createdb !== undefined) { | ||
options.push(roleOptions.createdb ? "CREATEDB" : "NOCREATEDB"); | ||
} | ||
if (roleOptions.createrole !== undefined) { | ||
options.push(roleOptions.createrole ? "CREATEROLE" : "NOCREATEROLE"); | ||
} | ||
if (roleOptions.inherit !== undefined) { | ||
options.push(roleOptions.inherit ? "INHERIT" : "NOINHERIT"); | ||
} | ||
if (roleOptions.login !== undefined) { | ||
options.push(roleOptions.login ? "LOGIN" : "NOLOGIN"); | ||
} | ||
if (roleOptions.replication !== undefined) { | ||
options.push(roleOptions.replication ? "REPLICATION" : "NOREPLICATION"); | ||
} | ||
if (roleOptions.bypassrls !== undefined) { | ||
options.push(roleOptions.bypassrls ? "BYPASSRLS" : "NOBYPASSRLS"); | ||
} | ||
if (roleOptions.limit) { | ||
options.push(`CONNECTION LIMIT ${Number(roleOptions.limit)}`); | ||
} | ||
if (roleOptions.password !== undefined) { | ||
@@ -45,2 +53,3 @@ const encrypted = roleOptions.encrypted === false ? "UNENCRYPTED" : "ENCRYPTED"; | ||
} | ||
if (roleOptions.valid !== undefined) { | ||
@@ -50,2 +59,3 @@ const valid = roleOptions.valid ? escapeValue(roleOptions.valid) : "'infinity'"; | ||
} | ||
if (roleOptions.inRole) { | ||
@@ -55,2 +65,3 @@ const inRole = isArray(roleOptions.inRole) ? roleOptions.inRole.join(",") : roleOptions.inRole; | ||
} | ||
if (roleOptions.role) { | ||
@@ -60,2 +71,3 @@ const role = isArray(roleOptions.role) ? roleOptions.role.join(",") : roleOptions.role; | ||
} | ||
if (roleOptions.admin) { | ||
@@ -70,3 +82,3 @@ const admin = isArray(roleOptions.admin) ? roleOptions.admin.join(",") : roleOptions.admin; | ||
function createRole(roleName, roleOptions = {}) { | ||
const options = formatRoleOptions(_extends({}, roleOptions, { | ||
const options = formatRoleOptions(_objectSpread({}, roleOptions, { | ||
superuser: roleOptions.superuser || false, | ||
@@ -83,3 +95,5 @@ createdb: roleOptions.createdb || false, | ||
function dropRole(roleName, { ifExists } = {}) { | ||
function dropRole(roleName, { | ||
ifExists | ||
} = {}) { | ||
return template`DROP ROLE${ifExists ? " IF EXISTS" : ""} "${roleName}";`; | ||
@@ -97,8 +111,7 @@ } | ||
const undoRename = (oldRoleName, newRoleName) => renameRole(newRoleName, oldRoleName); | ||
const undoRename = (oldRoleName, newRoleName) => renameRole(newRoleName, oldRoleName); // setup reverse functions | ||
// setup reverse functions | ||
createRole.reverse = dropRole; | ||
renameRole.reverse = undoRename; | ||
module.exports = { | ||
@@ -105,0 +118,0 @@ createRole, |
"use strict"; | ||
var _require = require("../utils"); | ||
const _require = require("../utils"), | ||
template = _require.template; | ||
const template = _require.template; | ||
function dropSchema(schemaName, { ifExists, cascade } = {}) { | ||
function dropSchema(schemaName, { | ||
ifExists, | ||
cascade | ||
} = {}) { | ||
const ifExistsStr = ifExists ? " IF EXISTS" : ""; | ||
@@ -14,3 +15,6 @@ const cascadeStr = cascade ? " CASCADE" : ""; | ||
function createSchema(schemaName, { ifNotExists, authorization } = {}) { | ||
function createSchema(schemaName, { | ||
ifNotExists, | ||
authorization | ||
} = {}) { | ||
const ifNotExistsStr = ifNotExists ? " IF NOT EXISTS" : ""; | ||
@@ -29,3 +33,2 @@ const authorizationStr = authorization ? ` AUTHORIZATION ${authorization}` : ""; | ||
renameSchema.reverse = undoRename; | ||
module.exports = { | ||
@@ -32,0 +35,0 @@ createSchema, |
"use strict"; | ||
var _require = require("../utils"); | ||
const template = _require.template, | ||
const _require = require("../utils"), | ||
template = _require.template, | ||
applyType = _require.applyType; | ||
const parseOptions = (typeShorthands, options) => { | ||
@@ -18,10 +16,12 @@ const type = options.type, | ||
owner = options.owner; | ||
const clauses = []; | ||
const clauses = []; | ||
if (type) { | ||
clauses.push(`AS ${applyType(type, typeShorthands).type}`); | ||
} | ||
if (increment) { | ||
clauses.push(`INCREMENT BY ${increment}`); | ||
} | ||
if (minvalue) { | ||
@@ -32,2 +32,3 @@ clauses.push(`MINVALUE ${minvalue}`); | ||
} | ||
if (maxvalue) { | ||
@@ -38,8 +39,11 @@ clauses.push(`MAXVALUE ${maxvalue}`); | ||
} | ||
if (start) { | ||
clauses.push(`START WITH ${start}`); | ||
} | ||
if (cache) { | ||
clauses.push(`CACHE ${cache}`); | ||
} | ||
if (cycle) { | ||
@@ -50,2 +54,3 @@ clauses.push("CYCLE"); | ||
} | ||
if (owner) { | ||
@@ -56,6 +61,10 @@ clauses.push(`OWNED BY ${owner}`); | ||
} | ||
return clauses; | ||
}; | ||
function dropSequence(sequenceName, { ifExists, cascade } = {}) { | ||
function dropSequence(sequenceName, { | ||
ifExists, | ||
cascade | ||
} = {}) { | ||
const ifExistsStr = ifExists ? " IF EXISTS" : ""; | ||
@@ -70,3 +79,2 @@ const cascadeStr = cascade ? " CASCADE" : ""; | ||
ifNotExists = options.ifNotExists; | ||
const temporaryStr = temporary ? " TEMPORARY" : ""; | ||
@@ -78,2 +86,3 @@ const ifNotExistsStr = ifNotExists ? " IF NOT EXISTS" : ""; | ||
}; | ||
_create.reverse = dropSequence; | ||
@@ -86,4 +95,4 @@ return _create; | ||
const restart = options.restart; | ||
const clauses = parseOptions(typeShorthands, options); | ||
const clauses = parseOptions(typeShorthands, options); | ||
if (restart) { | ||
@@ -96,2 +105,3 @@ if (restart === true) { | ||
} | ||
return template`ALTER SEQUENCE "${sequenceName}" | ||
@@ -109,3 +119,2 @@ ${clauses.join("\n ")};`; | ||
renameSequence.reverse = undoRename; | ||
module.exports = { | ||
@@ -112,0 +121,0 @@ createSequence, |
"use strict"; | ||
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; | ||
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; } | ||
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } | ||
const _ = require("lodash"); | ||
var _require = require("../utils"); | ||
const escapeValue = _require.escapeValue, | ||
const _require = require("../utils"), | ||
escapeValue = _require.escapeValue, | ||
template = _require.template, | ||
@@ -18,3 +19,2 @@ quote = _require.quote, | ||
const parseReferences = options => { | ||
@@ -26,17 +26,22 @@ const references = options.references, | ||
onUpdate = options.onUpdate; | ||
const clauses = []; | ||
const clauses = []; | ||
if (referencesConstraintName) { | ||
clauses.push(`CONSTRAINT "${referencesConstraintName}"`); | ||
} | ||
clauses.push(typeof references === "string" ? `REFERENCES ${references}` : template`REFERENCES "${references}"`); | ||
if (match) { | ||
clauses.push(`MATCH ${match}`); | ||
} | ||
if (onDelete) { | ||
clauses.push(`ON DELETE ${onDelete}`); | ||
} | ||
if (onUpdate) { | ||
clauses.push(`ON UPDATE ${onUpdate}`); | ||
} | ||
return clauses.join(" "); | ||
@@ -48,3 +53,2 @@ }; | ||
deferred = options.deferred; | ||
return deferrable ? `DEFERRABLE INITIALLY ${deferred ? "DEFERRED" : "IMMEDIATE"}` : null; | ||
@@ -57,6 +61,7 @@ }; | ||
const primaryColumns = _.chain(columnsWithOptions).map((options, columnName) => options.primaryKey ? columnName : null).filter().value(); | ||
const multiplePrimaryColumns = primaryColumns.length > 1; | ||
if (multiplePrimaryColumns) { | ||
columnsWithOptions = _.mapValues(columnsWithOptions, options => _extends({}, options, { | ||
columnsWithOptions = _.mapValues(columnsWithOptions, options => _objectSpread({}, options, { | ||
primaryKey: false | ||
@@ -79,25 +84,32 @@ })); | ||
deferrable = options.deferrable; | ||
const constraints = []; | ||
const constraints = []; | ||
if (collation) { | ||
constraints.push(`COLLATE ${collation}`); | ||
} | ||
if (defaultValue !== undefined) { | ||
constraints.push(`DEFAULT ${escapeValue(defaultValue)}`); | ||
} | ||
if (unique) { | ||
constraints.push("UNIQUE"); | ||
} | ||
if (primaryKey) { | ||
constraints.push("PRIMARY KEY"); | ||
} | ||
if (notNull) { | ||
constraints.push("NOT NULL"); | ||
} | ||
if (check) { | ||
constraints.push(`CHECK (${check})`); | ||
} | ||
if (references) { | ||
constraints.push(parseReferences(options)); | ||
} | ||
if (deferrable) { | ||
@@ -108,8 +120,8 @@ constraints.push(parseDeferrable(options)); | ||
const constraintsStr = constraints.length ? ` ${constraints.join(" ")}` : ""; | ||
const sType = typeof type === "object" ? `"${schemalize(type)}"` : type; | ||
return template`"${columnName}" ${sType}${constraintsStr}`; | ||
}), | ||
constraints: _extends({}, multiplePrimaryColumns ? { primaryKey: primaryColumns } : {}), | ||
constraints: _objectSpread({}, multiplePrimaryColumns ? { | ||
primaryKey: primaryColumns | ||
} : {}), | ||
comments | ||
@@ -126,5 +138,5 @@ }; | ||
deferrable = options.deferrable; | ||
const tableName = typeof table === "object" ? table.name : table; | ||
const constraints = []; | ||
if (check) { | ||
@@ -134,2 +146,3 @@ const name = genName ? `CONSTRAINT "${tableName}_chck" ` : ""; | ||
} | ||
if (unique) { | ||
@@ -144,2 +157,3 @@ const uniqueArray = _.isArray(unique) ? unique : [unique]; | ||
} | ||
if (primaryKey) { | ||
@@ -150,6 +164,6 @@ const name = genName ? `CONSTRAINT "${tableName}_pkey" ` : ""; | ||
} | ||
if (foreignKeys) { | ||
(_.isArray(foreignKeys) ? foreignKeys : [foreignKeys]).forEach(fk => { | ||
const columns = fk.columns; | ||
const cols = _.isArray(columns) ? columns : [columns]; | ||
@@ -161,2 +175,3 @@ const name = genName ? `CONSTRAINT "${tableName}_fk_${cols.join("_")}" ` : ""; | ||
} | ||
if (exclude) { | ||
@@ -168,6 +183,9 @@ const name = genName ? `CONSTRAINT "${tableName}_excl" ` : ""; | ||
return deferrable ? constraints.map(constraint => `${constraint} ${parseDeferrable(options)}`) : constraints; | ||
}; | ||
}; // TABLE | ||
// TABLE | ||
function dropTable(tableName, { ifExists, cascade } = {}) { | ||
function dropTable(tableName, { | ||
ifExists, | ||
cascade | ||
} = {}) { | ||
const ifExistsStr = ifExists ? " IF EXISTS" : ""; | ||
@@ -183,15 +201,15 @@ const cascadeStr = cascade ? " CASCADE" : ""; | ||
inherits = options.inherits, | ||
like = options.like; | ||
var _options$constraints = options.constraints; | ||
const optionsConstraints = _options$constraints === undefined ? {} : _options$constraints, | ||
like = options.like, | ||
_options$constraints = options.constraints, | ||
optionsConstraints = _options$constraints === void 0 ? {} : _options$constraints, | ||
tableComment = options.comment; | ||
var _parseColumns = parseColumns(tableName, columns, typeShorthands); | ||
const _parseColumns = parseColumns(tableName, columns, typeShorthands), | ||
columnLines = _parseColumns.columns, | ||
columnsConstraints = _parseColumns.constraints, | ||
_parseColumns$comment = _parseColumns.comments, | ||
columnComments = _parseColumns$comment === void 0 ? [] : _parseColumns$comment; | ||
const columnLines = _parseColumns.columns, | ||
columnsConstraints = _parseColumns.constraints; | ||
var _parseColumns$comment = _parseColumns.comments; | ||
const columnComments = _parseColumns$comment === undefined ? [] : _parseColumns$comment; | ||
const dupes = _.intersection(Object.keys(optionsConstraints), Object.keys(columnsConstraints)); | ||
const dupes = _.intersection(Object.keys(optionsConstraints), Object.keys(columnsConstraints)); | ||
if (dupes.length > 0) { | ||
@@ -202,10 +220,9 @@ const dupesStr = dupes.join(", "); | ||
const constraints = _extends({}, optionsConstraints, columnsConstraints); | ||
const constraints = _objectSpread({}, optionsConstraints, columnsConstraints); | ||
const constraintLines = parseConstraints(tableName, constraints, true); | ||
const tableDefinition = [...columnLines, ...constraintLines].concat(like ? [template`LIKE "${like}"`] : []); | ||
const temporaryStr = temporary ? " TEMPORARY" : ""; | ||
const ifNotExistsStr = ifNotExists ? " IF NOT EXISTS" : ""; | ||
const inheritsStr = inherits ? template` INHERITS ("${inherits}")` : ""; | ||
const createTableQuery = template`CREATE TABLE${temporaryStr}${ifNotExistsStr} "${tableName}" ( | ||
@@ -215,7 +232,10 @@ ${formatLines(tableDefinition)} | ||
const comments = columnComments; | ||
if (typeof tableComment !== "undefined") { | ||
comments.push(comment("TABLE ", tableName, tableComment)); | ||
} | ||
return `${createTableQuery}${comments.length > 0 ? `\n${comments.join("\n")}` : ""}`; | ||
}; | ||
_create.reverse = dropTable; | ||
@@ -227,11 +247,16 @@ return _create; | ||
const alterDefinition = []; | ||
if (options.levelSecurity) { | ||
alterDefinition.push(`${options.levelSecurity} ROW LEVEL SECURITY`); | ||
} | ||
return template`ALTER TABLE "${tableName}" | ||
${formatLines(alterDefinition)};`; | ||
} | ||
} // COLUMNS | ||
// COLUMNS | ||
function dropColumns(tableName, columns, { ifExists, cascade } = {}) { | ||
function dropColumns(tableName, columns, { | ||
ifExists, | ||
cascade | ||
} = {}) { | ||
if (typeof columns === "string") { | ||
@@ -242,2 +267,3 @@ columns = [columns]; // eslint-disable-line no-param-reassign | ||
} | ||
const columnsStr = formatLines(quote(columns), ` DROP ${ifExists ? " IF EXISTS" : ""}`, `${cascade ? " CASCADE" : ""},`); | ||
@@ -250,8 +276,7 @@ return template`ALTER TABLE "${tableName}" | ||
const _add = (tableName, columns) => { | ||
var _parseColumns2 = parseColumns(tableName, columns, typeShorthands); | ||
const _parseColumns2 = parseColumns(tableName, columns, typeShorthands), | ||
columnLines = _parseColumns2.columns, | ||
_parseColumns2$commen = _parseColumns2.comments, | ||
columnComments = _parseColumns2$commen === void 0 ? [] : _parseColumns2$commen; | ||
const columnLines = _parseColumns2.columns; | ||
var _parseColumns2$commen = _parseColumns2.comments; | ||
const columnComments = _parseColumns2$commen === undefined ? [] : _parseColumns2$commen; | ||
const columnsStr = formatLines(columnLines, " ADD "); | ||
@@ -262,2 +287,3 @@ const alterTableQuery = template`ALTER TABLE "${tableName}"\n${columnsStr};`; | ||
}; | ||
_add.reverse = dropColumns; | ||
@@ -275,4 +301,4 @@ return _add; | ||
columnComment = options.comment; | ||
const actions = []; | ||
const actions = []; | ||
if (defaultValue === null) { | ||
@@ -283,2 +309,3 @@ actions.push("DROP DEFAULT"); | ||
} | ||
if (type) { | ||
@@ -290,2 +317,3 @@ const typeStr = applyTypeAdapters(type); | ||
} | ||
if (notNull) { | ||
@@ -298,2 +326,3 @@ actions.push("SET NOT NULL"); | ||
const queries = []; | ||
if (actions.length > 0) { | ||
@@ -303,5 +332,7 @@ const columnsStr = formatLines(actions, ` ALTER "${columnName}" `); | ||
} | ||
if (typeof columnComment !== "undefined") { | ||
queries.push(comment("COLUMN ", template`${tableName}"."${columnName}`, columnComment)); | ||
} | ||
return queries.join("\n"); | ||
@@ -334,3 +365,6 @@ } | ||
function dropConstraint(tableName, constraintName, { ifExists, cascade } = {}) { | ||
function dropConstraint(tableName, constraintName, { | ||
ifExists, | ||
cascade | ||
} = {}) { | ||
const ifExistsStr = ifExists ? " IF EXISTS" : ""; | ||
@@ -346,3 +380,2 @@ const cascadeStr = cascade ? " CASCADE" : ""; | ||
renameTable.reverse = undoRenameTable; | ||
module.exports = { | ||
@@ -349,0 +382,0 @@ createTable, |
"use strict"; | ||
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; | ||
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; } | ||
var _require = require("lodash"); | ||
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } | ||
const isArray = _require.isArray; | ||
const _require = require("lodash"), | ||
isArray = _require.isArray; | ||
var _require2 = require("../utils"); | ||
const escapeValue = _require2.escapeValue, | ||
const _require2 = require("../utils"), | ||
escapeValue = _require2.escapeValue, | ||
template = _require2.template; | ||
var _require3 = require("./functions"); | ||
const createFunction = _require3.createFunction, | ||
const _require3 = require("./functions"), | ||
createFunction = _require3.createFunction, | ||
dropFunction = _require3.dropFunction; | ||
function dropTrigger(tableName, triggerName, { ifExists, cascade } = {}) { | ||
function dropTrigger(tableName, triggerName, { | ||
ifExists, | ||
cascade | ||
} = {}) { | ||
const ifExistsStr = ifExists ? " IF EXISTS" : ""; | ||
@@ -32,18 +33,21 @@ const cascadeStr = cascade ? " CASCADE" : ""; | ||
deferrable = triggerOptions.deferrable, | ||
deferred = triggerOptions.deferred; | ||
var _triggerOptions$funct = triggerOptions.functionArgs; | ||
const functionArgs = _triggerOptions$funct === undefined ? [] : _triggerOptions$funct; | ||
let when = triggerOptions.when; | ||
var _triggerOptions$level = triggerOptions.level; | ||
let level = _triggerOptions$level === undefined ? "STATEMENT" : _triggerOptions$level, | ||
deferred = triggerOptions.deferred, | ||
_triggerOptions$funct = triggerOptions.functionArgs, | ||
functionArgs = _triggerOptions$funct === void 0 ? [] : _triggerOptions$funct; | ||
let when = triggerOptions.when, | ||
_triggerOptions$level = triggerOptions.level, | ||
level = _triggerOptions$level === void 0 ? "STATEMENT" : _triggerOptions$level, | ||
functionName = triggerOptions.function; | ||
const operations = isArray(operation) ? operation.join(" OR ") : operation; | ||
const operations = isArray(operation) ? operation.join(" OR ") : operation; | ||
if (constraint) { | ||
when = "AFTER"; | ||
} | ||
const isInsteadOf = /instead\s+of/i.test(when); | ||
if (isInsteadOf) { | ||
level = "ROW"; | ||
} | ||
if (definition) { | ||
@@ -58,2 +62,3 @@ functionName = functionName || triggerName; | ||
} | ||
if (!operations) { | ||
@@ -67,3 +72,2 @@ throw new Error('"operation" (INSERT/UPDATE[ OF ...]/DELETE/TRUNCATE) have to be specified'); | ||
const paramsStr = functionArgs.map(escapeValue).join(", "); | ||
const triggerSQL = template`CREATE${constraintStr} TRIGGER "${triggerName}" | ||
@@ -73,4 +77,5 @@ ${when} ${operations} ON "${tableName}" | ||
${conditionClause}EXECUTE PROCEDURE "${functionName}"(${paramsStr});`; | ||
const fnSQL = definition ? `${createFunction(typeShorthands)(functionName, [], _extends({}, triggerOptions, { returns: "trigger" }), definition)}\n` : ""; | ||
const fnSQL = definition ? `${createFunction(typeShorthands)(functionName, [], _objectSpread({}, triggerOptions, { | ||
returns: "trigger" | ||
}), definition)}\n` : ""; | ||
return `${fnSQL}${triggerSQL}`; | ||
@@ -95,3 +100,2 @@ }; | ||
renameTrigger.reverse = undoRename; | ||
module.exports = { | ||
@@ -98,0 +102,0 @@ createTrigger, |
@@ -5,10 +5,11 @@ "use strict"; | ||
var _require = require("../utils"); | ||
const template = _require.template, | ||
const _require = require("../utils"), | ||
template = _require.template, | ||
applyType = _require.applyType, | ||
escapeValue = _require.escapeValue; | ||
function dropType(typeName, { ifExists, cascade } = {}) { | ||
function dropType(typeName, { | ||
ifExists, | ||
cascade | ||
} = {}) { | ||
const ifExistsStr = ifExists ? " IF EXISTS" : ""; | ||
@@ -25,2 +26,3 @@ const cascadeStr = cascade ? " CASCADE" : ""; | ||
} | ||
const attributes = _.map(options, (attribute, attributeName) => { | ||
@@ -30,4 +32,6 @@ const typeStr = applyType(attribute, typeShorthands).type; | ||
}).join(",\n"); | ||
return template`CREATE TYPE "${typeName}" AS (\n${attributes}\n);`; | ||
}; | ||
_create.reverse = dropType; | ||
@@ -37,3 +41,5 @@ return _create; | ||
function dropTypeAttribute(typeName, attributeName, { ifExists } = {}) { | ||
function dropTypeAttribute(typeName, attributeName, { | ||
ifExists | ||
} = {}) { | ||
const ifExistsStr = ifExists ? " IF EXISTS" : ""; | ||
@@ -46,5 +52,5 @@ return template`ALTER TYPE "${typeName}" DROP ATTRIBUTE "${attributeName}"${ifExistsStr};`; | ||
const typeStr = applyType(attributeType, typeShorthands).type; | ||
return template`ALTER TYPE "${typeName}" ADD ATTRIBUTE "${attributeName}" ${typeStr};`; | ||
}; | ||
_alterAttributeAdd.reverse = dropTypeAttribute; | ||
@@ -57,3 +63,2 @@ return _alterAttributeAdd; | ||
const typeStr = applyType(attributeType, typeShorthands).type; | ||
return template`ALTER TYPE "${typeName}" ALTER ATTRIBUTE "${attributeName}" SET DATA TYPE ${typeStr};`; | ||
@@ -68,6 +73,6 @@ }; | ||
if (before && after) { | ||
throw new Error('"before" and "after" can\'t be specified together'); | ||
} | ||
const beforeStr = before ? ` BEFORE ${before}` : ""; | ||
@@ -77,3 +82,2 @@ const afterStr = after ? ` AFTER ${after}` : ""; | ||
const valueStr = escapeValue(value); | ||
return template`ALTER TYPE "${typeName}" ADD VALUE${ifNotExistsStr} ${valueStr}${beforeStr}${afterStr};`; | ||
@@ -105,3 +109,2 @@ } | ||
renameTypeValue.reverse = undoRenameTypeValue; | ||
module.exports = { | ||
@@ -108,0 +111,0 @@ createType, |
"use strict"; | ||
var _require = require("../utils"); | ||
const template = _require.template, | ||
const _require = require("../utils"), | ||
template = _require.template, | ||
quote = _require.quote, | ||
escapeValue = _require.escapeValue; | ||
function dropView(viewName, { ifExists, cascade } = {}) { | ||
function dropView(viewName, { | ||
ifExists, | ||
cascade | ||
} = {}) { | ||
const ifExistsStr = ifExists ? " IF EXISTS" : ""; | ||
@@ -19,7 +20,6 @@ const cascadeStr = cascade ? " CASCADE" : ""; | ||
replace = options.replace, | ||
recursive = options.recursive; | ||
var _options$columns = options.columns; | ||
const columns = _options$columns === undefined ? [] : _options$columns, | ||
checkOption = options.checkOption; | ||
// prettier-ignore | ||
recursive = options.recursive, | ||
_options$columns = options.columns, | ||
columns = _options$columns === void 0 ? [] : _options$columns, | ||
checkOption = options.checkOption; // prettier-ignore | ||
@@ -32,3 +32,2 @@ const columnNames = quote(Array.isArray(columns) ? columns : [columns]).join(", "); | ||
const checkOptionStr = checkOption ? ` WITH ${checkOption} CHECK OPTION` : ""; | ||
return template`CREATE${replaceStr}${temporaryStr}${recursiveStr} VIEW "${viewName}"${columnStr} AS ${definition}${checkOptionStr};`; | ||
@@ -39,4 +38,4 @@ } | ||
const checkOption = options.checkOption; | ||
const clauses = []; | ||
const clauses = []; | ||
if (checkOption !== undefined) { | ||
@@ -49,2 +48,3 @@ if (checkOption) { | ||
} | ||
return clauses.map(clause => template`ALTER VIEW "${viewName}" ${clause};`).join("\n"); | ||
@@ -55,4 +55,4 @@ } | ||
const defaultValue = options.default; | ||
const actions = []; | ||
const actions = []; | ||
if (defaultValue === null) { | ||
@@ -63,2 +63,3 @@ actions.push("DROP DEFAULT"); | ||
} | ||
return actions.map(action => template`ALTER VIEW "${viewName}" ALTER COLUMN ${columnName} ${action};`).join("\n"); | ||
@@ -75,3 +76,2 @@ } | ||
renameView.reverse = undoRename; | ||
module.exports = { | ||
@@ -78,0 +78,0 @@ createView, |
"use strict"; | ||
var _require = require("../utils"); | ||
const template = _require.template, | ||
const _require = require("../utils"), | ||
template = _require.template, | ||
quote = _require.quote, | ||
formatLines = _require.formatLines; | ||
const dataClause = data => data !== undefined ? ` WITH${data ? "" : " NO"} DATA` : ""; | ||
const dataClause = data => data !== undefined ? ` WITH${data ? "" : " NO"} DATA` : ""; | ||
const storageParameterStr = storageParameters => key => { | ||
@@ -16,3 +15,6 @@ const value = storageParameters[key] === true ? "" : ` = ${storageParameters[key]}`; | ||
function dropMaterializedView(viewName, { ifExists, cascade } = {}) { | ||
function dropMaterializedView(viewName, { | ||
ifExists, | ||
cascade | ||
} = {}) { | ||
const ifExistsStr = ifExists ? " IF EXISTS" : ""; | ||
@@ -24,14 +26,12 @@ const cascadeStr = cascade ? " CASCADE" : ""; | ||
function createMaterializedView(viewName, options, definition) { | ||
const ifNotExists = options.ifNotExists; | ||
var _options$columns = options.columns; | ||
const columns = _options$columns === undefined ? [] : _options$columns, | ||
tablespace = options.tablespace; | ||
var _options$storageParam = options.storageParameters; | ||
const storageParameters = _options$storageParam === undefined ? {} : _options$storageParam, | ||
data = options.data; | ||
// prettier-ignore | ||
const ifNotExists = options.ifNotExists, | ||
_options$columns = options.columns, | ||
columns = _options$columns === void 0 ? [] : _options$columns, | ||
tablespace = options.tablespace, | ||
_options$storageParam = options.storageParameters, | ||
storageParameters = _options$storageParam === void 0 ? {} : _options$storageParam, | ||
data = options.data; // prettier-ignore | ||
const columnNames = quote(Array.isArray(columns) ? columns : [columns]).join(", "); | ||
const withOptions = Object.keys(storageParameters).map(storageParameterStr(storageParameters)).join(", "); | ||
const ifNotExistsStr = ifNotExists ? " IF NOT EXISTS" : ""; | ||
@@ -42,3 +42,2 @@ const columnsStr = columnNames ? `(${columnNames})` : ""; | ||
const dataStr = dataClause(data); | ||
return template`CREATE MATERIALIZED VIEW${ifNotExistsStr} "${viewName}"${columnsStr}${withOptionsStr}${tablespaceStr} AS ${definition}${dataStr};`; | ||
@@ -49,7 +48,7 @@ } | ||
const cluster = options.cluster, | ||
extension = options.extension; | ||
var _options$storageParam2 = options.storageParameters; | ||
const storageParameters = _options$storageParam2 === undefined ? {} : _options$storageParam2; | ||
extension = options.extension, | ||
_options$storageParam2 = options.storageParameters, | ||
storageParameters = _options$storageParam2 === void 0 ? {} : _options$storageParam2; | ||
const clauses = []; | ||
const clauses = []; | ||
if (cluster !== undefined) { | ||
@@ -62,13 +61,19 @@ if (cluster) { | ||
} | ||
if (extension) { | ||
clauses.push(`DEPENDS ON EXTENSION "${extension}"`); | ||
} | ||
const withOptions = Object.keys(storageParameters).filter(key => storageParameters[key]).map(storageParameterStr(storageParameters)).join(", "); | ||
if (withOptions) { | ||
clauses.push(`SET (${withOptions})`); | ||
} | ||
const resetOptions = Object.keys(storageParameters).filter(key => !storageParameters[key]).join(", "); | ||
if (resetOptions) { | ||
clauses.push(`RESET (${resetOptions})`); | ||
} | ||
const clausesStr = formatLines(clauses); | ||
@@ -90,3 +95,6 @@ return template`ALTER MATERIALIZED VIEW "${viewName}"\n${clausesStr};`; | ||
function refreshMaterializedView(viewName, { concurrently, data } = {}) { | ||
function refreshMaterializedView(viewName, { | ||
concurrently, | ||
data | ||
} = {}) { | ||
const concurrentlyStr = concurrently ? " CONCURRENTLY" : ""; | ||
@@ -101,3 +109,2 @@ const dataStr = dataClause(data); | ||
refreshMaterializedView.reverse = refreshMaterializedView; | ||
module.exports = { | ||
@@ -104,0 +111,0 @@ createMaterializedView, |
"use strict"; | ||
var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }(); | ||
function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); } | ||
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; | ||
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } | ||
function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; } | ||
function _iterableToArrayLimit(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } | ||
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } | ||
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; } | ||
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } | ||
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } | ||
function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } | ||
const path = require("path"); | ||
const fs = require("fs"); | ||
const Db = require("./db"); | ||
const Migration = require("./migration"); | ||
var _require = require("./utils"); | ||
const getMigrationTableSchema = _require.getMigrationTableSchema, | ||
const _require = require("./utils"), | ||
getMigrationTableSchema = _require.getMigrationTableSchema, | ||
template = _require.template, | ||
promisify = _require.promisify, | ||
PgLiteral = _require.PgLiteral; | ||
PgLiteral = _require.PgLiteral; // Random but well-known identifier shared by all instances of node-pg-migrate | ||
// Random but well-known identifier shared by all instances of node-pg-migrate | ||
const PG_MIGRATE_LOCK_ID = 7241865325823964; | ||
const readdir = promisify(fs.readdir); // eslint-disable-line security/detect-non-literal-fs-filename | ||
const readdir = promisify(fs.readdir); // eslint-disable-line security/detect-non-literal-fs-filename | ||
const readFile = promisify(fs.readFile); // eslint-disable-line security/detect-non-literal-fs-filename | ||
const lstat = promisify(fs.lstat); // eslint-disable-line security/detect-non-literal-fs-filename | ||
@@ -33,6 +45,10 @@ | ||
const loadMigrationFiles = (() => { | ||
const loadMigrationFiles = | ||
/*#__PURE__*/ | ||
function () { | ||
var _ref = _asyncToGenerator(function* (db, options, log) { | ||
try { | ||
const files = yield Promise.all((yield readdir(`${options.dir}/`)).map((() => { | ||
const files = yield Promise.all((yield readdir(`${options.dir}/`)).map( | ||
/*#__PURE__*/ | ||
function () { | ||
var _ref2 = _asyncToGenerator(function* (file) { | ||
@@ -46,15 +62,13 @@ const stats = yield lstat(`${options.dir}/${file}`); | ||
}; | ||
})())); | ||
}())); | ||
const filter = new RegExp(`^(${options.ignorePattern})$`); // eslint-disable-line security/detect-non-literal-regexp | ||
let shorthands = {}; | ||
return files.filter(function (i) { | ||
return i && !filter.test(i); | ||
}).sort(function (f1, f2) { | ||
return f1 < f2 // eslint-disable-line no-nested-ternary | ||
? -1 : f1 > f2 ? 1 : 0; | ||
}).map(function (file) { | ||
return files.filter(i => i && !filter.test(i)).sort((f1, f2) => f1 < f2 // eslint-disable-line no-nested-ternary | ||
? -1 : f1 > f2 ? 1 : 0).map(file => { | ||
const filePath = `${options.dir}/${file}`; | ||
const actions = path.extname(filePath) === ".sql" ? // eslint-disable-next-line security/detect-non-literal-fs-filename | ||
{ up: (() => { | ||
var _ref3 = _asyncToGenerator(function* (pgm) { | ||
{ | ||
up: function () { | ||
var _up = _asyncToGenerator(function* (pgm) { | ||
return pgm.sql((yield readFile(filePath, "utf8"))); | ||
@@ -64,8 +78,9 @@ }); | ||
return function up(_x5) { | ||
return _ref3.apply(this, arguments); | ||
return _up.apply(this, arguments); | ||
}; | ||
})() } : // eslint-disable-next-line global-require,import/no-dynamic-require,security/detect-non-literal-require | ||
}() | ||
} : // eslint-disable-next-line global-require,import/no-dynamic-require,security/detect-non-literal-require | ||
require(path.relative(__dirname, filePath)); | ||
shorthands = _extends({}, shorthands, actions.shorthands); | ||
return new Migration(db, filePath, actions, options, _extends({}, shorthands), log); | ||
shorthands = _objectSpread({}, shorthands, actions.shorthands); | ||
return new Migration(db, filePath, actions, options, _objectSpread({}, shorthands), log); | ||
}); | ||
@@ -80,11 +95,12 @@ } catch (err) { | ||
}; | ||
})(); | ||
}(); | ||
const lock = (() => { | ||
var _ref4 = _asyncToGenerator(function* (db) { | ||
var _ref5 = yield db.query(`select pg_try_advisory_lock(${PG_MIGRATE_LOCK_ID}) as "lockObtained"`), | ||
_ref5$rows = _slicedToArray(_ref5.rows, 1); | ||
const lock = | ||
/*#__PURE__*/ | ||
function () { | ||
var _ref3 = _asyncToGenerator(function* (db) { | ||
const _ref4 = yield db.query(`select pg_try_advisory_lock(${PG_MIGRATE_LOCK_ID}) as "lockObtained"`), | ||
_ref4$rows = _slicedToArray(_ref4.rows, 1), | ||
lockObtained = _ref4$rows[0]; | ||
const lockObtained = _ref5$rows[0]; | ||
if (!lockObtained) { | ||
@@ -96,12 +112,13 @@ throw new Error("Another migration is already running"); | ||
return function lock(_x6) { | ||
return _ref4.apply(this, arguments); | ||
return _ref3.apply(this, arguments); | ||
}; | ||
})(); | ||
}(); | ||
const ensureMigrationsTable = (() => { | ||
var _ref6 = _asyncToGenerator(function* (db, options) { | ||
const ensureMigrationsTable = | ||
/*#__PURE__*/ | ||
function () { | ||
var _ref5 = _asyncToGenerator(function* (db, options) { | ||
try { | ||
const schema = getMigrationTableSchema(options); | ||
const migrationsTable = options.migrationsTable; | ||
const fullTableName = { | ||
@@ -111,3 +128,2 @@ schema, | ||
}; | ||
const migrationTables = yield db.select(`SELECT table_name FROM information_schema.tables WHERE table_schema = '${schema}' AND table_name = '${migrationsTable}'`); | ||
@@ -117,2 +133,3 @@ | ||
const primaryKeyConstraints = yield db.select(`SELECT constraint_name FROM information_schema.table_constraints WHERE table_schema = '${schema}' AND table_name = '${migrationsTable}' AND constraint_type = 'PRIMARY KEY'`); | ||
if (!primaryKeyConstraints || primaryKeyConstraints.length !== 1) { | ||
@@ -130,11 +147,12 @@ yield db.query(template`ALTER TABLE "${fullTableName}" ADD PRIMARY KEY (${idColumn})`); | ||
return function ensureMigrationsTable(_x7, _x8) { | ||
return _ref6.apply(this, arguments); | ||
return _ref5.apply(this, arguments); | ||
}; | ||
})(); | ||
}(); | ||
const getRunMigrations = (() => { | ||
var _ref7 = _asyncToGenerator(function* (db, options) { | ||
const getRunMigrations = | ||
/*#__PURE__*/ | ||
function () { | ||
var _ref6 = _asyncToGenerator(function* (db, options) { | ||
const schema = getMigrationTableSchema(options); | ||
const migrationsTable = options.migrationsTable; | ||
const fullTableName = { | ||
@@ -148,11 +166,16 @@ schema, | ||
return function getRunMigrations(_x9, _x10) { | ||
return _ref7.apply(this, arguments); | ||
return _ref6.apply(this, arguments); | ||
}; | ||
})(); | ||
}(); | ||
const getMigrationsToRun = (options, runNames, migrations) => { | ||
if (options.direction === "down") { | ||
const downMigrations = runNames.filter(migrationName => !options.file || options.file === migrationName).map(migrationName => migrations.find(({ name }) => name === migrationName) || migrationName); | ||
const toRun = (options.timestamp ? downMigrations.filter(({ timestamp }) => timestamp >= options.count) : downMigrations.slice(-Math.abs(options.count === undefined ? 1 : options.count))).reverse(); | ||
const downMigrations = runNames.filter(migrationName => !options.file || options.file === migrationName).map(migrationName => migrations.find(({ | ||
name | ||
}) => name === migrationName) || migrationName); | ||
const toRun = (options.timestamp ? downMigrations.filter(({ | ||
timestamp | ||
}) => timestamp >= options.count) : downMigrations.slice(-Math.abs(options.count === undefined ? 1 : options.count))).reverse(); | ||
const deletedMigrations = toRun.filter(migration => typeof migration === "string"); | ||
if (deletedMigrations.length) { | ||
@@ -162,6 +185,12 @@ const deletedMigrationsStr = deletedMigrations.join(", "); | ||
} | ||
return toRun; | ||
} | ||
const upMigrations = migrations.filter(({ name }) => runNames.indexOf(name) < 0 && (!options.file || options.file === name)); | ||
return options.timestamp ? upMigrations.filter(({ timestamp }) => timestamp <= options.count) : upMigrations.slice(0, Math.abs(options.count === undefined ? Infinity : options.count)); | ||
const upMigrations = migrations.filter(({ | ||
name | ||
}) => runNames.indexOf(name) < 0 && (!options.file || options.file === name)); | ||
return options.timestamp ? upMigrations.filter(({ | ||
timestamp | ||
}) => timestamp <= options.count) : upMigrations.slice(0, Math.abs(options.count === undefined ? Infinity : options.count)); | ||
}; | ||
@@ -171,5 +200,7 @@ | ||
const len = Math.min(runNames.length, migrations.length); | ||
for (let i = 0; i < len; i += 1) { | ||
const runName = runNames[i]; | ||
const migrationName = migrations[i].name; | ||
if (runName !== migrationName) { | ||
@@ -183,6 +214,9 @@ throw new Error(`Not run migration ${migrationName} is preceding already run migration ${runName}`); | ||
const runner = (() => { | ||
var _ref8 = _asyncToGenerator(function* (options) { | ||
const runner = | ||
/*#__PURE__*/ | ||
function () { | ||
var _ref7 = _asyncToGenerator(function* (options) { | ||
const log = options.log || console.log; | ||
const db = Db(options.databaseUrl, log); | ||
try { | ||
@@ -193,4 +227,6 @@ if (options.schema) { | ||
} | ||
yield db.query(`SET SCHEMA '${options.schema}'`); | ||
} | ||
if (options.migrationsSchema && options.createMigrationsSchema) { | ||
@@ -206,9 +242,7 @@ yield db.query(`CREATE SCHEMA IF NOT EXISTS "${options.migrationsSchema}"`); | ||
var _ref9 = yield Promise.all([loadMigrationFiles(db, options, log), getRunMigrations(db, options)]), | ||
_ref10 = _slicedToArray(_ref9, 2); | ||
const _ref8 = yield Promise.all([loadMigrationFiles(db, options, log), getRunMigrations(db, options)]), | ||
_ref9 = _slicedToArray(_ref8, 2), | ||
migrations = _ref9[0], | ||
runNames = _ref9[1]; | ||
const migrations = _ref10[0], | ||
runNames = _ref10[1]; | ||
if (options.checkOrder) { | ||
@@ -223,7 +257,7 @@ checkOrder(runNames, migrations); | ||
return; | ||
} | ||
} // TODO: add some fancy colors to logging | ||
// TODO: add some fancy colors to logging | ||
log("> Migrating files:"); | ||
toRun.forEach(function (m) { | ||
toRun.forEach(m => { | ||
log(`> - ${m.name}`); | ||
@@ -236,2 +270,3 @@ }); | ||
yield db.query("BEGIN"); | ||
try { | ||
@@ -254,10 +289,10 @@ yield runMigrations(toRun, "apply", options.direction); | ||
return function runner(_x11) { | ||
return _ref8.apply(this, arguments); | ||
return _ref7.apply(this, arguments); | ||
}; | ||
})(); | ||
}(); | ||
runner.default = runner; // workaround for transpilers | ||
runner.PgLiteral = PgLiteral; | ||
runner.Migration = Migration; | ||
module.exports = runner; |
"use strict"; | ||
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; | ||
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; } | ||
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } | ||
// This is used to create unescaped strings | ||
@@ -19,2 +21,3 @@ // exposed in the migrations via pgm.func | ||
} | ||
} | ||
@@ -26,5 +29,5 @@ | ||
name = v.name; | ||
return (schema ? `${schema}"."` : "") + name; | ||
} | ||
return v; | ||
@@ -37,5 +40,5 @@ }; | ||
name = v.name; | ||
return schema ? `OPERATOR(${schema}.${name})` : name; | ||
} | ||
return v; | ||
@@ -51,8 +54,11 @@ }; | ||
} | ||
if (typeof val === "boolean") { | ||
return val.toString(); | ||
} | ||
if (typeof val === "string") { | ||
let dollars; | ||
let index = 0; | ||
do { | ||
@@ -62,7 +68,10 @@ index += 1; | ||
} while (val.indexOf(dollars) >= 0); | ||
return `${dollars}${val}${dollars}`; | ||
} | ||
if (typeof val === "number") { | ||
return val; | ||
} | ||
if (Array.isArray(val)) { | ||
@@ -72,5 +81,7 @@ const arrayStr = val.map(escapeValue).join(",").replace(/ARRAY/g, ""); | ||
} | ||
if (val instanceof PgLiteral) { | ||
return val.toString(); | ||
} | ||
return ""; | ||
@@ -108,15 +119,42 @@ }; | ||
}; | ||
const defaultTypeShorthands = { | ||
id: { type: "serial", primaryKey: true // convenience type for serial primary keys | ||
} }; | ||
id: { | ||
type: "serial", | ||
primaryKey: true // convenience type for serial primary keys | ||
// some convenience adapters -- see above | ||
} | ||
}; // some convenience adapters -- see above | ||
const applyTypeAdapters = type => typeAdapters[type] ? typeAdapters[type] : type; | ||
const applyType = (type, extendingTypeShorthands = {}) => { | ||
const typeShorthands = _extends({}, defaultTypeShorthands, extendingTypeShorthands); | ||
const options = typeof type === "string" ? { type } : type; | ||
const ext = typeShorthands[options.type] || { type: options.type }; | ||
return _extends({}, ext, options, { | ||
const typeShorthands = _objectSpread({}, defaultTypeShorthands, extendingTypeShorthands); | ||
const options = typeof type === "string" ? { | ||
type | ||
} : type; | ||
let ext = null; | ||
const types = [options.type]; | ||
while (typeShorthands[types[types.length - 1]]) { | ||
if (ext) { | ||
delete ext.type; | ||
} | ||
ext = _objectSpread({}, typeShorthands[types[types.length - 1]], ext); | ||
if (types.includes(ext.type)) { | ||
throw new Error(`Shorthands contain cyclic dependency: ${types.join(", ")}, ${ext.type}`); | ||
} else { | ||
types.push(ext.type); | ||
} | ||
} | ||
if (!ext) { | ||
ext = { | ||
type: options.type | ||
}; | ||
} | ||
return _objectSpread({}, ext, options, { | ||
type: applyTypeAdapters(ext.type) | ||
@@ -127,5 +165,4 @@ }); | ||
const formatParam = typeShorthands => param => { | ||
var _applyType = applyType(param, typeShorthands); | ||
const mode = _applyType.mode, | ||
const _applyType = applyType(param, typeShorthands), | ||
mode = _applyType.mode, | ||
name = _applyType.name, | ||
@@ -136,14 +173,19 @@ type = _applyType.type, | ||
const options = []; | ||
if (mode) { | ||
options.push(mode); | ||
} | ||
if (name) { | ||
options.push(schemalize(name)); | ||
} | ||
if (type) { | ||
options.push(type); | ||
} | ||
if (defaultValue) { | ||
options.push(`DEFAULT ${escapeValue(defaultValue)}`); | ||
} | ||
return options.join(" "); | ||
@@ -161,3 +203,3 @@ }; | ||
const promisify = fn => (...args) => new Promise((resolve, reject) => fn.call(undefined, ...args, (err, ...result) => err ? reject(err) : resolve(...result))); | ||
const promisify = fn => (...args) => new Promise((resolve, reject) => fn.call(void 0, ...args, (err, ...result) => err ? reject(err) : resolve(...result))); | ||
@@ -164,0 +206,0 @@ module.exports = { |
@@ -119,3 +119,20 @@ // This is used to create unescaped strings | ||
const options = typeof type === "string" ? { type } : type; | ||
const ext = typeShorthands[options.type] || { type: options.type }; | ||
let ext = null; | ||
const types = [options.type]; | ||
while (typeShorthands[types[types.length - 1]]) { | ||
if (ext) { | ||
delete ext.type; | ||
} | ||
ext = { ...typeShorthands[types[types.length - 1]], ...ext }; | ||
if (types.includes(ext.type)) { | ||
throw new Error( | ||
`Shorthands contain cyclic dependency: ${types.join(", ")}, ${ext.type}` | ||
); | ||
} else { | ||
types.push(ext.type); | ||
} | ||
} | ||
if (!ext) { | ||
ext = { type: options.type }; | ||
} | ||
return { | ||
@@ -122,0 +139,0 @@ ...ext, |
{ | ||
"name": "node-pg-migrate", | ||
"version": "3.11.0", | ||
"version": "3.12.0", | ||
"description": "Postgresql database migration management tool for node.js", | ||
@@ -52,7 +52,8 @@ "author": "Theo Ephraim", | ||
"devDependencies": { | ||
"babel-cli": "6.26.0", | ||
"babel-eslint": "9.0.0", | ||
"babel-plugin-transform-object-rest-spread": "6.26.0", | ||
"babel-preset-env": "1.7.0", | ||
"chai": "4.1.2", | ||
"@babel/cli": "7.1.2", | ||
"@babel/core": "7.1.2", | ||
"@babel/plugin-proposal-object-rest-spread": "7.0.0", | ||
"@babel/preset-env": "7.1.0", | ||
"babel-eslint": "10.0.1", | ||
"chai": "4.2.0", | ||
"chai-as-promised": "7.1.1", | ||
@@ -62,15 +63,15 @@ "config": ">=1.0.0", | ||
"dotenv": ">=1.0.0", | ||
"eslint": "5.5.0", | ||
"eslint": "5.7.0", | ||
"eslint-config-airbnb-base": "13.1.0", | ||
"eslint-config-prettier": "3.0.1", | ||
"eslint-config-prettier": "3.1.0", | ||
"eslint-plugin-import": "2.14.0", | ||
"eslint-plugin-prettier": "2.6.2", | ||
"eslint-plugin-prettier": "3.0.0", | ||
"eslint-plugin-security": "1.4.0", | ||
"husky": "0.14.3", | ||
"lint-staged": "7.2.2", | ||
"husky": "1.1.2", | ||
"lint-staged": "7.3.0", | ||
"mocha": "5.2.0", | ||
"pg": "7.4.3", | ||
"prettier": "1.14.2", | ||
"pg": "7.5.0", | ||
"prettier": "1.14.3", | ||
"proxyquire": "2.1.0", | ||
"sinon": "6.2.0", | ||
"sinon": "7.0.0", | ||
"sinon-chai": "3.2.0" | ||
@@ -86,10 +87,14 @@ }, | ||
"scripts": { | ||
"precommit": "lint-staged", | ||
"compile": "babel lib/ -d dist/ && cp lib/migration-template.* dist/", | ||
"test": "cross-env NODE_ENV=test mocha --opts ./mocha.opts test", | ||
"migrate": "babel-node bin/node-pg-migrate", | ||
"lint": "eslint -c eslintrc.js . bin/*", | ||
"migrate": "node bin/node-pg-migrate", | ||
"lint": "eslint . bin/*", | ||
"lintfix": "npm run lint -- --fix && prettier --write *.json *.md docs/*.md", | ||
"prepare": "npm run compile" | ||
}, | ||
"husky": { | ||
"hooks": { | ||
"pre-commit": "lint-staged" | ||
} | ||
}, | ||
"lint-staged": { | ||
@@ -96,0 +101,0 @@ "*.js": ["npm run lintfix", "git add"], |
266906
4637
24
74