Skip to content

Commit c8242ff

Browse files
kravets-levkoJesse
andauthored
Add a query cancelling example (#42)
* Add a query cancelling example * Update examples/cancel_operation.js Co-authored-by: Jesse <jwhitehouse@airpost.net> Co-authored-by: Jesse <jwhitehouse@airpost.net>
1 parent e313eb1 commit c8242ff

File tree

1 file changed

+70
-0
lines changed

1 file changed

+70
-0
lines changed

examples/cancel_operation.js

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
const { DBSQLClient } = require('../');
2+
3+
const client = new DBSQLClient();
4+
5+
const host = '****.databricks.com';
6+
const path = '/sql/1.0/endpoints/****';
7+
const token = 'dapi********************************';
8+
9+
async function getQueryResult(operation) {
10+
const utils = DBSQLClient.utils;
11+
12+
await utils.waitUntilReady(operation, false, () => {});
13+
console.log('Fetching data...');
14+
await utils.fetchAll(operation);
15+
await operation.close();
16+
17+
return utils.getResult(operation).getValue();
18+
}
19+
20+
async function cancelQuery(operation) {
21+
return new Promise((resolve, reject) => {
22+
operation
23+
.cancel()
24+
.then((status) => {
25+
if (status.success()) {
26+
resolve();
27+
} else {
28+
reject(new Error(status.getInfo().join('\n')));
29+
}
30+
})
31+
.catch(reject);
32+
});
33+
}
34+
35+
client
36+
.connect({ host, path, token })
37+
.then(async (client) => {
38+
const session = await client.openSession();
39+
40+
// Execute long-running query
41+
console.log('Running query...');
42+
const queryOperation = await session.executeStatement(
43+
`
44+
SELECT id
45+
FROM RANGE(100000000)
46+
ORDER BY RANDOM() + 2 asc
47+
`,
48+
{ runAsync: true },
49+
);
50+
getQueryResult(queryOperation)
51+
.then((result) => console.log(`Query returned ${result.length} row(s)`))
52+
.catch((error) => console.log(`Failed to load data: ${error.message}`));
53+
54+
// Cancel query
55+
cancelQuery(queryOperation)
56+
.then(() => console.log('Query cancelled'))
57+
.catch((error) => console.log(`Failed to cancel query: ${error.message}`));
58+
59+
// Expected output in console:
60+
//
61+
// > node examples/cancel_operation.js Node 16.13.1
62+
// Running query...
63+
// Query cancelled
64+
// Failed to load data: The operation was canceled by a client
65+
66+
await session.close();
67+
})
68+
.catch((error) => {
69+
console.log(error);
70+
});

0 commit comments

Comments
 (0)