w3resource

Drizzle ORM and SQLite Integration: A Developer's Guide


SQLite with Drizzle ORM: Simplified Database Management

Drizzle ORM is a lightweight TypeScript ORM designed for modern JavaScript and TypeScript projects. It offers a simple, intuitive way to interact with SQLite databases while leveraging the benefits of a fully-typed ORM. Drizzle ORM supports features like type safety, schema migration, and a fluent query builder. This guide demonstrates how to use Drizzle ORM with SQLite, including syntax, examples, and code explanations.


Setting Up Drizzle ORM with SQLite

    1. Install Dependencies
    Install Drizzle ORM and SQLite libraries:

    npm install drizzle-orm sqlite3
    

    2. Initialize Drizzle ORM
    Drizzle ORM requires defining a schema and connecting to a database.


Example: Using Drizzle ORM with SQLite

Step 1: Setting Up the SQLite Database

// Import required modules
const { sqliteTable, drizzle } = require('drizzle-orm/sqlite');
const sqlite3 = require('sqlite3');

// Open SQLite database
const db = new sqlite3.Database('example.db');

// Connect Drizzle to the SQLite database
const drizzleDb = drizzle(db);
  • sqliteTable: Used to define table schemas.
  • drizzle: Connects to the SQLite database.

Step 2: Define a Schema

// Define a schema using Drizzle's `sqliteTable`
const users = sqliteTable('users', {
  id: 'INTEGER PRIMARY KEY AUTOINCREMENT', // Auto-incrementing primary key
  name: 'TEXT NOT NULL',                  // Non-nullable text field
  email: 'TEXT UNIQUE NOT NULL',          // Unique, non-nullable email field
});
  • sqliteTable: Declares a table structure.
  • Fields like id, name, and email are defined with constraints for data integrity.

Step 3: Insert Data

Code:

// Insert a new user
await drizzleDb.insert(users).values({
  name: 'Agata Rosette', 
  email: '[email protected]',
});
console.log('User inserted successfully');
  • insert: Adds a new record to the database.
  • The values method specifies the data to insert.

Step 4: Query Data

Code:

// Fetch all users
const allUsers = await drizzleDb.select().from(users);
console.log('All Users:', allUsers);
  • select: Retrieves records from the database.
  • from: Specifies the table to query.

Step 5: Update Data

Code:

// Update a user's email
await drizzleDb.update(users)
  .set({ email: '[email protected]' }) // Specify the new email
  .where(users.email.equals('[email protected]')); // Update condition
console.log('User updated successfully');
  • update: Modifies existing records.
  • set: Defines the updated values.
  • where: Filters records to update.

Step 6: Delete Data

Code:

// Delete a user by email
await drizzleDb.delete(users)
  .where(users.email.equals('[email protected]')); // Deletion condition
console.log('User deleted successfully');
  • delete: Removes records matching the condition.

Explanation of Key Concepts

    1. Type Safety
    Drizzle ORM ensures queries are type-safe, reducing runtime errors and improving code maintainability.

    2. Fluent API
    The fluent API structure makes it easy to write, read, and modify queries.

    3. Schema Definition
    The schema is defined using TypeScript, allowing tight integration with your codebase.

    4. Minimal Dependencies
    Drizzle ORM works seamlessly with SQLite, ensuring a lightweight stack.


Advantages of Using Drizzle ORM with SQLite

    1. Improved Developer Experience: Simplifies database operations with a clean API.

    2. Flexibility: Drizzle ORM supports dynamic queries and schema migrations.

    3. Scalability: Handles growing datasets effectively with advanced querying capabilities.

Practical Guides to SQLite Snippets and Examples.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/sqlite/snippets/simplify-sqlite-with-drizzle-orm.php