mql-mysql
Build sql dynamically
Install
npm i --save mql-mysql
This package depends on ext-mysql
which is used to make requests to the database.
Why should you use a SQL builder?
Just to be clear, IMO, you should avoid that. Whenever is possible, write down your raw sqls. But, maybe you're are building a custom report or forms and lists based in custom values, flags and your SQL starts to look something similar to:
var sql = "SELECT ";for var i in columns sql += columnsi;// ...if hasJoins sql += joins; if where //...
You may find this useful.
Matrix Query Language
It's not exactly a language, but a matrix object. It explains how the data you want to retrieve or set should be found. It could a json file, but there is MQL class to help you do that. Let's set up an example.
const MQL MQLtoMySQL = ;const MySQL = ; // Set your MySQL dbprocessenvENCODE = "utf8";processenvMYSQL_HOSTNAME = "localhost";processenvMYSQL_USER = "root";processenvMYSQL_PASSWORD = "";processenvMYSQL_DATABASE = "test";MySQL; // Create a MySQL connectionconst conn = ;await conn;
Our first MQL
const mql = ; // Set a table called persons and add two columns, id and name.mql;mqlpersons;mqlpersons; // Now you use this mql object to select from database.var sql binds = await MQLtoMySQL;console;// SELECT persons.id id, persons.name name FROM persons persons // Or you can run to databasevar rows fields = await MQLtoMySQL;
MQL.addTable( key, name = key, primary = 'id' )
The key works as an alias, but if you don't provide a (table) name, it's going to be that too. Primary is the column name of the primary key of the table.
MQL.addColumn( table, key, name = key, value = null, flag = MQL.GET )
The table is the alias you gave before (you have to set the table before the column), key works as an alias for the column, name of the column same rule of setTable
. Value is used for set, where, join. And flag sets what you want to do about the column. You can access the table and set a column like mmql.myTableAlias.addColumn( 'colName' )
.
Examples
This mql below create a row for person table with name and age. After it gets the insert id, it will replace the person.id
with the correct value and add the address.
mql = ; const mql = ; mql;mqlperson;mqlperson;mqlperson; mql;mqladdress;mqladdress;mqladdress; var ids results = MQLtoMySQL;
Update
This example does the same as before, but updating value. Now we have to set a column with MQL.EQUAL_TO
in order to create a where rule. The address will be found because of the MQL.JOIN
. It updates and get the person row, look for a address that fits the MQL.JOIN
if found, updates, when not, inserts a new row.
mql = ; const mql = ; mql;mqlperson;mqlperson;mqlperson; mql;mqladdress;mqladdress;mqladdress; var ids results = MQLtoMySQL;
Delete
This is the same than before, I just remove the MQL.SET
columns. You could keep those there, they are ignored.
mql = ; const mql = ; mql;mqlperson; mql;mqladdress; var ids results = MQLtoMySQL;
// TODO: More examples.