npm package: @nuraly/dbclient
Description: A comprehensive TypeScript/JavaScript client for Nuraly Database Manager with static interface for all database operations
Author: Nuraly Team
Latest version: 0.1.0

# @nuraly/dbclient

A comprehensive TypeScript/JavaScript client for Nuraly Database Manager that provides a clean static interface for all database operations including table management, data operations, joins, and advanced queries.

## Features

- 🚀 **Static Interface**: Easy-to-use static methods for all database operations
- 🔍 **Schema Introspection**: Comprehensive database schema querying capabilities
- 🔗 **Advanced Joins**: Support for complex table relationships and joins
- 📊 **Aggregations**: Built-in support for COUNT, SUM, AVG, MIN, MAX operations
- 🔄 **Batch Operations**: Execute multiple operations in a single request
- 📄 **Pagination**: Built-in pagination support with metadata
- 🔍 **Search**: Full-text search across multiple fields
- 💾 **Backup/Restore**: Data backup and restoration capabilities
- 🔌 **Connection Management**: Multi-connection support with easy switching
- 📝 **TypeScript Support**: Full TypeScript definitions included

## Installation

```bash
npm install @nuraly/dbclient
```

## Quick Start

```typescript
import Database from '@nuraly/dbclient';

// Configure the client
Database.configure('/api/v1/database', {
    timeout: 30000,
    connectionId: 1
});

// Create a table
await Database.createTable('users', {
    id: { type: 'INTEGER', nullable: false },
    name: { type: 'VARCHAR', nullable: false },
    email: { type: 'VARCHAR', nullable: false },
    age: { type: 'INTEGER', nullable: true }
});

// Insert data
await Database.insert('users', {
    name: 'John Doe',
    email: 'john@example.com',
    age: 30
});

// Query data
const users = await Database.select('users', {
    criteria: { age: { gte: 18 } },
    fields: ['name', 'email'],
    limit: 10,
    orderBy: 'name'
});
```

## Schema Introspection

The library provides comprehensive schema introspection capabilities:

```typescript
// List all tables
const tables = await Database.schemaQuery('LIST_TABLES');

// Get table structure
const structure = await Database.schemaQuery('DESCRIBE_TABLE', 'users');

// Check if table exists
const exists = await Database.tableExists('users');

// Get database info
const dbInfo = await Database.getDatabaseInfo();

// Get table constraints
const constraints = await Database.getConstraints('users');

// Get foreign keys
const foreignKeys = await Database.getForeignKeys('users');
```

## Advanced Queries

### Joins and Relations

```typescript
const userOrders = await Database.select('users', {
    relations: [{
        table: 'orders',
        localField: 'id',
        foreignField: 'user_id',
        type: 'inner'
    }],
    fields: ['users.name', 'users.email', 'orders.total_amount'],
    criteria: { 'orders.status': 'completed' }
});
```

### Aggregations

```typescript
const userCount = await Database.count('users', { status: 'active' });
const avgAge = await Database.avg('users', 'age');
const totalSales = await Database.sum('orders', 'total_amount');
const oldestUser = await Database.max('users', 'age');
const youngestUser = await Database.min('users', 'age');
```

### Pagination

```typescript
const page2 = await Database.paginate('users', 2, 20, {
    criteria: { status: 'active' },
    orderBy: 'created_at',
    orderDirection: 'DESC'
});

console.log(page2.data); // Array of users
console.log(page2.pagination); // Pagination metadata
```

### Search

```typescript
const searchResults = await Database.search('users', 'john', ['name', 'email']);
```

## Batch Operations

```typescript
await Database.batch([
    { method: 'insert', table: 'users', data: { name: 'Jane', email: 'jane@example.com' }},
    { method: 'insert', table: 'users', data: { name: 'Bob', email: 'bob@example.com' }},
    { method: 'update', table: 'users', data: { status: 'verified' }, criteria: { name: 'John Doe' }}
]);
```

## Connection Management

```typescript
// List connections
const connections = await Database.listConnections();

// Create a new connection
const newConn = await Database.createConnection({
    name: 'Production DB',
    type: 'POSTGRESQL',
    host: 'db.example.com',
    port: 5432,
    database: 'production',
    username: 'dbuser',
    password: 'securepassword'
});

// Switch connections
Database.setConnection(2);
const users = await Database.select('users'); // Uses connection 2

// Test connection
const testResult = await Database.testConnection(1);
```

## API Reference

### Configuration

- `Database.configure(baseUrl, options)` - Configure the client
- `Database.setConnection(connectionId)` - Set active connection

### Table Management

- `Database.createTable(tableName, schema, options)` - Create a table
- `Database.updateSchema(tableName, schema)` - Update table schema
- `Database.dropTable(tableName)` - Drop a table
- `Database.listTables()` - List all tables
- `Database.getTableSchema(tableName)` - Get table schema

### Data Operations

- `Database.insert(tableName, data)` - Insert a record
- `Database.select(tableName, options)` - Query records
- `Database.update(tableName, data, criteria)` - Update records
- `Database.delete(tableName, criteria)` - Delete records

### Schema Queries

- `Database.schemaQuery(type, tableName?)` - Execute schema operations
- `Database.tableExists(tableName)` - Check if table exists
- `Database.columns(tableName)` - Get column information
- `Database.getDatabaseInfo()` - Get database metadata
- `Database.getConstraints(tableName)` - Get table constraints
- `Database.getForeignKeys(tableName)` - Get foreign keys

### Aggregations

- `Database.count(tableName, criteria?)` - Count records
- `Database.sum(tableName, field, criteria?)` - Sum values
- `Database.avg(tableName, field, criteria?)` - Average values
- `Database.min(tableName, field, criteria?)` - Minimum value
- `Database.max(tableName, field, criteria?)` - Maximum value

### Utilities

- `Database.paginate(tableName, page, pageSize, options?)` - Paginated results
- `Database.search(tableName, searchTerm, fields)` - Search records
- `Database.batch(operations)` - Batch operations
- `Database.backup(tableName)` - Backup table data
- `Database.restore(backupData, overwrite?)` - Restore data

## TypeScript Support

The library is written in TypeScript and includes full type definitions:

```typescript
import Database, { DatabaseOptions, SelectOptions, PaginationResult } from '@nuraly/dbclient';

const options: SelectOptions = {
    criteria: { status: 'active' },
    fields: ['name', 'email'],
    limit: 10
};

const result: PaginationResult<any> = await Database.paginate('users', 1, 10, options);
```

## Contributing

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

## License

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

## Support

For support and questions, please visit our [GitHub Issues](https://github.com/Nuralyio/dbclient/issues) page.