Initial commit

This commit is contained in:
2025-12-07 14:32:46 +00:00
commit 0a0969b8af
4726 changed files with 536089 additions and 0 deletions

View File

@@ -0,0 +1,156 @@
// PostgreSQL Column Compiler
// -------
const ColumnCompiler = require('../../../schema/columncompiler');
const { isObject } = require('../../../util/is');
const { toNumber } = require('../../../util/helpers');
const commentEscapeRegex = /(?<!')'(?!')/g;
class ColumnCompiler_PG extends ColumnCompiler {
constructor(client, tableCompiler, columnBuilder) {
super(client, tableCompiler, columnBuilder);
this.modifiers = ['nullable', 'defaultTo', 'comment'];
this._addCheckModifiers();
}
// Types
// ------
bit(column) {
return column.length !== false ? `bit(${column.length})` : 'bit';
}
// Create the column definition for an enum type.
// Using method "2" here: http://stackoverflow.com/a/10984951/525714
enu(allowed, options) {
options = options || {};
const values =
options.useNative && options.existingType
? undefined
: allowed.join("', '");
if (options.useNative) {
let enumName = '';
const schemaName = options.schemaName || this.tableCompiler.schemaNameRaw;
if (schemaName) {
enumName += `"${schemaName}".`;
}
enumName += `"${options.enumName}"`;
if (!options.existingType) {
this.tableCompiler.unshiftQuery(
`create type ${enumName} as enum ('${values}')`
);
}
return enumName;
}
return `text check (${this.formatter.wrap(this.args[0])} in ('${values}'))`;
}
decimal(precision, scale) {
if (precision === null) return 'decimal';
return `decimal(${toNumber(precision, 8)}, ${toNumber(scale, 2)})`;
}
json(jsonb) {
if (jsonb) this.client.logger.deprecate('json(true)', 'jsonb()');
return jsonColumn(this.client, jsonb);
}
jsonb() {
return jsonColumn(this.client, true);
}
checkRegex(regex, constraintName) {
return this._check(
`${this.formatter.wrap(
this.getColumnName()
)} ~ ${this.client._escapeBinding(regex)}`,
constraintName
);
}
datetime(withoutTz = false, precision) {
let useTz;
if (isObject(withoutTz)) {
({ useTz, precision } = withoutTz);
} else {
useTz = !withoutTz;
}
useTz = typeof useTz === 'boolean' ? useTz : true;
precision =
precision !== undefined && precision !== null
? '(' + precision + ')'
: '';
return `${useTz ? 'timestamptz' : 'timestamp'}${precision}`;
}
timestamp(withoutTz = false, precision) {
return this.datetime(withoutTz, precision);
}
// Modifiers:
// ------
comment(comment) {
const columnName = this.args[0] || this.defaults('columnName');
const escapedComment = comment
? `'${comment.replace(commentEscapeRegex, "''")}'`
: 'NULL';
this.pushAdditional(function () {
this.pushQuery(
`comment on column ${this.tableCompiler.tableName()}.` +
this.formatter.wrap(columnName) +
` is ${escapedComment}`
);
}, comment);
}
increments(options = { primaryKey: true }) {
return (
'serial' +
(this.tableCompiler._canBeAddPrimaryKey(options) ? ' primary key' : '')
);
}
bigincrements(options = { primaryKey: true }) {
return (
'bigserial' +
(this.tableCompiler._canBeAddPrimaryKey(options) ? ' primary key' : '')
);
}
uuid(options = { primaryKey: false }) {
return (
'uuid' +
(this.tableCompiler._canBeAddPrimaryKey(options) ? ' primary key' : '')
);
}
}
ColumnCompiler_PG.prototype.bigint = 'bigint';
ColumnCompiler_PG.prototype.binary = 'bytea';
ColumnCompiler_PG.prototype.bool = 'boolean';
ColumnCompiler_PG.prototype.double = 'double precision';
ColumnCompiler_PG.prototype.floating = 'real';
ColumnCompiler_PG.prototype.smallint = 'smallint';
ColumnCompiler_PG.prototype.tinyint = 'smallint';
function jsonColumn(client, jsonb) {
if (
!client.version ||
client.config.client === 'cockroachdb' ||
client.config.jsonbSupport === true ||
parseFloat(client.version) >= 9.2
) {
return jsonb ? 'jsonb' : 'json';
}
return 'text';
}
module.exports = ColumnCompiler_PG;

138
node_modules/knex/lib/dialects/postgres/schema/pg-compiler.js generated vendored Executable file
View File

@@ -0,0 +1,138 @@
// PostgreSQL Schema Compiler
// -------
const SchemaCompiler = require('../../../schema/compiler');
class SchemaCompiler_PG extends SchemaCompiler {
constructor(client, builder) {
super(client, builder);
}
// Check whether the current table
hasTable(tableName) {
let sql = 'select * from information_schema.tables where table_name = ?';
const bindings = [tableName];
if (this.schema) {
sql += ' and table_schema = ?';
bindings.push(this.schema);
} else {
sql += ' and table_schema = current_schema()';
}
this.pushQuery({
sql,
bindings,
output(resp) {
return resp.rows.length > 0;
},
});
}
// Compile the query to determine if a column exists in a table.
hasColumn(tableName, columnName) {
let sql =
'select * from information_schema.columns where table_name = ? and column_name = ?';
const bindings = [tableName, columnName];
if (this.schema) {
sql += ' and table_schema = ?';
bindings.push(this.schema);
} else {
sql += ' and table_schema = current_schema()';
}
this.pushQuery({
sql,
bindings,
output(resp) {
return resp.rows.length > 0;
},
});
}
qualifiedTableName(tableName) {
const name = this.schema ? `${this.schema}.${tableName}` : tableName;
return this.formatter.wrap(name);
}
// Compile a rename table command.
renameTable(from, to) {
this.pushQuery(
`alter table ${this.qualifiedTableName(
from
)} rename to ${this.formatter.wrap(to)}`
);
}
createSchema(schemaName) {
this.pushQuery(`create schema ${this.formatter.wrap(schemaName)}`);
}
createSchemaIfNotExists(schemaName) {
this.pushQuery(
`create schema if not exists ${this.formatter.wrap(schemaName)}`
);
}
dropSchema(schemaName, cascade = false) {
this.pushQuery(
`drop schema ${this.formatter.wrap(schemaName)}${
cascade ? ' cascade' : ''
}`
);
}
dropSchemaIfExists(schemaName, cascade = false) {
this.pushQuery(
`drop schema if exists ${this.formatter.wrap(schemaName)}${
cascade ? ' cascade' : ''
}`
);
}
dropExtension(extensionName) {
this.pushQuery(`drop extension ${this.formatter.wrap(extensionName)}`);
}
dropExtensionIfExists(extensionName) {
this.pushQuery(
`drop extension if exists ${this.formatter.wrap(extensionName)}`
);
}
createExtension(extensionName) {
this.pushQuery(`create extension ${this.formatter.wrap(extensionName)}`);
}
createExtensionIfNotExists(extensionName) {
this.pushQuery(
`create extension if not exists ${this.formatter.wrap(extensionName)}`
);
}
renameView(from, to) {
this.pushQuery(
this.alterViewPrefix +
`${this.formatter.wrap(from)} rename to ${this.formatter.wrap(to)}`
);
}
refreshMaterializedView(viewName, concurrently = false) {
this.pushQuery({
sql: `refresh materialized view${
concurrently ? ' concurrently' : ''
} ${this.formatter.wrap(viewName)}`,
});
}
dropMaterializedView(viewName) {
this._dropView(viewName, false, true);
}
dropMaterializedViewIfExists(viewName) {
this._dropView(viewName, true, true);
}
}
module.exports = SchemaCompiler_PG;

View File

@@ -0,0 +1,304 @@
/* eslint max-len: 0 */
// PostgreSQL Table Builder & Compiler
// -------
const has = require('lodash/has');
const TableCompiler = require('../../../schema/tablecompiler');
const { isObject, isString } = require('../../../util/is');
class TableCompiler_PG extends TableCompiler {
constructor(client, tableBuilder) {
super(client, tableBuilder);
}
// Compile a rename column command.
renameColumn(from, to) {
return this.pushQuery({
sql: `alter table ${this.tableName()} rename ${this.formatter.wrap(
from
)} to ${this.formatter.wrap(to)}`,
});
}
_setNullableState(column, isNullable) {
const constraintAction = isNullable ? 'drop not null' : 'set not null';
const sql = `alter table ${this.tableName()} alter column ${this.formatter.wrap(
column
)} ${constraintAction}`;
return this.pushQuery({
sql: sql,
});
}
compileAdd(builder) {
const table = this.formatter.wrap(builder);
const columns = this.prefixArray('add column', this.getColumns(builder));
return this.pushQuery({
sql: `alter table ${table} ${columns.join(', ')}`,
});
}
// Adds the "create" query to the query sequence.
createQuery(columns, ifNot, like) {
const createStatement = ifNot
? 'create table if not exists '
: 'create table ';
const columnsSql = ` (${columns.sql.join(', ')}${
this.primaryKeys() || ''
}${this._addChecks()})`;
let sql =
createStatement +
this.tableName() +
(like && this.tableNameLike()
? ' (like ' +
this.tableNameLike() +
' including all' +
(columns.sql.length ? ', ' + columns.sql.join(', ') : '') +
')'
: columnsSql);
if (this.single.inherits)
sql += ` inherits (${this.formatter.wrap(this.single.inherits)})`;
this.pushQuery({
sql,
bindings: columns.bindings,
});
const hasComment = has(this.single, 'comment');
if (hasComment) this.comment(this.single.comment);
}
primaryKeys() {
const pks = (this.grouped.alterTable || []).filter(
(k) => k.method === 'primary'
);
if (pks.length > 0 && pks[0].args.length > 0) {
const columns = pks[0].args[0];
let constraintName = pks[0].args[1] || '';
let deferrable;
if (isObject(constraintName)) {
({ constraintName, deferrable } = constraintName);
}
deferrable = deferrable ? ` deferrable initially ${deferrable}` : '';
constraintName = constraintName
? this.formatter.wrap(constraintName)
: this.formatter.wrap(`${this.tableNameRaw}_pkey`);
return `, constraint ${constraintName} primary key (${this.formatter.columnize(
columns
)})${deferrable}`;
}
}
addColumns(columns, prefix, colCompilers) {
if (prefix === this.alterColumnsPrefix) {
// alter columns
for (const col of colCompilers) {
this._addColumn(col);
}
} else {
// base class implementation for normal add
super.addColumns(columns, prefix);
}
}
_addColumn(col) {
const quotedTableName = this.tableName();
const type = col.getColumnType();
// We'd prefer to call this.formatter.wrapAsIdentifier here instead, however the context passed to
// `this` instance is not that of the column, but of the table. Thus, we unfortunately have to call
// `wrapIdentifier` here as well (it is already called once on the initial column operation) to give
// our `alter` operation the correct `queryContext`. Refer to issue #2606 and PR #2612.
const colName = this.client.wrapIdentifier(
col.getColumnName(),
col.columnBuilder.queryContext()
);
// To alter enum columns they must be cast to text first
const isEnum = col.type === 'enu';
this.pushQuery({
sql: `alter table ${quotedTableName} alter column ${colName} drop default`,
bindings: [],
});
const alterNullable = col.columnBuilder.alterNullable;
if (alterNullable) {
this.pushQuery({
sql: `alter table ${quotedTableName} alter column ${colName} drop not null`,
bindings: [],
});
}
const alterType = col.columnBuilder.alterType;
if (alterType) {
this.pushQuery({
sql: `alter table ${quotedTableName} alter column ${colName} type ${type} using (${colName}${
isEnum ? '::text::' : '::'
}${type})`,
bindings: [],
});
}
const defaultTo = col.modified['defaultTo'];
if (defaultTo) {
const modifier = col.defaultTo.apply(col, defaultTo);
this.pushQuery({
sql: `alter table ${quotedTableName} alter column ${colName} set ${modifier}`,
bindings: [],
});
}
if (alterNullable) {
const nullable = col.modified['nullable'];
if (nullable && nullable[0] === false) {
this.pushQuery({
sql: `alter table ${quotedTableName} alter column ${colName} set not null`,
bindings: [],
});
}
}
}
// Compiles the comment on the table.
comment(comment) {
this.pushQuery(
`comment on table ${this.tableName()} is '${this.single.comment}'`
);
}
// Indexes:
// -------
primary(columns, constraintName) {
let deferrable;
if (isObject(constraintName)) {
({ constraintName, deferrable } = constraintName);
}
deferrable = deferrable ? ` deferrable initially ${deferrable}` : '';
constraintName = constraintName
? this.formatter.wrap(constraintName)
: this.formatter.wrap(`${this.tableNameRaw}_pkey`);
if (this.method !== 'create' && this.method !== 'createIfNot') {
this.pushQuery(
`alter table ${this.tableName()} add constraint ${constraintName} primary key (${this.formatter.columnize(
columns
)})${deferrable}`
);
}
}
unique(columns, indexName) {
let deferrable;
let useConstraint = true;
let predicate;
if (isObject(indexName)) {
({ indexName, deferrable, useConstraint, predicate } = indexName);
if (useConstraint === undefined) {
useConstraint = !!deferrable || !predicate;
}
}
if (!useConstraint && deferrable && deferrable !== 'not deferrable') {
throw new Error('postgres cannot create deferrable index');
}
if (useConstraint && predicate) {
throw new Error('postgres cannot create constraint with predicate');
}
deferrable = deferrable ? ` deferrable initially ${deferrable}` : '';
indexName = indexName
? this.formatter.wrap(indexName)
: this._indexCommand('unique', this.tableNameRaw, columns);
if (useConstraint) {
this.pushQuery(
`alter table ${this.tableName()} add constraint ${indexName}` +
' unique (' +
this.formatter.columnize(columns) +
')' +
deferrable
);
} else {
const predicateQuery = predicate
? ' ' + this.client.queryCompiler(predicate).where()
: '';
this.pushQuery(
`create unique index ${indexName} on ${this.tableName()} (${this.formatter.columnize(
columns
)})${predicateQuery}`
);
}
}
index(columns, indexName, options) {
indexName = indexName
? this.formatter.wrap(indexName)
: this._indexCommand('index', this.tableNameRaw, columns);
let predicate;
let storageEngineIndexType;
let indexType;
if (isString(options)) {
storageEngineIndexType = options;
} else if (isObject(options)) {
({ indexType, storageEngineIndexType, predicate } = options);
}
const predicateQuery = predicate
? ' ' + this.client.queryCompiler(predicate).where()
: '';
this.pushQuery(
`create${
typeof indexType === 'string' && indexType.toLowerCase() === 'unique'
? ' unique'
: ''
} index ${indexName} on ${this.tableName()}${
(storageEngineIndexType && ` using ${storageEngineIndexType}`) || ''
}` +
' (' +
this.formatter.columnize(columns) +
')' +
`${predicateQuery}`
);
}
dropPrimary(constraintName) {
constraintName = constraintName
? this.formatter.wrap(constraintName)
: this.formatter.wrap(this.tableNameRaw + '_pkey');
this.pushQuery(
`alter table ${this.tableName()} drop constraint ${constraintName}`
);
}
dropIndex(columns, indexName) {
indexName = indexName
? this.formatter.wrap(indexName)
: this._indexCommand('index', this.tableNameRaw, columns);
indexName = this.schemaNameRaw
? `${this.formatter.wrap(this.schemaNameRaw)}.${indexName}`
: indexName;
this.pushQuery(`drop index ${indexName}`);
}
dropUnique(columns, indexName) {
indexName = indexName
? this.formatter.wrap(indexName)
: this._indexCommand('unique', this.tableNameRaw, columns);
this.pushQuery(
`alter table ${this.tableName()} drop constraint ${indexName}`
);
}
dropForeign(columns, indexName) {
indexName = indexName
? this.formatter.wrap(indexName)
: this._indexCommand('foreign', this.tableNameRaw, columns);
this.pushQuery(
`alter table ${this.tableName()} drop constraint ${indexName}`
);
}
}
module.exports = TableCompiler_PG;

View File

@@ -0,0 +1,21 @@
const ViewBuilder = require('../../../schema/viewbuilder.js');
class ViewBuilder_PG extends ViewBuilder {
constructor() {
super(...arguments);
}
checkOption() {
this._single.checkOption = 'default_option';
}
localCheckOption() {
this._single.checkOption = 'local';
}
cascadedCheckOption() {
this._single.checkOption = 'cascaded';
}
}
module.exports = ViewBuilder_PG;

View File

@@ -0,0 +1,35 @@
/* eslint max-len: 0 */
const ViewCompiler = require('../../../schema/viewcompiler.js');
class ViewCompiler_PG extends ViewCompiler {
constructor(client, viewCompiler) {
super(client, viewCompiler);
}
renameColumn(from, to) {
return this.pushQuery({
sql: `alter view ${this.viewName()} rename ${this.formatter.wrap(
from
)} to ${this.formatter.wrap(to)}`,
});
}
defaultTo(column, defaultValue) {
return this.pushQuery({
sql: `alter view ${this.viewName()} alter ${this.formatter.wrap(
column
)} set default ${defaultValue}`,
});
}
createOrReplace() {
this.createQuery(this.columns, this.selectQuery, false, true);
}
createMaterializedView() {
this.createQuery(this.columns, this.selectQuery, true);
}
}
module.exports = ViewCompiler_PG;