Fully end to end encrypted anonymous chat program. Server only stores public key lookup for users and the encrypted messages. No credentials are transfered to the server, but kept in local browser storage. This allows 100% safe chatting. https://safechat.ch
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

67 lines
48 KiB

{
"name": "mysql",
"description": "A node.js driver for mysql. It is written in JavaScript, does not require compiling, and is 100% MIT licensed.",
"version": "2.10.0",
"license": "MIT",
"author": {
"name": "Felix Geisendörfer",
"email": "felix@debuggable.com",
"url": "http://debuggable.com/"
},
"contributors": [
{
"name": "Andrey Sidorov",
"email": "sidorares@yandex.ru"
},
{
"name": "Douglas Christopher Wilson",
"email": "doug@somethingdoug.com"
},
{
"name": "Diogo Resende",
"email": "dresende@thinkdigital.pt"
}
],
"homepage": "https://github.com/felixge/node-mysql",
"repository": {
"type": "git",
"url": "git://github.com/felixge/node-mysql"
},
"dependencies": {
"bignumber.js": "2.1.2",
"readable-stream": "~1.1.13"
},
"devDependencies": {
"eslint": "1.10.1",
"istanbul": "0.4.1",
"require-all": "2.0.0",
"rimraf": "2.2.8",
"timezone-mock": "0.0.0",
"mkdirp": "0.5.1",
"urun": "0.0.8",
"utest": "0.0.8"
},
"files": [
"lib/",
"Changes.md",
"License",
"Readme.md",
"index.js"
],
"engines": {
"node": ">= 0.6"
},
"scripts": {
"lint": "eslint lib/**/*.js index.js test/**/*.js",
"test": "node test/run.js",
"test-ci": "node test/run-cov.js lcovonly",
"test-cov": "node test/run-cov.js"
},
"readme": "# mysql\n\n[![NPM Version][npm-image]][npm-url]\n[![NPM Downloads][downloads-image]][downloads-url]\n[![Node.js Version][node-version-image]][node-version-url]\n[![Linux Build][travis-image]][travis-url]\n[![Windows Build][appveyor-image]][appveyor-url]\n[![Test Coverage][coveralls-image]][coveralls-url]\n\n## Table of Contents\n\n- [Install](#install)\n- [Introduction](#introduction)\n- [Contributors](#contributors)\n- [Sponsors](#sponsors)\n- [Community](#community)\n- [Establishing connections](#establishing-connections)\n- [Connection options](#connection-options)\n- [SSL options](#ssl-options)\n- [Terminating connections](#terminating-connections)\n- [Pooling connections](#pooling-connections)\n- [Pool options](#pool-options)\n- [Pool events](#pool-events)\n- [Closing all the connections in a pool](#closing-all-the-connections-in-a-pool)\n- [PoolCluster](#poolcluster)\n- [PoolCluster Option](#poolcluster-option)\n- [Switching users and altering connection state](#switching-users-and-altering-connection-state)\n- [Server disconnects](#server-disconnects)\n- [Performing queries](#performing-queries)\n- [Escaping query values](#escaping-query-values)\n- [Escaping query identifiers](#escaping-query-identifiers)\n- [Preparing Queries](#preparing-queries)\n- [Custom format](#custom-format)\n- [Getting the id of an inserted row](#getting-the-id-of-an-inserted-row)\n- [Getting the number of affected rows](#getting-the-number-of-affected-rows)\n- [Getting the number of changed rows](#getting-the-number-of-changed-rows)\n- [Getting the connection ID](#getting-the-connection-id)\n- [Executing queries in parallel](#executing-queries-in-parallel)\n- [Streaming query rows](#streaming-query-rows)\n- [Piping results with Streams2](#piping-results-with-streams2)\n- [Multiple statement queries](#multiple-statement-queries)\n- [Stored procedures](#stored-procedures)\n- [Joins with overlapping column names](#joins-with-overlapping-column-names)\n- [Transactions](#transactions)\n- [Timeouts](#timeouts)\n- [Error handling](#error-handling)\n- [Exception Safety](#exception-safety)\n- [Type casting](#type-casting)\n- [Connection Flags](#connection-flags)\n- [Debugging and reporting problems](#debugging-and-reporting-problems)\n- [Running tests](#running-tests)\n- [Todo](#todo)\n\n## Install\n\n```sh\n$ npm install mysql\n```\n\nFor information about the previous 0.9.x releases, visit the [v0.9 branch][].\n\nSometimes I may also ask you to install the latest version from Github to check\nif a bugfix is working. In this case, please do:\n\n```sh\n$ npm install felixge/node-mysql\n```\n\n[v0.9 branch]: https://github.com/felixge/node-mysql/tree/v0.9\n\n## Introduction\n\nThis is a node.js driver for mysql. It is written in JavaScript, does not\nrequire compiling, and is 100% MIT licensed.\n\nHere is an example on how to use it:\n\n```js\nvar mysql = require('mysql');\nvar connection = mysql.createConnection({\n host : 'localhost',\n user : 'me',\n password : 'secret',\n database : 'my_db'\n});\n\nconnection.connect();\n\nconnection.query('SELECT 1 + 1 AS solution', function(err, rows, fields) {\n if (err) throw err;\n\n console.log('The solution is: ', rows[0].solution);\n});\n\nconnection.end();\n```\n\nFrom this example, you can learn the following:\n\n* Every method you invoke on a connection is queued and executed in sequence.\n* Closing the connection is done using `end()` which makes sure all remaining\n queries are executed before sending a quit packet to the mysql server.\n\n## Contributors\n\nThanks goes to the people who have contributed code to this module, see the\n[GitHub Contributors page][].\n\n[GitHub Contributors page]: https://github.com/felixge/node-mysql/graphs/contributors\n\nAdditionally I'd like to thank the following people:\n\n* [Andrey Hristov][] (Oracle) - for helping me with protocol questions.\n* [Ulf Wendel][] (Oracle) - for helping me with protocol questions.\n\n[Ulf Wendel]: http://blog.ulf-wendel.de/\n[Andrey Hristov]: http://andrey.hristov.com/\n\n## Sponsors\n\nThe following companies have supported this project financially, allowing me to\nspend more time on it (ordered by time of contribution):\n\n* [Transloadit](http://transloadit.com) (my startup, we do file uploading &\n video encoding as a service, check it out)\n* [Joyent](http://www.joyent.com/)\n* [pinkbike.com](http://pinkbike.com/)\n* [Holiday Extras](http://www.holidayextras.co.uk/) (they are [hiring](http://join.holidayextras.co.uk/))\n* [Newscope](http://newscope.com/) (they are [hiring](http://www.newscope.com/stellenangebote))\n\nIf you are interested in sponsoring a day or more of my time, please\n[get in touch][].\n\n[get in touch]: http://felixge.de/#consulting\n\n## Community\n\nIf you'd like to discuss this module, or ask questions about it, please use one\nof the following:\n\n* **Mailing list**: https://groups.google.com/forum/#!forum/node-mysql\n* **IRC Channel**: #node.js (on freenode.net, I pay attention to any message\n including the term `mysql`)\n\n## Establishing connections\n\nThe recommended way to establish a connection is this:\n\n```js\nvar mysql = require('mysql');\nvar connection = mysql.createConnection({\n host : 'example.org',\n user : 'bob',\n password : 'secret'\n});\n\nconnection.connect(function(err) {\n if (err) {\n console.error('error connecting: ' + err.stack);\n return;\n }\n\n console.log('connected as id ' + connection.threadId);\n});\n```\n\nHowever, a connection can also be implicitly established by invoking a query:\n\n```js\nvar mysql = require('mysql');\nvar connection = mysql.createConnection(...);\n\nconnection.query('SELECT 1', function(err, rows) {\n // connected! (unless `err` is set)\n});\n```\n\nDepending on how you like to handle your errors, either method may be\nappropriate. Any type of connection error (handshake or network) is considered\na fatal error, see the [Error Handling](#error-handling) section for more\ninformation.\n\n## Connection options\n\nWhen establishing a connection, you can set the following options:\n\n* `host`: The hostname of the database you are connecting to. (Default:\n `localhost`)\n* `port`: The port number to connect to. (Default: `3306`)\n* `localAddress`: The source IP address to use for TCP connection. (Optional)\n* `socketPath`: The path to a unix domain socket to connect to. When used `host`\n and `port` are ignored.\n* `user`: The MySQL user to authenticate as.\n* `password`: The password of that MySQL user.\n* `database`: Name of the database to use for this connection (Optional).\n* `charset`: The charset for the connection. This is called \"collation\" in the SQL-level\n of MySQL (like `utf8_general_ci`). If a SQL-level charset is specified (like `utf8mb4`)\n then the default collation for that charset is used. (Default: `'UTF8_GENERAL_CI'`)\n* `timezone`: The timezone used to store local dates. (Default: `'local'`)\n* `connectTimeout`: The milliseconds before a timeout occurs during the initial connection\n to the MySQL server. (Default: `10000`)\n* `stringifyObjects`: Stringify objects instead of converting to values. See\nissue [#501](https://github.com/felixge/node-mysql/issues/501). (Default: `'false'`)\n* `insecureAuth`: Allow connecting to MySQL instances that ask for the old\n (insecure) authentication method. (Default: `false`)\n* `typeCast`: Determines if column values should be converted to native\n JavaScript types. (Default: `true`)\n* `queryFormat`: A custom query format function. See [Custom format](#custom-format).\n* `supportBigNumbers`: When dealing with big numbers (BIGINT and DECIMAL columns) in the database,\n you should enable this option (Default: `false`).\n* `bigNumberStrings`: Enabling both `supportBigNumbers` and `bigNumberStrings` forces big numbers\n (BIGINT and DECIMAL columns) to be always returned as JavaScript String objects (Default: `false`).\n Enabling `supportBigNumbers` but leaving `bigNumberStrings` disabled will return big numbers as String\n objects only when they cannot be accurately represented with [JavaScript Number objects] (http://ecma262-5.com/ELS5_HTML.htm#Section_8.5)\n (which happens when they exceed the [-2^53, +2^53] range), otherwise they will be returned as\n Number objects. This option is ignored if `supportBigNumbers` is disabled.\n* `dateStrings`: Force date types (TIMESTAMP, DATETIME, DATE) to be returned as strings rather then\n inflated into JavaScript Date objects. (Default: `false`)\n* `debug`: Prints protocol details to stdout. (Default: `false`)\n* `trace`: Generates stack traces on `Error` to include call site of library\n entrance (\"long stack traces\"). Slight performance penalty for most calls.\n (Default: `true`)\n* `multipleStatements`: Allow multiple mysql statements per query. Be careful\n with this, it could increase the scope of SQL injection attacks. (Default: `false`)\n* `flags`: List of connection flags to use other than the default ones. It is\n also possible to blacklist default ones. For more information, check\n [Connection Flags](#connection-flags).\n* `ssl`: object with ssl parameters or a string containing name of ssl profile. See [SSL options](#ssl-options).\n\n\nIn addition to passing these options as an object, you can also use a url\nstring. For example:\n\n```js\nvar connection = mysql.createConnection('mysql://user:pass@host/db?debug=true&charset=BIG5_CHINESE_CI&timezone=-0700');\n```\n\nNote: The query values are first attempted to be parsed as JSON, and if that\nfails assumed to be plaintext strings.\n\n### SSL options\n\nThe `ssl` option in the connection options takes a string or an object. When given a string,\nit uses one of the predefined SSL profiles included. The following profiles are included:\n\n* `\"Amazon RDS\"`: this profile is for connecting to an Amazon RDS server and contains the\n certificates from https://rds.amazonaws.com/doc/rds-ssl-ca-cert.pem and\n https://s3.amazonaws.com/rds-downloads/rds-combined-ca-bundle.pem\n\nWhen connecting to other servers, you will need to provide an object of options, in the\nsame format as [crypto.createCredentials](http://nodejs.org/api/crypto.html#crypto_crypto_createcredentials_details).\nPlease note the arguments expect a string of the certificate, not a file name to the\ncertificate. Here is a simple example:\n\n```js\nvar connection = mysql.createConnection({\n host : 'localhost',\n ssl : {\n ca : fs.readFileSync(__dirname + '/mysql-ca.crt')\n }\n});\n```\n\nYou can also connect to a MySQL server without properly providing the appropriate\nCA to trust. _You should not do this_.\n\n```js\nvar connection = mysql.createConnection({\n host : 'localhost',\n ssl : {\n // DO NOT DO THIS\n // set up your ca correctly to trust the connection\n rejectUnauthorized: false\n }\n});\n```\n\n## Terminating connections\n\nThere are two ways to end a connection. Terminating a connection gracefully is\ndone by calling the `end()` method:\n\n```js\nconnection.end(function(err) {\n // The connection is terminated now\n});\n```\n\nThis will make sure all previously enqueued queries are still before sending a\n`COM_QUIT` packet to the MySQL server. If a fatal error occurs before the\n`COM_QUIT` packet can be sent, an `err` argument will be provided to the\ncallback, but the connection will be terminated regardless of that.\n\nAn alternative way to end the connection is to call the `destroy()` method.\nThis will cause an immediate termination of the underlying socket.\nAdditionally `destroy()` guarantees that no more events or callbacks will be\ntriggered for the connection.\n\n```js\nconnection.destroy();\n```\n\nUnlike `end()` the `destroy()` method does not take a callback argument.\n\n## Pooling connections\n\nUse pool directly.\n```js\nvar mysql = require('mysql');\nvar pool = mysql.createPool({\n connectionLimit : 10,\n host : 'example.org',\n user : 'bob',\n password : 'secret'\n});\n\npool.query('SELECT 1 + 1 AS solution', function(err, rows, fields) {\n if (err) throw err;\n\n console.log('The solution is: ', rows[0].solution);\n});\n```\n\nConnections can be pooled to ease sharing a single connection, or managing\nmultiple connections.\n\n```js\nvar mysql = require('mysql');\nvar pool = mysql.createPool({\n host : 'example.org',\n user : 'bob',\n password : 'secret'\n});\n\npool.getConnection(function(err, connection) {\n // connected! (unless `err` is set)\n});\n```\n\nWhen you are done with a connection, just call `connection.release()` and the\nconnection will return to the pool, ready to be used again by someone else.\n\n```js\nvar mysql = require('mysql');\nvar pool = mysql.createPool(...);\n\npool.getConnection(function(err, connection) {\n // Use the connection\n connection.query( 'SELECT something FROM sometable', function(err, rows) {\n // And done with the connection.\n connection.release();\n\n // Don't use the connection here, it has been returned to the pool.\n });\n});\n```\n\nIf you would like to close the connection and remove it from the pool, use\n`connection.destroy()` instead. The pool will create a new connection the next\ntime one is needed.\n\nConnections are lazily created by the pool. If you configure the pool to allow\nup to 100 connections, but only ever use 5 simultaneously, only 5 connections\nwill be made. Connections are also cycled round-robin style, with connections\nbeing taken from the top of the pool and returning to the bottom.\n\nWhen a previous connection is retrieved from the pool, a ping packet is sent\nto the server to check if the connection is still good.\n\n## Pool options\n\nPools accept all the same options as a connection. When creating a new\nconnection, the options are simply passed to the connection constructor. In\naddition to those options pools accept a few extras:\n\n* `acquireTimeout`: The milliseconds before a timeout occurs during the connection\n acquisition. This is slightly different from `connectTimeout`, because acquiring\n a pool connection does not always involve making a connection. (Default: `10000`)\n* `waitForConnections`: Determines the pool's action when no connections are\n available and the limit has been reached. If `true`, the pool will queue the\n connection request and call it when one becomes available. If `false`, the\n pool will immediately call back with an error. (Default: `true`)\n* `connectionLimit`: The maximum number of connections to create at once.\n (Default: `10`)\n* `queueLimit`: The maximum number of connection requests the pool will queue\n before returning an error from `getConnection`. If set to `0`, there is no\n limit to the number of queued connection requests. (Default: `0`)\n\n## Pool events\n\n### connection\n\nThe pool will emit a `connection` event when a new connection is made within the pool. \nIf you need to set session variables on the connection before it gets used, you can\nlisten to the `connection` event.\n\n```js\npool.on('connection', function (connection) {\n connection.query('SET SESSION auto_increment_increment=1')\n});\n```\n\n### enqueue\n\nThe pool will emit an `enqueue` event when a callback has been queued to wait for\nan available connection.\n\n```js\npool.on('enqueue', function () {\n console.log('Waiting for available connection slot');\n});\n```\n\n## Closing all the connections in a pool\n\nWhen you are done using the pool, you have to end all the connections or the\nNode.js event loop will stay active until the connections are closed by the\nMySQL server. This is typically done if the pool is used in a script or when\ntrying to gracefully shutdown a server. To end all the connections in the\npool, use the `end` method on the pool:\n\n```js\npool.end(function (err) {\n // all connections in the pool have ended\n});\n```\n\nThe `end` method takes an _optional_ callback that you can use to know once\nall the connections have ended. The connections end _gracefully_, so all\npending queries will still complete and the time to end the pool will vary.\n\n**Once `pool.end()` has been called, `pool.getConnection` and other operations\ncan no longer be performed**\n\n## PoolCluster\n\nPoolCluster provides multiple hosts connection. (group & retry & selector)\n\n```js\n// create\nvar poolCluster = mysql.createPoolCluster();\n\n// add configurations\npoolCluster.add(config); // anonymous group\npoolCluster.add('MASTER', masterConfig);\npoolCluster.add('SLAVE1', slave1Config);\npoolCluster.add('SLAVE2', slave2Config);\n\n// remove configurations\npoolCluster.remove('SLAVE2'); // By nodeId\npoolCluster.remove('SLAVE*'); // By target group : SLAVE1-2\n\n// Target Group : ALL(anonymous, MASTER, SLAVE1-2), Selector : round-robin(default)\npoolCluster.getConnection(function (err, connection) {});\n\n// Target Group : MASTER, Selector : round-robin\npoolCluster.getConnection('MASTER', function (err, connection) {});\n\n// Target Group : SLAVE1-2, Selector : order\n// If can't connect to SLAVE1, return SLAVE2. (remove SLAVE1 in the cluster)\npoolCluster.on('remove', function (nodeId) {\n console.log('REMOVED NODE : ' + nodeId); // nodeId = SLAVE1 \n});\n\npoolCluster.getConnection('SLAVE*', 'ORDER', function (err, connection) {});\n\n// of namespace : of(pattern, selector)\npoolCluster.of('*').getConnection(function (err, connection) {});\n\nvar pool = poolCluster.of('SLAVE*', 'RANDOM');\npool.getConnection(function (err, connection) {});\npool.getConnection(function (err, connection) {});\n\n// close all connections\npoolCluster.end(function (err) {\n // all connections in the pool cluster have ended\n});\n```\n\n## PoolCluster Option\n* `canRetry`: If `true`, `PoolCluster` will attempt to reconnect when connection fails. (Default: `true`)\n* `removeNodeErrorCount`: If connection fails, node's `errorCount` increases. \n When `errorCount` is greater than `removeNodeErrorCount`, remove a node in the `PoolCluster`. (Default: `5`)\n* `restoreNodeTimeout`: If connection fails, specifies the number of milliseconds\n before another connection attempt will be made. If set to `0`, then node will be\n removed instead and never re-used. (Default: `0`)\n* `defaultSelector`: The default selector. (Default: `RR`)\n * `RR`: Select one alternately. (Round-Robin)\n * `RANDOM`: Select the node by random function.\n * `ORDER`: Select the first node available unconditionally.\n\n```js\nvar clusterConfig = {\n removeNodeErrorCount: 1, // Remove the node immediately when connection fails.\n defaultSelector: 'ORDER'\n};\n\nvar poolCluster = mysql.createPoolCluster(clusterConfig);\n```\n\n## Switching users and altering connection state\n\nMySQL offers a changeUser command that allows you to alter the current user and\nother aspects of the connection without shutting down the underlying socket:\n\n```js\nconnection.changeUser({user : 'john'}, function(err) {\n if (err) throw err;\n});\n```\n\nThe available options for this feature are:\n\n* `user`: The name of the new user (defaults to the previous one).\n* `password`: The password of the new user (defaults to the previous one).\n* `charset`: The new charset (defaults to the previous one).\n* `database`: The new database (defaults to the previous one).\n\nA sometimes useful side effect of this functionality is that this function also\nresets any connection state (variables, transactions, etc.).\n\nErrors encountered during this operation are treated as fatal connection errors\nby this module.\n\n## Server disconnects\n\nYou may lose the connection to a MySQL server due to network problems, the\nserver timing you out, the server being restarted, or crashing. All of these\nevents are considered fatal errors, and will have the `err.code =\n'PROTOCOL_CONNECTION_LOST'`. See the [Error Handling](#error-handling) section\nfor more information.\n\nRe-connecting a connection is done by establishing a new connection. Once\nterminated, an existing connection object cannot be re-connected by design.\n\nWith Pool, disconnected connections will be removed from the pool freeing up\nspace for a new connection to be created on the next getConnection call.\n\n## Performing queries\n\nThe most basic way to perform a query is to call the `.query()` method on an object\n(like a `Connection` or `Pool` instance).\n\nThe simplest form of .`query()` is `.query(sqlString, callback)`, where a SQL string\nis the first argument and the second is a callback:\n\n```js\nconnection.query('SELECT * FROM `books` WHERE `author` = \"David\"', function (error, results, fields) {\n // error will be an Error if one occurred during the query\n // results will contain the results of the query\n // fields will contain information about the returned results fields (if any)\n});\n```\n\nThe second form `.query(sqlString, values, callback)` comes when using\nplaceholder values (see [escaping query values](#escaping-query-values)):\n\n```js\nconnection.query('SELECT * FROM `books` WHERE `author` = ?', ['David'], function (error, results, fields) {\n // error will be an Error if one occurred during the query\n // results will contain the results of the query\n // fields will contain information about the returned results fields (if any)\n});\n```\n\nThe third form `.query(options, callback)` comes when using various advanced\noptions on the query, like [escaping query values](#escaping-query-values),\n[joins with overlapping column names](#joins-with-overlapping-column-names),\n[timeouts](#timeout), and [type casting](#type-casting).\n\n```js\nconnection.query({\n sql: 'SELECT * FROM `books` WHERE `author` = ?',\n timeout: 40000, // 40s\n values: ['David']\n}, function (error, results, fields) {\n // error will be an Error if one occurred during the query\n // results will contain the results of the query\n // fields will contain information about the returned results fields (if any)\n});\n```\n\nNote that a combination of the second and third forms can be used where the\nplaceholder values are passes as an argument and not in the options object.\nThe `values` argument will override the `values` in the option object.\n\n```js\nconnection.query({\n sql: 'SELECT * FROM `books` WHERE `author` = ?',\n timeout: 40000, // 40s\n },\n ['David'],\n function (error, results, fields) {\n // error will be an Error if one occurred during the query\n // results will contain the results of the query\n // fields will contain information about the returned results fields (if any)\n }\n);\n```\n\n## Escaping query values\n\nIn order to avoid SQL Injection attacks, you should always escape any user\nprovided data before using it inside a SQL query. You can do so using the\n`mysql.escape()`, `connection.escape()` or `pool.escape()` methods:\n\n```js\nvar userId = 'some user provided value';\nvar sql = 'SELECT * FROM users WHERE id = ' + connection.escape(userId);\nconnection.query(sql, function(err, results) {\n // ...\n});\n```\n\nAlternatively, you can use `?` characters as placeholders for values you would\nlike to have escaped like this:\n\n```js\nconnection.query('SELECT * FROM users WHERE id = ?', [userId], function(err, results) {\n // ...\n});\n```\n\nThis looks similar to prepared statements in MySQL, however it really just uses\nthe same `connection.escape()` method internally.\n\n**Caution** This also differs from prepared statements in that all `?` are\nreplaced, even those contained in comments and strings.\n\nDifferent value types are escaped differently, here is how:\n\n* Numbers are left untouched\n* Booleans are converted to `true` / `false`\n* Date objects are converted to `'YYYY-mm-dd HH:ii:ss'` strings\n* Buffers are converted to hex strings, e.g. `X'0fa5'`\n* Strings are safely escaped\n* Arrays are turned into list, e.g. `['a', 'b']` turns into `'a', 'b'`\n* Nested arrays are turned into grouped lists (for bulk inserts), e.g. `[['a',\n 'b'], ['c', 'd']]` turns into `('a', 'b'), ('c', 'd')`\n* Objects are turned into `key = 'val'` pairs for each enumerable property on\n the object. If the property's value is a function, it is skipped; if the\n property's value is an object, toString() is called on it and the returned\n value is used.\n* `undefined` / `null` are converted to `NULL`\n* `NaN` / `Infinity` are left as-is. MySQL does not support these, and trying\n to insert them as values will trigger MySQL errors until they implement\n support.\n\nIf you paid attention, you may have noticed that this escaping allows you\nto do neat things like this:\n\n```js\nvar post = {id: 1, title: 'Hello MySQL'};\nvar query = connection.query('INSERT INTO posts SET ?', post, function(err, result) {\n // Neat!\n});\nconsole.log(query.sql); // INSERT INTO posts SET `id` = 1, `title` = 'Hello MySQL'\n\n```\n\nIf you feel the need to escape queries by yourself, you can also use the escaping\nfunction directly:\n\n```js\nvar query = \"SELECT * FROM posts WHERE title=\" + mysql.escape(\"Hello MySQL\");\n\nconsole.log(query); // SELECT * FROM posts WHERE title='Hello MySQL'\n```\n\n## Escaping query identifiers\n\nIf you can't trust an SQL identifier (database / table / column name) because it is\nprovided by a user, you should escape it with `mysql.escapeId(identifier)`,\n`connection.escapeId(identifier)` or `pool.escapeId(identifier)` like this:\n\n```js\nvar sorter = 'date';\nvar sql = 'SELECT * FROM posts ORDER BY ' + connection.escapeId(sorter);\nconnection.query(sql, function(err, results) {\n // ...\n});\n```\n\nIt also supports adding qualified identifiers. It will escape both parts.\n\n```js\nvar sorter = 'date';\nvar sql = 'SELECT * FROM posts ORDER BY ' + connection.escapeId('posts.' + sorter);\nconnection.query(sql, function(err, results) {\n // ...\n});\n```\n\nAlternatively, you can use `??` characters as placeholders for identifiers you would\nlike to have escaped like this:\n\n```js\nvar userId = 1;\nvar columns = ['username', 'email'];\nvar query = connection.query('SELECT ?? FROM ?? WHERE id = ?', [columns, 'users', userId], function(err, results) {\n // ...\n});\n\nconsole.log(query.sql); // SELECT `username`, `email` FROM `users` WHERE id = 1\n```\n**Please note that this last character sequence is experimental and syntax might change**\n\nWhen you pass an Object to `.escape()` or `.query()`, `.escapeId()` is used to avoid SQL injection in object keys.\n\n### Preparing Queries\n\nYou can use mysql.format to prepare a query with multiple insertion points, utilizing the proper escaping for ids and values. A simple example of this follows:\n\n```js\nvar sql = \"SELECT * FROM ?? WHERE ?? = ?\";\nvar inserts = ['users', 'id', userId];\nsql = mysql.format(sql, inserts);\n```\n\nFollowing this you then have a valid, escaped query that you can then send to the database safely. This is useful if you are looking to prepare the query before actually sending it to the database. As mysql.format is exposed from SqlString.format you also have the option (but are not required) to pass in stringifyObject and timezone, allowing you provide a custom means of turning objects into strings, as well as a location-specific/timezone-aware Date.\n\n### Custom format\n\nIf you prefer to have another type of query escape format, there's a connection configuration option you can use to define a custom format function. You can access the connection object if you want to use the built-in `.escape()` or any other connection function.\n\nHere's an example of how to implement another format:\n\n```js\nconnection.config.queryFormat = function (query, values) {\n if (!values) return query;\n return query.replace(/\\:(\\w+)/g, function (txt, key) {\n if (values.hasOwnProperty(key)) {\n return this.escape(values[key]);\n }\n return txt;\n }.bind(this));\n};\n\nconnection.query(\"UPDATE posts SET title = :title\", { title: \"Hello MySQL\" });\n```\n\n## Getting the id of an inserted row\n\nIf you are inserting a row into a table with an auto increment primary key, you\ncan retrieve the insert id like this:\n\n```js\nconnection.query('INSERT INTO posts SET ?', {title: 'test'}, function(err, result) {\n if (err) throw err;\n\n console.log(result.insertId);\n});\n```\n\nWhen dealing with big numbers (above JavaScript Number precision limit), you should\nconsider enabling `supportBigNumbers` option to be able to read the insert id as a\nstring, otherwise it will throw.\n\nThis option is also required when fetching big numbers from the database, otherwise\nyou will get values rounded to hundreds or thousands due to the precision limit.\n\n## Getting the number of affected rows\n\nYou can get the number of affected rows from an insert, update or delete statement.\n\n```js\nconnection.query('DELETE FROM posts WHERE title = \"wrong\"', function (err, result) {\n if (err) throw err;\n\n console.log('deleted ' + result.affectedRows + ' rows');\n})\n```\n\n## Getting the number of changed rows\n\nYou can get the number of changed rows from an update statement.\n\n\"changedRows\" differs from \"affectedRows\" in that it does not count updated rows\nwhose values were not changed.\n\n```js\nconnection.query('UPDATE posts SET ...', function (err, result) {\n if (err) throw err;\n\n console.log('changed ' + result.changedRows + ' rows');\n})\n```\n\n## Getting the connection ID\n\nYou can get the MySQL connection ID (\"thread ID\") of a given connection using the `threadId`\nproperty.\n\n```js\nconnection.connect(function(err) {\n if (err) throw err;\n console.log('connected as id ' + connection.threadId);\n});\n```\n\n## Executing queries in parallel\n\nThe MySQL protocol is sequential, this means that you need multiple connections\nto execute queries in parallel. You can use a Pool to manage connections, one\nsimple approach is to create one connection per incoming http request.\n\n## Streaming query rows\n\nSometimes you may want to select large quantities of rows and process each of\nthem as they are received. This can be done like this:\n\n```js\nvar query = connection.query('SELECT * FROM posts');\nquery\n .on('error', function(err) {\n // Handle error, an 'end' event will be emitted after this as well\n })\n .on('fields', function(fields) {\n // the field packets for the rows to follow\n })\n .on('result', function(row) {\n // Pausing the connnection is useful if your processing involves I/O\n connection.pause();\n\n processRow(row, function() {\n connection.resume();\n });\n })\n .on('end', function() {\n // all rows have been received\n });\n```\n\nPlease note a few things about the example above:\n\n* Usually you will want to receive a certain amount of rows before starting to\n throttle the connection using `pause()`. This number will depend on the\n amount and size of your rows.\n* `pause()` / `resume()` operate on the underlying socket and parser. You are\n guaranteed that no more `'result'` events will fire after calling `pause()`.\n* You MUST NOT provide a callback to the `query()` method when streaming rows.\n* The `'result'` event will fire for both rows as well as OK packets\n confirming the success of a INSERT/UPDATE query.\n* It is very important not to leave the result paused too long, or you may\n encounter `Error: Connection lost: The server closed the connection.`\n The time limit for this is determined by the\n [net_write_timeout setting](https://dev.mysql.com/doc/refman/5.5/en/server-system-variables.html#sysvar_net_write_timeout)\n on your MySQL server.\n\nAdditionally you may be interested to know that it is currently not possible to\nstream individual row columns, they will always be buffered up entirely. If you\nhave a good use case for streaming large fields to and from MySQL, I'd love to\nget your thoughts and contributions on this.\n\n### Piping results with Streams2\n\nThe query object provides a convenience method `.stream([options])` that wraps\nquery events into a [Readable](http://nodejs.org/api/stream.html#stream_class_stream_readable)\n[Streams2](http://blog.nodejs.org/2012/12/20/streams2/) object. This\nstream can easily be piped downstream and provides automatic pause/resume,\nbased on downstream congestion and the optional `highWaterMark`. The\n`objectMode` parameter of the stream is set to `true` and cannot be changed\n(if you need a byte stream, you will need to use a transform stream, like\n[objstream](https://www.npmjs.com/package/objstream) for example).\n\nFor example, piping query results into another stream (with a max buffer of 5\nobjects) is simply:\n\n```js\nconnection.query('SELECT * FROM posts')\n .stream({highWaterMark: 5})\n .pipe(...);\n```\n\n## Multiple statement queries\n\nSupport for multiple statements is disabled for security reasons (it allows for\nSQL injection attacks if values are not properly escaped). To use this feature\nyou have to enable it for your connection:\n\n```js\nvar connection = mysql.createConnection({multipleStatements: true});\n```\n\nOnce enabled, you can execute multiple statement queries like any other query:\n\n```js\nconnection.query('SELECT 1; SELECT 2', function(err, results) {\n if (err) throw err;\n\n // `results` is an array with one element for every statement in the query:\n console.log(results[0]); // [{1: 1}]\n console.log(results[1]); // [{2: 2}]\n});\n```\n\nAdditionally you can also stream the results of multiple statement queries:\n\n```js\nvar query = connection.query('SELECT 1; SELECT 2');\n\nquery\n .on('fields', function(fields, index) {\n // the fields for the result rows that follow\n })\n .on('result', function(row, index) {\n // index refers to the statement this result belongs to (starts at 0)\n });\n```\n\nIf one of the statements in your query causes an error, the resulting Error\nobject contains a `err.index` property which tells you which statement caused\nit. MySQL will also stop executing any remaining statements when an error\noccurs.\n\nPlease note that the interface for streaming multiple statement queries is\nexperimental and I am looking forward to feedback on it.\n\n## Stored procedures\n\nYou can call stored procedures from your queries as with any other mysql driver.\nIf the stored procedure produces several result sets, they are exposed to you\nthe same way as the results for multiple statement queries.\n\n## Joins with overlapping column names\n\nWhen executing joins, you are likely to get result sets with overlapping column\nnames.\n\nBy default, node-mysql will overwrite colliding column names in the\norder the columns are received from MySQL, causing some of the received values\nto be unavailable.\n\nHowever, you can also specify that you want your columns to be nested below\nthe table name like this:\n\n```js\nvar options = {sql: '...', nestTables: true};\nconnection.query(options, function(err, results) {\n /* results will be an array like this now:\n [{\n table1: {\n fieldA: '...',\n fieldB: '...',\n },\n table2: {\n fieldA: '...',\n fieldB: '...',\n },\n }, ...]\n */\n});\n```\n\nOr use a string separator to have your results merged.\n\n```js\nvar options = {sql: '...', nestTables: '_'};\nconnection.query(options, function(err, results) {\n /* results will be an array like this now:\n [{\n table1_fieldA: '...',\n table1_fieldB: '...',\n table2_fieldA: '...',\n table2_fieldB: '...',\n }, ...]\n */\n});\n```\n\n## Transactions\n\nSimple transaction support is available at the connection level:\n\n```js\nconnection.beginTransaction(function(err) {\n if (err) { throw err; }\n connection.query('INSERT INTO posts SET title=?', title, function(err, result) {\n if (err) {\n return connection.rollback(function() {\n throw err;\n });\n }\n\n var log = 'Post ' + result.insertId + ' added';\n\n connection.query('INSERT INTO log SET data=?', log, function(err, result) {\n if (err) {\n return connection.rollback(function() {\n throw err;\n });\n } \n connection.commit(function(err) {\n if (err) {\n return connection.rollback(function() {\n throw err;\n });\n }\n console.log('success!');\n });\n });\n });\n});\n```\nPlease note that beginTransaction(), commit() and rollback() are simply convenience\nfunctions that execute the START TRANSACTION, COMMIT, and ROLLBACK commands respectively.\nIt is important to understand that many commands in MySQL can cause an implicit commit,\nas described [in the MySQL documentation](http://dev.mysql.com/doc/refman/5.5/en/implicit-commit.html)\n\n## Ping\n\nA ping packet can be sent over a connection using the `connection.ping` method. This\nmethod will send a ping packet to the server and when the server responds, the callback\nwill fire. If an error occurred, the callback will fire with an error argument.\n\n```js\nconnection.ping(function (err) {\n if (err) throw err;\n console.log('Server responded to ping');\n})\n```\n\n## Timeouts\n\nEvery operation takes an optional inactivity timeout option. This allows you to\nspecify appropriate timeouts for operations. It is important to note that these\ntimeouts are not part of the MySQL protocol, and rather timeout operations through\nthe client. This means that when a timeout is reached, the connection it occurred\non will be destroyed and no further operations can be performed.\n\n```js\n// Kill query after 60s\nconnection.query({sql: 'SELECT COUNT(*) AS count FROM big_table', timeout: 60000}, function (err, rows) {\n if (err && err.code === 'PROTOCOL_SEQUENCE_TIMEOUT') {\n throw new Error('too long to count table rows!');\n }\n\n if (err) {\n throw err;\n }\n\n console.log(rows[0].count + ' rows');\n});\n```\n\n## Error handling\n\nThis module comes with a consistent approach to error handling that you should\nreview carefully in order to write solid applications.\n\nAll errors created by this module are instances of the JavaScript [Error][]\nobject. Additionally they come with two properties:\n\n* `err.code`: Either a [MySQL server error][] (e.g.\n `'ER_ACCESS_DENIED_ERROR'`), a node.js error (e.g. `'ECONNREFUSED'`) or an\n internal error (e.g. `'PROTOCOL_CONNECTION_LOST'`).\n* `err.fatal`: Boolean, indicating if this error is terminal to the connection\n object.\n\n[Error]: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error\n[MySQL server error]: http://dev.mysql.com/doc/refman/5.5/en/error-messages-server.html\n\nFatal errors are propagated to *all* pending callbacks. In the example below, a\nfatal error is triggered by trying to connect to an invalid port. Therefore the\nerror object is propagated to both pending callbacks:\n\n```js\nvar connection = require('mysql').createConnection({\n port: 84943, // WRONG PORT\n});\n\nconnection.connect(function(err) {\n console.log(err.code); // 'ECONNREFUSED'\n console.log(err.fatal); // true\n});\n\nconnection.query('SELECT 1', function(err) {\n console.log(err.code); // 'ECONNREFUSED'\n console.log(err.fatal); // true\n});\n```\n\nNormal errors however are only delegated to the callback they belong to. So in\nthe example below, only the first callback receives an error, the second query\nworks as expected:\n\n```js\nconnection.query('USE name_of_db_that_does_not_exist', function(err, rows) {\n console.log(err.code); // 'ER_BAD_DB_ERROR'\n});\n\nconnection.query('SELECT 1', function(err, rows) {\n console.log(err); // null\n console.log(rows.length); // 1\n});\n```\n\nLast but not least: If a fatal errors occurs and there are no pending\ncallbacks, or a normal error occurs which has no callback belonging to it, the\nerror is emitted as an `'error'` event on the connection object. This is\ndemonstrated in the example below:\n\n```js\nconnection.on('error', function(err) {\n console.log(err.code); // 'ER_BAD_DB_ERROR'\n});\n\nconnection.query('USE name_of_db_that_does_not_exist');\n```\n\nNote: `'error'` events are special in node. If they occur without an attached\nlistener, a stack trace is printed and your process is killed.\n\n**tl;dr:** This module does not want you to deal with silent failures. You\nshould always provide callbacks to your method calls. If you want to ignore\nthis advice and suppress unhandled errors, you can do this:\n\n```js\n// I am Chuck Norris:\nconnection.on('error', function() {});\n```\n\n## Exception Safety\n\nThis module is exception safe. That means you can continue to use it, even if\none of your callback functions throws an error which you're catching using\n'uncaughtException' or a domain.\n\n## Type casting\n\nFor your convenience, this driver will cast mysql types into native JavaScript\ntypes by default. The following mappings exist:\n\n### Number\n\n* TINYINT\n* SMALLINT\n* INT\n* MEDIUMINT\n* YEAR\n* FLOAT\n* DOUBLE\n\n### Date\n\n* TIMESTAMP\n* DATE\n* DATETIME\n\n### Buffer\n\n* TINYBLOB\n* MEDIUMBLOB\n* LONGBLOB\n* BLOB\n* BINARY\n* VARBINARY\n* BIT (last byte will be filled with 0 bits as necessary)\n\n### String\n\n**Note** text in the binary character set is returned as `Buffer`, rather\nthan a string.\n\n* CHAR\n* VARCHAR\n* TINYTEXT\n* MEDIUMTEXT\n* LONGTEXT\n* TEXT\n* ENUM\n* SET\n* DECIMAL (may exceed float precision)\n* BIGINT (may exceed float precision)\n* TIME (could be mapped to Date, but what date would be set?)\n* GEOMETRY (never used those, get in touch if you do)\n\nIt is not recommended (and may go away / change in the future) to disable type\ncasting, but you can currently do so on either the connection:\n\n```js\nvar connection = require('mysql').createConnection({typeCast: false});\n```\n\nOr on the query level:\n\n```js\nvar options = {sql: '...', typeCast: false};\nvar query = connection.query(options, function(err, results) {\n\n});\n```\n\nYou can also pass a function and handle type casting yourself. You're given some\ncolumn information like database, table and name and also type and length. If you\njust want to apply a custom type casting to a specific type you can do it and then\nfallback to the default. Here's an example of converting `TINYINT(1)` to boolean:\n\n```js\nconnection.query({\n sql: '...',\n typeCast: function (field, next) {\n if (field.type == 'TINY' && field.length == 1) {\n return (field.string() == '1'); // 1 = true, 0 = false\n }\n return next();\n }\n});\n```\n__WARNING: YOU MUST INVOKE the parser using one of these three field functions in your custom typeCast callback. They can only be called once. (see [#539](https://github.com/felixge/node-mysql/issues/539) for discussion)__\n\n```\nfield.string()\nfield.buffer()\nfield.geometry()\n```\nare aliases for\n```\nparser.parseLengthCodedString()\nparser.parseLengthCodedBuffer()\nparser.parseGeometryValue()\n```\n__You can find which field function you need to use by looking at: [RowDataPacket.prototype._typeCast](https://github.com/felixge/node-mysql/blob/master/lib/protocol/packets/RowDataPacket.js#L41)__\n\n\n## Connection Flags\n\nIf, for any reason, you would like to change the default connection flags, you\ncan use the connection option `flags`. Pass a string with a comma separated list\nof items to add to the default flags. If you don't want a default flag to be used\nprepend the flag with a minus sign. To add a flag that is not in the default list,\njust write the flag name, or prefix it with a plus (case insensitive).\n\n**Please note that some available flags that are not supported (e.g.: Compression),\nare still not allowed to be specified.**\n\n### Example\n\nThe next example blacklists FOUND_ROWS flag from default connection flags.\n\n```js\nvar connection = mysql.createConnection(\"mysql://localhost/test?flags=-FOUND_ROWS\");\n```\n\n### Default Flags\n\nThe following flags are sent by default on a new connection:\n\n- `CONNECT_WITH_DB` - Ability to specify the database on connection.\n- `FOUND_ROWS` - Send the found rows instead of the affected rows as `affectedRows`.\n- `IGNORE_SIGPIPE` - Old; no effect.\n- `IGNORE_SPACE` - Let the parser ignore spaces before the `(` in queries.\n- `LOCAL_FILES` - Can use `LOAD DATA LOCAL`.\n- `LONG_FLAG`\n- `LONG_PASSWORD` - Use the improved version of Old Password Authentication.\n- `MULTI_RESULTS` - Can handle multiple resultsets for COM_QUERY.\n- `ODBC` Old; no effect.\n- `PROTOCOL_41` - Uses the 4.1 protocol.\n- `PS_MULTI_RESULTS` - Can handle multiple resultsets for COM_STMT_EXECUTE.\n- `RESERVED` - Old flag for the 4.1 protocol.\n- `SECURE_CONNECTION` - Support native 4.1 authentication.\n- `TRANSACTIONS` - Asks for the transaction status flags.\n\nIn addition, the following flag will be sent if the option `multipleStatements`\nis set to `true`:\n\n- `MULTI_STATEMENTS` - The client may send multiple statement per query or\n statement prepare.\n\n### Other Available Flags\n\nThere are other flags available. They may or may not function, but are still\navailable to specify.\n\n- COMPRESS\n- INTERACTIVE\n- NO_SCHEMA\n- PLUGIN_AUTH\n- REMEMBER_OPTIONS\n- SSL\n- SSL_VERIFY_SERVER_CERT\n\n## Debugging and reporting problems\n\nIf you are running into problems, one thing that may help is enabling the\n`debug` mode for the connection:\n\n```js\nvar connection = mysql.createConnection({debug: true});\n```\n\nThis will print all incoming and outgoing packets on stdout. You can also restrict debugging to\npacket types by passing an array of types to debug:\n\n```js\nvar connection = mysql.createConnection({debug: ['ComQueryPacket', 'RowDataPacket']});\n```\n\nto restrict debugging to the query and data packets.\n\nIf that does not help, feel free to open a GitHub issue. A good GitHub issue\nwill have:\n\n* The minimal amount of code required to reproduce the problem (if possible)\n* As much debugging output and information about your environment (mysql\n version, node version, os, etc.) as you can gather.\n\n## Running tests\n\nThe test suite is split into two parts: unit tests and integration tests.\nThe unit tests run on any machine while the integration tests require a\nMySQL server instance to be setup.\n\n### Running unit tests\n\n```sh\n$ FILTER=unit npm test\n```\n\n### Running integration tests\n\nSet the environment variables `MYSQL_DATABASE`, `MYSQL_HOST`, `MYSQL_PORT`,\n`MYSQL_USER` and `MYSQL_PASSWORD`. Then run `npm test`.\n\nFor example, if you have an installation of mysql running on localhost:3306\nand no password set for the `root` user, run:\n\n```sh\n$ mysql -u root -e \"CREATE DATABASE IF NOT EXISTS node_mysql_test\"\n$ MYSQL_HOST=localhost MYSQL_PORT=3306 MYSQL_DATABASE=node_mysql_test MYSQL_USER=root MYSQL_PASSWORD= FILTER=integration npm test\n```\n\n## Todo\n\n* Prepared statements\n* Support for encodings other than UTF-8 / ASCII\n\n[npm-image]: https://img.shields.io/npm/v/mysql.svg\n[npm-url]: https://npmjs.org/package/mysql\n[node-version-image]: http://img.shields.io/node/v/mysql.svg\n[node-version-url]: http://nodejs.org/download/\n[travis-image]: https://img.shields.io/travis/felixge/node-mysql/master.svg?label=linux\n[travis-url]: https://travis-ci.org/felixge/node-mysql\n[appveyor-image]: https://img.shields.io/appveyor/ci/dougwilson/node-mysql/master.svg?label=windows\n[appveyor-url]: https://ci.appveyor.com/project/dougwilson/node-mysql\n[coveralls-image]: https://img.shields.io/coveralls/felixge/node-mysql/master.svg\n[coveralls-url]: https://coveralls.io/r/felixge/node-mysql?branch=master\n[downloads-image]: https://img.shields.io/npm/dm/mysql.svg\n[downloads-url]: https://npmjs.org/package/mysql\n",
"readmeFilename": "Readme.md",
"bugs": {
"url": "https://github.com/felixge/node-mysql/issues"
},
"_id": "mysql@2.10.0",
"_from": "mysql@"
}