Skip to content

Commit

Permalink
feat: use metaschema Model and Schema classes
Browse files Browse the repository at this point in the history
Refs: #117
Refs: metarhia/metaschema#291

PR-URL: #125
  • Loading branch information
tshemsedinov committed May 6, 2021
1 parent 4c83e01 commit a3275eb
Show file tree
Hide file tree
Showing 7 changed files with 18 additions and 241 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Expand Up @@ -8,6 +8,7 @@
- async col(table, field, conditions): Array
- async dict(table, fields, conditions): Object
- Update metaschema to v1.1.0
- Use metaschema Model and Schema classes

## [1.0.1][] - 2021-04-04

Expand Down
40 changes: 12 additions & 28 deletions lib/model-db.js
Expand Up @@ -2,25 +2,19 @@

const path = require('path');
const fs = require('fs').promises;
const { Model } = require('metaschema');

const schema = require('./schema.js');
const { cpdir, shorten } = require('./utils.js');

const dbms = {};

const loadModel = async (modelPath) => {
const structs = await schema.readDirectory(modelPath);
const database = structs.get('.database');
structs.delete('.database');
if (!database) {
const dbmsTypes = dbms.pg.types;
const model = await Model.load(modelPath, dbmsTypes);
if (!model.database) {
throw new Error(`File is not found: ${modelPath}/.database.js`);
}
const dbmsTypes = dbms[database.driver].types;
const customTypes = structs.get('.types') || {};
structs.delete('.types');
const types = { ...dbmsTypes, ...customTypes };
const databaseModel = new schema.DomainModel(database, types, structs);
return databaseModel;
return model;
};

const getPreviousVersion = async (modelPath) => {
Expand All @@ -38,19 +32,7 @@ const getPreviousVersion = async (modelPath) => {
}
}
if (version === 0) return null;
const previousPath = path.join(historyPath, previousName);
return loadModel(previousPath);
};

const saveTypes = async (model, outputPath) => {
const filePath = path.join(outputPath, 'database.d.ts');
console.log('Generating types ' + shorten(filePath));
const dts = [];
for (const name of model.order) {
const entity = model.entities.get(name);
dts.push(schema.toInterface(name, entity));
}
await fs.writeFile(filePath, dts.join('\n\n') + '\n');
return path.join(historyPath, previousName);
};

const create = async (modelPath, outputPath) => {
Expand All @@ -64,20 +46,22 @@ const create = async (modelPath, outputPath) => {
}
const dbPath = path.join(outputPath, 'database.sql');
await fs.writeFile(dbPath, script.join('\n\n') + '\n');
await saveTypes(model, outputPath);
const dtsPath = path.join(outputPath, 'database.d.ts');
await model.saveTypes(dtsPath);
};

const generate = async (modelPath) => {
const model = await loadModel(modelPath);
const { name, driver, version } = model.database;
const now = new Date().toISOString().substring(0, 10);
console.log(`Generate migration: ${driver}:${name} v${version} (${now})`);
const ps = await getPreviousVersion(modelPath);
const previousPath = await getPreviousVersion(modelPath);
const ps = await loadModel(previousPath);
if (!ps) {
console.log('Previous version is not found in ../history');
return;
}
const folder = path.basename(ps.path);
const folder = path.basename(previousPath);
const date = folder.substring(0, folder.lastIndexOf('v') - 1);
console.log(`Previous version: v${ps.database.version} (${date})`);
if (ps.database.version >= version) {
Expand All @@ -91,7 +75,7 @@ const generate = async (modelPath) => {
console.log(`Save history: ${shorten(newFolder)}`);
await fs.mkdir(newFolder);
await cpdir(modelPath, newFolder);
console.log(`Migration up: ${shorten(migUp)})`);
console.log(`Migration up: ${shorten(migUp)}`);
console.log(`Migration down: ${shorten(migDn)}`);
};

Expand Down
8 changes: 4 additions & 4 deletions lib/model-pg.js
Expand Up @@ -5,7 +5,7 @@ const { Client } = require('pg');
const { dbms } = require('./model-db.js');
const { Schema } = require('metaschema');

const { toLowerCamel, toUpperCamel, isUpperCamel } = require('./utils.js');
const { isFirstUpper, toLowerCamel, toUpperCamel } = require('metautil');

const DB_RELATION = 1;
const DB_FIELD = 2;
Expand Down Expand Up @@ -95,7 +95,7 @@ const primaryCustom = (entityName, fields, entity) => {
if (!def) continue;
const { type } = def;
if (!type) continue;
const ref = isUpperCamel(type);
const ref = isFirstUpper(type);
idx[i] = ref ? field + 'Id' : field;
}
}
Expand All @@ -122,7 +122,7 @@ const createEntity = (model, name) => {
const def = entity.fields[field];
const nullable = def.required ? ' NOT NULL' : '';
if (def.type) {
const kind = isUpperCamel(def.type) ? DB_RELATION : DB_FIELD;
const kind = isFirstUpper(def.type) ? DB_RELATION : DB_FIELD;
let pgType = kind === DB_FIELD ? model.types[def.type] : 'bigint';
if (!pgType) throw new Error(`Unknown type: ${def.type}`);
const pgField = field + (kind === DB_FIELD ? '' : 'Id');
Expand Down Expand Up @@ -161,7 +161,7 @@ const execute = async (database, sql) => {
};

dbms.pg = {
types: PG_TYPES, // entities.set('.types', { ...PG_TYPES, ...types });
types: PG_TYPES,
execute,
createEntity,
};
133 changes: 0 additions & 133 deletions lib/schema.js

This file was deleted.

7 changes: 0 additions & 7 deletions lib/utils.js
Expand Up @@ -13,19 +13,12 @@ const cpdir = async (from, to) => {
}
};

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();

const shorten = (dir) => {
const pos = dir.lastIndexOf('/');
return pos !== -1 ? dir.substring(pos) : dir;
};

module.exports = {
cpdir,
toLowerCamel,
toUpperCamel,
isUpperCamel,
shorten,
};
3 changes: 1 addition & 2 deletions metasql.js
Expand Up @@ -2,8 +2,7 @@

const database = require('./lib/database.js');
const model = require('./lib/model-db.js');
const schema = require('./lib/schema.js');

require('./lib/model-pg.js');

module.exports = { ...database, ...model, ...schema };
module.exports = { ...database, ...model };
67 changes: 0 additions & 67 deletions test/schema.js

This file was deleted.

0 comments on commit a3275eb

Please sign in to comment.