Skip to content

Commit 55711be

Browse files
committed
docs: make example code standards compliant
1 parent 039932d commit 55711be

1 file changed

Lines changed: 45 additions & 10 deletions

File tree

README.md

Lines changed: 45 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -140,7 +140,7 @@ const db = await Database.load('mydb.db')
140140
// Get all migration events (including ones emitted before listener could be registered)
141141
const events = await db.getMigrationEvents()
142142
for (const event of events) {
143-
console.log(`${event.status}: ${event.dbPath}`)
143+
console.info(`${event.status}: ${event.dbPath}`)
144144
if (event.status === 'failed') {
145145
console.error(`Migration error: ${event.error}`)
146146
}
@@ -156,7 +156,7 @@ import type { MigrationEvent } from '@silvermine/tauri-plugin-sqlite'
156156

157157
await listen<MigrationEvent>('sqlite:migration', (event) => {
158158
const { dbPath, status, migrationCount, error } = event.payload
159-
// status: 'running' | 'completed' | 'failed'
159+
console.info(`Migration ${status} for ${dbPath}: ${migrationCount} migrations`, error)
160160
})
161161
```
162162

@@ -166,16 +166,16 @@ await listen<MigrationEvent>('sqlite:migration', (event) => {
166166
import Database from '@silvermine/tauri-plugin-sqlite'
167167

168168
// Path is relative to app config directory (no sqlite: prefix needed)
169-
const db = await Database.load('mydb.db')
169+
let db = await Database.load('mydb.db')
170170

171171
// With custom configuration
172-
const db = await Database.load('mydb.db', {
172+
db = await Database.load('mydb.db', {
173173
maxReadConnections: 10, // default: 6
174174
idleTimeoutSecs: 60 // default: 30
175175
})
176176

177177
// Lazy initialization (connects on first query)
178-
const db = Database.get('mydb.db')
178+
db = Database.get('mydb.db')
179179
```
180180

181181
### Parameter Binding
@@ -211,7 +211,7 @@ const result = await db.execute(
211211
'INSERT INTO users (name, email) VALUES ($1, $2)',
212212
['Alice', 'alice@example.com']
213213
)
214-
console.log(result.rowsAffected, result.lastInsertId)
214+
console.info(`Inserted ${result.rowsAffected} row(s), ID: ${result.lastInsertId}`)
215215
```
216216

217217
### Read Operations
@@ -224,12 +224,16 @@ const users = await db.fetchAll<User[]>(
224224
'SELECT * FROM users WHERE email LIKE $1',
225225
['%@example.com']
226226
)
227+
console.info(`Found ${users.length} users`)
227228

228229
// Single row (returns undefined if not found, throws if multiple rows)
229230
const user = await db.fetchOne<User>(
230231
'SELECT * FROM users WHERE id = $1',
231232
[42]
232233
)
234+
if (user) {
235+
console.info(`Found user: ${user.name}`)
236+
}
233237
```
234238

235239
### Transactions
@@ -242,6 +246,7 @@ const results = await db.executeTransaction([
242246
['UPDATE accounts SET balance = balance + $1 WHERE id = $2', [100, 2]],
243247
['INSERT INTO transfers (from_id, to_id, amount) VALUES ($1, $2, $3)', [1, 2, 100]]
244248
])
249+
console.info(`Transaction completed: ${results.length} statements executed`)
245250
```
246251

247252
Transactions use `BEGIN IMMEDIATE`, commit on success, and rollback on any failure.
@@ -253,6 +258,11 @@ decide how to proceed.** For example, inserting a record, reading back its
253258
generated ID or other computed values, then using that data in subsequent writes.
254259

255260
```typescript
261+
// Assuming userId, productId, itemTotal are defined in your application context
262+
const userId = 123
263+
const productId = 456
264+
const itemTotal = 99.99
265+
256266
// Begin transaction with initial insert
257267
let tx = await db.beginInterruptibleTransaction([
258268
['INSERT INTO orders (user_id, total) VALUES ($1, $2)', [userId, 0]]
@@ -311,6 +321,7 @@ const results = await db.fetchAll(
311321
mode: 'readOnly'
312322
}
313323
])
324+
console.info(`Found ${results.length} results from cross-database query`)
314325

315326
// Update main database using data from attached database
316327
await db.execute(
@@ -325,6 +336,10 @@ await db.execute(
325336
])
326337

327338
// Atomic writes across multiple databases
339+
// Assuming userId and total are defined in your application context
340+
const userId = 123
341+
const total = 99.99
342+
328343
await db.executeTransaction([
329344
['INSERT INTO main.orders (user_id, total) VALUES ($1, $2)', [userId, total]],
330345
['UPDATE stats.order_count SET count = count + 1', []]
@@ -459,15 +474,15 @@ use tauri_plugin_sqlite::DatabaseWrapper;
459474
use std::path::PathBuf;
460475

461476
// Load a database
462-
let db = DatabaseWrapper::load(PathBuf::from("/path/to/mydb.db"), None).await?;
477+
let mut db = DatabaseWrapper::load(PathBuf::from("/path/to/mydb.db"), None).await?;
463478

464479
// With custom configuration
465480
use tauri_plugin_sqlite::CustomConfig;
466481
let config = CustomConfig {
467482
max_read_connections: Some(10),
468483
idle_timeout_secs: Some(60),
469484
};
470-
let db = DatabaseWrapper::load(PathBuf::from("/path/to/mydb.db"), Some(config)).await?;
485+
db = DatabaseWrapper::load(PathBuf::from("/path/to/mydb.db"), Some(config)).await?;
471486
```
472487

473488
### Basic Operations
@@ -480,6 +495,7 @@ let result = db.execute(
480495
"INSERT INTO users (name, email) VALUES (?, ?)".into(),
481496
vec![json!("Alice"), json!("alice@example.com")]
482497
).await?;
498+
483499
println!("Inserted row {}", result.last_insert_id);
484500

485501
// Read multiple rows
@@ -488,11 +504,17 @@ let users = db.fetch_all(
488504
vec![json!(true)]
489505
).await?;
490506

507+
println!("Found {} users", users.len());
508+
491509
// Read single row
492510
let user = db.fetch_one(
493511
"SELECT * FROM users WHERE id = ?".into(),
494512
vec![json!(42)]
495513
).await?;
514+
515+
if let Some(user_data) = user {
516+
println!("Found user: {:?}", user_data);
517+
}
496518
```
497519

498520
### Simple Transactions
@@ -506,6 +528,8 @@ let results = db.execute_transaction(vec![
506528
("INSERT INTO transfers (from_id, to_id, amount) VALUES (?, ?, ?)", vec![json!(1), json!(2), json!(100)]),
507529
]).await?;
508530

531+
println!("Transaction completed: {} statements executed", results.len());
532+
509533
// Returns Vec<WriteQueryResult> on success, rolls back on any failure
510534
```
511535

@@ -514,6 +538,11 @@ let results = db.execute_transaction(vec![
514538
For transactions that need to read data mid-transaction:
515539

516540
```rust
541+
// Assuming user_id, product_id, item_total are defined in your application context
542+
let user_id = 123;
543+
let product_id = 456;
544+
let item_total = 99.99;
545+
517546
// Begin transaction with initial statements
518547
let mut tx = db.begin_interruptible_transaction()
519548
.execute(vec![
@@ -559,8 +588,13 @@ let results = db.execute_transaction(vec![
559588
}])
560589
.await?;
561590

591+
println!("Cross-database transaction completed: {} statements", results.len());
592+
562593
// Interruptible transaction with attached database
563-
let tx = db.begin_interruptible_transaction()
594+
// Assuming product_id is defined in your application context
595+
let product_id = 789;
596+
597+
let _tx = db.begin_interruptible_transaction()
564598
.attach(vec![AttachedDatabaseSpec {
565599
database_path: "inventory.db".into(),
566600
schema_name: "inv".into(),
@@ -570,6 +604,7 @@ let tx = db.begin_interruptible_transaction()
570604
("UPDATE inv.stock SET quantity = quantity - ? WHERE product_id = ?", vec![json!(1), json!(product_id)]),
571605
])
572606
.await?;
607+
// Continue with transaction operations...
573608
```
574609

575610
### Cleanup
@@ -632,7 +667,7 @@ fn init_tracing() {}
632667
fn main() {
633668
init_tracing();
634669
tauri::Builder::default()
635-
.plugin(tauri_plugin_sqlite::init())
670+
.plugin(tauri_plugin_sqlite::Builder::new().build())
636671
.run(tauri::generate_context!())
637672
.expect("error while running tauri application");
638673
}

0 commit comments

Comments
 (0)