import {connection} from "./connection"; import {PoolConnection} from "mysql2/promise"; import {config} from "./config"; import * as t from "io-ts"; import * as d from "fp-ts/Either"; import {tools} from "./tools"; import {dataObject} from "./dataObject"; import * as fs from "fs"; import * as handlebars from "handlebars"; type TableDataHeader = { table_name:string, dataKeys:string[], dataKeysString:string, dataKeysPrimary:string[], dataKeysPrimaryString:string, dataKeysAutoInc:string[], dataKeysAutoIncString:string, dataKeysUnique:string[], dataKeysUniqueString:string, required:string[], requiredString:string, data_properties_index:string[], data_properties_indexString:string, data_properties:string[], data_propertiesString:string, data_property_types:{[key:string]:string}, data_property_typesString:string, properties:TableDataPropertyExtended[], } const TableDataPropertyCodec = t.type({ Field:t.string, Type:t.string, Null:t.string, Key:t.string, Default:t.union([t.string,t.null]), Extra:t.string, }); type TableDataProperty = t.TypeOf; type TableDataPropertyExtended = TableDataProperty & { object_types:string, default_value:string|number, } export class build{ private static connection:PoolConnection; public static CONFIG_LOCATION = ""; public static async run(target_dir?:string, target_dataObject:string = "./dataObject", restrict_to_local:boolean = true){ if(restrict_to_local && config.getEnv() != config.ENV.local){ throw new Error("unable to run orm build on a non-local environment"); } if(typeof target_dir === "undefined") target_dir = config.getBaseDirectory(); if(config.getConfig().verbose_log) console.log(`running orm build on ${target_dir}`); let tables = await build.getTablesInfo(); for(let index in tables){ let table = tables[index]; if(config.getConfig().verbose_log) console.log("creating db orm class for "+table.table_name); let tpl = await fs.promises.readFile(__dirname+"/dataObject_template.hbs","utf-8"); let template = handlebars.compile(tpl); // @ts-ignore table[`target_dataObject`] = target_dataObject; let result = template(table); await fs.promises.writeFile(`${target_dir}/${table.table_name}.ts`,result); } console.log("db orm ts classes build successful"); } public static async getTablesInfo():Promise{ if(config.getConfig().verbose_log) console.log("retrieving tables information"); build.connection = await connection.getConnection() as PoolConnection; let tables = await build.initiateAndRetrieveTableNames(); if(config.getConfig().verbose_log) console.log(`found table:${tables.length}`); for(let i=0; i{ let result = await connection.execute({sql:"SHOW TABLES"}) as object[]; let tablesData:TableDataHeader[] = []; for(let i=0; i{ let result = await connection.execute({sql:`DESCRIBE ${dataHeader.table_name}`}) as object[]; for(let i=0; i