knex/lib/schema/columncompiler.js

178 lines
5.5 KiB
JavaScript
Raw Normal View History

2016-03-02 17:07:05 +01:00
// Column Compiler
// Used for designating column definitions
// during the table "create" / "alter" statements.
// -------
const Raw = require('../raw');
const helpers = require('./helpers');
const groupBy = require('lodash/groupBy');
const first = require('lodash/first');
const has = require('lodash/has');
const isObject = require('lodash/isObject');
const tail = require('lodash/tail');
2016-03-02 17:07:05 +01:00
function ColumnCompiler(client, tableCompiler, columnBuilder) {
this.client = client;
this.tableCompiler = tableCompiler;
this.columnBuilder = columnBuilder;
this._commonBuilder = this.columnBuilder;
this.args = columnBuilder._args;
this.type = columnBuilder._type.toLowerCase();
this.grouped = groupBy(columnBuilder._statements, 'grouping');
this.modified = columnBuilder._modifiers;
this.isIncrements = this.type.indexOf('increments') !== -1;
Add queryContext to schema and query builders (#2314) * feat(query-builder): add hookContext for wrapIdentifier * refactor: use isUndefined * test(transaction): test passing of hookContext * feat(runnner): pass context to postProcessResponse * test(runner): test postProcessResponse for raw responses * test(raw): test passing of hookContext * feat: add hookContext to Raw and SchemaBuilder * test(transaction): fix test for hookContext * chore: fix lint error * fix: check for hookContext before calling it * test(transaction): fix hookContext test * chore: remove whitespace * test(hookContext): test cloning of context object * refactor: hookContext -> queryContext * minor: use more descriptive variable name i.e. refactor: `context` => `queryContext` * fix: remove unnecessary checks for query builder * fix(Raw): pass query builder to formatter * fix(SchemaCompiler): pass schema builder to formatter * refactor: add addQueryContext helper * feat: add queryContext to TableBuilder and ColumnBuilder * fix(TableCompiler): pass table builder to formatter * fix(ColumnCompiler): pass column builder to formatter * fix(pushQuery): fix passing builder to formatter * test(Schema|Table|ColumnCompiler): test passing queryContext * fix(SchemaCompiler): pass queryContext to TableCompiler * fix(TableCompiler): pass queryContext to ColumnCompiler * test: add queryContext tests for all schema dialects * test(TableCompiler): test overwriting queryContext from SchemaCompiler * test(Raw): test passing queryContext to wrapIdentifier * tests: run all the tests
2018-02-01 23:41:01 +01:00
this.formatter = client.formatter(columnBuilder);
this.sequence = [];
this.modifiers = [];
2016-03-02 17:07:05 +01:00
}
ColumnCompiler.prototype.pushQuery = helpers.pushQuery;
2016-03-02 17:07:05 +01:00
ColumnCompiler.prototype.pushAdditional = helpers.pushAdditional;
2016-03-02 17:07:05 +01:00
ColumnCompiler.prototype.unshiftQuery = helpers.unshiftQuery;
ColumnCompiler.prototype._defaultMap = {
2020-04-19 00:40:23 +02:00
columnName: function () {
if (!this.isIncrements) {
throw new Error(
`You did not specify a column name for the ${this.type} column.`
);
}
return 'id';
},
};
2020-04-19 00:40:23 +02:00
ColumnCompiler.prototype.defaults = function (label) {
if (Object.prototype.hasOwnProperty.call(this._defaultMap, label)) {
return this._defaultMap[label].bind(this)();
} else {
throw new Error(
`There is no default for the specified identifier ${label}`
);
}
};
2016-03-02 17:07:05 +01:00
// To convert to sql, we first go through and build the
// column as it would be in the insert statement
2020-04-19 00:40:23 +02:00
ColumnCompiler.prototype.toSQL = function () {
2016-03-02 17:07:05 +01:00
this.pushQuery(this.compileColumn());
if (this.sequence.additional) {
this.sequence = this.sequence.concat(this.sequence.additional);
}
return this.sequence;
};
// Compiles a column.
2020-04-19 00:40:23 +02:00
ColumnCompiler.prototype.compileColumn = function () {
return (
this.formatter.wrap(this.getColumnName()) +
' ' +
this.getColumnType() +
this.getModifiers()
);
2016-03-02 17:07:05 +01:00
};
// Assumes the autoincrementing key is named `id` if not otherwise specified.
2020-04-19 00:40:23 +02:00
ColumnCompiler.prototype.getColumnName = function () {
const value = first(this.args);
return value || this.defaults('columnName');
2016-03-02 17:07:05 +01:00
};
2020-04-19 00:40:23 +02:00
ColumnCompiler.prototype.getColumnType = function () {
const type = this[this.type];
2016-03-02 17:07:05 +01:00
return typeof type === 'function' ? type.apply(this, tail(this.args)) : type;
};
2020-04-19 00:40:23 +02:00
ColumnCompiler.prototype.getModifiers = function () {
const modifiers = [];
for (let i = 0, l = this.modifiers.length; i < l; i++) {
const modifier = this.modifiers[i];
//Cannot allow 'nullable' modifiers on increments types
if (!this.isIncrements || (this.isIncrements && modifier === 'comment')) {
2016-03-02 17:07:05 +01:00
if (has(this.modified, modifier)) {
const val = this[modifier].apply(this, this.modified[modifier]);
2016-03-02 17:07:05 +01:00
if (val) modifiers.push(val);
}
}
}
return modifiers.length > 0 ? ` ${modifiers.join(' ')}` : '';
2016-03-02 17:07:05 +01:00
};
// Types
// ------
ColumnCompiler.prototype.increments =
'integer not null primary key autoincrement';
ColumnCompiler.prototype.bigincrements =
'integer not null primary key autoincrement';
ColumnCompiler.prototype.integer = ColumnCompiler.prototype.smallint = ColumnCompiler.prototype.mediumint =
'integer';
ColumnCompiler.prototype.biginteger = 'bigint';
2020-04-19 00:40:23 +02:00
ColumnCompiler.prototype.varchar = function (length) {
return `varchar(${this._num(length, 255)})`;
2016-03-02 17:07:05 +01:00
};
ColumnCompiler.prototype.text = 'text';
ColumnCompiler.prototype.tinyint = 'tinyint';
2020-04-19 00:40:23 +02:00
ColumnCompiler.prototype.floating = function (precision, scale) {
return `float(${this._num(precision, 8)}, ${this._num(scale, 2)})`;
2016-03-02 17:07:05 +01:00
};
2020-04-19 00:40:23 +02:00
ColumnCompiler.prototype.decimal = function (precision, scale) {
if (precision === null) {
throw new Error(
'Specifying no precision on decimal columns is not supported for that SQL dialect.'
);
}
return `decimal(${this._num(precision, 8)}, ${this._num(scale, 2)})`;
2016-03-02 17:07:05 +01:00
};
ColumnCompiler.prototype.binary = 'blob';
ColumnCompiler.prototype.bool = 'boolean';
ColumnCompiler.prototype.date = 'date';
ColumnCompiler.prototype.datetime = 'datetime';
ColumnCompiler.prototype.time = 'time';
ColumnCompiler.prototype.timestamp = 'timestamp';
ColumnCompiler.prototype.enu = 'varchar';
ColumnCompiler.prototype.bit = ColumnCompiler.prototype.json = 'text';
2016-03-02 17:07:05 +01:00
ColumnCompiler.prototype.uuid = 'char(36)';
ColumnCompiler.prototype.specifictype = (type) => type;
2016-03-02 17:07:05 +01:00
// Modifiers
// -------
ColumnCompiler.prototype.nullable = (nullable) =>
nullable === false ? 'not null' : 'null';
2020-04-19 00:40:23 +02:00
ColumnCompiler.prototype.notNullable = function () {
2016-03-02 17:07:05 +01:00
return this.nullable(false);
};
2020-04-19 00:40:23 +02:00
ColumnCompiler.prototype.defaultTo = function (value) {
2016-03-02 17:07:05 +01:00
if (value === void 0) {
return '';
} else if (value === null) {
value = 'null';
2016-03-02 17:07:05 +01:00
} else if (value instanceof Raw) {
value = value.toQuery();
} else if (this.type === 'bool') {
if (value === 'false') value = 0;
value = `'${value ? 1 : 0}'`;
} else if (
(this.type === 'json' || this.type === 'jsonb') &&
isObject(value)
) {
value = `'${JSON.stringify(value)}'`;
2016-03-02 17:07:05 +01:00
} else {
value = `'${value}'`;
2016-03-02 17:07:05 +01:00
}
return `default ${value}`;
2016-03-02 17:07:05 +01:00
};
2020-04-19 00:40:23 +02:00
ColumnCompiler.prototype._num = function (val, fallback) {
2016-03-02 17:07:05 +01:00
if (val === undefined || val === null) return fallback;
const number = parseInt(val, 10);
2016-03-02 17:07:05 +01:00
return isNaN(number) ? fallback : number;
};
module.exports = ColumnCompiler;