Profiles·Public

typeorm

semver>=0.3.0 <2.0.0postconditions39functions27last verified2026-06-23coverage score96%

Postconditions: what we check

  • find · find-query-error
    error
    Whenquery fails (connection lost, invalid relation, timeout, syntax error)
    ThrowsQueryFailedError or connection error
    Required handlingCaller MUST wrap repository.find() in try-catch to handle database errors. Connection failures and invalid queries crash application if unhandled.
    costmediumin prodimmediate exceptionusers seeservice unavailablevisibilityvisible
    Sources[1]
  • save · save-constraint-violation
    error
    Whensave violates constraint (unique, foreign key, validation, type mismatch)
    ThrowsQueryFailedError with constraint violation details
    Required handlingCaller MUST wrap save() in try-catch to handle constraint violations and validation errors. Unique violations, foreign key errors, and validation failures crash application if unhandled.
    costmediumin prodimmediate exceptionusers seeservice unavailablevisibilityvisible
    Sources[2]
  • transaction · transaction-error
    error
    Whenoperation within transaction fails (constraint violation, deadlock, connection lost)
    ThrowsError causing automatic rollback
    Required handlingCaller MUST wrap transaction operations in try-catch to handle errors and ensure rollback. Unhandled errors leave database in inconsistent state if transaction partially commits.
    costmediumin prodimmediate exceptionusers seeservice unavailablevisibilityvisible
    Sources[3]
  • findOne · findone-query-failed-error
    error
    WhenDatabase query fails (connection lost, invalid relations, timeout)
    ThrowsQueryFailedError (extends TypeORMError) with driverError containing underlying DB error
    Required handlingCaller MUST wrap in try-catch to handle database errors. findOne() returns null when not found — no need to handle EntityNotFoundError here. Distinguish null result (not found) from thrown error (DB failure) in caller logic.
    costmediumin prodimmediate exceptionusers seeservice unavailablevisibilityvisible
    Sources[4][5]
  • findOneBy · findoneby-query-failed-error
    error
    WhenDatabase query fails (connection lost, invalid column, timeout)
    ThrowsQueryFailedError with driverError containing underlying DB error
    Required handlingCaller MUST wrap in try-catch. A null return means not found (not an error). A thrown QueryFailedError means the DB operation failed.
    costmediumin prodimmediate exceptionusers seeservice unavailablevisibilityvisible
    Sources[4]
  • findOneOrFail · findone-or-fail-entity-not-found
    error
    WhenNo entity matches the given find options
    ThrowsEntityNotFoundError (extends TypeORMError) — message includes entity name and criteria
    Required handlingCaller MUST wrap in try-catch and handle EntityNotFoundError. Import EntityNotFoundError from 'typeorm' for type-safe instanceof checks. Distinguish from QueryFailedError (DB failure) vs EntityNotFoundError (not found). This is the GUARANTEED throw path — do not use findOneOrFail() without a catch block.
    costmediumin prodimmediate exceptionusers seeservice unavailablevisibilityvisible
    Sources[6][7]
  • findOneOrFail · findone-or-fail-query-failed
    error
    WhenDatabase query fails (connection lost, timeout, invalid schema)
    ThrowsQueryFailedError with driverError containing the underlying DB error
    Required handlingCaller MUST also handle QueryFailedError separately from EntityNotFoundError. Two distinct failure modes: entity not found vs DB failure.
    costmediumin prodimmediate exceptionusers seeservice unavailablevisibilityvisible
    Sources[4]
  • findOneByOrFail · findonebyorfail-entity-not-found
    error
    WhenNo entity matches the WHERE conditions
    ThrowsEntityNotFoundError (extends TypeORMError) — always thrown when no result found
    Required handlingCaller MUST wrap in try-catch. EntityNotFoundError has entityClass and criteria properties for context. This is the preferred pattern over findOneBy() + manual null check when entity MUST exist.
    costmediumin prodimmediate exceptionusers seeservice unavailablevisibilityvisible
    Sources[6]
  • insert · insert-duplicate-key-error
    error
    WhenUnique constraint or primary key violation (duplicate insert)
    ThrowsQueryFailedError with driverError.code = 'ER_DUP_ENTRY' (MySQL), '23505' (PostgreSQL), 'SQLITE_CONSTRAINT' (SQLite)
    Required handlingCaller MUST wrap in try-catch. Check error.driverError.code for database-specific constraint violation codes. insert() is intentionally primitive — no upsert logic. Use upsert() for idempotent inserts. Unlike save(), insert() will not merge existing entities — always throws on duplicate PK.
    costmediumin prodimmediate exceptionusers seelost datavisibilityvisible
    Sources[4][5]
  • insert · insert-foreign-key-violation
    error
    WhenForeign key constraint violation (referenced entity does not exist)
    ThrowsQueryFailedError with driverError containing FK violation details
    Required handlingCaller MUST validate referenced entity existence before insert. Or wrap in try-catch and handle FK error from driverError.
    costmediumin prodimmediate exceptionusers seelost datavisibilityvisible
    Sources[4]
  • update · update-constraint-violation
    error
    WhenUpdate violates unique constraint or type mismatch
    ThrowsQueryFailedError with driverError containing constraint violation details
    Required handlingCaller MUST wrap in try-catch to handle constraint violations. Also check UpdateResult.affected to verify rows were actually updated — TypeORM does NOT throw if criteria match 0 rows.
    costmediumin prodimmediate exceptionusers seelost datavisibilityvisible
    Sources[4][5]
  • update · update-silent-no-op
    warning
    WhenCriteria matches 0 rows — update silently affects nothing
    ThrowsDoes not throw — UpdateResult.affected === 0
    Required handlingCaller SHOULD check UpdateResult.affected after update(). If affected === 0, entity did not exist — decide whether to create or error. Typical bug: assume update succeeded without checking affected count.
    costmediumin prodsilent failureusers seedegraded performancevisibilitysilent
    Sources[5]
  • delete · delete-foreign-key-constraint
    error
    WhenDelete violates foreign key constraint (other records reference this entity)
    ThrowsQueryFailedError with driverError containing FK constraint details
    Required handlingCaller MUST wrap in try-catch to handle FK constraint violations. Check driverError.code for database-specific FK codes (MySQL: ER_ROW_IS_REFERENCED_2, Postgres: 23503). Consider using cascade:true in entity relations or deleting dependent records first.
    costmediumin prodimmediate exceptionusers seeservice unavailablevisibilityvisible
    Sources[4][5]
  • delete · delete-silent-no-op
    warning
    WhenCriteria matches 0 rows — delete silently affects nothing
    ThrowsDoes not throw — DeleteResult.affected === 0
    Required handlingCaller SHOULD check DeleteResult.affected after delete(). If business logic requires entity to exist, use findOneOrFail() first.
    costlowin prodsilent failureusers seedegraded performancevisibilitysilent
    Sources[5]
  • upsert · upsert-constraint-violation
    error
    WhenForeign key violation or non-conflict unique constraint violated by upsert
    ThrowsQueryFailedError with driverError containing constraint violation details
    Required handlingCaller MUST wrap in try-catch. Conflict resolution only handles the specified conflictPaths — other constraints still throw. Check driverError.code for database-specific constraint codes.
    costmediumin prodimmediate exceptionusers seelost datavisibilityvisible
    Sources[4][5]
  • query · query-sql-syntax-error
    error
    WhenSQL query has syntax error or references non-existent table/column
    ThrowsQueryFailedError with driverError containing the SQL error details and the original query
    Required handlingCaller MUST wrap in try-catch. QueryFailedError.query contains the SQL that failed — useful for debugging. QueryFailedError.driverError contains database-specific error code and message.
    costmediumin prodimmediate exceptionusers seeservice unavailablevisibilityvisible
    Sources[4][5]
  • query · query-sql-injection-risk
    error
    WhenUser input interpolated directly into SQL string (not using parameterized query)
    ThrowsDoes not throw — silently allows SQL injection
    Required handlingALWAYS use parameterized queries: repository.query('SELECT * FROM users WHERE id = $1', [userId]) NEVER concatenate user input into SQL: repository.query(`SELECT * FROM users WHERE id = ${userId}`) SQL injection can exfiltrate entire database or destroy all data.
    costhighin prodsilent failureusers seesecurity breachvisibilitysilent
    Sources[5]
  • softDelete · softdelete-missing-delete-date-column
    error
    WhenEntity does not have a @DeleteDateColumn() decorated field
    ThrowsMissingDeleteDateColumnError (extends TypeORMError) — entity name included in message
    Required handlingEnsure entity class has @DeleteDateColumn() column before calling softDelete(). Add column: @DeleteDateColumn() deletedAt: Date This error occurs at runtime — schema mismatch between entity definition and usage.
    costlowin prodimmediate exceptionusers seeservice unavailablevisibilityvisible
    Sources[8]
  • softDelete · softdelete-silent-no-op
    warning
    WhenCriteria matches 0 rows — softDelete silently affects nothing
    ThrowsDoes not throw — UpdateResult.affected === 0
    Required handlingCheck UpdateResult.affected to verify rows were actually soft-deleted.
    costlowin prodsilent failureusers seedegraded performancevisibilitysilent
    Sources[5]
  • restore · restore-missing-delete-date-column
    error
    WhenEntity does not have @DeleteDateColumn() decorated field
    ThrowsMissingDeleteDateColumnError (extends TypeORMError)
    Required handlingEnsure entity has @DeleteDateColumn() before calling restore(). Same configuration requirement as softDelete().
    costlowin prodimmediate exceptionusers seeservice unavailablevisibilityvisible
    Sources[8]
  • remove · remove-foreign-key-constraint
    error
    WhenFK constraint violation on entity or cascaded entities
    ThrowsQueryFailedError with driverError containing FK constraint details
    Required handlingCaller MUST wrap in try-catch. Unlike delete(), remove() processes relations — cascade errors surface here. Ensure all dependent records are handled (deleted or reassigned) before removing.
    costmediumin prodimmediate exceptionusers seelost datavisibilityvisible
    Sources[4]
  • count · count-query-failed-error
    error
    WhenDatabase query fails (connection lost, invalid relations, timeout)
    ThrowsQueryFailedError with driverError containing the database error
    Required handlingCaller MUST wrap in try-catch. Pagination logic that depends on count() can expose incorrect totals if errors are swallowed.
    costlowin prodimmediate exceptionusers seeservice unavailablevisibilityvisible
    Sources[4]
  • findBy · findby-query-failed-error
    error
    WhenDatabase query fails (connection lost, invalid column, timeout)
    ThrowsQueryFailedError with driverError
    Required handlingCaller MUST wrap in try-catch. Empty array is a valid result — not an error.
    costmediumin prodimmediate exceptionusers seeservice unavailablevisibilityvisible
    Sources[4]
  • findAndCount · findandcount-query-failed-error
    error
    WhenEither the find or count query fails (connection lost, timeout)
    ThrowsQueryFailedError with driverError
    Required handlingCaller MUST wrap in try-catch. A failed findAndCount() leaves pagination state undefined — do not cache partial results. Common pagination pattern: never silently fall back to page 1 on error.
    costmediumin prodimmediate exceptionusers seeservice unavailablevisibilityvisible
    Sources[4]
  • increment · increment-type-mismatch
    error
    WhenColumn is not numeric or propertyPath does not exist on entity
    ThrowsQueryFailedError or TypeORMError with type mismatch details
    Required handlingCaller MUST wrap in try-catch. Ensure propertyPath is a numeric @Column — calling increment() on a string column throws at runtime. Also check UpdateResult.affected — silent no-op if criteria matches 0 rows.
    costlowin prodimmediate exceptionusers seelost datavisibilityvisible
    Sources[4][5]
  • decrement · decrement-type-mismatch
    error
    WhenColumn is not numeric, propertyPath does not exist, or check constraint violated
    ThrowsQueryFailedError or TypeORMError
    Required handlingCaller MUST wrap in try-catch. Database-level check constraints (e.g., balance >= 0) will throw QueryFailedError on violation. Application-level guard: ensure value is > 0 before decrementing counters/balances.
    costlowin prodimmediate exceptionusers seelost datavisibilityvisible
    Sources[4]
  • initialize · initialize-already-connected
    error
    WhenDataSource.initialize() called when DataSource is already initialized (isInitialized === true)
    ThrowsCannotConnectAlreadyConnectedError (extends TypeORMError)
    Required handlingCheck dataSource.isInitialized before calling initialize(). Or guard with: if (!dataSource.isInitialized) await dataSource.initialize() Common bug: initializing inside request handlers (called on every request).
    costmediumin prodimmediate exceptionusers seeservice unavailablevisibilityvisible
    Sources[9][10]
  • initialize · initialize-connection-failure
    error
    WhenCannot connect to database (wrong credentials, host unreachable, invalid connection string)
    ThrowsError from underlying database driver (propagated through DataSource, destroys partial state)
    Required handlingCaller MUST wrap in try-catch and handle startup failure gracefully. A failed initialize() should stop application startup — log error and exit. Re-throwing is acceptable at startup boundary; silently swallowing means no DB access but no visible error.
    costhighin prodimmediate exceptionusers seeservice unavailablevisibilityvisible
    Sources[9][11]
  • destroy · destroy-not-initialized
    warning
    WhenDataSource.destroy() called when DataSource is not initialized
    ThrowsCannotExecuteNotConnectedError (extends TypeORMError)
    Required handlingCheck dataSource.isInitialized before calling destroy(). Pattern: if (dataSource.isInitialized) await dataSource.destroy() Common in test teardown or graceful shutdown handlers.
    costlowin prodimmediate exceptionusers seeservice unavailablevisibilityvisible
    Sources[9][12]
  • synchronize · synchronize-query-failed-error
    error
    WhenDDL execution fails (schema lock, permission denied, conflicting constraints)
    ThrowsQueryFailedError with driverError containing the DDL error
    Required handlingCaller MUST wrap in try-catch. synchronize() runs many DDL statements — partial failure leaves schema half-migrated. DO NOT call synchronize() in production code paths. Use migrations instead. Common bug: synchronize: true in DataSource config silently corrupts production schema.
    costhighin prodimmediate exceptionusers seeservice unavailablevisibilityvisible
    Sources[9][13]
  • synchronize · synchronize-not-connected
    error
    Whensynchronize() called on DataSource that is not yet initialized
    ThrowsCannotExecuteNotConnectedError (extends TypeORMError)
    Required handlingEnsure dataSource.initialize() has been awaited before calling synchronize(). Pattern: await dataSource.initialize(); await dataSource.synchronize().
    costmediumin prodimmediate exceptionusers seeservice unavailablevisibilityvisible
    Sources[12]
  • runMigrations · run-migrations-query-failed-error
    error
    WhenA migration fails mid-execution (DDL error, constraint violation, data conversion failure)
    ThrowsQueryFailedError with driverError containing the failing SQL and database error
    Required handlingCaller MUST wrap in try-catch and stop application startup on failure. With transaction:"each" (default) the failing migration rolls back, but earlier migrations in the batch have already committed — the schema is in a partially-migrated state. Pattern: on failure, log error, exit non-zero; do NOT proceed to serve traffic with a half-migrated schema. Re-running runMigrations() after a fix is safe.
    costhighin prodimmediate exceptionusers seeservice unavailablevisibilityvisible
    Sources[14][15]
  • runMigrations · run-migrations-not-connected
    error
    WhenrunMigrations() called before dataSource.initialize() has resolved
    ThrowsCannotExecuteNotConnectedError (extends TypeORMError)
    Required handlingAlways await dataSource.initialize() before runMigrations(). Pattern: await dataSource.initialize(); await dataSource.runMigrations().
    costmediumin prodimmediate exceptionusers seeservice unavailablevisibilityvisible
    Sources[12]
  • startTransaction · start-transaction-already-started
    error
    WhenstartTransaction() called when QueryRunner already has an active transaction
    ThrowsTransactionAlreadyStartedError (extends TypeORMError)
    Required handlingCheck queryRunner.isTransactionActive before calling startTransaction(). Common bug: calling startTransaction() twice in nested service methods on the same runner. Nested transactions need savepoints, not a second startTransaction() call.
    costmediumin prodimmediate exceptionusers seelost datavisibilityvisible
    Sources[16][3]
  • startTransaction · start-transaction-already-released
    error
    WhenstartTransaction() called on a QueryRunner that has already been released
    ThrowsQueryRunnerAlreadyReleasedError (extends TypeORMError)
    Required handlingAcquire a fresh QueryRunner via dataSource.createQueryRunner() for each transaction. Do NOT reuse a runner after calling release() — it cannot run further queries. Pattern: const qr = ds.createQueryRunner(); try { await qr.startTransaction(); ... } finally { await qr.release(); }
    costmediumin prodimmediate exceptionusers seeservice unavailablevisibilityvisible
    Sources[17]
  • commitTransaction · commit-transaction-not-started
    error
    WhencommitTransaction() called when no transaction is active on the QueryRunner
    ThrowsTransactionNotStartedError (extends TypeORMError)
    Required handlingCheck queryRunner.isTransactionActive before commit. Common bug: calling commitTransaction() in a finally block when an early error prevented startTransaction() from running. Pattern: if (queryRunner.isTransactionActive) await queryRunner.commitTransaction().
    costmediumin prodimmediate exceptionusers seelost datavisibilityvisible
    Sources[18][3]
  • commitTransaction · commit-transaction-query-failed
    error
    WhenUnderlying COMMIT SQL fails (deadlock, serialization failure, connection lost)
    ThrowsQueryFailedError with driverError (e.g. Postgres 40001 serialization_failure, 40P01 deadlock_detected)
    Required handlingCaller MUST wrap commit in try-catch AND rollback on failure. A failed commit means the transaction may be in an indeterminate state — the safe path is rollbackTransaction() then release(), and surface the error to the caller. Retry policy for serialization/deadlock errors lives at the caller layer, not here.
    costmediumin prodimmediate exceptionusers seelost datavisibilityvisible
    Sources[4]
  • release · release-already-released
    warning
    Whenrelease() called on a QueryRunner that has already been released
    ThrowsQueryRunnerAlreadyReleasedError (extends TypeORMError)
    Required handlingRelease the runner exactly once, in a finally block at the end of its scope. Common bug: double-release when error handling code calls release() AND a finally block also calls release(). Pattern: const qr = ds.createQueryRunner(); try { ... } finally { await qr.release(); }
    costlowin prodimmediate exceptionusers seedegraded performancevisibilityvisible
    Sources[17]
  • release · release-not-called-connection-leak
    error
    WhenQueryRunner created via createQueryRunner() but release() never called
    ThrowsDoes not throw — silent connection pool exhaustion
    Required handlingALWAYS call queryRunner.release() in a finally block. Forgetting release() under error paths is the dominant cause of TypeORM connection pool exhaustion (DataSource hangs on next query waiting for a free connection). Pattern: const qr = ds.createQueryRunner(); try { ... } finally { await qr.release(); }. Never put logic between createQueryRunner() and the try block.
    costhighin prodsilent failureusers seeservice unavailablevisibilitysilent
    Sources[19][20]

Sources

Every postcondition cites at least one of these. Grouped by source type; numbered to match the footnotes above.

Official documentation
Source code

Research notes

Curator notes from SOURCES.md captured when the profile was written so you can verify the reasoning, not just the rules.

Sources: typeorm

Package: typeorm Version: 0.3.x Category: database (TypeScript ORM) Status: ✅ Complete


Official Documentation

Behavioral Requirements

Database Errors: Connection failures, constraint violations, query errors Must wrap repository operations in try-catch Transactions must handle errors to ensure rollback DataSource must be initialized before use DataSource must be destroyed on shutdown

Contract Rationale

Repository operations can fail: Validation, constraints, connections Transaction errors leave inconsistent state: Must rollback Uninitialized DataSource causes crashes Unclosed connections prevent shutdown

Created: 2026-02-26 Status: ✅ COMPLETE

Need a different package?
Request a profile