Skip to content

Commit 42564aa

Browse files
authored
Merge pull request #73 from neon-bindings/kv/async-sqlite
Async SQLite example
2 parents 83bf889 + 06ac431 commit 42564aa

File tree

10 files changed

+2340
-13
lines changed

10 files changed

+2340
-13
lines changed

Cargo.lock

Lines changed: 135 additions & 8 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Cargo.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
[workspace]
22
members = [
3+
"examples/async-sqlite",
34
"examples/hello-world",
45
"examples/cpu-count",
56
]

README.md

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -12,12 +12,13 @@ All examples are for [`napi-backend`][napi-migration]. For examples using `legac
1212

1313
## Table of Contents
1414

15-
| Example | Description |
16-
| ---------------------------- | ------------------------------------------ |
17-
| [`cpu-count`][cpu-count] | Return the number of CPUs |
18-
| [`hello-world`][hello-world] | Return a JS String with a greeting message |
19-
15+
| Example | Description |
16+
| ------------------------------ | ------------------------------------------ |
17+
| [`async-sqlite`][async-sqlite] | Async interface to a SQLite database |
18+
| [`cpu-count`][cpu-count] | Return the number of CPUs |
19+
| [`hello-world`][hello-world] | Return a JS String with a greeting message |
2020

21+
[async-sqlite]: examples/async-sqlite
2122
[cpu-count]: examples/cpu-count
2223
[hello-world]: examples/hello-world
2324

examples/async-sqlite/Cargo.toml

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
[package]
2+
name = "async-sqlite"
3+
version = "0.1.0"
4+
description = "Neon Async SQLite"
5+
license = "MIT"
6+
edition = "2018"
7+
exclude = ["index.node"]
8+
9+
[lib]
10+
crate-type = ["cdylib"]
11+
12+
[dependencies]
13+
rusqlite = "0.25"
14+
15+
[dependencies.neon]
16+
version = "0.8"
17+
default-features = false
18+
features = ["napi-6", "event-queue-api", "try-catch-api"]

examples/async-sqlite/README.md

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
# Async SQLite
2+
3+
The Async SQLite example implements a simple database in Rust with a JavaScript API.
4+
5+
## Usage
6+
7+
```js
8+
const Database = require(".");
9+
10+
(async () => {
11+
const db = new Database();
12+
13+
const id = await db.insert("Marty McFly");
14+
const name = await db.byId(id);
15+
16+
console.log(name);
17+
})();
18+
```
19+
20+
## Design
21+
22+
### Rust
23+
24+
SQLite provides a _synchronous_ interface. This means that the current thread is blocked while a query is executing. Ideally, JavaScript would be able to continue executing concurrently with query execution.
25+
26+
The Async SQLite example demonstrates one pattern for moving database operations to a separate thread and asynchronously calling back to JavaScript when the operation has completed.
27+
28+
#### Threads and Channels
29+
30+
Since SQLite is naturally single threaded, our application does not benefit from a thread pool or connection pool when querying the database. Instead, a _single_ rust [thread][thread] is spawned for performing database operations.
31+
32+
Once the database thread is spawned, the JavaScript main thread needs a way to communicate with it. A [multi-producer, single-consumer (mpsc)][mpsc] channel is created. The receiving end is owned by the database thread and the sender is held by JavaScript.
33+
34+
#### `JsBox`
35+
36+
Rust data cannot be directly held by JavaScript. The [`JsBox`][jsbox] provides a mechanism for allowing JavaScript to hold a reference to Rust data and later access it again from Rust.
37+
38+
#### Channels and `EventQueue`
39+
40+
The mpsc channel provides a way for the JavaScript main thread to communicate with the database thread, but it is one-way. In order to complete the callback, the database thread must be able to communicate with the JavaScript main thread. [`EventQueue`][eventqueue] provides a channel for sending these events back.
41+
42+
#### `Root`
43+
44+
The last issue to solve is sending a reference to the JavaScript callback to the database thread and back again before finally calling it. [Handles][handle] to JavaScript values are not `Send`; they cannot escape the scope that created them. The reason they cannot be passed to other threads is because when control is returned back to the JavaScript engine, the garbage collector may determine they are no longer used and free the value.
45+
46+
A [`Root`][root] is a special handle to a JavaScript value that prevents the value from being freed as long as the `Root` has not been dropped. By placing the callback in a `Root`, it can be safely sent across threads and finally accessed and called when back on the JavaScript main thread.
47+
48+
### JavaScript
49+
50+
[thread]: https://doc.rust-lang.org/std/thread/
51+
[mpsc]: https://doc.rust-lang.org/std/sync/mpsc/index.html
52+
[jsbox]: https://docs.rs/neon/0.8.1-napi/neon/types/struct.JsBox.html
53+
[eventqueue]: https://docs.rs/neon/0.8.1-napi/neon/event/struct.EventQueue.html
54+
[handle]: https://docs.rs/neon/0.8.1-napi/neon/handle/struct.Handle.html
55+
[root]: https://docs.rs/neon/0.8.1-napi/neon/handle/struct.Root.html

examples/async-sqlite/index.js

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
"use strict";
2+
3+
const { promisify } = require("util");
4+
5+
const { databaseNew, databaseClose, databaseInsert, databaseGetById } = require("./index.node");
6+
7+
// Convert the DB methods from using callbacks to returning promises
8+
const databaseInsertAsync = promisify(databaseInsert);
9+
const databaseGetByIdAsync = promisify(databaseGetById);
10+
11+
// Wrapper class for the boxed `Database` for idiomatic JavaScript usage
12+
class Database {
13+
constructor() {
14+
this.db = databaseNew();
15+
}
16+
17+
// Wrap each method with a delegate to `this.db`
18+
// This could be node in several other ways, for example binding assignment
19+
// in the constructor
20+
insert(name) {
21+
return databaseInsertAsync.call(this.db, name);
22+
}
23+
24+
byId(id) {
25+
return databaseGetByIdAsync.call(this.db, id);
26+
}
27+
28+
close() {
29+
databaseClose.call(this.db);
30+
}
31+
}
32+
33+
module.exports = Database;

examples/async-sqlite/package.json

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
{
2+
"name": "async-sqlite",
3+
"version": "0.1.0",
4+
"description": "Neon Async SQLite",
5+
"main": "index.js",
6+
"scripts": {
7+
"build": "cargo-cp-artifact -nc index.node -- cargo build --message-format=json-render-diagnostics",
8+
"install": "npm run build",
9+
"test": "mocha"
10+
},
11+
"license": "MIT",
12+
"devDependencies": {
13+
"cargo-cp-artifact": "^0.1",
14+
"mocha": "^8.4.0"
15+
},
16+
"repository": {
17+
"type": "git",
18+
"url": "git+https://github.com/neon-bindings/examples.git"
19+
},
20+
"keywords": [
21+
"Neon",
22+
"Examples"
23+
],
24+
"bugs": {
25+
"url": "https://github.com/neon-bindings/examples/issues"
26+
},
27+
"homepage": "https://github.com/neon-bindings/examples#readme"
28+
}

0 commit comments

Comments
 (0)