mysql4-helpers
v1.5.0
Published
This module provides three helpers for [mysql4](https://www.npmjs.com/package/mysql4): `Query`, `PreparedStatement` and `transaction`.
Downloads
6
Readme
MySQL 4 Helpers
This module provides three helpers for mysql4: Query
, PreparedStatement
and transaction
.
It only supports promisified versions of connection
and pool
;
Usage
Query
Query
is a wrapper object for SQL queries that internally uses mysql4
query()
method.
const { Query } = require('mysql4-helpers');
let sql = 'SELECT * FROM table WHERE id = ?';
let params = [id];
let transformFn = (res, info) => res.name;
// defaultConnection is an instance of mysql4 connection/pool
let insertQuery = new Query(sql, params, defaultConnection, transformFn);
// Execution on default connection
insertQuery.execute().then(id => console.log(id));
// Execution on custom connection
insertQuery.execute(conn).then(id => console.log(id));
PreparedStatement
PreparedStatement
is a wrapper object for SQL queries that internally uses mysql4
execute()
method.
const { PreparedStatement } = require('mysql4-helpers');
let sql = 'SELECT * FROM table WHERE id = ?';
let params = [id];
let transformFn = (res, info) => res.name;
// defaultConnection is an instance of mysql4 connection/pool
let insertQuery = new PreparedStatement(sql, params, defaultConnection, transformFn);
// Execution on default connection
insertQuery.execute().then(id => console.log(id));
// Execution on custom connection
insertQuery.execute(conn).then(id => console.log(id));
transaction
The function transaction
allows to execute Query
and PreparedStatement
objects in transaction.
const { Query, PreparedStatement, transaction, IsolationLevel } = require('mysql4-helpers');
let selectQuery = id => new PreparedStatement(
'SELECT field FROM table1 WHERE id = ?',
[id],
pool,
res => res.field
);
let updateQuery = (field, newValue) => new Query(
'UPDATE table2 SET another_field = ? WHERE field = ?',
[newValue, field],
pool
);
// connection is an instance of mysql4 connection/pool
const tx = await transaction(connection, IsolationLevel.SERIALIZABLE);
const res = await selectQuery(1).execute(tx);
await updateQuery(res, 50).execute(tx);
await tx.commit();
// OR
await tx.rollback();