1.0.10 • Published 6 months ago

@drizzle-adapter/core v1.0.10

Weekly downloads
-
License
-
Repository
-
Last release
6 months ago

@drizzle-adapter/core

A TypeScript-first Object-Oriented adapter layer for Drizzle ORM that provides a unified interface across different database drivers.

Overview

The @drizzle-adapter/core package serves as an abstraction layer over Drizzle ORM, providing a unified interface that works consistently across different database drivers. This abstraction allows you to write database-agnostic code that can work with any supported database system without modification.

The key concept is that while different database drivers in Drizzle ORM may offer varying features and slightly different APIs, this adapter layer normalizes these differences, ensuring your code remains portable across different database systems.

Key Features

  • Unified Interface: Write your database code once and switch between different databases without changing your application code
  • Type Safety: Full TypeScript support with strict typing
  • Dependency Injection Ready: Clean architecture with interfaces suitable for dependency injection
  • Driver Agnostic: Support for multiple database drivers including MySQL, PostgreSQL, SQLite, and more
  • Consistent API: Normalized interface across different database systems
  • Automatic Driver Loading: Factory pattern that automatically loads and configures the appropriate driver

Installation

pnpm install @drizzle-adapter/core

Plus the driver-specific package you want to use:

pnpm install @drizzle-adapter/mysql2 # for MySQL
# or
pnpm install @drizzle-adapter/node-postgres # for PostgreSQL
# or
pnpm install @drizzle-adapter/libsql # for SQLite
# etc.

Usage

  1. Configure your database connection:
import { TypeDrizzleDatabaseConfig } from '@drizzle-adapter/core';

const config: TypeDrizzleDatabaseConfig = {
  DATABASE_DRIVER: 'mysql2', // or 'node-postgres', 'libsql', etc.
  DATABASE_URL: process.env.DATABASE_URL
};
  1. Create an adapter instance using the core factory:
import { DrizzleAdapterFactory } from '@drizzle-adapter/core';

// The factory automatically loads the appropriate driver
const factory = new DrizzleAdapterFactory();
const adapter = factory.create(config);
  1. Define your schema:
// The data types are abstracted, so this works with any database
const dataTypes = adapter.getDataTypes();

const users = dataTypes.dbTable('users', {
  id: dataTypes.dbSerial('id').primaryKey(),
  name: dataTypes.dbText('name').notNull(),
  email: dataTypes.dbText('email').notNull(),
  createdAt: dataTypes.dbTimestamp('created_at').defaultNow()
});
  1. Use the adapter for database operations:
import { eq } from 'drizzle-orm';

// Connect to the database (works the same for any driver)
const connection = await adapter.getConnection();

// Get the database client
const client = connection.getClient();

try {
  // All these operations work consistently across different databases
  
  // Insert
  await client.insert(users).values({
    name: 'John Doe',
    email: 'john@example.com'
  });

  // Query
  const user = await client
    .select()
    .from(users)
    .where(eq(users.email, 'john@example.com'))
    .limit(1);

  // Update
  await client
    .update(users)
    .set({ name: 'John Smith' })
    .where(eq(users.email, 'john@example.com'));

  // Delete
  await client
    .delete(users)
    .where(eq(users.email, 'john@example.com'));

} finally {
  // Always disconnect
  await connection.disconnect();
}
  1. Example Repository Pattern (Database Agnostic):
import { DrizzleAdapterInterface, DrizzleClientInterface } from '@drizzle-adapter/core';
import { eq } from 'drizzle-orm';

interface User {
  id: number;
  name: string;
  email: string;
}

class UserRepository {
  private client: DrizzleClientInterface;
  private users: any; // Your users table schema

  constructor(private adapter: DrizzleAdapterInterface) {
    // Schema definition works the same regardless of the database
    const dataTypes = adapter.getDataTypes();
    this.users = dataTypes.dbTable('users', {
      id: dataTypes.dbSerial('id').primaryKey(),
      name: dataTypes.dbText('name').notNull(),
      email: dataTypes.dbText('email').notNull()
    });
  }

  async connect(): Promise<void> {
    const connection = await this.adapter.getConnection();
    this.client = connection.getClient();
  }

  async disconnect(): Promise<void> {
    await this.adapter.getConnection().disconnect();
  }

  async findById(id: number): Promise<User | null> {
    const result = await this.client
      .select()
      .from(this.users)
      .where(eq(this.users.id, id))
      .limit(1);
    
    return result[0] || null;
  }

  async create(user: Omit<User, 'id'>): Promise<User> {
    const result = await this.client
      .insert(this.users)
      .values(user)
      .returning();
    
    return result[0];
  }

  async update(id: number, data: Partial<Omit<User, 'id'>>): Promise<User | null> {
    const result = await this.client
      .update(this.users)
      .set(data)
      .where(eq(this.users.id, id))
      .returning();
    
    return result[0] || null;
  }

  async delete(id: number): Promise<void> {
    await this.client
      .delete(this.users)
      .where(eq(this.users.id, id));
  }
}

// Usage example (works with any database):
async function main() {
  const factory = new DrizzleAdapterFactory();
  
  // MySQL configuration
  const mysqlAdapter = factory.create({
    DATABASE_DRIVER: 'mysql2',
    DATABASE_URL: process.env.MYSQL_URL
  });

  // PostgreSQL configuration
  const pgAdapter = factory.create({
    DATABASE_DRIVER: 'node-postgres',
    DATABASE_URL: process.env.POSTGRES_URL
  });

  // The same repository works with any adapter
  const mysqlRepo = new UserRepository(mysqlAdapter);
  const pgRepo = new UserRepository(pgAdapter);

  // Use either repository - the code is exactly the same
  await mysqlRepo.connect();
  try {
    const user = await mysqlRepo.create({
      name: 'John Doe',
      email: 'john@example.com'
    });
  } finally {
    await mysqlRepo.disconnect();
  }
}

DrizzleAdapterSingleton

The DrizzleAdapterSingleton class implements the Singleton design pattern, ensuring that only one instance of DrizzleAdapterInterface can exist. This is useful for managing a single adapter instance throughout your application.

Methods

  • setInstance(instance: DrizzleAdapterInterface | undefined): Sets the singleton instance of the adapter.
  • getInstance(): Returns the singleton instance of the adapter. Throws an error if the instance has not been set.

Usage Example

import { DrizzleAdapterSingleton } from '@drizzle-adapter/core';
import type { DrizzleAdapterInterface } from '@drizzle-adapter/core';

// Setting the instance
DrizzleAdapterSingleton.setInstance(myAdapter);

// Getting the instance
const adapter = DrizzleAdapterSingleton.getInstance();

Use Cases

  • Global Access: Use DrizzleAdapterSingleton when you need a globally accessible adapter instance throughout your application.
  • Configuration Management: Set the adapter instance once during application initialization and access it from anywhere in your codebase without passing it around.

Supported Drivers

The Drizzle Adapter ecosystem includes adapters for:

  • MySQL (@drizzle-adapter/mysql2)
  • PostgreSQL (@drizzle-adapter/node-postgres, @drizzle-adapter/postgres-js)
  • SQLite (@drizzle-adapter/libsql)
  • Cloudflare D1 (@drizzle-adapter/d1)
  • Neon (@drizzle-adapter/neon-http)
  • TiDB (@drizzle-adapter/tidb-serverless)
  • PGLite (@drizzle-adapter/pglite)

Contributing

Contributions are welcome! Here's how you can help:

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add some amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

Related Packages