Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@ssense/mysql

Package Overview
Dependencies
Maintainers
27
Versions
5
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@ssense/mysql

Helpers for accessing and sending queries to MySQL or MariaDB

  • 1.0.4
  • latest
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
82
increased by49.09%
Maintainers
27
Weekly downloads
 
Created
Source

🡐 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.

Keywords

FAQs

Package last updated on 01 Sep 2022

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc