knex/lib/dialects/postgres/query/pg-querycompiler.js

297 lines
7.5 KiB
JavaScript
Raw Normal View History

2016-03-02 17:07:05 +01:00
// PostgreSQL Query Builder & Compiler
// ------
const identity = require('lodash/identity');
const reduce = require('lodash/reduce');
2016-03-02 17:07:05 +01:00
2021-01-09 17:59:53 +02:00
const QueryCompiler = require('../../../query/querycompiler');
const {
wrapString,
wrap: wrap_,
} = require('../../../formatter/wrappingFormatter');
class QueryCompiler_PG extends QueryCompiler {
2021-01-07 23:34:46 +02:00
constructor(client, builder, formatter) {
super(client, builder, formatter);
this._defaultInsertValue = 'default';
}
2016-03-02 17:07:05 +01:00
// Compiles a truncate query.
truncate() {
return `truncate ${this.tableName} restart identity`;
}
2016-03-02 17:07:05 +01:00
// is used if the an array with multiple empty values supplied
// Compiles an `insert` query, allowing for multiple
// inserts using a single query statement.
insert() {
let sql = super.insert();
2016-03-02 17:07:05 +01:00
if (sql === '') return sql;
const { returning, onConflict, ignore, merge, insert } = this.single;
if (onConflict && ignore) sql += this._ignore(onConflict);
if (onConflict && merge) {
sql += this._merge(merge.updates, onConflict, insert);
const wheres = this.where();
if (wheres) sql += ` ${wheres}`;
}
if (returning) sql += this._returning(returning);
2016-03-02 17:07:05 +01:00
return {
sql: sql,
returning,
2016-03-02 17:07:05 +01:00
};
}
2016-03-02 17:07:05 +01:00
// Compiles an `update` query, allowing for a return value.
update() {
const withSQL = this.with();
const updateData = this._prepUpdate(this.single.update);
const wheres = this.where();
const { returning } = this.single;
2016-03-02 17:07:05 +01:00
return {
sql:
withSQL +
`update ${this.single.only ? 'only ' : ''}${this.tableName} ` +
`set ${updateData.join(', ')}` +
(wheres ? ` ${wheres}` : '') +
this._returning(returning),
returning,
2016-03-02 17:07:05 +01:00
};
}
2016-03-02 17:07:05 +01:00
using() {
const usingTables = this.single.using;
if (!usingTables) return;
let sql = 'using ';
if (Array.isArray(usingTables)) {
sql += usingTables
.map((table) => {
return this.formatter.wrap(table);
})
.join(',');
} else {
sql += this.formatter.wrap(usingTables);
}
return sql;
}
// Compiles an `delete` query, allowing for a return value.
del() {
// Make sure tableName is processed by the formatter first.
const { tableName } = this;
const withSQL = this.with();
let wheres = this.where() || '';
let using = this.using() || '';
const joins = this.grouped.join;
const tableJoins = [];
if (Array.isArray(joins)) {
for (const join of joins) {
tableJoins.push(
wrap_(
this._joinTable(join),
undefined,
this.builder,
this.client,
this.bindingsHolder
)
);
const joinWheres = [];
for (const clause of join.clauses) {
joinWheres.push(
this.whereBasic({
column: clause.column,
operator: '=',
value: clause.value,
asColumn: true,
})
);
}
if (joinWheres.length > 0) {
wheres += (wheres ? ' and ' : '') + joinWheres.join(' ');
}
}
if (tableJoins.length > 0) {
using += (using ? ',' : 'using ') + tableJoins.join(',');
}
}
// With 'using' syntax, no tablename between DELETE and FROM.
const sql =
withSQL +
`delete from ${this.single.only ? 'only ' : ''}${tableName}` +
(using ? ` ${using}` : '') +
(wheres ? ` ${wheres}` : '');
const { returning } = this.single;
2016-03-02 17:07:05 +01:00
return {
sql: sql + this._returning(returning),
returning,
2016-03-02 17:07:05 +01:00
};
}
2016-03-02 17:07:05 +01:00
aggregate(stmt) {
return this._aggregate(stmt, { distinctParentheses: true });
}
_returning(value) {
return value ? ` returning ${this.formatter.columnize(value)}` : '';
}
2016-03-02 17:07:05 +01:00
_ignore(columns) {
if (columns === true) {
return ' on conflict do nothing';
}
return ` on conflict (${this.formatter.columnize(columns)}) do nothing`;
}
_merge(updates, columns, insert) {
let sql = ` on conflict (${this.formatter.columnize(
columns
)}) do update set `;
if (updates && Array.isArray(updates)) {
sql += updates
.map((column) =>
wrapString(
column.split('.').pop(),
this.formatter.builder,
this.client,
this.formatter
)
)
.map((column) => `${column} = excluded.${column}`)
.join(', ');
return sql;
} else if (updates && typeof updates === 'object') {
const updateData = this._prepUpdate(updates);
if (typeof updateData === 'string') {
sql += updateData;
} else {
sql += updateData.join(',');
}
return sql;
} else {
const insertData = this._prepInsert(insert);
if (typeof insertData === 'string') {
throw new Error(
'If using merge with a raw insert query, then updates must be provided'
);
}
sql += insertData.columns
.map((column) =>
wrapString(column.split('.').pop(), this.builder, this.client)
)
.map((column) => `${column} = excluded.${column}`)
.join(', ');
return sql;
}
}
// Join array of table names and apply default schema.
_tableNames(tables) {
const schemaName = this.single.schema;
const sql = [];
for (let i = 0; i < tables.length; i++) {
let tableName = tables[i];
if (tableName) {
if (schemaName) {
tableName = `${schemaName}.${tableName}`;
}
sql.push(this.formatter.wrap(tableName));
}
}
return sql.join(', ');
}
_lockingClause(lockMode) {
const tables = this.single.lockTables || [];
return lockMode + (tables.length ? ' of ' + this._tableNames(tables) : '');
}
forUpdate() {
return this._lockingClause('for update');
}
2016-03-02 17:07:05 +01:00
forShare() {
return this._lockingClause('for share');
}
forNoKeyUpdate() {
return this._lockingClause('for no key update');
}
forKeyShare() {
return this._lockingClause('for key share');
}
2016-03-02 17:07:05 +01:00
skipLocked() {
return 'skip locked';
}
noWait() {
return 'nowait';
}
2016-03-02 17:07:05 +01:00
// Compiles a columnInfo query
columnInfo() {
const column = this.single.columnInfo;
let schema = this.single.schema;
// The user may have specified a custom wrapIdentifier function in the config. We
// need to run the identifiers through that function, but not format them as
// identifiers otherwise.
const table = this.client.customWrapIdentifier(this.single.table, identity);
if (schema) {
schema = this.client.customWrapIdentifier(schema, identity);
}
2016-03-02 17:07:05 +01:00
let sql =
'select * from information_schema.columns where table_name = ? and table_catalog = current_database()';
const bindings = [table];
2016-03-02 17:07:05 +01:00
if (schema) {
2016-03-02 17:07:05 +01:00
sql += ' and table_schema = ?';
bindings.push(schema);
2016-03-02 17:07:05 +01:00
} else {
Add redshift support without changing cli or package.json (#2233) * Add a Redshift dialect that inherits from Postgres. * Turn .index() and .dropIndex() into no-ops with warnings in the Redshift dialect. * Update the Redshift dialect to be compatible with master. * Update package.json * Disable liftoff cli * Remove the CLI * Add lib to the repo * Allow the escaping of named bindings. * Update dist * Update the Redshift dialect’s instantiation of the query and column compilers. * Update the distribution * Fix a merge conflict * Take lib back out * Trying to bring back in line with tgreisser/knex * Add npm 5 package-lock * Bring cli.js back in line * Bring cli.js back in line * Progress commit on redshift integration tests * Revert "Progress commit on redshift integration tests" This reverts commit 207e31635c638853dec54ce0580d34559ba5a54c. * Progress commit * Working not null on primary columns in createTable * Working redshift unit tests * Working unit and integration tests, still need to fix migration tests * Brought datatypes more in line with what redshift actually supports * Added query compiler unit tests * Add a hacky returning clause for redshift ugh * Working migration integration tests * Working insert integration tests * Allow multiple insert returning values * Working select integration tests * Working join integration tests * Working aggregate integration tests * All integration suite tests working * Put docker index for reconnect tests back * Redshift does not support insert...returning, there does not seem to be a way around that, therefore accept it and test accordingly * Leave redshift integration tests in place, but do not run them by default * Fix mysql order by test * Fix more tests * Change test db name to knex_test for consistency * Address PR comments
2018-02-03 08:33:02 -05:00
sql += ' and table_schema = current_schema()';
2016-03-02 17:07:05 +01:00
}
return {
sql,
bindings,
output(resp) {
const out = reduce(
resp.rows,
2020-04-19 00:40:23 +02:00
function (columns, val) {
columns[val.column_name] = {
type: val.data_type,
maxLength: val.character_maximum_length,
nullable: val.is_nullable === 'YES',
defaultValue: val.column_default,
};
return columns;
},
{}
);
return (column && out[column]) || out;
},
2016-03-02 17:07:05 +01:00
};
}
distinctOn(value) {
return 'distinct on (' + this.formatter.columnize(value) + ') ';
}
}
2016-03-02 17:07:05 +01:00
module.exports = QueryCompiler_PG;