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

mysql-database-connection

v0.2.0

Published

A class to establish read and write MySQL connections

Downloads

4

Readme

MySqlDatabaseConnection

A class to using multiple read and write MySQL connections. Under the hood, this is a using the mysql package and its pooling feature.

It comes with a factory to create an instance from environment variables which follows common best practices of not storing DB info in code.

Connection options

There are five properties used for each connection:

1. Database name

The same name is used for all the connections.

  • environment variable: DB_NAME=myDbName
  • constructor config: {database: 'myDbName'}

2. Database user

Each connection may have a different username. If a connection doesn't have a username set, the username set in the default connection will be used.

  • default environment variable: DB_USER=myuser
  • default constructor config: {defaultConnection: {user: 'myuser'}}
  • per connection environment variable: DB_READ0_USER=readonlyuser
  • per connection constructor config: {readConnections: [{user: 'readonlyuser'}]}

3. Database password

Each connection may have a different password. If a connection doesn't have a password set, the password set in the default connection will be used.

  • default environment variable: DB_PASS=secret
  • default constructor config: {defaultConnection: {pass: 'secret'}}
  • per connection environment variable: DB_WRITE0_PASS=secret
  • per connection constructor config: {writeConnections: [{pass: 'secret'}]}

4. Database host

Each connection may have a different host. If a connection doesn't have a host set, the host set in the default connection will be used.

  • default environment variable: DB_HOST=mysql.example.com
  • default constructor config: {defaultConnection: {host: 'mysql.example.com'}}
  • per connection environment variable: DB_READ0_HOST=mysql.example.com
  • per connection constructor config: {readConnections: [{host: 'mysql.example.com'}]}

5. Database port

Each connection may have a different port. If a connection doesn't have a port set, the port set in the default connection will be used. If no default port is set, then the MySQL default port of 3306 is used.

  • default environment variable: DB_PORT=8888
  • default constructor config: {defaultConnection: {port: 8888}}
  • per connection environment variable: DB_READ0_PORT=8888
  • per connection constructor config: {readConnections: [{port: 8888}]}

Environment variable configuration example

An example of configuring the connections via the environment variables.

# The same name is used in all connections
DB_NAME=myDatabase

# Default connection info used to populate other connections
DB_USER=myUser
DB_PASS=secret
DB_PORT=8888

# Write connection 1 has a different host while using the same user,
# password and port
DB_WRITE0_HOST=master.mysql.example.com

# Read connection 1 has a different host
DB_READ0_HOST=1.slave.mysql.example.com

# Read connection 2 has different host, user and password
DB_READ1_HOST=2.slave.mysql.example.com
DB_READ1_USER=readonly
DB_READ1_PASS=someOtherSecret

# Read connection 3
DB_READ2_HOST=6.slave.mysql.example.com
const MySqlDatabaseConnection = require('mysql-database-connection');
const dbConnections = MySqlDatabaseConnection.createConnectionFromEnv();

In Code Configuration Example

const MySqlDatabaseConnection = require('mysql-database-connection');
const dbConnections = new MySqlDatabaseConnection.MySqlDatabaseConnection({
  // The same name is used in all connections
  database: 'myDatabase',
    
  // Default connection info used to populate other connections
  defaultConnection: {
    user: 'myUser',
    password: 'secret',
    port: 8888,
  },

  writeConnections: [
    // Write connection 1 has a different host while using the same user,
    // password and port
    {
      host: 'master.mysql.example.com',
    }
  ],

  readConnections: [
    // Read connection 1 has a different host
    {
      host: '1.slave.mysql.example.com',
    },
    
    // Read connection 2 has different host, user and password
    {
      host: '2.slave.mysql.example.com',
      user: 'readonly',
      pass: 'someOtherSecret',
    },
    
    // Read connection 3
    {
      host: '6.slave.mysql.example.com',
    },
  ],
});

MySqlDatabaseConnection class

constructor(connectionOptions [, poolingOptions [, mysql]])

methods

readQuery(sqlString [, values])

Execute a read query.

db.readQuery('SELECT * FROM users WHERE id=?', [5])
  .then((dbResults) => {
    console.log('User DB', dbResults);
  }, (dbError) => {
    console.log('Error: ', dbError);
  });
Parameters
Return value

A promise with the results.

writeQuery(query, args)

Execute a write query.

db.readQuery('INSERT INTO users VALUES (?, ?)', ['John', '[email protected]'])
  .then((dbResults) => {
    console.log('Insert', dbResults);
  }, (dbError) => {
    console.log('Error: ', dbError);
  });
Parameters
Return value

A promise with the results.

getReadConnection()

Get a mysql read connection.

getWriteConnection()

Get a mysql write connection.

destroy([done])

Destroy the pool of connections.

Parameters

getDataRowsFromResults(results)

A utility to get just the RowDataPackets in the results.

The DB results will contain the OkPackets and sometimes be nested arrays. This will walk through nested arrays to find the RowDataPackets.

Parameters
Return value

An array of just RowDataPackets.

createConnectionFromEnv([poolOptions [, envs [, mysql]]])

Parameters