npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@ssense/mysql

v1.0.4

Published

Helpers for accessing and sending queries to MySQL or MariaDB

Downloads

432

Readme

🡐 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

| Method | Returns | Description | | ------------------------------------------------------------------------------------------------------------------------------------------------------ | --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | | constructor(options: ConnectionOptions) | Connection | Creates 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

| Name | Type | Required | Description | | ------- | ------------------- | :------: | -------------------------------------------------- | | options | ConnectionOptions | Yes | The parameters used to connect to the MySQL server |

ConnectionOptions properties

See here for more detail about options properties.

| Name | Type | Required | Description | | --------------- | -------- | :------: | ------------------------------------------------------------------------------------------------------------------------------------------------------------- | | host | string | Yes | MySQL server hostname or IP address | | database | string | Yes | Name of database to use | | port | number | No | MySQL port (default: 3306) | | user | string | No | MySQL username (default: null) | | password | string | No | MySQL password (default: null) | | connectionLimit | number | No | Maximum number of parallel connections in internal MySQL connection pool (default: 10) | | timezone | string | No | The 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

| Name | Type | Required | Description | | ------ | -------- | :------: | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | sql | string | Yes | SQL query | | params | any[] | No | SQL query params for a query with parameters (will be protected against SQL injections, see mysql npm module for more detail) |

Return value

| Type | Description | | -------------- | ---------------------------- | | 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

| Name | Type | Required | Description | | -------- | --------------------- | :------: | ----------------------------------------------------------------------------------------------- | | callback | TransactionFunction | Yes | Function 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

| Type | Description | | -------------- | ---------------------------------- | | 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

| Name | Type | Required | Description | | -------- | --------------------- | :------: | ----------------------------------------------------------------------------------------------- | | locks | LockTableOption[] | Yes | Array of LockTableOption (tables to lock with lock mode) | | callback | TransactionFunction | Yes | Function in which all the MySQL statements can be executed (will be run in a MySQL transaction) |

LockTableOption properties

| Name | Type | Required | Description | | ---- | ------------------- | :------: | ------------------------------------------------------ | | name | string | Yes | Name of the table to lock | | mode | 'READ'|'WRITE' | Yes | Lock 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

| Type | Description | | -------------- | ---------------------------------- | | 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.