Compare commits

...

32 commits
v0.6.1 ... main

Author SHA1 Message Date
3ed554f5ea Merge pull request 'order by' (#23) from dev into main
All checks were successful
ci/woodpecker/push/woodpecker Pipeline was successful
ci/woodpecker/tag/woodpecker Pipeline was successful
Reviewed-on: #23
2023-03-29 21:10:53 +02:00
25a38efdc6
version
All checks were successful
ci/woodpecker/push/woodpecker Pipeline was successful
ci/woodpecker/pr/woodpecker Pipeline was successful
2023-03-29 21:10:11 +02:00
575e9c2d4f
order by
All checks were successful
ci/woodpecker/push/woodpecker Pipeline was successful
2023-03-29 21:09:05 +02:00
f290b61f44 Merge pull request 'bug fix' (#22) from dev into main
All checks were successful
ci/woodpecker/push/woodpecker Pipeline was successful
ci/woodpecker/tag/woodpecker Pipeline was successful
Reviewed-on: #22
2023-03-28 18:31:35 +02:00
c2dc88062f
version, log remove
All checks were successful
ci/woodpecker/push/woodpecker Pipeline was successful
ci/woodpecker/pr/woodpecker Pipeline was successful
2023-03-28 18:30:57 +02:00
0a1cb7c85f
bug fix
All checks were successful
ci/woodpecker/push/woodpecker Pipeline was successful
2023-03-28 18:28:52 +02:00
3a01244199 Merge pull request 'coalesce' (#21) from dev into main
All checks were successful
ci/woodpecker/push/woodpecker Pipeline was successful
ci/woodpecker/tag/woodpecker Pipeline was successful
Reviewed-on: #21
2023-03-24 21:27:48 +01:00
23ebf3c75a
coalesce
All checks were successful
ci/woodpecker/push/woodpecker Pipeline was successful
ci/woodpecker/pr/woodpecker Pipeline was successful
2023-03-24 21:27:10 +01:00
eed8d36c0b Merge pull request 'bug fix' (#20) from dev into main
All checks were successful
ci/woodpecker/push/woodpecker Pipeline was successful
ci/woodpecker/tag/woodpecker Pipeline was successful
Reviewed-on: #20
2023-03-24 18:53:03 +01:00
5d97a3211f
version
All checks were successful
ci/woodpecker/push/woodpecker Pipeline was successful
ci/woodpecker/pr/woodpecker Pipeline was successful
2023-03-24 18:51:54 +01:00
56fb927c74
fix bugged primary key change with auto_increment
All checks were successful
ci/woodpecker/push/woodpecker Pipeline was successful
2023-03-24 18:51:09 +01:00
21b2bec2c4 Merge pull request 'better solution' (#19) from dev into main
All checks were successful
ci/woodpecker/push/woodpecker Pipeline was successful
ci/woodpecker/tag/woodpecker Pipeline was successful
Reviewed-on: #19
2023-03-24 17:49:11 +01:00
1e396b5934
better solution
All checks were successful
ci/woodpecker/push/woodpecker Pipeline was successful
ci/woodpecker/pr/woodpecker Pipeline was successful
2023-03-24 17:48:09 +01:00
57544dffd2 Merge pull request 'fixes' (#18) from dev into main
All checks were successful
ci/woodpecker/push/woodpecker Pipeline was successful
ci/woodpecker/tag/woodpecker Pipeline was successful
Reviewed-on: #18
2023-03-24 16:48:40 +01:00
c9f76a0799
fixes
All checks were successful
ci/woodpecker/push/woodpecker Pipeline was successful
ci/woodpecker/pr/woodpecker Pipeline was successful
2023-03-24 16:46:50 +01:00
d647fba5a9 Merge pull request 'unique delete bug fix' (#17) from dev into main
Some checks failed
ci/woodpecker/push/woodpecker Pipeline was successful
ci/woodpecker/tag/woodpecker Pipeline failed
Reviewed-on: #17
2023-03-19 13:38:35 +01:00
dc7f68054d
unique delete bug fix
All checks were successful
ci/woodpecker/push/woodpecker Pipeline was successful
ci/woodpecker/pr/woodpecker Pipeline was successful
2023-03-19 13:38:01 +01:00
5810a834ab Merge pull request 'hash to long keys' (#16) from dev into main
All checks were successful
ci/woodpecker/push/woodpecker Pipeline was successful
ci/woodpecker/tag/woodpecker Pipeline was successful
Reviewed-on: #16
2023-03-19 12:04:23 +01:00
92678dc4b2
version
All checks were successful
ci/woodpecker/push/woodpecker Pipeline was successful
ci/woodpecker/pr/woodpecker Pipeline was successful
2023-03-19 12:03:12 +01:00
5222fa22af
hash to long keys
All checks were successful
ci/woodpecker/push/woodpecker Pipeline was successful
2023-03-19 12:01:38 +01:00
fc9718f9a1 Merge pull request 'generell aliases and small fixes' (#15) from dev into main
All checks were successful
ci/woodpecker/push/woodpecker Pipeline was successful
ci/woodpecker/tag/woodpecker Pipeline was successful
Reviewed-on: #15
2023-03-02 14:36:59 +01:00
8210af9c6b
version
All checks were successful
ci/woodpecker/push/woodpecker Pipeline was successful
ci/woodpecker/pr/woodpecker Pipeline was successful
2023-03-02 14:36:13 +01:00
124c129c2b
generell Aliases
All checks were successful
ci/woodpecker/push/woodpecker Pipeline was successful
2023-03-02 14:33:41 +01:00
6e38f4ee13
changed git ignore
All checks were successful
ci/woodpecker/push/woodpecker Pipeline was successful
2023-03-01 16:37:17 +01:00
f8aa601fcf
readme fix
All checks were successful
ci/woodpecker/push/woodpecker Pipeline was successful
2023-03-01 16:35:09 +01:00
d51ad10864
update connect var
All checks were successful
ci/woodpecker/push/woodpecker Pipeline was successful
2023-03-01 16:32:34 +01:00
ea5954a9ff Merge pull request 'changed to es6' (#14) from dev into main
All checks were successful
ci/woodpecker/push/woodpecker Pipeline was successful
ci/woodpecker/tag/woodpecker Pipeline was successful
Reviewed-on: #14
2023-02-27 18:00:21 +01:00
cbac881a49 bug fix
All checks were successful
ci/woodpecker/push/woodpecker Pipeline was successful
ci/woodpecker/pr/woodpecker Pipeline was successful
2023-02-27 17:59:16 +01:00
53cb448e36 upgrade to es6 and catch conn errors
All checks were successful
ci/woodpecker/push/woodpecker Pipeline was successful
2023-02-27 16:33:27 +01:00
67b10d949a Merge pull request 'exists' (#13) from dev into main
All checks were successful
ci/woodpecker/push/woodpecker Pipeline was successful
ci/woodpecker/tag/woodpecker Pipeline was successful
Reviewed-on: #13
2023-02-26 16:38:34 +01:00
a6d368eb58 readme version
All checks were successful
ci/woodpecker/push/woodpecker Pipeline was successful
ci/woodpecker/pr/woodpecker Pipeline was successful
2023-02-26 16:37:19 +01:00
e446270591 exists
All checks were successful
ci/woodpecker/push/woodpecker Pipeline was successful
2023-02-26 16:34:42 +01:00
14 changed files with 272 additions and 89 deletions

1
.gitignore vendored
View file

@ -3,3 +3,4 @@ node_modules
ltests
sqlsave
postgresHandler.ts
.vscode

6
package-lock.json generated
View file

@ -1,12 +1,12 @@
{
"name": "dblang",
"version": "1.0.0",
"version": "0.9.6",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "dblang",
"version": "1.0.0",
"version": "0.9.6",
"license": "UNLICENSED",
"dependencies": {
"mariadb": "^3.0.2",
@ -19,7 +19,7 @@
"typescript": "^4.9.4"
},
"engines": {
"node": ">= 14"
"node": ">= 16"
}
},
"node_modules/@esbuild/android-arm": {

View file

@ -1,10 +1,10 @@
{
"name": "dblang",
"version": "1.0.0",
"version": "0.9.6",
"description": "",
"main": "dist/db.js",
"types": "dist/db.d.ts",
"type": "commonjs",
"type": "module",
"directories": {
"dist": "dist"
},
@ -22,7 +22,7 @@
"pg": "^8.9.0"
},
"engines": {
"node": ">= 14"
"node": ">= 16"
},
"devDependencies": {
"@types/node": "^18.11.18",

View file

@ -13,6 +13,7 @@ Features:
- [x] remove unused Schema
- [x] joins
- [x] table alias
- [x] general aliases
- [x] unified response
- [ ] change Schema
- [ ] Key-Value Store Shortcut
@ -29,7 +30,8 @@ Supported Databses:
```javascript
import { DB } from "dblang";
const db = new DB({
const db = new DB();
db.connect({
host: "localhost",
user: "root",
password: "0123456789",
@ -130,6 +132,7 @@ _Aliases_:
```javascript
const alias1 = TableA.createAlias("alias1");
//alias1 can be used like a Table in select Statements.
const alias2 = alias(avg(TableA.A1), "someAvg");
```
Get requestet Data:
@ -238,6 +241,7 @@ BooleanModifier:
- `le(v1, v2, ...)`
- `not(v1)`
- `like(v1, v2)`
- `exists(s)`
NumberModifier:
- `plus(v1, v2, ...)`
@ -248,7 +252,7 @@ NumberModifier:
StringModifier:
- `concat(v1, v2, ...)`
(v\* = string, number, boolean, null, Modifier, Aggregation, select Query, Attribute)
(v\* = string, number, boolean, null, Modifier, Aggregation, select Query, Attribute; s = selectQuery)
#### Joins

View file

@ -1,5 +1,8 @@
import { Attribute, DB, Table } from "./db"
import { Handler } from "./defaultHandler";
import { Attribute, DB, Table } from "./db.js"
import { Aggregation, Modifier } from "./dbStructure.js";
import { Handler } from "./defaultHandler.js";
import { QueryBuilder, selectQuery } from "./query.js";
import { selectElements } from "./types.js";
export class AttributeAlias {
name: string;
@ -21,7 +24,7 @@ export class AttributeAlias {
getStringFunc(handler: Handler) {
return this.table.serialize(handler) + "(" + this.serialize(handler) + ")";
}
toString(){
toString() {
return this.table.dbLangTableName + "_" + this.name;
}
}
@ -55,3 +58,33 @@ export class TableAlias {
return handler.builders.escapeID(this.dbLangTableName);
}
}
export class Alias {
alias: string;
a: selectElements;
constructor(a: selectElements, alias: string) {
this.alias = alias;
this.a = a;
}
serialize(handler: Handler) {
let builder = new QueryBuilder();
if (this.a instanceof Attribute || this.a instanceof AttributeAlias)
builder.addCode(this.a.getString(handler) + " " + handler.builders.escapeID(this.a.toString()));
else if (this.a instanceof Modifier || this.a instanceof selectQuery || this.a instanceof Aggregation || this.a instanceof Alias) {
builder.addCode("(");
builder.append(this.a.serialize(handler));
builder.addCode(")");
} else {
builder.addInjection(this.a);
}
return builder;
}
getString(handler: Handler) {
return this.serialize(handler);
}
toString() {
return this.alias;
}
}

View file

@ -1,12 +1,17 @@
import mariadb from 'mariadb';
import { checkConstraint, Constraint, Datatype, foreignConstraint, uniqueConstraint } from './dbStructure';
import { Handler } from './defaultHandler';
import { Query } from './query';
import { attributeSettings, extendedAttributeSettings, onAction, dbType } from './types';
import { TableAlias } from "./alias"
import { insertResponse, readResponse, writeResponse, singleResponse } from "./responses"
import { checkConstraint, Constraint, Datatype, foreignConstraint, uniqueConstraint } from './dbStructure.js';
import { Handler } from './defaultHandler.js';
import { Query } from './query.js';
import { attributeSettings, extendedAttributeSettings, onAction, dbType, order } from './types.js';
import { TableAlias } from "./alias.js"
import { insertResponse, readResponse, writeResponse, singleResponse } from "./responses.js"
//import { postgresHandler } from "./postgresHandler"
declare module "mariadb" {
interface Pool{
on(ev: 'error', callback: () => void): Pool;
}
}
export class DB {
tables: Table[] = [];
@ -21,6 +26,8 @@ export class DB {
this.type = databaseType;
if (databaseType == dbType.mariadb) {
this.mariaPool = mariadb.createPool({ host, user, password, port, database, connectionLimit, multipleStatements: true });
// catch errors
this.mariaPool.on("error",()=>{});
this.handler = new Handler(this);
}
/*else if (databaseType == dbType.postgres) {
@ -67,6 +74,7 @@ export class DB {
if (!this.connected) throw new Error("Not connected yet!");
if (this.type == dbType.mariadb && this.mariaPool) await this.mariaPool.end();
//if (this.type == dbType.postgres && this.pgPool) await this.pgPool.end();
this.connected = false;
}
}
@ -96,13 +104,13 @@ export class Attribute {
[this]
))
}
if (ops.foreginKey != null) {
if (ops.foreignKey != null) {
table.addConstraint(new foreignConstraint(
table.dbLangDatabaseInstance.name + "_" + table.dbLangTableName + "_" + name + "_foreign_constraint_to_" + ops.foreginKey.link.name,
table.dbLangDatabaseInstance.name + "_" + table.dbLangTableName + "_" + name + "_foreign_constraint_to_" + ops.foreignKey.link.name,
[this],
[ops.foreginKey.link],
ops.foreginKey.onDelete,
ops.foreginKey.onUpdate
[ops.foreignKey.link],
ops.foreignKey.onDelete,
ops.foreignKey.onUpdate
));
}
}
@ -162,7 +170,8 @@ export class Table {
}));
}
addConstraint(c: Constraint) {
c.check(this);
let check = c.check(this);
if(typeof check == "string") throw new Error(check);
this.dbLangConstrains.push(c);
}
createAlias(name: string) {
@ -170,7 +179,7 @@ export class Table {
}
}
export * from './funcs';
export { onAction };
export * from './funcs.js';
export { onAction, order };
export { dbType as databaseType }
export { readResponse, writeResponse, insertResponse, singleResponse }

View file

@ -1,7 +1,8 @@
import { Attribute, Table } from "./db";
import { Handler } from "./defaultHandler";
import { QueryBuilder } from "./query";
import { allModifierInput, joinElements, joinType, onAction, primaryData, serializeReturn } from "./types";
import { Attribute, Table } from "./db.js";
import { Handler } from "./defaultHandler.js";
import { QueryBuilder } from "./query.js";
import { sha256 } from "./tools.js";
import { allModifierInput, joinElements, joinType, onAction, primaryData, serializeReturn } from "./types.js";
export class Datatype {
type: string;
@ -110,6 +111,7 @@ export class checkConstraint implements Constraint {
checkQuery: BooleanModifier;
name: string;
constructor(name: string, check: BooleanModifier) {
if (name.length > 64) name = sha256(name);
this.name = name.toLowerCase();
this.checkQuery = check;
}
@ -125,14 +127,17 @@ export class uniqueConstraint implements Constraint {
name: string;
attrs: Attribute[];
constructor(name: string, attrs: Attribute[]) {
if (name.length > 64) name = sha256(name);
this.name = name.toLowerCase();
this.attrs = attrs;
}
check(table: Table): boolean | string {
let prim = true;
for (let i = 0; i < this.attrs.length; i++) {
if (this.attrs[i].ops.primaryKey) return "Can not combine unique Constraint and primary key";
if (!this.attrs[i].ops.primaryKey) prim = false;
if (this.attrs[i].table != table) return "Referencing Attributes must be in host Table.";
}
if (prim) return "Can not combine unique Constraint and primary key";
return false;
}
uses(attr: Attribute): boolean {
@ -147,6 +152,7 @@ export class foreignConstraint implements Constraint {
onUpdate: onAction;
onDelete: onAction;
constructor(name: string, from: Attribute[], to: Attribute[], onDelete: onAction = onAction.nothing, onUpdate: onAction = onAction.nothing) {
if (name.length > 64) name = sha256(name);
this.name = name.toLowerCase();
this.fromAttrs = from;
this.toAttrs = to;
@ -160,7 +166,7 @@ export class foreignConstraint implements Constraint {
let table = this.toAttrs[0].table;
for (let i = 0; i < this.toAttrs.length; i++) {
if (table != this.toAttrs[i].table) return "Referenced Attributes must be in one Table.";
if (this.toAttrs[i].ops.primaryKey) return "Can not reference non primary keys.";
if (!this.toAttrs[i].ops.primaryKey) return "Can not reference non primary keys.";
}
for (let i = 0; i < this.fromAttrs.length; i++) {
if (this.fromAttrs[i].table != t) return "Referencing Attributes must be in host Table.";

View file

@ -1,8 +1,9 @@
import { AttributeAlias, TableAlias } from "./alias";
import { Attribute, DB, insertResponse, readResponse, Table, writeResponse } from "./db"
import { Aggregation, checkConstraint, joinCross, Datatype, foreignConstraint, Modifier, joinNatural, onJoin, uniqueConstraint, usingJoin } from "./dbStructure"
import { insertQuery, Query, QueryBuilder, removeQuery, selectQuery, updateQuery } from "./query"
import { allModifierInput, joinType, onAction, primaryData } from "./types"
import { Alias, AttributeAlias, TableAlias } from "./alias.js";
import { Attribute, DB, insertResponse, readResponse, Table, writeResponse } from "./db.js"
import { Aggregation, checkConstraint, joinCross, Datatype, foreignConstraint, Modifier, joinNatural, onJoin, uniqueConstraint, usingJoin } from "./dbStructure.js"
import { insertQuery, Query, QueryBuilder, removeQuery, selectQuery, updateQuery } from "./query.js"
import { allModifierInput, joinType, onAction, order, primaryData } from "./types.js"
import { sha256 } from "./tools.js"
export class Handler {
db: DB;
@ -120,6 +121,21 @@ export class Handler {
return found == fromAttrs.length && found == toAttrs.length;
}
function freeForUpdate(attr: string, table: string, start = false, pool = del) {
for (let i = 0; i < key.length; i++) {
const k = key[i];
if (
((k.REFERENCED_TABLE_NAME ?? k.referenced_table_name) == table
&& (k.REFERENCED_COLUMN_NAME ?? k.referenced_column_name).toLowerCase() == attr.toLowerCase())
|| (start && (k.TABLE_NAME ?? k.table_name) == table
&& (k.COLUMN_NAME ?? k.column_name).toLowerCase() == attr.toLowerCase() && (k.REFERENCED_COLUMN_NAME ?? k.referenced_column_name) != null)
) {
pool.appendEnding(handler.querys.removeForeignKey(handler, (k.TABLE_NAME ?? k.table_name), (k.CONSTRAINT_NAME ?? k.constraint_name)));
key.splice(i--, 1);
}
}
}
//delete check and unused/false(unique, foreign) constraints
for (let i = 0; i < constraints.length; i++) {
const c = constraints[i];
@ -129,7 +145,19 @@ export class Handler {
if (
(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)));
) {
const uTName = (c.TABLE_NAME ?? c.table_name);
const uCName = (c.CONSTRAINT_NAME ?? c.constraint_name);
for (let j = 0; j < key.length; j++) {
if (
(key[j].CONSTRAINT_NAME ?? key[j].constraint_name) == uCName
&& (key[j].TABLE_NAME ?? key[j].table_name) == uTName
) {
freeForUpdate((key[j].COLUMN_NAME ?? key[j].column_name), uTName, true);
}
}
del.appendEnding(handler.querys.removeUnique(handler, uTName, uCName));
}
} else if ((c.CONSTRAINT_TYPE ?? c.constraint_type) == "FOREIGN KEY") {
if (
(typeof tableData[c.TABLE_NAME ?? c.table_name] == "undefined" && deleteInDB)
@ -142,19 +170,6 @@ export class Handler {
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 ?? 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.table_name), (k.CONSTRAINT_NAME ?? k.constraint_name)));
key.splice(i--, 1);
}
}
}
//create tables
for (let i = 0; i < db.tables.length; i++) {
const table = db.tables[i];
@ -180,7 +195,13 @@ export class Handler {
const a = table.dbLangTableAttributes[keys[j]];
const attrData = tableD[keys[j]];
if (attrData == null) {
create.appendEnding(handler.querys.addColumn(handler, a));
if (a.ops.autoIncrement) {
a.ops.autoIncrement = false;
create.appendEnding(handler.querys.addColumn(handler, a));
a.ops.autoIncrement = true;
connst.appendEnding(handler.querys.addColumn(handler, a));
}
else create.appendEnding(handler.querys.addColumn(handler, a));
if (a.ops.primaryKey) changePrimary = true;
} else if (
!handler.builders.compareDatatypes(handler, a.type, attrData.Type) ||
@ -188,10 +209,6 @@ export class Handler {
(!!a.ops.notNull || !!a.ops.autoIncrement || !!a.ops.primaryKey) != (attrData.Null == "NO") ||
(!!a.ops.autoIncrement) != (attrData.Extra == "auto_increment")
) {
/*console.log(!handler.builders.compareDatatypes(handler, a.type, attrData.Type), "|",
a.ops.default, attrData.Default, "|",
(!!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);
if (a.ops.autoIncrement) {
a.ops.autoIncrement = false;
@ -204,11 +221,20 @@ export class Handler {
if (attrData != null) {
if ((attrData.Key == "PRI") != (!!a.ops.primaryKey)) {
freeForUpdate(a.name, a.table.dbLangTableName);
console.log("206");
changePrimary = true;
}
}
}
if (changePrimary) for (let j = 0; j < keys.length; j++) {
const a = table.dbLangTableAttributes[keys[j]];
if (a.ops.autoIncrement) {
a.ops.autoIncrement = false;
create.appendEnding(handler.querys.changeColumn(handler, a));
a.ops.autoIncrement = true;
connst.appendEnding(handler.querys.changeColumn(handler, a));
}
freeForUpdate(a.name, a.table.dbLangTableName, true, create);
}
}
if (changePrimary) {
create.appendEnding(handler.querys.removePrimaryKey(handler, table.dbLangTableName));
@ -245,8 +271,11 @@ export class Handler {
for (let i = 0; i < a.length; i++) {
const d = a[i];
if (d instanceof Attribute || d instanceof AttributeAlias)
builder.addCode(d.getString(handler)+" "+ handler.builders.escapeID(d.toString()));
else if (d instanceof Modifier || d instanceof selectQuery || d instanceof Aggregation) {
builder.addCode(d.getString(handler) + " " + handler.builders.escapeID(d.toString()));
else if (d instanceof Alias) {
builder.append(d.serialize(handler));
builder.addCode(handler.builders.escapeID(d.toString()));
} else if (d instanceof Modifier || d instanceof selectQuery || d instanceof Aggregation) {
builder.addCode("(");
builder.append(d.serialize(handler));
builder.addCode(")");
@ -278,6 +307,25 @@ export class Handler {
builder.append(q.havingD.serialize(handler));
}
}
if (q.orderByD.length > 0) {
builder.addCode(" order by ");
for (let i = 0; i < q.orderByD.length; i++) {
const d = q.orderByD[i];
if (d[0] instanceof Attribute || d[0] instanceof AttributeAlias) builder.addCode(d[0].getString(handler));
else if (d[0] instanceof Alias)
builder.addCode(handler.builders.escapeID(d.toString()));
else if (d[0] instanceof Modifier || d[0] instanceof selectQuery || d[0] instanceof Aggregation) {
builder.addCode("(");
builder.append(d[0].serialize(handler));
builder.addCode(")");
} else {
builder.addInjection(d[0]);
}
if(d[1] == order.DESC) builder.addCode(" DESC");
else builder.addCode(" ASC");
if (i + 1 < q.orderByD.length) builder.addCode(", ");
}
}
if (q.limitD != null) {
if (q.limitOffsetD == null) {
builder.addCode(" limit ");
@ -298,7 +346,7 @@ export class Handler {
},
insert: (hander: Handler, q: insertQuery): QueryBuilder => {
const qb = new QueryBuilder();
qb.addCode("INSERT INTO ");
qb.addCode("INSERT IGNORE INTO ");
qb.addCode(q.attrs[0].table.serialize(hander));
qb.addCode("(");
qb.addCodeCommaSeperated(q.attrs.map(a => a.serialize(hander)));
@ -326,6 +374,8 @@ export class Handler {
qb.addCode(s[0].serialize(handler));
qb.addCode(" = (");
if (s[1] instanceof Attribute || s[1] instanceof AttributeAlias) qb.addCode(s[1].serialize(handler));
else if (s[1] instanceof Alias)
qb.addCode(handler.builders.escapeID(s[1].toString()));
else if (s[1] instanceof Modifier || s[1] instanceof selectQuery || s[1] instanceof Aggregation) {
qb.append(s[1].serialize(handler));
} else {
@ -566,6 +616,7 @@ export class Handler {
},
escapeID: (key: string): string => {
if (!key || key === "" || key.includes('\u0000')) throw new Error("Can not escape empty key or with null unicode!");
if (key.length > 64) key = sha256(key);
if (key.match(/^`.+`$/g)) return key;
return `\`${key.replace(/`/g, '``')}\``;
},
@ -704,6 +755,8 @@ export class Handler {
not: (handler: Handler, a: allModifierInput[]): QueryBuilder => {
let e = a[0];
if (e instanceof Attribute || e instanceof AttributeAlias) return new QueryBuilder([{ data: "not (" + e.getString(handler) + ")" }])
if (e instanceof Alias)
return new QueryBuilder([{ data: handler.builders.escapeID(e.toString()) }]);
if (e instanceof Modifier || e instanceof selectQuery || e instanceof Aggregation) {
const builder = new QueryBuilder();
builder.addCode("not (");
@ -720,6 +773,8 @@ export class Handler {
like: (handler: Handler, a: allModifierInput[]): QueryBuilder => {
const builder = new QueryBuilder();
if (a[0] instanceof Attribute || a[0] instanceof AttributeAlias) builder.addCode(a[0].getString());
else if (a[0] instanceof Alias)
builder.addCode(handler.builders.escapeID(a[0].toString()));
else if (a[0] instanceof Modifier || a[0] instanceof selectQuery || a[0] instanceof Aggregation) {
builder.append(a[0].serialize(handler));
} else {
@ -727,6 +782,8 @@ export class Handler {
}
builder.addCode(" LIKE ");
if (a[1] instanceof Attribute || a[1] instanceof AttributeAlias) builder.addCode(a[1].getString());
else if (a[1] instanceof Alias)
builder.addCode(handler.builders.escapeID(a[1].toString()));
else if (a[1] instanceof Modifier || a[1] instanceof selectQuery || a[1] instanceof Aggregation) {
builder.append(a[1].serialize(handler));
} else {
@ -737,6 +794,8 @@ export class Handler {
regexp: (handler: Handler, a: allModifierInput[]): QueryBuilder => {
const builder = new QueryBuilder();
if (a[0] instanceof Attribute || a[0] instanceof AttributeAlias) builder.addCode(a[0].getString());
else if (a[0] instanceof Alias)
builder.addCode(handler.builders.escapeID(a[0].toString()));
else if (a[0] instanceof Modifier || a[0] instanceof selectQuery || a[0] instanceof Aggregation) {
builder.append(a[0].serialize(handler));
} else {
@ -744,6 +803,8 @@ export class Handler {
}
builder.addCode(" REGEXP ");
if (a[1] instanceof Attribute || a[1] instanceof AttributeAlias) builder.addCode(a[1].getString());
else if (a[1] instanceof Alias)
builder.addCode(handler.builders.escapeID(a[1].toString()));
else if (a[1] instanceof Modifier || a[1] instanceof selectQuery || a[1] instanceof Aggregation) {
builder.append(a[1].serialize(handler));
} else {
@ -751,12 +812,32 @@ export class Handler {
}
return builder;
},
exists: (handler: Handler, a: allModifierInput[]): QueryBuilder => {
let e = a[0];
if (e instanceof Attribute || e instanceof AttributeAlias) return new QueryBuilder([{ data: "exists (" + e.getString(handler) + ")" }])
if (e instanceof Alias)
return new QueryBuilder([{ data: handler.builders.escapeID(e.toString()) }]);
if (e instanceof Modifier || e instanceof selectQuery || e instanceof Aggregation) {
const builder = new QueryBuilder();
builder.addCode("exists (");
builder.append(e.serialize(handler));
builder.addCode(")");
return builder;
}
return new QueryBuilder([
{ data: "exists (" },
{ inject: true, data: e },
{ data: ")" }
]);
},
concat: (handler: Handler, a: allModifierInput[]): QueryBuilder => {
const builder = new QueryBuilder();
builder.addCode("CONCAT(");
for (let i = 0; i < a.length; i++) {
const e = a[i];
if (e instanceof Attribute || e instanceof AttributeAlias) builder.addCode(e.getString());
else if (e instanceof Alias)
builder.addCode(handler.builders.escapeID(e.toString()));
else if (e instanceof Modifier || e instanceof selectQuery || e instanceof Aggregation) {
builder.append(e.serialize(handler));
} else {
@ -766,7 +847,25 @@ export class Handler {
}
builder.addCode(")");
return builder;
}
},
coalesce: (handler: Handler, a: allModifierInput[]): QueryBuilder => {
const builder = new QueryBuilder();
builder.addCode("COALESCE(");
for (let i = 0; i < a.length; i++) {
const e = a[i];
if (e instanceof Attribute || e instanceof AttributeAlias) builder.addCode(e.getString());
else if (e instanceof Alias)
builder.addCode(handler.builders.escapeID(e.toString()));
else if (e instanceof Modifier || e instanceof selectQuery || e instanceof Aggregation) {
builder.append(e.serialize(handler));
} else {
builder.addInjection(e);
}
if (i < a.length - 1) builder.addCode(", ");
}
builder.addCode(")");
return builder;
},
}
datatypes = {
@ -855,6 +954,8 @@ function joinArg(type: string) {
for (let i = 0; i < a.length; i++) {
const d = a[i];
if (d instanceof Attribute || d instanceof AttributeAlias) builder.addCode(d.getString(handler));
else if (d instanceof Alias)
builder.addCode(handler.builders.escapeID(d.toString()));
else if (d instanceof Modifier || d instanceof selectQuery || d instanceof Aggregation) {
builder.addCode("(");
builder.append(d.serialize(handler));

View file

@ -1,7 +1,8 @@
import { Attribute, Table } from "./db";
import { Aggregation, BooleanModifier, checkConstraint, Datatype, foreignConstraint, joinCross, joinNatural, usingJoin, onJoin, NumberModifier, StringModifier, uniqueConstraint } from "./dbStructure";
import { insertQuery, removeQuery, selectQuery, updateQuery } from "./query";
import { allModifierInput, joinType, selectElements, selectFromElements } from "./types";
import { Alias } from "./alias.js";
import { Attribute, Table } from "./db.js";
import { Aggregation, BooleanModifier, checkConstraint, Datatype, foreignConstraint, joinCross, joinNatural, usingJoin, onJoin, NumberModifier, StringModifier, uniqueConstraint } from "./dbStructure.js";
import { insertQuery, removeQuery, selectQuery, updateQuery } from "./query.js";
import { allModifierInput, joinType, selectElements, selectFromElements } from "./types.js";
//modifiers
export const and = (...args: BooleanModifier[]) => new BooleanModifier("and", args);
@ -20,7 +21,10 @@ export const not = (arg: allModifierInput) => new BooleanModifier("not", [arg]);
export const like = (a: allModifierInput, b: allModifierInput) => new BooleanModifier("like", [a, b]);
export const regexp = (a: allModifierInput, b: allModifierInput) => new BooleanModifier("regexp", [a, b]);
export const exists = (q: selectQuery) => new BooleanModifier("exists", [q]);
export const concat = (...args: allModifierInput[]) => new StringModifier("concat", args);
export const coalesce = (...args: allModifierInput[]) => new StringModifier("coalesce", args);
//aggregations
export const count = (a: Attribute) => new Aggregation("count", a);
@ -54,6 +58,9 @@ export const insert = (...attrs: Attribute[]) => new insertQuery(attrs);
export const update = (table: Table) => new updateQuery(table);
export const remove = (table: Table) => new removeQuery(table);
//alias
export const alias = (a: selectElements, name: string) => new Alias(a, name);
//datatypes
export const CHAR = (size: number) => new Datatype("char", [size]);

View file

@ -1,8 +1,8 @@
import { AttributeAlias } from "./alias";
import { Attribute, DB, Table } from "./db";
import { BooleanModifier, Modifier } from "./dbStructure";
import { Handler } from "./defaultHandler";
import { allModifierInput, primaryData, selectElements, selectFromElements, serializeReturn } from "./types";
import { AttributeAlias } from "./alias.js";
import { Attribute, DB, Table } from "./db.js";
import { BooleanModifier, Modifier } from "./dbStructure.js";
import { Handler } from "./defaultHandler.js";
import { allModifierInput, order, primaryData, selectElements, selectFromElements, serializeReturn } from "./types.js";
export class Query {
@ -84,6 +84,17 @@ export class selectQuery {
this.havingD = m;
return this;
}
orderByD: ([allModifierInput, order])[] = [];
addOrderBy(a: allModifierInput, o: order = order.ASC) {
this.orderByD.push([a, o]);
return this;
}
orderBY(a: allModifierInput, o: order = order.ASC) {
this.orderByD = [[a, o]];
return this;
}
limitD: number | null = null;
limitOffsetD: number | null = null;
limit(i: number, offset: number = 0) {
@ -101,7 +112,7 @@ export class selectQuery {
const builder = this.serialize(handler);
const s = handler.builders.query(builder);
let readResp = await db.query(s, printQuery);
return db.getHandler().responses.readResponse(readResp);
return handler.responses.readResponse(readResp);
}
}
@ -139,7 +150,7 @@ export class insertQuery {
const builder = this.serialize(handler);
const s = handler.builders.query(builder);
let readResp = await db.query(s, printQuery);
return db.getHandler().responses.insertResponse(readResp);
return handler.responses.insertResponse(readResp);
}
}
@ -168,7 +179,7 @@ export class updateQuery {
const builder = this.serialize(handler);
const s = handler.builders.query(builder);
let readResp = await db.query(s, printQuery);
return db.getHandler().responses.writeResponse(readResp);
return handler.responses.writeResponse(readResp);
}
}
@ -190,6 +201,6 @@ export class removeQuery {
const builder = this.serialize(handler);
const s = handler.builders.query(builder);
let readResp = await db.query(s, printQuery);
return db.getHandler().responses.writeResponse(readResp);
return handler.responses.writeResponse(readResp);
}
}

View file

@ -1,6 +1,6 @@
import { AttributeAlias } from "./alias";
import { Attribute } from "./db";
import { primaryData } from "./types";
import { AttributeAlias } from "./alias.js";
import { Attribute } from "./db.js";
import { primaryData } from "./types.js";
export class singleResponse {
[key: string]: primaryData | any;
@ -15,7 +15,9 @@ export class singleResponse {
export class readResponse extends Array<singleResponse>{
constructor(rows: ({ [key: string]: primaryData })[]) {
super();
this.push(...rows.map(r => new singleResponse(r)));
for(let i = 0; i < rows.length; i++){
this[i] = new singleResponse(rows[i])
}
}
}

3
src/tools.ts Normal file
View file

@ -0,0 +1,3 @@
import crypto from "crypto";
export const sha256 = (d: any) => crypto.createHash('sha256').update(String(d)).digest('base64');

View file

@ -1,12 +1,12 @@
import { AttributeAlias, TableAlias } from "./alias";
import { Attribute, Table } from "./db";
import { Aggregation, BooleanModifier, Datatype, Joins, Modifier } from "./dbStructure";
import { QueryBuilder, selectQuery } from "./query";
import { Alias, AttributeAlias, TableAlias } from "./alias.js";
import { Attribute, Table } from "./db.js";
import { Aggregation, BooleanModifier, Datatype, Joins, Modifier } from "./dbStructure.js";
import { QueryBuilder, selectQuery } from "./query.js";
export type primaryData = string | number | boolean | null;
export type allModifierInput = primaryData | Modifier | selectQuery | Attribute | AttributeAlias | Aggregation;
export type allModifierInput = primaryData | Modifier | selectQuery | Attribute | AttributeAlias | Aggregation | Alias;
export type selectElements = primaryData | Attribute | AttributeAlias | Aggregation | selectQuery
export type selectElements = primaryData | Attribute | AttributeAlias | Aggregation | selectQuery | Alias;
export type selectFromElements = TableAlias | Table | Joins | null;
export type joinElements = Table | Joins;
@ -20,7 +20,7 @@ export type attributeSettings = {
default?: primaryData,
notNull?: boolean
primaryKey?: boolean,
foreginKey?: {
foreignKey?: {
link: Attribute,
onDelete?: onAction,
onUpdate?: onAction
@ -35,7 +35,7 @@ export type extendedAttributeSettings = {
default?: primaryData,
notNull?: boolean
primaryKey?: boolean,
foreginKey?: {
foreignKey?: {
link: Attribute,
onDelete?: onAction,
onUpdate?: onAction
@ -64,3 +64,8 @@ export enum dbType {
//mysql,
postgres,
}
export enum order {
ASC,
DESC
}

View file

@ -1,6 +1,7 @@
{
"compilerOptions": {
"module": "CommonJS",
"target": "ES6",
"module": "ES6",
"lib": ["es6"],
"types": ["node"],
"declaration": true,