Skip to content

Commit 864cb64

Browse files
committed
2 parents cb28861 + 2f12cdf commit 864cb64

12 files changed

+603
-20
lines changed

javascript/node-oracledb/README.md

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,18 @@
11
# Node-oracledb Examples
22

3-
This directory contains [node-oracledb 2.3](https://www.npmjs.com/package/oracledb) examples.
3+
This directory contains [node-oracledb 3.0](https://www.npmjs.com/package/oracledb) examples.
44

55
The node-oracledb add-on for Node.js powers high performance Oracle Database applications.
66

77
[Node-oracledb documentation](https://oracle.github.io/node-oracledb/doc/api.html)
88

99
[Issues and questions](https://github.com/oracle/node-oracledb/issues)
1010

11+
Issues and questions about node-oracledb can be posted on
12+
[GitHub](https://github.com/oracle/node-oracledb/issues) or
13+
[Slack](https://node-oracledb.slack.com/) ([link to join
14+
Slack](https://join.slack.com/t/node-oracledb/shared_invite/enQtNDI4NTUyNjMzMDA5LWRiZWRkZjQ3NjBhNDUwOGJlNDFiZWJhZTIzYTJkMWQ5N2UwNTg5NzNmNmY1YmZjZGYxNmRhOTkyOTlhMmViNjY)).
15+
1116
To run the examples:
1217

1318
- [Install node-oracledb](https://oracle.github.io/node-oracledb/INSTALL.html).
Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
/* Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved. */
2+
3+
/******************************************************************************
4+
*
5+
* You may not use the identified files except in compliance with the Apache
6+
* License, Version 2.0 (the "License.")
7+
*
8+
* You may obtain a copy of the License at
9+
* http://www.apache.org/licenses/LICENSE-2.0.
10+
*
11+
* Unless required by applicable law or agreed to in writing, software
12+
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
13+
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14+
*
15+
* See the License for the specific language governing permissions and
16+
* limitations under the License.
17+
*
18+
* NAME
19+
* calltimeout.js
20+
*
21+
* DESCRIPTION
22+
* Shows how to time out long running database calls.
23+
* See https://oracle.github.io/node-oracledb/doc/api.html#dbcalltimeouts
24+
* Node-oracledb must be using Oracle Client 18c libraries, or greater.
25+
*
26+
* This example uses Async/Await of Node 8.
27+
*
28+
*****************************************************************************/
29+
30+
let oracledb = require("oracledb");
31+
let dbConfig = require('./dbconfig.js');
32+
33+
// "Sleep" in the database for a number of seconds.
34+
// This uses an inefficent sleep implementation instead of
35+
// dbms_lock.sleep() which not all users can use.
36+
const sql = `
37+
DECLARE
38+
t DATE := SYSDATE + (:sleepsec * (1/86400));
39+
BEGIN
40+
LOOP
41+
EXIT WHEN t <= SYSDATE;
42+
END LOOP;
43+
END;`;
44+
45+
let dboptime = 4; // seconds the DB operation will take
46+
let timeout = 2; // seconds the application will wait for the DB operation
47+
48+
async function runTest() {
49+
let connection;
50+
51+
try {
52+
connection = await oracledb.getConnection(dbConfig);
53+
connection.callTimeout = timeout * 1000; // milliseconds
54+
console.log("Database call timeout set to " + connection.callTimeout / 1000 + " seconds");
55+
console.log("Executing a " + dboptime + " second DB operation");
56+
await connection.execute(sql, [dboptime]);
57+
console.log("DB operation successfully completed");
58+
} catch (err) {
59+
if (err.message.startsWith('DPI-1067:') || err.errorNum === 3114)
60+
console.log('DB operation was stopped after exceeding the call timeout');
61+
else
62+
console.error(err);
63+
} finally {
64+
if (connection) {
65+
try {
66+
await connection.close();
67+
} catch (err) {
68+
console.error(err);
69+
}
70+
}
71+
}
72+
}
73+
74+
runTest();

javascript/node-oracledb/demo.sql

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -257,4 +257,6 @@ COMMIT;
257257
-- The DBA must grant access:
258258
-- GRANT CHANGE NOTIFICATION TO myuser;
259259

260-
create table cqntable (k number);
260+
BEGIN EXECUTE IMMEDIATE 'DROP TABLE cqntable'; EXCEPTION WHEN OTHERS THEN IF SQLCODE <> -942 THEN RAISE; END IF; END;
261+
/
262+
CREATE TABLE cqntable (k NUMBER);

javascript/node-oracledb/example.js

Lines changed: 115 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,115 @@
1+
/* Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved. */
2+
3+
/******************************************************************************
4+
*
5+
* You may not use the identified files except in compliance with the Apache
6+
* License, Version 2.0 (the "License.")
7+
*
8+
* You may obtain a copy of the License at
9+
* http://www.apache.org/licenses/LICENSE-2.0.
10+
*
11+
* Unless required by applicable law or agreed to in writing, software
12+
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
13+
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14+
*
15+
* See the License for the specific language governing permissions and
16+
* limitations under the License.
17+
*
18+
* NAME
19+
* example.js
20+
*
21+
* DESCRIPTION
22+
* A basic node-oracledb example using Node.js 8's async/await syntax.
23+
*
24+
* For a connection pool example see webapp.js
25+
* For a ResultSet example see resultset2.js
26+
* For a query stream example see selectstream.js
27+
* For a Promise example see promises.js
28+
* For a callback example see select1.js
29+
*
30+
*****************************************************************************/
31+
32+
var oracledb = require('oracledb');
33+
var dbConfig = require('./dbconfig.js');
34+
35+
async function run() {
36+
let connection;
37+
38+
try {
39+
40+
let sql, binds, options, result;
41+
42+
connection = await oracledb.getConnection( {
43+
user : dbConfig.user,
44+
password : dbConfig.password,
45+
connectString : dbConfig.connectString
46+
});
47+
48+
// Create a table
49+
50+
await connection.execute(
51+
`BEGIN
52+
EXECUTE IMMEDIATE 'DROP TABLE mytab';
53+
EXCEPTION
54+
WHEN OTHERS THEN
55+
IF SQLCODE NOT IN (-00942) THEN
56+
RAISE;
57+
END IF;
58+
END;`);
59+
60+
await connection.execute(
61+
`CREATE TABLE mytab (id NUMBER, data VARCHAR2(20))`);
62+
63+
// Insert some data
64+
65+
sql = `INSERT INTO mytab VALUES (:1, :2)`;
66+
67+
binds = [ [101, "Alpha" ], [102, "Beta" ], [103, "Gamma" ] ];
68+
69+
// For a complete list of options see the documentation.
70+
options = {
71+
autoCommit: true,
72+
// batchErrors: true, // continue processing even if there are data errors
73+
bindDefs: [
74+
{ type: oracledb.NUMBER },
75+
{ type: oracledb.STRING, maxSize: 20 }
76+
]
77+
};
78+
79+
result = await connection.executeMany(sql, binds, options);
80+
81+
console.log("Number of rows inserted:", result.rowsAffected);
82+
83+
// Query the data
84+
85+
sql = `SELECT * FROM mytab`;
86+
87+
binds = {};
88+
89+
// For a complete list of options see the documentation.
90+
options = {
91+
outFormat: oracledb.OBJECT // query result format
92+
// extendedMetaData: true, // get extra metadata
93+
// fetchArraySize: 100 // internal buffer allocation size for tuning
94+
};
95+
96+
result = await connection.execute(sql, binds, options);
97+
98+
console.log("Column metadata: ", result.metaData);
99+
console.log("Query results: ");
100+
console.log(result.rows);
101+
102+
} catch (err) {
103+
console.error(err);
104+
} finally {
105+
if (connection) {
106+
try {
107+
await connection.close();
108+
} catch (err) {
109+
console.error(err);
110+
}
111+
}
112+
}
113+
}
114+
115+
run();

javascript/node-oracledb/insert1.js

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,8 @@
2121
* DESCRIPTION
2222
* Creates a table and inserts data. Shows DDL and DML
2323
*
24+
* (To insert many records at a time see em_insert1.js)
25+
*
2426
*****************************************************************************/
2527

2628
var async = require('async');

javascript/node-oracledb/select1.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@
2525
* Scripts to create the HR schema can be found at:
2626
* https://github.com/oracle/db-sample-schemas
2727
*
28+
* For an async/await example see selectawait.js
2829
* For a connection pool example see webapp.js
2930
* For a ResultSet example see resultset2.js
3031
* For a query stream example see selectstream.js

javascript/node-oracledb/selectjson.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@
2121
* DESCRIPTION
2222
* Shows some JSON features of Oracle Database 12c.
2323
* Requires Oracle Database 12.1.0.2, which has extensive JSON datatype support.
24-
* See http://docs.oracle.com/database/122/ADJSN/toc.htm
24+
* See https://www.oracle.com/pls/topic/lookup?ctx=dblatest&id=ADJSN
2525
*
2626
* Uses Oracle's sample HR schema.
2727
* Also run demo.sql to create the required extra table or do:

javascript/node-oracledb/selectjsonblob.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@
2121
* DESCRIPTION
2222
* Executes sample insert and query statements using a JSON column with BLOB storage.
2323
* Requires Oracle Database 12.1.0.2, which has extensive JSON datatype support.
24-
* See https://docs.oracle.com/database/122/ADJSN/toc.htm
24+
* See https://www.oracle.com/pls/topic/lookup?ctx=dblatest&id=ADJSN
2525
*
2626
* Use demo.sql to create the required table.
2727
*

javascript/node-oracledb/soda1.js

Lines changed: 133 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,133 @@
1+
/* Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved. */
2+
3+
/******************************************************************************
4+
*
5+
* You may not use the identified files except in compliance with the Apache
6+
* License, Version 2.0 (the "License.")
7+
*
8+
* You may obtain a copy of the License at
9+
* http://www.apache.org/licenses/LICENSE-2.0.
10+
*
11+
* Unless required by applicable law or agreed to in writing, software
12+
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
13+
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14+
*
15+
* See the License for the specific language governing permissions and
16+
* limitations under the License.
17+
*
18+
* NAME
19+
* soda1.js
20+
*
21+
* DESCRIPTION
22+
* Basic Simple Oracle Document Access (SODA) example.
23+
*
24+
* Creates and uses a SODA collection.
25+
* Requires Oracle Database and Client 18.3, or higher.
26+
* The user must have been granted the SODA_APP privilege.
27+
* See https://oracle.github.io/node-oracledb/doc/api.html#sodaoverview
28+
*
29+
* This uses Node 8's async/await syntax but could be rewritten to
30+
* use callbacks.
31+
*
32+
*****************************************************************************/
33+
34+
var oracledb = require('oracledb');
35+
var dbConfig = require('./dbconfig.js');
36+
37+
// The general recommendation for simple SODA usage is to enable autocommit
38+
oracledb.autoCommit = true;
39+
40+
async function run() {
41+
let conn, collection;
42+
43+
try {
44+
let soda, indexSpec, content, doc, key, documents, res;
45+
46+
conn = await oracledb.getConnection(dbConfig);
47+
48+
// Create the parent object for SODA
49+
soda = conn.getSodaDatabase();
50+
51+
// Create a new SODA collection and index
52+
// This will open an existing collection, if the name is already in use.
53+
collection = await soda.createCollection("mycollection");
54+
indexSpec = { "name": "CITY_IDX",
55+
"fields": [ {
56+
"path": "address.city",
57+
"datatype": "string",
58+
"order": "asc" } ] };
59+
await collection.createIndex(indexSpec);
60+
61+
// Insert a document.
62+
// A system generated key is created by default.
63+
content = {name: "Matilda", address: {city: "Melbourne"}};
64+
doc = await collection.insertOneAndGet(content);
65+
key = doc.key;
66+
console.log("The key of the new SODA document is: ", key);
67+
68+
// Fetch the document back
69+
doc = await collection.find().key(key).getOne(); // A SodaDocument
70+
content = doc.getContent(); // A JavaScript object
71+
console.log('Retrieved SODA document as an object:');
72+
console.log(content);
73+
content = doc.getContentAsString(); // A JSON string
74+
console.log('Retrieved SODA document as a string:');
75+
console.log(content);
76+
77+
// Replace document contents
78+
content = {name: "Matilda", address: {city: "Sydney"}};
79+
await collection.find().key(key).replaceOne(content);
80+
81+
// Insert some more documents without caring about their keys
82+
content = {name: "Venkat", address: {city: "Bengaluru"}};
83+
await collection.insertOne(content);
84+
content = {name: "May", address: {city: "London"}};
85+
await collection.insertOne(content);
86+
content = {name: "Sally-Ann", address: {city: "San Francisco"}};
87+
await collection.insertOne(content);
88+
89+
// Find all documents with city names starting with 'S'
90+
console.log('Cities starting with S');
91+
documents = await collection.find()
92+
.filter({"address.city": {"$like": "S%"}})
93+
.getDocuments();
94+
95+
for (let i = 0; i < documents.length; i++) {
96+
content = documents[i].getContent();
97+
console.log(' city is: ', content.address.city);
98+
}
99+
100+
// Count all documents
101+
res = await collection.find().count();
102+
console.log('Collection has ' + res.count + ' documents');
103+
104+
// Remove documents with cities containing 'o'
105+
console.log('Removing documents');
106+
res = await collection.find().filter({"address.city": {"$regex": ".*o.*"}}).remove();
107+
console.log('Dropped ' + res.count + ' documents');
108+
109+
// Count all documents
110+
res = await collection.find().count();
111+
console.log('Collection has ' + res.count + ' documents');
112+
113+
} catch (err) {
114+
console.error(err);
115+
} finally {
116+
if (collection) {
117+
// Drop the collection
118+
let res = await collection.drop();
119+
if (res.dropped) {
120+
console.log('Collection was dropped');
121+
}
122+
}
123+
if (conn) {
124+
try {
125+
await conn.close();
126+
} catch (err) {
127+
console.error(err);
128+
}
129+
}
130+
}
131+
}
132+
133+
run();

0 commit comments

Comments
 (0)