1.0.4 • Published 2 years ago

@ssense/mysql v1.0.4

Weekly downloads
-
License
ISC
Repository
github
Last release
2 years ago

🡐 Go to main README page

MySQL Client

class Connection

Connection is a helper that makes it easy to access and send queries to a MySQL or MariaDB server. (see examples here)

Methods

MethodReturnsDescription
constructor(options: ConnectionOptions)ConnectionCreates a new instance of Connection
query(sql: string, params?: any[])Promise<any>Sends a query to MySQL server and return a result
runInTransaction(callback: TransactionFunction)Promise<any>Executes a list of statements in a MySQL transactional way, managing the transaction (begin, commit, rollback) automatically
runWithLockTables(locks: LockTableOption[], callback: TransactionFunction)Promise<any>Same as runInTransaction() method, except it explicitly locks tables before running the transaction (calling LOCK TABLES instead of START TRANSACTION)
close()Promise<void>Closes all opened connections to the database and prevent new connections to be created

Details

constructor(options: ConnectionOptions)

Creates a new instance of Connection

Parameters

NameTypeRequiredDescription
optionsConnectionOptionsYesThe parameters used to connect to the MySQL server

ConnectionOptions properties

See here for more detail about options properties.

NameTypeRequiredDescription
hoststringYesMySQL server hostname or IP address
databasestringYesName of database to use
portnumberNoMySQL port (default: 3306)
userstringNoMySQL username (default: null)
passwordstringNoMySQL password (default: null)
connectionLimitnumberNoMaximum number of parallel connections in internal MySQL connection pool (default: 10)
timezonestringNoThe timezone configured on the MySQL server. This is used to type cast server date/time values to JavaScript Date object and vice versa. (default: 'local')

query(sql: string, params?: any[])

Sends a query to MySQL server and return a result

Parameters

NameTypeRequiredDescription
sqlstringYesSQL query
paramsany[]NoSQL query params for a query with parameters (will be protected against SQL injections, see mysql npm module for more detail)

Return value

TypeDescription
Promise<any>Result of the executed query

runInTransaction(callback: TransactionFunction)

Executes a list of statements in a MySQL transactional way, managing the transaction (begin, commit, rollback) automatically

Parameters

NameTypeRequiredDescription
callbackTransactionFunctionYesFunction in which all the MySQL statements can be executed (will be run in a MySQL transaction)

TransactionFunction definition

TransactionFunction is a callback function that will be called with a transaction parameter, this transaction exposes a query function, which has the exact same profile as the query function above. You are therefore able to call transaction.query() to send MySQL queries in a transactional context. See examples for more detail.

Return value

TypeDescription
Promise<any>Result of the executed transaction

runWithLockTables(locks: LockTableOption[], callback: TransactionFunction)

Same as runInTransaction() method, except it explicitly locks tables before running the transaction (calling LOCK TABLES instead of START TRANSACTION)

Parameters

NameTypeRequiredDescription
locksLockTableOption[]YesArray of LockTableOption (tables to lock with lock mode)
callbackTransactionFunctionYesFunction in which all the MySQL statements can be executed (will be run in a MySQL transaction)

LockTableOption properties

NameTypeRequiredDescription
namestringYesName of the table to lock
mode'READ'|'WRITE'YesLock mode to use, must be one of 'READ' or 'WRITE'

TransactionFunction definition

Definition for TransactionFunction is available in runInTransaction() method above. See examples for more detail.

Return value

TypeDescription
Promise<any>Result of the executed transaction

close()

Closes all opened connections to the database and prevent new connections to be created

Examples

Transactional queries using runInTransaction()

import { Connection } from '@ssense/framework';

// Create connection
const connection = new Connection({ ...params });

// Run multiple MySQL commands inside a managed transaction
const result = await connection.runInTransaction(async (transaction) => {
    const users = await transaction.query('SELECT * FROM USERS');
    if (users.length > 0) {
        await transaction.query('UPDATE users set name=.....');
    }

    return users[0];
});

// result will be the object returned by the runInTransaction() method, here users[0]
// All the MySQL transaction commands (BEGIN, COMMIT or ROLLBACK) are automatically performed, so you just have to focus on your business case.

Transactional queries using runWithLockTables()

import { Connection } from '@ssense/framework';

// Create connection
const connection = new Connection({ ...params });

// Run multiple MySQL commands inside a managed transaction
const result = await connection.runWithLockTables(
    [
        { name: 'users', mode: 'WRITE' },
        { name: 'accounts', mode: 'WRITE' },
    ],
    async (transaction) => {
        // When reaching this part of the code, both "users" and "accounts" tables will be locked, even if we don't perfom any query on the "accounts" table
        const users = await transaction.query('SELECT * FROM USERS');
        if (users.length > 0) {
            await transaction.query('UPDATE users set name=.....');
        }

        return users[0];
    },
);

// result will be the object returned by the runWithLockTables() method, here users[0]
// All the MySQL transaction commands (BEGIN, COMMIT or ROLLBACK) are automatically performed, so you just have to focus on your business case.
1.0.4

2 years ago

1.0.3

2 years ago

1.0.2

3 years ago

1.0.1

3 years ago

1.0.0

3 years ago