npm package: @suman-malik-repo/repodb-client
Description: A lightweight and powerful client SDK for LiteBase Cloud Database. Use SQLite like MySQL in the cloud.
Author: LiteBase Team
Latest version: 1.0.5

# LiteBase Client

A powerful, MySQL-like client SDK for **LiteBase Cloud** (SQLite-as-a-Service).
Connect to your cloud SQLite databases over HTTP with a familiar API.

## Installation

```bash
npm install @suman-malik-repo/repodb-client
```

## Quick Start

```javascript
import LiteBase from '@suman-malik-repo/repodb-client';

// Initialize client
const db = new LiteBase({
  host: 'https://your-litebase-server.com', // Your LiteBase instance URL
  token: 'db_token_...' // Your database token
});

// Run a query
const users = await db.select('SELECT * FROM users WHERE active = ?', [1]);
console.log(users);
```

## Authentication

You can authenticate using either a **Database Token** (recommended) or **Credentials**.

### Option 1: Database Token (Best for Apps)
Generate a token from your LiteBase dashboard.

```javascript
const db = new LiteBase({
  host: 'https://api.litebase.com',
  token: 'your_db_token'
});
```

### Option 2: Credentials (Admin/Owner)
Connect using your account credentials and database name.

```javascript
const db = new LiteBase({
  host: 'https://api.litebase.com',
  dbName: 'my_database',
  username: 'my_username',
  password: 'my_password'
});
```

## MySQL Compatibility Mode

LiteBase supports MySQL syntax translation! When enabled, you can write queries using MySQL syntax and they will be automatically translated to SQLite.

### Enable MySQL Mode

**Option 1: Constructor (Default for all queries)**
```javascript
const db = new LiteBase({
  host: 'https://api.litebase.com',
  token: 'your_db_token',
  dialect: 'mysql' // Enable MySQL compatibility
});

// Now all queries use MySQL syntax
await db.query("CREATE TABLE users (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(100))");
await db.query("SELECT NOW(), UUID()");
await db.query("SELECT * FROM users LIMIT 10, 20"); // MySQL offset syntax
```

**Option 2: Per-Query Override**
```javascript
const db = new LiteBase({
  host: 'https://api.litebase.com',
  token: 'your_db_token'
});

// Use MySQL syntax for specific queries
await db.query(
  "INSERT INTO users (created_at) VALUES (NOW())", 
  [], 
  { dialect: 'mysql' }
);
```

**Option 3: Runtime Toggle**
```javascript
db.setDialect('mysql');
await db.query("SELECT NOW()"); // Uses MySQL mode

db.setDialect('sqlite');
await db.query("SELECT datetime('now')"); // Back to SQLite mode
```

### Supported MySQL Features

| MySQL Syntax | SQLite Translation |
|--------------|-------------------|
| `INT AUTO_INCREMENT` | `INTEGER AUTOINCREMENT` |
| `VARCHAR(n)`, `CHAR(n)` | `TEXT` |
| `TINYINT`, `BIGINT` | `INTEGER` |
| `BOOLEAN` | `INTEGER` |
| `ENUM('a','b')` | `TEXT` with CHECK constraint |
| `NOW()` | `datetime('now')` |
| `UUID()` | `lower(hex(randomblob(16)))` |
| `IFNULL(a, b)` | `COALESCE(a, b)` |
| `CONCAT(a, b)` | `(a \|\| b)` |
| `LIMIT 10, 20` | `LIMIT 20 OFFSET 10` |
| `JSON_EXTRACT()` | `json_extract()` |
| `SHOW TABLES` | `SELECT name FROM sqlite_master...` |
| `DESCRIBE table` | `PRAGMA table_info()` |

## API Reference

### `query(sql, params, options)`
Execute a SQL query.

- `sql` (string): The SQL statement.
- `params` (array): Optional parameters for binding (e.g., `?`).
- `options` (object): Optional query options.
  - `dialect` (string): Override dialect for this query (`'mysql'` or `'sqlite'`).
- **Returns**: Promise resolving to the result object (`{ success: true, rows: [...], ... }`).

```javascript
await db.query('INSERT INTO users (name, email) VALUES (?, ?)', ['Alice', 'alice@example.com']);

// With MySQL dialect override
await db.query('SELECT NOW()', [], { dialect: 'mysql' });
```

### `select(sql, params, options)`
Alias for `query`. Semantically useful for read operations.

### `execute(sql, params, options)`
Alias for `query`. Semantically useful for write operations.

### `transaction(statements, options)`
Execute multiple queries in a single atomic transaction.

- `statements` (array): Array of objects `{ sql: string, params?: array }`.
- `options` (object): Optional transaction options.
  - `dialect` (string): Override dialect for this transaction.

```javascript
await db.transaction([
  { sql: 'INSERT INTO users (name) VALUES (?)', params: ['Bob'] },
  { sql: 'UPDATE stats SET count = count + 1 WHERE id = 1' }
]);

// With MySQL dialect
await db.transaction([
  { sql: 'INSERT INTO users (created_at) VALUES (NOW())' }
], { dialect: 'mysql' });
```

### `setDialect(dialect)`
Set the default dialect for all subsequent queries.

- `dialect` (string): `'mysql'` or `'sqlite'`.

```javascript
db.setDialect('mysql');
```

### `getDialect()`
Get the current dialect setting.

```javascript
const currentDialect = db.getDialect(); // 'mysql', 'sqlite', or null
```

### `ping()`
Check if the database is reachable. Returns `true` or `false`.

```javascript
const isAlive = await db.ping();
```

### `version()`
Get the SQLite version.

```javascript
const ver = await db.version(); // e.g., "3.45.0"
```

## Error Handling

All methods return a Promise that rejects if the request fails or the server returns an error.

```javascript
try {
  await db.query('SELECT * FROM non_existent_table');
} catch (err) {
  console.error('Query failed:', err.message);
}
```

## License

MIT