quick-erd
Version:
quick and easy text-based ERD + code generator for migration, query, typescript types and orm entity
119 lines (118 loc) • 3.34 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.textToSqlite = textToSqlite;
exports.toSqliteColumnSql = toSqliteColumnSql;
exports.wrapSqliteName = wrapSqliteName;
const ast_1 = require("../core/ast");
const sort_tables_1 = require("./sort-tables");
function textToSqlite(text) {
const result = (0, ast_1.parse)(text);
const table_list = (0, sort_tables_1.sortTables)(result.table_list);
let up = '';
let down = '';
table_list.forEach(table => {
const field_list = table.field_list.slice();
const fieldNames = {};
if (field_list.length === 0) {
field_list.push({
name: 'id',
type: 'integer',
is_primary_key: true,
is_null: false,
is_unique: false,
is_unsigned: false,
is_zerofill: false,
default_value: undefined,
references: undefined,
collate: undefined,
});
}
// const fields: Record<string, 1> = {}
up += /* sql */ `
create table if not exists ${table.name} (`;
field_list.forEach((field, i) => {
fieldNames[field.name] = 1;
const is_first = i === 0;
if (is_first) {
up += `
`;
}
else {
up += `
, `;
}
up += toSqliteColumnSql(field);
});
if (!fieldNames.created_at && !fieldNames.updated_at) {
up += /* sql */ `
, created_at text not null default CURRENT_TIMESTAMP
, updated_at text null`;
}
up += /* sql */ `
);
`;
down =
/* sql */ `
drop table if exists ${table.name};
` + down;
});
up = up
.replace(/\r\n\r\n/, '\r\n')
.replace(/\n\n/g, '\n')
.trim();
down = down
.replace(/\r\n\r\n/, '\r\n')
.replace(/\n\n/g, '\n')
.trim();
return { up, down };
}
function toSqliteColumnSql(field) {
const name = wrapSqliteName(field.name);
if (field.is_primary_key) {
return `${name} integer primary key`;
}
let type = field.type;
// TODO add check constraints for varchar and char
if (type.match(/^string/i)) {
type = 'text';
}
let enums = '';
if (type.match(/^enum/i)) {
enums = type.replace(/^enum/i, '');
type = 'text';
}
let sql = `${name} ${type}`;
if (field.collate) {
sql += ` collate ${field.collate}`;
}
if (field.is_null) {
sql += ` null`;
}
else {
sql += ` not null`;
}
if (field.is_unique) {
sql += ` unique`;
}
if (field.default_value) {
sql += ` default ${field.default_value}`;
}
if (enums) {
sql += ` check(${name} in ${enums})`;
}
const ref = field.references;
if (ref) {
const table = wrapSqliteName(ref.table);
const field = wrapSqliteName(ref.field);
sql += ` references ${table}(${field})`;
}
return sql;
}
function wrapSqliteName(name) {
// only check in dev mode
// if (name.startsWith('`') && name.endsWith('`')) {
// throw new Error(`name is already wrapped: ${name}`)
// }
name = (0, ast_1.unwrapQuotedName)(name);
return '`' + name + '`';
}