1
1
mirror of https://github.com/Fabio286/antares.git synced 2025-06-05 21:59:22 +02:00

Improvements to query builder

This commit is contained in:
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'; import ipcHandlers from './ipc-handlers';
if (module.hot) module.hot.accept(); const isDevelopment = process.env.NODE_ENV !== 'production';
const isDevelopment = process.env.NODE_ENV === 'development';
process.env.ELECTRON_DISABLE_SECURITY_WARNINGS = 'true'; process.env.ELECTRON_DISABLE_SECURITY_WARNINGS = 'true';
// global reference to mainWindow (necessary to prevent window from being garbage collected) // global reference to mainWindow (necessary to prevent window from being garbage collected)

View File

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

View File

@ -1,36 +1,78 @@
'use strict'; 'use strict';
import mysql from 'mysql2'; import mysql from 'mysql2';
/**
* As Simple As Possible Query Builder
*
* @export
* @class AntaresConnector
*/
export class AntaresConnector { export class AntaresConnector {
/**
*Creates an instance of AntaresConnector.
* @param {Object} args connection params
* @memberof AntaresConnector
*/
constructor (args) { constructor (args) {
this.client = args.client; this._client = args.client;
this.params = args.params; this._params = args.params;
this.poolSize = args.poolSize || false; this._poolSize = args.poolSize || false;
this.connection = null; this._connection = null;
this.query = { this._queryDefaults = {
schema: '',
select: [], select: [],
from: '', from: '',
where: [], where: [],
groupBy: [], groupBy: [],
orderBy: [], orderBy: [],
limit: '',
join: [], join: [],
update: [], 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 () { connect () {
switch (this.client) { switch (this._client) {
case 'maria': case 'maria':
case 'mysql': case 'mysql':
if (!this.poolSize) { if (!this._poolSize) {
const connection = mysql.createConnection(this.params); const connection = mysql.createConnection(this._params);
this.connection = connection.promise(); this._connection = connection.promise();
} }
else { else {
const pool = mysql.createPool({ ...this.params, connectionLimit: this.poolSize }); const pool = mysql.createPool({ ...this._params, connectionLimit: this._poolSize });
this.connection = pool.promise(); this._connection = pool.promise();
} }
break; break;
@ -39,26 +81,66 @@ export class AntaresConnector {
} }
} }
// select (args) { schema (schema) {
// const type = typeof args; this._query.schema = schema;
return this;
}
// switch (type) { select (...args) {
// case string: this._query.select = [...this._query.select, ...args];
// case number: return this;
// this.query.select; }
// break;
// default: from (table) {
// break; 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) { async raw (sql) {
switch (this.client) { switch (this._client) {
case 'maria': case 'maria':
case 'mysql': { case 'mysql': {
console.log(mysql); const [rows, fields] = await this._connection.query(sql);
const [rows, fields] = await this.connection.query(sql);
return { rows, fields }; return { rows, fields };
} }
default: default:
@ -66,11 +148,14 @@ export class AntaresConnector {
} }
} }
/**
* @memberof AntaresConnector
*/
destroy () { destroy () {
switch (this.client) { switch (this._client) {
case 'maria': case 'maria':
case 'mysql': { case 'mysql': {
this.connection.end(); this._connection.end();
break; break;
} }
default: default:

View File

@ -1,11 +1,17 @@
'use strict'; 'use strict';
export default class { export default class {
static testConnection (connection) { static testConnection (connection) {
return connection.raw('SELECT 1+1'); return connection.select('1+1').run();
} }
static getStructure (connection) { 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; // TODO: SELECT * FROM `information_schema`.`COLUMNS` WHERE TABLE_SCHEMA='fepcomdb' AND TABLE_NAME='macchine' ORDER BY ORDINAL_POSITION;