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 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 | 2x 2x 2x 2x 2x 2x 2x 2x 76x 76x 76x 76x 76x 76x 366x 8x 8x 12x 12x 8x 8x 183x 183x 1x 182x 169x 169x 169x 10188x 10188x 10188x 10188x 10188x 10188x 10188x 71298x 71298x 10188x 10000x 10000x 10000x 70000x 30000x 10000x 26x 26x 26x 26x 182x 81x 26x 141x 141x 140x 134x 134x 134x 134x 134x 137x 137x 134x 137x 134x 134x 129x 129x 134x 13x 13x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 10000x 4x 28x 28x 28x 28x 28x 28x 28x 28x 2x 26x 26x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 21x 19x 19x 1x 3x 2x 1x 1x 3x 2x 1x 18x 18x 57x 18x 18x 15x 16x 21x 13x 28x 28x 28x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 8x 8x 8x 8x 8x 5x 8x 3x 3x 2x 1x | import { Type } from '../core/types';
import { DatabaseAdapter } from './interface';
import { MetadataRegistry } from '../core/MetadataRegistry';
import { SchemaReflector } from '../core/SchemaReflector';
import { RelationshipOptions } from '../core/types';
// Renamed from Index to PgIndex to avoid naming conflict with MongoDB
export function PgIndex(options: {
name?: string;
columns: string[];
unique?: boolean;
method?: 'btree' | 'hash' | 'gist' | 'gin';
} = { columns: [] }) {
return function(target: any) {
const existingIndexes = Reflect.getMetadata('postgres:indexes', target) || [];
existingIndexes.push(options);
Reflect.defineMetadata('postgres:indexes', existingIndexes, target);
};
}
/**
* PostgreSQL-specific table decorator
*/
export function Table(tableName: string) {
return function(target: any) {
Reflect.defineMetadata('postgres:table', tableName, target);
};
}
/**
* PostgreSQL-specific column decorator
*/
export function Column(options: {
name?: string;
type?: string;
nullable?: boolean;
default?: any;
primary?: boolean;
unique?: boolean;
} = {}) {
return function(target: any, propertyKey: string) {
const existingColumns = Reflect.getMetadata('postgres:columns', target.constructor) || {};
existingColumns[propertyKey] = {
...options,
fieldName: options.name || propertyKey
};
Reflect.defineMetadata('postgres:columns', existingColumns, target.constructor);
};
}
/**
* PostgreSQL-specific join table decorator for many-to-many relations
*/
export function JoinTable(options: {
name: string;
joinColumn: string;
inverseJoinColumn: string;
}) {
return function(target: any, propertyKey: string) {
Reflect.defineMetadata('postgres:joinTable', options, target, propertyKey);
};
}
/**
* Shorthand decorator for PostgreSQL entities
*/
export function PostgreSQL<T extends { new (...args: any[]): any }>(target: T): T {
return DatabaseAdapter('PostgreSQL')(target);
}
/**
* Types to simulate pg library
*/
interface Pool {
connect(): Promise<PoolClient>;
end(): Promise<void>;
}
interface PoolClient {
query(text: string, params?: any[]): Promise<QueryResult>;
release(): void;
}
interface QueryResult {
rows: any[];
rowCount: number;
}
/**
* Implementation of DatabaseAdapter for PostgreSQL
*/
export class PostgreSQLAdapter implements DatabaseAdapter {
readonly type = 'PostgreSQL';
private registry: MetadataRegistry;
private reflector = new SchemaReflector();
private pool: Pool | null = null;
private initialized = false;
/**
* Constructor for PostgreSQL adapter
* @param registry The metadata registry to use for schema information
* @param connectionString The PostgreSQL connection string
*/
constructor(registry: MetadataRegistry, private connectionString: string) {
this.registry = registry;
}
/**
* Initialize the PostgreSQL connection pool
*/
private async initialize(): Promise<void> {
if (this.initialized) return;
try {
// Mock pool implementation for testing
this.pool = {
connect: async () => {
return {
query: async (text: string, params?: any[]) => {
return {
rows: [],
rowCount: 0
};
},
release: () => {}
};
},
end: async () => {}
};
this.initialized = true;
console.log('[PostgreSQLAdapter] Successfully connected to PostgreSQL');
} catch (error) {
console.error('[PostgreSQLAdapter] Failed to connect to PostgreSQL:', error);
throw error;
}
}
/**
* Get a PostgreSQL client from the pool
*/
private async getClient(): Promise<PoolClient> {
await this.initialize();
if (!this.pool) {
throw new Error('Pool not initialized');
}
return this.pool.connect();
}
/**
* 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 in snake_case
const tableName = Reflect.getMetadata('postgres:table', entityType);
Iif (tableName) {
return tableName;
}
// Convert from PascalCase to snake_case
return entityType.name
.replace(/([A-Z])/g, '_$1')
.toLowerCase()
.substring(1); // Remove leading underscore
}
/**
* Get column definitions for an entity type
*/
private getColumns<T>(entityType: Type<T>): Record<string, any> {
return Reflect.getMetadata('postgres:columns', entityType) || {};
}
/**
* Get join table definition for a relationship
*/
private getJoinTable<T>(entityType: Type<T>, propertyKey: string): any {
return Reflect.getMetadata('postgres:joinTable', entityType.prototype, propertyKey);
}
/**
* Map entity property names to database column names
*/
private getColumnMapping<T>(entityType: Type<T>): Record<string, string> {
const columns = this.getColumns(entityType);
const mapping: Record<string, string> = {};
// Add explicitly defined columns
for (const [prop, options] of Object.entries(columns)) {
mapping[prop] = options.fieldName || prop;
}
// Add properties from registry
const properties = this.registry.getAllProperties(entityType);
if (properties) {
for (const [prop] of properties.entries()) {
if (!mapping[prop]) {
// Convert from camelCase to snake_case for default mapping
mapping[prop] = prop.replace(/([A-Z])/g, '_$1').toLowerCase();
}
}
}
return mapping;
}
/**
* Convert database row to entity instance
*/
private rowToEntity<T>(entityType: Type<T>, row: any): T {
const entity = new entityType();
const columnMapping = this.getColumnMapping(entityType);
// Map database columns back to entity properties
for (const [prop, col] of Object.entries(columnMapping)) {
if (row[col] !== undefined) {
(entity as any)[prop] = row[col];
}
}
return entity;
}
/**
* Convert entity to database row
*/
private entityToRow<T>(entity: T): Record<string, any> {
const entityType = entity.constructor as Type<T>;
const columnMapping = this.getColumnMapping(entityType);
const row: Record<string, any> = {};
// Map entity properties to database columns
for (const [prop, col] of Object.entries(columnMapping)) {
if ((entity as any)[prop] !== undefined) {
row[col] = (entity as any)[prop];
}
}
return row;
}
/**
* Query for a single entity by criteria
*/
async query<T>(entityType: Type<T>, criteria: object): Promise<T | null> {
try {
await this.initialize();
const client = await this.getClient();
try {
const tableName = this.getTableName(entityType);
const columnMapping = this.getColumnMapping(entityType);
// Convert criteria from entity properties to database columns
const dbCriteria: Record<string, any> = {};
for (const [prop, value] of Object.entries(criteria)) {
const col = columnMapping[prop] || prop;
dbCriteria[col] = value;
}
// Build WHERE clause
const whereClause = Object.keys(dbCriteria)
.map((col, index) => `${col} = $${index + 1}`)
.join(' AND ');
const query = `
SELECT * FROM ${tableName}
${whereClause ? `WHERE ${whereClause}` : ''}
LIMIT 1
`;
const result = await client.query(query, Object.values(dbCriteria));
if (result.rows.length === 0) {
return null;
}
return this.rowToEntity(entityType, result.rows[0]);
} finally {
client.release();
}
} catch (error) {
console.error('[PostgreSQLAdapter] Error in query:', error);
throw error;
}
}
/**
* Query for multiple entities by criteria
*/
async queryMany<T>(entityType: Type<T>, criteria: object): Promise<T[]> {
try {
await this.initialize();
const client = await this.getClient();
try {
const tableName = this.getTableName(entityType);
const columnMapping = this.getColumnMapping(entityType);
// Convert criteria from entity properties to database columns
const dbCriteria: Record<string, any> = {};
for (const [prop, value] of Object.entries(criteria)) {
const col = columnMapping[prop] || prop;
dbCriteria[col] = value;
}
// Build WHERE clause
let query = `SELECT * FROM ${tableName}`;
const params: any[] = [];
if (Object.keys(dbCriteria).length > 0) {
const whereClause = Object.keys(dbCriteria)
.map((col, index) => {
params.push(dbCriteria[col]);
return `${col} = $${index + 1}`;
})
.join(' AND ');
query += ` WHERE ${whereClause}`;
}
const result = await client.query(query, params);
return result.rows.map(row => this.rowToEntity(entityType, row));
} finally {
client.release();
}
} catch (error) {
console.error('[PostgreSQLAdapter] Error in queryMany:', error);
throw error;
}
}
/**
* Save an entity to PostgreSQL
*/
async save<T>(entity: T): Promise<void> {
try {
await this.initialize();
const client = await this.getClient();
try {
const entityType = entity.constructor as Type<T>;
const tableName = this.getTableName(entityType);
// Validate the entity before saving
const validation = this.reflector.validateEntity(entity);
if (!validation.valid) {
throw new Error(`Invalid entity: ${validation.errors.join(', ')}`);
}
// Convert entity to database row
const row = this.entityToRow(entity);
// Start a transaction
await client.query('BEGIN');
try {
// Check if entity exists (has an ID and exists in the database)
const idProps = this.registry.getIdProperties(entityType);
Iif (!idProps || idProps.size === 0) {
throw new Error(`Entity ${entityType.name} has no ID property defined`);
}
// Get the first ID property
const idProperty = Array.from(idProps)[0] as string;
const columnMapping = this.getColumnMapping(entityType);
const idColumnName = columnMapping[idProperty] || idProperty;
const idValue = row[idColumnName];
let entityExists = false;
if (idValue) {
const checkQuery = `
SELECT 1 FROM ${tableName}
WHERE ${idColumnName} = $1
LIMIT 1
`;
const checkResult = await client.query(checkQuery, [idValue]);
entityExists = checkResult.rows.length > 0;
}
let result: QueryResult;
if (entityExists) {
// Update existing entity
const setClauses = Object.keys(row)
.filter(col => col !== idColumnName)
.map((col, index) => `${col} = $${index + 2}`)
.join(', ');
const updateQuery = `
UPDATE ${tableName}
SET ${setClauses}
WHERE ${idColumnName} = $1
RETURNING *
`;
const updateValues = [idValue, ...Object.entries(row)
.filter(([col]) => col !== idColumnName)
.map(([_, value]) => value)];
result = await client.query(updateQuery, updateValues);
} else {
// Insert new entity
const columns = Object.keys(row).join(', ');
const placeholders = Object.keys(row)
.map((_, index) => `$${index + 1}`)
.join(', ');
const insertQuery = `
INSERT INTO ${tableName} (${columns})
VALUES (${placeholders})
RETURNING *
`;
result = await client.query(insertQuery, Object.values(row));
// Update the ID if it was auto-generated
Iif (!idValue && result.rows.length > 0) {
(entity as any)[idProperty] = result.rows[0][idColumnName];
}
}
// Handle relationships
const entitySchema = this.reflector.getEntitySchema(entityType);
for (const [propKey, relationshipMetaUntyped] of Object.entries(entitySchema.relationships)) {
const relationshipMeta = relationshipMetaUntyped as RelationshipOptions;
const relatedEntity = (entity as any)[propKey];
Iif (!relatedEntity) continue;
const targetType = relationshipMeta.target as Type<any>;
const targetTableName = this.getTableName(targetType);
// Handle different relationship cardinalities
if (relationshipMeta.cardinality === 'one') {
// Handle one-to-one or many-to-one relationship
// Save the related entity and set up foreign key
await this.save(relatedEntity);
// For one-to-one or many-to-one, typically we just saved the related entity
// And the foreign key is already in our entity
} else Iif (relationshipMeta.cardinality === 'many' && Array.isArray(relatedEntity)) {
// Handle one-to-many or many-to-many relationship
// For many-to-many, we need a join table
const joinTable = this.getJoinTable(entityType, propKey);
if (joinTable) {
// Many-to-many with explicit join table
const joinTableName = joinTable.name;
const sourceColumn = joinTable.joinColumn;
const targetColumn = joinTable.inverseJoinColumn;
// First, delete existing relationships
const deleteQuery = `
DELETE FROM ${joinTableName}
WHERE ${sourceColumn} = $1
`;
await client.query(deleteQuery, [idValue]);
// Then insert new relationships
for (const related of relatedEntity) {
// Save the related entity first
await this.save(related);
// Get the related entity's ID
const relatedIdProps = this.registry.getIdProperties(targetType);
Iif (!relatedIdProps || relatedIdProps.size === 0) {
throw new Error(`Entity ${targetType.name} has no ID property defined`);
}
// Get the first ID property
const relatedIdProperty = Array.from(relatedIdProps)[0] as string;
const relatedIdValue = (related as any)[relatedIdProperty];
// Insert into join table
const insertJoinQuery = `
INSERT INTO ${joinTableName} (${sourceColumn}, ${targetColumn})
VALUES ($1, $2)
`;
await client.query(insertJoinQuery, [idValue, relatedIdValue]);
}
} else {
// One-to-many (or implicit many-to-many without join table)
// Just save each related entity
for (const related of relatedEntity) {
// Handle back-reference if an inverse relationship exists
Iif (relationshipMeta.inverse) {
// Set the back-reference to this entity
(related as any)[relationshipMeta.inverse] = entity;
}
// Save the related entity
await this.save(related);
}
}
}
}
// Commit the transaction
await client.query('COMMIT');
} catch (error) {
// Rollback on error
await client.query('ROLLBACK');
throw error;
}
} finally {
client.release();
}
} catch (error) {
console.error('[PostgreSQLAdapter] Error in save:', error);
throw error;
}
}
/**
* Delete an entity from PostgreSQL
*/
async delete<T>(entityType: Type<T>, id: string | number): Promise<void> {
try {
await this.initialize();
const client = await this.getClient();
try {
const tableName = this.getTableName(entityType);
// Get the ID column name
const idProps = this.registry.getIdProperties(entityType);
Iif (!idProps || idProps.size === 0) {
throw new Error(`Entity ${entityType.name} has no ID property defined`);
}
const idProperty = Array.from(idProps)[0] as string;
const columnMapping = this.getColumnMapping(entityType);
const idColumnName = columnMapping[idProperty] || idProperty;
// Delete the entity
const query = `DELETE FROM ${tableName} WHERE ${idColumnName} = $1`;
await client.query(query, [id]);
} finally {
client.release();
}
} catch (error) {
console.error('[PostgreSQLAdapter] Error in delete:', error);
throw error;
}
}
/**
* Execute a raw SQL query
*/
async runNativeQuery<T>(query: string, params?: any[]): Promise<T> {
try {
await this.initialize();
const client = await this.getClient();
try {
const result = await client.query(query, params);
return { rows: result.rows, rowCount: result.rowCount } as unknown as T;
} finally {
client.release();
}
} catch (error) {
console.error('[PostgreSQLAdapter] Error in runNativeQuery:', error);
throw error;
}
}
/**
* Close the connection pool when done
*/
async close(): Promise<void> {
if (this.pool) {
await this.pool.end();
this.initialized = false;
}
}
} |