Improvements to query builder

This commit is contained in:
Fabio 2020-06-14 19:02:07 +02:00
parent 3e13b9962d
commit aa7618ec8d
5 changed files with 124 additions and 34 deletions

View File

@ -7,8 +7,7 @@ import { autoUpdater } from 'electron-updater';
import ipcHandlers from './ipc-handlers';
if (module.hot) module.hot.accept();
const isDevelopment = process.env.NODE_ENV === 'development';
const isDevelopment = process.env.NODE_ENV !== 'production';
process.env.ELECTRON_DISABLE_SECURITY_WARNINGS = 'true';
// global reference to mainWindow (necessary to prevent window from being garbage collected)

View File

@ -2,7 +2,7 @@
import { ipcMain } from 'electron';
import { AntaresConnector } from '../libs/AntaresConnector';
import InformationSchema from '../models/InformationSchema';
import GenericQuery from '../models/GenericQuery';
import Generic from '../models/Generic';
const connections = {};
@ -76,7 +76,7 @@ export default () => {
ipcMain.handle('rawQuery', async (event, { uid, query, database }) => {
if (!query) return;
try {
const result = await GenericQuery.raw(connections[uid], query, database);
const result = await Generic.raw(connections[uid], query, database);
return { status: 'success', response: result };
}
catch (err) {

View File

@ -1,36 +1,78 @@
'use strict';
import mysql from 'mysql2';
/**
* As Simple As Possible Query Builder
*
* @export
* @class AntaresConnector
*/
export class AntaresConnector {
/**
*Creates an instance of AntaresConnector.
* @param {Object} args connection params
* @memberof AntaresConnector
*/
constructor (args) {
this.client = args.client;
this.params = args.params;
this.poolSize = args.poolSize || false;
this.connection = null;
this._client = args.client;
this._params = args.params;
this._poolSize = args.poolSize || false;
this._connection = null;
this.query = {
this._queryDefaults = {
schema: '',
select: [],
from: '',
where: [],
groupBy: [],
orderBy: [],
limit: '',
join: [],
update: [],
insert: []
insert: [],
delete: []
};
this._query = Object.assign({}, this._queryDefaults);
}
_reducer (acc, curr) {
const type = typeof curr;
switch (type) {
case 'number':
case 'string':
return [...acc, curr];
case 'object':
if (Array.isArray(curr))
return [...acc, ...curr];
else {
const clausoles = [];
for (const key in curr)
clausoles.push(`${key} ${curr[key]}`);
return clausoles;
}
}
}
_resetQuery () {
this._query = Object.assign({}, this._queryDefaults);
}
/**
* @memberof AntaresConnector
*/
connect () {
switch (this.client) {
switch (this._client) {
case 'maria':
case 'mysql':
if (!this.poolSize) {
const connection = mysql.createConnection(this.params);
this.connection = connection.promise();
if (!this._poolSize) {
const connection = mysql.createConnection(this._params);
this._connection = connection.promise();
}
else {
const pool = mysql.createPool({ ...this.params, connectionLimit: this.poolSize });
this.connection = pool.promise();
const pool = mysql.createPool({ ...this._params, connectionLimit: this._poolSize });
this._connection = pool.promise();
}
break;
@ -39,26 +81,66 @@ export class AntaresConnector {
}
}
// select (args) {
// const type = typeof args;
schema (schema) {
this._query.schema = schema;
return this;
}
// switch (type) {
// case string:
// case number:
// this.query.select;
// break;
select (...args) {
this._query.select = [...this._query.select, ...args];
return this;
}
// default:
// break;
// }
// }
from (table) {
this._query.from = table;
return this;
}
where (...args) {
this._query.where = [...this._query.where, ...args];
return this;
}
groupBy (...args) {
this._query.groupBy = [...this._query.groupBy, ...args];
return this;
}
orderBy (...args) {
this._query.orderBy = [...this._query.orderBy, ...args];
return this;
}
getQueryString () {
const selectArray = this._query.select.reduce(this._reducer, []);
const selectRaw = selectArray.length ? `SELECT ${selectArray.join(', ')}` : 'SELECT *';
const fromRaw = this._query.from ? `FROM ${this._query.schema ? `\`${this._query.schema}\`.` : ''} \`${this._query.from}\`` : '';
const whereArray = this._query.where.reduce(this._reducer, []);
const whereRaw = whereArray.length ? `WHERE ${whereArray.join(', AND ')}` : '';
const groupByArray = this._query.groupBy.reduce(this._reducer, []);
const groupByRaw = groupByArray.length ? `GROUP BY ${groupByArray.join(', ')}` : '';
const orderByArray = this._query.orderBy.reduce(this._reducer, []);
const orderByRaw = orderByArray.length ? `ORDER BY ${orderByArray.join(', ')}` : '';
return `${selectRaw} ${fromRaw} ${whereRaw} ${groupByRaw} ${orderByRaw}`;
}
run () {
const rawQuery = this.getQueryString();
this._resetQuery();
return this.raw(rawQuery);
}
/**
* @param {*} sql raw SQL query
* @returns {Promise}
* @memberof AntaresConnector
*/
async raw (sql) {
switch (this.client) {
switch (this._client) {
case 'maria':
case 'mysql': {
console.log(mysql);
const [rows, fields] = await this.connection.query(sql);
const [rows, fields] = await this._connection.query(sql);
return { rows, fields };
}
default:
@ -66,11 +148,14 @@ export class AntaresConnector {
}
}
/**
* @memberof AntaresConnector
*/
destroy () {
switch (this.client) {
switch (this._client) {
case 'maria':
case 'mysql': {
this.connection.end();
this._connection.end();
break;
}
default:

View File

@ -1,11 +1,17 @@
'use strict';
export default class {
static testConnection (connection) {
return connection.raw('SELECT 1+1');
return connection.select('1+1').run();
}
static getStructure (connection) {
return connection.raw('SELECT * FROM information_schema.TABLES ORDER BY TABLE_SCHEMA, TABLE_NAME ASC');
// return connection.raw('SELECT * FROM information_schema.TABLES ORDER BY TABLE_SCHEMA ASC, TABLE_NAME ASC');
return connection
.select('*')
.schema('information_schema')
.from('TABLES')
.orderBy({ TABLE_SCHEMA: 'ASC', TABLE_NAME: 'ASC' })
.run();
}
// TODO: SELECT * FROM `information_schema`.`COLUMNS` WHERE TABLE_SCHEMA='fepcomdb' AND TABLE_NAME='macchine' ORDER BY ORDINAL_POSITION;