mysql-serverless

Manage MySQL connections in cloud functions environments


Keywords
mysql, serverless, cloud functions, rds, lambda
License
CNRI-Python-GPL-Compatible
Install
npm install mysql-serverless@1.1.6

Documentation

MySQL serverless

NPM Version NPM Downloads Node.js Version

MySQL Serverless is a wrapper for Doug Wilson's amazing mysql Node.js module. Manage MySQL connections in cloud functions environments, like AWS Lambda or Azure Cloud Functions, where pooling is not available or its configuration is a little bit confusing.

Features:

  • master/slave architecture (handling multiple read replicas)
  • async/await support
  • transactions support
  • dont worry for open loops (all connections are terminated gracefully)

This module is based on temporary connections philosophy. If you want your connections to be persisted across different executions, use jdaly module instead.

NOTE: This module should work with any standards-based MySQL server. It has been tested with AWS's RDS MySQL, Aurora MySQL, and Aurora Serverless.

Table of Contents

Installation

Using npm:

$ npm i --save mysql-serverless

Using yarn:

$ yarn add mysql-serverless

Requirements

  • Node.js 8.10 or higher is required.

Usage

Configuration

Initialize outside of your handler function. Simple configuration (it will use the same database for both reading and writing):

const mysql = require("mysql-serverless")({
    host        : process.env.DB_HOST,
    user        : process.env.DB_USER,
    password    : process.env.DB_PASSWORD,
    database    : process.env.DB_NAME
});

Connection options can be passed later using the configure() method.

const mysql = require("mysql-serverless");

exports.handler = async (event, context) {
    const config = {
        host        : event.stageVariables.db_host,
        user        : event.stageVariables.db_user,
        password    : event.stageVariables.db_password,
        database    : event.stageVariables.db_name
    };
    mysql.configure(config);
};

Setting master/slave

Setting master and one slave:

const mysql = require("mysql-serverless")({
    masterConfig: { 
        host        : process.env.DB_MASTER_HOST,
        user        : process.env.DB_MASTER_USER,
        password    : process.env.DB_MASTER_PASSWORD,
        database    : process.env.DB_NAME
    },
    slaveConfig: {
        host        : process.env.DB_SLAVE_HOST,
        user        : process.env.DB_SLAVE_USER,
        password    : process.env.DB_SLAVE_PASSWORD,
        database    : process.env.DB_NAME
    }
});

// Using configure()
const mysql = require("mysql-serverless");
const masterConfig = {...};
const slaveConfig = {...};
mysql.configure(masterConfig, slaveConfig);

Setting master and multiple slaves:

const mysql = require("mysql-serverless")({
    masterConfig: { 
        host        : process.env.DB_MASTER_HOST,
        user        : process.env.DB_MASTER_USER,
        password    : process.env.DB_MASTER_PASSWORD,
        database    : process.env.DB_NAME
    },
    slavesConfig: [{
        host        : process.env.DB_SLAVE1_HOST,
        user        : process.env.DB_SLAVE1_USER,
        password    : process.env.DB_SLAVE1_PASSWORD,
        database    : process.env.DB_NAME
    }, {
        host        : process.env.DB_SLAVE2_HOST,
        user        : process.env.DB_SLAVE2_USER,
        password    : process.env.DB_SLAVE2_PASSWORD,
        database    : process.env.DB_NAME
    }]
});

// Using configure()
const mysql = require("mysql-serverless");
const masterConfig = {...};
const slave1Config = {...};
const slave2Config = {...};
mysql.configure(masterConfig, [slave1Config, slave2Config]);

Querying database

Execute queries using mysql.query(sql, params, connection?). Read-only queries are sent to read replicas (if set). Any other query that involves writing to the database are sent to the master host. Pass in a previously created connection to reuse it.

// Using async/await
try {
    const rows = await mysql.query("SELECT * FROM user WHERE id = ?", [96]);
    console.log(rows);
} catch(err) {
    console.log(err);
}

// Using promises
mysql.query("SELECT * FROM user WHERE id = ?", [96]).then(rows => {
    console.log(rows);
}).catch(err => {
    console.log(err);
});

Transactions

Begin transaction with beginTransaction(). This method returns a connection object you will need to make queries and commit all changes.
Once you have executed all queries, commit all changes with connection.commit(). By default, the connection will be closed after commit. If you need to rollback manually, you can use connection.rollback().

Every query you invoke on a connection is queued and executed in sequence.

// begin transaction
const connection = await mysql.beginTransaction();

// make queries
await connection.query("INSERT INTO Marks VALUES (?, ?, ?)", ['Alice', 'Maths', 55]);
await connection.query("INSERT INTO Marks VALUES (?, ?, ?)", ['Bob', 'Maths', 50]);

// commit all changes and end connection
await connection.commit();

License

GPL-3.0-or-later licensed. See LICENSE file for details.