more code cleaning

This commit is contained in:
Kononnable 2018-12-08 12:49:57 +01:00
parent a4592ffb4d
commit 721a85a0b9
15 changed files with 379 additions and 373 deletions

View File

@ -10,7 +10,7 @@ import * as TomgUtils from "./Utils";
export class Engine {
constructor(
private driver: AbstractDriver,
public Options: EngineOptions
public Options: IEngineOptions
) {}
public async createModelFromDatabase(): Promise<boolean> {
@ -88,7 +88,7 @@ export class Engine {
});
});
element.GenerateConstructor = this.Options.constructor;
element.Imports.filter(function(elem, index, self) {
element.Imports.filter((elem, index, self) => {
return index === self.indexOf(elem);
});
let casedFileName = "";
@ -186,13 +186,13 @@ export class Engine {
}
});
Handlebars.registerHelper({
eq: (v1, v2) => v1 === v2,
ne: (v1, v2) => v1 !== v2,
lt: (v1, v2) => v1 < v2,
gt: (v1, v2) => v1 > v2,
lte: (v1, v2) => v1 <= v2,
gte: (v1, v2) => v1 >= v2,
and: (v1, v2) => v1 && v2,
eq: (v1, v2) => v1 === v2,
gt: (v1, v2) => v1 > v2,
gte: (v1, v2) => v1 >= v2,
lt: (v1, v2) => v1 < v2,
lte: (v1, v2) => v1 <= v2,
ne: (v1, v2) => v1 !== v2,
or: (v1, v2) => v1 || v2
});
}
@ -214,7 +214,7 @@ export class Engine {
);
}
private createTypeOrmConfig(resultPath) {
if (this.Options.schemaName == "") {
if (this.Options.schemaName === "") {
fs.writeFileSync(
path.resolve(resultPath, "ormconfig.json"),
`[
@ -258,7 +258,7 @@ export class Engine {
}
}
}
export interface EngineOptions {
export interface IEngineOptions {
host: string;
port: number;
databaseName: string;

View File

@ -10,7 +10,7 @@ export class NamingStrategy extends AbstractNamingStrategy {
): string {
const isRelationToMany = relation.isOneToMany || relation.isManyToMany;
const ownerEntity = dbModel.entities.find(
v => v.EntityName == relation.ownerTable
v => v.EntityName === relation.ownerTable
)!;
let columnName =
@ -25,19 +25,19 @@ export class NamingStrategy extends AbstractNamingStrategy {
columnName.toLowerCase().lastIndexOf("id")
);
}
if (!isNaN(parseInt(columnName[columnName.length - 1]))) {
if (!isNaN(parseInt(columnName[columnName.length - 1], 10))) {
columnName = columnName.substring(0, columnName.length - 1);
}
if (!isNaN(parseInt(columnName[columnName.length - 1]))) {
if (!isNaN(parseInt(columnName[columnName.length - 1], 10))) {
columnName = columnName.substring(0, columnName.length - 1);
}
columnName += isRelationToMany ? "s" : "";
if (
relation.relationType != "ManyToMany" &&
columnOldName != columnName
relation.relationType !== "ManyToMany" &&
columnOldName !== columnName
) {
if (ownerEntity.Columns.some(v => v.tsName == columnName)) {
if (ownerEntity.Columns.some(v => v.tsName === columnName)) {
columnName = columnName + "_";
for (let i = 2; i <= ownerEntity.Columns.length; i++) {
columnName =
@ -48,8 +48,8 @@ export class NamingStrategy extends AbstractNamingStrategy {
if (
ownerEntity.Columns.every(
v =>
v.tsName != columnName ||
columnName == columnOldName
v.tsName !== columnName ||
columnName === columnOldName
)
) {
break;

View File

@ -288,7 +288,7 @@ export abstract class AbstractDriver {
}
public GetRelationsFromRelationTempInfo(
relationsTemp: RelationTempInfo[],
relationsTemp: IRelationTempInfo[],
entities: EntityInfo[]
) {
relationsTemp.forEach(relationTmp => {
@ -356,9 +356,9 @@ export abstract class AbstractDriver {
let isOneToMany: boolean;
isOneToMany = false;
const index = ownerEntity.Indexes.find(
index =>
index.isUnique &&
index.columns.some(
ind =>
ind.isUnique &&
ind.columns.some(
col => col.name === ownerColumn!.tsName
)
);

View File

@ -1,27 +1,28 @@
import { AbstractDriver } from "./AbstractDriver";
import * as MSSQL from "mssql";
import { ColumnInfo } from "../models/ColumnInfo";
import { EntityInfo } from "../models/EntityInfo";
import * as TomgUtils from "../Utils";
import { AbstractDriver } from "./AbstractDriver";
export class MssqlDriver extends AbstractDriver {
GetAllTablesQuery = async (schema: string) => {
private Connection: MSSQL.ConnectionPool;
public GetAllTablesQuery = async (schema: string) => {
const request = new MSSQL.Request(this.Connection);
const response: {
const response: Array<{
TABLE_SCHEMA: string;
TABLE_NAME: string;
}[] = (await request.query(
}> = (await request.query(
`SELECT TABLE_SCHEMA,TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE='BASE TABLE' and TABLE_SCHEMA in (${schema})`
)).recordset;
return response;
};
async GetCoulmnsFromEntity(
public async GetCoulmnsFromEntity(
entities: EntityInfo[],
schema: string
): Promise<EntityInfo[]> {
const request = new MSSQL.Request(this.Connection);
const response: {
const response: Array<{
TABLE_NAME: string;
COLUMN_NAME: string;
COLUMN_DEFAULT: string;
@ -32,7 +33,7 @@ export class MssqlDriver extends AbstractDriver {
NUMERIC_SCALE: number;
IsIdentity: number;
IsUnique: number;
}[] = (await request.query(`SELECT TABLE_NAME,COLUMN_NAME,COLUMN_DEFAULT,IS_NULLABLE,
}> = (await request.query(`SELECT TABLE_NAME,COLUMN_NAME,COLUMN_DEFAULT,IS_NULLABLE,
DATA_TYPE,CHARACTER_MAXIMUM_LENGTH,NUMERIC_PRECISION,NUMERIC_SCALE,
COLUMNPROPERTY(object_id(TABLE_NAME), COLUMN_NAME, 'IsIdentity') IsIdentity,
(SELECT count(*)
@ -52,113 +53,113 @@ export class MssqlDriver extends AbstractDriver {
return filterVal.TABLE_NAME == ent.EntityName;
})
.forEach(resp => {
let colInfo: ColumnInfo = new ColumnInfo();
const colInfo: ColumnInfo = new ColumnInfo();
colInfo.tsName = resp.COLUMN_NAME;
colInfo.sqlName = resp.COLUMN_NAME;
colInfo.is_nullable = resp.IS_NULLABLE == "YES";
colInfo.is_generated = resp.IsIdentity == 1;
colInfo.is_unique = resp.IsUnique == 1;
colInfo.isNullable = resp.IS_NULLABLE == "YES";
colInfo.isGenerated = resp.IsIdentity == 1;
colInfo.isUnique = resp.IsUnique == 1;
colInfo.default = resp.COLUMN_DEFAULT;
colInfo.sql_type = resp.DATA_TYPE;
colInfo.sqlType = resp.DATA_TYPE;
switch (resp.DATA_TYPE) {
case "bigint":
colInfo.ts_type = "string";
colInfo.tsType = "string";
break;
case "bit":
colInfo.ts_type = "boolean";
colInfo.tsType = "boolean";
break;
case "decimal":
colInfo.ts_type = "number";
colInfo.tsType = "number";
break;
case "int":
colInfo.ts_type = "number";
colInfo.tsType = "number";
break;
case "money":
colInfo.ts_type = "number";
colInfo.tsType = "number";
break;
case "numeric":
colInfo.ts_type = "number";
colInfo.tsType = "number";
break;
case "smallint":
colInfo.ts_type = "number";
colInfo.tsType = "number";
break;
case "smallmoney":
colInfo.ts_type = "number";
colInfo.tsType = "number";
break;
case "tinyint":
colInfo.ts_type = "number";
colInfo.tsType = "number";
break;
case "float":
colInfo.ts_type = "number";
colInfo.tsType = "number";
break;
case "real":
colInfo.ts_type = "number";
colInfo.tsType = "number";
break;
case "date":
colInfo.ts_type = "Date";
colInfo.tsType = "Date";
break;
case "datetime2":
colInfo.ts_type = "Date";
colInfo.tsType = "Date";
break;
case "datetime":
colInfo.ts_type = "Date";
colInfo.tsType = "Date";
break;
case "datetimeoffset":
colInfo.ts_type = "Date";
colInfo.tsType = "Date";
break;
case "smalldatetime":
colInfo.ts_type = "Date";
colInfo.tsType = "Date";
break;
case "time":
colInfo.ts_type = "Date";
colInfo.tsType = "Date";
break;
case "char":
colInfo.ts_type = "string";
colInfo.tsType = "string";
break;
case "text":
colInfo.ts_type = "string";
colInfo.tsType = "string";
break;
case "varchar":
colInfo.ts_type = "string";
colInfo.tsType = "string";
break;
case "nchar":
colInfo.ts_type = "string";
colInfo.tsType = "string";
break;
case "ntext":
colInfo.ts_type = "string";
colInfo.tsType = "string";
break;
case "nvarchar":
colInfo.ts_type = "string";
colInfo.tsType = "string";
break;
case "binary":
colInfo.ts_type = "Buffer";
colInfo.tsType = "Buffer";
break;
case "image":
colInfo.ts_type = "Buffer";
colInfo.tsType = "Buffer";
break;
case "varbinary":
colInfo.ts_type = "Buffer";
colInfo.tsType = "Buffer";
break;
case "hierarchyid":
colInfo.ts_type = "string";
colInfo.tsType = "string";
break;
case "sql_variant":
colInfo.ts_type = "string";
colInfo.tsType = "string";
break;
case "timestamp":
colInfo.ts_type = "Date";
colInfo.tsType = "Date";
break;
case "uniqueidentifier":
colInfo.ts_type = "string";
colInfo.tsType = "string";
break;
case "xml":
colInfo.ts_type = "string";
colInfo.tsType = "string";
break;
case "geometry":
colInfo.ts_type = "string";
colInfo.tsType = "string";
break;
case "geography":
colInfo.ts_type = "string";
colInfo.tsType = "string";
break;
default:
TomgUtils.LogError(
@ -173,7 +174,7 @@ export class MssqlDriver extends AbstractDriver {
if (
this.ColumnTypesWithPrecision.some(
v => v == colInfo.sql_type
v => v == colInfo.sqlType
)
) {
colInfo.numericPrecision = resp.NUMERIC_PRECISION;
@ -181,7 +182,7 @@ export class MssqlDriver extends AbstractDriver {
}
if (
this.ColumnTypesWithLength.some(
v => v == colInfo.sql_type
v => v == colInfo.sqlType
)
) {
colInfo.lenght =
@ -190,23 +191,25 @@ export class MssqlDriver extends AbstractDriver {
: null;
}
if (colInfo.sql_type) ent.Columns.push(colInfo);
if (colInfo.sqlType) {
ent.Columns.push(colInfo);
}
});
});
return entities;
}
async GetIndexesFromEntity(
public async GetIndexesFromEntity(
entities: EntityInfo[],
schema: string
): Promise<EntityInfo[]> {
const request = new MSSQL.Request(this.Connection);
const response: {
const response: Array<{
TableName: string;
IndexName: string;
ColumnName: string;
is_unique: number;
is_primary_key: number;
}[] = (await request.query(`SELECT
}> = (await request.query(`SELECT
TableName = t.name,
IndexName = ind.name,
ColumnName = col.name,
@ -230,8 +233,8 @@ ORDER BY
response
.filter(filterVal => filterVal.TableName == ent.EntityName)
.forEach(resp => {
let indexInfo: IndexInfo = <IndexInfo>{};
let indexColumnInfo: IndexColumnInfo = <IndexColumnInfo>{};
let indexInfo: IndexInfo = {} as IndexInfo;
const indexColumnInfo: IndexColumnInfo = {} as IndexColumnInfo;
if (
ent.Indexes.filter(filterVal => {
return filterVal.name == resp.IndexName;
@ -241,7 +244,7 @@ ORDER BY
return filterVal.name == resp.IndexName;
})[0];
} else {
indexInfo.columns = <IndexColumnInfo[]>[];
indexInfo.columns = [] as IndexColumnInfo[];
indexInfo.name = resp.IndexName;
indexInfo.isUnique = resp.is_unique == 1;
indexInfo.isPrimaryKey = resp.is_primary_key == 1;
@ -254,12 +257,12 @@ ORDER BY
return entities;
}
async GetRelations(
public async GetRelations(
entities: EntityInfo[],
schema: string
): Promise<EntityInfo[]> {
const request = new MSSQL.Request(this.Connection);
const response: {
const response: Array<{
TableWithForeignKey: string;
FK_PartNo: number;
ForeignKeyColumn: string;
@ -268,7 +271,7 @@ ORDER BY
onDelete: "RESTRICT" | "CASCADE" | "SET_NULL" | "NO_ACTION";
onUpdate: "RESTRICT" | "CASCADE" | "SET_NULL" | "NO_ACTION";
object_id: number;
}[] = (await request.query(`select
}> = (await request.query(`select
parentTable.name as TableWithForeignKey,
fkc.constraint_column_id as FK_PartNo,
parentColumn.name as ForeignKeyColumn,
@ -295,13 +298,13 @@ where
fk.is_disabled=0 and fk.is_ms_shipped=0 and parentSchema.name in (${schema})
order by
TableWithForeignKey, FK_PartNo`)).recordset;
let relationsTemp: RelationTempInfo[] = <RelationTempInfo[]>[];
const relationsTemp: IRelationTempInfo[] = [] as IRelationTempInfo[];
response.forEach(resp => {
let rels = relationsTemp.find(
val => val.object_id == resp.object_id
);
if (rels == undefined) {
rels = <RelationTempInfo>{};
rels = {} as IRelationTempInfo;
rels.ownerColumnsNames = [];
rels.referencedColumnsNames = [];
switch (resp.onDelete) {
@ -340,12 +343,12 @@ order by
);
return entities;
}
async DisconnectFromServer() {
if (this.Connection) await this.Connection.close();
public async DisconnectFromServer() {
if (this.Connection) {
await this.Connection.close();
}
}
private Connection: MSSQL.ConnectionPool;
async ConnectToServer(
public async ConnectToServer(
database: string,
server: string,
port: number,
@ -353,16 +356,16 @@ order by
password: string,
ssl: boolean
) {
let config: MSSQL.config = {
database: database,
server: server,
port: port,
user: user,
password: password,
const config: MSSQL.config = {
database,
options: {
encrypt: ssl,
appName: "typeorm-model-generator"
}
appName: "typeorm-model-generator",
encrypt: ssl
},
password,
port,
server,
user
};
const promise = new Promise<boolean>((resolve, reject) => {
@ -382,19 +385,19 @@ order by
await promise;
}
async CreateDB(dbName: string) {
public async CreateDB(dbName: string) {
const request = new MSSQL.Request(this.Connection);
await request.query(`CREATE DATABASE ${dbName}; `);
}
async UseDB(dbName: string) {
public async UseDB(dbName: string) {
const request = new MSSQL.Request(this.Connection);
await request.query(`USE ${dbName}; `);
}
async DropDB(dbName: string) {
public async DropDB(dbName: string) {
const request = new MSSQL.Request(this.Connection);
await request.query(`DROP DATABASE ${dbName}; `);
}
async CheckIfDBExists(dbName: string): Promise<boolean> {
public async CheckIfDBExists(dbName: string): Promise<boolean> {
const request = new MSSQL.Request(this.Connection);
const resp = await request.query(
`SELECT name FROM master.sys.databases WHERE name = N'${dbName}' `

View File

@ -47,121 +47,121 @@ export class MysqlDriver extends AbstractDriver {
const colInfo: ColumnInfo = new ColumnInfo();
colInfo.tsName = resp.COLUMN_NAME;
colInfo.sqlName = resp.COLUMN_NAME;
colInfo.is_nullable = resp.IS_NULLABLE === "YES";
colInfo.is_generated = resp.IsIdentity === 1;
colInfo.is_unique = resp.column_key === "UNI";
colInfo.isNullable = resp.IS_NULLABLE === "YES";
colInfo.isGenerated = resp.IsIdentity === 1;
colInfo.isUnique = resp.column_key === "UNI";
colInfo.default = resp.COLUMN_DEFAULT;
colInfo.sql_type = resp.DATA_TYPE;
colInfo.sqlType = resp.DATA_TYPE;
switch (resp.DATA_TYPE) {
case "int":
colInfo.ts_type = "number";
colInfo.tsType = "number";
break;
case "tinyint":
if (resp.column_type === "tinyint(1)") {
colInfo.width = 1;
colInfo.ts_type = "boolean";
colInfo.tsType = "boolean";
} else {
colInfo.ts_type = "number";
colInfo.tsType = "number";
}
break;
case "smallint":
colInfo.ts_type = "number";
colInfo.tsType = "number";
break;
case "mediumint":
colInfo.ts_type = "number";
colInfo.tsType = "number";
break;
case "bigint":
colInfo.ts_type = "string";
colInfo.tsType = "string";
break;
case "float":
colInfo.ts_type = "number";
colInfo.tsType = "number";
break;
case "double":
colInfo.ts_type = "number";
colInfo.tsType = "number";
break;
case "decimal":
colInfo.ts_type = "string";
colInfo.tsType = "string";
break;
case "date":
colInfo.ts_type = "string";
colInfo.tsType = "string";
break;
case "datetime":
colInfo.ts_type = "Date";
colInfo.tsType = "Date";
break;
case "timestamp":
colInfo.ts_type = "Date";
colInfo.tsType = "Date";
break;
case "time":
colInfo.ts_type = "string";
colInfo.tsType = "string";
break;
case "year":
colInfo.ts_type = "number";
colInfo.tsType = "number";
break;
case "char":
colInfo.ts_type = "string";
colInfo.tsType = "string";
break;
case "varchar":
colInfo.ts_type = "string";
colInfo.tsType = "string";
break;
case "blob":
colInfo.ts_type = "Buffer";
colInfo.tsType = "Buffer";
break;
case "text":
colInfo.ts_type = "string";
colInfo.tsType = "string";
break;
case "tinyblob":
colInfo.ts_type = "Buffer";
colInfo.tsType = "Buffer";
break;
case "tinytext":
colInfo.ts_type = "string";
colInfo.tsType = "string";
break;
case "mediumblob":
colInfo.ts_type = "Buffer";
colInfo.tsType = "Buffer";
break;
case "mediumtext":
colInfo.ts_type = "string";
colInfo.tsType = "string";
break;
case "longblob":
colInfo.ts_type = "Buffer";
colInfo.tsType = "Buffer";
break;
case "longtext":
colInfo.ts_type = "string";
colInfo.tsType = "string";
break;
case "enum":
colInfo.ts_type = "string";
colInfo.tsType = "string";
colInfo.enumOptions = resp.column_type
.substring(5, resp.column_type.length - 1)
.replace(/\'/gi, '"');
break;
case "json":
colInfo.ts_type = "Object";
colInfo.tsType = "Object";
break;
case "binary":
colInfo.ts_type = "Buffer";
colInfo.tsType = "Buffer";
break;
case "geometry":
colInfo.ts_type = "string";
colInfo.tsType = "string";
break;
case "point":
colInfo.ts_type = "string";
colInfo.tsType = "string";
break;
case "linestring":
colInfo.ts_type = "string";
colInfo.tsType = "string";
break;
case "polygon":
colInfo.ts_type = "string";
colInfo.tsType = "string";
break;
case "multipoint":
colInfo.ts_type = "string";
colInfo.tsType = "string";
break;
case "multilinestring":
colInfo.ts_type = "string";
colInfo.tsType = "string";
break;
case "multipolygon":
colInfo.ts_type = "string";
colInfo.tsType = "string";
break;
case "geometrycollection":
colInfo.ts_type = "string";
colInfo.tsType = "string";
break;
default:
TomgUtils.LogError(
@ -175,7 +175,7 @@ export class MysqlDriver extends AbstractDriver {
}
if (
this.ColumnTypesWithPrecision.some(
v => v === colInfo.sql_type
v => v === colInfo.sqlType
)
) {
colInfo.numericPrecision = resp.NUMERIC_PRECISION;
@ -183,7 +183,7 @@ export class MysqlDriver extends AbstractDriver {
}
if (
this.ColumnTypesWithLength.some(
v => v === colInfo.sql_type
v => v === colInfo.sqlType
)
) {
colInfo.lenght =
@ -194,8 +194,8 @@ export class MysqlDriver extends AbstractDriver {
if (
this.ColumnTypesWithWidth.some(
v =>
v === colInfo.sql_type &&
colInfo.ts_type !== "boolean"
v === colInfo.sqlType &&
colInfo.tsType !== "boolean"
)
) {
colInfo.width =
@ -204,7 +204,7 @@ export class MysqlDriver extends AbstractDriver {
: null;
}
if (colInfo.sql_type) {
if (colInfo.sqlType) {
ent.Columns.push(colInfo);
}
});
@ -284,13 +284,13 @@ export class MysqlDriver extends AbstractDriver {
TABLE_SCHEMA = SCHEMA()
AND CU.REFERENCED_TABLE_NAME IS NOT NULL;
`);
const relationsTemp: RelationTempInfo[] = [] as RelationTempInfo[];
const relationsTemp: IRelationTempInfo[] = [] as IRelationTempInfo[];
response.forEach(resp => {
let rels = relationsTemp.find(
val => val.object_id === resp.object_id
);
if (rels === undefined) {
rels = {} as RelationTempInfo;
rels = {} as IRelationTempInfo;
rels.ownerColumnsNames = [];
rels.referencedColumnsNames = [];
rels.actionOnDelete =
@ -343,20 +343,20 @@ export class MysqlDriver extends AbstractDriver {
config = {
database,
host: server,
port,
user,
password,
port,
ssl: {
rejectUnauthorized: false
}
},
user
};
} else {
config = {
database,
host: server,
password,
port,
user,
password
user
};
}

View File

@ -42,7 +42,7 @@ export class OracleDriver extends AbstractDriver {
DATA_PRECISION: number;
DATA_SCALE: number;
IDENTITY_COLUMN: string;
IS_UNIQUE: Number;
IS_UNIQUE: number;
}> = (await this.Connection
.execute(`SELECT utc.TABLE_NAME, utc.COLUMN_NAME, DATA_DEFAULT, NULLABLE, DATA_TYPE, DATA_LENGTH,
DATA_PRECISION, DATA_SCALE, IDENTITY_COLUMN,
@ -58,102 +58,102 @@ export class OracleDriver extends AbstractDriver {
const colInfo: ColumnInfo = new ColumnInfo();
colInfo.tsName = resp.COLUMN_NAME;
colInfo.sqlName = resp.COLUMN_NAME;
colInfo.is_nullable = resp.NULLABLE === "Y";
colInfo.is_generated = resp.IDENTITY_COLUMN === "YES";
colInfo.isNullable = resp.NULLABLE === "Y";
colInfo.isGenerated = resp.IDENTITY_COLUMN === "YES";
colInfo.default =
!resp.DATA_DEFAULT || resp.DATA_DEFAULT.includes('"')
? null
: resp.DATA_DEFAULT;
colInfo.is_unique = resp.IS_UNIQUE > 0;
colInfo.isUnique = resp.IS_UNIQUE > 0;
resp.DATA_TYPE = resp.DATA_TYPE.replace(/\([0-9]+\)/g, "");
colInfo.sql_type = resp.DATA_TYPE.toLowerCase();
colInfo.sqlType = resp.DATA_TYPE.toLowerCase();
switch (resp.DATA_TYPE.toLowerCase()) {
case "char":
colInfo.ts_type = "string";
colInfo.tsType = "string";
break;
case "nchar":
colInfo.ts_type = "string";
colInfo.tsType = "string";
break;
case "nvarchar2":
colInfo.ts_type = "string";
colInfo.tsType = "string";
break;
case "varchar2":
colInfo.ts_type = "string";
colInfo.tsType = "string";
break;
case "long":
colInfo.ts_type = "string";
colInfo.tsType = "string";
break;
case "raw":
colInfo.ts_type = "Buffer";
colInfo.tsType = "Buffer";
break;
case "long raw":
colInfo.ts_type = "Buffer";
colInfo.tsType = "Buffer";
break;
case "number":
colInfo.ts_type = "number";
colInfo.tsType = "number";
break;
case "numeric":
colInfo.ts_type = "number";
colInfo.tsType = "number";
break;
case "float":
colInfo.ts_type = "number";
colInfo.tsType = "number";
break;
case "dec":
colInfo.ts_type = "number";
colInfo.tsType = "number";
break;
case "decimal":
colInfo.ts_type = "number";
colInfo.tsType = "number";
break;
case "integer":
colInfo.ts_type = "number";
colInfo.tsType = "number";
break;
case "int":
colInfo.ts_type = "number";
colInfo.tsType = "number";
break;
case "smallint":
colInfo.ts_type = "number";
colInfo.tsType = "number";
break;
case "real":
colInfo.ts_type = "number";
colInfo.tsType = "number";
break;
case "double precision":
colInfo.ts_type = "number";
colInfo.tsType = "number";
break;
case "date":
colInfo.ts_type = "Date";
colInfo.tsType = "Date";
break;
case "timestamp":
colInfo.ts_type = "Date";
colInfo.tsType = "Date";
break;
case "timestamp with time zone":
colInfo.ts_type = "Date";
colInfo.tsType = "Date";
break;
case "timestamp with local time zone":
colInfo.ts_type = "Date";
colInfo.tsType = "Date";
break;
case "interval year to month":
colInfo.ts_type = "string";
colInfo.tsType = "string";
break;
case "interval day to second":
colInfo.ts_type = "string";
colInfo.tsType = "string";
break;
case "bfile":
colInfo.ts_type = "Buffer";
colInfo.tsType = "Buffer";
break;
case "blob":
colInfo.ts_type = "Buffer";
colInfo.tsType = "Buffer";
break;
case "clob":
colInfo.ts_type = "string";
colInfo.tsType = "string";
break;
case "nclob":
colInfo.ts_type = "string";
colInfo.tsType = "string";
break;
case "rowid":
colInfo.ts_type = "number";
colInfo.tsType = "number";
break;
case "urowid":
colInfo.ts_type = "number";
colInfo.tsType = "number";
break;
default:
TomgUtils.LogError(
@ -163,7 +163,7 @@ export class OracleDriver extends AbstractDriver {
}
if (
this.ColumnTypesWithPrecision.some(
v => v === colInfo.sql_type
v => v === colInfo.sqlType
)
) {
colInfo.numericPrecision = resp.DATA_PRECISION;
@ -171,14 +171,14 @@ export class OracleDriver extends AbstractDriver {
}
if (
this.ColumnTypesWithLength.some(
v => v === colInfo.sql_type
v => v === colInfo.sqlType
)
) {
colInfo.lenght =
resp.DATA_LENGTH > 0 ? resp.DATA_LENGTH : null;
}
if (colInfo.sql_type) {
if (colInfo.sqlType) {
ent.Columns.push(colInfo);
}
});
@ -254,13 +254,13 @@ export class OracleDriver extends AbstractDriver {
ORDER BY OWNER_TABLE_NAME ASC, owner.CONSTRAINT_NAME ASC, OWNER_POSITION ASC`))
.rows!;
const relationsTemp: RelationTempInfo[] = [] as RelationTempInfo[];
const relationsTemp: IRelationTempInfo[] = [] as IRelationTempInfo[];
response.forEach(resp => {
let rels = relationsTemp.find(
val => val.object_id === resp.CONSTRAINT_NAME
);
if (rels === undefined) {
rels = {} as RelationTempInfo;
rels = {} as IRelationTempInfo;
rels.ownerColumnsNames = [];
rels.referencedColumnsNames = [];
rels.actionOnDelete =
@ -296,23 +296,23 @@ export class OracleDriver extends AbstractDriver {
let config: any;
if (user === String(process.env.ORACLE_UsernameSys)) {
config /*Oracle.IConnectionAttributes*/ = {
user,
password,
connectString: `${server}:${port}/${database}`,
externalAuth: ssl,
privilege: this.Oracle.SYSDBA
password,
privilege: this.Oracle.SYSDBA,
user
};
} else {
config /*Oracle.IConnectionAttributes*/ = {
user,
password,
connectString: `${server}:${port}/${database}`,
externalAuth: ssl
externalAuth: ssl,
password,
user
};
}
const that = this;
const promise = new Promise<boolean>((resolve, reject) => {
this.Oracle.getConnection(config, function(err, connection) {
this.Oracle.getConnection(config, (err, connection) => {
if (!err) {
that.Connection = connection;
resolve(true);
@ -338,7 +338,9 @@ export class OracleDriver extends AbstractDriver {
);
await this.Connection.execute(`GRANT CONNECT TO ${dbName}`);
}
public async UseDB(dbName: string) {}
public async UseDB(dbName: string) {
// not supported
}
public async DropDB(dbName: string) {
await this.Connection.execute(`DROP USER ${dbName} CASCADE`);
}

View File

@ -1,27 +1,27 @@
import { AbstractDriver } from "./AbstractDriver";
import * as PG from "pg";
import { ColumnInfo } from "../models/ColumnInfo";
import { EntityInfo } from "../models/EntityInfo";
import * as TomgUtils from "../Utils";
import { AbstractDriver } from "./AbstractDriver";
export class PostgresDriver extends AbstractDriver {
private Connection: PG.Client;
GetAllTablesQuery = async (schema: string) => {
const response: {
public GetAllTablesQuery = async (schema: string) => {
const response: Array<{
TABLE_SCHEMA: string;
TABLE_NAME: string;
}[] = (await this.Connection.query(
}> = (await this.Connection.query(
`SELECT table_schema as "TABLE_SCHEMA",table_name as "TABLE_NAME" FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE='BASE TABLE' AND table_schema in (${schema}) `
)).rows;
return response;
};
async GetCoulmnsFromEntity(
public async GetCoulmnsFromEntity(
entities: EntityInfo[],
schema: string
): Promise<EntityInfo[]> {
const response: {
const response: Array<{
table_name: string;
column_name: string;
udt_name: string;
@ -33,7 +33,7 @@ export class PostgresDriver extends AbstractDriver {
numeric_scale: number;
isidentity: string;
isunique: number;
}[] = (await this.Connection
}> = (await this.Connection
.query(`SELECT table_name,column_name,udt_name,column_default,is_nullable,
data_type,character_maximum_length,numeric_precision,numeric_scale,
case when column_default LIKE 'nextval%' then 'YES' else 'NO' end isidentity,
@ -52,13 +52,13 @@ export class PostgresDriver extends AbstractDriver {
response
.filter(filterVal => filterVal.table_name == ent.EntityName)
.forEach(resp => {
let colInfo: ColumnInfo = new ColumnInfo();
const colInfo: ColumnInfo = new ColumnInfo();
colInfo.tsName = resp.column_name;
colInfo.sqlName = resp.column_name;
colInfo.is_nullable = resp.is_nullable == "YES";
colInfo.is_generated = resp.isidentity == "YES";
colInfo.is_unique = resp.isunique == 1;
colInfo.default = colInfo.is_generated
colInfo.isNullable = resp.is_nullable == "YES";
colInfo.isGenerated = resp.isidentity == "YES";
colInfo.isUnique = resp.isunique == 1;
colInfo.default = colInfo.isGenerated
? null
: resp.column_default;
@ -89,19 +89,19 @@ export class PostgresDriver extends AbstractDriver {
}
return;
}
colInfo.sql_type = columnTypes.sql_type;
colInfo.ts_type = columnTypes.ts_type;
colInfo.is_array = columnTypes.is_array;
if (colInfo.is_array) {
colInfo.ts_type = <any>colInfo.ts_type
colInfo.sqlType = columnTypes.sql_type;
colInfo.tsType = columnTypes.ts_type;
colInfo.isArray = columnTypes.is_array;
if (colInfo.isArray) {
colInfo.tsType = colInfo.tsType
.split("|")
.map(x => x.replace("|", "").trim() + "[]")
.join(" | ");
.join(" | ") as any;
}
if (
this.ColumnTypesWithPrecision.some(
v => v == colInfo.sql_type
v => v == colInfo.sqlType
)
) {
colInfo.numericPrecision = resp.numeric_precision;
@ -109,7 +109,7 @@ export class PostgresDriver extends AbstractDriver {
}
if (
this.ColumnTypesWithLength.some(
v => v == colInfo.sql_type
v => v == colInfo.sqlType
)
) {
colInfo.lenght =
@ -119,7 +119,7 @@ export class PostgresDriver extends AbstractDriver {
}
if (
this.ColumnTypesWithWidth.some(
v => v == colInfo.sql_type
v => v == colInfo.sqlType
)
) {
colInfo.width =
@ -127,7 +127,7 @@ export class PostgresDriver extends AbstractDriver {
? resp.character_maximum_length
: null;
}
if (colInfo.sql_type && colInfo.ts_type) {
if (colInfo.sqlType && colInfo.tsType) {
ent.Columns.push(colInfo);
}
});
@ -135,8 +135,8 @@ export class PostgresDriver extends AbstractDriver {
return entities;
}
MatchColumnTypes(data_type: string, udt_name: string) {
let ret: {
public MatchColumnTypes(dataType: string, udtName: string) {
const ret: {
ts_type:
| "number"
| "string"
@ -151,8 +151,8 @@ export class PostgresDriver extends AbstractDriver {
sql_type: string | null;
is_array: boolean;
} = { ts_type: null, sql_type: null, is_array: false };
ret.sql_type = data_type;
switch (data_type) {
ret.sql_type = dataType;
switch (dataType) {
case "int2":
ret.ts_type = "number";
break;
@ -338,18 +338,15 @@ export class PostgresDriver extends AbstractDriver {
ret.ts_type = "string";
break;
case "ARRAY":
const z = this.MatchColumnTypes(
udt_name.substring(1),
udt_name
);
const z = this.MatchColumnTypes(udtName.substring(1), udtName);
ret.ts_type = z.ts_type;
ret.sql_type = z.sql_type;
ret.is_array = true;
break;
case "USER-DEFINED":
ret.sql_type = udt_name;
ret.sql_type = udtName;
ret.ts_type = "string";
switch (udt_name) {
switch (udtName) {
case "citext":
case "hstore":
case "geometry":
@ -367,17 +364,17 @@ export class PostgresDriver extends AbstractDriver {
}
return ret;
}
async GetIndexesFromEntity(
public async GetIndexesFromEntity(
entities: EntityInfo[],
schema: string
): Promise<EntityInfo[]> {
const response: {
const response: Array<{
tablename: string;
indexname: string;
columnname: string;
is_unique: number;
is_primary_key: number;
}[] = (await this.Connection.query(`SELECT
}> = (await this.Connection.query(`SELECT
c.relname AS tablename,
i.relname as indexname,
f.attname AS columnname,
@ -405,8 +402,8 @@ export class PostgresDriver extends AbstractDriver {
response
.filter(filterVal => filterVal.tablename == ent.EntityName)
.forEach(resp => {
let indexInfo: IndexInfo = <IndexInfo>{};
let indexColumnInfo: IndexColumnInfo = <IndexColumnInfo>{};
let indexInfo: IndexInfo = {} as IndexInfo;
const indexColumnInfo: IndexColumnInfo = {} as IndexColumnInfo;
if (
ent.Indexes.filter(
filterVal => filterVal.name == resp.indexname
@ -416,7 +413,7 @@ export class PostgresDriver extends AbstractDriver {
filterVal => filterVal.name == resp.indexname
)!;
} else {
indexInfo.columns = <IndexColumnInfo[]>[];
indexInfo.columns = [] as IndexColumnInfo[];
indexInfo.name = resp.indexname;
indexInfo.isUnique = resp.is_unique == 1;
indexInfo.isPrimaryKey = resp.is_primary_key == 1;
@ -432,11 +429,11 @@ export class PostgresDriver extends AbstractDriver {
return entities;
}
async GetRelations(
public async GetRelations(
entities: EntityInfo[],
schema: string
): Promise<EntityInfo[]> {
const response: {
const response: Array<{
tablewithforeignkey: string;
fk_partno: number;
foreignkeycolumn: string;
@ -445,7 +442,7 @@ export class PostgresDriver extends AbstractDriver {
ondelete: "RESTRICT" | "CASCADE" | "SET NULL" | "NO ACTION";
onupdate: "RESTRICT" | "CASCADE" | "SET NULL" | "NO ACTION";
object_id: string;
}[] = (await this.Connection.query(`SELECT
}> = (await this.Connection.query(`SELECT
con.relname AS tablewithforeignkey,
att.attnum as fk_partno,
att2.attname AS foreignkeycolumn,
@ -483,13 +480,13 @@ export class PostgresDriver extends AbstractDriver {
AND att2.attrelid = con.conrelid
AND att2.attnum = con.parent
and rc.constraint_name= con.conname`)).rows;
let relationsTemp: RelationTempInfo[] = <RelationTempInfo[]>[];
const relationsTemp: IRelationTempInfo[] = [] as IRelationTempInfo[];
response.forEach(resp => {
let rels = relationsTemp.find(
val => val.object_id == resp.object_id
);
if (rels == undefined) {
rels = <RelationTempInfo>{};
rels = {} as IRelationTempInfo;
rels.ownerColumnsNames = [];
rels.referencedColumnsNames = [];
rels.actionOnDelete =
@ -510,7 +507,7 @@ export class PostgresDriver extends AbstractDriver {
);
return entities;
}
async DisconnectFromServer() {
public async DisconnectFromServer() {
if (this.Connection) {
const promise = new Promise<boolean>((resolve, reject) => {
this.Connection.end(err => {
@ -530,7 +527,7 @@ export class PostgresDriver extends AbstractDriver {
}
}
async ConnectToServer(
public async ConnectToServer(
database: string,
server: string,
port: number,
@ -539,12 +536,12 @@ export class PostgresDriver extends AbstractDriver {
ssl: boolean
) {
this.Connection = new PG.Client({
database: database,
database,
host: server,
port: port,
user: user,
password: password,
ssl: ssl
password,
port,
ssl,
user
});
const promise = new Promise<boolean>((resolve, reject) => {
@ -565,16 +562,16 @@ export class PostgresDriver extends AbstractDriver {
await promise;
}
async CreateDB(dbName: string) {
public async CreateDB(dbName: string) {
await this.Connection.query(`CREATE DATABASE ${dbName}; `);
}
async UseDB(dbName: string) {
public async UseDB(dbName: string) {
await this.Connection.query(`USE ${dbName}; `);
}
async DropDB(dbName: string) {
public async DropDB(dbName: string) {
await this.Connection.query(`DROP DATABASE ${dbName}; `);
}
async CheckIfDBExists(dbName: string): Promise<boolean> {
public async CheckIfDBExists(dbName: string): Promise<boolean> {
const resp = await this.Connection.query(
`SELECT datname FROM pg_database WHERE datname ='${dbName}' `
);

View File

@ -6,7 +6,7 @@ import { AbstractDriver } from "./AbstractDriver";
export class SqliteDriver extends AbstractDriver {
public sqlite = require("sqlite3").verbose();
public db: any;
public tablesWithGeneratedPrimaryKey: String[] = new Array<String>();
public tablesWithGeneratedPrimaryKey: string[] = new Array<string>();
public GetAllTablesQuery: any;
public async GetAllTables(schema: string): Promise<EntityInfo[]> {
@ -43,103 +43,103 @@ export class SqliteDriver extends AbstractDriver {
const colInfo: ColumnInfo = new ColumnInfo();
colInfo.tsName = resp.name;
colInfo.sqlName = resp.name;
colInfo.is_nullable = resp.notnull == 0;
colInfo.isNullable = resp.notnull === 0;
colInfo.isPrimary = resp.pk > 0;
colInfo.default = resp.dflt_value ? resp.dflt_value : null;
colInfo.sql_type = resp.type
colInfo.sqlType = resp.type
.replace(/\([0-9 ,]+\)/g, "")
.toLowerCase()
.trim();
colInfo.is_generated =
colInfo.isGenerated =
colInfo.isPrimary &&
this.tablesWithGeneratedPrimaryKey.includes(ent.EntityName);
switch (colInfo.sql_type) {
switch (colInfo.sqlType) {
case "int":
colInfo.ts_type = "number";
colInfo.tsType = "number";
break;
case "integer":
colInfo.ts_type = "number";
colInfo.tsType = "number";
break;
case "int2":
colInfo.ts_type = "number";
colInfo.tsType = "number";
break;
case "int8":
colInfo.ts_type = "number";
colInfo.tsType = "number";
break;
case "tinyint":
colInfo.ts_type = "number";
colInfo.tsType = "number";
break;
case "smallint":
colInfo.ts_type = "number";
colInfo.tsType = "number";
break;
case "mediumint":
colInfo.ts_type = "number";
colInfo.tsType = "number";
break;
case "bigint":
colInfo.ts_type = "string";
colInfo.tsType = "string";
break;
case "unsigned big int":
colInfo.ts_type = "string";
colInfo.tsType = "string";
break;
case "character":
colInfo.ts_type = "string";
colInfo.tsType = "string";
break;
case "varchar":
colInfo.ts_type = "string";
colInfo.tsType = "string";
break;
case "varying character":
colInfo.ts_type = "string";
colInfo.tsType = "string";
break;
case "nchar":
colInfo.ts_type = "string";
colInfo.tsType = "string";
break;
case "native character":
colInfo.ts_type = "string";
colInfo.tsType = "string";
break;
case "nvarchar":
colInfo.ts_type = "string";
colInfo.tsType = "string";
break;
case "text":
colInfo.ts_type = "string";
colInfo.tsType = "string";
break;
case "blob":
colInfo.ts_type = "Buffer";
colInfo.tsType = "Buffer";
break;
case "clob":
colInfo.ts_type = "string";
colInfo.tsType = "string";
break;
case "real":
colInfo.ts_type = "number";
colInfo.tsType = "number";
break;
case "double":
colInfo.ts_type = "number";
colInfo.tsType = "number";
break;
case "double precision":
colInfo.ts_type = "number";
colInfo.tsType = "number";
break;
case "float":
colInfo.ts_type = "number";
colInfo.tsType = "number";
break;
case "numeric":
colInfo.ts_type = "number";
colInfo.tsType = "number";
break;
case "decimal":
colInfo.ts_type = "number";
colInfo.tsType = "number";
break;
case "boolean":
colInfo.ts_type = "boolean";
colInfo.tsType = "boolean";
break;
case "date":
colInfo.ts_type = "string";
colInfo.tsType = "string";
break;
case "datetime":
colInfo.ts_type = "Date";
colInfo.tsType = "Date";
break;
default:
console.log(colInfo.sql_type.toLowerCase().trim());
console.log(colInfo.sqlType.toLowerCase().trim());
TomgUtils.LogError(
`Unknown column type: ${
colInfo.sql_type
colInfo.sqlType
} table name: ${ent.EntityName} column name: ${
resp.name
}`
@ -149,7 +149,7 @@ export class SqliteDriver extends AbstractDriver {
const options = resp.type.match(/\([0-9 ,]+\)/g);
if (
this.ColumnTypesWithPrecision.some(
v => v == colInfo.sql_type
v => v === colInfo.sqlType
) &&
options
) {
@ -162,7 +162,7 @@ export class SqliteDriver extends AbstractDriver {
}
if (
this.ColumnTypesWithLength.some(
v => v == colInfo.sql_type
v => v === colInfo.sqlType
) &&
options
) {
@ -174,8 +174,8 @@ export class SqliteDriver extends AbstractDriver {
if (
this.ColumnTypesWithWidth.some(
v =>
v == colInfo.sql_type &&
colInfo.ts_type != "boolean"
v === colInfo.sqlType &&
colInfo.tsType !== "boolean"
) &&
options
) {
@ -185,7 +185,7 @@ export class SqliteDriver extends AbstractDriver {
) as any;
}
if (colInfo.sql_type) {
if (colInfo.sqlType) {
ent.Columns.push(colInfo);
}
});
@ -216,26 +216,26 @@ export class SqliteDriver extends AbstractDriver {
const indexColumnInfo: IndexColumnInfo = {} as IndexColumnInfo;
if (
ent.Indexes.filter(filterVal => {
return filterVal.name == resp.name;
return filterVal.name === resp.name;
}).length > 0
) {
indexInfo = ent.Indexes.find(
filterVal => filterVal.name == resp.name
filterVal => filterVal.name === resp.name
)!;
} else {
indexInfo.columns = [] as IndexColumnInfo[];
indexInfo.name = resp.name;
indexInfo.isUnique = resp.unique == 1;
indexInfo.isUnique = resp.unique === 1;
ent.Indexes.push(indexInfo);
}
indexColumnInfo.name = element.name;
if (
indexColumnsResponse.length == 1 &&
indexColumnsResponse.length === 1 &&
indexInfo.isUnique
) {
ent.Columns.filter(
v => v.tsName == indexColumnInfo.name
).map(v => (v.is_unique = true));
v => v.tsName === indexColumnInfo.name
).map(v => (v.isUnique = true));
}
indexInfo.columns.push(indexColumnInfo);
});
@ -259,15 +259,15 @@ export class SqliteDriver extends AbstractDriver {
on_delete: "RESTRICT" | "CASCADE" | "SET NULL" | "NO ACTION";
match: string;
}>(`PRAGMA foreign_key_list('${entity.EntityName}');`);
const relationsTemp: RelationTempInfo[] = [] as RelationTempInfo[];
const relationsTemp: IRelationTempInfo[] = [] as IRelationTempInfo[];
response.forEach(resp => {
const rels = {} as RelationTempInfo;
const rels = {} as IRelationTempInfo;
rels.ownerColumnsNames = [];
rels.referencedColumnsNames = [];
rels.actionOnDelete =
resp.on_delete == "NO ACTION" ? null : resp.on_delete;
resp.on_delete === "NO ACTION" ? null : resp.on_delete;
rels.actionOnUpdate =
resp.on_update == "NO ACTION" ? null : resp.on_update;
resp.on_update === "NO ACTION" ? null : resp.on_update;
rels.ownerTable = entity.EntityName;
rels.referencedTable = resp.table;
relationsTemp.push(rels);
@ -296,7 +296,9 @@ export class SqliteDriver extends AbstractDriver {
await this.UseDB(database);
}
public async CreateDB(dbName: string) {}
public async CreateDB(dbName: string) {
// not supported
}
public async UseDB(dbName: string) {
const promise = new Promise<boolean>((resolve, reject) => {
this.db = new this.sqlite.Database(dbName, err => {
@ -310,7 +312,9 @@ export class SqliteDriver extends AbstractDriver {
});
return promise;
}
public async DropDB(dbName: string) {}
public async DropDB(dbName: string) {
// not supported
}
public async CheckIfDBExists(dbName: string): Promise<boolean> {
return true;
}
@ -319,7 +323,7 @@ export class SqliteDriver extends AbstractDriver {
let ret: any;
const promise = new Promise<boolean>((resolve, reject) => {
this.db.serialize(() => {
this.db.all(sql, [], function(err, row) {
this.db.all(sql, [], (err, row) => {
if (!err) {
ret = row;
resolve(true);

View File

@ -8,24 +8,24 @@ import {Index,Entity, PrimaryColumn, PrimaryGeneratedColumn, Column, OneToOne, O
{{/isPrimaryKey}}{{/Indexes}}export class {{toEntityName EntityName}} {
{{#Columns}}
{{^relations}}{{#is_generated}} @PrimaryGeneratedColumn({
type:"{{sql_type}}", {{/is_generated}}{{^is_generated}} @Column("{{sql_type}}",{ {{#is_nullable}}
nullable:true,{{/is_nullable}}{{^is_nullable}}
nullable:false,{{/is_nullable}}{{#isPrimary}}
primary:{{isPrimary}},{{/isPrimary}}{{/is_generated}}{{#is_unique}}
unique: true,{{/is_unique}}{{#lenght}}
{{^relations}}{{#isGenerated}} @PrimaryGeneratedColumn({
type:"{{sqlType}}", {{/isGenerated}}{{^isGenerated}} @Column("{{sqlType}}",{ {{#isNullable}}
nullable:true,{{/isNullable}}{{^isNullable}}
nullable:false,{{/isNullable}}{{#isPrimary}}
primary:{{isPrimary}},{{/isPrimary}}{{/isGenerated}}{{#isUnique}}
unique: true,{{/isUnique}}{{#lenght}}
length:{{.}},{{/lenght}}{{#width}}
width:{{.}},{{/width}}{{#default}}
default:"{{.}}",{{/default}}{{#numericPrecision}}
precision:{{.}},{{/numericPrecision}}{{#numericScale}}
scale:{{.}},{{/numericScale}}{{#enumOptions}}
enum:[{{.}}],{{/enumOptions}}{{#is_array}}
array:{{is_array}},{{/is_array}}
enum:[{{.}}],{{/enumOptions}}{{#isArray}}
array:{{isArray}},{{/isArray}}
name:"{{sqlName}}"
})
{{printPropertyVisibility}}{{toPropertyName tsName}}:{{ts_type}}{{#is_nullable}} | null{{/is_nullable}};
{{printPropertyVisibility}}{{toPropertyName tsName}}:{{tsType}}{{#isNullable}} | null{{/isNullable}};
{{/relations}}{{#relations}}
@{{relationType}}(type=>{{toEntityName relatedTable}}, {{toEntityName relatedTable}}=>{{toEntityName relatedTable}}.{{#if isOwner}}{{toPropertyName ownerColumn}},{ {{#../isPrimary}}primary:true,{{/../isPrimary}}{{^../is_nullable}} nullable:false,{{/../is_nullable}}{{#actionOnDelete}}onDelete: '{{.}}',{{/actionOnDelete}}{{#actionOnUpdate}}onUpdate: '{{.}}'{{/actionOnUpdate}} }{{else}}{{toPropertyName relatedColumn}}{{#if (or actionOnDelete actionOnUpdate ) }}{{#actionOnDelete}},{ onDelete: '{{.}}' ,{{/actionOnDelete}}{{#actionOnUpdate}}onUpdate: '{{.}}'{{/actionOnUpdate}} }{{/if}}{{/if}}){{#isOwner}}
@{{relationType}}(type=>{{toEntityName relatedTable}}, {{toEntityName relatedTable}}=>{{toEntityName relatedTable}}.{{#if isOwner}}{{toPropertyName ownerColumn}},{ {{#../isPrimary}}primary:true,{{/../isPrimary}}{{^../isNullable}} nullable:false,{{/../isNullable}}{{#actionOnDelete}}onDelete: '{{.}}',{{/actionOnDelete}}{{#actionOnUpdate}}onUpdate: '{{.}}'{{/actionOnUpdate}} }{{else}}{{toPropertyName relatedColumn}}{{#if (or actionOnDelete actionOnUpdate ) }}{{#actionOnDelete}},{ onDelete: '{{.}}' ,{{/actionOnDelete}}{{#actionOnUpdate}}onUpdate: '{{.}}'{{/actionOnUpdate}} }{{/if}}{{/if}}){{#isOwner}}
{{#if isManyToMany}}@JoinTable(){{else}}@JoinColumn({ name:'{{ ../sqlName}}'}){{/if}}{{/isOwner}}
{{#if (or isOneToMany isManyToMany)}}{{printPropertyVisibility}}{{toPropertyName ../tsName}}:{{toLazy (concat (toEntityName relatedTable) "[]")}};
{{else}}{{printPropertyVisibility}}{{toPropertyName ../tsName}}:{{toLazy (concat (toEntityName relatedTable) ' | null')}};
@ -33,7 +33,7 @@ import {Index,Entity, PrimaryColumn, PrimaryGeneratedColumn, Column, OneToOne, O
{{#if relationIdField }}
@RelationId(({{../../EntityName}}: {{../../EntityName}}) => {{../../EntityName}}.{{toPropertyName ../tsName}})
{{toPropertyName ../tsName}}Id: {{#if isOneToOne}}{{toLazy ../ts_type}}{{else}}{{toLazy (concat ../ts_type "[]")}}{{/if}};{{/if}}{{/relations}}
{{toPropertyName ../tsName}}Id: {{#if isOneToOne}}{{toLazy ../tsType}}{{else}}{{toLazy (concat ../tsType "[]")}}{{/if}};{{/if}}{{/relations}}
{{/Columns}}
{{#if GenerateConstructor}}
constructor(init?: Partial<{{toEntityName EntityName}}>) {

View File

@ -17,13 +17,13 @@ const argv = Yargs.usage(
)
.option("h", {
alias: "host",
describe: "IP adress/Hostname for database server",
default: "127.0.0.1"
default: "127.0.0.1",
describe: "IP adress/Hostname for database server"
})
.option("d", {
alias: "database",
describe: "Database name(or path for sqlite)",
demand: true
demand: true,
describe: "Database name(or path for sqlite)"
})
.option("u", {
alias: "user",
@ -31,8 +31,8 @@ const argv = Yargs.usage(
})
.option("x", {
alias: "pass",
describe: "Password for database server",
default: ""
default: "",
describe: "Password for database server"
})
.option("p", {
alias: "port",
@ -40,14 +40,14 @@ const argv = Yargs.usage(
})
.option("e", {
alias: "engine",
describe: "Database engine",
choices: ["mssql", "postgres", "mysql", "mariadb", "oracle", "sqlite"],
default: "mssql"
default: "mssql",
describe: "Database engine"
})
.option("o", {
alias: "output",
describe: "Where to place generated models",
default: path.resolve(process.cwd(), "output")
default: path.resolve(process.cwd(), "output"),
describe: "Where to place generated models"
})
.option("s", {
alias: "schema",
@ -60,50 +60,50 @@ const argv = Yargs.usage(
})
.option("noConfig", {
boolean: true,
describe: `Doesn't create tsconfig.json and ormconfig.json`,
default: false
default: false,
describe: `Doesn't create tsconfig.json and ormconfig.json`
})
.option("cf", {
alias: "case-file",
describe: "Convert file names to specified case",
choices: ["pascal", "param", "camel", "none"],
default: "none"
default: "none",
describe: "Convert file names to specified case"
})
.option("ce", {
alias: "case-entity",
describe: "Convert class names to specified case",
choices: ["pascal", "camel", "none"],
default: "none"
default: "none",
describe: "Convert class names to specified case"
})
.option("cp", {
alias: "case-property",
describe: "Convert property names to specified case",
choices: ["pascal", "camel", "none"],
default: "none"
default: "none",
describe: "Convert property names to specified case"
})
.option("pv", {
alias: "property-visibility",
describe: "Defines which visibility should have the generated property",
choices: ["public", "protected", "private", "none"],
default: "none"
default: "none",
describe: "Defines which visibility should have the generated property"
})
.option("lazy", {
describe: "Generate lazy relations",
boolean: true,
default: false
default: false,
describe: "Generate lazy relations"
})
.option("namingStrategy", {
describe: "Use custom naming strategy"
})
.option("relationIds", {
describe: "Generate RelationId fields",
boolean: true,
default: false
default: false,
describe: "Generate RelationId fields"
})
.option("generateConstructor", {
describe: "Generate constructor allowing partial initialization",
boolean: true,
default: false
default: false,
describe: "Generate constructor allowing partial initialization"
}).argv;
let driver: AbstractDriver;
@ -147,7 +147,7 @@ switch (argv.e) {
throw new Error("Database engine not recognized.");
}
let namingStrategy: AbstractNamingStrategy;
if (argv.namingStrategy && argv.namingStrategy != "") {
if (argv.namingStrategy && argv.namingStrategy !== "") {
const req = require(argv.namingStrategy);
namingStrategy = new req.NamingStrategy();
} else {
@ -155,24 +155,24 @@ if (argv.namingStrategy && argv.namingStrategy != "") {
}
const engine = new Engine(driver, {
host: argv.h,
port: parseInt(argv.p) || standardPort,
constructor: argv.generateConstructor,
convertCaseEntity: argv.ce,
convertCaseFile: argv.cf,
convertCaseProperty: argv.cp,
databaseName: argv.d ? argv.d.toString() : null,
user: argv.u ? argv.u.toString() : standardUser,
password: argv.x ? argv.x.toString() : null,
databaseType: argv.e,
host: argv.h,
lazy: argv.lazy,
namingStrategy,
noConfigs: argv.noConfig,
password: argv.x ? argv.x.toString() : null,
port: parseInt(argv.p, 10) || standardPort,
propertyVisibility: argv.pv,
relationIds: argv.relationIds,
resultsPath: argv.o ? argv.o.toString() : null,
schemaName: argv.s ? argv.s.toString() : standardSchema,
ssl: argv.ssl,
noConfigs: argv.noConfig,
convertCaseFile: argv.cf,
convertCaseEntity: argv.ce,
convertCaseProperty: argv.cp,
propertyVisibility: argv.pv,
lazy: argv.lazy,
constructor: argv.generateConstructor,
relationIds: argv.relationIds,
namingStrategy
user: argv.u ? argv.u.toString() : standardUser
});
console.log(TomgUtils.packageVersion());

View File

@ -4,9 +4,9 @@ export class ColumnInfo {
public tsName: string = "";
public sqlName: string = "";
public default: string | null = null;
public is_nullable: boolean = false;
public is_unique: boolean = false;
public ts_type:
public isNullable: boolean = false;
public isUnique: boolean = false;
public tsType:
| "number"
| "string"
| "boolean"
@ -16,12 +16,12 @@ export class ColumnInfo {
| "string | Object"
| "string | string[]"
| "any";
public sql_type: string;
public sqlType: string;
public lenght: number | null = null;
public width: number | null = null;
public isPrimary: boolean = false;
public is_generated: boolean = false;
public is_array: boolean = false;
public isGenerated: boolean = false;
public isArray: boolean = false;
public numericPrecision: number | null = null;
public numericScale: number | null = null;
public enumOptions: string | null = null;

View File

@ -13,13 +13,13 @@ export class EntityInfo {
const imports: string[] = [];
this.Columns.forEach(column => {
column.relations.forEach(relation => {
if (this.EntityName != relation.relatedTable) {
if (this.EntityName !== relation.relatedTable) {
imports.push(relation.relatedTable);
}
});
});
this.UniqueImports = imports.filter(
(elem, index, self) => index == self.indexOf(elem)
(elem, index, self) => index === self.indexOf(elem)
);
}
}

View File

@ -21,15 +21,15 @@ export class RelationInfo {
public relationIdField: boolean = false;
get isOneToMany(): boolean {
return this.relationType == "OneToMany";
return this.relationType === "OneToMany";
}
get isManyToMany(): boolean {
return this.relationType == "ManyToMany";
return this.relationType === "ManyToMany";
}
get isOneToOne(): boolean {
return this.relationType == "OneToOne";
return this.relationType === "OneToOne";
}
get isManyToOne(): boolean {
return this.relationType == "ManyToOne";
return this.relationType === "ManyToOne";
}
}

View File

@ -1,4 +1,4 @@
interface RelationTempInfo {
interface IRelationTempInfo {
ownerTable: string;
ownerColumnsNames: string[];
referencedTable: string;

View File

@ -83,19 +83,19 @@ describe('MssqlDriver', function () {
expected[0].Columns.push({
lenght: null,
default: 'a',
is_nullable: true,
isNullable: true,
isPrimary: false,
is_generated: true,
isGenerated: true,
tsName: 'name',
sqlName: 'name',
numericPrecision: null,
numericScale: null,
width: null,
sql_type: 'int',
ts_type: 'number',
sqlType: 'int',
tsType: 'number',
enumOptions: null,
is_unique:false,
is_array:false,
isUnique:false,
isArray:false,
relations: [] as RelationInfo[],
})
const result = await driver.GetCoulmnsFromEntity(entities, 'schema');