All files / adapters neo4j.ts

36.77% Statements 82/223
8.2% Branches 11/134
39.13% Functions 18/46
36.4% Lines 79/217

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 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753  8x   8x           8x                 8x                 8x                                                                                                                                                                     8x 10x   10x   10x                                               10x 10x   10x       10x   7x     10x   10x       1x                                                                                       7x                                           20x   7x   7x                         7x 7x 7x                         10x 10x                   3x 3x               12x 12x       12x                                                                                                                                                                             5x 5x 5x   5x 5x     5x 3x 3x   3x 3x               2x 2x 2x 2x     2x           2x   2x 2x           5x                       2x 2x 2x   2x 2x     2x 2x 2x 2x     2x           2x   2x         2x                                                                                                                                                                                                                                                                                                         2x 2x 2x   2x 2x     2x         2x   2x                       1x 1x 1x   1x 1x     1x                                                                                                                                                                                                       1x   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';
 
/**
 * Neo4j-specific node label decorator
 */
export function Labels(labels: string[]) {
  return function(target: any) {
    Reflect.defineMetadata('neo4j:labels', labels, target);
  };
}
 
/**
 * Neo4j-specific relationship type decorator
 */
export function RelationshipType(type: string) {
  return function(target: any, propertyKey: string) {
    Reflect.defineMetadata('neo4j:relationshipType', type, target, propertyKey);
  };
}
 
/**
 * Shorthand decorator for Neo4j entities
 */
export function Neo4j<T extends { new (...args: any[]): any }>(target: T): T {
  return DatabaseAdapter('Neo4j')(target);
}
 
// Mock Neo4j types for testing - these would be replaced with real neo4j-driver in production
interface Neo4jNode {
  identity: { toString(): string };
  labels: string[];
  properties: { [key: string]: any };
}
 
interface Neo4jRelationship {
  identity: { toString(): string };
  type: string;
  properties: { [key: string]: any };
  startNodeId?: { toString(): string };
  endNodeId?: { toString(): string };
  startNodeIdentity?: { toString(): string };
  endNodeIdentity?: { toString(): string };
}
 
interface Neo4jPath {
  segments: Array<{
    start: Neo4jNode;
    relationship: Neo4jRelationship;
    end: Neo4jNode;
  }>;
}
 
interface Neo4jRecord {
  keys: string[];
  get(key: string): any;
}
 
interface Neo4jResult {
  records: Neo4jRecord[];
  summary: {
    counters: {
      updates(): { [key: string]: number };
    };
    resultAvailableAfter: number;
    resultConsumedAfter: number;
    database?: string;
    query: {
      text: string;
      parameters: Record<string, any>;
    };
  };
}
 
interface Neo4jTransaction {
  run(query: string, params?: Record<string, any>): Promise<Neo4jResult>;
  commit(): Promise<void>;
  rollback(): Promise<void>;
}
 
interface Neo4jSession {
  run(query: string, params?: Record<string, any>): Promise<Neo4jResult>;
  close(): Promise<void>;
  beginTransaction(): Neo4jTransaction;
}
 
interface Neo4jDriver {
  session(config?: { defaultAccessMode?: string; database?: string }): Neo4jSession;
  verifyConnectivity(): Promise<void>;
  close(): Promise<void>;
}
 
interface Neo4jAuth {
  basic(username: string, password: string): { username: string; password: string };
}
 
/**
 * Interface for Neo4j auth configuration
 */
export interface Neo4jAuthConfig {
  username: string;
  password: string;
}
 
/**
 * Implementation of DatabaseAdapter for Neo4j
 */
export class Neo4jAdapter implements DatabaseAdapter {
  readonly type = 'Neo4j';
  private registry: MetadataRegistry;
  private reflector = new SchemaReflector();
  private driver: Neo4jDriver;
  private initialized = false;
  private neo4j: {
    driver: (...args: any[]) => Neo4jDriver;
    session: { READ: string; WRITE: string };
    auth: Neo4jAuth;
    isNode?(value: any): value is Neo4jNode;
    isRelationship?(value: any): value is Neo4jRelationship;
    isPath?(value: any): value is Neo4jPath;
    isDate?(value: any): boolean;
    isDateTime?(value: any): boolean;
    isTime?(value: any): boolean;
    isLocalTime?(value: any): boolean;
    isLocalDateTime?(value: any): boolean;
    isDuration?(value: any): boolean;
  };
  
  /**
   * Constructor for Neo4j adapter
   * @param registry The metadata registry to use for schema information
   * @param connectionString The Neo4j connection string
   * @param auth The Neo4j authentication (username/password)
   */
  constructor(
    registry: MetadataRegistry, 
    private connectionString: string,
    private auth: Neo4jAuthConfig = { username: 'neo4j', password: 'password' }
  ) {
    this.registry = registry;
    
    // Create a mock neo4j object for testing
    // In production, this would be replaced with the real neo4j-driver
    this.neo4j = {
      driver: (url: string, auth: any, config?: any): Neo4jDriver => {
        return {
          verifyConnectivity: async () => {},
          session: (config?: any) => {
            return {
              run: async (query: string, params?: any): Promise<Neo4jResult> => {
                return { 
                  records: [],
                  summary: {
                    counters: {
                      updates: () => ({})
                    },
                    resultAvailableAfter: 0,
                    resultConsumedAfter: 0,
                    query: {
                      text: query,
                      parameters: params || {}
                    }
                  }
                };
              },
              close: async () => {},
              beginTransaction: () => {
                return {
                  run: async (query: string, params?: any): Promise<Neo4jResult> => {
                    return { 
                      records: [], 
                      summary: {
                        counters: {
                          updates: () => ({})
                        },
                        resultAvailableAfter: 0,
                        resultConsumedAfter: 0,
                        query: {
                          text: query,
                          parameters: params || {}
                        }
                      }
                    };
                  },
                  commit: async () => {},
                  rollback: async () => {}
                };
              }
            };
          },
          close: async () => {}
        };
      },
      session: {
        READ: 'READ',
        WRITE: 'WRITE'
      },
      auth: {
        basic: (username: string, password: string) => ({ username, password })
      },
      // Type checking helpers
      isNode: (value: any): value is Neo4jNode => 
        value && typeof value === 'object' && value.labels && value.properties,
      isRelationship: (value: any): value is Neo4jRelationship => 
        value && typeof value === 'object' && value.type && (value.startNodeId || value.startNodeIdentity),
      isPath: (value: any): value is Neo4jPath => 
        value && typeof value === 'object' && Array.isArray(value.segments),
      isDate: (value: any): boolean => false,
      isDateTime: (value: any): boolean => false,
      isTime: (value: any): boolean => false,
      isLocalTime: (value: any): boolean => false,
      isLocalDateTime: (value: any): boolean => false,
      isDuration: (value: any): boolean => false
    };
  }
  
  /**
   * Initialize the Neo4j connection
   */
  private async initialize(): Promise<void> {
    if (this.initialized) return;
    
    try {
      // In a real implementation, this would use the neo4j-driver package
      this.driver = this.neo4j.driver(
        this.connectionString,
        this.neo4j.auth.basic(this.auth.username, this.auth.password),
        {
          // Optional configuration
          maxConnectionLifetime: 3 * 60 * 60 * 1000, // 3 hours
          maxConnectionPoolSize: 50,
          connectionAcquisitionTimeout: 30 * 1000, // 30 seconds
          disableLosslessIntegers: true // Convert Neo4j integers to JavaScript numbers
        }
      );
      
      // Verify connectivity
      await this.driver.verifyConnectivity();
      this.initialized = true;
      console.log('[Neo4jAdapter] Successfully connected to Neo4j');
    } catch (error) {
      console.error('[Neo4jAdapter] Failed to connect to Neo4j:', error);
      throw error;
    }
  }
  
  /**
   * Get a Neo4j session with optional transaction mode
   * @param mode Session mode (READ or WRITE)
   * @returns A Neo4j session
   */
  private async getSession(mode: string = this.neo4j.session.WRITE): Promise<Neo4jSession> {
    await this.initialize();
    return this.driver.session({
      defaultAccessMode: mode,
      database: 'neo4j' // Use default database, can be configured if needed
    });
  }
  
  /**
   * Build a Cypher query to find an entity by its ID
   */
  private buildFindByIdQuery<T>(entityType: Type<T>): string {
    const labels = this.getEntityLabels(entityType);
    return `MATCH (n:${labels.join(':')} {id: $id}) RETURN n`;
  }
  
  /**
   * Get all Neo4j labels for an entity
   */
  private getEntityLabels<T>(entityType: Type<T>): string[] {
    // Get custom labels if defined, otherwise use the entity name
    const customLabels = Reflect.getMetadata('neo4j:labels', entityType);
    Iif (customLabels && Array.isArray(customLabels)) {
      return customLabels;
    }
    
    return [entityType.name];
  }
  
  /**
   * Get relationship type for a property
   */
  private getRelationshipType(entityType: Function, propertyKey: string): string {
    // Get custom relationship type if defined, otherwise use uppercase property name
    const customType = Reflect.getMetadata('neo4j:relationshipType', entityType.prototype, propertyKey);
    Iif (customType) {
      return customType;
    }
    
    // Look for relationship metadata
    const relationshipOptions = this.registry.getRelationshipMetadata(entityType, propertyKey);
    Iif (relationshipOptions?.name) {
      return relationshipOptions.name;
    }
    
    return propertyKey.toUpperCase();
  }
  
  /**
   * Convert Neo4j node to entity instance
   */
  private nodeToEntity<T>(entityType: Type<T>, node: any): T {
    const entity = new entityType();
    
    // Copy node properties to entity
    Iif (node && typeof node === 'object') {
      // Handle Neo4j Integer conversions
      const properties = node.properties ? { ...node.properties } : {};
      
      Object.keys(properties).forEach(key => {
        // Get the property value
        let value = properties[key];
        
        // Convert Neo4j date types to JavaScript types if needed
        if (this.neo4j.isDate && this.neo4j.isDate(value)) {
          value = value.toString(); // or value.toStandardDate() for Date object
        } else if (this.neo4j.isDateTime && this.neo4j.isDateTime(value)) {
          value = value.toString(); // or value.toStandardDate() for Date object
        } else if (this.neo4j.isLocalDateTime && this.neo4j.isLocalDateTime(value)) {
          value = value.toString();
        } else if (this.neo4j.isLocalTime && this.neo4j.isLocalTime(value)) {
          value = value.toString();
        } else Iif (this.neo4j.isTime && this.neo4j.isTime(value)) {
          value = value.toString();
        }
        
        // Assign the converted value to the entity
        (entity as any)[key] = value;
      });
    }
    
    return entity;
  }
  
  /**
   * Convert entity to Neo4j properties
   */
  private entityToProperties<T>(entity: T): { [key: string]: any } {
    const entityType = entity.constructor as Type<T>;
    const entitySchema = this.reflector.getEntitySchema(entityType);
    const properties: { [key: string]: any } = {};
    
    // Convert each property
    for (const [key, meta] of Object.entries(entitySchema.properties)) {
      Iif ((entity as any)[key] !== undefined) {
        const value = (entity as any)[key];
        
        // Handle Date objects (convert to ISO string)
        if (value instanceof Date) {
          properties[key] = value.toISOString();
        } else {
          properties[key] = value;
        }
      }
    }
    
    return properties;
  }
 
  /**
   * Query for a single entity by criteria
   */
  async query<T>(entityType: Type<T>, criteria: object): Promise<T | null> {
    try {
      await this.initialize();
      const session = await this.getSession(this.neo4j.session.READ);
      
      try {
        const labels = this.getEntityLabels(entityType);
        
        // If criteria includes an ID, use the optimized findById query
        if ('id' in criteria) {
          const query = this.buildFindByIdQuery(entityType);
          const result = await session.run(query, { id: criteria.id });
          
          if (result.records.length === 0) {
            return null;
          }
          
          const node = result.records[0].get('n');
          return this.nodeToEntity(entityType, node);
        }
        
        // Otherwise, build a query based on criteria
        let whereClause = '';
        if (Object.keys(criteria).length > 0) {
          const conditions = Object.keys(criteria).map(key => `n.${key} = $${key}`).join(' AND ');
          whereClause = `WHERE ${conditions}`;
        }
        
        const query = `
          MATCH (n:${labels.join(':')})
          ${whereClause}
          RETURN n LIMIT 1
        `;
        
        const result = await session.run(query, criteria);
        
        if (result.records.length === 0) {
          return null;
        }
        
        const node = result.records[0].get('n');
        return this.nodeToEntity(entityType, node);
      } finally {
        await session.close();
      }
    } catch (error) {
      console.error('[Neo4jAdapter] 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 session = await this.getSession(this.neo4j.session.READ);
      
      try {
        const labels = this.getEntityLabels(entityType);
        
        // Build the query based on criteria
        let whereClause = '';
        if (Object.keys(criteria).length > 0) {
          const conditions = Object.keys(criteria).map(key => `n.${key} = $${key}`).join(' AND ');
          whereClause = `WHERE ${conditions}`;
        }
        
        const query = `
          MATCH (n:${labels.join(':')})
          ${whereClause}
          RETURN n
        `;
        
        const result = await session.run(query, criteria);
        
        return result.records.map(record => {
          const node = record.get('n');
          return this.nodeToEntity(entityType, node);
        });
      } finally {
        await session.close();
      }
    } catch (error) {
      console.error('[Neo4jAdapter] Error in queryMany:', error);
      throw error;
    }
  }
  
  /**
   * Save an entity to Neo4j
   */
  async save<T>(entity: T): Promise<void> {
    try {
      await this.initialize();
      const session = await this.getSession(this.neo4j.session.WRITE);
      
      try {
        // Start a transaction for atomicity
        const tx = session.beginTransaction();
        
        try {
          const entityType = entity.constructor as Type<T>;
          const entitySchema = this.reflector.getEntitySchema(entityType);
          const labels = this.getEntityLabels(entityType);
          
          // Validate the entity before saving
          const validation = this.reflector.validateEntity(entity);
          Iif (!validation.valid) {
            throw new Error(`Invalid entity: ${validation.errors.join(', ')}`);
          }
          
          // Extract properties
          const properties = this.entityToProperties(entity);
          
          // Create or update the node
          const createNodeQuery = `
            MERGE (n:${labels.join(':')} {id: $id})
            SET n += $props
            RETURN n
          `;
          
          await tx.run(createNodeQuery, {
            id: properties['id'],
            props: properties
          });
          
          // Handle relationships
          for (const [key, relationshipMetaUntyped] of Object.entries(entitySchema.relationships || {})) {
            const relationshipMeta = relationshipMetaUntyped as RelationshipOptions;
            const relatedEntity = (entity as any)[key];
            Iif (!relatedEntity) continue;
            
            const relationshipType = this.getRelationshipType(entityType, key);
            
            // Handle different relationship cardinalities
            if (relationshipMeta.cardinality === 'one') {
              // Handle one-to-one or many-to-one relationship
              const relatedProperties = this.entityToProperties(relatedEntity);
              const relatedLabels = this.getEntityLabels(relationshipMeta.target as Type<any>);
              
              // Create or update the related node first
              const createRelatedNodeQuery = `
                MERGE (m:${relatedLabels.join(':')} {id: $id})
                SET m += $props
                RETURN m
              `;
              
              await tx.run(createRelatedNodeQuery, {
                id: relatedProperties['id'],
                props: relatedProperties
              });
              
              // Create the relationship
              const createRelationshipQuery = `
                MATCH (n:${labels.join(':')} {id: $nodeId})
                MATCH (m:${relatedLabels.join(':')} {id: $relatedId})
                MERGE (n)-[r:${relationshipType}]->(m)
                RETURN r
              `;
              
              await tx.run(createRelationshipQuery, {
                nodeId: properties['id'],
                relatedId: relatedProperties['id']
              });
            } else Iif (relationshipMeta.cardinality === 'many' && Array.isArray(relatedEntity)) {
              // Handle one-to-many or many-to-many relationship
              // First, delete existing relationships
              const deleteRelationshipsQuery = `
                MATCH (n:${labels.join(':')} {id: $nodeId})-[r:${relationshipType}]->()
                DELETE r
              `;
              
              await tx.run(deleteRelationshipsQuery, {
                nodeId: properties['id']
              });
              
              // Then create nodes and relationships for each related entity
              for (const related of relatedEntity) {
                const relatedProperties = this.entityToProperties(related);
                const relatedLabels = this.getEntityLabels(relationshipMeta.target as Type<any>);
                
                // Create or update the related node
                const createRelatedNodeQuery = `
                  MERGE (m:${relatedLabels.join(':')} {id: $id})
                  SET m += $props
                  RETURN m
                `;
                
                await tx.run(createRelatedNodeQuery, {
                  id: relatedProperties['id'],
                  props: relatedProperties
                });
                
                // Create the relationship
                const createRelationshipQuery = `
                  MATCH (n:${labels.join(':')} {id: $nodeId})
                  MATCH (m:${relatedLabels.join(':')} {id: $relatedId})
                  MERGE (n)-[r:${relationshipType}]->(m)
                  RETURN r
                `;
                
                await tx.run(createRelationshipQuery, {
                  nodeId: properties['id'],
                  relatedId: relatedProperties['id']
                });
              }
            }
          }
          
          // Commit the transaction
          await tx.commit();
        } catch (error) {
          // Rollback transaction on error
          await tx.rollback();
          throw error;
        }
      } finally {
        await session.close();
      }
    } catch (error) {
      console.error('[Neo4jAdapter] Error in save:', error);
      throw error;
    }
  }
  
  /**
   * Delete an entity from Neo4j
   */
  async delete<T>(entityType: Type<T>, id: string | number): Promise<void> {
    try {
      await this.initialize();
      const session = await this.getSession(this.neo4j.session.WRITE);
      
      try {
        const labels = this.getEntityLabels(entityType);
        
        // Delete the node and all its relationships
        const query = `
          MATCH (n:${labels.join(':')} {id: $id})
          DETACH DELETE n
        `;
        
        await session.run(query, { id });
      } finally {
        await session.close();
      }
    } catch (error) {
      console.error('[Neo4jAdapter] Error in delete:', error);
      throw error;
    }
  }
  
  /**
   * Execute a raw Cypher query
   */
  async runNativeQuery<T = any>(query: string, params?: Record<string, any>): Promise<T> {
    try {
      await this.initialize();
      const session = await this.getSession();
      
      try {
        const result = await session.run(query, params);
        
        // Convert Neo4j result to a more usable format
        const convertedResult = {
          records: result.records.map(record => {
            const obj: { [key: string]: any } = {};
            
            for (let i = 0; i < record.keys.length; i++) {
              const key = record.keys[i];
              // Skip if key is a symbol
              Iif (typeof key === 'symbol') continue;
              const value = record.get(key);
              
              // Handle Neo4j Node objects
              if (value && this.neo4j.isNode && this.neo4j.isNode(value)) {
                obj[key] = {
                  ...(value.properties || {}),
                  _labels: value.labels,
                  _id: value.identity.toString()
                };
              } 
              // Handle Neo4j Relationship objects
              else if (value && this.neo4j.isRelationship && this.neo4j.isRelationship(value)) {
                // Check what properties are available for the relationship
                // Neo4j JS driver has changed property names in different versions
                const startId = 
                  (value.startNodeIdentity && value.startNodeIdentity.toString()) || 
                  (value.startNodeId && value.startNodeId.toString()) || 
                  "unknown";
                
                const endId = 
                  (value.endNodeIdentity && value.endNodeIdentity.toString()) || 
                  (value.endNodeId && value.endNodeId.toString()) || 
                  "unknown";
                
                obj[key] = {
                  ...(value.properties || {}),
                  _type: value.type,
                  _id: value.identity.toString(),
                  _startNodeId: startId,
                  _endNodeId: endId
                };
              }
              // Handle Neo4j Path objects
              else if (value && this.neo4j.isPath && this.neo4j.isPath(value)) {
                const segments = [];
                Iif (value.segments && Array.isArray(value.segments)) {
                  for (const segment of value.segments) {
                    segments.push({
                      start: {
                        ...(segment.start.properties || {}),
                        _labels: segment.start.labels,
                        _id: segment.start.identity.toString()
                      },
                      relationship: {
                        ...(segment.relationship.properties || {}),
                        _type: segment.relationship.type,
                        _id: segment.relationship.identity.toString()
                      },
                      end: {
                        ...(segment.end.properties || {}),
                        _labels: segment.end.labels,
                        _id: segment.end.identity.toString()
                      }
                    });
                  }
                }
                obj[key] = { segments };
              }
              // Handle other Neo4j types
              else if (value && typeof value === 'object' && value.constructor) {
                // Handle date/time types
                if ((this.neo4j.isDateTime && this.neo4j.isDateTime(value)) || 
                    (this.neo4j.isDate && this.neo4j.isDate(value)) || 
                    (this.neo4j.isTime && this.neo4j.isTime(value)) || 
                    (this.neo4j.isLocalDateTime && this.neo4j.isLocalDateTime(value)) || 
                    (this.neo4j.isLocalTime && this.neo4j.isLocalTime(value)) || 
                    (this.neo4j.isDuration && this.neo4j.isDuration(value))) {
                  obj[key] = value.toString();
                } else {
                  // For other objects, convert to plain object safely
                  obj[key] = typeof value === 'object' && value !== null ? Object.assign({}, value) : value;
                }
              } else {
                // For primitive values
                obj[key] = value;
              }
            }
            
            return obj;
          }),
          summary: {
            counters: result.summary.counters ? result.summary.counters.updates() : {},
            resultAvailableAfter: result.summary.resultAvailableAfter,
            resultConsumedAfter: result.summary.resultConsumedAfter,
            database: result.summary.database,
            query: {
              text: result.summary.query.text,
              parameters: result.summary.query.parameters
            }
          }
        };
        
        return convertedResult as unknown as T;
      } finally {
        await session.close();
      }
    } catch (error) {
      console.error('[Neo4jAdapter] Error in runNativeQuery:', error);
      throw error;
    }
  }
  
  /**
   * Close the Neo4j driver when done
   */
  async close(): Promise<void> {
    Iif (this.driver) {
      await this.driver.close();
      this.initialized = false;
      console.log('[Neo4jAdapter] Connection to Neo4j closed');
    }
  }
}