Tauri SQLite ORM
Your First Schema & Query
A Quick Start guide with examples.
This guide provides a complete "Hello World" example, taking you from schema definition to querying data.
We will create a simple users table, add a user to it, and then retrieve that user.
1. Define a Schema
First, let's create the schema.ts file we imported in the setup guide. This file will define our database tables.
Create a file at src/lib/db/schema.ts:
src/lib/db/schema.ts
import { sqliteTable, text, integer } from '@type32/tauri-sqlite-orm';
// Define the 'users' table
export const users = sqliteTable('users', {
id: integer('id').primaryKey().autoincrement(),
name: text('name').notNull(),
email: text('email').unique(),
});
Here, we've defined a table named users with three columns:
id: An auto-incrementing integer that serves as the primary key.name: A non-nullable text field.email: A text field that must be unique across all rows.
2. Run Migrations and Query Data
Now that we have a schema and our db instance, let's use them. You can run this code in a Svelte +page.svelte script, a React useEffect hook, or any async context in your app.
src/lib/demo.ts
import { db } from '$lib/db'; // Adjust path based on your project
import { users } from '$lib/db/schema';
import { eq } from '@type32/tauri-sqlite-orm';
async function runDatabaseDemo() {
// 1. Run migrations
// This checks if the schema in your code has changed and applies
// necessary updates to the database (like creating our new 'users' table).
console.log('Checking for migrations...');
const dirty = await db.migrateIfDirty();
if (dirty) {
console.log('Schema was updated!');
} else {
console.log('Schema is up-to-date.');
}
// 2. Insert a new user
// The .values() method is fully type-safe based on your schema.
// Note: `id` is not required because it's an autoincrementing primary key.
console.log('Inserting a new user...');
await db.insert(users).values({
name: 'Jane Doe',
email: 'jane.doe@example.com'
}).onConflictDoNothing().execute(); // .onConflictDoNothing prevents errors if we run this twice
// 3. Select all users
console.log('Querying for all users...');
const allUsers = await db.select(users).all();
console.log('All users:', allUsers);
// Expected output: [{ id: 1, name: 'Jane Doe', email: 'jane.doe@example.com' }]
// 4. Select a specific user
// Use the `eq` operator to build a 'WHERE' clause.
console.log("Querying for users named 'Jane Doe'...");
const jane = await db.select(users).where(eq(users._.columns.name, 'Jane Doe')).get();
console.log('Found user:', jane);
// Expected output: { id: 1, name: 'Jane Doe', email: 'jane.doe@example.com' }
}
// Run the demo
runDatabaseDemo();
With just a few lines of code, you have created a table, inserted data, and safely queried it back. You are now ready to explore more advanced features.