{"id":16349,"library":"ent-framework","title":"Ent Framework","description":"Ent Framework is a TypeScript-first library designed for interacting with PostgreSQL databases, presenting a graph-like representation of entities rather than a traditional ORM approach. It is currently stable at version 2.26.1 and appears to be actively maintained with regular updates. Key differentiators include its robust solution for the 'N+1 selects' problem through query batching and coalescing, built-in support for microsharding and intelligent replication lag tracking to optimize read operations, and a comprehensive row-level security (privacy layer) system that defines access based on entity relationships. The framework also emphasizes immutability for entity properties and offers a pluggable architecture, allowing integration into existing database setups. It aims to simplify scaling and security concerns for complex business logic by abstracting away much of the underlying SQL complexities.","status":"active","version":"2.26.1","language":"javascript","source_language":"en","source_url":"git://github.com/dimikot/ent-framework","tags":["javascript","postgresql","postgres","orm","sql","replication lag","cluster","sharding","micro-sharding","typescript"],"install":[{"cmd":"npm install ent-framework","lang":"bash","label":"npm"},{"cmd":"yarn add ent-framework","lang":"bash","label":"yarn"},{"cmd":"pnpm add ent-framework","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"The base class for all domain entities. Extend this class to define your business objects.","wrong":"const Ent = require('ent-framework').Ent;","symbol":"Ent","correct":"import { Ent } from 'ent-framework';"},{"note":"The central context object for managing database interactions, transactions, and entity lifecycle. Often initialized once per application.","wrong":"import { Context } from 'ent-framework';","symbol":"EntContext","correct":"import { EntContext } from 'ent-framework';"},{"note":"Decorator used to define properties on an Ent class that map to database columns or relationships.","wrong":"import { Prop } from 'ent-framework';","symbol":"Field","correct":"import { Field } from 'ent-framework';"}],"quickstart":{"code":"import { Ent, EntContext, Field, UUID, PrimaryKey, UUIDField, StringField, BooleanField, EntCreationOptions, EntQueryContext } from 'ent-framework';\n\ninterface UserData {\n  id: UUID;\n  name: string;\n  isActive: boolean;\n}\n\nclass User extends Ent<UserData> {\n  @Field(UUIDField())\n  id: UUID = PrimaryKey.empty();\n\n  @Field(StringField())\n  name: string = '';\n\n  @Field(BooleanField({ defaultValue: true }))\n  isActive: boolean = true;\n\n  static create(context: EntQueryContext, data: Partial<UserData>, options?: EntCreationOptions): User {\n    return super.create(context, data, options) as User;\n  }\n\n  static load(context: EntQueryContext, id: UUID): Promise<User | null> {\n    return super.load(context, id) as Promise<User | null>;\n  }\n}\n\nasync function runExample() {\n  // In a real application, DATABASE_URL would point to your PostgreSQL instance.\n  // For this example, we simulate a context setup.\n  const entContext = new EntContext({\n    // Replace with actual database connection configuration\n    // For demonstration, we'll use a placeholder URL.\n    connectionUri: process.env.DATABASE_URL ?? 'postgresql://user:password@host:port/database',\n    // Other configuration like sharding rules, logging, etc.\n    logLevel: 'debug'\n  });\n\n  try {\n    await entContext.init();\n    console.log('EntContext initialized.');\n\n    // Assume schema migration/sync is handled externally or by framework setup\n\n    const newUser = await User.create(entContext, { name: 'Alice', isActive: true });\n    console.log(`Created user: ${newUser.name} (ID: ${newUser.id})`);\n\n    const loadedUser = await User.load(entContext, newUser.id);\n    if (loadedUser) {\n      console.log(`Loaded user: ${loadedUser.name}, Active: ${loadedUser.isActive}`);\n    } else {\n      console.log('User not found.');\n    }\n\n    // Example of another operation (e.g., updating)\n    if (loadedUser) {\n      const updatedUser = await loadedUser.update(entContext, { isActive: false });\n      console.log(`Updated user: ${updatedUser.name}, Active: ${updatedUser.isActive}`);\n    }\n\n  } catch (error) {\n    console.error('Error during example run:', error);\n  } finally {\n    await entContext.close();\n    console.log('EntContext closed.');\n  }\n}\n\nrunExample();\n","lang":"typescript","description":"This quickstart demonstrates defining a basic 'User' Ent class, initializing the EntContext, creating a new user entity, and then loading it by ID, showcasing fundamental interaction patterns."},"warnings":[{"fix":"Review the changelog and migration guides for the specific version you are upgrading to. Pay close attention to changes in decorators, field types, and `EntContext` configuration options.","message":"Major versions of Ent Framework may introduce breaking changes to the core API or configuration schemas, particularly around how Ent classes are defined, how relationships are managed, or changes to the database abstraction layer. Always consult the release notes when upgrading.","severity":"breaking","affected_versions":">=2.0"},{"fix":"Ensure `\"experimentalDecorators\": true` and `\"emitDecoratorMetadata\": true` are set under `compilerOptions` in your `tsconfig.json`.","message":"Ent Framework leverages TypeScript decorators, which require `emitDecoratorMetadata` and `experimentalDecorators` to be enabled in your `tsconfig.json`. Failing to do so will result in runtime errors related to decorator usage.","severity":"gotcha","affected_versions":">=1.0"},{"fix":"Always use the provided `EntContext` and `Ent` methods for data retrieval and manipulation. Understand the framework's intended data access patterns to ensure optimal performance.","message":"While Ent Framework handles query batching and N+1 problems automatically, improper use of raw SQL or bypassing the framework's loading mechanisms can reintroduce performance bottlenecks and negate the benefits of its optimized query patterns.","severity":"gotcha","affected_versions":">=1.0"},{"fix":"Implement a robust schema migration strategy (e.g., using a separate migration tool or the framework's recommended approach if available) and test thoroughly in non-production environments before deploying schema changes.","message":"Schema synchronization and migration are critical for any database framework. Ent Framework often requires careful management of your database schema to match your Ent definitions. Automatic migrations might not cover all edge cases or production scenarios.","severity":"gotcha","affected_versions":">=1.0"},{"fix":"Thoroughly understand the sharding key definitions, replica lag tolerances, and routing logic. Implement comprehensive integration tests to validate data consistency and correct routing across your sharded and replicated database cluster.","message":"Correctly configuring microsharding and replication lag tracking can be complex. Misconfigurations can lead to data consistency issues (e.g., reading stale data from replicas) or routing requests to incorrect shards, causing data not found errors or performance degradation.","severity":"gotcha","affected_versions":">=1.0"}],"env_vars":null,"last_verified":"2026-04-22T00:00:00.000Z","next_check":"2026-07-21T00:00:00.000Z","problems":[{"fix":"Add or ensure `\"experimentalDecorators\": true` and `\"emitDecoratorMetadata\": true` are in `compilerOptions` in `tsconfig.json`.","cause":"TypeScript decorators metadata emission is disabled in `tsconfig.json`.","error":"TypeError: Reflect.metadata is not a function"},{"fix":"Verify the `connectionUri` in `EntContext` initialization. Ensure the PostgreSQL server is running, accessible from the application's host, and that firewall rules permit the connection. Check user credentials and database existence.","cause":"The application cannot connect to the PostgreSQL database. This could be due to incorrect connection URI, database server not running, firewall issues, or incorrect credentials.","error":"Error: connect ECONNREFUSED <DB_HOST>:<DB_PORT>"},{"fix":"Run database migrations to create or update the tables and columns corresponding to your Ent definitions. Ensure your Ent class names correctly map to table names (considering potential naming conventions).","cause":"The database schema does not match the defined Ent classes. This usually happens when an Ent class is defined but the corresponding table or column does not exist in the database, or schema migrations have not been applied.","error":"Error: relation \"<table_name>\" does not exist"}],"ecosystem":"npm"}