From b5e68e6640de89f05629918e489e359ce6a03110 Mon Sep 17 00:00:00 2001 From: jusax23 Date: Wed, 15 Feb 2023 16:17:09 +0100 Subject: [PATCH 01/10] removed unimplemented and unsed Methode --- src/dbStructure.ts | 11 ----------- 1 file changed, 11 deletions(-) diff --git a/src/dbStructure.ts b/src/dbStructure.ts index 1ca68d8..26de25e 100644 --- a/src/dbStructure.ts +++ b/src/dbStructure.ts @@ -102,7 +102,6 @@ export class joinCross implements Joins{ export interface Constraint { name: string; - serialize(handler: Handler): QueryBuilder; uses(attr: Attribute): boolean; check(table: Table): boolean | string; } @@ -120,9 +119,6 @@ export class checkConstraint implements Constraint { uses(attr: Attribute): boolean { throw new Error("Method not implemented."); } - serialize(handler: Handler): QueryBuilder { - throw new Error("Method not implemented."); - } } export class uniqueConstraint implements Constraint { @@ -142,10 +138,6 @@ export class uniqueConstraint implements Constraint { uses(attr: Attribute): boolean { return this.attrs.includes(attr); } - serialize(handler: Handler): QueryBuilder { - throw new Error("Method not implemented."); - } - } export class foreignConstraint implements Constraint { @@ -161,9 +153,6 @@ export class foreignConstraint implements Constraint { this.onUpdate = onUpdate; this.onDelete = onDelete; } - serialize(handler: Handler): QueryBuilder { - throw new Error("Method not implemented."); - } uses(attr: Attribute): boolean { throw new Error("Method not implemented."); } From 2b6e4872d5b10906bcb8f570198fb5d0420eef42 Mon Sep 17 00:00:00 2001 From: jusax23 Date: Wed, 15 Feb 2023 16:22:40 +0100 Subject: [PATCH 02/10] fiexed limit --- src/defaultHandler.ts | 19 +++++++++++++------ src/query.ts | 4 +++- 2 files changed, 16 insertions(+), 7 deletions(-) diff --git a/src/defaultHandler.ts b/src/defaultHandler.ts index 25bc8b1..c643775 100644 --- a/src/defaultHandler.ts +++ b/src/defaultHandler.ts @@ -236,11 +236,11 @@ export class Handler { builder.addCode("select "); builder.append(joinArg(", ")(handler, q.attr)); builder.addCode(` from `); - if(q.from == null){ + if (q.from == null) { builder.addCode(" DUAL"); - }else if (q.from instanceof Table){ + } else if (q.from instanceof Table) { builder.addCode(q.from.serialize(handler)); - }else{ + } else { builder.append(q.from.serialize(handler)); } if (q.whereD) { @@ -255,9 +255,16 @@ export class Handler { builder.append(q.havingD.serialize(handler)); } } - if (q.havingD) { - builder.addCode(" limit "); - builder.addInjection(q.limitD); + if (q.limitD != null) { + if (q.limitOffsetD == null) { + builder.addCode(" limit "); + builder.addInjection(q.limitD); + } else { + builder.addCode(" limit "); + builder.addInjection(q.limitOffsetD); + builder.addCode(", "); + builder.addInjection(q.limitD); + } } /*builder.setHandler((json)=>{ diff --git a/src/query.ts b/src/query.ts index 9fd00d6..0c39120 100644 --- a/src/query.ts +++ b/src/query.ts @@ -83,8 +83,10 @@ export class selectQuery { return this; } limitD: number | null = null; - limit(i: number) { + limitOffsetD: number | null = null; + limit(i: number, offset: number = 0) { this.limitD = i; + this.limitOffsetD = offset; return this; } From 287de2e09fab9d7616a480ae16b2b9e3cb02961d Mon Sep 17 00:00:00 2001 From: jusax23 Date: Wed, 15 Feb 2023 16:45:55 +0100 Subject: [PATCH 03/10] moved constraint data query --- src/defaultHandler.ts | 30 +++++++++++++++++++----------- 1 file changed, 19 insertions(+), 11 deletions(-) diff --git a/src/defaultHandler.ts b/src/defaultHandler.ts index c643775..8a34be5 100644 --- a/src/defaultHandler.ts +++ b/src/defaultHandler.ts @@ -5,17 +5,9 @@ import { allModifierInput, joinType, onAction, primaryData } from "./types" export class Handler { async syncDB(db: DB, handler: Handler, deleteInDB: boolean = false) { - let gd = new QueryBuilder(); - gd.addCode(`SELECT * FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE where CONSTRAINT_SCHEMA = `); - gd.addInjection(db.name); - gd.addCode(` or TABLE_SCHEMA = `); - gd.addInjection(db.name); - gd.addCode(`;select * from information_schema.table_constraints where CONSTRAINT_SCHEMA = `); - gd.addInjection(db.name) - gd.addCode(` or TABLE_SCHEMA = `); - gd.addInjection(db.name); - - let [key, constraints] = await db.query(handler.builders.query(gd)); + //Constraint Data + let constraints = await db.query(handler.builders.query(handler.querys.listConstraints(handler, db))); + let key = await db.query(handler.builders.query(handler.querys.listConstraintDetails(handler, db))); //Table List let allTables = (await db.query(handler.builders.query(handler.querys.listTables(handler, db)))).map((d: any) => d.TABLE_NAME); @@ -334,6 +326,22 @@ export class Handler { qb.addCode(` and TABLE_TYPE = "BASE TABLE"`); return qb; }, + listConstraints: (handler: Handler, db: DB) => { + let qb = new QueryBuilder(); + qb.addCode(`select * from information_schema.table_constraints where CONSTRAINT_SCHEMA = `); + qb.addInjection(db.name); + qb.addCode(` or TABLE_SCHEMA = `); + qb.addInjection(db.name); + return qb; + }, + listConstraintDetails: (handler: Handler, db: DB) => { + let qb = new QueryBuilder(); + qb.addCode(`SELECT * FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE where CONSTRAINT_SCHEMA = `); + qb.addInjection(db.name); + qb.addCode(` or TABLE_SCHEMA = `); + qb.addInjection(db.name); + return qb; + }, create: (handler: Handler, table: Table): QueryBuilder => { const builder = new QueryBuilder(); builder.addCode(`create table if not exists ${table.toString(handler)}(`); From 5fd514332b7d1a733917a85b5f43123c3c16569b Mon Sep 17 00:00:00 2001 From: jusax23 Date: Wed, 15 Feb 2023 21:06:53 +0100 Subject: [PATCH 04/10] added target --- readme.md | 1 + 1 file changed, 1 insertion(+) diff --git a/readme.md b/readme.md index 2e2ee40..7f0eba9 100644 --- a/readme.md +++ b/readme.md @@ -12,6 +12,7 @@ Features: - [x] create Schema - [x] remove unused Schema - [x] joins +- [ ] table alias - [ ] change Schema - [ ] Key-Value Store Shortcut - [ ] Views From af4208ed3aba8b9e19f1e15b97f07add44b23417 Mon Sep 17 00:00:00 2001 From: jusax23 Date: Fri, 17 Feb 2023 22:04:24 +0100 Subject: [PATCH 05/10] pg Vorbereitung --- .gitignore | 3 +- package-lock.json | 153 +++++++++++++++++++++++++++++++++++++++++- package.json | 4 +- src/db.ts | 41 +++++++---- src/defaultHandler.ts | 66 +++++++++--------- src/types.ts | 6 ++ 6 files changed, 225 insertions(+), 48 deletions(-) diff --git a/.gitignore b/.gitignore index a3c17fd..d4f1590 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,5 @@ dist node_modules ltests -sqlsave \ No newline at end of file +sqlsave +postgresHandler.ts \ No newline at end of file diff --git a/package-lock.json b/package-lock.json index 63a0d16..5ee3cc6 100644 --- a/package-lock.json +++ b/package-lock.json @@ -9,10 +9,12 @@ "version": "1.0.0", "license": "UNLICENSED", "dependencies": { - "mariadb": "^3.0.2" + "mariadb": "^3.0.2", + "pg": "^8.9.0" }, "devDependencies": { "@types/node": "^18.11.18", + "@types/pg": "^8.6.6", "esbuild": "^0.17.4", "typescript": "^4.9.4" }, @@ -383,6 +385,25 @@ "integrity": "sha512-DHQpWGjyQKSHj3ebjFI/wRKcqQcdR+MoFBygntYOZytCqNfkd2ZC4ARDJ2DQqhjH5p85Nnd3jhUJIXrszFX/JA==", "dev": true }, + "node_modules/@types/pg": { + "version": "8.6.6", + "resolved": "https://registry.npmjs.org/@types/pg/-/pg-8.6.6.tgz", + "integrity": "sha512-O2xNmXebtwVekJDD+02udOncjVcMZQuTEQEMpKJ0ZRf5E7/9JJX3izhKUcUifBkyKpljyUM6BTgy2trmviKlpw==", + "dev": true, + "dependencies": { + "@types/node": "*", + "pg-protocol": "*", + "pg-types": "^2.2.0" + } + }, + "node_modules/buffer-writer": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/buffer-writer/-/buffer-writer-2.0.0.tgz", + "integrity": "sha512-a7ZpuTZU1TRtnwyCNW3I5dc0wWNC3VR9S++Ewyk2HHZdrO3CQJqSpd+95Us590V6AL7JqUAH2IwZ/398PmNFgw==", + "engines": { + "node": ">=4" + } + }, "node_modules/denque": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/denque/-/denque-2.1.0.tgz", @@ -487,11 +508,133 @@ "node": "*" } }, + "node_modules/packet-reader": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/packet-reader/-/packet-reader-1.0.0.tgz", + "integrity": "sha512-HAKu/fG3HpHFO0AA8WE8q2g+gBJaZ9MG7fcKk+IJPLTGAD6Psw4443l+9DGRbOIh3/aXr7Phy0TjilYivJo5XQ==" + }, + "node_modules/pg": { + "version": "8.9.0", + "resolved": "https://registry.npmjs.org/pg/-/pg-8.9.0.tgz", + "integrity": "sha512-ZJM+qkEbtOHRuXjmvBtOgNOXOtLSbxiMiUVMgE4rV6Zwocy03RicCVvDXgx8l4Biwo8/qORUnEqn2fdQzV7KCg==", + "dependencies": { + "buffer-writer": "2.0.0", + "packet-reader": "1.0.0", + "pg-connection-string": "^2.5.0", + "pg-pool": "^3.5.2", + "pg-protocol": "^1.6.0", + "pg-types": "^2.1.0", + "pgpass": "1.x" + }, + "engines": { + "node": ">= 8.0.0" + }, + "peerDependencies": { + "pg-native": ">=3.0.1" + }, + "peerDependenciesMeta": { + "pg-native": { + "optional": true + } + } + }, + "node_modules/pg-connection-string": { + "version": "2.5.0", + "resolved": "https://registry.npmjs.org/pg-connection-string/-/pg-connection-string-2.5.0.tgz", + "integrity": "sha512-r5o/V/ORTA6TmUnyWZR9nCj1klXCO2CEKNRlVuJptZe85QuhFayC7WeMic7ndayT5IRIR0S0xFxFi2ousartlQ==" + }, + "node_modules/pg-int8": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/pg-int8/-/pg-int8-1.0.1.tgz", + "integrity": "sha512-WCtabS6t3c8SkpDBUlb1kjOs7l66xsGdKpIPZsg4wR+B3+u9UAum2odSsF9tnvxg80h4ZxLWMy4pRjOsFIqQpw==", + "engines": { + "node": ">=4.0.0" + } + }, + "node_modules/pg-pool": { + "version": "3.5.2", + "resolved": "https://registry.npmjs.org/pg-pool/-/pg-pool-3.5.2.tgz", + "integrity": "sha512-His3Fh17Z4eg7oANLob6ZvH8xIVen3phEZh2QuyrIl4dQSDVEabNducv6ysROKpDNPSD+12tONZVWfSgMvDD9w==", + "peerDependencies": { + "pg": ">=8.0" + } + }, + "node_modules/pg-protocol": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/pg-protocol/-/pg-protocol-1.6.0.tgz", + "integrity": "sha512-M+PDm637OY5WM307051+bsDia5Xej6d9IR4GwJse1qA1DIhiKlksvrneZOYQq42OM+spubpcNYEo2FcKQrDk+Q==" + }, + "node_modules/pg-types": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/pg-types/-/pg-types-2.2.0.tgz", + "integrity": "sha512-qTAAlrEsl8s4OiEQY69wDvcMIdQN6wdz5ojQiOy6YRMuynxenON0O5oCpJI6lshc6scgAY8qvJ2On/p+CXY0GA==", + "dependencies": { + "pg-int8": "1.0.1", + "postgres-array": "~2.0.0", + "postgres-bytea": "~1.0.0", + "postgres-date": "~1.0.4", + "postgres-interval": "^1.1.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/pgpass": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/pgpass/-/pgpass-1.0.5.tgz", + "integrity": "sha512-FdW9r/jQZhSeohs1Z3sI1yxFQNFvMcnmfuj4WBMUTxOrAyLMaTcE1aAMBiTlbMNaXvBCQuVi0R7hd8udDSP7ug==", + "dependencies": { + "split2": "^4.1.0" + } + }, + "node_modules/postgres-array": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/postgres-array/-/postgres-array-2.0.0.tgz", + "integrity": "sha512-VpZrUqU5A69eQyW2c5CA1jtLecCsN2U/bD6VilrFDWq5+5UIEVO7nazS3TEcHf1zuPYO/sqGvUvW62g86RXZuA==", + "engines": { + "node": ">=4" + } + }, + "node_modules/postgres-bytea": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/postgres-bytea/-/postgres-bytea-1.0.0.tgz", + "integrity": "sha512-xy3pmLuQqRBZBXDULy7KbaitYqLcmxigw14Q5sj8QBVLqEwXfeybIKVWiqAXTlcvdvb0+xkOtDbfQMOf4lST1w==", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/postgres-date": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/postgres-date/-/postgres-date-1.0.7.tgz", + "integrity": "sha512-suDmjLVQg78nMK2UZ454hAG+OAW+HQPZ6n++TNDUX+L0+uUlLywnoxJKDou51Zm+zTCjrCl0Nq6J9C5hP9vK/Q==", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/postgres-interval": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/postgres-interval/-/postgres-interval-1.2.0.tgz", + "integrity": "sha512-9ZhXKM/rw350N1ovuWHbGxnGh/SNJ4cnxHiM0rxE4VN41wsg8P8zWn9hv/buK00RP4WvlOyr/RBDiptyxVbkZQ==", + "dependencies": { + "xtend": "^4.0.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, "node_modules/safer-buffer": { "version": "2.1.2", "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==" }, + "node_modules/split2": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/split2/-/split2-4.1.0.tgz", + "integrity": "sha512-VBiJxFkxiXRlUIeyMQi8s4hgvKCSjtknJv/LVYbrgALPwf5zSKmEwV9Lst25AkvMDnvxODugjdl6KZgwKM1WYQ==", + "engines": { + "node": ">= 10.x" + } + }, "node_modules/typescript": { "version": "4.9.4", "resolved": "https://registry.npmjs.org/typescript/-/typescript-4.9.4.tgz", @@ -504,6 +647,14 @@ "engines": { "node": ">=4.2.0" } + }, + "node_modules/xtend": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.2.tgz", + "integrity": "sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ==", + "engines": { + "node": ">=0.4" + } } } } diff --git a/package.json b/package.json index 27be79e..8abae43 100644 --- a/package.json +++ b/package.json @@ -18,13 +18,15 @@ "author": "jusax23", "license": "UNLICENSED", "dependencies": { - "mariadb": "^3.0.2" + "mariadb": "^3.0.2", + "pg": "^8.9.0" }, "engines": { "node": ">= 14" }, "devDependencies": { "@types/node": "^18.11.18", + "@types/pg": "^8.6.6", "esbuild": "^0.17.4", "typescript": "^4.9.4" } diff --git a/src/db.ts b/src/db.ts index bc3cb92..06af42b 100644 --- a/src/db.ts +++ b/src/db.ts @@ -2,22 +2,40 @@ import mariadb from 'mariadb'; import { checkConstraint, Constraint, Datatype, foreignConstraint, uniqueConstraint } from './dbStructure'; import { Handler } from './defaultHandler'; import { Query } from './query'; -import { attributeSettings, extendedAttributeSettings, onAction } from './types'; +import { attributeSettings, extendedAttributeSettings, onAction, dbType } from './types'; +//import { postgresHandler } from "./postgresHandler" export class DB { tables: Table[] = []; handler: Handler; name: string; - pool: mariadb.Pool; - constructor({ host, user, password, database, connectionLimit = 5 }: { host: string, user: string, password: string, database: string, connectionLimit: number }) { - this.pool = mariadb.createPool({ host, user, password, database, connectionLimit, multipleStatements: true }); - this.handler = new Handler(); + type: dbType; + mariaPool!: mariadb.Pool; + //pgPool!: pg.Pool; + constructor({ host, user, password, database, connectionLimit = 5, databaseType = dbType.mariadb }: { host: string, user: string, password: string, database: string, connectionLimit: number, databaseType: dbType }) { + this.type = databaseType; + if (databaseType == dbType.mariadb) { + this.mariaPool = mariadb.createPool({ host, user, password, database, connectionLimit, multipleStatements: true }); + this.handler = new Handler(); + } + /*else if (databaseType == dbType.postgres) { + this.pgPool = new pg.Pool({ host, user, password, max: connectionLimit, database, idleTimeoutMillis: 30000, connectionTimeoutMillis: 2000 }); + this.handler = new postgresHandler(); + }*/ + else throw new Error("Unsuported Database type!"); + this.name = database; } async query(query: Query) { - //console.log(query); - return await this.pool.query(query); + console.log(query); + if (this.type == dbType.mariadb) return await this.mariaPool.query(query); + /*else if (this.type == dbType.postgres) { + let res = await this.pgPool.query(query.sql, query.values); + console.log([...res.rows]); + return res.rows; + }*/ + else throw new Error("Invalid Database Type!"); } getHandler() { return this.handler; @@ -26,9 +44,6 @@ export class DB { async sync(force = false) { let handler = this.getHandler(); await handler.syncDB(this, handler, force); - //this.tables.forEach(t=>{ - // console.log(handler.builders.query(handler.querys.create(handler,t))); - //}) } newTable(name: string) { @@ -42,7 +57,8 @@ export class DB { return null; } async close() { - if (this.pool) await this.pool.end(); + if (this.type == dbType.mariadb && this.mariaPool) await this.mariaPool.end(); + //if (this.type == dbType.postgres && this.pgPool) await this.pgPool.end(); } } @@ -139,4 +155,5 @@ export class Table { } export * from './funcs'; -export { onAction }; \ No newline at end of file +export { onAction }; +export { dbType as databaseType } \ No newline at end of file diff --git a/src/defaultHandler.ts b/src/defaultHandler.ts index 8a34be5..0d7e63d 100644 --- a/src/defaultHandler.ts +++ b/src/defaultHandler.ts @@ -10,8 +10,7 @@ export class Handler { let key = await db.query(handler.builders.query(handler.querys.listConstraintDetails(handler, db))); //Table List - let allTables = (await db.query(handler.builders.query(handler.querys.listTables(handler, db)))).map((d: any) => d.TABLE_NAME); - + let allTables = (await db.query(handler.builders.query(handler.querys.listTables(handler, db)))).map((d: any) => d.TABLE_NAME ?? d.table_name); // gether Table Schematics let tableData: { [key: string]: any; } = {}; for (let i = 0; i < db.tables.length; i++) { @@ -40,10 +39,10 @@ export class Handler { let found = 0; for (let j = 0; j < key.length; j++) { if ( - key[j].CONSTRAINT_NAME == n - && key[j].TABLE_NAME == table + (key[j].CONSTRAINT_NAME ?? key[j].constraint_name) == n + && (key[j].TABLE_NAME ?? key[j].table_name) == table ) { - if (attrs.includes(key[j].COLUMN_NAME.toLowerCase())) found++; + if (attrs.includes((key[j].COLUMN_NAME ?? key[j].column_name).toLowerCase())) found++; else return false; } } @@ -65,12 +64,12 @@ export class Handler { let found = 0; for (let j = 0; j < key.length; j++) { if ( - key[j].CONSTRAINT_NAME == n - && key[j].TABLE_NAME == table - && key[j].REFERENCED_TABLE_NAME == refTable + (key[j].CONSTRAINT_NAME ?? key[j].constraint_name) == n + && (key[j].TABLE_NAME ?? key[j].table_name) == table + && (key[j].REFERENCED_TABLE_NAME ?? key[j].referenced_table_name) == refTable ) { - let inF = fromAttrs.indexOf(key[j].COLUMN_NAME.toLowerCase()); - let inT = toAttrs.indexOf(key[j].REFERENCED_COLUMN_NAME.toLowerCase()); + let inF = fromAttrs.indexOf((key[j].COLUMN_NAME ?? key[j].column_name).toLowerCase()); + let inT = toAttrs.indexOf((key[j].REFERENCED_COLUMN_NAME ?? key[j].referenced_column_name).toLowerCase()); if (inF != -1 && inT == inF) found++; else return false; } @@ -86,10 +85,10 @@ export class Handler { let found = 0; for (let j = 0; j < key.length; j++) { if ( - key[j].CONSTRAINT_NAME.toLowerCase() == c.name - && key[j].TABLE_NAME == tabel.dbLangTableName + (key[j].CONSTRAINT_NAME ?? key[j].constraint_name).toLowerCase() == c.name + && (key[j].TABLE_NAME ?? key[j].table_name) == tabel.dbLangTableName ) { - if (attrs.includes(key[j].COLUMN_NAME.toLowerCase())) found++; + if (attrs.includes((key[j].COLUMN_NAME ?? key[j].column_name).toLowerCase())) found++; else return false; } } @@ -102,12 +101,12 @@ export class Handler { let found = 0; for (let j = 0; j < key.length; j++) { if ( - key[j].CONSTRAINT_NAME == c.name - && key[j].TABLE_NAME == tabel.dbLangTableName - && key[j].REFERENCED_TABLE_NAME == refTable + (key[j].CONSTRAINT_NAME ?? key[j].constraint_name) == c.name + && (key[j].TABLE_NAME ?? key[j].table_name) == tabel.dbLangTableName + && (key[j].REFERENCED_TABLE_NAME ?? key[j].referenced_table_name) == refTable ) { - let inF = fromAttrs.indexOf(key[j].COLUMN_NAME.toLowerCase()); - let inT = toAttrs.indexOf(key[j].REFERENCED_COLUMN_NAME.toLowerCase()); + let inF = fromAttrs.indexOf((key[j].COLUMN_NAME ?? key[j].column_name).toLowerCase()); + let inT = toAttrs.indexOf((key[j].REFERENCED_COLUMN_NAME ?? key[j].referenced_column_name).toLowerCase()); if (inF != -1 && inT == inF) found++; else return false; } @@ -118,33 +117,33 @@ export class Handler { //delete check and unused/false(unique, foreign) constraints for (let i = 0; i < constraints.length; i++) { const c = constraints[i]; - if (c.CONSTRAINT_TYPE == "CHECK") { - del.appendEnding(handler.querys.removeCheck(handler, c.TABLE_NAME, c.CONSTRAINT_NAME)); - } else if (c.CONSTRAINT_TYPE == "UNIQUE") { + if ((c.CONSTRAINT_TYPE ?? c.constraint_type) == "CHECK") { + del.appendEnding(handler.querys.removeCheck(handler, (c.TABLE_NAME ?? c.table_name), (c.CONSTRAINT_NAME ?? c.constraint_name))); + } else if ((c.CONSTRAINT_TYPE ?? c.constraint_type) == "UNIQUE") { if ( - (typeof tableData[c.TABLE_NAME.toLowerCase()] == "undefined" && deleteInDB) - || !checkUniqueIsVaild(c.CONSTRAINT_NAME, c.TABLE_NAME) - ) del.appendEnding(handler.querys.removeUnique(handler, c.TABLE_NAME, c.CONSTRAINT_NAME)); - } else if (c.CONSTRAINT_TYPE == "FOREIGN KEY") { + (typeof tableData[(c.TABLE_NAME ?? c.table_name).toLowerCase()] == "undefined" && deleteInDB) + || !checkUniqueIsVaild((c.CONSTRAINT_NAME ?? c.constraint_name), (c.TABLE_NAME ?? c.table_name)) + ) del.appendEnding(handler.querys.removeUnique(handler, (c.TABLE_NAME ?? c.table_name), (c.CONSTRAINT_NAME ?? c.constraint_name))); + } else if ((c.CONSTRAINT_TYPE ?? c.constraint_type) == "FOREIGN KEY") { if ( - (typeof tableData[c.TABLE_NAME.toLowerCase()] == "undefined" && deleteInDB) - || !checkForeignIsVaild(c.CONSTRAINT_NAME, c.TABLE_NAME) - ) del.appendEnding(handler.querys.removeForeignKey(handler, c.TABLE_NAME, c.CONSTRAINT_NAME)); + (typeof tableData[(c.TABLE_NAME ?? c.table_name).toLowerCase()] == "undefined" && deleteInDB) + || !checkForeignIsVaild((c.CONSTRAINT_NAME ?? c.constraint_name), (c.TABLE_NAME ?? c.table_name)) + ) del.appendEnding(handler.querys.removeForeignKey(handler, (c.TABLE_NAME ?? c.table_name), (c.CONSTRAINT_NAME ?? c.constraint_name))); } } //delete unused Tables if (deleteInDB) for (let i = 0; i < allTables.length; i++) { - if (typeof tableData[allTables[i].toLowerCase()] == "undefined") del.appendEnding(handler.querys.deleteTable(handler, allTables[i])); + if (typeof tableData[allTables[i]] == "undefined") del.appendEnding(handler.querys.deleteTable(handler, allTables[i])); } function freeForUpdate(attr: string, table: string) { for (let i = 0; i < key.length; i++) { const k = key[i]; if ( - k.REFERENCED_TABLE_NAME == table - && k.REFERENCED_COLUMN_NAME.toLowerCase() == attr.toLowerCase() + (k.REFERENCED_TABLE_NAME ?? k.referenced_table_name) == table + && (k.REFERENCED_COLUMN_NAME ?? k.referenced_column_name).toLowerCase() == attr.toLowerCase() ) { - del.appendEnding(handler.querys.removeForeignKey(handler, k.TABLE_NAME, k.CONSTRAINT_NAME)); + del.appendEnding(handler.querys.removeForeignKey(handler, (k.TABLE_NAME ?? k.table_name), (k.CONSTRAINT_NAME ?? k.constraint_name))); } } } @@ -323,7 +322,8 @@ export class Handler { const qb = new QueryBuilder(); qb.addCode(`SELECT * FROM information_schema.tables where TABLE_SCHEMA = `); qb.addInjection(db.name); - qb.addCode(` and TABLE_TYPE = "BASE TABLE"`); + qb.addCode(` and TABLE_TYPE = `); + qb.addInjection("BASE TABLE"); return qb; }, listConstraints: (handler: Handler, db: DB) => { diff --git a/src/types.ts b/src/types.ts index 5b26bfc..8f95678 100644 --- a/src/types.ts +++ b/src/types.ts @@ -56,4 +56,10 @@ export enum joinType { right, full, cross +} + +export enum dbType { + mariadb, + //mysql, + postgres, } \ No newline at end of file From 2f94997f4a4637fd57ffaa2fea79e4a5bea465da Mon Sep 17 00:00:00 2001 From: jusax23 Date: Sat, 18 Feb 2023 11:45:23 +0100 Subject: [PATCH 06/10] fixed auto_increment --- src/alias.ts | 9 +++++++++ src/db.ts | 6 +++--- src/defaultHandler.ts | 34 ++++++++++++++++++++++++++-------- 3 files changed, 38 insertions(+), 11 deletions(-) create mode 100644 src/alias.ts diff --git a/src/alias.ts b/src/alias.ts new file mode 100644 index 0000000..501753c --- /dev/null +++ b/src/alias.ts @@ -0,0 +1,9 @@ +import { Attribute, Table } from "./db" + +export class TableAlias extends Table{ + +} + +export class AttributeAlias extends Attribute{ + +} \ No newline at end of file diff --git a/src/db.ts b/src/db.ts index 06af42b..1ea9169 100644 --- a/src/db.ts +++ b/src/db.ts @@ -17,18 +17,18 @@ export class DB { this.type = databaseType; if (databaseType == dbType.mariadb) { this.mariaPool = mariadb.createPool({ host, user, password, database, connectionLimit, multipleStatements: true }); - this.handler = new Handler(); + this.handler = new Handler(this); } /*else if (databaseType == dbType.postgres) { this.pgPool = new pg.Pool({ host, user, password, max: connectionLimit, database, idleTimeoutMillis: 30000, connectionTimeoutMillis: 2000 }); - this.handler = new postgresHandler(); + this.handler = new postgresHandler(this); }*/ else throw new Error("Unsuported Database type!"); this.name = database; } async query(query: Query) { - console.log(query); + //console.log(query); if (this.type == dbType.mariadb) return await this.mariaPool.query(query); /*else if (this.type == dbType.postgres) { let res = await this.pgPool.query(query.sql, query.values); diff --git a/src/defaultHandler.ts b/src/defaultHandler.ts index 0d7e63d..d5f9c3c 100644 --- a/src/defaultHandler.ts +++ b/src/defaultHandler.ts @@ -4,6 +4,10 @@ import { insertQuery, Query, QueryBuilder, removeQuery, selectQuery, updateQuery import { allModifierInput, joinType, onAction, primaryData } from "./types" export class Handler { + db: DB; + constructor(db: DB){ + this.db = db; + } async syncDB(db: DB, handler: Handler, deleteInDB: boolean = false) { //Constraint Data let constraints = await db.query(handler.builders.query(handler.querys.listConstraints(handler, db))); @@ -28,6 +32,7 @@ export class Handler { const del = new QueryBuilder(); const create = new QueryBuilder(); + const connst = new QueryBuilder(); function checkUniqueIsVaild(n: string, table: string) { let t = db.getTable(table); @@ -166,7 +171,7 @@ export class Handler { let changePrimary = false; if (tableD == null) { create.appendEnding(handler.querys.create(handler, table)); - changePrimary = true; + //changePrimary = true; } else { let keys = Object.keys(table.dbLangTableAttributes); for (let j = 0; j < keys.length; j++) { @@ -205,19 +210,20 @@ export class Handler { for (let j = 0; j < table.dbLangConstrains.length; j++) { const c = table.dbLangConstrains[j]; if (c instanceof checkConstraint) { - create.appendEnding(handler.querys.addCheck(handler, table, c)); + connst.appendEnding(handler.querys.addCheck(handler, table, c)); } else if (c instanceof uniqueConstraint) { if (!checkUniqueExists(table, c)) { - create.appendEnding(handler.querys.addUnique(handler, table, c)); + connst.appendEnding(handler.querys.addUnique(handler, table, c)); } } else if (c instanceof foreignConstraint) { if (!checkForeignExists(table, c)) { - create.appendEnding(handler.querys.addForeignKey(handler, table, c)); + connst.appendEnding(handler.querys.addForeignKey(handler, table, c)); } } } } if (!create.isEmpty()) del.append(create); + if (!connst.isEmpty()) del.append(connst); if (!del.isEmpty()) await db.query(handler.builders.query(del)); } @@ -352,6 +358,15 @@ export class Handler { builder.append(a.serializeSettings(handler)); if (i + 1 < keys.length) builder.addCode(", "); } + let primAttr = Object.entries(table.dbLangTableAttributes) + .filter(([n, attr]) => !!attr.ops.primaryKey); + if (primAttr.length > 0) { + builder.addCode(", primary key ("); + builder.addCodeCommaSeperated( + primAttr.map(([n, attr]) => handler.builders.escapeID(n)) + ); + builder.addCode(")"); + } builder.addCode(")"); return builder; }, @@ -527,15 +542,18 @@ export class Handler { if (key.match(/^`.+`$/g)) return key; return `\`${key.replace(/`/g, '``')}\``; }, + escapeLiteral: (data: any): string => { + return this.db.mariaPool.escape(data); + }, compareDatatypes: (handler: Handler, attr: Datatype, curr: String) => { let qb = attr.serialize(handler); let sql = ""; for (let i = 0; i < qb.list.length; i++) { const [inject, data] = qb.list[i]; - sql += data; + if(inject)sql += handler.builders.escapeLiteral(data); + else sql += data; } - - return curr.split(" ").join("").startsWith(sql.split(" ").join("")); + return curr.split(", ").join(",").startsWith(sql.split(", ").join(",")); }, } @@ -724,7 +742,7 @@ export class Handler { builder.addCode(")"); return builder; }, - bool: dataTypeNoArg("bool"), + bool: dataTypeNoArg("tinyint"), bit: dataTypeNoArg("bit"), tinyint: dataTypeNoArg("tinyint"), smallint: dataTypeNoArg("smallint"), From 039ae267732a281142cb342ab2b206e2a963856f Mon Sep 17 00:00:00 2001 From: jusax23 Date: Sat, 18 Feb 2023 14:47:44 +0100 Subject: [PATCH 07/10] Aliases and fiexes --- src/alias.ts | 52 ++++++++++++++++++++++++++++++++++++++----- src/db.ts | 16 ++++++++----- src/defaultHandler.ts | 45 +++++++++++++++++++++---------------- src/query.ts | 6 +++-- src/types.ts | 7 +++--- 5 files changed, 92 insertions(+), 34 deletions(-) diff --git a/src/alias.ts b/src/alias.ts index 501753c..c66da53 100644 --- a/src/alias.ts +++ b/src/alias.ts @@ -1,9 +1,51 @@ -import { Attribute, Table } from "./db" - -export class TableAlias extends Table{ +import { Attribute, DB, Table } from "./db" +import { Handler } from "./defaultHandler"; +export class AttributeAlias { + name: string; + nameO: string; + table: TableAlias; + attr: Attribute; + constructor(attr: Attribute, table: TableAlias) { + this.name = attr.name; + this.nameO = attr.nameO; + this.attr = attr; + this.table = table; + } + serialize(handler: Handler) { + return handler.builders.escapeID(this.name); + } + toString(handler: Handler = this.table.dbLangDatabaseInstance.getHandler()) { + return this.table.serialize(handler) + "." + this.serialize(handler); + } + toStringFunc(handler: Handler) { + return this.table.serialize(handler) + "(" + this.serialize(handler) + ")"; + } } -export class AttributeAlias extends Attribute{ - +export class TableAlias { + dbLangTableName: string; + dbLangTableAttributes: { [key: string]: AttributeAlias; } = {}; + dbLangDatabaseInstance: DB; + dbLangTableInstance: Table; + [key: string]: AttributeAlias | any; + constructor(name: string, table: Table) { + this.dbLangTableName = name; + this.dbLangTableInstance = table; + this.dbLangDatabaseInstance = table.dbLangDatabaseInstance; + let keys = Object.keys(table.dbLangTableAttributes); + for (let i = 0; i < keys.length; i++) { + const a = table.dbLangTableAttributes[keys[i]]; + let attrAlias = new AttributeAlias(a, this); + this[a.name] = attrAlias; + this[a.nameO] = attrAlias; + this.dbLangTableAttributes[a.name] = attrAlias; + } + } + serialize(handler: Handler) { + return this.toString(handler); + } + toString(handler: Handler = this.dbLangDatabaseInstance.getHandler()) { + return handler.builders.escapeID(this.dbLangTableName); + } } \ No newline at end of file diff --git a/src/db.ts b/src/db.ts index 1ea9169..7b9de08 100644 --- a/src/db.ts +++ b/src/db.ts @@ -3,6 +3,7 @@ import { checkConstraint, Constraint, Datatype, foreignConstraint, uniqueConstra import { Handler } from './defaultHandler'; import { Query } from './query'; import { attributeSettings, extendedAttributeSettings, onAction, dbType } from './types'; +import { TableAlias } from "./alias" //import { postgresHandler } from "./postgresHandler" @@ -16,7 +17,7 @@ export class DB { constructor({ host, user, password, database, connectionLimit = 5, databaseType = dbType.mariadb }: { host: string, user: string, password: string, database: string, connectionLimit: number, databaseType: dbType }) { this.type = databaseType; if (databaseType == dbType.mariadb) { - this.mariaPool = mariadb.createPool({ host, user, password, database, connectionLimit, multipleStatements: true }); + this.mariaPool = mariadb.createPool({ host, user, password, database, connectionLimit, multipleStatements: false }); this.handler = new Handler(this); } /*else if (databaseType == dbType.postgres) { @@ -28,7 +29,7 @@ export class DB { this.name = database; } async query(query: Query) { - //console.log(query); + console.log(query); if (this.type == dbType.mariadb) return await this.mariaPool.query(query); /*else if (this.type == dbType.postgres) { let res = await this.pgPool.query(query.sql, query.values); @@ -64,11 +65,13 @@ export class DB { export class Attribute { name: string; + nameO: string; table: Table; ops: attributeSettings; type: Datatype; - constructor(name: string, table: Table, type: Datatype, ops: attributeSettings) { + constructor(name: string, nameO: string, table: Table, type: Datatype, ops: attributeSettings) { this.name = name.toLowerCase(); + this.nameO = nameO; this.type = type; this.table = table; this.ops = ops; @@ -133,9 +136,9 @@ export class Table { addAttribute(name: string, type: Datatype, ops: attributeSettings = {}, noErrorOnNameConflict = false) { let lowName = name.toLowerCase(); if (this.dbLangTableAttributes[lowName] != null) throw new Error("You are tring to create an Attribute twise!"); - let attr = new Attribute(lowName, this, type, ops); + let attr = new Attribute(lowName, name, this, type, ops); this.dbLangTableAttributes[lowName] = attr; - if (["serialize", "toString", "addAttribute", "dbLangTableName", "dbLangTableAttributes", "dbLangDatabaseInstance", "addConstraint", "addAttributes"].includes(lowName)) { + if (["serialize", "toString", "addAttribute", "dbLangTableName", "dbLangTableAttributes", "dbLangDatabaseInstance", "addConstraint", "addAttributes", "createAlias"].includes(lowName)) { if (!noErrorOnNameConflict) throw new Error("You cannot name Attribute like Methode of this Table!"); } else { this[lowName] = attr; @@ -152,6 +155,9 @@ export class Table { c.check(this); this.dbLangConstrains.push(c); } + createAlias(name: string) { + return new TableAlias(name, this); + } } export * from './funcs'; diff --git a/src/defaultHandler.ts b/src/defaultHandler.ts index d5f9c3c..510da7e 100644 --- a/src/defaultHandler.ts +++ b/src/defaultHandler.ts @@ -1,3 +1,4 @@ +import { AttributeAlias, TableAlias } from "./alias"; import { Attribute, DB, Table } from "./db" import { Aggregation, checkConstraint, joinCross, Datatype, foreignConstraint, Modifier, joinNatural, onJoin, uniqueConstraint, usingJoin } from "./dbStructure" import { insertQuery, Query, QueryBuilder, removeQuery, selectQuery, updateQuery } from "./query" @@ -5,13 +6,13 @@ import { allModifierInput, joinType, onAction, primaryData } from "./types" export class Handler { db: DB; - constructor(db: DB){ + constructor(db: DB) { this.db = db; } async syncDB(db: DB, handler: Handler, deleteInDB: boolean = false) { //Constraint Data let constraints = await db.query(handler.builders.query(handler.querys.listConstraints(handler, db))); - let key = await db.query(handler.builders.query(handler.querys.listConstraintDetails(handler, db))); + let key = [...await db.query(handler.builders.query(handler.querys.listConstraintDetails(handler, db)))]; //Table List let allTables = (await db.query(handler.builders.query(handler.querys.listTables(handler, db)))).map((d: any) => d.TABLE_NAME ?? d.table_name); @@ -23,10 +24,10 @@ export class Handler { const tableDataBuilder = new QueryBuilder(); tableDataBuilder.addCode("DESCRIBE "); tableDataBuilder.addCode(table.serialize(handler)); - tableData[table.dbLangTableName.toLowerCase()] = + tableData[table.dbLangTableName] = Object.fromEntries((await db.query(handler.builders.query(tableDataBuilder))).map((d: any) => [d.Field.toLowerCase(), d])); } catch (_) { - tableData[table.dbLangTableName.toLowerCase()] = null; + tableData[table.dbLangTableName] = null; } } @@ -126,12 +127,12 @@ export class Handler { del.appendEnding(handler.querys.removeCheck(handler, (c.TABLE_NAME ?? c.table_name), (c.CONSTRAINT_NAME ?? c.constraint_name))); } else if ((c.CONSTRAINT_TYPE ?? c.constraint_type) == "UNIQUE") { if ( - (typeof tableData[(c.TABLE_NAME ?? c.table_name).toLowerCase()] == "undefined" && deleteInDB) + (typeof tableData[c.TABLE_NAME ?? c.table_name] == "undefined" && deleteInDB) || !checkUniqueIsVaild((c.CONSTRAINT_NAME ?? c.constraint_name), (c.TABLE_NAME ?? c.table_name)) ) del.appendEnding(handler.querys.removeUnique(handler, (c.TABLE_NAME ?? c.table_name), (c.CONSTRAINT_NAME ?? c.constraint_name))); } else if ((c.CONSTRAINT_TYPE ?? c.constraint_type) == "FOREIGN KEY") { if ( - (typeof tableData[(c.TABLE_NAME ?? c.table_name).toLowerCase()] == "undefined" && deleteInDB) + (typeof tableData[c.TABLE_NAME ?? c.table_name] == "undefined" && deleteInDB) || !checkForeignIsVaild((c.CONSTRAINT_NAME ?? c.constraint_name), (c.TABLE_NAME ?? c.table_name)) ) del.appendEnding(handler.querys.removeForeignKey(handler, (c.TABLE_NAME ?? c.table_name), (c.CONSTRAINT_NAME ?? c.constraint_name))); } @@ -149,6 +150,7 @@ export class Handler { && (k.REFERENCED_COLUMN_NAME ?? k.referenced_column_name).toLowerCase() == attr.toLowerCase() ) { del.appendEnding(handler.querys.removeForeignKey(handler, (k.TABLE_NAME ?? k.table_name), (k.CONSTRAINT_NAME ?? k.constraint_name))); + key.splice(i--, 1); } } } @@ -156,7 +158,7 @@ export class Handler { //create tables for (let i = 0; i < db.tables.length; i++) { const table = db.tables[i]; - const tableD = tableData[table.dbLangTableName.toLowerCase()]; + const tableD = tableData[table.dbLangTableName]; //delete unused Columns if (deleteInDB && tableD != null) { let keys = Object.keys(tableD); @@ -191,7 +193,8 @@ export class Handler { (!!a.ops.notNull || !!a.ops.autoIncrement || !!a.ops.primaryKey), (attrData.Null == "NO"), "|", (!!a.ops.autoIncrement), (attrData.Extra == "auto_increment"));*/ freeForUpdate(a.name, a.table.dbLangTableName); - create.appendEnding(handler.querys.changeColumn(handler, a)); + if (a.ops.autoIncrement) + create.appendEnding(handler.querys.changeColumn(handler, a)); } if (attrData == null) { changePrimary = true; @@ -207,6 +210,9 @@ export class Handler { create.appendEnding(handler.querys.removePrimaryKey(handler, table.dbLangTableName)); create.appendEnding(handler.querys.addPrimaryKey(handler, table)); } + } + for (let i = 0; i < db.tables.length; i++) { + const table = db.tables[i]; for (let j = 0; j < table.dbLangConstrains.length; j++) { const c = table.dbLangConstrains[j]; if (c instanceof checkConstraint) { @@ -235,7 +241,7 @@ export class Handler { builder.addCode(` from `); if (q.from == null) { builder.addCode(" DUAL"); - } else if (q.from instanceof Table) { + } else if (q.from instanceof Table || q.from instanceof TableAlias) { builder.addCode(q.from.serialize(handler)); } else { builder.append(q.from.serialize(handler)); @@ -299,7 +305,7 @@ export class Handler { const s = q.setD[i]; qb.addCode(s[0].serialize(handler)); qb.addCode(" = ("); - if (s[1] instanceof Attribute) qb.addCode(s[1].serialize(handler)); + if (s[1] instanceof Attribute || s[1] instanceof AttributeAlias) qb.addCode(s[1].serialize(handler)); else if (s[1] instanceof Modifier || s[1] instanceof selectQuery || s[1] instanceof Aggregation) { qb.append(s[1].serialize(handler)); } else { @@ -443,14 +449,15 @@ export class Handler { return builder; }, addPrimaryKey: (handler: Handler, table: Table) => { + let primaAttr = Object.entries(table.dbLangTableAttributes) + .filter(([n, attr]) => !!attr.ops.primaryKey); const qb = new QueryBuilder(); + if(primaAttr.length == 0) return qb; qb.addCode("ALTER TABLE "); qb.addCode(table.serialize(handler)); qb.addCode(" add PRIMARY KEY if not exists ("); qb.addCodeCommaSeperated( - Object.entries(table.dbLangTableAttributes) - .filter(([n, attr]) => !!attr.ops.primaryKey) - .map(([n, attr]) => handler.builders.escapeID(n)) + primaAttr.map(([n, attr]) => handler.builders.escapeID(n)) ); qb.addCode(")"); return qb; @@ -550,7 +557,7 @@ export class Handler { let sql = ""; for (let i = 0; i < qb.list.length; i++) { const [inject, data] = qb.list[i]; - if(inject)sql += handler.builders.escapeLiteral(data); + if (inject) sql += handler.builders.escapeLiteral(data); else sql += data; } return curr.split(", ").join(",").startsWith(sql.split(", ").join(",")); @@ -664,7 +671,7 @@ export class Handler { divide: joinArg("-/"), not: (handler: Handler, a: allModifierInput[]): QueryBuilder => { let e = a[0]; - if (e instanceof Attribute) return new QueryBuilder([{ data: "not (" + e.toString(handler) + ")" }]) + if (e instanceof Attribute || e instanceof AttributeAlias) return new QueryBuilder([{ data: "not (" + e.toString(handler) + ")" }]) if (e instanceof Modifier || e instanceof selectQuery || e instanceof Aggregation) { const builder = new QueryBuilder(); builder.addCode("not ("); @@ -680,14 +687,14 @@ export class Handler { }, like: (handler: Handler, a: allModifierInput[]): QueryBuilder => { const builder = new QueryBuilder(); - if (a[0] instanceof Attribute) builder.addCode(a[0].toString()); + if (a[0] instanceof Attribute || a[0] instanceof AttributeAlias) builder.addCode(a[0].toString()); else if (a[0] instanceof Modifier || a[0] instanceof selectQuery || a[0] instanceof Aggregation) { builder.append(a[0].serialize(handler)); } else { builder.addInjection(a[0]); } builder.addCode(" LIKE "); - if (a[1] instanceof Attribute) builder.addCode(a[1].toString()); + if (a[1] instanceof Attribute || a[1] instanceof AttributeAlias) builder.addCode(a[1].toString()); else if (a[1] instanceof Modifier || a[1] instanceof selectQuery || a[1] instanceof Aggregation) { builder.append(a[1].serialize(handler)); } else { @@ -700,7 +707,7 @@ export class Handler { builder.addCode("CONCAT("); for (let i = 0; i < a.length; i++) { const e = a[i]; - if (e instanceof Attribute) builder.addCode(e.toString()); + if (e instanceof Attribute || e instanceof AttributeAlias) builder.addCode(e.toString()); else if (e instanceof Modifier || e instanceof selectQuery || e instanceof Aggregation) { builder.append(e.serialize(handler)); } else { @@ -798,7 +805,7 @@ function joinArg(type: string) { const builder = new QueryBuilder(); for (let i = 0; i < a.length; i++) { const d = a[i]; - if (d instanceof Attribute) builder.addCode(d.toString(handler)); + if (d instanceof Attribute || d instanceof AttributeAlias) builder.addCode(d.toString(handler)); else if (d instanceof Modifier || d instanceof selectQuery || d instanceof Aggregation) { builder.addCode("("); builder.append(d.serialize(handler)); diff --git a/src/query.ts b/src/query.ts index 0c39120..29b713e 100644 --- a/src/query.ts +++ b/src/query.ts @@ -1,3 +1,4 @@ +import { AttributeAlias } from "./alias"; import { Attribute, DB, Table } from "./db"; import { BooleanModifier, Modifier } from "./dbStructure"; import { Handler } from "./defaultHandler"; @@ -48,6 +49,7 @@ export class QueryBuilder { this.list.push(...qb.list); } appendEnding(qb: QueryBuilder) { + if(qb.isEmpty()) return; this.append(qb); this.list.push([false, ";"]); } @@ -72,8 +74,8 @@ export class selectQuery { this.whereD = m; return this; } - groupByD: Attribute[] = []; - groupBy(a: Attribute[]) { + groupByD: (Attribute | AttributeAlias)[] = []; + groupBy(a: (Attribute | AttributeAlias)[]) { this.groupByD = a; return this; } diff --git a/src/types.ts b/src/types.ts index 8f95678..f256d8d 100644 --- a/src/types.ts +++ b/src/types.ts @@ -1,12 +1,13 @@ +import { AttributeAlias, TableAlias } from "./alias"; import { Attribute, Table } from "./db"; import { Aggregation, BooleanModifier, Datatype, Joins, Modifier } from "./dbStructure"; import { QueryBuilder, selectQuery } from "./query"; export type primaryData = string | number | boolean | null; -export type allModifierInput = primaryData | Modifier | selectQuery | Attribute | Aggregation; +export type allModifierInput = primaryData | Modifier | selectQuery | Attribute | AttributeAlias | Aggregation; -export type selectElements = primaryData | Attribute | Aggregation | selectQuery -export type selectFromElements = Table | Joins | null; +export type selectElements = primaryData | Attribute | AttributeAlias | Aggregation | selectQuery +export type selectFromElements = TableAlias | Table | Joins | null; export type joinElements = Table | Joins; export type serializeReturn = [string, primaryData[]]; From 6aa679169937c625d56e0d0f53ad6c42092b0cdf Mon Sep 17 00:00:00 2001 From: jusax23 Date: Sat, 18 Feb 2023 14:53:07 +0100 Subject: [PATCH 08/10] fix --- src/db.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/db.ts b/src/db.ts index 7b9de08..f69447d 100644 --- a/src/db.ts +++ b/src/db.ts @@ -17,7 +17,7 @@ export class DB { constructor({ host, user, password, database, connectionLimit = 5, databaseType = dbType.mariadb }: { host: string, user: string, password: string, database: string, connectionLimit: number, databaseType: dbType }) { this.type = databaseType; if (databaseType == dbType.mariadb) { - this.mariaPool = mariadb.createPool({ host, user, password, database, connectionLimit, multipleStatements: false }); + this.mariaPool = mariadb.createPool({ host, user, password, database, connectionLimit, multipleStatements: true }); this.handler = new Handler(this); } /*else if (databaseType == dbType.postgres) { From d342aab53966a4e3405e8dc139de083e743966a2 Mon Sep 17 00:00:00 2001 From: jusax23 Date: Sat, 18 Feb 2023 15:06:31 +0100 Subject: [PATCH 09/10] fixes --- src/alias.ts | 3 +++ src/defaultHandler.ts | 4 +++- 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/src/alias.ts b/src/alias.ts index c66da53..e588614 100644 --- a/src/alias.ts +++ b/src/alias.ts @@ -42,6 +42,9 @@ export class TableAlias { this.dbLangTableAttributes[a.name] = attrAlias; } } + serializeAlias(hander: Handler) { + return this.dbLangTableInstance.serialize(hander) + " " + this.toString(hander); + } serialize(handler: Handler) { return this.toString(handler); } diff --git a/src/defaultHandler.ts b/src/defaultHandler.ts index 510da7e..81398e1 100644 --- a/src/defaultHandler.ts +++ b/src/defaultHandler.ts @@ -241,8 +241,10 @@ export class Handler { builder.addCode(` from `); if (q.from == null) { builder.addCode(" DUAL"); - } else if (q.from instanceof Table || q.from instanceof TableAlias) { + } else if (q.from instanceof Table) { builder.addCode(q.from.serialize(handler)); + } else if (q.from instanceof TableAlias) { + builder.addCode(q.from.serializeAlias(handler)); } else { builder.append(q.from.serialize(handler)); } From baff76e50d61608a717a069e50cd8695e7c79f97 Mon Sep 17 00:00:00 2001 From: jusax23 Date: Sat, 18 Feb 2023 15:45:15 +0100 Subject: [PATCH 10/10] updated readme.md --- readme.md | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/readme.md b/readme.md index 7f0eba9..47aceb6 100644 --- a/readme.md +++ b/readme.md @@ -12,7 +12,7 @@ Features: - [x] create Schema - [x] remove unused Schema - [x] joins -- [ ] table alias +- [x] table alias - [ ] change Schema - [ ] Key-Value Store Shortcut - [ ] Views @@ -104,7 +104,7 @@ let res = await select([Table2.AttrName2], Table1) .query(db); ``` -Joins: +_Joins_: ```javascript import { INT, onAction } from "dblang" @@ -125,6 +125,12 @@ let res = await select([TableA.A1, TableB.B1], innerJoinOn(eq(TableA.A1, Tableb. ``` See: [Joins](#joins) +_Aliases_: +```javascript +const alias1 = TableA.createAlias("alias1"); +//alias1 can be used like a Table in select Statements. +``` + #### Insert: ```javascript import { select } from "dblang"