mysql4-helpers

1.5.0 • Public • Published

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();

Readme

Keywords

none

Package Sidebar

Install

npm i mysql4-helpers

Weekly Downloads

1

Version

1.5.0

License

ISC

Unpacked Size

5.22 kB

Total Files

7

Last publish

Collaborators

  • pan1994