@iota-big3/sdk-gateway
Version:
Universal API Gateway with protocol translation, intelligent routing, rate limiting, health checking, and caching
858 lines • 21.7 kB
TypeScript
/**
* Database Operation Type Definitions
*
* @module database-types
* @description Comprehensive types for database operations including:
* - Connection management and pooling
* - Query building and execution
* - Transactions and isolation levels
* - Schema migrations
* - Type-safe ORM patterns
* - Database-agnostic interfaces
* - Performance monitoring
* - Backup and recovery
*
* Designed for type-safe database operations across multiple engines
*/
import type { Brand, Option, Result } from './index';
/** Unique connection identifier */
export type ConnectionId = Brand<string, 'ConnectionId'>;
/** Transaction identifier */
export type TransactionId = Brand<string, 'TransactionId'>;
/** Migration identifier */
export type MigrationId = Brand<string, 'MigrationId'>;
/** Query identifier for tracking */
export type QueryId = Brand<string, 'QueryId'>;
/** Schema version identifier */
export type SchemaVersion = Brand<number, 'SchemaVersion'>;
/**
* Database connection configuration
*/
export interface DatabaseConfig {
readonly type: DatabaseType;
readonly host: string;
readonly port: number;
readonly database: string;
readonly username?: string;
readonly password?: string;
readonly ssl?: SSLConfig;
readonly pool?: PoolConfig;
readonly options?: Record<string, unknown>;
}
/**
* Supported database types
*/
export declare enum DatabaseType {
PostgreSQL = "POSTGRESQL",
MySQL = "MYSQL",
MariaDB = "MARIADB",
SQLite = "SQLITE",
MongoDB = "MONGODB",
Redis = "REDIS",
Cassandra = "CASSANDRA",
DynamoDB = "DYNAMODB",
CosmosDB = "COSMOSDB",
Neo4j = "NEO4J"
}
/**
* SSL configuration
*/
export interface SSLConfig {
readonly enabled: boolean;
readonly rejectUnauthorized?: boolean;
readonly ca?: string;
readonly cert?: string;
readonly key?: string;
}
/**
* Connection pool configuration
*/
export interface PoolConfig {
readonly min: number;
readonly max: number;
readonly acquireTimeout?: number;
readonly idleTimeout?: number;
readonly connectionTimeout?: number;
readonly maxWaitingClients?: number;
readonly testOnBorrow?: boolean;
}
/**
* Active database connection
*/
export interface DatabaseConnection {
readonly connectionId: ConnectionId;
readonly config: DatabaseConfig;
readonly status: ConnectionStatus;
readonly createdAt: string;
readonly lastUsedAt?: string;
readonly stats: ConnectionStats;
}
/**
* Connection status
*/
export declare enum ConnectionStatus {
Connecting = "CONNECTING",
Connected = "CONNECTED",
Disconnected = "DISCONNECTED",
Error = "ERROR",
Pooled = "POOLED"
}
/**
* Connection statistics
*/
export interface ConnectionStats {
readonly queriesExecuted: number;
readonly totalDuration: number;
readonly errors: number;
readonly activeTransactions: number;
readonly poolPosition?: number;
}
/**
* Database query builder
*/
export interface QueryBuilder<T = unknown> {
readonly select: (columns?: string[]) => QueryBuilder<T>;
readonly from: (table: string) => QueryBuilder<T>;
readonly join: (table: string, on: string) => QueryBuilder<T>;
readonly leftJoin: (table: string, on: string) => QueryBuilder<T>;
readonly rightJoin: (table: string, on: string) => QueryBuilder<T>;
readonly where: (condition: WhereCondition) => QueryBuilder<T>;
readonly whereIn: (column: string, values: unknown[]) => QueryBuilder<T>;
readonly orderBy: (column: string, direction?: 'ASC' | 'DESC') => QueryBuilder<T>;
readonly groupBy: (columns: string[]) => QueryBuilder<T>;
readonly having: (condition: string) => QueryBuilder<T>;
readonly limit: (count: number) => QueryBuilder<T>;
readonly offset: (count: number) => QueryBuilder<T>;
readonly build: () => Query;
readonly execute: () => Promise<Result<T[], DatabaseError>>;
}
/**
* Where condition types
*/
export type WhereCondition = {
column: string;
operator: ComparisonOperator;
value: unknown;
} | {
and: WhereCondition[];
} | {
or: WhereCondition[];
} | {
not: WhereCondition;
} | {
raw: string;
params?: unknown[];
};
/**
* Comparison operators
*/
export declare enum ComparisonOperator {
Equal = "=",
NotEqual = "!=",
GreaterThan = ">",
GreaterThanOrEqual = ">=",
LessThan = "<",
LessThanOrEqual = "<=",
Like = "LIKE",
NotLike = "NOT LIKE",
In = "IN",
NotIn = "NOT IN",
IsNull = "IS NULL",
IsNotNull = "IS NOT NULL",
Between = "BETWEEN"
}
/**
* Raw SQL query
*/
export interface Query {
readonly queryId: QueryId;
readonly sql: string;
readonly params?: unknown[];
readonly timeout?: number;
readonly tags?: Record<string, string>;
}
/**
* Query result
*/
export interface QueryResult<T = unknown> {
readonly rows: T[];
readonly rowCount: number;
readonly fields?: FieldInfo[];
readonly duration: number;
readonly cached: boolean;
}
/**
* Field information
*/
export interface FieldInfo {
readonly name: string;
readonly dataType: string;
readonly nullable: boolean;
readonly maxLength?: number;
readonly precision?: number;
readonly scale?: number;
}
/**
* Database transaction
*/
export interface Transaction {
readonly transactionId: TransactionId;
readonly connectionId: ConnectionId;
readonly isolationLevel: IsolationLevel;
readonly readOnly: boolean;
readonly startedAt: string;
readonly status: TransactionStatus;
readonly savepoints: string[];
}
/**
* Transaction isolation levels
*/
export declare enum IsolationLevel {
ReadUncommitted = "READ_UNCOMMITTED",
ReadCommitted = "READ_COMMITTED",
RepeatableRead = "REPEATABLE_READ",
Serializable = "SERIALIZABLE",
Snapshot = "SNAPSHOT"
}
/**
* Transaction status
*/
export declare enum TransactionStatus {
Active = "ACTIVE",
Committed = "COMMITTED",
RolledBack = "ROLLED_BACK",
Failed = "FAILED"
}
/**
* Transaction options
*/
export interface TransactionOptions {
readonly isolationLevel?: IsolationLevel;
readonly readOnly?: boolean;
readonly deferrable?: boolean;
readonly timeout?: number;
readonly retryable?: boolean;
readonly maxRetries?: number;
}
/**
* Unit of work pattern
*/
export interface UnitOfWork {
readonly register: <T>(entity: T, operation: 'insert' | 'update' | 'delete') => void;
readonly commit: () => Promise<Result<void, DatabaseError>>;
readonly rollback: () => Promise<void>;
readonly getChanges: () => EntityChange[];
}
/**
* Entity change tracking
*/
export interface EntityChange {
readonly entity: unknown;
readonly operation: 'insert' | 'update' | 'delete';
readonly originalValues?: Record<string, unknown>;
readonly currentValues?: Record<string, unknown>;
readonly changedProperties?: string[];
}
/**
* Database schema
*/
export interface DatabaseSchema {
readonly name: string;
readonly version: SchemaVersion;
readonly tables: Table[];
readonly views?: View[];
readonly indexes?: Index[];
readonly functions?: StoredFunction[];
readonly triggers?: Trigger[];
}
/**
* Table definition
*/
export interface Table {
readonly name: string;
readonly schema?: string;
readonly columns: Column[];
readonly primaryKey?: PrimaryKey;
readonly foreignKeys?: ForeignKey[];
readonly indexes?: Index[];
readonly constraints?: Constraint[];
readonly comment?: string;
}
/**
* Column definition
*/
export interface Column {
readonly name: string;
readonly dataType: DataType;
readonly nullable: boolean;
readonly defaultValue?: unknown;
readonly autoIncrement?: boolean;
readonly unique?: boolean;
readonly comment?: string;
readonly collation?: string;
}
/**
* Data types
*/
export interface DataType {
readonly type: SqlDataType;
readonly length?: number;
readonly precision?: number;
readonly scale?: number;
readonly unsigned?: boolean;
readonly timezone?: boolean;
}
/**
* SQL data types
*/
export declare enum SqlDataType {
TinyInt = "TINYINT",
SmallInt = "SMALLINT",
MediumInt = "MEDIUMINT",
Int = "INT",
BigInt = "BIGINT",
Decimal = "DECIMAL",
Numeric = "NUMERIC",
Float = "FLOAT",
Double = "DOUBLE",
Real = "REAL",
Char = "CHAR",
VarChar = "VARCHAR",
Text = "TEXT",
TinyText = "TINYTEXT",
MediumText = "MEDIUMTEXT",
LongText = "LONGTEXT",
Binary = "BINARY",
VarBinary = "VARBINARY",
Blob = "BLOB",
TinyBlob = "TINYBLOB",
MediumBlob = "MEDIUMBLOB",
LongBlob = "LONGBLOB",
Date = "DATE",
Time = "TIME",
DateTime = "DATETIME",
Timestamp = "TIMESTAMP",
Year = "YEAR",
Boolean = "BOOLEAN",
Json = "JSON",
Jsonb = "JSONB",
Uuid = "UUID",
Xml = "XML",
Enum = "ENUM",
Set = "SET",
Array = "ARRAY",
Geometry = "GEOMETRY"
}
/**
* Primary key definition
*/
export interface PrimaryKey {
readonly name?: string;
readonly columns: string[];
readonly clustered?: boolean;
}
/**
* Foreign key definition
*/
export interface ForeignKey {
readonly name?: string;
readonly columns: string[];
readonly referencedTable: string;
readonly referencedColumns: string[];
readonly onUpdate?: ReferentialAction;
readonly onDelete?: ReferentialAction;
}
/**
* Referential actions
*/
export declare enum ReferentialAction {
NoAction = "NO ACTION",
Restrict = "RESTRICT",
Cascade = "CASCADE",
SetNull = "SET NULL",
SetDefault = "SET DEFAULT"
}
/**
* Index definition
*/
export interface Index {
readonly name: string;
readonly table: string;
readonly columns: IndexColumn[];
readonly unique: boolean;
readonly type?: IndexType;
readonly method?: IndexMethod;
readonly where?: string;
readonly include?: string[];
}
/**
* Index column
*/
export interface IndexColumn {
readonly name: string;
readonly direction?: 'ASC' | 'DESC';
readonly nullsFirst?: boolean;
}
/**
* Index types
*/
export declare enum IndexType {
BTree = "BTREE",
Hash = "HASH",
GiST = "GIST",
GIN = "GIN",
FullText = "FULLTEXT",
Spatial = "SPATIAL"
}
/**
* Index methods
*/
export declare enum IndexMethod {
BTree = "btree",
Hash = "hash",
Gist = "gist",
SpGist = "spgist",
Gin = "gin",
Brin = "brin"
}
/**
* Constraint definition
*/
export interface Constraint {
readonly name?: string;
readonly type: ConstraintType;
readonly columns?: string[];
readonly checkExpression?: string;
readonly deferrable?: boolean;
readonly initiallyDeferred?: boolean;
}
/**
* Constraint types
*/
export declare enum ConstraintType {
Check = "CHECK",
Unique = "UNIQUE",
PrimaryKey = "PRIMARY_KEY",
ForeignKey = "FOREIGN_KEY",
NotNull = "NOT_NULL",
Default = "DEFAULT"
}
/**
* Database view
*/
export interface View {
readonly name: string;
readonly schema?: string;
readonly definition: string;
readonly columns?: Column[];
readonly materialized?: boolean;
readonly withCheckOption?: boolean;
}
/**
* Stored function/procedure
*/
export interface StoredFunction {
readonly name: string;
readonly schema?: string;
readonly parameters: Parameter[];
readonly returnType?: DataType;
readonly body: string;
readonly language: string;
readonly deterministic?: boolean;
readonly securityType?: 'DEFINER' | 'INVOKER';
}
/**
* Function parameter
*/
export interface Parameter {
readonly name: string;
readonly type: DataType;
readonly mode?: 'IN' | 'OUT' | 'INOUT';
readonly defaultValue?: unknown;
}
/**
* Database trigger
*/
export interface Trigger {
readonly name: string;
readonly table: string;
readonly timing: 'BEFORE' | 'AFTER' | 'INSTEAD OF';
readonly event: 'INSERT' | 'UPDATE' | 'DELETE';
readonly forEachRow: boolean;
readonly condition?: string;
readonly body: string;
}
/**
* Database migration
*/
export interface Migration {
readonly migrationId: MigrationId;
readonly version: string;
readonly name: string;
readonly description?: string;
readonly up: MigrationStep[];
readonly down: MigrationStep[];
readonly checksum?: string;
readonly dependencies?: MigrationId[];
}
/**
* Migration step
*/
export type MigrationStep = {
type: 'sql';
sql: string;
} | {
type: 'createTable';
table: Table;
} | {
type: 'dropTable';
tableName: string;
} | {
type: 'addColumn';
table: string;
column: Column;
} | {
type: 'dropColumn';
table: string;
columnName: string;
} | {
type: 'modifyColumn';
table: string;
columnName: string;
newDefinition: Column;
} | {
type: 'createIndex';
index: Index;
} | {
type: 'dropIndex';
indexName: string;
} | {
type: 'addConstraint';
table: string;
constraint: Constraint;
} | {
type: 'dropConstraint';
table: string;
constraintName: string;
} | {
type: 'renameTable';
oldName: string;
newName: string;
} | {
type: 'renameColumn';
table: string;
oldName: string;
newName: string;
};
/**
* Migration history
*/
export interface MigrationHistory {
readonly migrationId: MigrationId;
readonly version: string;
readonly appliedAt: string;
readonly appliedBy: string;
readonly executionTime: number;
readonly success: boolean;
readonly error?: string;
}
/**
* Migration runner
*/
export interface MigrationRunner {
readonly migrate: (target?: string) => Promise<Result<MigrationResult, DatabaseError>>;
readonly rollback: (steps?: number) => Promise<Result<MigrationResult, DatabaseError>>;
readonly status: () => Promise<MigrationStatus[]>;
readonly create: (name: string) => Promise<Migration>;
}
/**
* Migration result
*/
export interface MigrationResult {
readonly appliedMigrations: MigrationHistory[];
readonly failedMigration?: MigrationHistory;
readonly currentVersion: string;
}
/**
* Migration status
*/
export interface MigrationStatus {
readonly migration: Migration;
readonly applied: boolean;
readonly appliedAt?: string;
readonly pending: boolean;
}
/**
* Repository interface for data access
*/
export interface Repository<T, ID = unknown> {
readonly findById: (id: ID) => Promise<Option<T>>;
readonly findAll: (options?: FindOptions) => Promise<T[]>;
readonly findOne: (criteria: Partial<T>) => Promise<Option<T>>;
readonly count: (criteria?: Partial<T>) => Promise<number>;
readonly save: (entity: T) => Promise<Result<T, DatabaseError>>;
readonly saveAll: (entities: T[]) => Promise<Result<T[], DatabaseError>>;
readonly delete: (id: ID) => Promise<Result<void, DatabaseError>>;
readonly deleteAll: (criteria: Partial<T>) => Promise<Result<number, DatabaseError>>;
readonly exists: (id: ID) => Promise<boolean>;
}
/**
* Find options
*/
export interface FindOptions {
readonly where?: Record<string, unknown>;
readonly orderBy?: Record<string, 'ASC' | 'DESC'>;
readonly limit?: number;
readonly offset?: number;
readonly include?: string[];
readonly select?: string[];
}
/**
* Entity metadata
*/
export interface EntityMetadata<T = unknown> {
readonly tableName: string;
readonly schema?: string;
readonly columns: EntityColumn[];
readonly relations?: EntityRelation[];
readonly indexes?: EntityIndex[];
readonly hooks?: EntityHooks<T>;
}
/**
* Entity column mapping
*/
export interface EntityColumn {
readonly propertyName: string;
readonly columnName: string;
readonly type: DataType;
readonly primary?: boolean;
readonly generated?: boolean;
readonly transformer?: ValueTransformer;
}
/**
* Value transformer
*/
export interface ValueTransformer {
readonly to: (value: unknown) => unknown;
readonly from: (value: unknown) => unknown;
}
/**
* Entity relation
*/
export interface EntityRelation {
readonly propertyName: string;
readonly type: RelationType;
readonly target: string;
readonly joinColumn?: string;
readonly inverseProperty?: string;
readonly cascade?: CascadeOption[];
readonly eager?: boolean;
}
/**
* Relation types
*/
export declare enum RelationType {
OneToOne = "ONE_TO_ONE",
OneToMany = "ONE_TO_MANY",
ManyToOne = "MANY_TO_ONE",
ManyToMany = "MANY_TO_MANY"
}
/**
* Cascade options
*/
export declare enum CascadeOption {
Insert = "INSERT",
Update = "UPDATE",
Delete = "DELETE",
SoftDelete = "SOFT_DELETE",
Recover = "RECOVER"
}
/**
* Entity index mapping
*/
export interface EntityIndex {
readonly name?: string;
readonly columns: string[];
readonly unique?: boolean;
readonly spatial?: boolean;
readonly fulltext?: boolean;
}
/**
* Entity lifecycle hooks
*/
export interface EntityHooks<T> {
readonly beforeInsert?: (entity: T) => Promise<void>;
readonly afterInsert?: (entity: T) => Promise<void>;
readonly beforeUpdate?: (entity: T) => Promise<void>;
readonly afterUpdate?: (entity: T) => Promise<void>;
readonly beforeDelete?: (entity: T) => Promise<void>;
readonly afterDelete?: (entity: T) => Promise<void>;
readonly afterLoad?: (entity: T) => Promise<void>;
}
/**
* Query execution plan
*/
export interface QueryPlan {
readonly queryId: QueryId;
readonly planType: 'estimated' | 'actual';
readonly rootNode: PlanNode;
readonly totalCost?: number;
readonly executionTime?: number;
readonly planningTime?: number;
}
/**
* Plan node in execution tree
*/
export interface PlanNode {
readonly nodeType: string;
readonly operation: string;
readonly cost?: {
readonly startup: number;
readonly total: number;
};
readonly rows?: {
readonly estimated: number;
readonly actual?: number;
};
readonly time?: {
readonly startup: number;
readonly total: number;
};
readonly children?: PlanNode[];
readonly properties?: Record<string, unknown>;
}
/**
* Query statistics
*/
export interface QueryStatistics {
readonly queryId: QueryId;
readonly executionCount: number;
readonly totalTime: number;
readonly meanTime: number;
readonly minTime: number;
readonly maxTime: number;
readonly stdDev: number;
readonly rowsReturned: number;
readonly cacheHitRate?: number;
}
/**
* Database error types
*/
export type DatabaseError = {
type: 'CONNECTION_ERROR';
message: string;
code?: string;
} | {
type: 'QUERY_ERROR';
message: string;
query?: string;
code?: string;
} | {
type: 'CONSTRAINT_VIOLATION';
constraint: string;
table?: string;
} | {
type: 'TRANSACTION_ERROR';
message: string;
transactionId?: TransactionId;
} | {
type: 'MIGRATION_ERROR';
migration: string;
step?: number;
error: string;
} | {
type: 'TIMEOUT';
duration: number;
operation: string;
} | {
type: 'DEADLOCK';
resources: string[];
} | {
type: 'DISK_FULL';
available: number;
required: number;
} | {
type: 'PERMISSION_DENIED';
operation: string;
object: string;
};
/**
* Database backup configuration
*/
export interface BackupConfig {
readonly type: BackupType;
readonly compression?: CompressionType;
readonly encryption?: EncryptionConfig;
readonly location: string;
readonly schedule?: string;
readonly retention?: RetentionPolicy;
}
/**
* Backup types
*/
export declare enum BackupType {
Full = "FULL",
Incremental = "INCREMENTAL",
Differential = "DIFFERENTIAL",
TransactionLog = "TRANSACTION_LOG",
Snapshot = "SNAPSHOT"
}
/**
* Compression types
*/
export declare enum CompressionType {
None = "NONE",
Gzip = "GZIP",
Bzip2 = "BZIP2",
Lz4 = "LZ4",
Zstd = "ZSTD"
}
/**
* Encryption configuration
*/
export interface EncryptionConfig {
readonly algorithm: string;
readonly keyId: string;
readonly keyManagement: 'local' | 'kms' | 'vault';
}
/**
* Retention policy
*/
export interface RetentionPolicy {
readonly daily: number;
readonly weekly: number;
readonly monthly: number;
readonly yearly: number;
}
/**
* Validate connection pool configuration
*/
export declare function validatePoolConfig(config: PoolConfig): Result<boolean, string>;
/**
* Calculate query complexity score
*/
export declare function calculateQueryComplexity(query: string): number;
/**
* Check if migration order is valid
*/
export declare function validateMigrationOrder(migrations: Migration[]): Result<boolean, string>;
export declare const databaseTypes: {
DatabaseType: typeof DatabaseType;
ConnectionStatus: typeof ConnectionStatus;
ComparisonOperator: typeof ComparisonOperator;
IsolationLevel: typeof IsolationLevel;
TransactionStatus: typeof TransactionStatus;
SqlDataType: typeof SqlDataType;
ReferentialAction: typeof ReferentialAction;
IndexType: typeof IndexType;
IndexMethod: typeof IndexMethod;
ConstraintType: typeof ConstraintType;
RelationType: typeof RelationType;
CascadeOption: typeof CascadeOption;
BackupType: typeof BackupType;
CompressionType: typeof CompressionType;
validatePoolConfig: typeof validatePoolConfig;
calculateQueryComplexity: typeof calculateQueryComplexity;
validateMigrationOrder: typeof validateMigrationOrder;
};
//# sourceMappingURL=database-types.d.ts.map