Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Foreign keys for pg SQL DDL #14

Closed
wants to merge 5 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
24 changes: 18 additions & 6 deletions lib/ddl.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,7 @@
'use strict';

const { DatabaseSchema } = require('./schema-db.js');

const toLowerCamel = s => s.charAt(0).toLowerCase() + s.slice(1);
const toUpperCamel = s => s.charAt(0).toUpperCase() + s.slice(1);
const isUpperCamel = s => s[0] === s[0].toUpperCase();
const { toLowerCamel, toUpperCamel, isUpperCamel } = require('./utils.js');

const DB_RELATION = 1;
const DB_FIELD = 2;
Expand Down Expand Up @@ -45,6 +42,21 @@ const createIndex = (entityName, { name, unique, index }) => {
return `CREATE ${uni}INDEX ${idxName} ON ${idxOn};`;
};

const foreignKey = (entityName, { name, type }) => {
const fk = 'fk' + entityName + toUpperCamel(name);
return (
`ALTER TABLE "${entityName}" ADD CONSTRAINT "${fk}" ` +
`FOREIGN KEY ("${name}") ` +
`REFERENCES "${type}" ("${type}Id") ON DELETE CASCADE;`
);
};

const primaryKey = entityName => {
const fieldName = toLowerCamel(entityName) + 'Id';
const constraint = `"pk${entityName}" PRIMARY KEY ("${fieldName}")`;
return `ALTER TABLE "${entityName}" ADD CONSTRAINT ${constraint};`;
};

class PgSchema extends DatabaseSchema {
async preprocessEntity(name, entity) {
const fields = Object.keys(entity);
Expand All @@ -63,8 +75,7 @@ class PgSchema extends DatabaseSchema {
sql.push(`CREATE TABLE "${name}" (`);
const pk = toLowerCamel(name) + 'Id';
sql.push(` "${pk}" bigint unsigned generated always as identity,`);
const constraint = `"pk${name}" PRIMARY KEY ("${pk}")`;
idx.push(`ALTER TABLE "${name}" ADD CONSTRAINT ${constraint};`);
idx.push(primaryKey(name));
const fields = Object.keys(entity);
for (const fieldName of fields) {
const def = entity[fieldName];
Expand All @@ -75,6 +86,7 @@ class PgSchema extends DatabaseSchema {
if (!pgType) throw new Error(`Unknown type: ${def.type}`);
const pgField = def.name + (kind === DB_FIELD ? '' : 'Id');
sql.push(` "${pgField}" ${pgType}${nullable},`);
if (kind === DB_RELATION) idx.push(foreignKey(name, def));
}
if (def.unique || def.index) idx.push(createIndex(name, def));
}
Expand Down
24 changes: 22 additions & 2 deletions lib/schema-db.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,14 @@
const path = require('path');
const fs = require('fs').promises;

const { isUpperCamel } = require('./utils.js');
const { Schema } = require('./schema.js');

class DatabaseSchema {
constructor(schemaPath) {
this.path = schemaPath;
this.entities = new Map();
this.order = new Set();
return this.load();
}

Expand All @@ -30,6 +32,11 @@ class DatabaseSchema {
for (const [name, entity] of this.entities) {
await this.preprocessEntity(name, entity);
}
for (const [name, entity] of this.entities) {
if (!this.order.has(name)) {
await this.reorderEntity(name, entity);
}
}
}

async preprocessEntity(name, entity) {
Expand All @@ -38,9 +45,21 @@ class DatabaseSchema {
throw new Error(`Method is not implemented: preprocessEntity(${args})`);
}

async reorderEntity(name, entity) {
const fields = Object.keys(entity);
for (const field of fields) {
const { type } = entity[field];
if (isUpperCamel(type) && !this.order.has(type)) {
await this.reorderEntity(type, this.entities.get(type));
}
}
this.order.add(name);
}

async validate() {
console.log('Validating metaschema');
for (const [name, entity] of this.entities) {
for (const name of this.order) {
const entity = this.entities.get(name);
const fields = Object.keys(entity);
if (entity) console.log(` ${name}: ${fields.length} fields`);
}
Expand All @@ -49,7 +68,8 @@ class DatabaseSchema {
async generate(outputPath) {
console.log('Generating SQL DDL script ' + outputPath);
const script = [];
for (const [name, entity] of this.entities) {
for (const name of this.order) {
const entity = this.entities.get(name);
const sql = await this.generateEntity(name, entity);
script.push(sql);
}
Expand Down
7 changes: 7 additions & 0 deletions lib/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,16 @@ const joinIterable = (val, sep) => {
return res;
};

const toLowerCamel = s => s.charAt(0).toLowerCase() + s.slice(1);
const toUpperCamel = s => s.charAt(0).toUpperCase() + s.slice(1);
const isUpperCamel = s => !!s && s[0] === s[0].toUpperCase();

module.exports = {
escapeIdentifier,
escapeKey,
mapJoinIterable,
joinIterable,
toLowerCamel,
toUpperCamel,
isUpperCamel,
};
1 change: 1 addition & 0 deletions test/schema/Country.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
({
planet: 'Planet',
name: { type: 'string', unique: true },
});
4 changes: 4 additions & 0 deletions test/schema/District.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
({
city: 'City',
name: { type: 'string', unique: true },
});
3 changes: 3 additions & 0 deletions test/schema/Planet.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
({
name: { type: 'string', unique: true },
});