Skip to content

Commit

Permalink
Update README + Add Example website (#17)
Browse files Browse the repository at this point in the history
  • Loading branch information
insipx authored Dec 10, 2024
1 parent 7f0f938 commit 0aa5305
Show file tree
Hide file tree
Showing 34 changed files with 1,981 additions and 510 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -30,3 +30,4 @@ node_modules/**
.direnv/**
.envrc
.DS_Store
examples/web-sqlite/pkg/**
4 changes: 3 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
[package]
name = "diesel-wasm-sqlite"
name = "sqlite-web"
version = "0.0.1"
edition = "2021"
resolver = "2"
Expand Down Expand Up @@ -63,3 +63,5 @@ unsafe-debug-query = []
[build]
target = "wasm32-unknown-unknown"

[package.metadata.wasm-pack.profile.dev.wasm-bindgen]
split-linked-modules = true
69 changes: 17 additions & 52 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,66 +4,31 @@ Use SQLite with Diesel ORM in your web apps!

## Quickstart

Add `diesel-wasm-sqlite` to your project. SQLite is automatically bundled with
the library.
Add `sqlite-web` to your project. SQLite is automatically bundled with the
library.

```toml
[dependencies]
diesel = { version = "2.2" }
diesel-wasm-sqlite = { git = "https://github.com/xmtp/libxmtp", branch = "wasm-backend" }
sqlite-web = { git = "https://github.com/xmtp/sqlite-web-rs", branch = "main" }
wasm-bindgen = "0.2"
```

```rust
use diesel_wasm_sqlite::{connection::WasmSqliteConnection, WasmSqlite};
use wasm_bindgen::prelude::*;

pub const MIGRATIONS: EmbeddedMigrations = embed_migrations!("./tests/web/migrations/");

mod schema {
diesel::table! {
books {
id -> Integer,
title -> Text,
author -> Nullable<Text>,
}
}
}


#[derive(Deserialize, Insertable, Debug, PartialEq, Clone)]
#[diesel(table_name = books)]
pub struct BookForm {
title: String,
author: Option<String>,
}

// SQLite must be instantiated in a web-worker
// to take advantage of OPFS
#[wasm_bindgen]
async fn code_in_web_worker() -> Result<i32, diesel::QueryResult<usize>> {
use schema::books::dsl::*;
// `init_sqlite` sets up OPFS and SQLite. It must be ran before anything else,
// or we crash once we start trying to do queries.
diesel_wasm_sqlite::init_sqlite().await;

// create a new persistent SQLite database with OPFS
let result = WasmSqliteConnection::establish(&format!("test-{}", rng));
let query = insert_into(books).values(vec![
BookForm {
title: "Game of Thrones".into(),
author: Some("George R.R".into()),
},
BookForm {
title: "The Hobbit".into(),
author: Some("J.R.R. Tolkien".into()),
},
]);
Ok(query.execute(conn)?)
}
```
## Try It Out!

Try out SQLite on the web with rust at this
[example app](https://sqlite-web-example.netlify.app/)

## Running the Example

Look in `examples/web-sqlite` for a working example!

Look in `tests/test/web.rs` for a working example!
- run `yarn` in the root of the repo
- navigate to `examples/web-sqlite`
- make sure the [`miniserve`](https://github.com/svenstaro/miniserve) crate is
installed locally
- run `./build.sh && ./run.sh`
- navigate to `localhost:8080`

## Contributing

Expand Down
34 changes: 34 additions & 0 deletions examples/web-sqlite/.vscode/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
{
"rust-analyzer.cargo.sysroot": "discover",
"rust-analyzer.cargo.allTargets": false,
"rust-analyzer.cargo.target": "wasm32-unknown-unknown",
"rust-analyzer.procMacro.enable": true,
"rust-analyzer.diagnostics.enable": true,
"rust-analyzer.diagnostics.disabled": [
"unlinked-file",
"unresolved-macro-call",
"unresolved-proc-macro"
],
"rust-analyzer.procMacro.attributes.enable": true,
"rust-analyzer.procMacro.ignored": {
"async-trait": ["async_trait"],
"napi-derive": ["napi"],
"async-recursion": ["async_recursion"],
"ctor": ["ctor"],
"tokio": ["test"],
"diesel": ["table"],
"wasm-bindgen": ["wasm-bindgen"]
},
"[toml]": {
"editor.defaultFormatter": "tamasfe.even-better-toml"
},
"[typescript]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[javascript]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"[json]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
}
}
49 changes: 49 additions & 0 deletions examples/web-sqlite/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
[package]
name = "example-sqlite-web"
version = "0.0.0"
edition = "2021"
publish = false

[lib]
crate-type = ["cdylib"]

[dependencies]
sqlite-web = { path = "./../../" }
wasm-bindgen = "=0.2.99"
wasm-bindgen-futures = "0.4"
diesel = "2.2"
console_error_panic_hook = { version = "0.1.6" }
diesel_migrations = "2.2"
serde = "1"
serde-wasm-bindgen = "0.6"
anyhow = "1"
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
tracing = "0.1"
tracing-wasm = "0.2"

[dependencies.web-sys]
version = "0.3"
features = [
'console',
'Document',
'HtmlElement',
'HtmlInputElement',
'HtmlTextAreaElement',
'MessageEvent',
'Window',
'Worker',
'WorkerType',
'WorkerOptions'
]

# patch needed until diesel makes a release that includes
# the latest changes
[patch.crates-io]
diesel = { git = "https://github.com/diesel-rs/diesel", branch = "master" }
diesel_derives = { git = "https://github.com/diesel-rs/diesel", branch = "master" }
diesel_migrations = { git = "https://github.com/diesel-rs/diesel", branch = "master" }


[package.metadata.wasm-pack.profile.dev.wasm-bindgen]
# Required for sqlite-web
split-linked-modules = true
1 change: 1 addition & 0 deletions examples/web-sqlite/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
# web-sqlite
26 changes: 26 additions & 0 deletions examples/web-sqlite/build.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
#!/bin/bash

set -ex

# This example requires to *not* create ES modules, therefore we pass the flag
# `--target no-modules`
cd ../../
yarn
cd examples/web-sqlite

curl -L --proto '=https' --tlsv1.2 -sSf https://raw.githubusercontent.com/cargo-bins/cargo-binstall/main/install-from-binstall-release.sh | bash
cargo binstall wasm-bindgen-cli

RUSTFLAGS="-Ctarget-feature=+bulk-memory,+mutable-globals,+reference-types" cargo build \
--release --target wasm32-unknown-unknown

wasm-bindgen ./target/wasm32-unknown-unknown/release/example_sqlite_web.wasm \
--out-dir ./pkg --split-linked-modules --target web
rm pkg/package.json
yarn wasm-opt ./pkg/example_sqlite_web_bg.wasm -o ./pkg/example_sqlite_web_bg.wasm-opt.wasm -Oz

if [[ $? -eq 0 ]]; then
mv ./pkg/example_sqlite_web_bg.wasm-opt.wasm ./pkg/example_sqlite_web_bg.wasm
else
echo "wasm-opt failed"
fi
1 change: 1 addition & 0 deletions examples/web-sqlite/css/attribution.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
CSS provided by https://github.com/matifandy8/NeoBrutalismCSS/tree/main
1 change: 1 addition & 0 deletions examples/web-sqlite/css/brutalist.css

Large diffs are not rendered by default.

35 changes: 35 additions & 0 deletions examples/web-sqlite/css/style.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
body {
width: 100%;
height: 100%;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
font-family: "Century Gothic", CenturyGothic, Geneva, AppleGothic, sans-serif;
}

#wrapper {
width: 50%;
display: flex;
flex-direction: row;
align-items: center;
justify-content: center;
}

#div-wrapper {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
padding: 2em;
}

#inputNumber {
text-align: center;
}

#resultField {
text-align: center;
height: 1em;
padding-top: 0.2em;
}
8 changes: 8 additions & 0 deletions examples/web-sqlite/diesel.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
# For documentation on how to configure this file,
# see https://diesel.rs/guides/configuring-diesel-cli

[print_schema]
file = "src/storage/encrypted_store/schema.rs"

[migrations_directory]
dir = "migrations"
57 changes: 57 additions & 0 deletions examples/web-sqlite/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Simple Post Manager</title>
<link rel="stylesheet" href="css/style.css">
<link rel="stylesheet" href="css/brutalist.css" />
</head>
<body>
<div id = "div-wrapper">
<H2>Database</h2>
<h4>web-sqlite-rs-test-db.db3</h4>
</div>
<div id="wrapper">
<div>
<div id = "div-wrapper">
<div>
<label for="title">Title:</label>
<input type="text" id="title" class="nb-input default" required>
</div>
<div>
<label for="body">Body:</label>
<textarea id="body" class="nb-input default" rows="4" required></textarea>
</div>
<div>
<label for="published">
<input type="checkbox" class="nb-checkbox" id="published"> Published
</label>
</div>
<button id="create-post-btn" type="button" class="nb-button blue">Create Post</button>
</div>
</div>
<div>
<div id = "div-wrapper">
<input type="text" id="post-id" class="nb-input default" required>
<button id="delete-post-btn" type="button" class="nb-button blue">Delete Post</button>
</div>
</div>
<div id = "div-wrapper">
<button id="list-posts-btn" type="button" class="nb-button blue">List Posts</button>
</div>
<div id = "div-wrapper">
<button id="clear-posts-btn" type="button" class="nb-button blue">Clear</button>
</div>
</div>
<div>
<!-- List of Posts -->
<div>
<h2>Posts</h2>
<hr>
<div id="posts-container" class="grid"></div>
</div>
</div>
<script type="module" src="./index.js"></script>
</body>
</html>
18 changes: 18 additions & 0 deletions examples/web-sqlite/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
// We only need `startup` here which is the main entry point
// In theory, we could also use all other functions/struct types from Rust which we have bound with
// `#[wasm_bindgen]`
import init, { startup } from "./pkg/example_sqlite_web.js";

async function run_wasm() {
// Load the Wasm file by awaiting the Promise returned by `wasm_bindgen`
// `wasm_bindgen` was imported in `index.html`
await init();

console.log("index.js loaded");

// Run main Wasm entry point
// This will create a worker from within our Rust code compiled to Wasm
startup();
}

run_wasm();
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
DROP TABLE posts
6 changes: 6 additions & 0 deletions examples/web-sqlite/migrations/2024-12-09-190250_posts/up.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
CREATE TABLE posts (
id INTEGER NOT NULL PRIMARY KEY,
title VARCHAR NOT NULL,
body TEXT NOT NULL,
published BOOLEAN NOT NULL DEFAULT 0
)
5 changes: 5 additions & 0 deletions examples/web-sqlite/netlify.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
[[headers]]
for = "/*"
[headers.values]
Cross-Origin-Embedder-Policy = "require-corp"
Cross-Origin-Opener-Policy = "same-origin"
Loading

0 comments on commit 0aa5305

Please sign in to comment.