Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 | 1x 1x 1x 2x 2x 1x 2x 2x 1x 1x 1x 1x 1x 1x 7x 7x 7x 7x 1x 1x 1x 1x 1x 1x 1x 22x 22x 22x 22x 2x 2x 1x 1x 2x 2x | import { Type } from "../core/types";
import { DatabaseAdapter } from "./interface";
import { MetadataRegistry } from "../core/MetadataRegistry";
import { SchemaReflector } from "../core/SchemaReflector";
/**
* SQLite-specific table decorator
*/
export function Table(name: string) {
return function (target: any) {
Reflect.defineMetadata("sqlite:table", name, target);
};
}
/**
* SQLite-specific primary key decorator
*/
export function PrimaryKey() {
return function (target: any, propertyKey: string) {
Reflect.defineMetadata(
"sqlite:primaryKey",
propertyKey,
target.constructor
);
};
}
/**
* SQLite-specific index decorator
*/
export function Index(name?: string, unique = false) {
return function (target: any, propertyKey: string) {
const indexes =
Reflect.getMetadata("sqlite:indexes", target.constructor) || [];
indexes.push({
name: name || `idx_${propertyKey}`,
column: propertyKey,
unique,
});
Reflect.defineMetadata("sqlite:indexes", indexes, target.constructor);
};
}
/**
* SQLite-specific column decorator
*/
export function Column(options: {
name?: string;
type?: "TEXT" | "INTEGER" | "REAL" | "BLOB" | "NULL";
nullable?: boolean;
defaultValue?: any;
}) {
return function (target: any, propertyKey: string) {
const columns =
Reflect.getMetadata("sqlite:columns", target.constructor) || {};
columns[propertyKey] = options;
Reflect.defineMetadata("sqlite:columns", columns, target.constructor);
};
}
/**
* SQLite-specific foreign key decorator
*/
export function ForeignKey(options: {
references: string;
column: string;
onDelete?: "CASCADE" | "RESTRICT" | "SET NULL" | "NO ACTION";
onUpdate?: "CASCADE" | "RESTRICT" | "SET NULL" | "NO ACTION";
}) {
return function (target: any, propertyKey: string) {
const foreignKeys =
Reflect.getMetadata("sqlite:foreignKeys", target.constructor) || [];
foreignKeys.push({
column: propertyKey,
...options,
});
Reflect.defineMetadata(
"sqlite:foreignKeys",
foreignKeys,
target.constructor
);
};
}
/**
* Shorthand decorator for SQLite entities
*/
export function SQLite<T extends { new (...args: any[]): any }>(target: T): T {
return DatabaseAdapter("SQLite")(target);
}
/**
* Implementation of DatabaseAdapter for SQLite
*/
export class SQLiteAdapter implements DatabaseAdapter {
readonly type = "SQLite";
private registry: MetadataRegistry;
private reflector = new SchemaReflector();
/**
* Constructor for SQLite adapter
* @param registry The metadata registry to use for schema information
* @param databasePath Path to the SQLite database file
*/
constructor(registry: MetadataRegistry, private databasePath: string) {
this.registry = registry;
}
/**
* Get the table name for an entity type
*/
private getTableName<T>(entityType: Type<T>): string {
// Get custom table name if defined, otherwise use entity name
const tableName = Reflect.getMetadata("sqlite:table", entityType);
if (tableName) {
return tableName;
}
// Use entity name in snake_case
return this.toSnakeCase(entityType.name);
}
/**
* Get primary key column for an entity type
*/
private getPrimaryKey<T>(entityType: Type<T>): string {
const primaryKey = Reflect.getMetadata("sqlite:primaryKey", entityType);
Iif (primaryKey) {
return primaryKey;
}
// Default to 'id' if not specified
return "id";
}
/**
* Get column configurations for an entity type
*/
private getColumns<T>(entityType: Type<T>): Record<string, any> {
return Reflect.getMetadata("sqlite:columns", entityType) || {};
}
/**
* Get index configurations for an entity type
*/
private getIndexes<T>(entityType: Type<T>): any[] {
return Reflect.getMetadata("sqlite:indexes", entityType) || [];
}
/**
* Get foreign key configurations for an entity type
*/
private getForeignKeys<T>(entityType: Type<T>): any[] {
return Reflect.getMetadata("sqlite:foreignKeys", entityType) || [];
}
/**
* Convert entity to SQLite row
*/
private entityToRow<T>(entity: T): Record<string, any> {
const entityType = entity.constructor as Type<T>;
const entitySchema = this.reflector.getEntitySchema(entityType);
const columns = this.getColumns(entityType);
const row: Record<string, any> = {};
// Convert each property to column value
for (const [key, meta] of Object.entries(entitySchema.properties)) {
Iif ((entity as any)[key] !== undefined) {
const columnConfig = columns[key];
const columnName = columnConfig?.name || this.toSnakeCase(key);
let value = (entity as any)[key];
// Handle date objects
Iif (value instanceof Date) {
value = value.toISOString();
}
// Handle objects (convert to JSON string)
Iif (typeof value === "object" && value !== null) {
value = JSON.stringify(value);
}
row[columnName] = value;
}
}
return row;
}
/**
* Convert SQLite row to entity instance
*/
private rowToEntity<T>(entityType: Type<T>, row: Record<string, any>): T {
const entity = new entityType();
const entitySchema = this.reflector.getEntitySchema(entityType);
const columns = this.getColumns(entityType);
// Create a map of column names to property names
const columnNameMap: Record<string, string> = {};
for (const [key, config] of Object.entries(columns)) {
if (config.name) {
columnNameMap[config.name] = key;
} else {
columnNameMap[this.toSnakeCase(key)] = key;
}
}
// Convert each column to entity property
for (const [colName, value] of Object.entries(row)) {
// Find the property name for this column
const propName = columnNameMap[colName] || this.toCamelCase(colName);
// Only set if the property exists in the schema
Iif (entitySchema.properties[propName]) {
let propValue = value;
// Handle string to object conversion
const propType = entitySchema.properties[propName].type;
Iif (propType === "object" && typeof value === "string") {
try {
propValue = JSON.parse(value);
} catch (e) {
// If parsing fails, use the original value
}
}
// Handle string to date conversion
Iif (propType === "date" && typeof value === "string") {
propValue = new Date(value);
}
(entity as any)[propName] = propValue;
}
}
return entity;
}
/**
* Convert string to snake_case
*/
private toSnakeCase(str: string): string {
return str
.replace(/([A-Z])/g, "_$1")
.toLowerCase()
.replace(/^_/, "");
}
/**
* Convert string to camelCase
*/
private toCamelCase(str: string): string {
return str.replace(/_([a-z])/g, (_, letter) => letter.toUpperCase());
}
/**
* Build a SQL WHERE clause from criteria
*/
private buildWhereClause(criteria: Record<string, any>): {
clause: string;
params: any[];
} {
const conditions: string[] = [];
const params: any[] = [];
for (const [key, value] of Object.entries(criteria)) {
if (value === null) {
conditions.push(`${this.toSnakeCase(key)} IS NULL`);
} else {
conditions.push(`${this.toSnakeCase(key)} = ?`);
params.push(value);
}
}
return {
clause: conditions.length ? `WHERE ${conditions.join(" AND ")}` : "",
params,
};
}
/**
* Query for a single entity by criteria
*/
async query<T>(entityType: Type<T>, criteria: object): Promise<T | null> {
const tableName = this.getTableName(entityType);
console.log(
`[SQLiteAdapter] Querying ${tableName} with criteria:`,
criteria
);
const { clause, params } = this.buildWhereClause(
criteria as Record<string, any>
);
const sql = `SELECT * FROM ${tableName} ${clause} LIMIT 1`;
console.log(`[SQLiteAdapter] SQL query: ${sql}`, params);
// In a real implementation, this would execute a SQL query
// const db = new SQLite3(this.databasePath);
// const row = await db.get(sql, ...params);
// return row ? this.rowToEntity(entityType, row) : null;
// Mock implementation
const result = await this.mockQueryExecution<T>(entityType, criteria);
return result;
}
/**
* Query for multiple entities by criteria
*/
async queryMany<T>(entityType: Type<T>, criteria: object): Promise<T[]> {
const tableName = this.getTableName(entityType);
console.log(
`[SQLiteAdapter] Querying for multiple rows in ${tableName} with criteria:`,
criteria
);
const { clause, params } = this.buildWhereClause(
criteria as Record<string, any>
);
const sql = `SELECT * FROM ${tableName} ${clause}`;
console.log(`[SQLiteAdapter] SQL query: ${sql}`, params);
// In a real implementation, this would execute a SQL query
// const db = new SQLite3(this.databasePath);
// const rows = await db.all(sql, ...params);
// return rows.map(row => this.rowToEntity(entityType, row));
// Mock implementation
return [];
}
/**
* Save an entity to SQLite
*/
async save<T extends object>(entity: T): Promise<void> {
const entityType = entity.constructor as Type<T>;
const tableName = this.getTableName(entityType);
// Validate the entity before saving
const validation = this.reflector.validateEntity(entity);
Iif (!validation.valid) {
throw new Error(`Invalid entity: ${validation.errors.join(", ")}`);
}
// Convert entity to row
const row = this.entityToRow(entity);
console.log(`[SQLiteAdapter] Saving row to table ${tableName}:`, row);
// Get primary key
const primaryKey = this.getPrimaryKey(entityType);
const primaryKeyCol = this.toSnakeCase(primaryKey);
// Determine if this is an insert or update
let sql: string;
let params: any[];
if (row[primaryKeyCol] === undefined) {
// Insert - exclude primary key if it's undefined (autoincrement)
const cols = Object.keys(row).filter(
(col) => col !== primaryKeyCol || row[primaryKeyCol] !== undefined
);
const placeholders = cols.map(() => "?").join(", ");
sql = `INSERT INTO ${tableName} (${cols.join(
", "
)}) VALUES (${placeholders})`;
params = cols.map((col) => row[col]);
} else {
// Update
const setClauses = Object.keys(row)
.filter((col) => col !== primaryKeyCol)
.map((col) => `${col} = ?`)
.join(", ");
sql = `UPDATE ${tableName} SET ${setClauses} WHERE ${primaryKeyCol} = ?`;
params = [
...Object.keys(row)
.filter((col) => col !== primaryKeyCol)
.map((col) => row[col]),
row[primaryKeyCol],
];
}
console.log(`[SQLiteAdapter] SQL: ${sql}`, params);
// In a real implementation, this would execute the SQL
// const db = new SQLite3(this.databasePath);
// await db.run(sql, ...params);
}
/**
* Delete an entity from SQLite
*/
async delete<T>(entityType: Type<T>, id: string | number): Promise<void> {
const tableName = this.getTableName(entityType);
const primaryKey = this.getPrimaryKey(entityType);
const primaryKeyCol = this.toSnakeCase(primaryKey);
console.log(
`[SQLiteAdapter] Deleting from ${tableName} where ${primaryKeyCol} = ${id}`
);
const sql = `DELETE FROM ${tableName} WHERE ${primaryKeyCol} = ?`;
// In a real implementation, this would execute the SQL
// const db = new SQLite3(this.databasePath);
// await db.run(sql, id);
}
/**
* Execute a raw SQL query
*/
async runNativeQuery<T>(query: string, params?: any[]): Promise<T> {
console.log(`[SQLiteAdapter] Running SQL query: ${query}`);
console.log(`[SQLiteAdapter] Params:`, params);
// In a real implementation, this would execute the SQL
// const db = new SQLite3(this.databasePath);
//
// if (query.trim().toUpperCase().startsWith('SELECT')) {
// return db.all(query, ...(params || [])) as T;
// } else {
// return db.run(query, ...(params || [])) as T;
// }
return {} as T; // Mock result
}
/**
* Create schema for an entity type
* This would typically be called during setup to create tables
*/
async createSchema<T>(entityType: Type<T>): Promise<void> {
const tableName = this.getTableName(entityType);
const entitySchema = this.reflector.getEntitySchema(entityType);
const columns = this.getColumns(entityType);
const primaryKey = this.getPrimaryKey(entityType);
const foreignKeys = this.getForeignKeys(entityType);
// Build column definitions
const columnDefs: string[] = [];
// Add column definitions for each property
for (const [propName, propMeta] of Object.entries(
entitySchema.properties
)) {
const columnConfig = columns[propName] || {};
const columnName = columnConfig.name || this.toSnakeCase(propName);
let sqlType = columnConfig.type;
// Derive SQL type from property type if not specified
Iif (!sqlType) {
if ((propMeta as any).type === "string") {
sqlType = "TEXT";
} else if ((propMeta as any).type === "number") {
sqlType = "REAL";
} else if ((propMeta as any).type === "boolean") {
sqlType = "INTEGER"; // SQLite doesn't have a boolean type
} else if ((propMeta as any).type === "date") {
sqlType = "TEXT"; // Store dates as ISO strings
} else {
sqlType = "TEXT"; // Default to TEXT for objects (stored as JSON)
}
}
// Build column definition
let columnDef = `${columnName} ${sqlType}`;
// Add primary key constraint
Iif (propName === primaryKey) {
columnDef += " PRIMARY KEY";
Iif (sqlType === "INTEGER") {
columnDef += " AUTOINCREMENT";
}
}
// Add nullable constraint
Iif (columnConfig.nullable === false) {
columnDef += " NOT NULL";
}
// Add default value
Iif (columnConfig.defaultValue !== undefined) {
let defaultValue = columnConfig.defaultValue;
Iif (typeof defaultValue === "string") {
defaultValue = `'${defaultValue}'`;
}
columnDef += ` DEFAULT ${defaultValue}`;
}
columnDefs.push(columnDef);
}
// Add foreign key constraints
for (const fk of foreignKeys) {
const columnName = this.toSnakeCase(fk.column);
let constraint = `FOREIGN KEY (${columnName}) REFERENCES ${fk.references}(${fk.column})`;
Iif (fk.onDelete) {
constraint += ` ON DELETE ${fk.onDelete}`;
}
Iif (fk.onUpdate) {
constraint += ` ON UPDATE ${fk.onUpdate}`;
}
columnDefs.push(constraint);
}
const createTableSQL = `
CREATE TABLE IF NOT EXISTS ${tableName} (
${columnDefs.join(",\n ")}
)
`;
console.log(`[SQLiteAdapter] Creating table with SQL:`, createTableSQL);
// In a real implementation, this would execute the SQL
// const db = new SQLite3(this.databasePath);
// await db.run(createTableSQL);
// Create indexes
const indexes = this.getIndexes(entityType);
for (const index of indexes) {
const createIndexSQL = `
CREATE ${index.unique ? "UNIQUE " : ""}INDEX IF NOT EXISTS ${index.name}
ON ${tableName} (${this.toSnakeCase(index.column)})
`;
console.log(`[SQLiteAdapter] Creating index with SQL:`, createIndexSQL);
// In a real implementation, this would execute the SQL
// await db.run(createIndexSQL);
}
}
/**
* Mock method to simulate database query execution
* In a real implementation, this would use the SQLite library
*/
private async mockQueryExecution<T>(
entityType: Type<T>,
criteria: object
): Promise<T | null> {
// Just a mock implementation for demonstration
const primaryKey = this.getPrimaryKey(entityType);
const criteriaObj = criteria as Record<string, any>;
Iif (criteriaObj.hasOwnProperty(primaryKey) && criteriaObj[primaryKey] === "123") {
const entity = new entityType();
Object.assign(entity, {
id: "123",
name: "Mock SQLite Entity",
createdAt: new Date().toISOString(),
});
return entity;
}
return null;
}
}
|