npm package: @seedts/adapters
Description: Adapter implementations for SeedTS
Author: SeedTS Contributors
Latest version: 0.1.1

# @seedts/adapters

Base adapter classes for SeedTS. Contains only framework-agnostic base classes with **zero external database dependencies**.

## Installation

```bash
npm install @seedts/adapters
# or
pnpm add @seedts/adapters
# or
yarn add @seedts/adapters
```

## What's Included

This package provides:

- **BaseAdapter** - Abstract base class for creating custom adapters
- **MemoryAdapter** - In-memory adapter for testing and development

## Database-Specific Adapters

Database-specific adapters are **separate packages**. Install only what you need:

- [@seedts/adapter-sqlite](../adapter-sqlite) - SQLite adapter (requires `better-sqlite3`)
- [@seedts/adapter-postgresql](../adapter-postgresql) - PostgreSQL adapter (requires `pg`)
- [@seedts/adapter-mysql](../adapter-mysql) - MySQL adapter (requires `mysql2`)

This separation ensures:
- ✅ **Zero dependencies** - Core package has no database drivers
- ✅ **Opt-in** - Install only adapters you need
- ✅ **Smaller bundles** - No unused database libraries
- ✅ **Independent versioning** - Adapters can version independently

## Available Adapters

### MemoryAdapter

An in-memory adapter for testing and development. **No external dependencies required**.

```typescript
import { MemoryAdapter } from '@seedts/adapters';

const adapter = new MemoryAdapter();
```

**Features:**
- Fast in-memory storage
- Perfect for testing
- Transaction support with snapshot/restore
- No external dependencies
- Zero configuration

### BaseAdapter

Abstract base class for creating custom adapters.

```typescript
import { BaseAdapter } from '@seedts/adapters';

export class MyCustomAdapter extends BaseAdapter {
  name = 'my-custom-adapter';

  async insert(tableName: string, data: any[]): Promise<any[]> {
    // Your implementation
  }

  async update(tableName: string, data: any[]): Promise<any[]> {
    // Your implementation
  }

  async delete(tableName: string, ids: any[]): Promise<void> {
    // Your implementation
  }

  async query(tableName: string, conditions?: any): Promise<any[]> {
    // Your implementation
  }
}
```

## Creating Custom Adapters

To create a custom adapter, extend the `BaseAdapter` class and implement the required methods:

```typescript
import { BaseAdapter } from '@seedts/adapters';
import type { SeedAdapter } from '@seedts/types';

export class PostgresAdapter extends BaseAdapter implements SeedAdapter {
  name = 'postgres';

  constructor(private config: PostgresConfig) {
    super();
  }

  async insert(tableName: string, data: any[]): Promise<any[]> {
    // Insert data into PostgreSQL
    return data;
  }

  async update(tableName: string, data: any[]): Promise<any[]> {
    // Update data in PostgreSQL
    return data;
  }

  async delete(tableName: string, ids: any[]): Promise<void> {
    // Delete data from PostgreSQL
  }

  async query(tableName: string, conditions?: any): Promise<any[]> {
    // Query data from PostgreSQL
    return [];
  }

  async beginTransaction(): Promise<void> {
    await super.beginTransaction();
    // Start PostgreSQL transaction
  }

  async commit(): Promise<void> {
    await super.commit();
    // Commit PostgreSQL transaction
  }

  async rollback(): Promise<void> {
    await super.rollback();
    // Rollback PostgreSQL transaction
  }

  async disconnect(): Promise<void> {
    // Close database connection
  }
}
```

## API Reference

### SeedAdapter Interface

All adapters implement the `SeedAdapter` interface from `@seedts/types`:

```typescript
type SeedAdapter<T = any> = {
  name: string;
  insert(tableName: string, data: T[]): Promise<T[]>;
  update(tableName: string, data: T[]): Promise<T[]>;
  delete(tableName: string, ids: any[]): Promise<void>;
  query(tableName: string, conditions?: any): Promise<T[]>;
  beginTransaction(): Promise<void>;
  commit(): Promise<void>;
  rollback(): Promise<void>;
  supportsTransactions(): boolean;
  truncate?(tableName: string): Promise<void>;
  disconnect?(): Promise<void>;
};
```

### BaseAdapter Methods

The `BaseAdapter` class provides default implementations for transaction management:

- `beginTransaction()`: Begin a transaction
- `commit()`: Commit the current transaction
- `rollback()`: Rollback the current transaction
- `supportsTransactions()`: Returns `true` by default
- `truncate(tableName)`: Truncate a table (must be implemented by subclass)
- `disconnect()`: Close database connection (optional)

## Examples

### Using MemoryAdapter

```typescript
import { MemoryAdapter } from '@seedts/adapters';

const adapter = new MemoryAdapter();

// Insert data
const users = await adapter.insert('users', [
  { name: 'Alice', email: 'alice@example.com' },
  { name: 'Bob', email: 'bob@example.com' },
]);

// Query data
const allUsers = await adapter.query('users');
const alice = await adapter.query('users', { name: 'Alice' });

// Update data
await adapter.update('users', [
  { id: 1, name: 'Alice Updated', email: 'alice.new@example.com' },
]);

// Delete data
await adapter.delete('users', [2]);

// Transactions
await adapter.beginTransaction();
try {
  await adapter.insert('users', [{ name: 'Charlie' }]);
  await adapter.commit();
} catch (error) {
  await adapter.rollback();
}
```

### Using SqliteAdapter

```typescript
import { SqliteAdapter } from '@seedts/adapters';

const adapter = new SqliteAdapter({
  filename: './data/myapp.db',
});

// Create table
adapter.exec(`
  CREATE TABLE IF NOT EXISTS users (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    name TEXT NOT NULL,
    email TEXT NOT NULL UNIQUE,
    created_at DATETIME DEFAULT CURRENT_TIMESTAMP
  )
`);

// Insert data
const users = await adapter.insert('users', [
  { name: 'Alice', email: 'alice@example.com' },
  { name: 'Bob', email: 'bob@example.com' },
]);

console.log(users[0].id); // Auto-generated ID

// Transactions
await adapter.beginTransaction();
try {
  await adapter.insert('users', [{ name: 'Charlie', email: 'charlie@example.com' }]);
  await adapter.commit();
} catch (error) {
  await adapter.rollback();
  throw error;
}

// Clean up
await adapter.disconnect();
```

## Testing

All adapters include comprehensive test suites:

```bash
pnpm test
```

## License

MIT