{
  "author": {
    "name": "Felix Geisendörfer",
    "email": "felix@debuggable.com",
    "url": "http://debuggable.com/"
  },
  "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.0.0",
  "homepage": "https://github.com/felixge/node-mysql",
  "repository": {
    "type": "git",
    "url": "https://github.com/felixge/node-mysql"
  },
  "main": "./index",
  "scripts": {
    "test": "make test"
  },
  "engines": {
    "node": "*"
  },
  "dependencies": {
    "require-all": "0.0.3",
    "bignumber.js": "1.0.1",
    "readable-stream": "~1.1.9"
  },
  "devDependencies": {
    "utest": "0.0.6",
    "urun": "0.0.6",
    "underscore": "1.3.1"
  },
  "optionalDependencies": {},
  "readme": "# node-mysql\n\n[![Build Status](https://secure.travis-ci.org/felixge/node-mysql.png)](http://travis-ci.org/felixge/node-mysql)\n\n## Install\n\n```bash\nnpm install mysql@2.0.0-rc1\n```\n\nDespite the `rc` tag, this is the recommended version for new applications.\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```\nnpm 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});\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/vacancy/software-engineer/))\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  // connected! (unless `err` is set)\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. (Default: `'UTF8_GENERAL_CI'`. Value needs to be all in upper case letters!)\n* `timezone`: The timezone used to store local dates. (Default: `'local'`)\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* `multipleStatements`: Allow multiple mysql statements per query. Be careful\n  with this, it exposes you to 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 [Connection Flags](#connection-flags).\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## 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\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\nIf you need to set session variables on the connection before it gets used,\nyou can listen to the `connection` event.\n\n```js\npool.on('connection', function(connection) {\n  connection.query('SET SESSION auto_increment_increment=1')\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\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* `createConnection`: The function to use to create the connection. (Default:\n  `mysql.createConnection`)\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## PoolCluster\n\nPoolCluster provides multiple hosts connection. (group & retry & selector)\n\n```js\n// create\nvar poolCluster = mysql.createPoolCluster();\n\npoolCluster.add(config); // anonymous group\npoolCluster.add('MASTER', masterConfig);\npoolCluster.add('SLAVE1', slave1Config);\npoolCluster.add('SLAVE2', slave2Config);\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// destroy\npoolCluster.end();\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* `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 / 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\nA good way to handle such unexpected disconnects is shown below:\n\n```js\nvar db_config = {\n  host: 'localhost',\n\tuser: 'root',\n\tpassword: '',\n\tdatabase: 'example'\n};\n\nvar connection;\n\nfunction handleDisconnect() {\n  connection = mysql.createConnection(db_config); // Recreate the connection, since\n                                                  // the old one cannot be reused.\n\n  connection.connect(function(err) {              // The server is either down\n    if(err) {                                     // or restarting (takes a while sometimes).\n      console.log('error when connecting to db:', err);\n      setTimeout(handleDisconnect, 2000); // We introduce a delay before attempting to reconnect,\n    }                                     // to avoid a hot loop, and to allow our node script to\n  });                                     // process asynchronous requests in the meantime.\n                                          // If you're also serving http, display a 503 error.\n  connection.on('error', function(err) {\n    console.log('db error', err);\n    if(err.code === 'PROTOCOL_CONNECTION_LOST') { // Connection to the MySQL server is usually\n      handleDisconnect();                         // lost due to either server restart, or a\n    } else {                                      // connnection idle timeout (the wait_timeout\n      throw err;                                  // server variable configures this)\n    }\n  });\n}\n\nhandleDisconnect();\n```\n\nAs you can see in the example above, re-connecting a connection is done by\nestablishing a new connection. Once terminated, an existing connection object\ncannot 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## 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`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\nDifferent value types are escaped differently, here is how:\n\n* Numbers are left untouched\n* Booleans are converted to `true` / `false` strings\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. Nested objects are cast to\n  strings.\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)` like this:\n\n```js\nvar sorter = 'date';\nvar query = 'SELECT * FROM posts ORDER BY ' + mysql.escapeId(sorter);\n\nconsole.log(query); // SELECT * FROM posts ORDER BY `date`\n```\n\nIt also supports adding qualified identifiers. It will escape both parts.\n\n```js\nvar sorter = 'date';\nvar query = 'SELECT * FROM posts ORDER BY ' + mysql.escapeId('posts.' + sorter);\n\nconsole.log(query); // SELECT * FROM posts ORDER BY `posts`.`date`\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## 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\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](http://blog.nodejs.org/2012/12/20/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)\nStreams2 object.  This stream can easily be piped downstream and provides\nautomatic pause/resume, based on downstream congestion and the optional\n`highWaterMark`. The `objectMode` parameter of the stream is set to `true` by\ndefault.\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      connection.rollback(function() {\n        throw err;\n      });\n    }\n\n\tvar log = 'Post ' + result.insertId + ' added';\n\n\tconnection.query('INSERT INTO log SET data=?', log, function(err, result) {\n\t  if (err) { \n        connection.rollback(function() {\n          throw err;\n        });\n      }  \n\t  connection.commit(function(err) {\n\t    if (err) { \n          connection.rollback(function() {\n            throw err;\n          });\n        }\n\t    console.log('success!');\n\t  });\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## 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'` 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* 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 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, don't prepend it with a plus sign, just write the flag name (case insensitive).\n\n**Please note that some available flags that are not default are still not supported\n(e.g.: SSL, Compression). Use at your own risk.**\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\n- LONG_PASSWORD\n- FOUND_ROWS\n- LONG_FLAG\n- CONNECT_WITH_DB\n- ODBC\n- LOCAL_FILES\n- IGNORE_SPACE\n- PROTOCOL_41\n- IGNORE_SIGPIPE\n- TRANSACTIONS\n- RESERVED\n- SECURE_CONNECTION\n- MULTI_RESULTS\n- MULTI_STATEMENTS (used if `multipleStatements` option is activated)\n\n### Other Available Flags\n\n- NO_SCHEMA\n- COMPRESS\n- INTERACTIVE\n- SSL\n- PS_MULTI_RESULTS\n- PLUGIN_AUTH\n- SSL_VERIFY_SERVER_CERT\n- REMEMBER_OPTIONS\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 unit tests\n\nSet the environment variables `MYSQL_DATABASE`, `MYSQL_HOST`, `MYSQL_PORT`, `MYSQL_USER` and `MYSQL_PASSWORD`. (You may want to put these in a `config.sh` file and source it when you run the tests). Then run `make test`.\n\nFor example, if you have an installation of mysql running on localhost:3306 and no password set for the `root` user, run:\n\n```\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= make test\n```\n\n## Running unit tests on windows\n\n* Edit the variables in the file ```make.bat```  according to your system and mysql-settings.\n* Make sure the database (e.g. 'test') you want to use exists and the user you entered has the proper rights to use the test database. (E.g. do not forget to execute the SQL-command ```FLUSH PRIVILEGES``` after you have created the user.)\n* In a DOS-box (or CMD-shell) in the folder of your application run ```npm install mysql --dev``` or in the mysql folder (```node_modules\\mysql```), run ```npm install --dev```. (This will install additional developer-dependencies for node-mysql.)\n* Run ```npm test mysql``` in your applications folder or ```npm test``` in the mysql subfolder.\n* If you want to log the output into a file use ```npm test mysql > test.log``` or ```npm test > test.log```.\n\n## Todo\n\n* Prepared statements\n* setTimeout() for Connection / Query\n* Support for encodings other than UTF-8 / ASCII\n",
  "readmeFilename": "Readme.md",
  "bugs": {
    "url": "https://github.com/felixge/node-mysql/issues"
  },
  "_id": "mysql@2.0.0",
  "dist": {
    "shasum": "f2bb9e4adf92317d73d70dc30c54de217f288f2e"
  },
  "_from": "mysql@",
  "_resolved": "https://registry.npmjs.org/mysql/-/mysql-2.0.0.tgz"
}
