@miatechnet/node-odbc 2.4.10-multiresult.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,1314 @@
1
+ # odbc (Fork con Soporte Multi-ResultSet)
2
+
3
+ 🔀 **Este es un fork de [IBM/node-odbc](https://github.com/IBM/node-odbc)**
4
+
5
+ ## Modificaciones por Pablo Pimentel
6
+
7
+ Esta versión ha sido modificada para soportar **múltiples result sets** cuando se llama a stored procedures que retornan más de un conjunto de resultados.
8
+
9
+ ### Cambios principales:
10
+ - ✅ Soporte para `SQLMoreResults` en `callProcedure()`
11
+ - ✅ Retorna un array de result sets en lugar de solo el primero
12
+ - ✅ Totalmente compatible con la API original
13
+
14
+ ### Ejemplo de uso con múltiples result sets
15
+
16
+ ```javascript
17
+ const odbc = require('@yoredstorm/node-odbc');
18
+
19
+ async function callProcedureWithMultipleResults() {
20
+ const connection = await odbc.connect('DSN=MYDSN');
21
+ const result = await connection.callProcedure(null, null, 'MY_PROC', [param1, param2]);
22
+
23
+ // Ahora result contiene TODOS los result sets
24
+ console.log('Total de result sets:', result.length);
25
+
26
+ result.forEach((resultSet, index) => {
27
+ console.log(`Result Set ${index + 1}:`, resultSet);
28
+ });
29
+ }
30
+ ```
31
+
32
+ ---
33
+
34
+ ## Documentación Original
35
+
36
+ An asynchronous interface for Node.js to unixODBC and its supported drivers.
37
+
38
+ ---
39
+
40
+ ## Requirements
41
+
42
+
43
+ * unixODBC binaries and development libraries for module compilation
44
+ * on Ubuntu/Debian `sudo apt-get install unixodbc unixodbc-dev`
45
+ * on RedHat/CentOS `sudo yum install unixODBC unixODBC-devel`
46
+ * on OSX
47
+ * using macports.org `sudo port unixODBC`
48
+ * using brew `brew install unixODBC`
49
+ * on FreeBSD from ports `cd /usr/ports/databases/unixODBC; make install`
50
+ * on IBM i `yum install unixODBC unixODBC-devel` (requires [yum](http://ibm.biz/ibmi-rpms))
51
+ * ODBC drivers for target database
52
+ * properly configured odbc.ini and odbcinst.ini.
53
+
54
+ ---
55
+
56
+ ## Node.js Version Support
57
+
58
+ This package is a native addon written in C++ using
59
+ [node-addon-api](https://github.com/nodejs/node-addon-api). Like
60
+ `node-addon-api`, `node-odbc` only supports the active LTS Node.js versions.
61
+
62
+ Currently supported versions include:
63
+
64
+ * Node.js 22
65
+ * Node.js 20
66
+ * Node.js 18
67
+
68
+ ---
69
+
70
+ ## Installation
71
+
72
+ Three main steps must be done before `node-odbc` can interact with your database:
73
+
74
+ * **Install unixODBC and unixODBC-devel:** Compilation of `node-odbc` on your system requires these packages to provide the correct headers.
75
+ * **Ubuntu/Debian**: `sudo apt-get install unixodbc unixodbc-dev`
76
+ * **RedHat/CentOS**: `sudo yum install unixODBC unixODBC-devel`
77
+ * **OSX**:
78
+ * **macports.<span></span>org:** `sudo port unixODBC`
79
+ * **using brew:** `brew install unixODBC`
80
+ * **FreeBSD** from ports: `cd /usr/ports/databases/unixODBC; make install`
81
+ * **IBM i:** `yum install unixODBC unixODBC-devel` (requires [yum](http://ibm.biz/ibmi-rpms))
82
+
83
+ * **Install ODBC drivers for target database:** Most database management system providers offer ODBC drivers for their product. See the website of your DBMS for more information.
84
+
85
+ * **odbc.ini and odbcinst.ini**: These files define your DSNs (data source names) and ODBC drivers, respectively. They must be set up for ODBC functions to correctly interact with your database.
86
+
87
+ When all these steps have been completed, install `node-odbc` into your Node.js project by using:
88
+
89
+ ```bash
90
+ npm install odbc
91
+ ```
92
+ ---
93
+
94
+ ## Debugging
95
+
96
+ This package used to contain its own method of tracing ODBC calls, which was enabled by recompiling the package with `DEBUG` defined. Because this information was almost wholly redundant with existing methods of tracing available through ODBC driver managers, it was removed in v2.4.0.
97
+
98
+ Instead, tracing should be enabled through your driver manager, and that information can be analyzed and included with the description of issues encountered.
99
+
100
+ * **unixODBC (Linux, MacOS, IBM i):**
101
+
102
+ In your `odbcinst.ini` file, add the following entry:
103
+ ```
104
+ [ODBC]
105
+ Trace=yes
106
+ TraceFile=/tmp/odbc.log
107
+ ```
108
+ Debug information will be appended to the trace file.
109
+
110
+ * **ODBC Data Source Administrator (Windows):**
111
+
112
+ Open up ODBC Data Source Administrator and select the "Tracing" tab. Enter the location where you want the log file to go in **"Log File Path"**, then click **"Start Tracing Now"**.
113
+ ---
114
+
115
+ ## Drivers
116
+
117
+ ---
118
+
119
+ ## Important Changes in 2.0
120
+
121
+ `node-odbc` has recently been upgraded from its initial release. The following list highlights the major improvements and potential code-breaking changes.
122
+
123
+ * **Promise support:** All asynchronous functions can now be used with native JavaScript Promises. If a callback function is not passed, the ODBC functions will return a native Promise. If a callback _is_ passed to the ODBC functions, then the old callback behavior will be used.
124
+
125
+ * **Performance improvements:** The underlying ODBC function calls have been reworked to greatly improve performance. For ODBC afficianados, `node-odbc` used to retrieved results using SQLGetData, which works for small amounts of data but is slow for large datasets. `node-odbc` now uses SQLBindCol for binding result sets, which for large queries is orders of magnitude faster.
126
+
127
+ * **Rewritten with N-API:** `node-odbc` was completely rewritten using node-addon-api, a C++ wrapper for N-API, which created an engine-agnostic and ABI-stable package. This means that if you upgrade your Node.js version, there is no need to recompile the package, it just works!
128
+
129
+ * **API Changes:** The API has been changed and simplified. See the documentation below for a list of all the changes.
130
+
131
+ * **Timestamp and Datetime Changes:** SQL_DATETIME and SQL_TIMESTAMP no longer are automatically converted to UTC from how they were stored in the table. Previously, the assumption was that whatever was stored in the table was in "local time", and then converted to UTC. There is no guarantee that the time stored is in "local time", and many DBMSs store times without timezone data. Now, the driver will determine how to format the timestamps and datetimes that are returned, as it is retrieved simply as a String with no additional manipulation by this package.
132
+
133
+ ---
134
+
135
+ ## API
136
+
137
+ * [Connection](#Connection)
138
+ * [constructor: odbc.connect()](#constructor-odbcconnectconnectionstring)
139
+ * [.query()](#querysql-parameters-callback)
140
+ * [.callProcedure()](#callprocedurecatalog-schema-name-parameters-callback)
141
+ * [.createStatement()](#createstatementcallback)
142
+ * [.tables()](#tablescatalog-schema-table-type-callback)
143
+ * [.columns()](#columnscatalog-schema-table-column-callback)
144
+ * [.setIsolationLevel()](#setIsolationLevellevel-callback)
145
+ * [.beginTransaction()](#begintransactioncallback)
146
+ * [.commit()](#commitcallback)
147
+ * [.rollback()](#rollbackcallback)
148
+ * [.close()](#closecallback)
149
+ * [Pool](#Pool)
150
+ * [constructor: odbc.pool()](#constructor-odbcpoolconnectionstring)
151
+ * [.connect()](#connectcallback)
152
+ * [.query()](#querysql-parameters-callback-1)
153
+ * [.close()](#closecallback-1)
154
+ * [Statement](#Statement)
155
+ * [.prepare()](#preparesql-callback)
156
+ * [.bind()](#bindparameters-callback)
157
+ * [.execute()](#executecallback)
158
+ * [.close()](#closecallback-2)
159
+ * [Cursor](#Cursor)
160
+ * [.fetch()](#fetchcallback)
161
+ * [.noData](#nodata)
162
+ * [.close()](#closecallback-3)
163
+
164
+ ### **Callbacks _or_ Promises**
165
+
166
+ Every asynchronous function in the Node.js `node-odbc` package can be called with either a callback Function or a Promise. To use Promises, simply do not pass a callback function (in the API docs below, specified with a `callback?`). This will return a Promise object than can then be used with `.then` or the more modern `async/await` workflow. To use callbacks, simply pass a callback function. For each function explained in the documents below, both Callback and Promise examples are given.
167
+
168
+ _All examples are shown using IBM i Db2 DSNs and queries. Because ODBC is DBMS-agnostic, examples will work as long as the query strings are modified for your particular DBMS._
169
+
170
+ ### **Result Array**
171
+
172
+ All functions that return a result set do so in an array, where each row in the result set is an entry in the array. The format of data within the row can either be an array or an object, depending on the configuration option passed to the connection.
173
+
174
+ The result array also contains several properties:
175
+ * `count`: the number of rows affected by the statement or procedure. Returns the result from ODBC function SQLRowCount.
176
+ * `columns`: a list of columns in the result set. This is returned in an array. Each column in the array has the following properties:
177
+ * `name`: The name of the column
178
+ * `dataType`: The data type of the column properties
179
+ * `statement`: The statement used to return the result set
180
+ * `parameters`: The parameters passed to the statement or procedure. For input/output and output parameters, this value will reflect the value updated from a procedure.
181
+ * `return`: The return value from some procedures. For many DBMS, this will always be undefined.
182
+
183
+ ```
184
+ [ { CUSNUM: 938472,
185
+ LSTNAM: 'Henning ',
186
+ INIT: 'G K',
187
+ STREET: '4859 Elm Ave ',
188
+ CITY: 'Dallas',
189
+ STATE: 'TX',
190
+ ZIPCOD: 75217,
191
+ CDTLMT: 5000,
192
+ CHGCOD: 3,
193
+ BALDUE: 37,
194
+ CDTDUE: 0 },
195
+ { CUSNUM: 839283,
196
+ LSTNAM: 'Jones ',
197
+ INIT: 'B D',
198
+ STREET: '21B NW 135 St',
199
+ CITY: 'Clay ',
200
+ STATE: 'NY',
201
+ ZIPCOD: 13041,
202
+ CDTLMT: 400,
203
+ CHGCOD: 1,
204
+ BALDUE: 100,
205
+ CDTDUE: 0 },
206
+ statement: 'SELECT * FROM QIWS.QCUSTCDT',
207
+ parameters: [],
208
+ return: undefined,
209
+ count: -1,
210
+ columns: [ { name: 'CUSNUM', dataType: 2 },
211
+ { name: 'LSTNAM', dataType: 1 },
212
+ { name: 'INIT', dataType: 1 },
213
+ { name: 'STREET', dataType: 1 },
214
+ { name: 'CITY', dataType: 1 },
215
+ { name: 'STATE', dataType: 1 },
216
+ { name: 'ZIPCOD', dataType: 2 },
217
+ { name: 'CDTLMT', dataType: 2 },
218
+ { name: 'CHGCOD', dataType: 2 },
219
+ { name: 'BALDUE', dataType: 2 },
220
+ { name: 'CDTDUE', dataType: 2 } ] ]
221
+ ```
222
+
223
+ In this example, two rows are returned, with eleven columns each. The format of these columns is found on the `columns` property, with their names and dataType (which are integers mapped to SQL data types).
224
+
225
+ With this result structure, users can iterate over the result set like any old array (in this case, `results.length` would return 2) while also accessing important information from the SQL call and result set.
226
+
227
+ ---
228
+ ---
229
+
230
+ ## **Connection**
231
+
232
+ A Connection is your means of connecting to the database through ODBC.
233
+
234
+ ### `constructor: odbc.connect(connectionString)`
235
+
236
+ In order to get a connection, you must use the `.connect` function exported from the module. This asynchronously creates a Connection and gives it back to you. Like all asynchronous functions, this can be done either with callback functions or Promises.
237
+
238
+ #### Parameters:
239
+ * **connectionString**: The connection string to connect to the database, usually by naming a DSN. Can also be a configuration object with the following properties:
240
+ * `connectionString` **REQUIRED**: The connection string to connect to the database
241
+ * `connectionTimeout`: The number of seconds to wait for a request on the connection to complete before returning to the application
242
+ * `loginTimeout`: The number of seconds to wait for a login request to complete before returning to the application
243
+ * **callback?**: The function called when `.connect` has finished connecting. If no callback function is given, `.connect` will return a native JavaScript `Promise`. Callback signature is:
244
+ * error: The error that occured in execution, or `null` if no error
245
+ * connection: The Connection object if a successful connection was made
246
+
247
+ #### Examples:
248
+
249
+ **Promises**
250
+
251
+ ```javascript
252
+ const odbc = require('odbc');
253
+
254
+ async function connectToDatabase() {
255
+ const connection1 = await odbc.connect('DSN=MYDSN');
256
+ // connection1 is now an open Connection
257
+
258
+ // or using a configuration object
259
+ const connectionConfig = {
260
+ connectionString: 'DSN=MYDSN',
261
+ connectionTimeout: 10,
262
+ loginTimeout: 10,
263
+ }
264
+ const connection2 = await odbc.connect(connectionConfig);
265
+ // connection2 is now an open Connection
266
+ }
267
+
268
+ connectToDatabase();
269
+ ```
270
+
271
+ **Callbacks**
272
+
273
+ ```javascript
274
+ const odbc = require('odbc');
275
+ odbc.connect(connectionString, (error, connection) => {
276
+ // connection is now an open Connection
277
+ });
278
+ ```
279
+
280
+ Once a Connection has been created with `odbc.connect`, you can use the following functions on the connection:
281
+
282
+ ---
283
+
284
+ ### `.query(sql, parameters?, options?, callback?)`
285
+
286
+ Run a query on the database. Can be passed an SQL string with parameter markers `?` and an array of parameters to bind to those markers. Returns a [result array](#result-array).
287
+
288
+ #### Parameters:
289
+ * **sql**: The SQL string to execute
290
+ * **parameters?**: An array of parameters to be bound the parameter markers (`?`)
291
+ * **options?**: An object containing query options that affect query behavior. Valid properties include:
292
+ * `cursor`: A boolean value indicating whether or not to return a cursor instead of results immediately. Can also be a string naming the cursor, which will assume that a cursor will be returned.
293
+ * `fetchSize`: Used with a cursor, sets the number of rows that are returned on a call to `fetch` on the Cursor.
294
+ * `timeout`: The amount of time (in seconds) that the query will attempt to execute before returning to the application.
295
+ * `initialBufferSize`: Sets the initial buffer size (in bytes) for storing data from SQL_LONG* data fields. Useful for avoiding resizes if buffer size is known before the call.
296
+ * **callback?**: The function called when `.query` has finished execution. If no callback function is given, `.query` will return a native JavaScript `Promise`. Callback signature is:
297
+ * error: The error that occured in execution, or `null` if no error
298
+ * result: The result object from execution
299
+
300
+ ```JavaScript
301
+ const odbc = require('odbc');
302
+ const connection = odbc.connect(connectionString, (error, connection) => {
303
+ connection.query('SELECT * FROM QIWS.QCUSTCDT', (error, result) => {
304
+ if (error) { console.error(error) }
305
+ console.log(result);
306
+ });
307
+ });
308
+ ```
309
+
310
+ ---
311
+
312
+ ### `.callProcedure(catalog, schema, name, parameters?, callback?)`
313
+
314
+ Calls a database procedure, returning the results in a [result array](#result-array).
315
+
316
+ #### Parameters:
317
+ * **catalog**: The name of the catalog where the procedure exists, or null to use the default catalog
318
+ * **schema**: The name of the schema where the procedure exists, or null to use a default schema
319
+ * **name**: The name of the procedure in the database
320
+ * **parameters?**: An array of parameters to pass to the procedure. For input and input/output parameters, the JavaScript value passed in is expected to be of a type translatable to the SQL type the procedure expects. For output parameters, any JavaScript value can be passed in, and will be overwritten by the function. The number of parameters passed in must match the number of parameters expected by the procedure.
321
+ * **callback?**: The function called when `.callProcedure` has finished execution. If no callback function is given, `.callProcedure` will return a native JavaScript `Promise`. Callback signature is:
322
+ * error: The error that occured in execution, or `null` if no error
323
+ * result: The result object from execution
324
+
325
+ #### Examples:
326
+
327
+ **Promises**
328
+
329
+ ```javascript
330
+ const odbc = require('odbc');
331
+
332
+ // can only use await keyword in an async function
333
+ async function callProcedureExample() {
334
+ const connection = await odbc.connect(`${process.env.CONNECTION_STRING}`);
335
+ const result = await connection.callProcedure(null, null, 'MY_PROC', [undefined]);
336
+ // result contains an array of results, and has a `parameters` property to access parameters returned by the procedure.
337
+ console.log(result);
338
+ }
339
+
340
+ callProcedureExample();
341
+ ```
342
+
343
+ **Callbacks**
344
+
345
+ ```javascript
346
+ const odbc = require('odbc');
347
+
348
+ odbc.connect(`${process.env.CONNECTION_STRING}`, (error, connection) => {
349
+ connection.callProcedure(null, null, 'MY_PROC', [undefined], (error, result) => {
350
+ if (error) { console.error(error) } // handle
351
+ // result contains an array of results, and has a `parameters` property to access parameters returned by the procedure.
352
+ console.log(result);
353
+ });
354
+ });
355
+ ```
356
+
357
+ ---
358
+
359
+ ### `.createStatement(callback?)`
360
+
361
+ Returns a [Statement](#Statement) object from the connection.
362
+
363
+ #### Parameters:
364
+ * **callback?**: The function called when `.createStatement` has finished execution. If no callback function is given, `.createStatement` will return a native JavaScript `Promise`. Callback signature is:
365
+ * error: The error that occured in execution, or `null` if no error
366
+ * statement: The newly created Statement object
367
+
368
+ #### Examples:
369
+
370
+ **Promises**
371
+
372
+ ```javascript
373
+ const odbc = require('odbc');
374
+
375
+ // can only use await keyword in an async function
376
+ async function statementExample() {
377
+ const connection = await odbc.connect(`${process.env.CONNECTION_STRING}`);
378
+ const statement = await connection.createStatement();
379
+ // now have a statement where sql can be prepared, bound, and executed
380
+ }
381
+
382
+ statementExample();
383
+ ```
384
+
385
+ **Callbacks**
386
+
387
+ ```javascript
388
+ const odbc = require('odbc');
389
+
390
+ // returns information about all tables in schema MY_SCHEMA
391
+ odbc.connect(`${process.env.CONNECTION_STRING}`, (error, connection) => {
392
+ connection.createStatement((error, statement) => {
393
+ if (error) { return; } // handle
394
+ // now have a statement where sql can be prepared, bound, and executed
395
+ });
396
+ });
397
+ ```
398
+
399
+ ---
400
+
401
+ ### `.tables(catalog, schema, table, type, callback?)`
402
+
403
+ Returns information about the table specified in the parameters by calling the ODBC function [SQLTables](https://docs.microsoft.com/en-us/sql/odbc/reference/syntax/sqltables-function?view=sql-server-2017). Values passed to parameters will narrow the result set, while `null` will include all results of that level.
404
+
405
+ #### Parameters:
406
+ * **catalog**: The name of the catalog, or null if not specified
407
+ * **schema**: The name of the schema, or null if not specified
408
+ * **table**: The name of the table, or null if not specified
409
+ * **type**: The type of table that you want information about, or null if not specified
410
+ * **callback?**: The function called when `.tables` has finished execution. If no callback function is given, `.tables` will return a native JavaScript `Promise`. Callback signature is:
411
+ * error: The error that occured in execution, or `null` if no error
412
+ * result: The result object from execution
413
+
414
+ #### Examples:
415
+
416
+ **Promises**
417
+
418
+ ```javascript
419
+ const odbc = require('odbc');
420
+
421
+ // can only use await keyword in an async function
422
+ async function getTables() {
423
+ // returns information about all tables in schema MY_SCHEMA
424
+ const connection = await odbc.connect(`${process.env.CONNECTION_STRING}`);
425
+ const result = await connection.tables(null, 'MY_SCHEMA', null, null);
426
+ console.log(result);
427
+ }
428
+
429
+ getTables();
430
+ ```
431
+
432
+ **Callbacks**
433
+
434
+ ```javascript
435
+ const odbc = require('odbc');
436
+
437
+ // returns information about all tables in schema MY_SCHEMA
438
+ odbc.connect(`${process.env.CONNECTION_STRING}`, (error, connection) => {
439
+ connection.columns(null, "MY_SCHEMA", null, null, (error, result) => {
440
+ if (error) { return; } // handle
441
+ console.log(result);
442
+ });
443
+ });
444
+ ```
445
+
446
+ ---
447
+
448
+ ### `.columns(catalog, schema, table, column, callback?)`
449
+
450
+ Returns information about the columns specified in the parameters by calling the ODBC function [SQLColumns](https://docs.microsoft.com/en-us/sql/odbc/reference/syntax/sqlcolumns-function?view=sql-server-2017). Values passed to parameters will narrow the result set, while `null` will include all results of that level.
451
+
452
+ #### Parameters:
453
+ * **catalog**: The name of the catalog, or null if not specified
454
+ * **schema**: The name of the schema, or null if not specified
455
+ * **table**: The name of the table, or null if not specified
456
+ * **column**: The name of the column that you want information about, or null if not specified
457
+ * **callback?**: The function called when `.columns` has finished execution. If no callback function is given, `.columns` will return a native JavaScript `Promise`. Callback signature is:
458
+ * error: The error that occured in execution, or `null` if no error
459
+ * result: The result object from execution
460
+
461
+ #### Examples:
462
+
463
+ **Promises**
464
+
465
+ ```javascript
466
+ const odbc = require('odbc');
467
+
468
+ // can only use await keyword in an async function
469
+ async function getColumns() {
470
+ // returns information about all columns in table MY_SCEHMA.MY_TABLE
471
+ const connection = await odbc.connect(`${process.env.CONNECTION_STRING}`);
472
+ const result = await connection.columns(null, 'MY_SCHEMA', 'MY_TABLE', null);
473
+ console.log(result);
474
+ }
475
+
476
+ getColumns();
477
+ ```
478
+
479
+ **Callbacks**
480
+
481
+ ```javascript
482
+ const odbc = require('odbc');
483
+
484
+ // returns information about all columns in table MY_SCEHMA.MY_TABLE
485
+ odbc.connect(`${process.env.CONNECTION_STRING}`, (error, connection) => {
486
+ connection.columns(null, "MY_SCHEMA", "MY_TABLE", null, (error, result) => {
487
+ if (error) { return; } // handle
488
+ console.log(result);
489
+ });
490
+ });
491
+ ```
492
+
493
+ ---
494
+
495
+ ### `.setIsolationLevel(level, callback?)`
496
+
497
+ Sets the transaction isolation level for the connection, which determines what degree of uncommitted changes can be seen. More information about ODBC isolation levels can be found on [the official ODBC documentation](https://docs.microsoft.com/en-us/sql/odbc/reference/develop-app/transaction-isolation?view=sql-server-2017).
498
+
499
+ #### Parameters:
500
+ * **level**: The isolation level to set on the connection. [There are four isolation levels specified by ODBC](https://docs.microsoft.com/en-us/sql/odbc/reference/develop-app/transaction-isolation-levels?view=sql-server-2017), which can be accessed through the base exported package:
501
+ * `odbc.SQL_TXN_READ_UNCOMMITTED`
502
+ * `odbc.SQL_TXN_READ_COMMITTED`
503
+ * `odbc.SQL_TXN_REPEATABLE_READ`
504
+ * `odbc.SQL_TXN_SERIALIZABLE`
505
+ * **callback?**: The function called when `.setIsolationLevel` has finished execution. If no callback function is given, `.setIsolationLevel` will return a native JavaScript `Promise`. Callback signature is:
506
+ * error: The error that occured in execution, or `null` if no error
507
+
508
+ #### Examples:
509
+
510
+ **Promises**
511
+
512
+ ```javascript
513
+ const odbc = require('odbc');
514
+
515
+ // can only use await keyword in an async function
516
+ async function isolationLevel() {
517
+ const connection = await odbc.connect(`${process.env.CONNECTION_STRING}`);
518
+ await connection.setIsolationLevel(odbc.SQL_TXN_READ_COMMITTED);
519
+ // isolation level is now set
520
+ }
521
+
522
+ isolationLevel();
523
+ ```
524
+
525
+ **Callbacks**
526
+
527
+ ```javascript
528
+ const odbc = require('odbc');
529
+
530
+ odbc.connect(`${process.env.CONNECTION_STRING}`, (error, connection) => {
531
+ connection.setIsolationLevel(odbc.SQL_TXN_READ_COMMITTED, (error) => {
532
+ if (error) { return; } // handle
533
+ // isolation level is now set
534
+ });
535
+ });
536
+ ```
537
+
538
+ ---
539
+
540
+ ### `.beginTransaction(callback?)`
541
+
542
+ Begins a transaction on the connection. The transaction can be committed by calling `.commit` or rolled back by calling `.rollback`. **If a connection is closed with an open transaction, it will be rolled back.** Connection isolation level will affect the data that other transactions can view mid transaction.
543
+
544
+ #### Parameters:
545
+ * **callback?**: The function called when `.beginTransaction` has finished execution. If no callback function is given, `.beginTransaction` will return a native JavaScript `Promise`. Callback signature is:
546
+ * error: The error that occured in execution, or `null` if no error
547
+
548
+ #### Examples:
549
+
550
+ **Promises**
551
+
552
+ ```javascript
553
+ const odbc = require('odbc');
554
+
555
+ // can only use await keyword in an async function
556
+ async function transaction() {
557
+ const connection = await odbc.connect(`${process.env.CONNECTION_STRING}`);
558
+ await connection.beginTransaction();
559
+ // transaction is now open
560
+ }
561
+
562
+ transaction();
563
+ ```
564
+
565
+ **Callbacks**
566
+
567
+ ```javascript
568
+ const odbc = require('odbc');
569
+
570
+ odbc.connect(`${process.env.CONNECTION_STRING}`, (error, connection) => {
571
+ connection.beginTransaction((error) => {
572
+ if (error) { return; } // handle
573
+ // transaction is now open
574
+ });
575
+ });
576
+ ```
577
+
578
+ ---
579
+
580
+ ### `.commit(callback?)`
581
+
582
+ Commits an open transaction. If called on a connection that doesn't have an open transaction, will no-op.
583
+
584
+ #### Parameters:
585
+ * **callback?**: The function called when `.commit` has finished execution. If no callback function is given, `.commit` will return a native JavaScript `Promise`. Callback signature is:
586
+ * error: The error that occured in execution, or `null` if no error
587
+
588
+ #### Examples:
589
+
590
+ **Promises**
591
+
592
+ ```javascript
593
+ const odbc = require('odbc');
594
+
595
+ // can only use await keyword in an async function
596
+ async function commitTransaction() {
597
+ const connection = await odbc.connect(`${process.env.CONNECTION_STRING}`);
598
+ await connection.beginTransaction();
599
+ const insertResult = await connection.query('INSERT INTO MY_TABLE VALUES(1, \'Name\')');
600
+ await connection.commit();
601
+ // INSERT query has now been committed
602
+ }
603
+
604
+ commitTransaction();
605
+ ```
606
+
607
+ **Callbacks**
608
+
609
+ ```javascript
610
+ const odbc = require('odbc');
611
+
612
+ odbc.connect(`${process.env.CONNECTION_STRING}`, (error, connection) => {
613
+ connection.beginTransaction((error1) => {
614
+ if (error1) { return; } // handle
615
+ connection.query('INSERT INTO MY_TABLE VALUES(1, \'Name\')', (error2, result) => {
616
+ if (error2) { return; } // handle
617
+ connection.commit((error3) => {
618
+ // INSERT query has now been committed
619
+ })
620
+ })
621
+ });
622
+ });
623
+ ```
624
+
625
+ ---
626
+
627
+
628
+ ### `.rollback(callback?)`
629
+
630
+ Rolls back an open transaction. If called on a connection that doesn't have an open transaction, will no-op.
631
+
632
+ #### Parameters:
633
+ * **callback?**: The function called when `.rollback` has finished execution. If no callback function is given, `.rollback` will return a native JavaScript `Promise`. Callback signature is:
634
+ * error: The error that occured in execution, or `null` if no error
635
+
636
+ #### Examples:
637
+
638
+ **Promises**
639
+
640
+ ```javascript
641
+ const odbc = require('odbc');
642
+
643
+ // can only use await keyword in an async function
644
+ async function rollbackTransaction() {
645
+ const connection = await odbc.connect(`${process.env.CONNECTION_STRING}`);
646
+ await connection.beginTransaction();
647
+ const insertResult = await connection.query('INSERT INTO MY_TABLE VALUES(1, \'Name\')');
648
+ await connection.rollback();
649
+ // INSERT query has now been rolled back
650
+ }
651
+
652
+ rollbackTransaction();
653
+ ```
654
+
655
+ **Callbacks**
656
+
657
+ ```javascript
658
+ const odbc = require('odbc');
659
+
660
+ odbc.connect(`${process.env.CONNECTION_STRING}`, (error, connection) => {
661
+ connection.beginTransaction((error1) => {
662
+ if (error1) { return; } // handle
663
+ connection.query('INSERT INTO MY_TABLE VALUES(1, \'Name\')', (error2, result) => {
664
+ if (error2) { return; } // handle
665
+ connection.rollback((error3) => {
666
+ // INSERT query has now been rolled back
667
+ })
668
+ })
669
+ });
670
+ });
671
+ ```
672
+
673
+ ---
674
+
675
+ ### `.close(callback?)`
676
+
677
+ Closes an open connection. Any transactions on the connection that have not been ended will be rolledback.
678
+
679
+ #### Parameters:
680
+ * **callback?**: The function called when `.close` has finished closing the connection. If no callback function is given, `.close` will return a native JavaScript `Promise`. Callback signature is:
681
+ * error: The error that occured in execution, or `null` if no error
682
+
683
+ #### Examples:
684
+
685
+ **Promises**
686
+
687
+ ```javascript
688
+ const odbc = require('odbc');
689
+
690
+ // can only use await keyword in an async function
691
+ async function closeConnection() {
692
+ const connection = await odbc.connect(`${process.env.CONNECTION_STRING}`);
693
+ // do something with your connection here
694
+ await connection.close();
695
+ }
696
+
697
+ rollbackTransaction();
698
+ ```
699
+
700
+ **Callbacks**
701
+
702
+ ```javascript
703
+ const odbc = require('odbc');
704
+
705
+ odbc.connect(`${process.env.CONNECTION_STRING}`, (error, connection) => {
706
+ // do something with your connection here
707
+ connection.close((error) => {
708
+ if (error) { return; } // handle
709
+ // connection is now closed
710
+ })
711
+ });
712
+ ```
713
+
714
+ ---
715
+ ---
716
+
717
+
718
+ ### **Pool**
719
+
720
+ ### `constructor: odbc.pool(connectionString)`
721
+
722
+ In order to get a Pool, you must use the `.pool` function exported from the module. This asynchronously creates a Pool of a number of Connections and returns it to you. Like all asynchronous functions, this can be done either with callback functions or Promises.
723
+
724
+ Note that `odbc.pool` will return from callback or Promise as soon as it has created 1 connection. It will continue to spin up Connections and add them to the Pool in the background, but by returning early it will allow you to use the Pool as soon as possible.
725
+
726
+ #### Parameters:
727
+ * **connectionString**: The connection string to connect to the database for all connections in the pool, usually by naming a DSN. Can also be a configuration object with the following properties:
728
+ * `connectionString` **REQUIRED**: The connection string to connect to the database
729
+ * `connectionTimeout`: The number of seconds to wait for a request on the connection to complete before returning to the application
730
+ * `loginTimeout`: The number of seconds to wait for a login request to complete before returning to the application
731
+ * `initialSize`: The initial number of Connections created in the Pool
732
+ * `incrementSize`: How many additional Connections to create when all of the Pool's connections are taken
733
+ * `maxSize`: The maximum number of open Connections the Pool will create
734
+ * `reuseConnections`: Whether or not to reuse an existing Connection instead of creating a new one
735
+ * `shrink`: Whether or not the number of Connections should shrink to `initialSize` as they free up
736
+ * **callback?**: The function called when `.connect` has finished connecting. If no callback function is given, `.connect` will return a native JavaScript `Promise`. Callback signature is:
737
+ * error: The error that occured in execution, or `null` if no error
738
+ * connection: The Connection object if a successful connection was made
739
+
740
+ #### Examples:
741
+
742
+ **Promises**
743
+
744
+ ```JavaScript
745
+ const odbc = require('odbc');
746
+
747
+ // can only use await keyword in an async function
748
+ async function createPool() {
749
+ const pool = await odbc.pool(`${process.env.CONNECTION_STRING}`);
750
+ // can now do something with the Pool
751
+ }
752
+
753
+ createPool();
754
+ ```
755
+
756
+ **Callbacks**
757
+
758
+ ```JavaScript
759
+ const odbc = require('odbc');
760
+ const pool = odbc.pool('DSN=MyDSN', (error, pool) => {
761
+ // pool now has open connections
762
+ });
763
+ ```
764
+
765
+ ### `.connect(callback?)`
766
+
767
+ Returns a [Connection](#connection) object for you to use from the Pool. Doesn't actually open a connection, because they are already open in the pool when `.init` is called.
768
+
769
+ #### Parameters:
770
+ * **callback?**: The function called when `.connect` has finished execution. If no callback function is given, `.connect` will return a native JavaScript `Promise`. Callback signature is:
771
+ * error: The error that occured in execution, or `null` if no error
772
+ * connection: The [Connection](#connection) retrieved from the Pool.
773
+
774
+ #### Examples:
775
+
776
+ **Promises**
777
+
778
+ ```javascript
779
+ const odbc = require('odbc');
780
+
781
+ // can only use await keyword in an async function
782
+ async function connectExample() {
783
+ const pool = await odbc.pool(`${process.env.CONNECTION_STRING}`);
784
+ const connection = await pool.connect();
785
+ // now have a Connection to do work with
786
+ }
787
+
788
+ connectExample();
789
+ ```
790
+
791
+ **Callbacks**
792
+
793
+ ```javascript
794
+ const odbc = require('odbc');
795
+ odbc.pool(`${process.env.CONNECTION_STRING}`, (error1, pool) => {
796
+ if (error1) { return; } // handle
797
+ pool.connect((error2, connection) => {
798
+ if (error2) { return; } // handle
799
+ // now have a Connection to do work with
800
+ });
801
+ });
802
+ ```
803
+
804
+ ---
805
+
806
+ ### `.query(sql, parameters?, callback?)`
807
+
808
+ Utility function to execute a query on any open connection in the pool. Will get a connection, fire off the query, return the results, and return the connection the the pool.
809
+
810
+ #### Parameters:
811
+ * **sql**: An SQL string that will be executed. Can optionally be given parameter markers (`?`) and also given an array of values to bind to the parameters.
812
+ * **parameters?**: An array of values to bind to the parameter markers, if there are any. The number of values in this array must match the number of parameter markers in the sql statement.
813
+ * **options?**: An object containing query options that affect query behavior. Valid properties include:
814
+ * `cursor`: A boolean value indicating whether or not to return a cursor instead of results immediately. Can also be a string naming the cursor, which will assume that a cursor will be returned.
815
+ * `fetchSize`: Used with a cursor, sets the number of rows that are returned on a call to `fetch` on the Cursor.
816
+ * `timeout`: The amount of time (in seconds) that the query will attempt to execute before returning to the application.
817
+ * `initialBufferSize`: Sets the initial buffer size (in bytes) for storing data from SQL_LONG* data fields. Useful for avoiding resizes if buffer size is known before the call.
818
+ * **callback?**: The function called when `.query` has finished execution. If no callback function is given, `.query` will return a native JavaScript `Promise`. Callback signature is:
819
+ * error: The error that occured in execution, or `null` if no error
820
+ * result: The [result array](#result-array) returned from the executed statement
821
+
822
+ #### Examples:
823
+
824
+ **Promises**
825
+
826
+ ```javascript
827
+ const odbc = require('odbc');
828
+
829
+ // can only use await keyword in an async function
830
+ async function queryExample() {
831
+ const pool = await odbc.pool(`${process.env.CONNECTION_STRING}`);
832
+ const result = await pool.query('SELECT * FROM MY_TABLE');
833
+ console.log(result);
834
+ }
835
+
836
+ queryExample();
837
+ ```
838
+
839
+ **Callbacks**
840
+
841
+ ```javascript
842
+ const odbc = require('odbc');
843
+ odbc.pool(`${process.env.CONNECTION_STRING}`, (error1, pool) => {
844
+ if (error1) { return; } // handle
845
+ pool.query('SELECT * FROM MY_TABLE', (error2, result) => {
846
+ if (error2) { return; } // handle
847
+ console.log(result);
848
+ });
849
+ });
850
+ ```
851
+
852
+ ---
853
+
854
+ ### `.close(callback?)`
855
+
856
+ Closes the entire pool of currently unused connections. Will not close connections that are checked-out, but will discard the connections when they are closed with Connection's `.close` function. After calling close, must create a new Pool sprin up new Connections.
857
+
858
+ #### Parameters:
859
+ * **callback?**: The function called when `.close` has finished execution. If no callback function is given, `.close` will return a native JavaScript `Promise`. Callback signature is:
860
+ * error: The error that occured in execution, or `null` if no error
861
+
862
+ #### Examples:
863
+
864
+ **Promises**
865
+
866
+ ```javascript
867
+ const odbc = require('odbc');
868
+
869
+ // can only use await keyword in an async function
870
+ async function closeExample() {
871
+ const pool = await odbc.pool(`${process.env.CONNECTION_STRING}`);
872
+ await pool.close();
873
+ // pool is now closed
874
+ }
875
+
876
+ closeExample();
877
+ ```
878
+
879
+ **Callbacks**
880
+
881
+ ```javascript
882
+ const odbc = require('odbc');
883
+
884
+ odbc.pool(`${process.env.CONNECTION_STRING}`, (error1, pool) => {
885
+ if (error1) { return; } // handle
886
+ // do something with your pool here
887
+ pool.close((error2) => {
888
+ if (error2) { return; } // handle
889
+ // pool is now closed
890
+ });
891
+ });
892
+ ```
893
+
894
+ ---
895
+ ---
896
+
897
+ ## **Statement**
898
+
899
+ A Statement object is created from a Connection, and cannot be created _ad hoc_ with a constructor.
900
+
901
+ Statements allow you to prepare a commonly used statement, then bind parameters to it multiple times, executing in between.
902
+
903
+ ---
904
+
905
+ ### `.prepare(sql, callback?)`
906
+
907
+ Prepares an SQL statement, with or without parameters (?) to bind to.
908
+
909
+ #### Parameters:
910
+ * **sql**: An SQL string that is prepared and can be executed with the .`execute` function.
911
+ * **callback?**: The function called when `.prepare` has finished execution. If no callback function is given, `.prepare` will return a native JavaScript `Promise`. Callback signature is:
912
+ * error: The error that occured in execution, or `null` if no error
913
+
914
+ #### Examples:
915
+
916
+ **Promises**
917
+
918
+ ```javascript
919
+ const odbc = require('odbc');
920
+
921
+ // can only use await keyword in an async function
922
+ async function prepareExample() {
923
+ const connection = await odbc.connect(`${process.env.CONNECTION_STRING}`);
924
+ const statement = await connection.createStatement();
925
+ await statement.prepare('INSERT INTO MY_TABLE VALUES(?, ?)');
926
+ // statement has been prepared, can bind and execute
927
+ }
928
+
929
+ prepareExample();
930
+ ```
931
+
932
+ **Callbacks**
933
+
934
+ ```javascript
935
+ const odbc = require('odbc');
936
+
937
+ odbc.connect(`${process.env.CONNECTION_STRING}`, (error, connection) => {
938
+ connection.createStatement((error1, statement) => {
939
+ if (error1) { return; } // handle
940
+ statement.prepare('INSERT INTO MY_TABLE VALUES(?, ?)' (error2) => {
941
+ if (error2) { return; } // handle
942
+ // statement has been prepared, can bind and execute
943
+ });
944
+ });
945
+ });
946
+ ```
947
+
948
+ ---
949
+
950
+ ### `.bind(parameters, callback?)`
951
+
952
+ Binds an array of values to the parameters on the prepared SQL statement. Cannot be called before `.prepare`.
953
+
954
+ #### Parameters:
955
+ * **sql**: An array of values to bind to the sql statement previously prepared. All parameters will be input parameters. The number of values passed in the array must match the number of parameters to bind to in the prepared statement.
956
+ * **callback?**: The function called when `.bind` has finished execution. If no callback function is given, `.bind` will return a native JavaScript `Promise`. Callback signature is:
957
+ * error: The error that occured in execution, or `null` if no error
958
+
959
+ #### Examples:
960
+
961
+ **Promises**
962
+
963
+ ```javascript
964
+ const odbc = require('odbc');
965
+
966
+ // can only use await keyword in an async function
967
+ async function bindExample() {
968
+ const connection = await odbc.connect(`${process.env.CONNECTION_STRING}`);
969
+ const statement = await connection.createStatement();
970
+ await statement.prepare('INSERT INTO MY_TABLE VALUES(?, ?)');
971
+ // Assuming MY_TABLE has INTEGER and VARCHAR fields.
972
+ await statement.bind([1, 'Name']);
973
+ // statement has been prepared and values bound, can now execute
974
+ }
975
+
976
+ bindExample();
977
+ ```
978
+
979
+ **Callbacks**
980
+
981
+ ```javascript
982
+ const odbc = require('odbc');
983
+
984
+ odbc.connect(`${process.env.CONNECTION_STRING}`, (error, connection) => {
985
+ connection.createStatement((error1, statement) => {
986
+ if (error1) { return; } // handle
987
+ statement.prepare('INSERT INTO MY_TABLE VALUES(?, ?)' (error2) => {
988
+ if (error2) { return; } // handle
989
+ // Assuming MY_TABLE has INTEGER and VARCHAR fields.
990
+ statement.bind([1, 'Name'], (error3) => {
991
+ if (error3) { return; } // handle
992
+ // statement has been prepared and values bound, can now execute
993
+ });
994
+ });
995
+ });
996
+ });
997
+ ```
998
+
999
+ ---
1000
+
1001
+ ### `.execute(options?, callback?)`
1002
+
1003
+ Executes the prepared and optionally bound SQL statement.
1004
+
1005
+ #### Parameters:
1006
+ * **options?**: An object containing options that affect execution behavior. Valid properties include:
1007
+ * `cursor`: A boolean value indicating whether or not to return a cursor instead of results immediately. Can also be a string naming the cursor, which will assume that a cursor will be returned. Closing the `Statement` will also close the `Cursor`, but closing the `Cursor` will keep the `Statement` valid.
1008
+ * `fetchSize`: Used with a cursor, sets the number of rows that are returned on a call to `fetch` on the Cursor.
1009
+ * `timeout`: The amount of time (in seconds) that the query will attempt to execute before returning to the application.
1010
+ * `initialBufferSize`: Sets the initial buffer size (in bytes) for storing data from SQL_LONG* data fields. Useful for avoiding resizes if buffer size is known before the call.
1011
+ * **callback?**: The function called when `.execute` has finished execution. If no callback function is given, `.execute` will return a native JavaScript `Promise`. Callback signature is:
1012
+ * error: The error that occured in execution, or `null` if no error
1013
+ * result: The [result array](#result-array) returned from the executed statement
1014
+
1015
+ #### Examples:
1016
+
1017
+ **Promises**
1018
+
1019
+ ```javascript
1020
+ const odbc = require('odbc');
1021
+
1022
+ // can only use await keyword in an async function
1023
+ async function executeExample() {
1024
+ const connection = await odbc.connect(`${process.env.CONNECTION_STRING}`);
1025
+ const statement = await connection.createStatement();
1026
+ await statement.prepare('INSERT INTO MY_TABLE VALUES(?, ?)');
1027
+ // Assuming MY_TABLE has INTEGER and VARCHAR fields.
1028
+ await statement.bind([1, 'Name']);
1029
+ const result = await statement.execute();
1030
+ console.log(result);
1031
+
1032
+ }
1033
+
1034
+ executeExample();
1035
+ ```
1036
+
1037
+ **Callbacks**
1038
+
1039
+ ```javascript
1040
+ const odbc = require('odbc');
1041
+
1042
+ odbc.connect(`${process.env.CONNECTION_STRING}`, (error, connection) => {
1043
+ connection.createStatement((error1, statement) => {
1044
+ if (error1) { return; } // handle
1045
+ statement.prepare('INSERT INTO MY_TABLE VALUES(?, ?)' (error2) => {
1046
+ if (error2) { return; } // handle
1047
+ // Assuming MY_TABLE has INTEGER and VARCHAR fields.
1048
+ statement.bind([1, 'Name'], (error3) => {
1049
+ if (error3) { return; } // handle
1050
+ statement.execute((error4, result) => {
1051
+ if (error4) { return; } // handle
1052
+ console.log(result);
1053
+ })
1054
+ });
1055
+ });
1056
+ });
1057
+ });
1058
+ ```
1059
+
1060
+ ---
1061
+
1062
+ ### `.close(callback?)`
1063
+
1064
+ Closes the Statement, freeing the statement handle. Running functions on the statement after closing will result in an error.
1065
+
1066
+ #### Parameters:
1067
+ * **callback?**: The function called when `.close` has finished execution. If no callback function is given, `.close` will return a native JavaScript `Promise`. Callback signature is:
1068
+ * error: The error that occured in execution, or `null` if no error
1069
+
1070
+ #### Examples:
1071
+
1072
+ **Promises**
1073
+
1074
+ ```javascript
1075
+ const odbc = require('odbc');
1076
+
1077
+ // can only use await keyword in an async function
1078
+ async function executeExample() {
1079
+ const connection = await odbc.connect(`${process.env.CONNECTION_STRING}`);
1080
+ const statement = await connection.createStatement();
1081
+ await statement.prepare('INSERT INTO MY_TABLE VALUES(?, ?)');
1082
+ // Assuming MY_TABLE has INTEGER and VARCHAR fields.
1083
+ await statement.bind([1, 'Name']);
1084
+ const result = await statement.execute();
1085
+ console.log(result);
1086
+ await statement.close();
1087
+ }
1088
+
1089
+ executeExample();
1090
+ ```
1091
+
1092
+ **Callbacks**
1093
+
1094
+ ```javascript
1095
+ const odbc = require('odbc');
1096
+
1097
+ odbc.connect(`${process.env.CONNECTION_STRING}`, (error, connection) => {
1098
+ connection.createStatement((error1, statement) => {
1099
+ if (error1) { return; } // handle
1100
+ statement.prepare('INSERT INTO MY_TABLE VALUES(?, ?)' (error2) => {
1101
+ if (error2) { return; } // handle
1102
+ // Assuming MY_TABLE has INTEGER and VARCHAR fields.
1103
+ statement.bind([1, 'Name'], (error3) => {
1104
+ if (error3) { return; } // handle
1105
+ statement.execute((error4, result) => {
1106
+ if (error4) { return; } // handle
1107
+ console.log(result);
1108
+ statement.close((error5) => {
1109
+ if (error5) { return; } // handle
1110
+ // statement closed successfully
1111
+ })
1112
+ })
1113
+ });
1114
+ });
1115
+ });
1116
+ });
1117
+ ```
1118
+
1119
+ ---
1120
+ ---
1121
+
1122
+ ## **Cursor**
1123
+
1124
+ A Cursor object is created from a Connection when running a query, and cannot be created _ad hoc_ with a constructor.
1125
+
1126
+ Cursors allow you to fetch piecemeal instead of retrieving all rows at once. The fetch size is set on the query options, and then a Cursor is returned from the query instead of a result set. `.fetch` is then called to retrieve the result set by the fetch size.
1127
+
1128
+ ---
1129
+
1130
+ ### `.fetch(callback?)`
1131
+
1132
+ Asynchronously returns the next chunk of rows from the result set and returns them as a Result object.
1133
+
1134
+ #### Parameters:
1135
+ * **callback?**: The function called when `.fetch` has finished retrieving the result rows. If no callback function is given, `.fetch` will return a native JavaScript `Promise` that resolve the result rows. Callback signature is:
1136
+ * error: The error that occured in execution, or `null` if no error
1137
+ * results: The [result array](#result-array) returned from the executed statement with at most `fetchSize`-number of rows.
1138
+
1139
+ #### Examples:
1140
+
1141
+ **Promises**
1142
+
1143
+ ```javascript
1144
+ const odbc = require('odbc');
1145
+
1146
+ // can only use await keyword in an async function
1147
+ async function cursorExample() {
1148
+ const connection = await odbc.connect(`${process.env.CONNECTION_STRING}`);
1149
+ const cursor = await connection.query('SELECT * FROM MY_TABLE', { cursor: true, fetchSize: 3 });
1150
+ const result = await cursor.fetch();
1151
+ // Now have a results array of size 3 (or less) that we can use
1152
+ await cursor.close();
1153
+ }
1154
+
1155
+ cursorExample();
1156
+ ```
1157
+
1158
+ **Callbacks**
1159
+
1160
+ ```javascript
1161
+ const odbc = require('odbc');
1162
+
1163
+ odbc.connect(`${process.env.CONNECTION_STRING}`, (error, connection) => {
1164
+ connection.query('SELECT * FROM MY_TABLE', { cursor: true, fetchSize: 3 }, (error1, cursor) => {
1165
+ if (error1) { return; } // handle
1166
+ cursor.fetch((error2, results) => {
1167
+ if (error2) { return; } // handle
1168
+ // Now have a results array of size 3 (or less) that we can use
1169
+ cursor.close((error3) => {
1170
+ if (error3) { return; } // handle
1171
+ // cursor now closed, now do more work
1172
+ })
1173
+ });
1174
+ });
1175
+ });
1176
+ ```
1177
+
1178
+ ---
1179
+
1180
+ ### `.noData`
1181
+
1182
+ Returns whether the cursor has reached the end of the result set. Fetch must be called at least once before noData can return `true`. Used for determining if there are no more results to retrieve from the cursor.
1183
+
1184
+ #### Parameters:
1185
+ None
1186
+
1187
+ #### Examples:
1188
+
1189
+ **Promises**
1190
+
1191
+ ```javascript
1192
+ const odbc = require('odbc');
1193
+
1194
+ // can only use await keyword in an async function
1195
+ async function cursorExample() {
1196
+ const connection = await odbc.connect(`${process.env.CONNECTION_STRING}`);
1197
+ const cursor = await connection.query('SELECT * FROM MY_TABLE', { cursor: true, fetchSize: 3 });
1198
+ // As long as noData is false, keep calling fetch
1199
+ while (!cursor.noData)
1200
+ {
1201
+ const result = await cursor.fetch();
1202
+ // Now have a results array of size 3 (or less) that we can use
1203
+ }
1204
+ await cursor.close();
1205
+ }
1206
+
1207
+ cursorExample();
1208
+ ```
1209
+
1210
+ **Callbacks**
1211
+
1212
+ ```javascript
1213
+ const odbc = require('odbc');
1214
+
1215
+ odbc.connect(`${process.env.CONNECTION_STRING}`, (error, connection) => {
1216
+ connection.query('SELECT * FROM MY_TABLE', { cursor: true, fetchSize: 3 }, (error1, cursor) => {
1217
+ if (error1) { return; } // handle
1218
+ cursor.fetch((error2, results) => {
1219
+ if (error2) { return; } // handle
1220
+ // Now have a results array of size 3 (or less) that we can use
1221
+ if (!cursor.noData) {
1222
+ // Still more data to retrieve!
1223
+ } else {
1224
+ cursor.close((error3) => {
1225
+ if (error3) { return; } // handle
1226
+ // cursor now closed, now do more work
1227
+ });
1228
+ }
1229
+ });
1230
+ });
1231
+ });
1232
+ ```
1233
+
1234
+ ---
1235
+
1236
+ ### `.close(callback?)`
1237
+
1238
+ Closes the statement that the cursor was generated from, and by extension the cursor itself. Needs to be called when the cursor is no longer needed.
1239
+
1240
+ #### Parameters:
1241
+ * **callback?**: The function called when `.close` has finished execution. If no callback function is given, `.close` will return a native JavaScript `Promise`. Callback signature is:
1242
+ * error: The error that occured while closing the statement, or `null` if no error
1243
+
1244
+ #### Examples:
1245
+
1246
+ **Promises**
1247
+
1248
+ ```javascript
1249
+ const odbc = require('odbc');
1250
+
1251
+ // can only use await keyword in an async function
1252
+ async function cursorExample() {
1253
+ const connection = await odbc.connect(`${process.env.CONNECTION_STRING}`);
1254
+ const cursor = await connection.query('SELECT * FROM MY_TABLE', { cursor: true, fetchSize: 3 });
1255
+ const result = await cursor.fetch();
1256
+ // Now have a results array of size 3 (or less) that we can use
1257
+ await cursor.close();
1258
+ }
1259
+
1260
+ cursorExample();
1261
+ ```
1262
+
1263
+ **Callbacks**
1264
+
1265
+ ```javascript
1266
+ const odbc = require('odbc');
1267
+
1268
+ odbc.connect(`${process.env.CONNECTION_STRING}`, (error, connection) => {
1269
+ connection.query('SELECT * FROM MY_TABLE', { cursor: true, fetchSize: 3 }, (error1, cursor) => {
1270
+ if (error1) { return; } // handle
1271
+ cursor.fetch((error2, results) => {
1272
+ if (error2) { return; } // handle
1273
+ // Now have a results array of size 3 (or less) that we can use
1274
+ cursor.close((error3) => {
1275
+ if (error3) { return; } // handle
1276
+ // cursor now closed, now do more work
1277
+ })
1278
+ });
1279
+ });
1280
+ });
1281
+ ```
1282
+
1283
+ ---
1284
+ ---
1285
+
1286
+
1287
+ ## Future improvements
1288
+
1289
+ Development of `node-odbc` is an ongoing endeavor, and there are many planned improvements for the package. If you would like to see something, simply add it to the Issues and we will respond!
1290
+
1291
+ ## contributors
1292
+
1293
+ * Mark Irish (mirish@ibm.com)
1294
+ * Dan VerWeire (dverweire@gmail.com)
1295
+ * Lee Smith (notwink@gmail.com)
1296
+ * Bruno Bigras
1297
+ * Christian Ensel
1298
+ * Yorick
1299
+ * Joachim Kainz
1300
+ * Oleg Efimov
1301
+ * paulhendrix
1302
+
1303
+ license
1304
+ -------
1305
+
1306
+ * Copyright (c) 2019, 2021 IBM
1307
+ * Copyright (c) 2013 Dan VerWeire <dverweire@gmail.com>
1308
+ * Copyright (c) 2010 Lee Smith <notwink@gmail.com>
1309
+
1310
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies ofthe Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
1311
+
1312
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
1313
+
1314
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.