-
Notifications
You must be signed in to change notification settings - Fork 44
Async SQLite example #73
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,5 +1,6 @@ | ||
[workspace] | ||
members = [ | ||
"examples/async-sqlite", | ||
"examples/hello-world", | ||
"examples/cpu-count", | ||
] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,18 @@ | ||
[package] | ||
name = "async-sqlite" | ||
version = "0.1.0" | ||
description = "Neon Async SQLite" | ||
license = "MIT" | ||
edition = "2018" | ||
exclude = ["index.node"] | ||
|
||
[lib] | ||
crate-type = ["cdylib"] | ||
|
||
[dependencies] | ||
rusqlite = "0.25" | ||
|
||
[dependencies.neon] | ||
version = "0.8" | ||
default-features = false | ||
features = ["napi-6", "event-queue-api", "try-catch-api"] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,55 @@ | ||
# Async SQLite | ||
|
||
The Async SQLite example implements a simple database in Rust with a JavaScript API. | ||
|
||
## Usage | ||
|
||
```js | ||
const Database = require("."); | ||
|
||
(async () => { | ||
const db = new Database(); | ||
|
||
const id = await db.insert("Marty McFly"); | ||
const name = await db.byId(id); | ||
|
||
console.log(name); | ||
})(); | ||
``` | ||
|
||
## Design | ||
|
||
### Rust | ||
|
||
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. | ||
|
||
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. | ||
|
||
#### Threads and Channels | ||
|
||
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. | ||
|
||
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. | ||
|
||
#### `JsBox` | ||
|
||
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. | ||
|
||
#### Channels and `EventQueue` | ||
|
||
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. | ||
|
||
#### `Root` | ||
|
||
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. | ||
|
||
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. | ||
|
||
### JavaScript | ||
|
||
[thread]: https://doc.rust-lang.org/std/thread/ | ||
[mpsc]: https://doc.rust-lang.org/std/sync/mpsc/index.html | ||
[jsbox]: https://docs.rs/neon/0.8.1-napi/neon/types/struct.JsBox.html | ||
[eventqueue]: https://docs.rs/neon/0.8.1-napi/neon/event/struct.EventQueue.html | ||
[handle]: https://docs.rs/neon/0.8.1-napi/neon/handle/struct.Handle.html | ||
[root]: https://docs.rs/neon/0.8.1-napi/neon/handle/struct.Root.html |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,33 @@ | ||
"use strict"; | ||
|
||
const { promisify } = require("util"); | ||
|
||
const { databaseNew, databaseClose, databaseInsert, databaseGetById } = require("./index.node"); | ||
|
||
// Convert the DB methods from using callbacks to returning promises | ||
const databaseInsertAsync = promisify(databaseInsert); | ||
const databaseGetByIdAsync = promisify(databaseGetById); | ||
|
||
// Wrapper class for the boxed `Database` for idiomatic JavaScript usage | ||
class Database { | ||
constructor() { | ||
this.db = databaseNew(); | ||
} | ||
|
||
// Wrap each method with a delegate to `this.db` | ||
// This could be node in several other ways, for example binding assignment | ||
// in the constructor | ||
insert(name) { | ||
return databaseInsertAsync.call(this.db, name); | ||
} | ||
|
||
byId(id) { | ||
return databaseGetByIdAsync.call(this.db, id); | ||
} | ||
|
||
close() { | ||
databaseClose.call(this.db); | ||
} | ||
} | ||
|
||
module.exports = Database; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,28 @@ | ||
{ | ||
"name": "async-sqlite", | ||
"version": "0.1.0", | ||
"description": "Neon Async SQLite", | ||
"main": "index.js", | ||
"scripts": { | ||
"build": "cargo-cp-artifact -nc index.node -- cargo build --message-format=json-render-diagnostics", | ||
"install": "npm run build", | ||
"test": "mocha" | ||
}, | ||
"license": "MIT", | ||
"devDependencies": { | ||
"cargo-cp-artifact": "^0.1", | ||
"mocha": "^8.4.0" | ||
}, | ||
"repository": { | ||
"type": "git", | ||
"url": "git+https://github.com/neon-bindings/examples.git" | ||
}, | ||
"keywords": [ | ||
"Neon", | ||
"Examples" | ||
], | ||
"bugs": { | ||
"url": "https://github.com/neon-bindings/examples/issues" | ||
}, | ||
"homepage": "https://github.com/neon-bindings/examples#readme" | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.