Drizzle ORM and SQLite Simplified for Database Management
Using SQLite with Drizzle ORM for Database Management
Drizzle ORM is a modern TypeScript-based Object-Relational Mapping (ORM) library designed for simplicity and type safety. It works well with SQLite for applications requiring lightweight database operations. With Drizzle ORM, developers can manage SQLite databases using a clean and declarative syntax while enjoying TypeScript's type-checking features.
Benefits of Drizzle ORM with SQLite
1. Type Safety: Ensures accurate SQL queries with TypeScript support.
2. Declarative API: Simplifies database interactions using intuitive methods.
3. Lightweight: Perfectly complements SQLite's minimalistic nature.
4. Cross-platform: Drizzle ORM works seamlessly in both server-side and edge environments.
Setting Up Drizzle ORM with SQLite
Prerequisites
1. Node.js Installed
2. SQLite Installed
3. Install Required Packages
Use the following command to install Drizzle and SQLite:
npm install drizzle-orm sqlite3
Step 1: Configuring Drizzle with SQLite
Code:
// Import required modules
import { sqliteTable, sqliteColumn, drizzle } from 'drizzle-orm/sqlite';
import { Database } from 'sqlite3';
// Initialize SQLite database connection
const sqlite = new Database('my_database.db'); // SQLite database file
const db = drizzle(sqlite); // Wrap SQLite connection with Drizzle ORM
// Define a Drizzle ORM table
const users = sqliteTable('users', {
id: sqliteColumn('integer').primaryKey().autoIncrement(),
name: sqliteColumn('text').notNull(),
email: sqliteColumn('text').notNull().unique(),
createdAt: sqliteColumn('text').default(() => new Date().toISOString()),
});
Explanation:
- sqliteTable: Defines an SQLite table with schema.
- sqliteColumn: Specifies columns with constraints like primaryKey or notNull.
- drizzle: Wraps the SQLite connection, providing ORM features.
Step 2: Creating and Inserting Data
Code:
// Function to create the table
async function createTable() {
await db.execute(sql`CREATE TABLE IF NOT EXISTS ${users}`);
console.log('Users table created successfully');
}
// Function to insert a user into the table
async function addUser(name: string, email: string) {
await db.insert(users).values({ name, email });
console.log('User added successfully');
}
// Call functions
createTable();
addUser('Alice', '[email protected]');
Explanation:
- db.execute: Executes raw SQL queries.
- db.insert: Inserts data into the specified table.
- Uses template literals (sql) for SQL query composition.
Step 3: Querying Data from SQLite
Code:
// Function to retrieve users
async function fetchUsers() {
const result = await db.select(users).all();
console.log('Users:', result);
}
// Call function
fetchUsers();
Explanation:
- db.select: Fetches rows from the specified table.
- .all(): Retrieves all matching records.
Step 4: Updating Data
Code:
// Function to update user data
async function updateUser(id: number, name: string) {
await db.update(users).set({ name }).where(users.id.eq(id));
console.log('User updated successfully');
}
// Call function
updateUser(1, 'Alice Smith');
Explanation:
- db.update: Updates a table with new values.
- .where: Specifies conditions for the update.
Step 5: Deleting Data
Code:
// Function to delete a user
async function deleteUser(id: number) {
await db.delete(users).where(users.id.eq(id));
console.log('User deleted successfully');
}
// Call function
deleteUser(1);
Explanation:
- db.delete: Deletes rows from the table.
- .where: Specifies conditions for the delete operation.
Advantages of Drizzle ORM with SQLite
1. Simplified Schema Management: Drizzle’s declarative approach reduces boilerplate code.
2. Enhanced Productivity: Type-safe queries minimize runtime errors.
3. Scalability: Ideal for projects of varying sizes.
4. Modern Syntax: Leverages TypeScript features for better development practices.
Use Cases
- 1. Local Databases: Applications requiring lightweight, on-device storage.
- 2. Prototyping: Quickly building proof-of-concept projects.
- 3. Edge Computing: Combining SQLite’s small footprint with Drizzle’s simplicity.
Conclusion
Using Drizzle ORM with SQLite brings the best of modern ORM techniques to lightweight database solutions. Its simplicity, combined with TypeScript type-safety, makes it an excellent choice for developers seeking a seamless and efficient database management experience.
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/drizzle-orm-sqlite.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics