• Stars
    star
    485
  • Rank 90,698 (Top 2 %)
  • Language
    C++
  • License
    MIT License
  • Created about 12 years ago
  • Updated over 4 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A node.js binding to MariaDB's non-blocking (MySQL-compatible) client library

Description

A node.js binding to MariaDB's non-blocking (MySQL-compatible) client library.

This binding is different from a vanilla libmysqlclient binding in that it uses the non-blocking functions available in MariaDB's client library. As a result, this binding does not use multiple threads to achieve non-blocking behavior.

Benchmarks comparing this module to the other node.js MySQL driver modules can be found here.

Build Status Build status

Upgrading from v0.1.x? See a list of (breaking) changes here.

Requirements

Install

npm install mariasql

Examples

  • Simple query:
var Client = require('mariasql');

var c = new Client({
  host: '127.0.0.1',
  user: 'foo',
  password: 'bar'
});

c.query('SHOW DATABASES', function(err, rows) {
  if (err)
    throw err;
  console.dir(rows);
});

c.end();
  • Get column metadata:
var Client = require('mariasql');

var c = new Client({
  host: '127.0.0.1',
  user: 'foo',
  password: 'bar'
});

c.query('SHOW DATABASES', null, { metadata: true }, function(err, rows) {
  if (err)
    throw err;
  // `rows.info.metadata` contains the metadata
  console.dir(rows);
});

c.end();
  • Use arrays (faster) instead of objects for rows:
var Client = require('mariasql');

var c = new Client({
  host: '127.0.0.1',
  user: 'foo',
  password: 'bar'
});

c.query('SHOW DATABASES', null, { useArray: true }, function(err, rows) {
  if (err)
    throw err;
  console.dir(rows);
});

c.end();
  • Use placeholders in a query
var Client = require('mariasql');

var c = new Client({
  host: '127.0.0.1',
  user: 'foo',
  password: 'bar',
  db: 'mydb'
});

c.query('SELECT * FROM users WHERE id = :id AND name = :name',
        { id: 1337, name: 'Frylock' },
        function(err, rows) {
  if (err)
    throw err;
  console.dir(rows);
});

c.query('SELECT * FROM users WHERE id = ? AND name = ?',
        [ 1337, 'Frylock' ],
        function(err, rows) {
  if (err)
    throw err;
  console.dir(rows);
});

c.end();
  • Stream rows
var Client = require('mariasql');

var c = new Client({
  host: '127.0.0.1',
  user: 'foo',
  password: 'bar',
  db: 'mydb'
});

var query = c.query("SELECT * FROM users WHERE id > 1");
query.on('result', function(res) {
  // `res` is a streams2+ Readable object stream
  res.on('data', function(row) {
    console.dir(row);
  }).on('end', function() {
    console.log('Result set finished');
  });
}).on('end', function() {
  console.log('No more result sets!');
});

c.end();
  • Explicitly generate a prepared query for later use
var Client = require('mariasql');

var c = new Client({
  host: '127.0.0.1',
  user: 'foo',
  password: 'bar',
  db: 'mydb'
});

var prep = c.prepare('SELECT * FROM users WHERE id = :id AND name = :name');

c.query(prep({ id: 1337, name: 'Frylock' }), function(err, rows) {
  if (err)
    throw err;
  console.dir(rows);
});

c.end();

API

require('mariasql') returns a Client object

Client properties

  • connected - boolean - true if the Client instance is currently connected to the server.

  • connecting - boolean - true if the Client instance is currently in the middle of connecting to the server.

  • threadId - string - If connected, this is the thread id of this connection on the server.

Client events

  • ready() - Connection and authentication with the server was successful.

  • error(< Error >err) - An error occurred at the connection level.

  • end() - The connection ended gracefully.

  • close() - The connection has closed.

Client methods

  • (constructor)() - Creates and returns a new Client instance.

  • connect(< object >config) - (void) - Attempts a connection to a server using the information given in config:

    • user - string - Username for authentication. Default: (*nix: current login name, Windows: ???)

    • password - string - Password for authentication. Default: (blank password)

    • host - string - Hostname or IP address of the MySQL/MariaDB server. Default: "localhost"

    • port - integer - Port number of the MySQL/MariaDB server. Default: 3306

    • unixSocket - string - Path to a unix socket to connect to (host and port are ignored). Default: (none)

    • protocol - string - Explicit connection method. Can be one of: 'tcp', 'socket', 'pipe', 'memory'. Any other value uses the default behavior. Default: 'tcp' if host or port are specified, 'socket' if unixSocket is specified, otherwise default behavior is used.

    • db - string - A database to automatically select after authentication. Default: (no db)

    • keepQueries - boolean - Keep enqueued queries that haven't started executing, after the connection closes? (Only relevant if reusing Client instance) Default: false

    • multiStatements - boolean - Allow multiple statements to be executed in a single "query" (e.g. connection.query('SELECT 1; SELECT 2; SELECT 3')) on this connection. Default: false

    • connTimeout - integer - Number of seconds to wait for a connection to be made. Default: 10

    • pingInterval - integer - Number of seconds between pings while idle. Default: 60

    • secureAuth - boolean - Use password hashing available in MySQL 4.1.1+ when authenticating. Default: true

    • compress - boolean - Use connection compression? Default: false

    • ssl - mixed - If boolean true, defaults listed below and default ciphers will be used, otherwise it must be an object with any of the following valid properties: Default: false

      • key - string - Path to a client private key file in PEM format (if the key requires a passphrase and libmysqlclient was built with yaSSL (bundled Windows libraries are), an error will occur). Default: (none)

      • cert - string - Path to a client certificate key file in PEM format. Default: (none)

      • ca - string - Path to a file in PEM format that contains a list of trusted certificate authorities. Default: (none)

      • capath - string - Path to a directory containing certificate authority certificate files in PEM format. Default: (none)

      • cipher - string - A colon-delimited list of ciphers to use when connecting. Default: "ECDHE-RSA-AES128-SHA256:AES128-GCM-SHA256:RC4:HIGH:!MD5:!aNULL:!EDH" (if cipher is set to anything other than false or non-empty string)

      • rejectUnauthorized - boolean - If true, the connection will be rejected if the Common Name value does not match that of the host name. Default: false

    • local_infile - boolean - If true, will set "local-infile" for the client. Default: (none)

      NOTE: the server needs to have its own local-infile = 1 under the [mysql] and/or [mysqld] sections of my.cnf

    • read_default_file - string - Provide a path to the my.cnf configuration file to be used by the client. Sets MYSQL_READ_DEFAULT_FILE option in the C client. Default: (none)

      FROM MAN PAGE: These options can be used to read a config file like /etc/my.cnf or ~/.my.cnf. By default MySQL's C client library doesn't use any config files unlike the client programs (mysql, mysqladmin, ...) that do, but outside of the C client library. Thus you need to explicitly request reading a config file...

    • read_default_group - string - Provide the name of the group to be read in the my.cnf configuration file without the square brackets e.g. "client" for section [client] in my.cnf. If not set but "read_default_file" is set, the client tries to read from these groups: [client] or [client-server] or [client-mariadb]. Sets MYSQL_READ_DEFAULT_GROUP option in the C client. Default: (none)

    • charset - string - The connection's charset.

    • streamHWM - integer - A global highWaterMark to use for all result set streams for this connection. This value can also be supplied/overriden on a per-query basis.

  • query(< string >query[, < mixed >values[, < object >options]][, < function >callback]) - mixed - Enqueues the given query and returns a Results object. values can be an object or array containing values to be used when replacing placeholders in query (see prepare()). If supplying options without values, you must pass null for values. If callback is supplied, all rows are buffered in memory and callback receives (err, rows) (rows also contains an info object containing information about the result set, including metadata if requested). Valid options:

    • useArray - boolean - When true, arrays are used to store row values instead of an object keyed on column names. (Note: using arrays performs much faster)

    • metadata - boolean - When true, column metadata is also retrieved and available for each result set.

    • hwm - integer - This is the highWaterMark of result set streams. If you supply a callback, this option has no effect.

  • prepare(< string >query) - function - Generates a re-usable function for query when it contains placeholders (can be simple ? position-based or named :foo_bar1 placeholders or any combination of the two). In the case that the function does contain placeholders, the generated function is cached per-connection if it is not already in the cache (currently the cache will hold at most 30 prepared queries). The returned function takes an object or array and returns the query with the placeholders replaced by the values in the object or array. Note: Every value is converted to a (utf8) string when filling the placeholders.

  • escape(< string >value) - string - Escapes value for use in queries. This method requires a live connection.

  • isMariaDB() - boolean - Returns true if the remote server is MariaDB.

  • abort([< boolean >killConn][, < function >callback]) - (void) - If killConn === true, then the current connection is killed (via a KILL xxxx query on a separate, temporary connection). Otherwise, just the currently running query is killed (via a KILL QUERY xxxx query on a separate, temporary connection). When killing just the currently running query, this method will have no effect if the query has already finished but is merely in the process of transferring results from the server to the client.

  • lastInsertId() - string - Returns the last inserted auto-increment id. If you insert multiple rows in a single query, then this value will return the auto-increment id of the first row, not the last.

  • serverVersion() - string - Returns a string containing the server version.

  • end() - (void) - Closes the connection once all queries in the queue have been executed.

  • destroy() - (void) - Closes the connection immediately, even if there are other queries still in the queue.

Client static properties

  • Column flags (in metadata):

    • Client.NOT_NULL_FLAG: Field cannot be NULL
    • Client.PRI_KEY_FLAG: Field is part of a primary key
    • Client.UNIQUE_KEY_FLAG: Field is part of a unique key
    • Client.MULTIPLE_KEY_FLAG: Field is part of a nonunique key
    • Client.BLOB_FLAG: Field is a BLOB or TEXT (deprecated)
    • Client.UNSIGNED_FLAG: Field has the UNSIGNED attribute
    • Client.ZEROFILL_FLAG: Field has the ZEROFILL attribute
    • Client.BINARY_FLAG: Field has the BINARY attribute
    • Client.ENUM_FLAG: Field is an ENUM
    • Client.AUTO_INCREMENT_FLAG: Field has the AUTO_INCREMENT attribute
    • Client.TIMESTAMP_FLAG: Field is a TIMESTAMP (deprecated)
    • Client.SET_FLAG: Field is a SET
    • Client.NO_DEFAULT_VALUE_FLAG: Field has no default value
    • Client.ON_UPDATE_NOW_FLAG: Field is set to NOW on UPDATE
    • Client.PART_KEY_FLAG: Field is part of some key
    • Client.NUM_FLAG: Field is numeric

Client static methods

  • escape(< string >value) - string - Escapes value for use in queries. This method does not take into account character encodings.

  • version() - string - Returns a string containing the libmariadbclient version number.

Results events

  • result(< ResultSetStream >res) - res represents a single result set.

  • error(< Error >err) - An error occurred while processing this set of results (the 'end' event will not be emitted).

  • end() - All queries in this result set finished successfully.

ResultSetStream is a standard streams2+ Readable object stream. Some things to note:

  • ResultSetStream instances have an info property that contains result set-specific information, such as metadata, row count, number of affected rows, and last insert id. These values are populated and available at the end event.

More Repositories

1

ssh2

SSH2 client and server modules written in pure JavaScript for node.js
JavaScript
5,493
star
2

busboy

A streaming parser for HTML form data for node.js
JavaScript
2,825
star
3

node-imap

An IMAP client module for node.js.
JavaScript
2,149
star
4

node-ftp

An FTP client module for node.js
JavaScript
1,128
star
5

mmmagic

An async libmagic binding for node.js for detecting content types by data inspection
C++
617
star
6

socksv5

SOCKS protocol version 5 server and client implementations for node.js
JavaScript
400
star
7

node-ncurses

An ncurses binding for node.js
C++
385
star
8

cap

A cross-platform binding for performing packet capturing with node.js
JavaScript
360
star
9

ssh2-streams

SSH2 and SFTP client/server protocol streams for node.js
JavaScript
204
star
10

node-xxhash

An xxhash binding for node.js
C++
193
star
11

sipster

A pjsip/pjsua2 binding for node.js
C++
190
star
12

dicer

A very fast streaming multipart parser for node.js
JavaScript
186
star
13

httpolyglot

Serve http and https connections over the same port with node.js
JavaScript
181
star
14

connect-busboy

Connect middleware for busboy
JavaScript
155
star
15

node-asterisk

An Asterisk module for node.js
JavaScript
96
star
16

spellcheck

An async hunspell binding for node.js
C++
82
star
17

node-nntp

An NNTP client module for node.js
JavaScript
74
star
18

streamsearch

Streaming Boyer-Moore-Horspool searching for node.js
JavaScript
69
star
19

node-rtp

An RTP module in pure JavaScript for node.js
JavaScript
59
star
20

node-oscar

An OSCAR protocol client module for node.js
JavaScript
54
star
21

cpu-features

A simple node.js binding to Google's cpu_features library for obtaining information about installed CPU(s)
C++
40
star
22

node-pcre

A pcre binding for node.js
C++
39
star
23

esqlite

An SQLite binding for node.js with built-in encryption, focused on simplicity and (async) performance
C++
36
star
24

base91.js

basE91 encoding/decoding for node.js and browsers
JavaScript
31
star
25

bellhop

A node.js module that exposes streams for doing Pubsub and RPC.
JavaScript
28
star
26

ssh-repl

SSH into your node.js process and access a REPL
JavaScript
26
star
27

groan

A PHP session file parser written in JavaScript
JavaScript
24
star
28

paclient

PulseAudio client written in pure JavaScript for node.js
JavaScript
23
star
29

pg2

A PostgreSQL driver for node.js that focuses on performance
JavaScript
21
star
30

pmq

A node.js addon for using POSIX message queues
C++
19
star
31

grappler

A minimalistic server for "comet" connections in Node.js.
JavaScript
19
star
32

reformed

A high-level form field handling and validation module for busboy
JavaScript
18
star
33

zup

A simple, fast template engine for node.js
JavaScript
15
star
34

express-optimized

A minimal, optimized version of Express
JavaScript
13
star
35

xfer

Simple binary TLV reader/writer for node.js
JavaScript
12
star
36

youknow

A realtime, multiplayer card game for node.js that supports multiple frontends
JavaScript
11
star
37

odroid-c2-minimal-debian-ubuntu

Fork of various scripts to setup a minimal debian/ubuntu installation for the odroid c2
Shell
8
star
38

print

A node.js module for communicating with printers
JavaScript
7
star
39

filebounce

A server for bouncing files from point A to point B
JavaScript
7
star
40

node-poormansmysql

MySQL driver module for node.js that executes queries using the mysql command-line client.
JavaScript
7
star
41

buffy

Access and manipulate multiple node.js Buffers as if they were one continuous Buffer
JavaScript
6
star
42

nodebench

Node.js Benchmark Results
HTML
6
star
43

xsys

A node.js binding to useful system-level functions
C++
5
star
44

speaky

A binding to the SVOX Pico engine (libttspico) for performing text-to-speech
C++
4
star
45

lrused

An LRU cache for node.js
JavaScript
4
star
46

conveyor

Feed multiple node.js streams sequentially into one stream
JavaScript
3
star
47

benchd

Benchmark JavaScript code across different node.js/io.js versions from the browser
JavaScript
3
star
48

beepjs

A BEEP protocol implementation for node.js
JavaScript
3
star
49

vermal

A VRML 1.0 push parser for node.js
JavaScript
2
star
50

datatables.sortpriorities

Display column sort orders in your Datatables table headers
JavaScript
1
star
51

build-addons

Build node.js addon binaries for releases using Github Actions
JavaScript
1
star
52

buildcheck

Build environment checking (a la autoconf) for node.js
JavaScript
1
star