All files / database/src model.js

87.98% Statements 315/358
75.56% Branches 266/352
96.66% Functions 58/60
88.15% Lines 305/346

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 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830                  43x 24x 24x                 101x 101x 7x       94x                 8x 8x                       82x                   23x       23x 23x 2x     21x 22x 22x 1x   20x 1x           18x                 7x 7x 1x       6x                     109x 109x 109x 109x     109x 109x 101x 101x 5x               5x 5x 5x 5x 5x 5x 5x 5x 5x 5x               26x 26x 26x                   13x 13x       12x 13x 12x 13x                             33x 33x   33x 33x 84x 21x               33x 33x 32x       3x 3x 2x   1x       8x 8x 14x                   12x 12x 12x 9x                     7x 7x 7x 4x                   7x 7x 7x 4x       27x       37x   164x 102x   62x         5x     219x 219x 219x 213x   219x         37x 37x   37x 79x 4x 4x   75x 2x 2x   73x   37x         229x 229x 229x   11x 2x 2x 3x 1x 1x 2x           91x 3x 2x 5x 2x       6x 6x 5x 5x   6x       1x         53x 53x     53x 9x     44x 82x       82x 8x       74x   25x 25x 25x 25x 1x 1x                                                     74x 49x 2x 2x     49x 2x 2x     49x 19x 1x 1x       49x 14x           49x 14x     14x 1x 1x           44x 6x     6x         6x 4x       2x 2x 1x 1x 1x       1x 1x 1x 1x 1x               38x 38x                       49x 49x   49x 47x     46x   49x 37x 1x 1x   37x 1x 1x       37x 32x 32x     37x 37x   2x   37x   37x     37x 37x 34x     37x 37x 1x 1x   37x 1x 1x       9x 1x     8x 8x       8x     8x 8x     8x 8x 8x   8x     45x 45x 45x                     6x 6x 6x   6x 1x     5x     5x   4x   4x   4x   4x                   8x 8x 8x   8x 1x     7x   7x     3x 3x 3x   3x       3x 3x       3x 3x 3x   3x       3x 3x                   7x           9x         1x 8x         8x       8x           18x 18x       18x     18x 14x 14x         18x 1x 1x 1x   1x   1x 1x                   1x       18x 1x 1x   1x       1x     18x       8x               34x   34x     34x 20x     14x         13x         13x       3x       1x       9x     9x 9x 9x             3x       3x       2x       2x         8x           8x     7x                 8x   8x 8x   8x             1x   1x 2x 2x       2x     1x                      
/**
 * Pure Object-Based Model System for Coherent.js
 *
 * @fileoverview Core model system using pure JavaScript objects for consistency
 */
 
import { executeQuery, assertIdentifier } from './query-builder.js';
 
function isPlainObject(value) {
  if (value === null || typeof value !== 'object') return false;
  const proto = Object.getPrototypeOf(value);
  return proto === Object.prototype || proto === null;
}
 
/**
 * The database a model class queries, or a clear error when none is set.
 *
 * @private
 */
function requireDatabase(ModelClass, options = {}) {
  const db = options.transaction || ModelClass.db;
  if (!db || typeof db.query !== 'function') {
    throw new Error(
      `${ModelClass.name} has no database connection. Call ${ModelClass.name}.setDatabase(db) before querying.`
    );
  }
  return db;
}
 
/**
 * Number of rows a write changed, as reported by the driver.
 *
 * @private
 */
function affectedRowsOf(result) {
  for (const key of ['affectedRows', 'changes', 'rowCount']) {
    Eif (typeof result?.[key] === 'number') return result[key];
  }
  return 0;
}
 
/**
 * Whether inserts must ask for generated keys with RETURNING (PostgreSQL reports no
 * insert id otherwise). A transaction has no config, so check the owning database too.
 *
 * @private
 */
function usesReturning(...databases) {
  return databases.some(db => db?.config?.type === 'postgresql');
}
 
/**
 * Validate `{ column: value }` equality conditions. Operator objects are rejected so a
 * request body cannot turn `where({ id })` into `id > 0`.
 *
 * @private
 */
function equalityConditions(conditions, context, { requireOne = false } = {}) {
  Iif (!isPlainObject(conditions)) {
    throw new Error(`${context} expects an object of column/value pairs`);
  }
 
  const entries = Object.entries(conditions);
  if (requireOne && entries.length === 0) {
    throw new Error(`${context} requires at least one condition`);
  }
 
  for (const [column, value] of entries) {
    assertIdentifier(column, context);
    if (value === undefined) {
      throw new Error(`${context}: value for ${column} is undefined`);
    }
    if (isPlainObject(value) || Array.isArray(value)) {
      throw new Error(
        `${context}: value for ${column} must be a single value. Use executeQuery() for operators such as in, like or >.`
      );
    }
  }
 
  return conditions;
}
 
/**
 * Resolve a relationship's `model`: a model class, or the name of one registered globally.
 *
 * @private
 */
function resolveRelatedModel(model, name, owner) {
  const Related = typeof model === 'function' ? model : (typeof model === 'string' ? globalThis[model] : undefined);
  if (typeof Related !== 'function') {
    throw new Error(
      `Related model ${String(model)} for relationship '${name}' on ${owner} not found. Pass the model class as \`model\`.`
    );
  }
  return Related;
}
 
/**
 * Model base class for database operations
 *
 * Set a connection with `Model.setDatabase(db)` (a DatabaseManager, a transaction, or
 * anything with `query(sql, params)`); every query method throws without one.
 */
export class Model {
  constructor(attributes = {}) {
    this.attributes = attributes || {};
    this.originalAttributes = { ...this.attributes };
    this._isNew = !this.attributes[this.constructor.primaryKey || 'id'];
    this._isDirty = false;
 
    // Relationship accessors: user.posts() resolves relationships.posts
    const relationships = this.constructor.relationships || this.constructor.relations || {};
    for (const name of Object.keys(relationships)) {
      Eif (!(name in this)) {
        Object.defineProperty(this, name, {
          value: () => this.getRelation(name),
          configurable: true,
          writable: true
        });
      }
    }
  }
 
  static tableName = 'models';
  static attributes = {};
  static db = null;
  static primaryKey = 'id';
  static fillable = [];
  static guarded = [];
  static hidden = [];
  static casts = {};
  static validationRules = {};
  static relations = {};
 
  /**
   * Build a persisted instance from a database row.
   *
   * @private
   */
  static _fromRow(row) {
    const instance = new this(row);
    instance._isNew = false;
    return instance;
  }
 
  /**
   * Find a record by primary key.
   *
   * @param {*} id - Primary key value
   * @returns {Promise<Model|null>} The record, or null when no row matches
   */
  static async find(id) {
    const db = requireDatabase(this);
    Iif (id === undefined || id === null) {
      return null;
    }
 
    const primaryKey = this.primaryKey || 'id';
    const result = await executeQuery(db, { table: this.tableName, where: { [primaryKey]: id }, limit: 1 });
    const row = result?.rows?.[0];
    return row ? this._fromRow(row) : null;
  }
 
  /**
   * Insert a new record from `attributes`, applying `fillable` / `guarded`
   * like fill(): `User.create(req.body)` used to write every key the client
   * sent (`role: 'admin'` included). Defaults from `static attributes` fill
   * whatever is left unset.
   *
   * @param {Object} attributes - Column values; keys outside `fillable` (or in
   *   `guarded`) are ignored
   * @param {Object} [options] - save() options, e.g. `{ transaction: tx }`
   * @returns {Promise<Model>} The saved instance
   */
  static async create(attributes = {}, options = {}) {
    const instance = new this();
    instance.fill(attributes ?? {});
 
    Eif (this.attributes) {
      for (const [key, config] of Object.entries(this.attributes)) {
        if (config.default !== undefined && instance.attributes[key] === undefined) {
          instance.setAttribute(key, config.default);
        }
      }
    }
 
    // Always an insert: built with the constructor, a model given its
    // primary key counted as already saved, so create({ id: 5, ... }) ran no
    // query at all and returned a record that did not exist.
    instance._isNew = true;
    await instance.save(options);
    return instance;
  }
 
  static async findOrFail(id) {
    const instance = await this.find(id);
    if (!instance) {
      throw new Error(`${this.name} with id ${id} not found`);
    }
    return instance;
  }
 
  static async all() {
    const db = requireDatabase(this);
    const result = await executeQuery(db, { table: this.tableName });
    return (result?.rows || []).map(row => this._fromRow(row));
  }
 
  /**
   * Find records whose columns equal the given values.
   *
   * @param {Object} conditions - `{ column: value }` pairs (null matches NULL)
   * @returns {Promise<Model[]>} Matching records
   */
  static async where(conditions) {
    const db = requireDatabase(this);
    const where = equalityConditions(conditions, `${this.name}.where()`);
    const result = await executeQuery(db, { table: this.tableName, where });
    return (result?.rows || []).map(row => this._fromRow(row));
  }
 
  /**
   * Update records whose columns equal the given values.
   *
   * @param {Object} conditions - `{ column: value }` pairs; at least one is required
   * @param {Object} updates - Columns to set
   * @returns {Promise<number>} Number of rows the driver reports as changed
   */
  static async updateWhere(conditions, updates) {
    const db = requireDatabase(this);
    const where = equalityConditions(conditions, `${this.name}.updateWhere()`, { requireOne: true });
    const result = await executeQuery(db, { table: this.tableName, update: updates, where });
    return affectedRowsOf(result);
  }
 
  /**
   * Delete records whose columns equal the given values.
   *
   * @param {Object} conditions - `{ column: value }` pairs; at least one is required
   * @returns {Promise<number>} Number of rows the driver reports as deleted
   */
  static async deleteWhere(conditions) {
    const db = requireDatabase(this);
    const where = equalityConditions(conditions, `${this.name}.deleteWhere()`, { requireOne: true });
    const result = await executeQuery(db, { table: this.tableName, delete: true, where });
    return affectedRowsOf(result);
  }
 
  static setDatabase(db) {
    this.db = db;
  }
 
  // Attribute access methods
  get(key) { return this.attributes[key]; }
  getAttribute(key, defaultValue) { 
    if (this.attributes.hasOwnProperty(key)) {
      return this.attributes[key];
    }
    return arguments.length > 1 ? defaultValue : null;
  }
  
  set(key, value) {
    // Same as setAttribute: casts the value and marks the model dirty so save() persists it
    return this.setAttribute(key, value);
  }
  setAttribute(key, value) {
    const oldValue = this.attributes[key];
    this.attributes[key] = this.castAttribute(key, value);
    if (oldValue !== this.attributes[key]) {
      this._isDirty = true;
    }
    return this;
  }
  
  // Fill methods
  fill(attributes) {
    const fillable = this.constructor.fillable;
    const guarded = this.constructor.guarded;
    
    for (const [key, value] of Object.entries(attributes)) {
      if (fillable.length > 0 && !fillable.includes(key)) {
        this.setAttribute(key, undefined); // Explicitly set filtered attributes to undefined
        continue;
      }
      if (guarded.length > 0 && guarded.includes(key)) {
        this.setAttribute(key, undefined); // Explicitly set guarded attributes to undefined
        continue;
      }
      this.setAttribute(key, value);
    }
    return this;
  }
  
  // Casting
  castAttribute(key, value, type = null) {
    const casts = this.constructor.casts;
    const castType = type || casts[key];
    if (!castType || value === null) return value;
    
    switch (castType) {
      case 'string': return String(value);
      case 'number': return Number(value);
      case 'boolean': return Boolean(value === 'true' || value === true || value === 1);
      case 'date': return new Date(value);
      case 'json': return typeof value === 'string' ? JSON.parse(value) : value;
      case 'array': return Array.isArray(value) ? value : [value];
      default: return value;
    }
  }
  
  // State properties
  get isNew() { return this._isNew; }
  set isNew(value) { this._isNew = value; }
  get isDeleted() { return this._isDeleted || false; }
  get isDirty() { return this._isDirty; }
  set isDirty(value) { this._isDirty = value; }
  
  // Object conversion
  toObject(includeHidden = false) {
    const obj = { ...this.attributes };
    if (!includeHidden) {
      const hidden = this.constructor.hidden;
      hidden.forEach(key => delete obj[key]);
    }
    return obj;
  }
  
  toJSON() {
    return this.toObject();
  }
  
  // Validation
  async validate(options = {}) {
    const rules = this.constructor.validationRules;
    const errors = {};
    
    // Return true if no validation rules
    if (!rules || Object.keys(rules).length === 0) {
      return true;
    }
    
    for (const [field, fieldRules] of Object.entries(rules)) {
      const value = this.getAttribute(field);
      
      // For existing models, only validate fields that are present
      // Skip required validation for missing fields on existing models
      if (!this.isNew && !this.attributes.hasOwnProperty(field)) {
        continue;
      }
      
      // Handle array of validation rules
      if (Array.isArray(fieldRules)) {
        // Check if this is a [function, message] tuple format
        if (fieldRules.length === 2 && typeof fieldRules[0] === 'function' && typeof fieldRules[1] === 'string') {
          const [validator, message] = fieldRules;
          const isValid = validator(value);
          if (!isValid) {
            errors[field] = errors[field] || [];
            errors[field].push(message);
          }
        } else E{
          // Handle array of individual rules
          for (const rule of fieldRules) {
            if (rule === 'required' && (value === undefined || value === null || value === '')) {
              errors[field] = errors[field] || [];
              errors[field].push(`${field} is required`);
            }
            
            if (rule === 'email' && value && !value.includes('@')) {
              errors[field] = errors[field] || [];
              errors[field].push(`${field} must be a valid email address`);
            }
            
            if (typeof rule === 'function') {
              const isValid = rule(value);
              if (!isValid) {
                errors[field] = errors[field] || [];
                errors[field].push(`${field} validation failed`);
              }
            }
          }
        }
      }
      
      // Handle object validation rules with constraints
      if (typeof fieldRules === 'object' && !Array.isArray(fieldRules)) {
        if (fieldRules.required && (value === undefined || value === null || value === '')) {
          errors[field] = errors[field] || [];
          errors[field].push(`${field} is required`);
        }
        
        if (fieldRules.email && value && !value.includes('@')) {
          errors[field] = errors[field] || [];
          errors[field].push(`${field} must be a valid email address`);
        }
        
        if (fieldRules.minLength !== undefined) {
          if (typeof value === 'string' && value.length < fieldRules.minLength) {
            errors[field] = errors[field] || [];
            errors[field].push(`${field} must be at least ${fieldRules.minLength} characters`);
          }
        }
        
        if (fieldRules.min !== undefined) {
          Iif (typeof value === 'number' && value < fieldRules.min) {
            errors[field] = errors[field] || [];
            errors[field].push(`${field} must be at least ${fieldRules.min}`);
          }
        }
        
        if (fieldRules.max !== undefined) {
          Iif (typeof value === 'string' && value.length > fieldRules.max) {
            errors[field] = errors[field] || [];
            errors[field].push(`${field} must be at most ${fieldRules.max} characters`);
          } else if (typeof value === 'number' && value > fieldRules.max) {
            errors[field] = errors[field] || [];
            errors[field].push(`${field} must be no more than ${fieldRules.max}`);
          }
        }
      }
    }
    
    if (Object.keys(errors).length > 0) {
      this.errors = errors; // Store errors on instance
      
      // If throwOnError is false, just return false
      Iif (options.throwOnError === false) {
        return false;
      }
      
      // Only throw errors when explicitly requested
      if (options.throwOnError !== true) {
        return false;
      }
      
      // If there are multiple validation errors, use general message
      const totalErrors = Object.keys(errors).length;
      if (totalErrors > 1) {
        const _error = new Error('Validation failed');
        _error.errors = errors;
        throw _error;
      }
      
      // For single field _error, throw with the specific message
      const firstError = Object.values(errors)[0];
      Eif (Array.isArray(firstError) && firstError[0]) {
        const _error = new Error(firstError[0]);
        _error.errors = errors;
        throw _error;
      }
      
      const _error = new Error('Validation failed');
      _error.errors = errors;
      throw _error;
    }
    
    this.errors = {};
    return true;
  }
  
  /**
   * Insert or update the record.
   *
   * @param {Object} [options={}]
   * @param {boolean} [options.skipValidation] - Skip validate()
   * @param {Object} [options.transaction] - Run the write on this transaction instead of Model.db
   * @returns {Promise<Model>} this
   */
  async save(options = {}) {
    const ModelClass = this.constructor;
    const db = requireDatabase(ModelClass, options);
 
    if (!options.skipValidation) {
      await this.validate({ throwOnError: true });
    }
 
    const primaryKey = ModelClass.primaryKey || 'id';
 
    if (this._isNew) {
      if (this.beforeSave) {
        await this.beforeSave();
        this.beforeSaveCalled = true;
      }
      if (this.beforeCreate) {
        await this.beforeCreate();
        this.beforeCreateCalled = true;
      }
 
      // Add timestamps for new models
      if (ModelClass.timestamps !== false) {
        this.setAttribute('created_at', new Date());
        this.setAttribute('updated_at', new Date());
      }
 
      const query = { table: ModelClass.tableName, insert: this.attributes };
      if (usesReturning(db, ModelClass.db)) {
        // PostgreSQL only reports generated keys through RETURNING
        query.returning = primaryKey;
      }
      const result = await executeQuery(db, query);
 
      const generatedId = result?.insertId ?? result?.rows?.[0]?.[primaryKey];
      // fill() stores filtered-out attributes as undefined, so a body that
      // carried a non-fillable `id` left the key undefined rather than null.
      const currentId = this.getAttribute(primaryKey);
      if ((currentId === null || currentId === undefined) && generatedId !== undefined && generatedId !== null) {
        this.setAttribute(primaryKey, generatedId);
      }
 
      this._isNew = false;
      if (this.afterCreate) {
        await this.afterCreate();
        this.afterCreateCalled = true;
      }
      if (this.afterSave) {
        await this.afterSave();
        this.afterSaveCalled = true;
      }
    } else {
      // Skip update if model is not dirty
      if (!this._isDirty) {
        return this;
      }
 
      const id = this.getAttribute(primaryKey);
      Iif (id === null || id === undefined) {
        throw new Error(`Cannot update ${ModelClass.name} without a primary key`);
      }
 
      Iif (this.beforeUpdate) await this.beforeUpdate();
 
      // Update timestamp for existing models
      Eif (ModelClass.timestamps !== false) {
        this.setAttribute('updated_at', new Date());
      }
 
      const changes = { ...this.attributes };
      delete changes[primaryKey];
      await executeQuery(db, { table: ModelClass.tableName, update: changes, where: { [primaryKey]: id } });
 
      Iif (this.afterUpdate) await this.afterUpdate();
    }
 
    this._isDirty = false;
    this.originalAttributes = { ...this.attributes };
    return this;
  }
 
  /**
   * Delete the record.
   *
   * @param {Object} [options={}]
   * @param {Object} [options.transaction] - Run the delete on this transaction instead of Model.db
   * @returns {Promise<boolean>} true
   */
  async delete(options = {}) {
    const ModelClass = this.constructor;
    const primaryKey = ModelClass.primaryKey || 'id';
    const id = this.getAttribute(primaryKey);
 
    if (id === null || id === undefined) {
      throw new Error('Cannot delete model without primary key');
    }
 
    const db = requireDatabase(ModelClass, options);
 
    // Call lifecycle hooks
    if (this.beforeDelete) await this.beforeDelete();
 
    await executeQuery(db, { table: ModelClass.tableName, delete: true, where: { [primaryKey]: id } });
 
    this._isDeleted = true;
 
    if (this.afterDelete) await this.afterDelete();
 
    return true;
  }
 
  /**
   * Load a relationship declared in `static relationships`.
   *
   * @param {string} name - Relationship name
   * @returns {Promise<Model[]|Model|null>} Related records (hasMany) or record (hasOne, belongsTo)
   */
  async getRelation(name) {
    const ModelClass = this.constructor;
    const relationships = ModelClass.relationships || ModelClass.relations || {};
    const relation = relationships[name];
 
    if (!relation) {
      throw new Error(`Relationship '${name}' not defined on ${ModelClass.name}`);
    }
 
    const Related = resolveRelatedModel(relation.model, name, ModelClass.name);
 
    switch (relation.type) {
      case 'hasMany':
      case 'hasOne': {
        const localKey = relation.localKey || ModelClass.primaryKey || 'id';
        const foreignKey = relation.foreignKey || `${ModelClass.name.toLowerCase()}_id`;
        const value = this.getAttribute(localKey);
 
        Iif (value === null || value === undefined) {
          return relation.type === 'hasMany' ? [] : null;
        }
 
        const related = await Related.where({ [foreignKey]: value });
        return relation.type === 'hasMany' ? related : (related[0] ?? null);
      }
 
      case 'belongsTo': {
        const foreignKey = relation.foreignKey || `${Related.name.toLowerCase()}_id`;
        const ownerKey = relation.ownerKey || Related.primaryKey || 'id';
        const value = this.getAttribute(foreignKey);
 
        Iif (value === null || value === undefined) {
          return null;
        }
 
        const related = await Related.where({ [ownerKey]: value });
        return related[0] ?? null;
      }
 
      default:
        throw new Error(`Unsupported relationship type '${relation.type}' for '${name}' on ${ModelClass.name}`);
    }
  }
}
 
export function createModel(db) {
  const models = new Map();
 
  // Helper functions
 
  /** INSERT config for a model's row, with RETURNING of the primary key on PostgreSQL. */
  function insertQuery(data, primaryKey) {
    return usesReturning(db) ? { insert: data, returning: primaryKey } : { insert: data };
  }
 
  /** An instance's column values: its own properties minus the attached methods. */
  function instanceData(instance) {
    return Object.fromEntries(
      Object.entries(instance).filter(([, value]) => typeof value !== 'function')
    );
  }
 
  function validateModelDefinition(definition) {
    Iif (!definition.tableName) {
      throw new Error('Model must have a tableName');
    }
    
    Iif (!definition.attributes || typeof definition.attributes !== 'object') {
      throw new Error('Model must have attributes object');
    }
  }
 
  function createInstance(modelName, attributes) {
    const model = models.get(modelName);
    Iif (!model) {
      throw new Error(`Model '${modelName}' not found`);
    }
 
    const instance = { ...attributes };
 
    // Add instance methods
    if (model.methods) {
      Object.entries(model.methods).forEach(([methodName, method]) => {
        instance[methodName] = method.bind(instance);
      });
    }
 
    // Add save method
    instance.save = async () => {
      const primaryKey = model.primaryKey || 'id';
      const id = instance[primaryKey];
      const data = instanceData(instance);
 
      if (id) {
        // Update existing
        delete data[primaryKey];
        await model.updateWhere({ [primaryKey]: id }, data);
      } else E{
        // Create new
        const result = await model.query(insertQuery(data, primaryKey));
        const generatedId = result.insertId ?? result.rows?.[0]?.[primaryKey];
        if (generatedId !== undefined && generatedId !== null) {
          instance[primaryKey] = generatedId;
        }
      }
 
      return instance;
    };
 
    // Add delete method
    instance.delete = async () => {
      const primaryKey = model.primaryKey || 'id';
      const id = instance[primaryKey];
      
      Iif (!id) {
        throw new Error('Cannot delete instance without primary key');
      }
 
      return await model.deleteWhere({ [primaryKey]: id });
    };
 
    return instance;
  }
 
  function createModel(name, definition) {
    const model = {
      name,
      db,
      ...definition,
 
      // Core query method
      query: async (config) => {
        // Default to the model's table without mutating the caller's config
        const query = config.table || config.from ? { ...config } : { ...config, table: definition.tableName };
 
        const result = await executeQuery(db, query);
 
        // Convert results to model instances for SELECT queries
        if (config.select && result.rows) {
          return result.rows.map(row => createInstance(name, row));
        }
 
        return result;
      },
 
      // Convenience methods
      find: async (id) => {
        const results = await model.query({
          select: '*',
          where: { [definition.primaryKey || 'id']: id },
          limit: 1
        });
        return results.length > 0 ? results[0] : null;
      },
 
      all: async () => {
        return await model.query({ select: '*' });
      },
 
      where: async (config) => {
        return await model.query(config);
      },
 
      create: async (attributes) => {
        const result = await model.query(insertQuery(attributes, definition.primaryKey || 'id'));
 
        // Return created instance with ID
        const generatedId = result.insertId ?? result.rows?.[0]?.[definition.primaryKey || 'id'];
        Eif (generatedId !== undefined && generatedId !== null) {
          return await model.find(generatedId);
        }
 
        return createInstance(name, attributes);
      },
 
      updateWhere: async (conditions, updates) => {
        const result = await model.query({
          update: updates,
          where: conditions
        });
        return result.affectedRows || 0;
      },
 
      deleteWhere: async (conditions) => {
        const result = await model.query({
          delete: true,
          where: conditions
        });
        return result.affectedRows || 0;
      }
    };
 
    // Add static methods if defined
    Iif (definition.statics) {
      Object.entries(definition.statics).forEach(([methodName, method]) => {
        model[methodName] = method.bind(model);
      });
    }
 
    return model;
  }
 
  return {
    /**
     * Register a model with pure object definition
     * 
     * @param {string} name - Model name
     * @param {Object} definition - Model definition object
     * @returns {Object} Enhanced model object
     */
    registerModel(name, definition) {
      validateModelDefinition(definition);
      
      const model = createModel(name, definition);
      models.set(name, model);
      
      return model;
    },
 
    /**
     * Execute multi-model queries
     */
    async execute(queryObject) {
      const results = {};
      
      for (const [modelName, queryConfig] of Object.entries(queryObject)) {
        const model = models.get(modelName);
        Iif (!model) {
          throw new Error(`Model '${modelName}' not found`);
        }
        
        results[modelName] = await model.query(queryConfig);
      }
      
      return results;
    },
 
    /**
     * Get registered model
     */
    getModel(name) {
      return models.get(name);
    }
  };
}