UNPKG

@stacksjs/stx

Version:

A performant UI Framework. Powered by Bun.

407 lines 12.1 kB
import type { StxOptions } from './types'; /** * Configure database connections * * @param config - Database configuration * * @example * configureDatabase({ * default: 'sqlite', * connections: { * sqlite: { driver: 'sqlite', database: './database.db' } * } * }) */ export declare function configureDatabase(config: Partial<DatabaseConfig>): void; /** * Get current database configuration */ export declare function getDatabaseConfig(): DatabaseConfig; /** * Reset database configuration to defaults */ export declare function resetDatabaseConfig(): void; /** * Register a custom database adapter * * @param name - Connection name * @param adapter - Database adapter instance */ export declare function registerAdapter(name: string, adapter: DatabaseAdapter): void; /** * Get database adapter for connection * * @param connection - Connection name (defaults to default connection) */ export declare function getAdapter(connection?: string): DatabaseAdapter; /** * Create a new query builder for a table * * @param table - Table name * @returns Query builder instance * * @example * const users = await query('users') * .where('active', true) * .orderBy('name') * .get() */ export declare function query(table: string): QueryBuilder; /** * Alias for query() */ export declare function table(name: string): QueryBuilder; /** * Create a raw SQL expression */ export declare function raw(sql: string, bindings?: unknown[]): RawExpression; /** * Define a model * * @param name - Model name * @param definition - Model definition * @returns Model instance * * @example * const User = defineModel('User', { * table: 'users', * primaryKey: 'id', * fillable: ['name', 'email'], * hidden: ['password'], * relationships: { * posts: { type: 'hasMany', model: 'Post', foreignKey: 'user_id' } * } * }) */ export declare function defineModel(name: string, definition: ModelDefinition): Model; /** * Get a registered model by name */ export declare function getModel(name: string): Model; /** * Check if a model is registered */ export declare function hasModel(name: string): boolean; /** * Run a callback within a transaction * * @param callback - Function to run within transaction * @param connection - Optional connection name * * @example * await transaction(async () => { * await query('users').insert({ name: 'John' }) * await query('profiles').insert({ user_id: 1, bio: 'Hello' }) * }) */ export declare function transaction<T>(callback: () => Promise<T>, connection?: string): Promise<T>; /** * Clear all query cache */ export declare function clearQueryCache(): void; /** * Get query cache statistics */ export declare function getQueryCacheStats(): { size: number, keys: string[] }; /** * Get query log */ export declare function getQueryLog(): typeof queryLog; /** * Clear query log */ export declare function clearQueryLog(): void; /** * Enable or disable query logging */ export declare function enableQueryLogging(enabled?: boolean): void; /** * Process @db directive in templates * * Syntax: @db('table')->method()->method() * * @example * @db('users')->where('active', true)->get() * @db('posts')->orderBy('created_at', 'desc')->limit(5)->get() */ export declare function processDbDirective(template: string, context: Record<string, any>, _filePath: string, _options: StxOptions): Promise<string>; /** * Process @model directive in templates * * Syntax: @model('ModelName')->method() * * @example * @model('User')->find(1) * @model('Post')->where('published', true)->get() */ export declare function processModelDirective(template: string, context: Record<string, any>, _filePath: string, _options: StxOptions): Promise<string>; /** * Process @query directive for inline SQL * * Syntax: @query('SELECT * FROM users WHERE id = ?', [1]) */ export declare function processQueryDirective(template: string, context: Record<string, any>, _filePath: string, _options: StxOptions): Promise<string>; /** * Process all database-related directives in a template */ export declare function processDatabaseDirectives(template: string, context: Record<string, any>, filePath: string, options: StxOptions): Promise<string>; /** * Get schema builder */ export declare function schema(): SchemaBuilder; /** * Database connection configuration */ export declare interface ConnectionConfig { driver: DatabaseDriver database: string host?: string port?: number username?: string password?: string poolSize?: number timeout?: number ssl?: boolean | Record<string, unknown> options?: Record<string, unknown> } /** * Database configuration */ export declare interface DatabaseConfig { default: string connections: Record<string, ConnectionConfig> logging?: boolean cacheTTL?: number maxCacheSize?: number } /** * Where clause condition */ export declare interface WhereCondition { column: string operator: QueryOperator value: unknown boolean: 'and' | 'or' } /** * Order by clause */ export declare interface OrderByClause { column: string direction: 'asc' | 'desc' } /** * Join clause */ export declare interface JoinClause { type: 'inner' | 'left' | 'right' | 'cross' table: string first: string operator: string second: string } /** * Raw SQL expression */ export declare interface RawExpression { __raw: true sql: string bindings: unknown[] } /** * Relationship definition */ export declare interface RelationshipDefinition { type: 'hasOne' | 'hasMany' | 'belongsTo' | 'belongsToMany' model: string foreignKey?: string localKey?: string pivotTable?: string pivotForeignKey?: string pivotRelatedKey?: string } /** * Model definition */ export declare interface ModelDefinition { table: string primaryKey?: string fillable?: string[] hidden?: string[] timestamps?: { createdAt?: string, updatedAt?: string } | boolean softDeletes?: string | boolean defaults?: Record<string, unknown> casts?: Record<string, 'string' | 'number' | 'boolean' | 'date' | 'json' | 'array'> relationships?: Record<string, RelationshipDefinition> scopes?: Record<string, (query: QueryBuilder) => QueryBuilder> } /** * Model instance */ export declare interface ModelInstance { get: (key: string) => unknown set: (key: string, value: unknown) => void toJSON: () => Row save: () => Promise<void> delete: () => Promise<void> refresh: () => Promise<void> exists: boolean original: Row attributes: Row isDirty: (key?: string) => boolean } /** * Model class */ export declare interface Model { name: string definition: ModelDefinition find: (id: unknown) => Promise<ModelInstance | null> findOrFail: (id: unknown) => Promise<ModelInstance> all: () => Promise<ModelInstance[]> create: (attributes: Row) => Promise<ModelInstance> update: (attributes: Row) => Promise<number> destroy: (ids: unknown | unknown[]) => Promise<number> query: () => QueryBuilder where: (column: string, operatorOrValue: QueryOperator | unknown, value?: unknown) => QueryBuilder first: () => Promise<ModelInstance | null> get: () => Promise<ModelInstance[]> count: () => Promise<number> } /** * Database adapter interface */ export declare interface DatabaseAdapter { connect: () => Promise<void> disconnect: () => Promise<void> query: <T = Row>(sql: string, bindings?: unknown[]) => Promise<T[]> insert: (sql: string, bindings?: unknown[]) => Promise<unknown> execute: (sql: string, bindings?: unknown[]) => Promise<number> beginTransaction: () => Promise<void> commit: () => Promise<void> rollback: () => Promise<void> isConnected: () => boolean } /** * Supported database drivers */ export type DatabaseDriver = 'sqlite' | 'postgres' | 'mysql' | 'custom' /** * Query operator types */ export type QueryOperator = '=' | '!=' | '<' | '<=' | '>' | '>=' | 'like' | 'in' | 'not in' | 'between' | 'is null' | 'is not null' /** * Query result row */ export type Row = Record<string, unknown> /** * Fluent query builder class */ export declare class QueryBuilder { private _table: string; private _columns: (string | RawExpression)[]; private _wheres: WhereCondition[]; private _orders: OrderByClause[]; private _joins: JoinClause[]; private _groupBy: string[]; private _having: WhereCondition[]; private _limit?: number; private _offset?: number; private _distinct: boolean; private _connection?: string; private _bindings: unknown[]; private _modelDefinition?: ModelDefinition; constructor(table?: string); table(name: string): this; from(name: string): this; connection(name: string): this; select(columns: (string | RawExpression)[]): this; addSelect(columns: (string | RawExpression)[]): this; distinct(): this; where(column: string, operatorOrValue: QueryOperator | unknown, value?: unknown): this; orWhere(column: string, operatorOrValue: QueryOperator | unknown, value?: unknown): this; whereIn(column: string, values: unknown[]): this; whereNotIn(column: string, values: unknown[]): this; whereNull(column: string): this; whereNotNull(column: string): this; whereBetween(column: string, min: unknown, max: unknown): this; whereLike(column: string, pattern: string): this; join(table: string, first: string, operator: string, second: string): this; leftJoin(table: string, first: string, operator: string, second: string): this; rightJoin(table: string, first: string, operator: string, second: string): this; orderBy(column: string, direction?: 'asc' | 'desc'): this; orderByDesc(column: string): this; groupBy(columns: string[]): this; having(column: string, operator: QueryOperator, value: unknown): this; limit(count: number): this; take(count: number): this; offset(count: number): this; skip(count: number): this; forPage(page: number, perPage?: number): this; get(): Promise<Row[]>; first(): Promise<Row | null>; firstOrFail(): Promise<Row>; find(id: unknown, primaryKey?: string): Promise<Row | null>; value(column: string): Promise<unknown>; pluck(column: string): Promise<unknown[]>; exists(): Promise<boolean>; doesntExist(): Promise<boolean>; count(column?: string): Promise<number>; max(column: string): Promise<number | null>; min(column: string): Promise<number | null>; sum(column: string): Promise<number>; avg(column: string): Promise<number | null>; insert(data: Row): Promise<unknown>; insertAll(rows: Row[]): Promise<void>; update(data: Row): Promise<number>; increment(column: string, amount?: number): Promise<number>; decrement(column: string, amount?: number): Promise<number>; delete(): Promise<number>; truncate(): Promise<void>; toSql(): { sql: string, bindings: unknown[] }; private buildWhereClause(): string; private getCacheKey(sql: string, bindings: unknown[]): string; clone(): QueryBuilder; } /** * Database error with query context */ export declare class DatabaseError extends Error { public sql?: string; public bindings?: unknown[]; constructor(message: string, sql?: string, bindings?: unknown[]); } /** * Schema builder for database migrations */ export declare class SchemaBuilder { private _connection?: string; connection(name: string): this; create(table: string, callback: (blueprint: Blueprint) => void): Promise<void>; drop(table: string): Promise<void>; rename(from: string, to: string): Promise<void>; hasTable(table: string): Promise<boolean>; } /** * Table blueprint for schema definitions */ export declare class Blueprint { private columns: string[]; private indices: string[]; private table: string; constructor(table: string); id(name?: string): this; string(name: string, length?: number): this; text(name: string): this; integer(name: string): this; boolean(name: string): this; datetime(name: string): this; timestamps(): this; softDeletes(): this; json(name: string): this; foreignId(name: string): this; index(columns: string | string[]): this; unique(columns: string | string[]): this; toCreateSQL(): string; getIndexSQL(): string[]; }