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.
33 lines
24 KiB
33 lines
24 KiB
{
|
|
"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-alpha5",
|
|
"repository": {
|
|
"url": ""
|
|
},
|
|
"main": "./index",
|
|
"scripts": {
|
|
"test": "make test"
|
|
},
|
|
"engines": {
|
|
"node": "*"
|
|
},
|
|
"dependencies": {
|
|
"require-all": "0.0.3"
|
|
},
|
|
"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-alpha5\n```\n\nDespite the alpha 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 git://github.com/felixge/node-mysql.git\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/senior-web-technologist/))\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* `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'`)\n* `timezone`: The timezone used to store local dates. (Default: `'local'`)\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* `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## 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, or the server crashing. All of these events are\nconsidered fatal errors, and will have the `err.code =\n'PROTOCOL_CONNECTION_LOST'`. See the [Error Handling](#error-handling) section\nfor more information.\n\nThe best way to handle such unexpected disconnects is shown below:\n\n```js\nfunction handleDisconnect(connection) {\n connection.on('error', function(err) {\n if (!err.fatal) {\n return;\n }\n\n if (err.code !== 'PROTOCOL_CONNECTION_LOST') {\n throw err;\n }\n\n console.log('Re-connecting lost connection: ' + err.stack);\n\n connection = mysql.createConnection(connection.config);\n handleDisconnect(connection);\n connection.connect();\n });\n}\n\nhandleDisconnect(connection);\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\nThis logic will also be part of connection pool support once I add that to this\nlibrary.\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()` method:\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\nWhen you pass an Object to `.escape()` or `.query()`, `.escapeId()` is used to avoid SQL\ninjection in object keys.\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\n## Executing queries in parallel\n\nThe MySQL protocol is sequential, this means that you need multiple connections\nto execute queries in parallel. Future version of this module may ship with a\nconnection pool implementation, but for now you have to figure out how to\nmanage multiple connections yourself if you want to execute queries in\nparallel.\n\nOne simple 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## 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## 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\nIf you need a buffer there's also a `.buffer()` function and also a `.geometry()` one\nboth used by the default type cast that you can use.\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.\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## Todo\n\n* Prepared statements\n* setTimeout() for Connection / Query\n* connection pooling\n* Support for encodings other than UTF-8 / ASCII\n* API support for transactions, similar to [php](http://www.php.net/manual/en/mysqli.quickstart.transactions.php)\n",
|
|
"readmeFilename": "Readme.md",
|
|
"_id": "mysql@2.0.0-alpha5",
|
|
"_from": "mysql@2.0.0-alpha5"
|
|
}
|