Skip to content

Commit f924d91

Browse files
committed
updating readme with mysql.format information
1 parent 05d8458 commit f924d91

File tree

1 file changed

+162
-32
lines changed

1 file changed

+162
-32
lines changed

Readme.md

Lines changed: 162 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
## Install
66

77
```bash
8-
npm install [email protected]alpha8
8+
npm install [email protected]alpha9
99
```
1010

1111
Despite the alpha tag, this is the recommended version for new applications.
@@ -208,7 +208,7 @@ var mysql = require('mysql');
208208
var pool = mysql.createPool({
209209
host : 'example.org',
210210
user : 'bob',
211-
password : 'secret'
211+
password : 'secret',
212212
});
213213

214214
pool.getConnection(function(err, connection) {
@@ -220,12 +220,12 @@ If you need to set session variables on the connection before it gets used,
220220
you can listen to the `connection` event.
221221

222222
```js
223-
pool.on('connection', function(err, connection) {
223+
pool.on('connection', function(connection) {
224224
connection.query('SET SESSION auto_increment_increment=1')
225-
})
225+
});
226226
```
227227

228-
When you are done with a connection, just call `connection.end()` and the
228+
When you are done with a connection, just call `connection.release()` and the
229229
connection will return to the pool, ready to be used again by someone else.
230230

231231
```js
@@ -236,7 +236,7 @@ pool.getConnection(function(err, connection) {
236236
// Use the connection
237237
connection.query( 'SELECT something FROM sometable', function(err, rows) {
238238
// And done with the connection.
239-
connection.end();
239+
connection.release();
240240

241241
// Don't use the connection here, it has been returned to the pool.
242242
});
@@ -270,6 +270,62 @@ addition to those options pools accept a few extras:
270270
before returning an error from `getConnection`. If set to `0`, there is no
271271
limit to the number of queued connection requests. (Default: `0`)
272272

273+
## PoolCluster
274+
275+
PoolCluster provides multiple hosts connection. (group & retry & selector)
276+
277+
```js
278+
// create
279+
var poolCluster = mysql.createPoolCluster();
280+
281+
poolCluster.add(config); // anonymous group
282+
poolCluster.add('MASTER', masterConfig);
283+
poolCluster.add('SLAVE1', slave1Config);
284+
poolCluster.add('SLAVE2', slave2Config);
285+
286+
// Target Group : ALL(anonymous, MASTER, SLAVE1-2), Selector : round-robin(default)
287+
poolCluster.getConnection(function (err, connection) {});
288+
289+
// Target Group : MASTER, Selector : round-robin
290+
poolCluster.getConnection('MASTER', function (err, connection) {});
291+
292+
// Target Group : SLAVE1-2, Selector : order
293+
// If can't connect to SLAVE1, return SLAVE2. (remove SLAVE1 in the cluster)
294+
poolCluster.on('remove', function (nodeId) {
295+
console.log('REMOVED NODE : ' + nodeId); // nodeId = SLAVE1
296+
});
297+
298+
poolCluster.getConnection('SLAVE*', 'ORDER', function (err, connection) {});
299+
300+
// of namespace : of(pattern, selector)
301+
poolCluster.of('*').getConnection(function (err, connection) {});
302+
303+
var pool = poolCluster.of('SLAVE*', 'RANDOM');
304+
pool.getConnection(function (err, connection) {});
305+
pool.getConnection(function (err, connection) {});
306+
307+
// destroy
308+
poolCluster.end();
309+
```
310+
311+
## PoolCluster Option
312+
* `canRetry`: If `true`, `PoolCluster` will attempt to reconnect when connection fails. (Default: `true`)
313+
* `removeNodeErrorCount`: If connection fails, node's `errorCount` increases.
314+
When `errorCount` is greater than `removeNodeErrorCount`, remove a node in the `PoolCluster`. (Default: `5`)
315+
* `defaultSelector`: The default selector. (Default: `RR`)
316+
* `RR`: Select one alternately. (Round-Robin)
317+
* `RANDOM`: Select the node by random function.
318+
* `ORDER`: Select the first node available unconditionally.
319+
320+
```js
321+
var clusterConfig = {
322+
removeNodeErrorCount: 1, // Remove the node immediately when connection fails.
323+
defaultSelector: 'ORDER',
324+
};
325+
326+
var poolCluster = mysql.createPoolCluster(clusterConfig);
327+
```
328+
273329
## Switching users / altering connection state
274330

275331
MySQL offers a changeUser command that allows you to alter the current user and
@@ -297,33 +353,45 @@ by this module.
297353
## Server disconnects
298354

299355
You may lose the connection to a MySQL server due to network problems, the
300-
server timing you out, or the server crashing. All of these events are
301-
considered fatal errors, and will have the `err.code =
356+
server timing you out, the server being restarted, or crashing. All of these
357+
events are considered fatal errors, and will have the `err.code =
302358
'PROTOCOL_CONNECTION_LOST'`. See the [Error Handling](#error-handling) section
303359
for more information.
304360

305-
The best way to handle such unexpected disconnects is shown below:
361+
A good way to handle such unexpected disconnects is shown below:
306362

307363
```js
308-
function handleDisconnect(connection) {
309-
connection.on('error', function(err) {
310-
if (!err.fatal) {
311-
return;
312-
}
364+
var db_config = {
365+
host: 'localhost',
366+
user: 'root',
367+
password: '',
368+
database: 'example'
369+
};
313370

314-
if (err.code !== 'PROTOCOL_CONNECTION_LOST') {
315-
throw err;
316-
}
371+
var connection;
317372

318-
console.log('Re-connecting lost connection: ' + err.stack);
373+
function handleDisconnect() {
374+
connection = mysql.createConnection(db_config); // Recreate the connection, since
375+
// the old one cannot be reused.
319376

320-
connection = mysql.createConnection(connection.config);
321-
handleDisconnect(connection);
322-
connection.connect();
377+
connection.connect(function(err) { // The server is either down
378+
if(err) { // or restarting (takes a while sometimes).
379+
console.log('error when connecting to db:', err);
380+
setTimeout(handleDisconnect, 2000); // We introduce a delay before attempting to reconnect,
381+
} // to avoid a hot loop, and to allow our node script to
382+
}); // process asynchronous requests in the meantime.
383+
// If you're also serving http, display a 503 error.
384+
connection.on('error', function(err) {
385+
console.log('db error', err);
386+
if(err.code === 'PROTOCOL_CONNECTION_LOST') { // Connection to the MySQL server is usually
387+
handleDisconnect(); // lost due to either server restart, or a
388+
} else { // connnection idle timeout (the wait_timeout
389+
throw err; // server variable configures this)
390+
}
323391
});
324392
}
325393

326-
handleDisconnect(connection);
394+
handleDisconnect();
327395
```
328396

329397
As you can see in the example above, re-connecting a connection is done by
@@ -337,7 +405,7 @@ space for a new connection to be created on the next getConnection call.
337405

338406
In order to avoid SQL Injection attacks, you should always escape any user
339407
provided data before using it inside a SQL query. You can do so using the
340-
`connection.escape()` method:
408+
`connection.escape()` or `pool.escape()` methods:
341409

342410
```js
343411
var userId = 'some user provided value';
@@ -430,6 +498,18 @@ connection.query('SELECT * FROM ?? WHERE id = ?', ['users', userId], function(er
430498

431499
When you pass an Object to `.escape()` or `.query()`, `.escapeId()` is used to avoid SQL injection in object keys.
432500

501+
### Preparing Queries
502+
503+
You 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:
504+
505+
```js
506+
var sql = "SELECT * FROM ?? WHERE ?? = ?";
507+
var inserts = ['users', 'id', userId];
508+
sql = mysql.format(sql, inserts);
509+
```
510+
511+
Following 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.
512+
433513
### Custom format
434514

435515
If 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.
@@ -627,12 +707,51 @@ connection.query(options, function(err, results) {
627707
table1_fieldA: '...',
628708
table1_fieldB: '...',
629709
table2_fieldA: '...',
630-
table2_fieldB: '...'
710+
table2_fieldB: '...',
631711
}, ...]
632712
*/
633713
});
634714
```
635715

716+
## Transactions
717+
718+
Simple transaction support is available at the connection level:
719+
720+
```js
721+
connection.beginTransaction(function(err) {
722+
if (err) { throw err; }
723+
connection.query('INSERT INTO posts SET title=?', title, function(err, result) {
724+
if (err) {
725+
connection.rollback(function() {
726+
throw err;
727+
});
728+
}
729+
730+
var log = 'Post ' + result.insertId + ' added';
731+
732+
connection.query('INSERT INTO log SET data=?', log, function(err, result) {
733+
if (err) {
734+
connection.rollback(function() {
735+
throw err;
736+
});
737+
}
738+
connection.commit(function(err) {
739+
if (err) {
740+
connection.rollback(function() {
741+
throw err;
742+
});
743+
}
744+
console.log('success!');
745+
});
746+
});
747+
});
748+
});
749+
```
750+
Please note that beginTransaction(), commit() and rollback() are simply convenience
751+
functions that execute the START TRANSACTION, COMMIT, and ROLLBACK commands respectively.
752+
It is important to understand that many commands in MySQL can cause an implicit commit,
753+
as described [in the MySQL documentation](http://dev.mysql.com/doc/refman/5.5/en/implicit-commit.html)
754+
636755
## Error handling
637756

638757
This module comes with a consistent approach to error handling that you should
@@ -775,7 +894,7 @@ Or on the query level:
775894
var options = {sql: '...', typeCast: false};
776895
var query = connection.query(options, function(err, results) {
777896

778-
}):
897+
});
779898
```
780899

781900
You can also pass a function and handle type casting yourself. You're given some
@@ -792,11 +911,23 @@ connection.query({
792911
}
793912
return next();
794913
}
795-
})
914+
});
915+
```
916+
__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)__
917+
918+
```
919+
field.string()
920+
field.buffer()
921+
field.geometry()
922+
```
923+
are aliases for
924+
```
925+
parser.parseLengthCodedString()
926+
parser.parseLengthCodedBuffer()
927+
parser.parseGeometryValue()
796928
```
929+
__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)__
797930

798-
If you need a buffer there's also a `.buffer()` function and also a `.geometry()` one
799-
both used by the default type cast that you can use.
800931

801932
## Connection Flags
802933

@@ -813,7 +944,7 @@ prepend the flag with a minus sign. To add a flag that is not in the default lis
813944
The next example blacklists FOUND_ROWS flag from default connection flags.
814945

815946
```js
816-
var connection = mysql.createConnection("mysql://localhost/test?flags=-FOUND_ROWS")
947+
var connection = mysql.createConnection("mysql://localhost/test?flags=-FOUND_ROWS");
817948
```
818949

819950
### Default Flags
@@ -886,11 +1017,10 @@ For example, if you have an installation of mysql running on localhost:3306 and
8861017
* 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.)
8871018
* 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.)
8881019
* Run ```npm test mysql``` in your applications folder or ```npm test``` in the mysql subfolder.
889-
* If you want to log the output into a file use ```npm test mysql > test.log``` or ```npm test > test.log```.
1020+
* If you want to log the output into a file use ```npm test mysql > test.log``` or ```npm test > test.log```.
8901021

8911022
## Todo
8921023

8931024
* Prepared statements
8941025
* setTimeout() for Connection / Query
895-
* Support for encodings other than UTF-8 / ASCII
896-
* API support for transactions, similar to [php](http://www.php.net/manual/en/mysqli.quickstart.transactions.php)
1026+
* Support for encodings other than UTF-8 / ASCII

0 commit comments

Comments
 (0)