typeorm
- Version 1.0.0
- Published
- 21.6 MB
- 10 dependencies
- MIT license
Install
npm i typeormyarn add typeormpnpm add typeormOverview
Data-Mapper ORM for TypeScript and ES2023+. Supports MySQL/MariaDB, PostgreSQL, MS SQL Server, Oracle, SAP HANA, SQLite, MongoDB databases.
Index
Functions
- AfterInsert()
- AfterLoad()
- AfterRecover()
- AfterRemove()
- AfterSoftRemove()
- AfterUpdate()
- And()
- Any()
- ArrayContainedBy()
- ArrayContains()
- ArrayOverlap()
- BeforeInsert()
- BeforeRecover()
- BeforeRemove()
- BeforeSoftRemove()
- BeforeUpdate()
- Between()
- Check()
- ChildEntity()
- Column()
- CreateDateColumn()
- DeleteDateColumn()
- Entity()
- Equal()
- EventSubscriber()
- Exclusion()
- ForeignKey()
- Generated()
- getMetadataArgsStorage()
- ILike()
- In()
- Index()
- IsNull()
- JoinColumn()
- JoinTable()
- JsonContains()
- LessThan()
- LessThanOrEqual()
- Like()
- ManyToMany()
- ManyToOne()
- MoreThan()
- MoreThanOrEqual()
- Not()
- ObjectIdColumn()
- OneToMany()
- OneToOne()
- Or()
- PrimaryColumn()
- PrimaryGeneratedColumn()
- Raw()
- RelationId()
- TableInheritance()
- Tree()
- TreeChildren()
- TreeLevelColumn()
- TreeParent()
- Unique()
- UpdateDateColumn()
- VersionColumn()
- ViewColumn()
- ViewEntity()
- VirtualColumn()
Classes
BaseEntity
- average()
- clear()
- count()
- countBy()
- create()
- createQueryBuilder()
- delete()
- exists()
- existsBy()
- find()
- findAndCount()
- findAndCountBy()
- findBy()
- findOne()
- findOneBy()
- findOneByOrFail()
- findOneOrFail()
- getId()
- getRepository()
- hasId()
- insert()
- maximum()
- merge()
- minimum()
- preload()
- query()
- recover()
- reload()
- remove()
- save()
- softRemove()
- sum()
- target
- update()
- upsert()
- useDataSource()
DataSource
- "@instanceof"
- buildMetadatas()
- createEntityManager()
- createQueryBuilder()
- createQueryRunner()
- defaultReplicationModeForReads()
- destroy()
- driver
- dropDatabase()
- entityMetadatas
- entityMetadatasMap
- findMetadata()
- getManyToManyMetadata()
- getMetadata()
- getMongoRepository()
- getRepository()
- getTreeRepository()
- hasMetadata()
- initialize()
- isInitialized
- logger
- manager
- metadataTableName
- migrations
- mongoManager
- namingStrategy
- options
- query()
- queryResultCache
- relationIdLoader
- relationLoader
- runMigrations()
- setOptions()
- showMigrations()
- sql()
- sqljsManager
- subscribers
- synchronize()
- transaction()
- undoLastMigration()
DefaultNamingStrategy
- checkConstraintName()
- closureJunctionTableName()
- columnName()
- defaultConstraintName()
- exclusionConstraintName()
- foreignKeyName()
- getTableName()
- hash()
- indexName()
- joinColumnName()
- joinTableColumnDuplicationPrefix()
- joinTableColumnName()
- joinTableInverseColumnName()
- joinTableName()
- materializedPathColumnName
- nestedSetColumnNames
- prefixTableName()
- primaryKeyName()
- relationConstraintName()
- relationName()
- tableName()
- uniqueConstraintName()
EntityManager
- "@instanceof"
- average()
- clear()
- connection
- count()
- countBy()
- create()
- createQueryBuilder()
- dataSource
- decrement()
- delete()
- deleteAll()
- exists()
- existsBy()
- find()
- findAndCount()
- findAndCountBy()
- findBy()
- findOne()
- findOneBy()
- findOneByOrFail()
- findOneOrFail()
- getId()
- getMongoRepository()
- getRepository()
- getTreeRepository()
- hasId()
- increment()
- insert()
- maximum()
- merge()
- minimum()
- plainObjectToEntityTransformer
- preload()
- query()
- queryRunner
- recover()
- release()
- remove()
- repositories
- restore()
- save()
- softDelete()
- softRemove()
- sql()
- sum()
- transaction()
- treeRepositories
- update()
- updateAll()
- upsert()
- withRepository()
EntityMetadata
- "@instanceof"
- afterInsertListeners
- afterLoadListeners
- afterRecoverListeners
- afterRemoveListeners
- afterSoftRemoveListeners
- afterUpdateListeners
- allEmbeddeds
- ancestorColumns
- beforeInsertListeners
- beforeRecoverListeners
- beforeRemoveListeners
- beforeSoftRemoveListeners
- beforeUpdateListeners
- build()
- checks
- childEntityMetadatas
- closureJunctionTable
- columns
- comment
- compareEntities()
- connection
- create()
- createDateColumn
- createPropertiesMap()
- database
- dataSource
- deleteDateColumn
- dependsOn
- descendantColumns
- difference()
- discriminatorColumn
- discriminatorValue
- eagerRelations
- embeddeds
- engine
- ensureEntityIdMap()
- exclusions
- expression
- extractRelationValuesFromEntity()
- findColumnsWithPropertyPath()
- findColumnWithDatabaseName()
- findColumnWithPropertyName()
- findColumnWithPropertyPath()
- findColumnWithPropertyPathStrict()
- findEmbeddedWithPropertyPath()
- findInheritanceMetadata()
- findRelationWithPropertyPath()
- foreignKeys
- generatedColumns
- getEntityIdMap()
- getEntityIdMixedMap()
- getInsertionReturningColumns()
- getValueMap()
- givenTableName
- hasAllPrimaryKeys()
- hasColumnWithPropertyPath()
- hasEmbeddedWithPropertyPath()
- hasId()
- hasMultiplePrimaryKeys
- hasNonNullableRelations
- hasRelationWithPropertyPath()
- hasUUIDGeneratedColumns
- indices
- inheritancePattern
- inheritanceTree
- inverseColumns
- isAlwaysUsingConstructor
- isClosureJunction
- isJunction
- lazyRelations
- listeners
- manyToManyRelations
- manyToOneRelations
- mapPropertyPathsToColumns()
- materializedPathColumn
- name
- nestedSetLeftColumn
- nestedSetRightColumn
- nonVirtualColumns
- objectIdColumn
- oneToManyRelations
- oneToOneRelations
- orderBy
- ownColumns
- ownerColumns
- ownerManyToManyRelations
- ownerOneToOneRelations
- ownIndices
- ownListeners
- ownRelations
- ownUniques
- parentClosureEntityMetadata
- parentEntityMetadata
- primaryColumns
- propertiesMap
- registerColumn()
- relationIds
- relations
- relationsWithJoinColumns
- schema
- synchronize
- tableMetadataArgs
- tableName
- tableNameWithoutPrefix
- tablePath
- tableType
- target
- targetName
- treeChildrenRelation
- treeLevelColumn
- treeOptions
- treeParentRelation
- treeType
- uniques
- updateDateColumn
- versionColumn
- withoutRowid
InsertQueryBuilder
- "@instanceof"
- createColumnNamesExpression()
- createColumnValueExpression()
- createInsertExpression()
- createMergeExpression()
- createMergeIntoInsertValuesExpression()
- createMergeIntoSourceExpression()
- createUpsertConditionExpression()
- createValuesExpression()
- execute()
- getInsertedColumns()
- getQuery()
- getValueSets()
- into()
- isOverridingAutoIncrementBehavior()
- orIgnore()
- orUpdate()
- output()
- returning()
- updateEntity()
- values()
- valuesFromSelect()
InstanceChecker
- isBaseEntityConstructor()
- isBrackets()
- isColumnMetadata()
- isDataSource()
- isDeleteQueryBuilder()
- isEntityMetadata()
- isEntitySchema()
- isEqualOperator()
- isFindOperator()
- isInsertQueryBuilder()
- isMongoEntityManager()
- isMssqlParameter()
- isNotBrackets()
- isQuery()
- isRdbmsSchemaBuilder()
- isRelationQueryBuilder()
- isSelectQueryBuilder()
- isSoftDeleteQueryBuilder()
- isSqljsEntityManager()
- isSubject()
- isTable()
- isTableCheck()
- isTableColumn()
- isTableExclusion()
- isTableForeignKey()
- isTableIndex()
- isTableUnique()
- isUpdateQueryBuilder()
- isView()
MigrationExecutor
- checkForDuplicateMigrations()
- createMigrationsTableIfNotExist()
- dataSource
- deleteExecutedMigration()
- deleteMigration()
- executeMigration()
- executePendingMigrations()
- fake
- getExecutedMigrations()
- getLatestExecutedMigration()
- getLatestTimestampMigration()
- getMigrations()
- getPendingMigrations()
- insertExecutedMigration()
- insertMigration()
- loadExecutedMigrations()
- queryRunner
- showMigrations()
- transaction
- undoLastMigration()
- withQueryRunner()
MongoEntityManager
- "@instanceof"
- aggregate()
- aggregateEntity()
- applyEntityTransformationToCursor()
- bulkWrite()
- collectionIndexes()
- collectionIndexExists()
- collectionIndexInformation()
- convertFindManyOptionsOrConditionsToMongodbQuery()
- convertFindOneOptionsOrConditionsToMongodbQuery()
- convertFindOptionsOrderToOrderCriteria()
- convertFindOptionsSelectToProjectCriteria()
- convertMixedCriteria()
- count()
- countBy()
- countDocuments()
- createCollectionIndex()
- createCollectionIndexes()
- createCursor()
- createEntityCursor()
- delete()
- deleteMany()
- deleteOne()
- distinct()
- dropCollectionIndex()
- dropCollectionIndexes()
- executeFind()
- executeFindAndCount()
- executeFindOne()
- filterSoftDeleted()
- find()
- findAndCount()
- findAndCountBy()
- findBy()
- findByIds()
- findOne()
- findOneAndDelete()
- findOneAndReplace()
- findOneAndUpdate()
- findOneBy()
- initializeOrderedBulkOp()
- initializeUnorderedBulkOp()
- insert()
- insertMany()
- insertOne()
- isCapped()
- listCollectionIndexes()
- mongoQueryRunner
- rename()
- replaceObjectIdProperty()
- replaceOne()
- update()
- updateMany()
- updateOne()
- watch()
MongoRepository
- aggregate()
- aggregateEntity()
- bulkWrite()
- collectionIndexes()
- collectionIndexExists()
- collectionIndexInformation()
- count()
- countBy()
- countDocuments()
- createCollectionIndex()
- createCollectionIndexes()
- createCursor()
- createEntityCursor()
- createQueryBuilder()
- deleteMany()
- deleteOne()
- distinct()
- dropCollectionIndex()
- dropCollectionIndexes()
- find()
- findAndCount()
- findAndCountBy()
- findBy()
- findByIds()
- findOne()
- findOneAndDelete()
- findOneAndReplace()
- findOneAndUpdate()
- findOneBy()
- findOneByOrFail()
- findOneOrFail()
- initializeOrderedBulkOp()
- initializeUnorderedBulkOp()
- insertMany()
- insertOne()
- isCapped()
- listCollectionIndexes()
- manager
- query()
- rename()
- replaceOne()
- updateMany()
- updateOne()
QueryBuilder
- "@instanceof"
- addCommonTableExpression()
- alias
- callListeners()
- clone()
- comment()
- connection
- createComment()
- createCteExpression()
- createFromAlias()
- createParameter()
- createPropertyPath()
- createQueryBuilder()
- createReturningExpression()
- createTimeTravelQuery()
- createWhereClausesExpression()
- createWhereConditionExpression()
- createWhereExpression()
- dataSource
- delete()
- disableEscaping()
- escape()
- execute()
- expressionMap
- getExistsCondition()
- getMainTableName()
- getParameters()
- getPredicates()
- getQuery()
- getQueryAndParameters()
- getReturningColumns()
- getSql()
- getTableName()
- getWhereCondition()
- getWhereInIdsCondition()
- getWherePredicateCondition()
- hasCommonTableExpressions()
- hasParameter()
- hasRelation()
- insert()
- normalizeNumber()
- obtainQueryRunner()
- parentQueryBuilder
- queryRunner
- registerQueryBuilderClass()
- relation()
- replacePropertyNamesForTheWholeQuery()
- restore()
- select()
- setParameter()
- setParameters()
- setQueryRunner()
- softDelete()
- update()
- useTransaction()
- validateNumericInput()
- validateOrderByCondition()
Repository
- average()
- clear()
- count()
- countBy()
- create()
- createQueryBuilder()
- decrement()
- delete()
- deleteAll()
- exists()
- existsBy()
- extend()
- find()
- findAndCount()
- findAndCountBy()
- findBy()
- findOne()
- findOneBy()
- findOneByOrFail()
- findOneOrFail()
- getId()
- hasId()
- increment()
- insert()
- manager
- maximum()
- merge()
- metadata
- minimum()
- preload()
- query()
- queryRunner
- recover()
- remove()
- restore()
- save()
- softDelete()
- softRemove()
- sql()
- sum()
- target
- update()
- updateAll()
- upsert()
SelectQueryBuilder
- "@instanceof"
- addFrom()
- addGroupBy()
- addOrderBy()
- addSelect()
- andHaving()
- andWhere()
- andWhereExists()
- andWhereInIds()
- applyFindOptions()
- buildEagerRelations()
- buildEscapedEntityColumnSelects()
- buildOrder()
- buildRelations()
- buildSelect()
- buildWhere()
- cache()
- concatRelationMetadata()
- conditions
- createGroupByExpression()
- createHavingExpression()
- createJoinExpression()
- createLimitOffsetExpression()
- createLockExpression()
- createOrderByCombinedWithSelectExpression()
- createOrderByExpression()
- createSelectDistinctExpression()
- createSelectExpression()
- distinct()
- distinctOn()
- eagerLoadChain
- executeCountQuery()
- executeEntitiesAndRawResults()
- executeExistsQuery()
- findEntityColumnSelects()
- findOptions
- from()
- fromDummy()
- getCount()
- getExists()
- getMany()
- getManyAndCount()
- getOne()
- getOneOrFail()
- getQuery()
- getRawAndEntities()
- getRawMany()
- getRawOne()
- getRelationJoinType()
- groupBy()
- having()
- innerJoin()
- innerJoinAndMapMany()
- innerJoinAndMapOne()
- innerJoinAndSelect()
- join()
- joins
- leftJoin()
- leftJoinAndMapMany()
- leftJoinAndMapOne()
- leftJoinAndSelect()
- limit()
- loadAllRelationIds()
- loadRawResults()
- loadRelationIdAndMap()
- maxExecutionTime()
- mergeExpressionMap()
- obtainQueryRunner()
- offset()
- orderBy()
- orderBys
- orHaving()
- orWhere()
- orWhereExists()
- orWhereInIds()
- relationMetadatas
- select()
- selects
- setFindOptions()
- setLock()
- setOnLocked()
- setOption()
- skip()
- stream()
- subQuery()
- take()
- timeTravelQuery()
- useIndex()
- where()
- whereExists()
- whereInIds()
- withDeleted()
Table
- "@instanceof"
- addCheckConstraint()
- addColumn()
- addExclusionConstraint()
- addForeignKey()
- addIndex()
- addUniqueConstraint()
- checks
- clone()
- columns
- comment
- create()
- database
- engine
- exclusions
- findColumnByName()
- findColumnChecks()
- findColumnForeignKeys()
- findColumnIndices()
- findColumnUniques()
- foreignKeys
- indices
- justCreated
- name
- primaryColumns
- removeCheckConstraint()
- removeColumn()
- removeExclusionConstraint()
- removeForeignKey()
- removeIndex()
- removeUniqueConstraint()
- schema
- uniques
- withoutRowid
Interfaces
Driver
- afterConnect()
- buildTableName()
- compareTableIndexTypes
- connect()
- createFullType()
- createGeneratedMap()
- createParameter()
- createQueryRunner()
- createSchemaBuilder()
- cteCapabilities
- database
- dataTypeDefaults
- disconnect()
- dummyTableName
- escape()
- escapeQueryWithParameters()
- findChangedColumns()
- getColumnLength()
- isFullTextColumnTypeSupported()
- isReplicated
- isReturningSqlSupported()
- isUUIDGenerationSupported()
- mappedDataTypes
- maxAliasLength
- normalizeDefault()
- normalizeIsUnique()
- normalizeType()
- obtainMasterConnection()
- obtainSlaveConnection()
- options
- parametersPrefix
- parseTableName()
- prepareHydratedValue()
- preparePersistentValue()
- schema
- spatialTypes
- supportedDataTypes
- supportedIndexTypes
- supportedIsolationLevels
- supportedOnDeleteTypes
- supportedOnUpdateTypes
- supportedUpsertTypes
- transactionSupport
- treeSupport
- version
- withLengthColumnTypes
- withPrecisionColumnTypes
- withScaleColumnTypes
EntitySchemaColumnOptions
- array
- asExpression
- charset
- collation
- columnDefinition
- comment
- createDate
- default
- deleteDate
- enum
- enumName
- foreignKey
- generated
- generatedType
- hstoreType
- insert
- length
- name
- nullable
- objectId
- onUpdate
- precision
- primary
- primaryKeyConstraintName
- query
- scale
- select
- transformer
- treeChildrenCount
- treeLevel
- type
- unique
- unsigned
- update
- updateDate
- version
- virtualProperty
EntitySubscriberInterface
- afterInsert()
- afterLoad()
- afterQuery()
- afterRecover()
- afterRemove()
- afterSoftRemove()
- afterTransactionCommit()
- afterTransactionRollback()
- afterTransactionStart()
- afterUpdate()
- beforeInsert()
- beforeQuery()
- beforeRecover()
- beforeRemove()
- beforeSoftRemove()
- beforeTransactionCommit()
- beforeTransactionRollback()
- beforeTransactionStart()
- beforeUpdate()
- listenTo()
NamingStrategyInterface
- checkConstraintName()
- closureJunctionTableName()
- columnName()
- defaultConstraintName()
- exclusionConstraintName()
- foreignKeyName()
- indexName()
- joinColumnName()
- joinTableColumnDuplicationPrefix()
- joinTableColumnName()
- joinTableInverseColumnName()
- joinTableName()
- materializedPathColumnName
- nestedSetColumnNames
- prefixTableName()
- primaryKeyName()
- relationConstraintName()
- relationName()
- tableName()
- uniqueConstraintName()
QueryRunner
- [Symbol.asyncDispose]()
- addColumn()
- addColumns()
- afterMigration()
- beforeMigration()
- broadcaster
- changeColumn()
- changeColumns()
- changeTableComment()
- clearDatabase()
- clearSqlMemory()
- clearTable()
- commitTransaction()
- connect()
- createCheckConstraint()
- createCheckConstraints()
- createDatabase()
- createExclusionConstraint()
- createExclusionConstraints()
- createForeignKey()
- createForeignKeys()
- createIndex()
- createIndices()
- createPrimaryKey()
- createSchema()
- createTable()
- createUniqueConstraint()
- createUniqueConstraints()
- createView()
- data
- dataSource
- disableSqlMemory()
- dropCheckConstraint()
- dropCheckConstraints()
- dropColumn()
- dropColumns()
- dropDatabase()
- dropExclusionConstraint()
- dropExclusionConstraints()
- dropForeignKey()
- dropForeignKeys()
- dropIndex()
- dropIndices()
- dropPrimaryKey()
- dropSchema()
- dropTable()
- dropUniqueConstraint()
- dropUniqueConstraints()
- dropView()
- enableSqlMemory()
- executeMemoryDownSql()
- executeMemoryUpSql()
- getCurrentDatabase()
- getCurrentSchema()
- getDatabases()
- getMemorySql()
- getReplicationMode()
- getSchemas()
- getTable()
- getTables()
- getView()
- getViews()
- hasColumn()
- hasDatabase()
- hasSchema()
- hasTable()
- isReleased
- isTransactionActive
- manager
- query()
- release()
- renameColumn()
- renameTable()
- rollbackTransaction()
- sql()
- startTransaction()
- stream()
- updatePrimaryKeys()
Type Aliases
- ColumnType
- DatabaseType
- DataSourceOptions
- DeepPartial
- EntityTarget
- Feature
- FeatureCollection
- FileLoggerOptions
- FindOperatorType
- FindOptionsOrder
- FindOptionsOrderProperty
- FindOptionsOrderValue
- FindOptionsRelations
- FindOptionsRelationsProperty
- FindOptionsSelect
- FindOptionsSelectProperty
- FindOptionsWhere
- FindOptionsWhereProperty
- Geography
- GeoJSON
- Geometry
- GeometryCollection
- LineString
- LoggerOptions
- LogLevel
- LogMessage
- LogMessageFormat
- LogMessageType
- MixedList
- MultiLineString
- MultiPoint
- MultiPolygon
- ObjectType
- OrderByCondition
- Point
- Polygon
- Position
- PrepareLogMessagesOptions
- PrimaryColumnOptions
- QueryDeepPartialEntity
- QueryPartialEntity
- Relation
- ReplicationMode
- ReturningOption
Functions
function AfterInsert
AfterInsert: () => PropertyDecorator;Calls a method on which this decorator is applied after this entity insertion.
function AfterLoad
AfterLoad: () => PropertyDecorator;Calls a method on which this decorator is applied after entity is loaded.
function AfterRecover
AfterRecover: () => PropertyDecorator;Calls a method on which this decorator is applied before this entity soft removal.
function AfterRemove
AfterRemove: () => PropertyDecorator;Calls a method on which this decorator is applied after this entity removal.
function AfterSoftRemove
AfterSoftRemove: () => PropertyDecorator;Calls a method on which this decorator is applied before this entity soft removal.
function AfterUpdate
AfterUpdate: () => PropertyDecorator;Calls a method on which this decorator is applied after this entity update.
function And
And: <T>(...values: FindOperator<T>[]) => FindOperator<T>;Parameter values
function Any
Any: <T>(value: readonly T[] | FindOperator<T>) => FindOperator<T>;Find Options Operator.
Parameter value
Example 1
{ someField: Any([...]) }
function ArrayContainedBy
ArrayContainedBy: <T>( value: readonly T[] | FindOperator<T>) => FindOperator<any>;FindOptions Operator.
Parameter value
Example 1
{ someField: ArrayContainedBy([...]) }
function ArrayContains
ArrayContains: <T>(value: readonly T[] | FindOperator<T>) => FindOperator<any>;FindOptions Operator.
Parameter value
Example 1
{ someField: ArrayContains([...]) }
function ArrayOverlap
ArrayOverlap: <T>(value: readonly T[] | FindOperator<T>) => FindOperator<any>;FindOptions Operator.
Parameter value
Example 1
{ someField: ArrayOverlap([...]) }
function BeforeInsert
BeforeInsert: () => PropertyDecorator;Calls a method on which this decorator is applied before this entity insertion.
function BeforeRecover
BeforeRecover: () => PropertyDecorator;Calls a method on which this decorator is applied before this entity soft removal.
function BeforeRemove
BeforeRemove: () => PropertyDecorator;Calls a method on which this decorator is applied before this entity removal.
function BeforeSoftRemove
BeforeSoftRemove: () => PropertyDecorator;Calls a method on which this decorator is applied before this entity soft removal.
function BeforeUpdate
BeforeUpdate: () => PropertyDecorator;Calls a method on which this decorator is applied before this entity update.
function Between
Between: <T>( from: T | FindOperator<T>, to: T | FindOperator<T>) => FindOperator<T>;Find Options Operator.
Parameter from
Parameter to
Example 1
{ someField: Between(x, y) }
function Check
Check: { (expression: string): ClassDecorator & PropertyDecorator; (name: string, expression: string): ClassDecorator & PropertyDecorator;};Creates a database check. Can be used on entity property or on entity. Can create checks with composite columns when used on entity.
Parameter expression
Creates a database check. Can be used on entity property or on entity. Can create checks with composite columns when used on entity.
Parameter name
Parameter expression
function ChildEntity
ChildEntity: (discriminatorValue?: any) => ClassDecorator;Special type of the table used in the single-table inherited tables.
Parameter discriminatorValue
function Column
Column: { (): PropertyDecorator; (options: ColumnOptions): PropertyDecorator; (type: SimpleColumnType, options?: ColumnCommonOptions): PropertyDecorator; ( type: SpatialColumnType, options?: ColumnCommonOptions & SpatialColumnOptions ): PropertyDecorator; ( type: WithLengthColumnType, options?: ColumnCommonOptions & ColumnWithLengthOptions ): PropertyDecorator; ( type: UnsignedColumnType, options?: ColumnCommonOptions & ColumnUnsignedOptions ): PropertyDecorator; ( type: WithPrecisionColumnType, options?: ColumnCommonOptions & ColumnNumericOptions ): PropertyDecorator; ( type: 'enum', options?: ColumnCommonOptions & ColumnEnumOptions ): PropertyDecorator; ( type: 'simple-enum', options?: ColumnCommonOptions & ColumnEnumOptions ): PropertyDecorator; ( type: 'set', options?: ColumnCommonOptions & ColumnEnumOptions ): PropertyDecorator; ( type: 'hstore', options?: ColumnCommonOptions & ColumnHstoreOptions ): PropertyDecorator; ( type: (type?: any) => Function, options?: ColumnEmbeddedOptions ): PropertyDecorator;};Column decorator is used to mark a specific class property as a table column. Only properties decorated with this decorator will be persisted to the database when entity be saved.
Column decorator is used to mark a specific class property as a table column. Only properties decorated with this decorator will be persisted to the database when entity be saved.
Parameter options
Column decorator is used to mark a specific class property as a table column. Only properties decorated with this decorator will be persisted to the database when entity be saved.
Parameter type
Parameter options
Column decorator is used to mark a specific class property as a table column. Only properties decorated with this decorator will be persisted to the database when entity be saved.
Property in entity can be marked as Embedded, and on persist all columns from the embedded are mapped to the single table of the entity where Embedded is used. And on hydration all columns which supposed to be in the embedded will be mapped to it from the single table.
Parameter type
Parameter options
function CreateDateColumn
CreateDateColumn: (options?: ColumnOptions) => PropertyDecorator;This column will store a creation date of the inserted object. Creation date is generated and inserted only once, at the first time when you create an object, the value is inserted into the table, and is never touched again.
Parameter options
function DeleteDateColumn
DeleteDateColumn: (options?: ColumnOptions) => PropertyDecorator;This column will store a delete date of the soft-deleted object. This date is being updated each time you soft-delete the object.
Parameter options
function Entity
Entity: { (options?: EntityOptions): ClassDecorator; (name?: string, options?: EntityOptions): ClassDecorator;};This decorator is used to mark classes that will be an entity (table or document depend on database type). Database schema will be created for all classes decorated with it, and Repository can be retrieved and used for it.
Parameter options
This decorator is used to mark classes that will be an entity (table or document depend on database type). Database schema will be created for all classes decorated with it, and Repository can be retrieved and used for it.
Parameter name
Parameter options
function Equal
Equal: <T>(value: T | FindOperator<T>) => EqualOperator<T>;Find Options Operator. This operator is handy to provide object value for non-relational properties of the Entity.
Parameter value
Example 1
{ someField: Equal("value") }
Example 2
{ uuid: Equal(new UUID()) }
function EventSubscriber
EventSubscriber: () => ClassDecorator;Classes decorated with this decorator will listen to ORM events and their methods will be triggered when event occurs. Those classes must implement EventSubscriberInterface interface.
function Exclusion
Exclusion: { (expression: string, options?: ExclusionOptions): ClassDecorator & PropertyDecorator; (name: string, expression: string, options?: ExclusionOptions): ClassDecorator & PropertyDecorator;};Creates a database exclusion. Can be used on entity. Can create exclusions with composite columns when used on entity.
Parameter expression
Parameter options
Creates a database exclusion. Can be used on entity. Can create exclusions with composite columns when used on entity.
Parameter name
Parameter expression
Parameter options
function ForeignKey
ForeignKey: { <T>( typeFunctionOrTarget: string | ((type?: any) => ObjectType<T>), options?: ForeignKeyOptions ): PropertyDecorator; <T>( typeFunctionOrTarget: string | ((type?: any) => ObjectType<T>), inverseSide: string | ((object: T) => any), options?: ForeignKeyOptions ): PropertyDecorator; < T, C extends (readonly [] | readonly string[]) & (number extends C['length'] ? readonly [] : unknown) >( typeFunctionOrTarget: string | ((type?: any) => ObjectType<T>), columnNames: C, referencedColumnNames: { [K in keyof C]: string }, options?: ForeignKeyOptions ): ClassDecorator;};Creates a database foreign key. Can be used on entity property or on entity. Can create foreign key with composite columns when used on entity. Warning! Don't use this with relations; relation decorators create foreign keys automatically.
Parameter typeFunctionOrTarget
Parameter options
Creates a database foreign key. Can be used on entity property or on entity. Can create foreign key with composite columns when used on entity. Warning! Don't use this with relations; relation decorators create foreign keys automatically.
Parameter typeFunctionOrTarget
Parameter inverseSide
Parameter options
Creates a database foreign key. Can be used on entity property or on entity. Can create foreign key with composite columns when used on entity. Warning! Don't use this with relations; relation decorators create foreign keys automatically.
Parameter typeFunctionOrTarget
Parameter columnNames
Parameter referencedColumnNames
Parameter options
function Generated
Generated: (strategy?: 'increment' | 'uuid' | 'rowid') => PropertyDecorator;Marks a column to generate a value on entity insertion. There are three types of generation strategy - increment, uuid and rowid (cockroachdb only). Increment uses a number which increases by one on each insertion. Uuid generates a special UUID token. Rowid supports only in CockroachDB and uses
unique_rowid()functionNote, some databases do not support non-primary generation columns.
Parameter strategy
function getMetadataArgsStorage
getMetadataArgsStorage: () => MetadataArgsStorage;Returns the singleton MetadataArgsStorage, creating it on the global scope if it does not already exist.
function ILike
ILike: <T>(value: T | FindOperator<T>) => FindOperator<T>;Find Options Operator.
Parameter value
Example 1
{ someField: ILike("%SOME string%") }
function In
In: <T>(value: readonly T[] | FindOperator<T>) => FindOperator<any>;Find Options Operator.
Parameter value
Example 1
{ someField: In([...]) }
function Index
Index: { (options?: IndexOptions): ClassDecorator & PropertyDecorator; (name: string, options?: IndexOptions): ClassDecorator & PropertyDecorator; (name: string, options: { synchronize: false }): ClassDecorator & PropertyDecorator; (name: string, fields: string[], options?: IndexOptions): ClassDecorator & PropertyDecorator; (fields: string[], options?: IndexOptions): ClassDecorator & PropertyDecorator; ( fields: (object?: any) => any[] | { [key: string]: number }, options?: IndexOptions ): ClassDecorator & PropertyDecorator; ( name: string, fields: (object?: any) => any[] | { [key: string]: number }, options?: IndexOptions ): ClassDecorator & PropertyDecorator;};Creates a database index. Can be used on entity property or on entity. Can create indices with composite columns when used on entity.
Parameter options
Creates a database index. Can be used on entity property or on entity. Can create indices with composite columns when used on entity.
Parameter name
Parameter options
Creates a database index. Can be used on entity property or on entity. Can create indices with composite columns when used on entity.
Parameter name
Parameter options
Parameter
options.synchronize
Creates a database index. Can be used on entity property or on entity. Can create indices with composite columns when used on entity.
Parameter name
Parameter fields
Parameter options
Creates a database index. Can be used on entity property or on entity. Can create indices with composite columns when used on entity.
Parameter fields
Parameter options
function IsNull
IsNull: () => FindOperator<any>;Find Options Operator.
Example 1
{ someField: IsNull() }
function JoinColumn
JoinColumn: { (): PropertyDecorator; (options: JoinColumnOptions): PropertyDecorator; (options: JoinColumnOptions[]): PropertyDecorator;};JoinColumn decorator used on one-to-one relations to specify owner side of relationship. It also can be used on both one-to-one and many-to-one relations to specify custom column name or custom referenced column.
JoinColumn decorator used on one-to-one relations to specify owner side of relationship. It also can be used on both one-to-one and many-to-one relations to specify custom column name or custom referenced column.
Parameter options
function JoinTable
JoinTable: { (): PropertyDecorator; (options: JoinTableOptions): PropertyDecorator; (options: JoinTableMultipleColumnsOptions): PropertyDecorator;};JoinTable decorator is used in many-to-many relationship to specify owner side of relationship. Its also used to set a custom junction table's name, column names and referenced columns.
JoinTable decorator is used in many-to-many relationship to specify owner side of relationship. Its also used to set a custom junction table's name, column names and referenced columns.
Parameter options
function JsonContains
JsonContains: < T extends Record<string | number | symbol, unknown> | readonly unknown[]>( value: T | FindOperator<T>) => FindOperator<any>;FindOptions Operator.
Parameter value
Example 1
{ someField: JsonContains({...}) }
function LessThan
LessThan: <T>(value: T | FindOperator<T>) => FindOperator<T>;Find Options Operator.
Parameter value
Example 1
{ someField: LessThan(10) }
function LessThanOrEqual
LessThanOrEqual: <T>(value: T | FindOperator<T>) => FindOperator<T>;Find Options Operator.
Parameter value
Example 1
{ someField: LessThanOrEqual(10) }
function Like
Like: <T>(value: T | FindOperator<T>) => FindOperator<T>;Find Options Operator.
Parameter value
Example 1
{ someField: Like("%some string%") }
function ManyToMany
ManyToMany: { <T>( typeFunctionOrTarget: string | ((type?: any) => ObjectType<T>), options?: RelationOptions ): PropertyDecorator; <T>( typeFunctionOrTarget: string | ((type?: any) => ObjectType<T>), inverseSide?: string | ((object: T) => any), options?: RelationOptions ): PropertyDecorator;};Many-to-many is a type of relationship when Entity1 can have multiple instances of Entity2, and Entity2 can have multiple instances of Entity1. To achieve it, this type of relation creates a junction table, where it storage entity1 and entity2 ids. This is owner side of the relationship.
Parameter typeFunctionOrTarget
Parameter options
Many-to-many is a type of relationship when Entity1 can have multiple instances of Entity2, and Entity2 can have multiple instances of Entity1. To achieve it, this type of relation creates a junction table, where it storage entity1 and entity2 ids. This is owner side of the relationship.
Parameter typeFunctionOrTarget
Parameter inverseSide
Parameter options
function ManyToOne
ManyToOne: { <T>( typeFunctionOrTarget: string | ((type?: any) => ObjectType<T>), options?: RelationOptions ): PropertyDecorator; <T>( typeFunctionOrTarget: string | ((type?: any) => ObjectType<T>), inverseSide?: string | ((object: T) => any), options?: RelationOptions ): PropertyDecorator;};A many-to-one relation allows creating the type of relation where Entity1 can have a single instance of Entity2, but Entity2 can have multiple instances of Entity1. Entity1 is the owner of the relationship, and stores the id of Entity2 on its side of the relation.
Parameter typeFunctionOrTarget
Parameter options
A many-to-one relation allows creating the type of relation where Entity1 can have a single instance of Entity2, but Entity2 can have multiple instances of Entity1. Entity1 is the owner of the relationship, and stores the id of Entity2 on its side of the relation.
Parameter typeFunctionOrTarget
Parameter inverseSide
Parameter options
function MoreThan
MoreThan: <T>(value: T | FindOperator<T>) => FindOperator<T>;Find Options Operator.
Parameter value
Example 1
{ someField: MoreThan(10) }
function MoreThanOrEqual
MoreThanOrEqual: <T>(value: T | FindOperator<T>) => FindOperator<T>;Find Options Operator.
Parameter value
Example 1
{ someField: MoreThanOrEqual(10) }
function Not
Not: <T>(value: T | FindOperator<T>) => FindOperator<T>;Find Options Operator. Used to negate expression.
Parameter value
Example 1
{ title: Not("hello") }
function ObjectIdColumn
ObjectIdColumn: (options?: ColumnOptions) => PropertyDecorator;Special type of column that is available only for MongoDB database. Marks your entity's column to be an object id.
Parameter options
function OneToMany
OneToMany: <T>( typeFunctionOrTarget: string | ((type?: any) => ObjectType<T>), inverseSide: string | ((object: T) => any), options?: RelationOptions) => PropertyDecorator;A one-to-many relation allows creating the type of relation where Entity1 can have multiple instances of Entity2, but Entity2 has only one Entity1. Entity2 is the owner of the relationship, and stores the id of Entity1 on its side of the relation.
Parameter typeFunctionOrTarget
Parameter inverseSide
Parameter options
function OneToOne
OneToOne: { <T>( typeFunctionOrTarget: string | ((type?: any) => ObjectType<T>), options?: RelationOptions ): PropertyDecorator; <T>( typeFunctionOrTarget: string | ((type?: any) => ObjectType<T>), inverseSide?: string | ((object: T) => any), options?: RelationOptions ): PropertyDecorator;};One-to-one relation allows the creation of a direct relation between two entities. Entity1 has only one Entity2. Entity1 is the owner of the relationship, and stores Entity2 id on its own side.
Parameter typeFunctionOrTarget
Parameter options
One-to-one relation allows the creation of a direct relation between two entities. Entity1 has only one Entity2. Entity1 is the owner of the relationship, and stores Entity2 id on its own side.
Parameter typeFunctionOrTarget
Parameter inverseSide
Parameter options
function Or
Or: <T>(...values: FindOperator<T>[]) => FindOperator<T>;Parameter values
function PrimaryColumn
PrimaryColumn: { (options?: PrimaryColumnOptions): PropertyDecorator; (type?: ColumnType, options?: PrimaryColumnOptions): PropertyDecorator;};Column decorator is used to mark a specific class property as a table column. Only properties decorated with this decorator will be persisted to the database when entity be saved. Primary columns also creates a PRIMARY KEY for this column in a db.
Parameter options
Column decorator is used to mark a specific class property as a table column. Only properties decorated with this decorator will be persisted to the database when entity be saved. Primary columns also creates a PRIMARY KEY for this column in a db.
Parameter type
Parameter options
function PrimaryGeneratedColumn
PrimaryGeneratedColumn: { (): PropertyDecorator; (options: PrimaryGeneratedColumnNumericOptions): PropertyDecorator; ( strategy: 'increment', options?: PrimaryGeneratedColumnNumericOptions ): PropertyDecorator; ( strategy: 'uuid', options?: PrimaryGeneratedColumnUUIDOptions ): PropertyDecorator; ( strategy: 'rowid', options?: PrimaryGeneratedColumnUUIDOptions ): PropertyDecorator; ( strategy: 'identity', options?: PrimaryGeneratedColumnIdentityOptions ): PropertyDecorator;};Column decorator is used to mark a specific class property as a table column.
Column decorator is used to mark a specific class property as a table column.
Parameter options
Column decorator is used to mark a specific class property as a table column.
Parameter strategy
Parameter options
function Raw
Raw: { <T>(value: string): FindOperator<any>; <T>(sqlGenerator: (columnAlias: string) => string): FindOperator<any>; <T>( sqlGenerator: (columnAlias: string) => string, parameters: ObjectLiteral ): FindOperator<any>;};Find Options Operator.
Parameter value
Example 1
{ someField: Raw("12") }
Find Options Operator.
Parameter sqlGenerator
Example 1
{ someField: Raw((columnAlias) =>
${columnAlias} = 5) }Find Options Operator. For escaping parameters use next syntax:
Parameter sqlGenerator
Parameter parameters
Example 1
{ someField: Raw((columnAlias) =>
${columnAlias} = :value, { value: 5 }) }
function RelationId
RelationId: <T>( relation: string | ((object: T) => any), alias?: string, queryBuilderFactory?: (qb: SelectQueryBuilder<any>) => SelectQueryBuilder<any>) => PropertyDecorator;Special decorator used to extract relation id into separate entity property.
Parameter relation
Parameter alias
Parameter queryBuilderFactory
Modifiers
@experimental
function TableInheritance
TableInheritance: (options?: { pattern?: 'STI'; column?: string | ColumnOptions;}) => ClassDecorator;Sets for entity to use table inheritance pattern.
Parameter options
Parameter
options.pattern
Parameter
options.column
function Tree
Tree: (type: TreeType, options?: ClosureTreeOptions) => ClassDecorator;Marks entity to work like a tree. Tree pattern that will be used for the tree entity should be specified.
Parameter type
Parameter options
@TreeParentdecorator must be used in tree entities.TreeRepositorycan be used to manipulate tree entities.
function TreeChildren
TreeChildren: (options?: { cascade?: | boolean | ('insert' | 'update' | 'remove' | 'soft-remove' | 'recover')[];}) => PropertyDecorator;Marks an entity property as a children of the tree. "Tree children" will contain all children (bind) of this entity.
Parameter options
Parameter
options.cascade
function TreeLevelColumn
TreeLevelColumn: () => PropertyDecorator;Creates a "level"/"length" column to the table that holds a closure table.
function TreeParent
TreeParent: (options?: { onDelete?: OnDeleteType }) => PropertyDecorator;Marks an entity property as a parent of the tree. "Tree parent" indicates who owns (is a parent) of this entity in tree structure.
Parameter options
Parameter
options.onDelete
function Unique
Unique: { (name: string, fields: string[], options?: UniqueOptions): ClassDecorator & PropertyDecorator; (fields: string[], options?: UniqueOptions): ClassDecorator & PropertyDecorator; ( fields: (object?: any) => any[] | { [key: string]: number }, options?: UniqueOptions ): ClassDecorator & PropertyDecorator; ( name: string, fields: (object?: any) => any[] | { [key: string]: number }, options?: UniqueOptions ): ClassDecorator & PropertyDecorator;};Composite unique constraint must be set on entity classes and must specify entity's fields to be unique.
Parameter name
Parameter fields
Parameter options
Composite unique constraint must be set on entity classes and must specify entity's fields to be unique.
Parameter fields
Parameter options
function UpdateDateColumn
UpdateDateColumn: (options?: ColumnOptions) => PropertyDecorator;This column will store an update date of the updated object. This date is being updated each time you persist the object.
Parameter options
function VersionColumn
VersionColumn: (options?: ColumnOptions) => PropertyDecorator;This column will store a number - version of the entity. Every time your entity will be persisted, this number will be increased by one - so you can organize visioning and update strategies of your entity.
Parameter options
function ViewColumn
ViewColumn: (options?: ViewColumnOptions) => PropertyDecorator;ViewColumn decorator is used to mark a specific class property as a view column.
Parameter options
function ViewEntity
ViewEntity: { (options?: ViewEntityOptions): ClassDecorator; (name?: string, options?: ViewEntityOptions): ClassDecorator;};This decorator is used to mark classes that will be an entity view. Database schema will be created for all classes decorated with it, and Repository can be retrieved and used for it.
Parameter options
This decorator is used to mark classes that will be an entity view. Database schema will be created for all classes decorated with it, and Repository can be retrieved and used for it.
Parameter name
Parameter options
function VirtualColumn
VirtualColumn: { (options: VirtualColumnOptions): PropertyDecorator; (typeOrOptions: ColumnType, options: VirtualColumnOptions): PropertyDecorator;};VirtualColumn decorator is used to mark a specific class property as a Virtual column.
Parameter options
VirtualColumn decorator is used to mark a specific class property as a Virtual column.
Parameter typeOrOptions
Parameter options
Classes
class AbstractLogger
abstract class AbstractLogger implements Logger {}constructor
constructor(options?: LoggerOptions);property options
protected options?: LoggerOptions;method isLogEnabledFor
protected isLogEnabledFor: (type?: LogLevel | LogMessageType) => boolean;Check is logging for level or message type is enabled.
Parameter type
method log
log: ( level: 'log' | 'info' | 'warn', message: any, queryRunner?: QueryRunner) => void;Perform logging using given logger, or by default to the console. Log has its own level and message.
Parameter level
Parameter message
Parameter queryRunner
method logMigration
logMigration: (message: string, queryRunner?: QueryRunner) => void;Logs events from the migration run process.
Parameter message
Parameter queryRunner
method logQuery
logQuery: ( query: string, parameters?: any[] | ObjectLiteral, queryRunner?: QueryRunner) => void;Logs query and parameters used in it.
Parameter query
Parameter parameters
Parameter queryRunner
method logQueryError
logQueryError: ( error: string, query: string, parameters?: any[] | ObjectLiteral, queryRunner?: QueryRunner) => void;Logs query that is failed.
Parameter error
Parameter query
Parameter parameters
Parameter queryRunner
method logQuerySlow
logQuerySlow: ( time: number, query: string, parameters?: any[] | ObjectLiteral, queryRunner?: QueryRunner) => void;Logs query that is slow.
Parameter time
Parameter query
Parameter parameters
Parameter queryRunner
method logSchemaBuild
logSchemaBuild: (message: string, queryRunner?: QueryRunner) => void;Logs events from the schema build process.
Parameter message
Parameter queryRunner
method prepareLogMessages
protected prepareLogMessages: ( logMessage: LogMessage | string | number | (LogMessage | string | number)[], options?: Partial<PrepareLogMessagesOptions>, queryRunner?: QueryRunner) => LogMessage[];Prepare and format log messages
Parameter logMessage
Parameter options
Parameter queryRunner
method stringifyParams
protected stringifyParams: ( parameters: any[] | ObjectLiteral) => string | any[] | ObjectLiteral;Converts parameters to a string. Sometimes parameters can have circular objects and therefor we are handle this case too.
Parameter parameters
method writeLog
protected abstract writeLog: ( level: LogLevel, message: LogMessage | string | number | (LogMessage | string | number)[], queryRunner?: QueryRunner) => void;Write log to specific output.
class AdvancedConsoleLogger
class AdvancedConsoleLogger extends AbstractLogger {}Performs logging of the events in TypeORM. This version of logger uses console to log events and use syntax highlighting.
method writeLog
protected writeLog: ( level: LogLevel, logMessage: LogMessage | LogMessage[], queryRunner?: QueryRunner) => void;Write log to specific output.
Parameter level
Parameter logMessage
Parameter queryRunner
class AlreadyHasActiveConnectionError
class AlreadyHasActiveConnectionError extends TypeORMError {}Thrown when consumer tries to recreate connection with the same name, but previous connection was not closed yet.
constructor
constructor(connectionName: string);class BaseEntity
class BaseEntity {}Base abstract entity for all entities, used in ActiveRecord patterns.
property target
static readonly target: EntityTarget<any>;Returns object that is managed by this repository. If this repository manages entity from schema, then it returns a name of that schema instead.
method average
static average: <T extends BaseEntity>( this: { new (): T } & typeof BaseEntity, columnName: PickKeysByType<T, number>, where: FindOptionsWhere<T>) => Promise<number | null>;Return the AVG of a column
Parameter columnName
Parameter where
method clear
static clear: <T extends BaseEntity>( this: { new (): T } & typeof BaseEntity, options?: { cascade?: boolean }) => Promise<void>;Clears all the data from the given table/collection (truncates/drops it).
Parameter options
Parameter
options.cascade
method count
static count: <T extends BaseEntity>( this: { new (): T } & typeof BaseEntity, options?: FindManyOptions<T>) => Promise<number>;Counts entities that match given options.
Parameter options
method countBy
static countBy: <T extends BaseEntity>( this: { new (): T } & typeof BaseEntity, where: FindOptionsWhere<T>) => Promise<number>;Counts entities that match given WHERE conditions.
Parameter where
method create
static create: { <T extends BaseEntity>(this: { new (): T } & typeof BaseEntity): T; <T extends BaseEntity>( this: (new () => T) & typeof BaseEntity, entityLikeArray: DeepPartial<T>[] ): T[]; <T extends BaseEntity>( this: (new () => T) & typeof BaseEntity, entityLike: DeepPartial<T> ): T;};Creates a new entity instance.
Creates a new entities and copies all entity properties from given objects into their new entities. Note that it copies only properties that present in entity schema.
Creates a new entity instance and copies all entity properties from this object into a new entity. Note that it copies only properties that present in entity schema.
method createQueryBuilder
static createQueryBuilder: <T extends BaseEntity>( this: { new (): T } & typeof BaseEntity, alias?: string) => SelectQueryBuilder<T>;Creates a new query builder that can be used to build a SQL query.
Parameter alias
method delete
static delete: <T extends BaseEntity>( this: { new (): T } & typeof BaseEntity, criteria: | string | string[] | number | number[] | Date | Date[] | ObjectId | ObjectId[] | FindOptionsWhere<T>) => Promise<DeleteResult>;Deletes entities by a given criteria. Unlike remove method executes a primitive operation without cascades, relations and other operations included. Executes fast and efficient DELETE query. Does not check if entity exist in the database.
Parameter criteria
method exists
static exists: <T extends BaseEntity>( this: { new (): T } & typeof BaseEntity, options?: FindManyOptions<T>) => Promise<boolean>;Checks whether any entity exists that matches the given options.
Parameter options
method existsBy
static existsBy: <T extends BaseEntity>( this: { new (): T } & typeof BaseEntity, where: FindOptionsWhere<T>) => Promise<boolean>;Checks whether any entity exists that matches the given conditions.
Parameter where
method find
static find: <T extends BaseEntity>( this: { new (): T } & typeof BaseEntity, options?: FindManyOptions<T>) => Promise<T[]>;Finds entities that match given options.
Parameter options
method findAndCount
static findAndCount: <T extends BaseEntity>( this: { new (): T } & typeof BaseEntity, options?: FindManyOptions<T>) => Promise<[T[], number]>;Finds entities that match given find options. Also counts all entities that match given conditions, but ignores pagination settings (from and take options).
Parameter options
method findAndCountBy
static findAndCountBy: <T extends BaseEntity>( this: { new (): T } & typeof BaseEntity, where: FindOptionsWhere<T>) => Promise<[T[], number]>;Finds entities that match given WHERE conditions. Also counts all entities that match given conditions, but ignores pagination settings (from and take options).
Parameter where
method findBy
static findBy: <T extends BaseEntity>( this: { new (): T } & typeof BaseEntity, where: FindOptionsWhere<T>) => Promise<T[]>;Finds entities that match given WHERE conditions.
Parameter where
method findOne
static findOne: <T extends BaseEntity>( this: { new (): T } & typeof BaseEntity, options: FindOneOptions<T>) => Promise<T | null>;Finds first entity that matches given conditions.
Parameter options
method findOneBy
static findOneBy: <T extends BaseEntity>( this: { new (): T } & typeof BaseEntity, where: FindOptionsWhere<T>) => Promise<T | null>;Finds first entity that matches given conditions.
Parameter where
method findOneByOrFail
static findOneByOrFail: <T extends BaseEntity>( this: { new (): T } & typeof BaseEntity, where: FindOptionsWhere<T>) => Promise<T>;Finds first entity that matches given conditions.
Parameter where
method findOneOrFail
static findOneOrFail: <T extends BaseEntity>( this: { new (): T } & typeof BaseEntity, options: FindOneOptions<T>) => Promise<T>;Finds first entity that matches given conditions.
Parameter options
method getId
static getId: <T extends BaseEntity>( this: { new (): T } & typeof BaseEntity, entity: T) => any;Gets entity mixed id.
Parameter entity
method getRepository
static getRepository: <T extends BaseEntity>( this: { new (): T } & typeof BaseEntity) => Repository<T>;Gets current entity's Repository.
method hasId
static hasId: (entity: BaseEntity) => boolean;Checks if entity has an id. If entity composite compose ids, it will check them all.
Checks entity has an id. If entity composite compose ids, it will check them all.
Parameter entity
method insert
static insert: <T extends BaseEntity>( this: { new (): T } & typeof BaseEntity, entity: QueryDeepPartialEntity<T> | QueryDeepPartialEntity<T>[]) => Promise<InsertResult>;Inserts a given entity into the database. Unlike save method executes a primitive operation without cascades, relations and other operations included. Executes fast and efficient INSERT query. Does not check if entity exist in the database, so query will fail if duplicate entity is being inserted.
Parameter entity
method maximum
static maximum: <T extends BaseEntity>( this: { new (): T } & typeof BaseEntity, columnName: PickKeysByType<T, number>, where: FindOptionsWhere<T>) => Promise<number | null>;Return the MAX of a column
Parameter columnName
Parameter where
method merge
static merge: <T extends BaseEntity>( this: { new (): T } & typeof BaseEntity, mergeIntoEntity: T, ...entityLikes: DeepPartial<T>[]) => T;Merges multiple entities (or entity-like objects) into a given entity.
Parameter mergeIntoEntity
Parameter entityLikes
method minimum
static minimum: <T extends BaseEntity>( this: { new (): T } & typeof BaseEntity, columnName: PickKeysByType<T, number>, where: FindOptionsWhere<T>) => Promise<number | null>;Return the MIN of a column
Parameter columnName
Parameter where
method preload
static preload: <T extends BaseEntity>( this: { new (): T } & typeof BaseEntity, entityLike: DeepPartial<T>) => Promise<T | undefined>;Creates a new entity from the given plain javascript object. If entity already exist in the database, then it loads it (and everything related to it), replaces all values with the new ones from the given object and returns this new entity. This new entity is actually a loaded from the db entity with all properties replaced from the new object.
Note that given entity-like object must have an entity id / primary key to find entity by. Returns undefined if entity with given id was not found.
Parameter entityLike
method query
static query: <T extends BaseEntity>( this: { new (): T } & typeof BaseEntity, query: string, parameters?: any[] | ObjectLiteral) => Promise<any>;Executes a raw SQL query and returns a raw database results. Raw query execution is supported only by relational databases (MongoDB is not supported).
Parameter query
Parameter parameters
method recover
recover: (options?: SaveOptions) => Promise<this>;Recovers a given entity in the database.
Parameter options
method reload
reload: () => Promise<void>;Reloads entity data from the database.
method remove
static remove: { <T extends BaseEntity>( this: { new (): T } & typeof BaseEntity, entities: T[], options?: RemoveOptions ): Promise<T[]>; <T extends BaseEntity>( this: (new () => T) & typeof BaseEntity, entity: T, options?: RemoveOptions ): Promise<T>;};Removes current entity from the database.
Parameter options
Removes a given entities from the database.
Removes a given entity from the database.
method save
static save: { <T extends BaseEntity>( this: { new (): T } & typeof BaseEntity, entities: DeepPartial<T>[], options?: SaveOptions ): Promise<T[]>; <T extends BaseEntity>( this: (new () => T) & typeof BaseEntity, entity: DeepPartial<T>, options?: SaveOptions ): Promise<T>;};Saves current entity in the database. If entity does not exist in the database then inserts, otherwise updates.
Parameter options
Saves all given entities in the database. If entities do not exist in the database then inserts, otherwise updates.
Saves a given entity in the database. If entity does not exist in the database then inserts, otherwise updates.
method softRemove
static softRemove: { <T extends BaseEntity>( this: { new (): T } & typeof BaseEntity, entities: T[], options?: SaveOptions ): Promise<T[]>; <T extends BaseEntity>( this: (new () => T) & typeof BaseEntity, entity: T, options?: SaveOptions ): Promise<T>;};Records the delete date of current entity.
Parameter options
Records the delete date of all given entities.
Records the delete date of a given entity.
method sum
static sum: <T extends BaseEntity>( this: { new (): T } & typeof BaseEntity, columnName: PickKeysByType<T, number>, where: FindOptionsWhere<T>) => Promise<number | null>;Return the SUM of a column
Parameter columnName
Parameter where
method update
static update: <T extends BaseEntity>( this: { new (): T } & typeof BaseEntity, criteria: | string | string[] | number | number[] | Date | Date[] | ObjectId | ObjectId[] | FindOptionsWhere<T>, partialEntity: QueryDeepPartialEntity<T>, options?: UpdateOptions) => Promise<UpdateResult>;Updates entity partially. Entity can be found by a given conditions. Unlike save method executes a primitive operation without cascades, relations and other operations included. Executes fast and efficient UPDATE query. Does not check if entity exist in the database.
Parameter criteria
Parameter partialEntity
Parameter options
method upsert
static upsert: <T extends BaseEntity>( this: { new (): T } & typeof BaseEntity, entityOrEntities: QueryDeepPartialEntity<T> | QueryDeepPartialEntity<T>[], conflictPathsOrOptions: string[] | UpsertOptions<T>) => Promise<InsertResult>;Inserts a given entity into the database, unless a unique constraint conflicts then updates the entity Unlike save method executes a primitive operation without cascades, relations and other operations included. Executes fast and efficient INSERT ... ON CONFLICT DO UPDATE/ON DUPLICATE KEY UPDATE query.
Parameter entityOrEntities
Parameter conflictPathsOrOptions
method useDataSource
static useDataSource: (dataSource: DataSource | null) => void;Sets DataSource to be used by entity.
Parameter dataSource
class Brackets
class Brackets {}Syntax sugar. Allows to use brackets in WHERE expressions for better syntax.
constructor
constructor(whereFactory: (qb: WhereExpressionBuilder) => any);Given WHERE query builder that will build a WHERE expression that will be taken into brackets.
Parameter whereFactory
property "@instanceof"
readonly '@instanceof': Symbol;property whereFactory
whereFactory: (qb: WhereExpressionBuilder) => any;WHERE expression that will be taken into brackets.
class CannotAttachTreeChildrenEntityError
class CannotAttachTreeChildrenEntityError extends TypeORMError {}Thrown when user saves tree children entity but its parent is not saved yet.
constructor
constructor(entityName: string);class CannotConnectAlreadyConnectedError
class CannotConnectAlreadyConnectedError extends TypeORMError {}Thrown when consumer tries to connect when he already connected.
constructor
constructor();class CannotCreateEntityIdMapError
class CannotCreateEntityIdMapError extends TypeORMError {}Thrown when user tries to create entity id map from the mixed id value, but id value is a single value when entity requires multiple values.
constructor
constructor(metadata: EntityMetadata, id: any);class CannotDetermineEntityError
class CannotDetermineEntityError extends TypeORMError {}Thrown when user tries to save/remove/etc. constructor-less object (object literal) instead of entity.
constructor
constructor(operation: string);class CannotExecuteNotConnectedError
class CannotExecuteNotConnectedError extends TypeORMError {}Thrown when consumer tries to execute operation allowed only if connection is opened.
constructor
constructor();class CannotGetEntityManagerNotConnectedError
class CannotGetEntityManagerNotConnectedError extends TypeORMError {}Thrown when consumer tries to access entity manager before connection is established.
constructor
constructor(connectionName: string);class CannotReflectMethodParameterTypeError
class CannotReflectMethodParameterTypeError extends TypeORMError {}Thrown when ORM cannot get method parameter's type. Basically, when reflect-metadata is not available or tsconfig is not properly setup.
constructor
constructor(target: Function, methodName: string);class CircularRelationsError
class CircularRelationsError extends TypeORMError {}Thrown when circular relations detected with nullable set to false.
constructor
constructor(path: string);class ColumnTypeUndefinedError
class ColumnTypeUndefinedError extends TypeORMError {}Thrown when ORM cannot get column's type automatically. Basically, when reflect-metadata is not available or tsconfig is not properly setup.
constructor
constructor(object: Object, propertyName: string);class ConnectionIsNotSetError
class ConnectionIsNotSetError extends TypeORMError {}Thrown when user tries to execute operation that requires connection to be established.
constructor
constructor(dbType: string);class ConnectionNotFoundError
class ConnectionNotFoundError extends TypeORMError {}Thrown when consumer tries to get connection that does not exist.
constructor
constructor(name: string);class ConnectionOptionsReader
class ConnectionOptionsReader {}Reads connection options from the ormconfig.
constructor
constructor(options?: { root?: string; configName?: string });property baseConfigName
readonly baseConfigName: string;Gets configuration file name.
property baseDirectory
readonly baseDirectory: string;Gets directory where configuration file should be located.
property baseFilePath
readonly baseFilePath: string;Gets directory where configuration file should be located and configuration file name.
property options
protected options?: { root?: string; configName?: string };method get
get: () => Promise<DataSourceOptions[]>;Returns all connection options read from the ormconfig.
method load
protected load: () => Promise<DataSourceOptions[] | undefined>;Loads all connection options from a configuration file.
todo: get in count NODE_ENV somehow
method normalizeConnectionOptions
protected normalizeConnectionOptions: ( connectionOptions: DataSourceOptions | DataSourceOptions[]) => DataSourceOptions[];Normalize connection options.
Parameter connectionOptions
class DataSource
class DataSource {}DataSource is a pre-defined connection configuration to a specific database. You can have multiple data sources connected (with multiple connections in it), connected to multiple databases in your application.
Before, it was called
Connection, but nowConnectionis deprecated becauseConnectionisn't the best name for what it's actually is.
constructor
constructor(options: DataSourceOptions);property "@instanceof"
readonly '@instanceof': Symbol;property driver
driver: Driver;Database driver used by this connection.
property entityMetadatas
readonly entityMetadatas: EntityMetadata[];All entity metadatas that are registered for this connection.
property entityMetadatasMap
readonly entityMetadatasMap: Map<EntityTarget<any>, EntityMetadata>;All entity metadatas that are registered for this connection. This is a copy of #.entityMetadatas property -> used for more performant searches.
property isInitialized
readonly isInitialized: boolean;Indicates if the DataSource is initialized or not.
property logger
logger: Logger;Logger used to log orm events.
property manager
readonly manager: EntityManager;EntityManager of this connection.
property metadataTableName
readonly metadataTableName: string;Name for the metadata table
property migrations
readonly migrations: MigrationInterface[];Migration instances that are registered for this connection.
property mongoManager
readonly mongoManager: MongoEntityManager;Gets the mongodb entity manager that allows to perform mongodb-specific repository operations with any entity in this connection.
Available only in mongodb connections.
Returns
the mongodb entity manager
property namingStrategy
namingStrategy: NamingStrategyInterface;Naming strategy used in the connection.
property options
readonly options: DataSourceOptions;DataSource options.
property queryResultCache
queryResultCache?: QueryResultCache;Used to work with query result cache.
property relationIdLoader
readonly relationIdLoader: RelationIdLoader;property relationLoader
readonly relationLoader: RelationLoader;Used to load relations and work with lazy relations.
property sqljsManager
readonly sqljsManager: SqljsEntityManager;Gets a sql.js specific Entity Manager that allows to perform special load and save operations
Available only in connection with the sqljs driver.
Returns
an sqljs specific Entity Manager
property subscribers
readonly subscribers: EntitySubscriberInterface<any>[];Entity subscriber instances that are registered for this connection.
method buildMetadatas
protected buildMetadatas: () => Promise<void>;Builds metadatas for all registered classes inside this connection.
method createEntityManager
createEntityManager: (queryRunner?: QueryRunner) => EntityManager;Creates an Entity Manager for the current connection with the help of the EntityManagerFactory.
Parameter queryRunner
method createQueryBuilder
createQueryBuilder: { <Entity extends ObjectLiteral>( entityClass: EntityTarget<Entity>, alias: string, queryRunner?: QueryRunner ): SelectQueryBuilder<Entity>; (queryRunner?: QueryRunner): SelectQueryBuilder<any>;};Creates a new query builder that can be used to build a SQL query.
method createQueryRunner
createQueryRunner: (mode?: ReplicationMode) => QueryRunner;Creates a query runner used for perform queries on a single database connection. Using query runners you can control your queries to execute using single database connection and manually control your database transaction.
Mode is used in replication mode and indicates whatever you want to connect to master database or any of slave databases. If you perform writes you must use master database, if you perform reads you can use slave databases.
Parameter mode
method defaultReplicationModeForReads
defaultReplicationModeForReads: () => ReplicationMode;Get the replication mode SELECT queries should use for this datasource by default
method destroy
destroy: () => Promise<void>;Closes connection with the database. Once connection is closed, you cannot use repositories or perform any operations except opening connection again.
method dropDatabase
dropDatabase: () => Promise<void>;Drops the database and all its data. Be careful with this method on production since this method will erase all your database tables and their data. Can be used only after connection to the database is established.
method findMetadata
protected findMetadata: ( target: EntityTarget<any>) => EntityMetadata | undefined;Finds exist entity metadata by the given entity class, target name or table name.
Parameter target
method getManyToManyMetadata
getManyToManyMetadata: ( entityTarget: EntityTarget<any>, relationPropertyPath: string) => EntityMetadata | undefined;Gets entity metadata of the junction table (many-to-many table).
Parameter entityTarget
Parameter relationPropertyPath
method getMetadata
getMetadata: (target: EntityTarget<any>) => EntityMetadata;Gets entity metadata for the given entity class or schema name.
Parameter target
method getMongoRepository
getMongoRepository: <Entity extends ObjectLiteral>( target: EntityTarget<Entity>) => MongoRepository<Entity>;Gets mongodb-specific repository for the given entity class or name. Works only if connection is mongodb-specific.
Parameter target
method getRepository
getRepository: <Entity extends ObjectLiteral>( target: EntityTarget<Entity>) => Repository<Entity>;Gets repository for the given entity.
Parameter target
method getTreeRepository
getTreeRepository: <Entity extends ObjectLiteral>( target: EntityTarget<Entity>) => TreeRepository<Entity>;Gets tree repository for the given entity class or name. Only tree-type entities can have a TreeRepository, like ones decorated with
@Treedecorator.Parameter target
method hasMetadata
hasMetadata: (target: EntityTarget<any>) => boolean;Checks if entity metadata exist for the given entity class, target name or table name.
Parameter target
method initialize
initialize: () => Promise<this>;Performs connection to the database. This method should be called once on application bootstrap. This method not necessarily creates database connection (depend on database type), but it also can setup a connection pool with database to use.
method query
query: <T = any>( query: string, parameters?: any[] | ObjectLiteral, queryRunner?: QueryRunner) => Promise<T>;Executes raw SQL query and returns raw database results.
Parameter query
Parameter parameters
Parameter queryRunner
Returns
a raw response from the database client
See Also
Official docs for examples.
method runMigrations
runMigrations: (options?: { transaction?: 'all' | 'none' | 'each'; fake?: boolean;}) => Promise<Migration[]>;Runs all pending migrations. Can be used only after connection to the database is established.
Parameter options
Parameter
options.transaction
Parameter
options.fake
method setOptions
setOptions: (options: Partial<DataSourceOptions>) => this;Updates current connection options with provided options.
Parameter options
method showMigrations
showMigrations: () => Promise<boolean>;Lists all migrations and whether they have been run. Returns true if there are pending migrations
method sql
sql: <T = any>( strings: TemplateStringsArray, ...values: unknown[]) => Promise<T>;Tagged template function that executes raw SQL query and returns raw database results. Template expressions are automatically transformed into database parameters. Raw query execution is supported only by relational databases (MongoDB is not supported). Note: Don't call this as a regular function, it is meant to be used with backticks to tag a template literal.
Parameter strings
Parameter values
Returns
a raw response from the database client
Example 1
dataSource.sql
SELECT * FROM table_name WHERE id = ${id}
method synchronize
synchronize: (dropBeforeSync?: boolean) => Promise<void>;Creates database schema for all entities registered in this connection. Can be used only after connection to the database is established.
Parameter dropBeforeSync
If set to true then it drops the database with all its tables and data
method transaction
transaction: { <T>( runInTransaction: (entityManager: EntityManager) => Promise<T> ): Promise<T>; <T>( isolationLevel: | 'READ COMMITTED' | 'READ UNCOMMITTED' | 'REPEATABLE READ' | 'SERIALIZABLE' | 'SNAPSHOT', runInTransaction: (entityManager: EntityManager) => Promise<T> ): Promise<T>;};Wraps given function execution (and all operations made there) into a transaction. All database operations must be executed using provided entity manager.
method undoLastMigration
undoLastMigration: (options?: { transaction?: 'all' | 'none' | 'each'; fake?: boolean;}) => Promise<void>;Reverts last executed migration. Can be used only after connection to the database is established.
Parameter options
Parameter
options.transaction
Parameter
options.fake
class DataTypeNotSupportedError
class DataTypeNotSupportedError extends TypeORMError {}constructor
constructor( column: ColumnMetadata, dataType: ColumnType, database?: DatabaseType);class DefaultNamingStrategy
class DefaultNamingStrategy implements NamingStrategyInterface {}Naming strategy that is used by default.
property materializedPathColumnName
materializedPathColumnName: string;property nestedSetColumnNames
nestedSetColumnNames: { left: string; right: string };method checkConstraintName
checkConstraintName: ( tableOrName: Table | string, expression: string, isEnum?: boolean) => string;method closureJunctionTableName
closureJunctionTableName: (originalClosureTableName: string) => string;method columnName
columnName: ( propertyName: string, customName: string, embeddedPrefixes: string[]) => string;method defaultConstraintName
defaultConstraintName: ( tableOrName: Table | string, columnName: string) => string;method exclusionConstraintName
exclusionConstraintName: ( tableOrName: Table | string, expression: string) => string;method foreignKeyName
foreignKeyName: ( tableOrName: Table | string, columnNames: string[], _referencedTablePath?: string, _referencedColumnNames?: string[]) => string;method getTableName
protected getTableName: (tableOrName: Table | string) => string;method hash
protected hash: (input: string) => string;method indexName
indexName: ( tableOrName: Table | string, columnNames: string[], where?: string) => string;method joinColumnName
joinColumnName: (relationName: string, referencedColumnName: string) => string;method joinTableColumnDuplicationPrefix
joinTableColumnDuplicationPrefix: (columnName: string, index: number) => string;method joinTableColumnName
joinTableColumnName: ( tableName: string, propertyName: string, columnName?: string) => string;method joinTableInverseColumnName
joinTableInverseColumnName: ( tableName: string, propertyName: string, columnName?: string) => string;method joinTableName
joinTableName: ( firstTableName: string, secondTableName: string, firstPropertyName: string, secondPropertyName: string) => string;method prefixTableName
prefixTableName: (prefix: string, tableName: string) => string;method primaryKeyName
primaryKeyName: (tableOrName: Table | string, columnNames: string[]) => string;method relationConstraintName
relationConstraintName: ( tableOrName: Table | string, columnNames: string[], where?: string) => string;method relationName
relationName: (propertyName: string) => string;method tableName
tableName: (targetName: string, userSpecifiedName: string | undefined) => string;method uniqueConstraintName
uniqueConstraintName: ( tableOrName: Table | string, columnNames: string[]) => string;class DeleteQueryBuilder
class DeleteQueryBuilder<Entity extends ObjectLiteral> extends QueryBuilder<Entity> implements WhereExpressionBuilder {}Allows to build complex sql queries in a fashion way and execute those queries.
constructor
constructor( connectionOrQueryBuilder: DataSource | QueryBuilder<any>, queryRunner?: QueryRunner);property "@instanceof"
readonly '@instanceof': Symbol;method andWhere
andWhere: ( where: | string | ObjectLiteral | Brackets | ObjectLiteral[] | ((qb: this) => string), parameters?: ObjectLiteral) => this;Adds new AND WHERE condition in the query builder. Additionally you can add parameters used in where expression.
Parameter where
Parameter parameters
method andWhereInIds
andWhereInIds: (ids: any | any[]) => this;Adds new AND WHERE with conditions for the given ids.
Parameter ids
method createDeleteExpression
protected createDeleteExpression: () => string;Creates DELETE express used to perform query.
method execute
execute: () => Promise<DeleteResult>;Executes sql generated by query builder and returns raw database results.
method from
from: <T extends ObjectLiteral>( entityTarget: EntityTarget<T>, aliasName?: string) => DeleteQueryBuilder<T>;Specifies FROM which entity's table select/update/delete will be executed. Also sets a main string alias of the selection data.
Parameter entityTarget
Parameter aliasName
method getQuery
getQuery: () => string;Gets generated SQL query without parameters being replaced.
method orWhere
orWhere: ( where: | string | ObjectLiteral | Brackets | ObjectLiteral[] | ((qb: this) => string), parameters?: ObjectLiteral) => this;Adds new OR WHERE condition in the query builder. Additionally you can add parameters used in where expression.
Parameter where
Parameter parameters
method orWhereInIds
orWhereInIds: (ids: any | any[]) => this;Adds new OR WHERE with conditions for the given ids.
Parameter ids
method output
output: { (columns: string[]): this; (output: string): this; (output: string | string[]): this;};Optional returning/output clause. This will return given column values.
Optional returning/output clause. Returning is a SQL string containing returning statement.
Optional returning/output clause.
method returning
returning: { (columns: string[]): this; (returning: string): this; (returning: string | string[]): this;};Optional returning/output clause. This will return given column values.
Optional returning/output clause. Returning is a SQL string containing returning statement.
Optional returning/output clause.
method where
where: ( where: | string | ObjectLiteral | Brackets | ObjectLiteral[] | ((qb: this) => string), parameters?: ObjectLiteral) => this;Sets WHERE condition in the query builder. If you had previously WHERE expression defined, calling this function will override previously set WHERE conditions. Additionally you can add parameters used in where expression.
Parameter where
Parameter parameters
method whereInIds
whereInIds: (ids: any | any[]) => this;Sets WHERE condition in the query builder with a condition for the given ids. If you had previously WHERE expression defined, calling this function will override previously set WHERE conditions.
Parameter ids
class DeleteResult
class DeleteResult {}Result object returned by DeleteQueryBuilder execution.
class DriverOptionNotSetError
class DriverOptionNotSetError extends TypeORMError {}Thrown if some required driver's option is not set.
constructor
constructor(optionName: string);class DriverPackageNotInstalledError
class DriverPackageNotInstalledError extends TypeORMError {}Thrown when required driver's package is not installed.
constructor
constructor(driverName: string, packageName: string);class EntityManager
class EntityManager {}Entity manager supposed to work with any entity, automatically find its repository and call its methods, whatever entity type are you passing.
constructor
constructor(dataSource: DataSource, queryRunner?: QueryRunner);property "@instanceof"
readonly '@instanceof': Symbol;property connection
readonly connection: DataSource;DataSource used by this entity manager.
Deprecated
since 1.0.0. Use dataSource instance instead.
property dataSource
readonly dataSource: DataSource;DataSource used by this entity manager.
property plainObjectToEntityTransformer
protected plainObjectToEntityTransformer: PlainObjectToNewEntityTransformer;Plain to object transformer used in create and merge operations.
property queryRunner
readonly queryRunner?: QueryRunner;Custom query runner to be used for operations in this entity manager. Used only in non-global entity manager.
property repositories
protected repositories: Map<EntityTarget<any>, Repository<any>>;Once created and then reused by repositories. Created as a future replacement for the #repositories to provide a bit more perf optimization.
property treeRepositories
protected treeRepositories: TreeRepository<any>[];Once created and then reused by repositories.
method average
average: <Entity extends ObjectLiteral>( entityClass: EntityTarget<Entity>, columnName: PickKeysByType<Entity, number>, where?: FindOptionsWhere<Entity> | FindOptionsWhere<Entity>[]) => Promise<number | null>;Return the AVG of a column
Parameter entityClass
Parameter columnName
Parameter where
method clear
clear: <Entity>( entityClass: EntityTarget<Entity>, options?: { cascade?: boolean }) => Promise<void>;Clears all the data from the given table (truncates/drops it).
Note: this method uses TRUNCATE and may not work as you expect in transactions on some platforms.
Parameter entityClass
Parameter options
Parameter
options.cascade
See Also
https://stackoverflow.com/a/5972738/925151
method count
count: <Entity extends ObjectLiteral>( entityClass: EntityTarget<Entity>, options?: FindManyOptions<Entity>) => Promise<number>;Counts entities that match given options. Useful for pagination.
Parameter entityClass
Parameter options
method countBy
countBy: <Entity extends ObjectLiteral>( entityClass: EntityTarget<Entity>, where: FindOptionsWhere<Entity> | FindOptionsWhere<Entity>[]) => Promise<number>;Counts entities that match given conditions. Useful for pagination.
Parameter entityClass
Parameter where
method create
create: { <Entity, EntityLike extends DeepPartial<Entity>>( entityClass: EntityTarget<Entity>, plainObject?: EntityLike ): Entity; <Entity, EntityLike extends DeepPartial<Entity>>( entityClass: EntityTarget<Entity>, plainObjects?: EntityLike[] ): Entity[];};Creates a new entity instance and copies all entity properties from this object into a new entity. Note that it copies only properties that present in entity schema.
Creates a new entities and copies all entity properties from given objects into their new entities. Note that it copies only properties that present in entity schema.
method createQueryBuilder
createQueryBuilder: { <Entity extends ObjectLiteral>( entityClass: EntityTarget<Entity>, alias: string, queryRunner?: QueryRunner ): SelectQueryBuilder<Entity>; (queryRunner?: QueryRunner): SelectQueryBuilder<any>;};Creates a new query builder that can be used to build a SQL query.
method decrement
decrement: <Entity extends ObjectLiteral>( entityClass: EntityTarget<Entity>, conditions: FindOptionsWhere<Entity>, propertyPath: string, value: number | string) => Promise<UpdateResult>;Decrements some column by provided value of the entities matched given conditions.
Parameter entityClass
Parameter conditions
Parameter propertyPath
Parameter value
method delete
delete: <Entity extends ObjectLiteral>( targetOrEntity: EntityTarget<Entity>, criteria: | string | string[] | number | number[] | Date | Date[] | ObjectId | ObjectId[] | any) => Promise<DeleteResult>;Deletes entities by a given condition(s). Unlike save method executes a primitive operation without cascades, relations and other operations included. Executes fast and efficient DELETE query. Does not check if entity exist in the database. Condition(s) cannot be empty.
Parameter targetOrEntity
Parameter criteria
method deleteAll
deleteAll: <Entity extends ObjectLiteral>( targetOrEntity: EntityTarget<Entity>) => Promise<DeleteResult>;Deletes all entities of target type. This is a primitive operation without cascades, relations or other operations included. Executes fast and efficient DELETE query without WHERE clause.
WARNING! This method deletes ALL rows in the target table.
Parameter targetOrEntity
method exists
exists: <Entity extends ObjectLiteral>( entityClass: EntityTarget<Entity>, options?: FindManyOptions<Entity>) => Promise<boolean>;Checks whether any entity exists with the given options.
Parameter entityClass
Parameter options
method existsBy
existsBy: <Entity extends ObjectLiteral>( entityClass: EntityTarget<Entity>, where: FindOptionsWhere<Entity> | FindOptionsWhere<Entity>[]) => Promise<boolean>;Checks whether any entity exists with the given conditions.
Parameter entityClass
Parameter where
method find
find: <Entity extends ObjectLiteral>( entityClass: EntityTarget<Entity>, options?: FindManyOptions<Entity>) => Promise<Entity[]>;Finds entities that match given find options.
Parameter entityClass
Parameter options
method findAndCount
findAndCount: <Entity extends ObjectLiteral>( entityClass: EntityTarget<Entity>, options?: FindManyOptions<Entity>) => Promise<[Entity[], number]>;Finds entities that match given find options. Also counts all entities that match given conditions, but ignores pagination settings (from and take options).
Parameter entityClass
Parameter options
method findAndCountBy
findAndCountBy: <Entity extends ObjectLiteral>( entityClass: EntityTarget<Entity>, where: FindOptionsWhere<Entity> | FindOptionsWhere<Entity>[]) => Promise<[Entity[], number]>;Finds entities that match given WHERE conditions. Also counts all entities that match given conditions, but ignores pagination settings (from and take options).
Parameter entityClass
Parameter where
method findBy
findBy: <Entity extends ObjectLiteral>( entityClass: EntityTarget<Entity>, where: FindOptionsWhere<Entity> | FindOptionsWhere<Entity>[]) => Promise<Entity[]>;Finds entities that match given find options.
Parameter entityClass
Parameter where
method findOne
findOne: <Entity extends ObjectLiteral>( entityClass: EntityTarget<Entity>, options: FindOneOptions<Entity>) => Promise<Entity | null>;Finds first entity by a given find options. If entity was not found in the database - returns null.
Parameter entityClass
Parameter options
method findOneBy
findOneBy: <Entity extends ObjectLiteral>( entityClass: EntityTarget<Entity>, where: FindOptionsWhere<Entity> | FindOptionsWhere<Entity>[]) => Promise<Entity | null>;Finds first entity that matches given where condition. If entity was not found in the database - returns null.
Parameter entityClass
Parameter where
method findOneByOrFail
findOneByOrFail: <Entity extends ObjectLiteral>( entityClass: EntityTarget<Entity>, where: FindOptionsWhere<Entity> | FindOptionsWhere<Entity>[]) => Promise<Entity>;Finds first entity that matches given where condition. If entity was not found in the database - rejects with error.
Parameter entityClass
Parameter where
method findOneOrFail
findOneOrFail: <Entity extends ObjectLiteral>( entityClass: EntityTarget<Entity>, options: FindOneOptions<Entity>) => Promise<Entity>;Finds first entity by a given find options. If entity was not found in the database - rejects with error.
Parameter entityClass
Parameter options
method getId
getId: { (entity: any): any; (target: EntityTarget<any>, entity: any): any };Gets entity mixed id.
method getMongoRepository
getMongoRepository: <Entity extends ObjectLiteral>( target: EntityTarget<Entity>) => MongoRepository<Entity>;Gets mongodb repository for the given entity class.
Parameter target
method getRepository
getRepository: <Entity extends ObjectLiteral>( target: EntityTarget<Entity>) => Repository<Entity>;Gets repository for the given entity class or name. If single database connection mode is used, then repository is obtained from the repository aggregator, where each repository is individually created for this entity manager. When single database connection is not used, repository is being obtained from the connection.
Parameter target
method getTreeRepository
getTreeRepository: <Entity extends ObjectLiteral>( target: EntityTarget<Entity>) => TreeRepository<Entity>;Gets tree repository for the given entity class or name. If single database connection mode is used, then repository is obtained from the repository aggregator, where each repository is individually created for this entity manager. When single database connection is not used, repository is being obtained from the connection.
Parameter target
method hasId
hasId: { (entity: any): boolean; (target: string | Function, entity: any): boolean;};Checks if entity has an id.
Checks if entity of given schema name has an id.
method increment
increment: <Entity extends ObjectLiteral>( entityClass: EntityTarget<Entity>, conditions: FindOptionsWhere<Entity>, propertyPath: string, value: number | string) => Promise<UpdateResult>;Increments some column by provided value of the entities matched given conditions.
Parameter entityClass
Parameter conditions
Parameter propertyPath
Parameter value
method insert
insert: <Entity extends ObjectLiteral>( target: EntityTarget<Entity>, entity: QueryDeepPartialEntity<Entity> | QueryDeepPartialEntity<Entity>[]) => Promise<InsertResult>;Inserts a given entity into the database. Unlike save method executes a primitive operation without cascades, relations and other operations included. Executes fast and efficient INSERT query. Does not check if entity exist in the database, so query will fail if duplicate entity is being inserted. You can execute bulk inserts using this method.
Parameter target
Parameter entity
method maximum
maximum: <Entity extends ObjectLiteral>( entityClass: EntityTarget<Entity>, columnName: PickKeysByType<Entity, number>, where?: FindOptionsWhere<Entity> | FindOptionsWhere<Entity>[]) => Promise<number | null>;Return the MAX of a column
Parameter entityClass
Parameter columnName
Parameter where
method merge
merge: <Entity extends ObjectLiteral>( entityClass: EntityTarget<Entity>, mergeIntoEntity: Entity, ...entityLikes: DeepPartial<Entity>[]) => Entity;Merges two entities into one new entity.
Parameter entityClass
Parameter mergeIntoEntity
Parameter entityLikes
method minimum
minimum: <Entity extends ObjectLiteral>( entityClass: EntityTarget<Entity>, columnName: PickKeysByType<Entity, number>, where?: FindOptionsWhere<Entity> | FindOptionsWhere<Entity>[]) => Promise<number | null>;Return the MIN of a column
Parameter entityClass
Parameter columnName
Parameter where
method preload
preload: <Entity extends ObjectLiteral>( entityClass: EntityTarget<Entity>, entityLike: DeepPartial<Entity>) => Promise<Entity | undefined>;Creates a new entity from the given plain javascript object. If entity already exist in the database, then it loads it (and everything related to it), replaces all values with the new ones from the given object and returns this new entity. This new entity is actually a loaded from the db entity with all properties replaced from the new object.
Parameter entityClass
Parameter entityLike
method query
query: <T = any>( query: string, parameters?: any[] | ObjectLiteral) => Promise<T>;Executes raw SQL query and returns raw database results.
Parameter query
Parameter parameters
See Also
[Official docs](https://typeorm.io/docs/Working%20with%20Entity%20Manager/entity-manager-api/) for examples.
method recover
recover: { <Entity>(entities: Entity[], options?: SaveOptions): Promise<Entity[]>; <Entity>(entity: Entity, options?: SaveOptions): Promise<Entity>; <Entity, T extends DeepPartial<Entity>>( targetOrEntity: EntityTarget<Entity>, entities: T[], options?: SaveOptions ): Promise<T[]>; <Entity, T extends DeepPartial<Entity>>( targetOrEntity: EntityTarget<Entity>, entity: T, options?: SaveOptions ): Promise<T>;};Recovers all given entities.
Recovers a given entity.
method release
release: () => Promise<void>;Releases all resources used by entity manager. This is used when entity manager is created with a single query runner, and this single query runner needs to be released after job with entity manager is done.
method remove
remove: { <Entity>(entity: Entity, options?: RemoveOptions): Promise<Entity>; <Entity>( targetOrEntity: EntityTarget<Entity>, entity: Entity, options?: RemoveOptions ): Promise<Entity>; <Entity>(entity: Entity[], options?: RemoveOptions): Promise<Entity>; <Entity>( targetOrEntity: EntityTarget<Entity>, entity: Entity[], options?: RemoveOptions ): Promise<Entity[]>;};Removes a given entity from the database.
method restore
restore: <Entity extends ObjectLiteral>( targetOrEntity: EntityTarget<Entity>, criteria: | string | string[] | number | number[] | Date | Date[] | ObjectId | ObjectId[] | any) => Promise<UpdateResult>;Restores entities by a given condition(s). Unlike save method executes a primitive operation without cascades, relations and other operations included. Executes fast and efficient UPDATE query. Does not check if entity exist in the database. Condition(s) cannot be empty.
Parameter targetOrEntity
Parameter criteria
method save
save: { <Entity>(entities: Entity[], options?: SaveOptions): Promise<Entity[]>; <Entity>(entity: Entity, options?: SaveOptions): Promise<Entity>; <Entity, T extends DeepPartial<Entity>>( targetOrEntity: EntityTarget<Entity>, entities: T[], options: SaveOptions & { reload: false } ): Promise<T[]>; <Entity, T extends DeepPartial<Entity>>( targetOrEntity: EntityTarget<Entity>, entities: T[], options?: SaveOptions ): Promise<(T & Entity)[]>; <Entity, T extends DeepPartial<Entity>>( targetOrEntity: EntityTarget<Entity>, entity: T, options: SaveOptions & { reload: false } ): Promise<T>; <Entity, T extends DeepPartial<Entity>>( targetOrEntity: EntityTarget<Entity>, entity: T, options?: SaveOptions ): Promise<T & Entity>;};Saves all given entities in the database. If entities do not exist in the database then inserts, otherwise updates.
Saves a given entity in the database. If entity does not exist in the database then inserts, otherwise updates.
method softDelete
softDelete: <Entity extends ObjectLiteral>( targetOrEntity: EntityTarget<Entity>, criteria: | string | string[] | number | number[] | Date | Date[] | ObjectId | ObjectId[] | any) => Promise<UpdateResult>;Records the delete date of entities by a given condition(s). Unlike save method executes a primitive operation without cascades, relations and other operations included. Executes fast and efficient UPDATE query. Does not check if entity exist in the database. Condition(s) cannot be empty.
Parameter targetOrEntity
Parameter criteria
method softRemove
softRemove: { <Entity>(entities: Entity[], options?: SaveOptions): Promise<Entity[]>; <Entity>(entity: Entity, options?: SaveOptions): Promise<Entity>; <Entity, T extends DeepPartial<Entity>>( targetOrEntity: EntityTarget<Entity>, entities: T[], options?: SaveOptions ): Promise<T[]>; <Entity, T extends DeepPartial<Entity>>( targetOrEntity: EntityTarget<Entity>, entity: T, options?: SaveOptions ): Promise<T>;};Records the delete date of all given entities.
Records the delete date of a given entity.
method sql
sql: <T = any>( strings: TemplateStringsArray, ...values: unknown[]) => Promise<T>;Tagged template function that executes raw SQL query and returns raw database results. Template expressions are automatically transformed into database parameters. Raw query execution is supported only by relational databases (MongoDB is not supported). Note: Don't call this as a regular function, it is meant to be used with backticks to tag a template literal.
Parameter strings
Parameter values
Example 1
entityManager.sql
SELECT * FROM table_name WHERE id = ${id}
method sum
sum: <Entity extends ObjectLiteral>( entityClass: EntityTarget<Entity>, columnName: PickKeysByType<Entity, number>, where?: FindOptionsWhere<Entity> | FindOptionsWhere<Entity>[]) => Promise<number | null>;Return the SUM of a column
Parameter entityClass
Parameter columnName
Parameter where
method transaction
transaction: { <T>( runInTransaction: (entityManager: EntityManager) => Promise<T> ): Promise<T>; <T>( isolationLevel: | 'READ COMMITTED' | 'READ UNCOMMITTED' | 'REPEATABLE READ' | 'SERIALIZABLE' | 'SNAPSHOT', runInTransaction: (entityManager: EntityManager) => Promise<T> ): Promise<T>;};Wraps given function execution (and all operations made there) in a transaction. All database operations must be executed using provided entity manager.
method update
update: <Entity extends ObjectLiteral>( target: EntityTarget<Entity>, criteria: | string | string[] | number | number[] | Date | Date[] | ObjectId | ObjectId[] | any, partialEntity: QueryDeepPartialEntity<Entity>, options?: UpdateOptions) => Promise<UpdateResult>;Updates entity partially. Entity can be found by a given condition(s). Unlike save method executes a primitive operation without cascades, relations and other operations included. Executes fast and efficient UPDATE query. Does not check if entity exist in the database. Condition(s) cannot be empty.
Parameter target
Parameter criteria
Parameter partialEntity
Parameter options
method updateAll
updateAll: <Entity extends ObjectLiteral>( target: EntityTarget<Entity>, partialEntity: QueryDeepPartialEntity<Entity>, options?: UpdateOptions) => Promise<UpdateResult>;Updates all entities of target type, setting fields from supplied partial entity. This is a primitive operation without cascades, relations or other operations included. Executes fast and efficient UPDATE query without WHERE clause.
WARNING! This method updates ALL rows in the target table.
Parameter target
Parameter partialEntity
Parameter options
method upsert
upsert: <Entity extends ObjectLiteral>( target: EntityTarget<Entity>, entityOrEntities: | QueryDeepPartialEntity<Entity> | QueryDeepPartialEntity<Entity>[], conflictPathsOrOptions: string[] | UpsertOptions<Entity>) => Promise<InsertResult>;method withRepository
withRepository: <Entity extends ObjectLiteral, R extends Repository<any>>( repository: R & Repository<Entity>) => R;Creates a new repository instance out of a given Repository and sets current EntityManager instance to it. Used to work with custom repositories in transactions.
Parameter repository
class EntityMetadata
class EntityMetadata {}Contains all entity metadata.
constructor
constructor(options: { dataSource: DataSource; inheritanceTree?: Function[]; inheritancePattern?: 'STI'; tableTree?: TreeMetadataArgs; parentClosureEntityMetadata?: EntityMetadata; args: TableMetadataArgs;});property "@instanceof"
readonly '@instanceof': Symbol;property afterInsertListeners
afterInsertListeners: EntityListenerMetadata[];Listener metadatas with "AFTER INSERT" type.
property afterLoadListeners
afterLoadListeners: EntityListenerMetadata[];Listener metadatas with "AFTER LOAD" type.
property afterRecoverListeners
afterRecoverListeners: EntityListenerMetadata[];Listener metadatas with "AFTER RECOVER" type.
property afterRemoveListeners
afterRemoveListeners: EntityListenerMetadata[];Listener metadatas with "AFTER REMOVE" type.
property afterSoftRemoveListeners
afterSoftRemoveListeners: EntityListenerMetadata[];Listener metadatas with "AFTER SOFT REMOVE" type.
property afterUpdateListeners
afterUpdateListeners: EntityListenerMetadata[];Listener metadatas with "AFTER UPDATE" type.
property allEmbeddeds
allEmbeddeds: EmbeddedMetadata[];All embeddeds - embeddeds from this entity metadata and from all child embeddeds, etc.
property ancestorColumns
ancestorColumns: ColumnMetadata[];Ancestor columns used only in closure junction tables.
property beforeInsertListeners
beforeInsertListeners: EntityListenerMetadata[];Listener metadatas with "BEFORE INSERT" type.
property beforeRecoverListeners
beforeRecoverListeners: EntityListenerMetadata[];Listener metadatas with "BEFORE RECOVER" type.
property beforeRemoveListeners
beforeRemoveListeners: EntityListenerMetadata[];Listener metadatas with "BEFORE REMOVE" type.
property beforeSoftRemoveListeners
beforeSoftRemoveListeners: EntityListenerMetadata[];Listener metadatas with "BEFORE SOFT REMOVE" type.
property beforeUpdateListeners
beforeUpdateListeners: EntityListenerMetadata[];Listener metadatas with "BEFORE UPDATE" type.
property checks
checks: CheckMetadata[];Entity's check metadatas.
property childEntityMetadatas
childEntityMetadatas: EntityMetadata[];Children entity metadatas. Used in inheritance patterns.
property closureJunctionTable
closureJunctionTable: EntityMetadata;If entity's table is a closure-typed table, then this entity will have a closure junction table metadata.
property columns
columns: ColumnMetadata[];Columns of the entity, including columns that are coming from the embeddeds of this entity.
property comment
comment?: string;Table comment. Not supported by all database types.
property connection
readonly connection: DataSource;DataSource where this entity metadata is created.
Deprecated
since 1.0.0. Use dataSource instance instead.
property createDateColumn
createDateColumn?: ColumnMetadata;Gets entity column which contains a create date value.
property database
database?: string;Database name.
property dataSource
dataSource: DataSource;DataSource where this entity metadata is created.
property deleteDateColumn
deleteDateColumn?: ColumnMetadata;Gets entity column which contains a delete date value.
property dependsOn
dependsOn?: Set<string | Function>;View's dependencies. Used in views
property descendantColumns
descendantColumns: ColumnMetadata[];Descendant columns used only in closure junction tables.
property discriminatorColumn
discriminatorColumn?: ColumnMetadata;Gets the discriminator column used to store entity identificator in single-table inheritance tables.
property discriminatorValue
discriminatorValue?: string;If this entity metadata is a child table of some table, it should have a discriminator value. Used to store a value in a discriminator column.
property eagerRelations
eagerRelations: RelationMetadata[];List of eager relations this metadata has.
property embeddeds
embeddeds: EmbeddedMetadata[];Entity's embedded metadatas.
property engine
engine?: string;Table's database engine type (like "InnoDB", "MyISAM", etc).
property exclusions
exclusions: ExclusionMetadata[];Entity's exclusion metadatas.
property expression
expression?: string | ((dataSource: DataSource) => SelectQueryBuilder<any>);View's expression. Used in views
property foreignKeys
foreignKeys: ForeignKeyMetadata[];Entity's foreign key metadatas.
property generatedColumns
generatedColumns: ColumnMetadata[];Gets the column with generated flag.
property givenTableName
givenTableName?: string;Original user-given table name (taken from schema or @Entity(tableName) decorator). If user haven't specified a table name this property will be undefined.
property hasMultiplePrimaryKeys
hasMultiplePrimaryKeys: boolean;Checks if entity's table has multiple primary columns.
property hasNonNullableRelations
hasNonNullableRelations: boolean;Checks if there any non-nullable column exist in this entity.
property hasUUIDGeneratedColumns
hasUUIDGeneratedColumns: boolean;Indicates if this entity metadata has uuid generated columns.
property indices
indices: IndexMetadata[];Entity's index metadatas.
property inheritancePattern
inheritancePattern?: string;If this entity metadata's table using one of the inheritance patterns, then this will contain what pattern it uses.
property inheritanceTree
inheritanceTree: Function[];All "inheritance tree" from a target entity. For example for target Post < ContentModel < Unit it will be an array of [Post, ContentModel, Unit]. It also contains child entities for single table inheritance.
property inverseColumns
inverseColumns: ColumnMetadata[];In the case if this entity metadata is junction table's entity metadata, this will contain all referenced columns of inverse entity.
property isAlwaysUsingConstructor
isAlwaysUsingConstructor: boolean;Indicates if the entity should be instantiated using the constructor or via allocating a new object via
Object.create().
property isClosureJunction
isClosureJunction: boolean;Checks if this table is a junction table of the closure table. This type is for tables that contain junction metadata of the closure tables.
property isJunction
isJunction: boolean;Indicates if this entity metadata of a junction table, or not. Junction table is a table created by many-to-many relationship.
Its also possible to understand if entity is junction via tableType.
property lazyRelations
lazyRelations: RelationMetadata[];List of eager relations this metadata has.
property listeners
listeners: EntityListenerMetadata[];Entity listener metadatas.
property manyToManyRelations
manyToManyRelations: RelationMetadata[];Gets only many-to-many relations of the entity.
property manyToOneRelations
manyToOneRelations: RelationMetadata[];Gets only many-to-one relations of the entity.
property materializedPathColumn
materializedPathColumn?: ColumnMetadata;Materialized path column. Used only in tree entities with materialized path pattern applied.
property name
name: string;Entity's name. Equal to entity target class's name if target is set to table. If target class is not then then it equals to table name.
property nestedSetLeftColumn
nestedSetLeftColumn?: ColumnMetadata;Nested set's left value column. Used only in tree entities with nested set pattern applied.
property nestedSetRightColumn
nestedSetRightColumn?: ColumnMetadata;Nested set's right value column. Used only in tree entities with nested set pattern applied.
property nonVirtualColumns
nonVirtualColumns: ColumnMetadata[];All columns except for virtual columns.
property objectIdColumn
objectIdColumn?: ColumnMetadata;Gets the object id column used with mongodb database.
property oneToManyRelations
oneToManyRelations: RelationMetadata[];Gets only one-to-many relations of the entity.
property oneToOneRelations
oneToOneRelations: RelationMetadata[];Gets only one-to-one relations of the entity.
property orderBy
orderBy?: OrderByCondition;Specifies a default order by used for queries from this table when no explicit order by is specified.
property ownColumns
ownColumns: ColumnMetadata[];Entity's column metadatas defined by user.
property ownerColumns
ownerColumns: ColumnMetadata[];In the case if this entity metadata is junction table's entity metadata, this will contain all referenced columns of owner entity.
property ownerManyToManyRelations
ownerManyToManyRelations: RelationMetadata[];Gets only owner many-to-many relations of the entity.
property ownerOneToOneRelations
ownerOneToOneRelations: RelationMetadata[];Gets only owner one-to-one relations of the entity.
property ownIndices
ownIndices: IndexMetadata[];Entity's own indices.
property ownListeners
ownListeners: EntityListenerMetadata[];Entity's own listener metadatas.
property ownRelations
ownRelations: RelationMetadata[];Entity's relation metadatas.
property ownUniques
ownUniques: UniqueMetadata[];Entity's own uniques.
property parentClosureEntityMetadata
parentClosureEntityMetadata: EntityMetadata;If this is entity metadata for a junction closure table then its owner closure table metadata will be set here.
property parentEntityMetadata
parentEntityMetadata: EntityMetadata;Parent's entity metadata. Used in inheritance patterns.
property primaryColumns
primaryColumns: ColumnMetadata[];Gets the primary columns.
property propertiesMap
propertiesMap: ObjectLiteral;Map of columns and relations of the entity.
example: Post{ id: number, name: string, counterEmbed: { count: number }, category: Category }. This method will create following object: { id: "id", counterEmbed: { count: "counterEmbed.count" }, category: "category" }
property relationIds
relationIds: RelationIdMetadata[];Entity's relation id metadatas.
property relations
relations: RelationMetadata[];Relations of the entity, including relations that are coming from the embeddeds of this entity.
property relationsWithJoinColumns
relationsWithJoinColumns: RelationMetadata[];Gets only owner one-to-one and many-to-one relations.
property schema
schema?: string;Schema name. Used in Postgres and Sql Server.
property synchronize
synchronize: boolean;Indicates if schema will be synchronized for this entity or not.
property tableMetadataArgs
tableMetadataArgs: TableMetadataArgs;Metadata arguments used to build this entity metadata.
property tableName
tableName: string;Entity table name in the database. This is final table name of the entity. This name already passed naming strategy, and generated based on multiple criteria, including user table name and global table prefix.
property tableNameWithoutPrefix
tableNameWithoutPrefix: string;Gets the table name without global table prefix. When querying table you need a table name with prefix, but in some scenarios, for example when you want to name a junction table that contains names of two other tables, you may want a table name without prefix.
property tablePath
tablePath: string;Entity table path. Contains database name, schema name and table name. E.g. myDB.mySchema.myTable
property tableType
tableType: TableType;Table type. Tables can be closure, junction, etc.
property target
target: string | Function;Target class to which this entity metadata is bind. Note, that when using table inheritance patterns target can be different rather then table's target. For virtual tables which lack of real entity (like junction tables) target is equal to their table name.
property targetName
targetName: string;Gets the name of the target.
property treeChildrenRelation
treeChildrenRelation?: RelationMetadata;Tree children relation. Used only in tree-tables.
property treeLevelColumn
treeLevelColumn?: ColumnMetadata;Special column that stores tree level in tree entities.
property treeOptions
treeOptions?: ClosureTreeOptions;Indicates if this entity is a tree, what options of tree it has.
property treeParentRelation
treeParentRelation?: RelationMetadata;Tree parent relation. Used only in tree-tables.
property treeType
treeType?: TreeType;Indicates if this entity is a tree, what type of tree it is.
property uniques
uniques: UniqueMetadata[];Entity's unique metadatas.
property updateDateColumn
updateDateColumn?: ColumnMetadata;Gets entity column which contains an update date value.
property versionColumn
versionColumn?: ColumnMetadata;Gets entity column which contains an entity version.
property withoutRowid
withoutRowid?: boolean;Enables Sqlite "WITHOUT ROWID" modifier for the "CREATE TABLE" statement
method build
build: () => void;method compareEntities
compareEntities: ( firstEntity: ObjectLiteral, secondEntity: ObjectLiteral) => boolean;Compares two different entities by their ids. Returns true if they match, false otherwise.
Parameter firstEntity
Parameter secondEntity
method create
create: ( queryRunner?: QueryRunner, options?: { fromDeserializer?: boolean; pojo?: boolean }) => any;Creates a new entity.
Parameter queryRunner
Parameter options
Parameter
options.fromDeserializer
Parameter
options.pojo
method createPropertiesMap
createPropertiesMap: () => { [name: string]: any };Creates a special object - all columns and relations of the object (plus columns and relations from embeds) in a special format - { propertyName: propertyName }.
example: Post{ id: number, name: string, counterEmbed: { count: number }, category: Category }. This method will create following object: { id: "id", counterEmbed: { count: "counterEmbed.count" }, category: "category" }
method difference
static difference: ( firstIdMaps: ObjectLiteral[], secondIdMaps: ObjectLiteral[]) => ObjectLiteral[];Finds difference between two entity id maps. Returns items that exist in the first array and absent in the second array.
Parameter firstIdMaps
Parameter secondIdMaps
method ensureEntityIdMap
ensureEntityIdMap: (id: any) => ObjectLiteral;Ensures that given object is an entity id map. If given id is an object then it means its already id map. If given id isn't an object then it means its a value of the id column and it creates a new id map with this value and name of the primary column.
Parameter id
method extractRelationValuesFromEntity
extractRelationValuesFromEntity: ( entity: ObjectLiteral, relations: RelationMetadata[]) => [RelationMetadata, any, EntityMetadata][];Iterates through entity and finds and extracts all values from relations in the entity. If relation value is an array its being flattened.
Parameter entity
Parameter relations
method findColumnsWithPropertyPath
findColumnsWithPropertyPath: (propertyPath: string) => ColumnMetadata[];Finds columns with a given property path. Property path can match a relation, and relations can contain multiple columns.
Parameter propertyPath
method findColumnWithDatabaseName
findColumnWithDatabaseName: (databaseName: string) => ColumnMetadata | undefined;Finds column with a given database name.
Parameter databaseName
method findColumnWithPropertyName
findColumnWithPropertyName: (propertyName: string) => ColumnMetadata | undefined;Finds column with a given property name.
Parameter propertyName
method findColumnWithPropertyPath
findColumnWithPropertyPath: (propertyPath: string) => ColumnMetadata | undefined;Finds column with a given property path.
Parameter propertyPath
method findColumnWithPropertyPathStrict
findColumnWithPropertyPathStrict: ( propertyPath: string) => ColumnMetadata | undefined;Finds column with a given property path. Does not search in relation unlike findColumnWithPropertyPath.
Parameter propertyPath
method findEmbeddedWithPropertyPath
findEmbeddedWithPropertyPath: ( propertyPath: string) => EmbeddedMetadata | undefined;Finds embedded with a given property path.
Parameter propertyPath
method findInheritanceMetadata
findInheritanceMetadata: (value: any) => EntityMetadata;In the case of SingleTableInheritance, find the correct metadata for a given value.
Parameter value
The value to find the metadata for.
Returns
The found metadata for the entity or the base metadata if no matching metadata was found in the whole inheritance tree.
method findRelationWithPropertyPath
findRelationWithPropertyPath: ( propertyPath: string) => RelationMetadata | undefined;Finds relation with the given property path.
Parameter propertyPath
method getEntityIdMap
getEntityIdMap: (entity: ObjectLiteral | undefined) => ObjectLiteral | undefined;Gets primary keys of the entity and returns them in a literal object. For example, for Post{ id: 1, title: "hello" } where id is primary it will return { id: 1 } For multiple primary keys it returns multiple keys in object. For primary keys inside embeds it returns complex object literal with keys in them.
Parameter entity
method getEntityIdMixedMap
getEntityIdMixedMap: ( entity: ObjectLiteral | undefined) => ObjectLiteral | undefined;Creates a "mixed id map". If entity has multiple primary keys (ids) then it will return just regular id map, like what getEntityIdMap returns. But if entity has a single primary key then it will return just value of the id column of the entity, just value. This is called mixed id map.
Parameter entity
method getInsertionReturningColumns
getInsertionReturningColumns: () => ColumnMetadata[];Checks if entity has any column which rely on returning data, e.g. columns with auto generated value, DEFAULT values considered as dependant of returning data. For example, if we need to have RETURNING after INSERT (or we need returned id for DBs not supporting RETURNING), it means we cannot execute bulk inserts in some cases.
method getValueMap
static getValueMap: ( entity: ObjectLiteral, columns: ColumnMetadata[]) => ObjectLiteral | undefined;Creates value map from the given values and columns. Examples of usages are primary columns map and join columns map.
Parameter entity
Parameter columns
method hasAllPrimaryKeys
hasAllPrimaryKeys: (entity: ObjectLiteral) => boolean;Checks if given entity / object contains ALL primary keys entity must have. Returns true if it contains all of them, false if at least one of them is not defined.
Parameter entity
method hasColumnWithPropertyPath
hasColumnWithPropertyPath: (propertyPath: string) => boolean;Checks if there is a column or relationship with a given property path.
Parameter propertyPath
method hasEmbeddedWithPropertyPath
hasEmbeddedWithPropertyPath: (propertyPath: string) => boolean;Checks if there is an embedded with a given property path.
Parameter propertyPath
method hasId
hasId: (entity: ObjectLiteral) => boolean;Checks if given entity has an id.
Parameter entity
method hasRelationWithPropertyPath
hasRelationWithPropertyPath: (propertyPath: string) => boolean;Checks if there is a relation with the given property path.
Parameter propertyPath
method mapPropertyPathsToColumns
mapPropertyPathsToColumns: (propertyPaths: string[]) => ColumnMetadata[];Returns an array of databaseNames mapped from provided propertyPaths
Parameter propertyPaths
method registerColumn
registerColumn: (column: ColumnMetadata) => void;Registers a new column in the entity and recomputes all depend properties.
Parameter column
class EntityMetadataNotFoundError
class EntityMetadataNotFoundError extends TypeORMError {}constructor
constructor(target: EntityTarget<any>);class EntityNotFoundError
class EntityNotFoundError extends TypeORMError {}Thrown when no result could be found in methods which are not allowed to return undefined or an empty set.
constructor
constructor(entityClass: EntityTarget<any>, criteria: any);property criteria
readonly criteria: any;property entityClass
readonly entityClass: EntityTarget<any>;class EntityPropertyNotFoundError
class EntityPropertyNotFoundError extends TypeORMError {}Thrown when specified entity property was not found.
constructor
constructor(propertyPath: string, metadata: EntityMetadata);class EntitySchema
class EntitySchema<T = any> {}Interface for entity metadata mappings stored inside "schemas" instead of models decorated by decorators.
constructor
constructor(options: EntitySchemaOptions<T>);property "@instanceof"
readonly '@instanceof': Symbol;property options
options: EntitySchemaOptions<T>;class EntitySchemaEmbeddedColumnOptions
class EntitySchemaEmbeddedColumnOptions {}property array
array?: boolean;Indicates if this embedded is in array mode.
This option works only in mongodb.
property prefix
prefix?: string | boolean;Embedded column prefix. If set to empty string or false, then prefix is not set at all.
property schema
schema: EntitySchema<any>;Schema of embedded entity
class EntitySchemaOptions
class EntitySchemaOptions<T> {}Interface for entity metadata mappings stored inside "schemas" instead of models decorated by decorators.
property checks
checks?: EntitySchemaCheckOptions[];Entity check options.
property columns
columns: { [P in keyof T]?: EntitySchemaColumnOptions };Entity column's options.
property database
database?: string;Database name. Used in MySql and Sql Server.
property discriminatorValue
discriminatorValue?: string;Custom discriminator value for Single Table Inheritance.
property embeddeds
embeddeds?: { [P in keyof Partial<T>]: EntitySchemaEmbeddedColumnOptions };Embedded Entities options
property exclusions
exclusions?: EntitySchemaExclusionOptions[];Entity exclusion options.
property expression
expression?: string | ((dataSource: DataSource) => SelectQueryBuilder<any>);View expression.
property foreignKeys
foreignKeys?: EntitySchemaForeignKeyOptions[];Entity foreign keys options.
property indices
indices?: EntitySchemaIndexOptions[];Entity indices options.
property inheritance
inheritance?: EntitySchemaInheritanceOptions;Inheritance options.
property name
name: string;Entity name.
property orderBy
orderBy?: OrderByCondition;Specifies a property name by which queries will perform ordering by default when fetching rows.
property relationIds
relationIds?: { [P in keyof T]?: EntitySchemaRelationIdOptions };Entity relation id options.
property relations
relations?: { [P in keyof T]?: EntitySchemaRelationOptions };Entity relation's options.
property schema
schema?: string;Schema name. Used in Postgres and Sql Server.
property synchronize
synchronize?: boolean;Indicates if schema synchronization is enabled or disabled for this entity. If it will be set to false then schema sync will and migrations ignore this entity. By default schema synchronization is enabled for all entities.
property tableName
tableName?: string;Table name.
property target
target?: Function;Target bind to this entity schema. Optional.
property trees
trees?: Omit<TreeMetadataArgs, 'target'>[];property type
type?: TableType;Table type.
property uniques
uniques?: EntitySchemaUniqueOptions[];Entity uniques options.
property withoutRowid
withoutRowid?: boolean;If set to 'true' this option disables Sqlite's default behaviour of secretly creating an integer primary key column named 'rowid' on table creation.
See Also
https://www.sqlite.org/withoutrowid.html.
class EqualOperator
class EqualOperator<T> extends FindOperator<T> {}constructor
constructor(value: T | FindOperator<T>);property "@instanceof"
readonly '@instanceof': Symbol;class FileLogger
class FileLogger extends AbstractLogger {}Performs logging of the events in TypeORM. This version of logger logs everything into ormlogs.log file.
constructor
constructor(options?: LoggerOptions, fileLoggerOptions?: FileLoggerOptions);method write
protected write: (strings: string | string[]) => void;Writes given strings into the log file.
Parameter strings
method writeLog
protected writeLog: ( level: LogLevel, logMessage: LogMessage | LogMessage[], queryRunner?: QueryRunner) => void;Write log to specific output.
Parameter level
Parameter logMessage
Parameter queryRunner
class FindOperator
class FindOperator<T> {}Find Operator used in Find Conditions.
constructor
constructor( type: FindOperatorType, value: FindOperator<T> | T, useParameter?: boolean, multipleParameters?: boolean, getSql?: SqlGeneratorType, objectLiteralParameters?: ObjectLiteral);property "@instanceof"
readonly '@instanceof': Symbol;property child
readonly child: FindOperator<T>;Gets the child FindOperator if it exists
property getSql
readonly getSql: SqlGeneratorType;Gets the SQL generator
property multipleParameters
readonly multipleParameters: boolean;Indicates if multiple parameters must be used for this operator. Extracts final value if value is another find operator.
property objectLiteralParameters
readonly objectLiteralParameters: ObjectLiteral;Gets ObjectLiteral parameters.
property type
readonly type: FindOperatorType;Gets the Type of this FindOperator
property useParameter
readonly useParameter: boolean;Indicates if parameter is used or not for this operator. Extracts final value if value is another find operator.
property value
readonly value: {};Gets the final value needs to be used as parameter value.
method transformValue
transformValue: (transformer: ValueTransformer | ValueTransformer[]) => void;class FindOptionsUtils
class FindOptionsUtils {}Utilities to work with FindOptions.
method applyOptionsToTreeQueryBuilder
static applyOptionsToTreeQueryBuilder: <T extends ObjectLiteral>( qb: SelectQueryBuilder<T>, options?: FindTreeOptions) => SelectQueryBuilder<T>;method applyRelationsRecursively
static applyRelationsRecursively: ( qb: SelectQueryBuilder<any>, allRelations: string[], alias: string, metadata: EntityMetadata, prefix: string) => void;Adds joins for all relations and sub-relations of the given relations provided in the find options.
Parameter qb
Parameter allRelations
Parameter alias
Parameter metadata
Parameter prefix
method getRelationJoinType
static getRelationJoinType: ( relation: RelationMetadata, withDeleted: boolean, parentJoinType?: 'inner' | 'left') => 'inner' | 'left';Determines the join type for a relation based on nullability, join column ownership, and soft-delete configuration.
Uses INNER JOIN only when: - The relation is non-nullable (nullable=false) - The relation owns the join column (ManyToOne or OneToOne owner) - The target entity has no soft-delete column, or withDeleted is enabled
Parameter relation
Parameter withDeleted
Parameter parentJoinType
method isFindManyOptions
static isFindManyOptions: <Entity = any>( obj: any) => obj is FindManyOptions<Entity>;Checks if given object is really instance of FindManyOptions interface.
Parameter obj
method isFindOneOptions
static isFindOneOptions: <Entity = any>( obj: any) => obj is FindOneOptions<Entity>;Checks if given object is really instance of FindOneOptions interface.
Parameter obj
method joinEagerRelations
static joinEagerRelations: ( qb: SelectQueryBuilder<any>, alias: string, metadata: EntityMetadata, parentJoinType?: 'inner' | 'left') => void;method rejectJoinOption
static rejectJoinOption: (options: unknown) => void;Throws if the removed
joinoption is present on a find-options object. This catches untyped/JS callers still passingjoinafter its removal in v1.0.Parameter options
method rejectStringArrayRelations
static rejectStringArrayRelations: (options: unknown) => void;Throws if the removed string-array
relationssyntax is used. This catches untyped/JS callers still passingrelations: ["rel"]after its removal in v1.0.Parameter options
method rejectStringArraySelect
static rejectStringArraySelect: (options: unknown) => void;Throws if the removed string-array
selectsyntax is used. This catches untyped/JS callers still passingselect: ["col"]after its removal in v1.0.Parameter options
class FindRelationsNotFoundError
class FindRelationsNotFoundError extends TypeORMError {}Thrown when relations specified in the find options were not found in the entities.
constructor
constructor(notFoundRelations: string[]);class ForbiddenTransactionModeOverrideError
class ForbiddenTransactionModeOverrideError extends TypeORMError {}Thrown when the per-migration transaction mode is overriden but the global transaction mode is set to "all".
constructor
constructor(migrationsOverridingTransactionMode: Migration[]);class FormattedConsoleLogger
class FormattedConsoleLogger extends AbstractLogger {}Performs logging of the events in TypeORM. This version of logger uses console to log events, syntax highlighting and formatting.
method writeLog
protected writeLog: ( level: LogLevel, logMessage: LogMessage | LogMessage[], queryRunner?: QueryRunner) => void;Write log to specific output.
Parameter level
Parameter logMessage
Parameter queryRunner
class InitializedRelationError
class InitializedRelationError extends TypeORMError {}Thrown when relation has array initialized which is forbidden my ORM.
See Also
https://github.com/typeorm/typeorm/issues/1319
http://typeorm.io/docs/Relations/relations-faq/#avoid-relation-property-initializers
constructor
constructor(relation: RelationMetadata);class InsertQueryBuilder
class InsertQueryBuilder< Entity extends ObjectLiteral> extends QueryBuilder<Entity> {}Allows to build complex sql queries in a fashion way and execute those queries.
property "@instanceof"
readonly '@instanceof': Symbol;method createColumnNamesExpression
protected createColumnNamesExpression: () => string;Creates a columns string where values must be inserted to for INSERT INTO expression.
method createColumnValueExpression
protected createColumnValueExpression: ( valueSets: ObjectLiteral[], valueSetIndex: number, column: ColumnMetadata) => string;method createInsertExpression
protected createInsertExpression: () => string;Creates INSERT express used to perform insert query.
method createMergeExpression
protected createMergeExpression: () => string;Creates MERGE express used to perform insert query.
method createMergeIntoInsertValuesExpression
protected createMergeIntoInsertValuesExpression: ( mergeSourceAlias: string) => string;Creates list of values needs to be inserted in the VALUES expression.
Parameter mergeSourceAlias
method createMergeIntoSourceExpression
protected createMergeIntoSourceExpression: (mergeSourceAlias: string) => string;Creates list of values needs to be inserted in the VALUES expression.
Parameter mergeSourceAlias
method createUpsertConditionExpression
protected createUpsertConditionExpression: (mainTableOrAlias: string) => string;Create upsert search condition expression.
Parameter mainTableOrAlias
method createValuesExpression
protected createValuesExpression: () => string;Creates list of values needs to be inserted in the VALUES expression.
method execute
execute: () => Promise<InsertResult>;Executes sql generated by query builder and returns raw database results.
method getInsertedColumns
protected getInsertedColumns: () => ColumnMetadata[];Gets list of columns where values must be inserted to.
method getQuery
getQuery: () => string;Gets generated SQL query without parameters being replaced.
method getValueSets
protected getValueSets: () => ObjectLiteral[];Gets array of values need to be inserted into the target table.
method into
into: <T extends ObjectLiteral>( entityTarget: EntityTarget<T>, columns?: string[]) => InsertQueryBuilder<T>;Specifies INTO which entity's table insertion will be executed.
Parameter entityTarget
Parameter columns
method isOverridingAutoIncrementBehavior
protected isOverridingAutoIncrementBehavior: (column: ColumnMetadata) => boolean;Checks if column is an auto-generated primary key, but the current insertion specifies a value for it.
Parameter column
method orIgnore
orIgnore: (statement?: string | boolean) => this;Adds additional ignore statement supported in databases.
Parameter statement
method orUpdate
orUpdate: ( overwrite: string[], conflictTarget?: string | string[], orUpdateOptions?: InsertOrUpdateOptions) => this;Adds an "upsert" clause to the insert query — when a row with the same conflict target already exists the listed columns are updated instead.
Parameter overwrite
Column names to overwrite on conflict.
Parameter conflictTarget
Column name(s) or constraint name used to detect conflicts. When an array is given the columns form a composite key; when a string is given it is treated as a constraint name.
Parameter orUpdateOptions
Additional options such as
skipUpdateIfNoValuesChanged,indexPredicate,upsertType, oroverwriteCondition.
method output
output: { (columns: string[]): this; (output: string): this; (output: string | string[]): this;};Optional returning/output clause. This will return given column values.
Optional returning/output clause. Returning is a SQL string containing returning statement.
Optional returning/output clause.
method returning
returning: { (columns: string[]): this; (returning: string): this; (returning: string | string[]): this;};Optional returning/output clause. This will return given column values.
Optional returning/output clause. Returning is a SQL string containing returning statement.
Optional returning/output clause.
method updateEntity
updateEntity: (enabled: boolean) => this;Indicates if entity must be updated after insertion operations. This may produce extra query or use RETURNING / OUTPUT statement (depend on database). Enabled by default.
Parameter enabled
method values
values: ( values: QueryDeepPartialEntity<Entity> | QueryDeepPartialEntity<Entity>[]) => this;Values needs to be inserted into table.
Parameter values
method valuesFromSelect
valuesFromSelect: { (queryBuilder: SelectQueryBuilder<any>): this; ( subQueryFactory: (qb: SelectQueryBuilder<any>) => SelectQueryBuilder<any> ): this;};Specifies a SELECT query to use as the source of values for the INSERT. This creates an INSERT INTO ... SELECT FROM statement.
class InsertResult
class InsertResult {}Result object returned by InsertQueryBuilder execution.
property generatedMaps
generatedMaps: ObjectLiteral[];Generated values returned by a database. Has entity-like structure (not just column database name and values).
property identifiers
identifiers: ObjectLiteral[];Contains inserted entity id. Has entity-like structure (not just column database name and values).
property raw
raw: any;Raw SQL result returned by executed query.
method from
static from: (queryResult: QueryResult) => InsertResult;class InsertValuesMissingError
class InsertValuesMissingError extends TypeORMError {}Thrown when user tries to insert using QueryBuilder but do not specify what to insert.
constructor
constructor();class InstanceChecker
class InstanceChecker {}method isBaseEntityConstructor
static isBaseEntityConstructor: (obj: unknown) => obj is typeof BaseEntity;method isBrackets
static isBrackets: (obj: unknown) => obj is Brackets;method isColumnMetadata
static isColumnMetadata: (obj: unknown) => obj is ColumnMetadata;method isDataSource
static isDataSource: (obj: unknown) => obj is DataSource;method isDeleteQueryBuilder
static isDeleteQueryBuilder: (obj: unknown) => obj is DeleteQueryBuilder<any>;method isEntityMetadata
static isEntityMetadata: (obj: unknown) => obj is EntityMetadata;method isEntitySchema
static isEntitySchema: (obj: unknown) => obj is EntitySchema<any>;method isEqualOperator
static isEqualOperator: (obj: unknown) => obj is EqualOperator<any>;method isFindOperator
static isFindOperator: (obj: unknown) => obj is FindOperator<any>;method isInsertQueryBuilder
static isInsertQueryBuilder: (obj: unknown) => obj is InsertQueryBuilder<any>;method isMongoEntityManager
static isMongoEntityManager: (obj: unknown) => obj is MongoEntityManager;method isMssqlParameter
static isMssqlParameter: (obj: unknown) => obj is MssqlParameter;method isNotBrackets
static isNotBrackets: (obj: unknown) => obj is NotBrackets;method isQuery
static isQuery: (obj: unknown) => obj is Query;method isRdbmsSchemaBuilder
static isRdbmsSchemaBuilder: (obj: unknown) => obj is RdbmsSchemaBuilder;method isRelationQueryBuilder
static isRelationQueryBuilder: ( obj: unknown) => obj is RelationQueryBuilder<any>;method isSelectQueryBuilder
static isSelectQueryBuilder: (obj: unknown) => obj is SelectQueryBuilder<any>;method isSoftDeleteQueryBuilder
static isSoftDeleteQueryBuilder: ( obj: unknown) => obj is SoftDeleteQueryBuilder<any>;method isSqljsEntityManager
static isSqljsEntityManager: (obj: unknown) => obj is SqljsEntityManager;method isSubject
static isSubject: (obj: unknown) => obj is Subject;method isTable
static isTable: (obj: unknown) => obj is Table;method isTableCheck
static isTableCheck: (obj: unknown) => obj is TableCheck;method isTableColumn
static isTableColumn: (obj: unknown) => obj is TableColumn;method isTableExclusion
static isTableExclusion: (obj: unknown) => obj is TableExclusion;method isTableForeignKey
static isTableForeignKey: (obj: unknown) => obj is TableForeignKey;method isTableIndex
static isTableIndex: (obj: unknown) => obj is TableIndex;method isTableUnique
static isTableUnique: (obj: unknown) => obj is TableUnique;method isUpdateQueryBuilder
static isUpdateQueryBuilder: (obj: unknown) => obj is UpdateQueryBuilder<any>;method isView
static isView: (obj: unknown) => obj is View;class LimitOnUpdateNotSupportedError
class LimitOnUpdateNotSupportedError extends TypeORMError {}Thrown when user tries to build an UPDATE query with LIMIT but the database does not support it.
constructor
constructor();class LockNotSupportedOnGivenDriverError
class LockNotSupportedOnGivenDriverError extends TypeORMError {}Thrown when selected sql driver does not supports locking.
constructor
constructor();class MetadataAlreadyExistsError
class MetadataAlreadyExistsError extends TypeORMError {}constructor
constructor(metadataType: string, constructor: Function, propertyName?: string);class MetadataWithSuchNameAlreadyExistsError
class MetadataWithSuchNameAlreadyExistsError extends TypeORMError {}constructor
constructor(metadataType: string, name: string);class Migration
class Migration {}Represents entity of the migration in the database.
constructor
constructor( id: number, timestamp: number, name: string, instance?: MigrationInterface, transaction?: boolean);property id
id: number;Migration id. Indicates order of the executed migrations.
property instance
instance?: MigrationInterface;Migration instance that needs to be run.
property name
name: string;Name of the migration (class name).
property timestamp
timestamp: number;Timestamp of the migration.
property transaction
transaction?: boolean;Whether to run this migration within a transaction
class MigrationExecutor
class MigrationExecutor {}Executes migrations: runs pending and reverts previously executed migrations.
constructor
constructor(dataSource: DataSource, queryRunner?: QueryRunner);property dataSource
protected dataSource: DataSource;property fake
fake: boolean;Option to fake-run or fake-revert a migration, adding to the executed migrations table, but not actually running it. This feature is useful for when migrations are added after the fact or for interoperability between applications which are desired to each keep a consistent migration history.
property queryRunner
protected queryRunner?: QueryRunner;property transaction
transaction: 'none' | 'all' | 'each';Indicates how migrations should be run in transactions. all: all migrations are run in a single transaction none: all migrations are run without a transaction each: each migration is run in a separate transaction
method checkForDuplicateMigrations
protected checkForDuplicateMigrations: (migrations: Migration[]) => void;method createMigrationsTableIfNotExist
protected createMigrationsTableIfNotExist: ( queryRunner: QueryRunner) => Promise<void>;Creates table "migrations" that will store information about executed migrations.
Parameter queryRunner
method deleteExecutedMigration
protected deleteExecutedMigration: ( queryRunner: QueryRunner, migration: Migration) => Promise<void>;Delete previously executed migration's data from the migrations table.
Parameter queryRunner
Parameter migration
method deleteMigration
deleteMigration: (migration: Migration) => Promise<void>;Deletes an executed migration.
Parameter migration
method executeMigration
executeMigration: (migration: Migration) => Promise<Migration>;Tries to execute a single migration given.
Parameter migration
method executePendingMigrations
executePendingMigrations: () => Promise<Migration[]>;Executes all pending migrations. Pending migrations are migrations that are not yet executed, thus not saved in the database.
method getExecutedMigrations
getExecutedMigrations: () => Promise<Migration[]>;Returns
An array of all executed migrations
method getLatestExecutedMigration
protected getLatestExecutedMigration: ( sortedMigrations: Migration[]) => Migration | undefined;Finds the latest migration in the given array of migrations. PRE: Migration array must be sorted by descending id.
Parameter sortedMigrations
method getLatestTimestampMigration
protected getLatestTimestampMigration: ( migrations: Migration[]) => Migration | undefined;Finds the latest migration (sorts by timestamp) in the given array of migrations.
Parameter migrations
method getMigrations
protected getMigrations: () => Migration[];Gets all migrations that setup for this connection.
method getPendingMigrations
getPendingMigrations: () => Promise<Migration[]>;Returns an array of all pending migrations.
method insertExecutedMigration
protected insertExecutedMigration: ( queryRunner: QueryRunner, migration: Migration) => Promise<void>;Inserts new executed migration's data into migrations table.
Parameter queryRunner
Parameter migration
method insertMigration
insertMigration: (migration: Migration) => Promise<void>;Inserts an executed migration.
Parameter migration
method loadExecutedMigrations
protected loadExecutedMigrations: ( queryRunner: QueryRunner) => Promise<Migration[]>;Loads all migrations that were executed and saved into the database (sorts by id).
Parameter queryRunner
method showMigrations
showMigrations: () => Promise<boolean>;Lists all migrations and whether they have been executed or not returns true if there are unapplied migrations
method undoLastMigration
undoLastMigration: () => Promise<void>;Reverts last migration that were run.
method withQueryRunner
protected withQueryRunner: <T extends unknown>( callback: (queryRunner: QueryRunner) => T | Promise<T>) => Promise<T>;class MissingDeleteDateColumnError
class MissingDeleteDateColumnError extends TypeORMError {}constructor
constructor(entityMetadata: EntityMetadata);class MissingDriverError
class MissingDriverError extends TypeORMError {}Thrown when consumer specifies driver type that does not exist or supported.
constructor
constructor(driverType: string, availableDrivers?: string[]);class MissingJoinColumnError
class MissingJoinColumnError extends TypeORMError {}constructor
constructor(entityMetadata: EntityMetadata, relation: RelationMetadata);class MissingJoinTableError
class MissingJoinTableError extends TypeORMError {}constructor
constructor(entityMetadata: EntityMetadata, relation: RelationMetadata);class MissingPrimaryColumnError
class MissingPrimaryColumnError extends TypeORMError {}constructor
constructor(entityMetadata: EntityMetadata);class MongoEntityManager
class MongoEntityManager extends EntityManager {}Entity manager supposed to work with any entity, automatically find its repository and call its methods, whatever entity type are you passing.
This implementation is used for MongoDB driver which has some specifics in its EntityManager.
constructor
constructor(dataSource: DataSource);property "@instanceof"
readonly '@instanceof': Symbol;property mongoQueryRunner
readonly mongoQueryRunner: MongoQueryRunner;method aggregate
aggregate: <Entity, R = any>( entityClassOrName: EntityTarget<Entity>, pipeline: Document[], options?: AggregateOptions) => AggregationCursor<R>;Execute an aggregation framework pipeline against the collection.
Parameter entityClassOrName
Parameter pipeline
Parameter options
method aggregateEntity
aggregateEntity: <Entity>( entityClassOrName: EntityTarget<Entity>, pipeline: Document[], options?: AggregateOptions) => AggregationCursor<Entity>;Execute an aggregation framework pipeline against the collection. This returns modified version of cursor that transforms each result into Entity model.
Parameter entityClassOrName
Parameter pipeline
Parameter options
method applyEntityTransformationToCursor
protected applyEntityTransformationToCursor: <Entity extends ObjectLiteral>( metadata: EntityMetadata, cursor: FindCursor<Entity> | AggregationCursor<Entity>) => void;Overrides cursor's toArray and next methods to convert results to entity automatically.
Parameter metadata
Parameter cursor
method bulkWrite
bulkWrite: <Entity>( entityClassOrName: EntityTarget<Entity>, operations: AnyBulkWriteOperation<Document>[], options?: BulkWriteOptions) => Promise<BulkWriteResult>;Perform a bulkWrite operation without a fluent API.
Parameter entityClassOrName
Parameter operations
Parameter options
method collectionIndexes
collectionIndexes: <Entity>( entityClassOrName: EntityTarget<Entity>) => Promise<Document>;Retrieve all the indexes on the collection.
Parameter entityClassOrName
method collectionIndexExists
collectionIndexExists: <Entity>( entityClassOrName: EntityTarget<Entity>, indexes: string | string[]) => Promise<boolean>;Retrieve all the indexes on the collection.
Parameter entityClassOrName
Parameter indexes
method collectionIndexInformation
collectionIndexInformation: <Entity>( entityClassOrName: EntityTarget<Entity>, options?: IndexInformationOptions) => Promise<any>;Retrieves this collections index info.
Parameter entityClassOrName
Parameter options
method convertFindManyOptionsOrConditionsToMongodbQuery
protected convertFindManyOptionsOrConditionsToMongodbQuery: <Entity>( optionsOrConditions: | MongoFindManyOptions<Entity> | Partial<Entity> | FilterOperators<Entity> | any[] | undefined) => ObjectLiteral | undefined;Converts FindManyOptions to mongodb query.
Parameter optionsOrConditions
method convertFindOneOptionsOrConditionsToMongodbQuery
protected convertFindOneOptionsOrConditionsToMongodbQuery: <Entity>( optionsOrConditions: | MongoFindOneOptions<Entity> | Partial<Entity> | undefined) => ObjectLiteral | undefined;Converts FindOneOptions to mongodb query.
Parameter optionsOrConditions
method convertFindOptionsOrderToOrderCriteria
protected convertFindOptionsOrderToOrderCriteria: ( order: ObjectLiteral) => ObjectLiteral;Converts FindOptions into mongodb order by criteria.
Parameter order
method convertFindOptionsSelectToProjectCriteria
protected convertFindOptionsSelectToProjectCriteria: ( selects: FindOptionsSelect<any>, metadata: EntityMetadata) => ObjectLiteral;Converts FindOptions into mongodb select by criteria.
Parameter selects
Parameter metadata
method convertMixedCriteria
protected convertMixedCriteria: ( metadata: EntityMetadata, idMap: any) => ObjectLiteral;Ensures given id is an id for query.
Parameter metadata
Parameter idMap
method count
count: <Entity>( entityClassOrName: EntityTarget<Entity>, query?: Filter<Document>, options?: CountOptions) => Promise<number>;Count number of matching documents in the db to a query.
Parameter entityClassOrName
Parameter query
Parameter options
method countBy
countBy: <Entity>( entityClassOrName: EntityTarget<Entity>, query?: ObjectLiteral, options?: CountOptions) => Promise<number>;Count number of matching documents in the db to a query.
Parameter entityClassOrName
Parameter query
Parameter options
method countDocuments
countDocuments: <Entity>( entityClassOrName: EntityTarget<Entity>, query?: Filter<Document>, options?: CountDocumentsOptions) => Promise<number>;Count number of matching documents in the db to a query.
Parameter entityClassOrName
Parameter query
Parameter options
method createCollectionIndex
createCollectionIndex: <Entity>( entityClassOrName: EntityTarget<Entity>, fieldOrSpec: IndexSpecification, options?: CreateIndexesOptions) => Promise<string>;Creates an index on the db and collection.
Parameter entityClassOrName
Parameter fieldOrSpec
Parameter options
method createCollectionIndexes
createCollectionIndexes: <Entity>( entityClassOrName: EntityTarget<Entity>, indexSpecs: IndexDescription[]) => Promise<string[]>;Creates multiple indexes in the collection, this method is only supported for MongoDB 2.6 or higher. Earlier version of MongoDB will throw a command not supported error. Index specifications are defined at http://docs.mongodb.org/manual/reference/command/createIndexes/.
Parameter entityClassOrName
Parameter indexSpecs
method createCursor
createCursor: <Entity, T = any>( entityClassOrName: EntityTarget<Entity>, query?: ObjectLiteral) => FindCursor<T>;Creates a cursor for a query that can be used to iterate over results from MongoDB.
Parameter entityClassOrName
Parameter query
method createEntityCursor
createEntityCursor: <Entity>( entityClassOrName: EntityTarget<Entity>, query?: ObjectLiteral) => FindCursor<Entity>;Creates a cursor for a query that can be used to iterate over results from MongoDB. This returns modified version of cursor that transforms each result into Entity model.
Parameter entityClassOrName
Parameter query
method delete
delete: <Entity>( target: EntityTarget<Entity>, criteria: | string | string[] | number | number[] | Date | Date[] | ObjectId | ObjectId[] | ObjectLiteral[]) => Promise<DeleteResult>;Deletes entities by a given conditions. Unlike save method executes a primitive operation without cascades, relations and other operations included. Executes fast and efficient DELETE query. Does not check if entity exist in the database.
Parameter target
Parameter criteria
method deleteMany
deleteMany: <Entity>( entityClassOrName: EntityTarget<Entity>, query: Filter<Document>, options?: DeleteOptions) => Promise<DeleteResultMongoDb>;Delete multiple documents on MongoDB.
Parameter entityClassOrName
Parameter query
Parameter options
method deleteOne
deleteOne: <Entity>( entityClassOrName: EntityTarget<Entity>, query: Filter<Document>, options?: DeleteOptions) => Promise<DeleteResultMongoDb>;Delete a document on MongoDB.
Parameter entityClassOrName
Parameter query
Parameter options
method distinct
distinct: <Entity>( entityClassOrName: EntityTarget<Entity>, key: string, query: Filter<Document>, options?: CommandOperationOptions) => Promise<any>;The distinct command returns returns a list of distinct values for the given key across a collection.
Parameter entityClassOrName
Parameter key
Parameter query
Parameter options
method dropCollectionIndex
dropCollectionIndex: <Entity>( entityClassOrName: EntityTarget<Entity>, indexName: string, options?: CommandOperationOptions) => Promise<any>;Drops an index from this collection.
Parameter entityClassOrName
Parameter indexName
Parameter options
method dropCollectionIndexes
dropCollectionIndexes: <Entity>( entityClassOrName: EntityTarget<Entity>) => Promise<any>;Drops all indexes from the collection.
Parameter entityClassOrName
method executeFind
protected executeFind: <Entity>( entityClassOrName: EntityTarget<Entity>, optionsOrConditions?: MongoFindManyOptions<Entity> | Partial<Entity> | any[]) => Promise<Entity[]>;method executeFindAndCount
executeFindAndCount: <Entity>( entityClassOrName: EntityTarget<Entity>, optionsOrConditions?: MongoFindManyOptions<Entity> | Partial<Entity>) => Promise<[Entity[], number]>;Finds entities that match given find options or conditions.
Parameter entityClassOrName
Parameter optionsOrConditions
method executeFindOne
protected executeFindOne: <Entity>( entityClassOrName: EntityTarget<Entity>, optionsOrConditions?: any, maybeOptions?: MongoFindOneOptions<Entity>) => Promise<Entity | null>;Finds first entity that matches given conditions and/or find options.
Parameter entityClassOrName
Parameter optionsOrConditions
Parameter maybeOptions
method filterSoftDeleted
protected filterSoftDeleted: <Entity>( cursor: FindCursor<Entity>, deleteDateColumn: ColumnMetadata, query?: ObjectLiteral) => void;method find
find: <Entity>( entityClassOrName: EntityTarget<Entity>, optionsOrConditions?: | FindManyOptions<Entity> | Partial<Entity> | FilterOperators<Entity>) => Promise<Entity[]>;Finds entities that match given find options or conditions.
Parameter entityClassOrName
Parameter optionsOrConditions
method findAndCount
findAndCount: <Entity>( entityClassOrName: EntityTarget<Entity>, options?: MongoFindManyOptions<Entity>) => Promise<[Entity[], number]>;Finds entities that match given find options or conditions. Also counts all entities that match given conditions, but ignores pagination settings (from and take options).
Parameter entityClassOrName
Parameter options
method findAndCountBy
findAndCountBy: <Entity>( entityClassOrName: EntityTarget<Entity>, where: any) => Promise<[Entity[], number]>;Finds entities that match given where conditions.
Parameter entityClassOrName
Parameter where
method findBy
findBy: <Entity>( entityClassOrName: EntityTarget<Entity>, where: any) => Promise<Entity[]>;Finds entities that match given WHERE conditions.
Parameter entityClassOrName
Parameter where
method findByIds
findByIds: <Entity>( entityClassOrName: EntityTarget<Entity>, ids: any[], optionsOrConditions?: FindManyOptions<Entity> | Partial<Entity>) => Promise<Entity[]>;Finds entities by ids. Optionally find options can be applied.
Parameter entityClassOrName
Parameter ids
Parameter optionsOrConditions
method findOne
findOne: <Entity>( entityClassOrName: EntityTarget<Entity>, options: MongoFindOneOptions<Entity>) => Promise<Entity | null>;Finds first entity that matches given conditions and/or find options.
Parameter entityClassOrName
Parameter options
method findOneAndDelete
findOneAndDelete: <Entity>( entityClassOrName: EntityTarget<Entity>, query: ObjectLiteral, options?: FindOneAndDeleteOptions) => Promise<Document | null>;Find a document and delete it in one atomic operation, requires a write lock for the duration of the operation.
Parameter entityClassOrName
Parameter query
Parameter options
method findOneAndReplace
findOneAndReplace: <Entity>( entityClassOrName: EntityTarget<Entity>, query: Filter<Document>, replacement: Document, options?: FindOneAndReplaceOptions) => Promise<Document | null>;Find a document and replace it in one atomic operation, requires a write lock for the duration of the operation.
Parameter entityClassOrName
Parameter query
Parameter replacement
Parameter options
method findOneAndUpdate
findOneAndUpdate: <Entity>( entityClassOrName: EntityTarget<Entity>, query: Filter<Document>, update: UpdateFilter<Document>, options?: FindOneAndUpdateOptions) => Promise<Document | null>;Find a document and update it in one atomic operation, requires a write lock for the duration of the operation.
Parameter entityClassOrName
Parameter query
Parameter update
Parameter options
method findOneBy
findOneBy: <Entity>( entityClassOrName: EntityTarget<Entity>, where: any) => Promise<Entity | null>;Finds first entity that matches given WHERE conditions.
Parameter entityClassOrName
Parameter where
method initializeOrderedBulkOp
initializeOrderedBulkOp: <Entity>( entityClassOrName: EntityTarget<Entity>, options?: BulkWriteOptions) => OrderedBulkOperation;Initiate an In order bulk write operation, operations will be serially executed in the order they are added, creating a new operation for each switch in types.
Parameter entityClassOrName
Parameter options
method initializeUnorderedBulkOp
initializeUnorderedBulkOp: <Entity>( entityClassOrName: EntityTarget<Entity>, options?: BulkWriteOptions) => UnorderedBulkOperation;Initiate a Out of order batch write operation. All operations will be buffered into insert/update/remove commands executed out of order.
Parameter entityClassOrName
Parameter options
method insert
insert: <Entity>( target: EntityTarget<Entity>, entity: QueryDeepPartialEntity<Entity> | QueryDeepPartialEntity<Entity>[]) => Promise<InsertResult>;Inserts a given entity into the database. Unlike save method executes a primitive operation without cascades, relations and other operations included. Executes fast and efficient INSERT query. Does not check if entity exist in the database, so query will fail if duplicate entity is being inserted. You can execute bulk inserts using this method.
Parameter target
Parameter entity
method insertMany
insertMany: <Entity>( entityClassOrName: EntityTarget<Entity>, docs: OptionalId<Document>[], options?: BulkWriteOptions) => Promise<InsertManyResult>;Inserts an array of documents into MongoDB.
Parameter entityClassOrName
Parameter docs
Parameter options
method insertOne
insertOne: <Entity>( entityClassOrName: EntityTarget<Entity>, doc: OptionalId<Document>, options?: InsertOneOptions) => Promise<InsertOneResult>;Inserts a single document into MongoDB.
Parameter entityClassOrName
Parameter doc
Parameter options
method isCapped
isCapped: <Entity>(entityClassOrName: EntityTarget<Entity>) => Promise<any>;Returns if the collection is a capped collection.
Parameter entityClassOrName
method listCollectionIndexes
listCollectionIndexes: <Entity>( entityClassOrName: EntityTarget<Entity>, options?: ListIndexesOptions) => ListIndexesCursor;Get the list of all indexes information for the collection.
Parameter entityClassOrName
Parameter options
method rename
rename: <Entity>( entityClassOrName: EntityTarget<Entity>, newName: string, options?: RenameOptions) => Promise<Collection<Document>>;Reindex all indexes on the collection Warning: reIndex is a blocking operation (indexes are rebuilt in the foreground) and will be slow for large collections.
Parameter entityClassOrName
Parameter newName
Parameter options
method replaceObjectIdProperty
protected replaceObjectIdProperty: ( metadata: EntityMetadata, query: ObjectLiteral | undefined) => ObjectLiteral | undefined;Replaces the entity's ObjectId property name (e.g. "id") with "_id" in a query object so that
findOneBy({ id: value })works as expected.Parameter metadata
Parameter query
method replaceOne
replaceOne: <Entity>( entityClassOrName: EntityTarget<Entity>, query: Filter<Document>, doc: Document, options?: ReplaceOptions) => Promise<Document | UpdateResultMongoDb>;Replace a document on MongoDB.
Parameter entityClassOrName
Parameter query
Parameter doc
Parameter options
method update
update: <Entity>( target: EntityTarget<Entity>, criteria: | string | string[] | number | number[] | Date | Date[] | ObjectId | ObjectId[] | ObjectLiteral, partialEntity: QueryDeepPartialEntity<Entity>) => Promise<UpdateResult>;Updates entity partially. Entity can be found by a given conditions. Unlike save method executes a primitive operation without cascades, relations and other operations included. Executes fast and efficient UPDATE query. Does not check if entity exist in the database.
Parameter target
Parameter criteria
Parameter partialEntity
method updateMany
updateMany: <Entity>( entityClassOrName: EntityTarget<Entity>, query: Filter<Document>, update: UpdateFilter<Document>, options?: UpdateOptions) => Promise<Document | UpdateResultMongoDb>;Update multiple documents on MongoDB.
Parameter entityClassOrName
Parameter query
Parameter update
Parameter options
method updateOne
updateOne: <Entity>( entityClassOrName: EntityTarget<Entity>, query: Filter<Document>, update: UpdateFilter<Document>, options?: UpdateOptions) => Promise<Document | UpdateResultMongoDb>;Update a single document on MongoDB.
Parameter entityClassOrName
Parameter query
Parameter update
Parameter options
method watch
watch: <Entity>( entityClassOrName: EntityTarget<Entity>, pipeline?: Document[], options?: ChangeStreamOptions) => ChangeStream;class MongoRepository
class MongoRepository<Entity extends ObjectLiteral> extends Repository<Entity> {}Repository used to manage mongodb documents of a single entity type.
property manager
readonly manager: MongoEntityManager;Entity Manager used by this repository.
method aggregate
aggregate: <R = any>( pipeline: ObjectLiteral[], options?: AggregateOptions) => AggregationCursor<R>;Execute an aggregation framework pipeline against the collection.
Parameter pipeline
Parameter options
method aggregateEntity
aggregateEntity: ( pipeline: ObjectLiteral[], options?: AggregateOptions) => AggregationCursor<Entity>;Execute an aggregation framework pipeline against the collection. This returns modified version of cursor that transforms each result into Entity model.
Parameter pipeline
Parameter options
method bulkWrite
bulkWrite: ( operations: AnyBulkWriteOperation[], options?: BulkWriteOptions) => Promise<BulkWriteResult>;Perform a bulkWrite operation without a fluent API.
Parameter operations
Parameter options
method collectionIndexes
collectionIndexes: () => Promise<any>;Retrieve all the indexes on the collection.
method collectionIndexExists
collectionIndexExists: (indexes: string | string[]) => Promise<boolean>;Retrieve all the indexes on the collection.
Parameter indexes
method collectionIndexInformation
collectionIndexInformation: (options?: { full: boolean }) => Promise<any>;Retrieves this collections index info.
Parameter options
Parameter
options.full
method count
count: (query?: ObjectLiteral, options?: CountOptions) => Promise<number>;Count number of matching documents in the db to a query.
Parameter query
Parameter options
method countBy
countBy: (query?: ObjectLiteral, options?: CountOptions) => Promise<number>;Count number of matching documents in the db to a query.
Parameter query
Parameter options
method countDocuments
countDocuments: ( query?: ObjectLiteral, options?: CountDocumentsOptions) => Promise<number>;Count number of matching documents in the db to a query.
Parameter query
Parameter options
method createCollectionIndex
createCollectionIndex: ( fieldOrSpec: string | any, options?: CreateIndexesOptions) => Promise<string>;Creates an index on the db and collection.
Parameter fieldOrSpec
Parameter options
method createCollectionIndexes
createCollectionIndexes: (indexSpecs: IndexDescription[]) => Promise<string[]>;Creates multiple indexes in the collection, this method is only supported for MongoDB 2.6 or higher. Earlier version of MongoDB will throw a command not supported error. Index specifications are defined at http://docs.mongodb.org/manual/reference/command/createIndexes/.
Parameter indexSpecs
method createCursor
createCursor: <T = any>(query?: Filter<Entity>) => FindCursor<T>;Creates a cursor for a query that can be used to iterate over results from MongoDB.
Parameter query
method createEntityCursor
createEntityCursor: (query?: Filter<Entity>) => FindCursor<Entity>;Creates a cursor for a query that can be used to iterate over results from MongoDB. This returns modified version of cursor that transforms each result into Entity model.
Parameter query
method createQueryBuilder
createQueryBuilder: ( alias: string, queryRunner?: QueryRunner) => SelectQueryBuilder<Entity>;Using Query Builder with MongoDB is not supported yet. Calling this method will return an error.
Parameter alias
Parameter queryRunner
method deleteMany
deleteMany: ( query: ObjectLiteral, options?: DeleteOptions) => Promise<DeleteResult>;Delete multiple documents on MongoDB.
Parameter query
Parameter options
method deleteOne
deleteOne: ( query: ObjectLiteral, options?: DeleteOptions) => Promise<DeleteResult>;Delete a document on MongoDB.
Parameter query
Parameter options
method distinct
distinct: ( key: string, query: ObjectLiteral, options?: CommandOperationOptions) => Promise<any>;The distinct command returns returns a list of distinct values for the given key across a collection.
Parameter key
Parameter query
Parameter options
method dropCollectionIndex
dropCollectionIndex: ( indexName: string, options?: CommandOperationOptions) => Promise<any>;Drops an index from this collection.
Parameter indexName
Parameter options
method dropCollectionIndexes
dropCollectionIndexes: () => Promise<any>;Drops all indexes from the collection.
method find
find: ( options?: FindManyOptions<Entity> | Partial<Entity> | FilterOperators<Entity>) => Promise<Entity[]>;Finds entities that match given find options or conditions.
Parameter options
method findAndCount
findAndCount: ( options?: MongoFindManyOptions<Entity>) => Promise<[Entity[], number]>;Finds entities that match given find options or conditions. Also counts all entities that match given conditions, but ignores pagination settings (from and take options).
Parameter options
method findAndCountBy
findAndCountBy: (where: any) => Promise<[Entity[], number]>;Finds entities that match given find options or conditions. Also counts all entities that match given conditions, but ignores pagination settings (from and take options).
Parameter where
method findBy
findBy: (where: any) => Promise<Entity[]>;Finds entities that match given find options or conditions.
Parameter where
method findByIds
findByIds: (ids: any[], options?: any) => Promise<Entity[]>;Finds entities by ids. Optionally find options can be applied.
Parameter ids
Parameter options
method findOne
findOne: (options: MongoFindOneOptions<Entity>) => Promise<Entity | null>;Finds first entity that matches given find options.
Parameter options
method findOneAndDelete
findOneAndDelete: ( query: ObjectLiteral, options?: FindOneAndDeleteOptions) => Promise<Document | null>;Find a document and delete it in one atomic operation, requires a write lock for the duration of the operation.
Parameter query
Parameter options
method findOneAndReplace
findOneAndReplace: ( query: ObjectLiteral, replacement: Object, options?: FindOneAndReplaceOptions) => Promise<Document | null>;Find a document and replace it in one atomic operation, requires a write lock for the duration of the operation.
Parameter query
Parameter replacement
Parameter options
method findOneAndUpdate
findOneAndUpdate: ( query: ObjectLiteral, update: Object, options?: FindOneAndUpdateOptions) => Promise<Document | null>;Find a document and update it in one atomic operation, requires a write lock for the duration of the operation.
Parameter query
Parameter update
Parameter options
method findOneBy
findOneBy: (where: any) => Promise<Entity | null>;Finds first entity that matches given WHERE conditions.
Parameter where
method findOneByOrFail
findOneByOrFail: (where: any) => Promise<Entity>;Finds first entity that matches given where condition. If entity was not found in the database - rejects with error.
Parameter where
method findOneOrFail
findOneOrFail: (options: FindOneOptions<Entity>) => Promise<Entity>;Finds first entity by a given find options. If entity was not found in the database - rejects with error.
Parameter options
method initializeOrderedBulkOp
initializeOrderedBulkOp: (options?: BulkWriteOptions) => OrderedBulkOperation;Initiate an In order bulk write operation, operations will be serially executed in the order they are added, creating a new operation for each switch in types.
Parameter options
method initializeUnorderedBulkOp
initializeUnorderedBulkOp: ( options?: BulkWriteOptions) => UnorderedBulkOperation;Initiate a Out of order batch write operation. All operations will be buffered into insert/update/remove commands executed out of order.
Parameter options
method insertMany
insertMany: ( docs: ObjectLiteral[], options?: BulkWriteOptions) => Promise<InsertManyResult<Document>>;Inserts an array of documents into MongoDB.
Parameter docs
Parameter options
method insertOne
insertOne: ( doc: ObjectLiteral, options?: InsertOneOptions) => Promise<InsertOneResult>;Inserts a single document into MongoDB.
Parameter doc
Parameter options
method isCapped
isCapped: () => Promise<any>;Returns if the collection is a capped collection.
method listCollectionIndexes
listCollectionIndexes: (options?: ListIndexesOptions) => ListIndexesCursor;Get the list of all indexes information for the collection.
Parameter options
method query
query: (query: string, parameters?: any[]) => Promise<any>;Raw SQL query execution is not supported by MongoDB. Calling this method will return an error.
Parameter query
Parameter parameters
method rename
rename: ( newName: string, options?: { dropTarget?: boolean }) => Promise<Collection<Document>>;Reindex all indexes on the collection Warning: reIndex is a blocking operation (indexes are rebuilt in the foreground) and will be slow for large collections.
Parameter newName
Parameter options
Parameter
options.dropTarget
method replaceOne
replaceOne: ( query: ObjectLiteral, doc: ObjectLiteral, options?: ReplaceOptions) => Promise<Document | UpdateResult>;Replace a document on MongoDB.
Parameter query
Parameter doc
Parameter options
method updateMany
updateMany: ( query: ObjectLiteral, update: UpdateFilter<Document>, options?: UpdateOptions) => Promise<Document | UpdateResult>;Update multiple documents on MongoDB.
Parameter query
Parameter update
Parameter options
method updateOne
updateOne: ( query: ObjectLiteral, update: UpdateFilter<Document>, options?: UpdateOptions) => Promise<Document | UpdateResult>;Update a single document on MongoDB.
Parameter query
Parameter update
Parameter options
class MssqlParameter
class MssqlParameter {}Sql server driver requires parameter types to be specified fo input parameters used in the query.
See Also
https://github.com/patriksimek/node-mssql#data-types
constructor
constructor(value: any, type: string);constructor
constructor(value: any, type: string);constructor
constructor(value: any, type: string, precision?: number, scale?: number);constructor
constructor(value: any, type: string);constructor
constructor(value: any, type: string);constructor
constructor(value: any, type: string);constructor
constructor(value: any, type: string, precision?: number, scale?: number);constructor
constructor(value: any, type: string);constructor
constructor(value: any, type: string);constructor
constructor(value: any, type: string);constructor
constructor(value: any, type: string);constructor
constructor(value: any, type: string, length?: number);constructor
constructor(value: any, type: string, length?: number);constructor
constructor(value: any, type: string);constructor
constructor(value: any, type: string);constructor
constructor(value: any, type: string, length?: number);constructor
constructor(value: any, type: string, length?: number);constructor
constructor(value: any, type: string);constructor
constructor(value: any, type: string, scale?: number);constructor
constructor(value: any, type: string);constructor
constructor(value: any, type: string);constructor
constructor(value: any, type: string, scale?: number);constructor
constructor(value: any, type: string, scale?: number);constructor
constructor(value: any, type: string);constructor
constructor(value: any, type: string);constructor
constructor(value: any, type: string);constructor
constructor(value: any, type: string);constructor
constructor(value: any, type: string, length?: number);constructor
constructor(value: any, type: string);constructor
constructor(value: any, type: string);constructor
constructor(value: any, type: string);constructor
constructor(value: any, type: string);constructor
constructor(value: any, type: string);constructor
constructor(value: any, type: string, length: number);property "@instanceof"
readonly '@instanceof': Symbol;property params
params: any[];property type
type: string;property value
value: any;class MustBeEntityError
class MustBeEntityError extends TypeORMError {}Thrown when method expects entity but instead something else is given.
constructor
constructor(operation: string, wrongValue: any);class NamedPlaceholdersNotSupportedError
class NamedPlaceholdersNotSupportedError extends TypeORMError {}Thrown when trying to use named placeholders with an incompatible driver.
constructor
constructor();class NoConnectionForRepositoryError
class NoConnectionForRepositoryError extends TypeORMError {}Thrown when consumer tries to access repository before connection is established.
constructor
constructor(dataSourceName: string);class NoConnectionOptionError
class NoConnectionOptionError extends TypeORMError {}Thrown when some option is not set in the connection options.
constructor
constructor(optionName: string);class NoNeedToReleaseEntityManagerError
class NoNeedToReleaseEntityManagerError extends TypeORMError {}Thrown when consumer tries to release entity manager that does not use single database connection.
constructor
constructor();class NotBrackets
class NotBrackets extends Brackets {}Syntax sugar. Allows to use negate brackets in WHERE expressions for better syntax.
property "@instanceof"
readonly '@instanceof': Symbol;class NoVersionOrUpdateDateColumnError
class NoVersionOrUpdateDateColumnError extends TypeORMError {}Thrown when an entity does not have no version and no update date column.
constructor
constructor(entity: string);class OffsetWithoutLimitNotSupportedError
class OffsetWithoutLimitNotSupportedError extends TypeORMError {}Thrown when user tries to build SELECT query using OFFSET without LIMIT applied but database does not support it.
constructor
constructor();class OptimisticLockCanNotBeUsedError
class OptimisticLockCanNotBeUsedError extends TypeORMError {}Thrown when an optimistic lock cannot be used in query builder.
constructor
constructor();class OptimisticLockVersionMismatchError
class OptimisticLockVersionMismatchError extends TypeORMError {}Thrown when a version check on an object that uses optimistic locking through a version field fails.
constructor
constructor( entity: string, expectedVersion: number | Date, actualVersion: number | Date);class PersistedEntityNotFoundError
class PersistedEntityNotFoundError extends TypeORMError {}Thrown . Theoretically can't be thrown.
constructor
constructor();class PessimisticLockTransactionRequiredError
class PessimisticLockTransactionRequiredError extends TypeORMError {}Thrown when a transaction is required for the current operation, but there is none open.
constructor
constructor();class PrimaryColumnCannotBeNullableError
class PrimaryColumnCannotBeNullableError extends TypeORMError {}constructor
constructor(object: Object, propertyName: string);class QueryBuilder
abstract class QueryBuilder<Entity extends ObjectLiteral> {}Allows to build complex sql queries in a fashion way and execute those queries.
constructor
constructor(queryBuilder: QueryBuilder<any>);QueryBuilder can be initialized from given Connection and QueryRunner objects or from given other QueryBuilder.
constructor
constructor(connection: DataSource, queryRunner?: QueryRunner);QueryBuilder can be initialized from given Connection and QueryRunner objects or from given other QueryBuilder.
property "@instanceof"
readonly '@instanceof': Symbol;property alias
readonly alias: string;Gets the main alias string used in this query builder.
property connection
readonly connection: DataSource;DataSource on which QueryBuilder was created.
Deprecated
since 1.0.0. Use dataSource instance instead.
property dataSource
readonly dataSource: DataSource;DataSource on which QueryBuilder was created.
property expressionMap
readonly expressionMap: QueryExpressionMap;Contains all properties of the QueryBuilder that needs to be build a final query.
property parentQueryBuilder
protected parentQueryBuilder: QueryBuilder<any>;If QueryBuilder was created in a subquery mode then its parent QueryBuilder (who created subquery) will be stored here.
property queryRunner
protected queryRunner?: QueryRunner;Query runner used to execute query builder query.
method addCommonTableExpression
addCommonTableExpression: ( queryBuilder: QueryBuilder<any> | string, alias: string, options?: QueryBuilderCteOptions) => this;Adds CTE to query
Parameter queryBuilder
Parameter alias
Parameter options
method callListeners
callListeners: (enabled: boolean) => this;Indicates if listeners and subscribers must be called before and after query execution. Enabled by default.
Parameter enabled
method clone
clone: () => this;Clones query builder as it is. Note: it uses new query runner, if you want query builder that uses exactly same query runner, you can create query builder using its constructor, for example new SelectQueryBuilder(queryBuilder) where queryBuilder is cloned QueryBuilder.
method comment
comment: (comment: string) => this;Includes a Query comment in the query builder. This is helpful for debugging purposes, such as finding a specific query in the database server's logs, or for categorization using an APM product.
Parameter comment
method createComment
protected createComment: () => string;method createCteExpression
protected createCteExpression: () => string;method createFromAlias
protected createFromAlias: ( entityTarget: | EntityTarget<any> | ((qb: SelectQueryBuilder<any>) => SelectQueryBuilder<any>), aliasName?: string) => Alias;Specifies FROM which entity's table select/update/delete will be executed. Also sets a main string alias of the selection data.
Parameter entityTarget
Parameter aliasName
method createParameter
protected createParameter: (value: any) => string;method createPropertyPath
protected createPropertyPath: ( metadata: EntityMetadata, entity: ObjectLiteral, prefix?: string) => string[];Creates a property paths for a given ObjectLiteral.
Parameter metadata
Parameter entity
Parameter prefix
method createQueryBuilder
createQueryBuilder: (queryRunner?: QueryRunner) => this;Creates a completely new query builder. Uses same query runner as current QueryBuilder.
Parameter queryRunner
method createReturningExpression
protected createReturningExpression: (returningType: ReturningType) => string;Creates "RETURNING" / "OUTPUT" expression.
Parameter returningType
method createTimeTravelQuery
protected createTimeTravelQuery: () => string;Time travel queries for CockroachDB
method createWhereClausesExpression
protected createWhereClausesExpression: (clauses: WhereClause[]) => string;method createWhereConditionExpression
protected createWhereConditionExpression: ( condition: WhereClauseCondition, alwaysWrap?: boolean) => string;Computes given where argument - transforms to a where string all forms it can take.
Parameter condition
Parameter alwaysWrap
method createWhereExpression
protected createWhereExpression: () => string;Creates "WHERE" expression.
method delete
delete: () => DeleteQueryBuilder<Entity>;Creates DELETE query.
method disableEscaping
disableEscaping: () => this;Disables escaping.
method escape
escape: (name: string) => string;Escapes table name, column name or alias name using current database's escaping character.
Parameter name
method execute
execute: () => Promise<any>;Executes sql generated by query builder and returns raw database results.
method getExistsCondition
protected getExistsCondition: (subQuery: any) => [string, any[]];method getMainTableName
protected getMainTableName: () => string;Gets name of the table where insert should be performed.
method getParameters
getParameters: () => ObjectLiteral;Gets all parameters.
method getPredicates
protected getPredicates: ( where: ObjectLiteral) => Generator<any[], void, unknown>;method getQuery
abstract getQuery: () => string;Gets generated SQL query without parameters being replaced.
method getQueryAndParameters
getQueryAndParameters: () => [string, any[]];Gets query to be executed with all parameters used in it.
method getReturningColumns
protected getReturningColumns: () => ColumnMetadata[];If returning / output cause is set to array of column names, then this method will return all column metadatas of those column names.
method getSql
getSql: () => string;Gets generated sql that will be executed. Parameters in the query are escaped for the currently used driver.
method getTableName
protected getTableName: (tablePath: string) => string;Gets escaped table name with schema name if SqlServer driver used with custom schema name, otherwise returns escaped table name.
Parameter tablePath
method getWhereCondition
protected getWhereCondition: ( where: | string | ObjectLiteral | Brackets | ((qb: this) => string) | NotBrackets | ObjectLiteral[]) => WhereClauseCondition;method getWhereInIdsCondition
protected getWhereInIdsCondition: (ids: any | any[]) => ObjectLiteral | Brackets;Creates "WHERE" condition for an in-ids condition.
Parameter ids
method getWherePredicateCondition
protected getWherePredicateCondition: ( aliasPath: string, parameterValue: any) => WhereClauseCondition;method hasCommonTableExpressions
protected hasCommonTableExpressions: () => boolean;method hasParameter
hasParameter: (key: string) => boolean;Check the existence of a parameter for this query builder.
Parameter key
method hasRelation
hasRelation: { <T>(target: EntityTarget<T>, relation: string): boolean; <T>(target: EntityTarget<T>, relation: string[]): boolean;};Checks if given relation exists in the entity. Returns true if relation exists, false otherwise.
todo: move this method to manager? or create a shortcut?
Checks if given relations exist in the entity. Returns true if relation exists, false otherwise.
todo: move this method to manager? or create a shortcut?
method insert
insert: () => InsertQueryBuilder<Entity>;Creates INSERT query.
method normalizeNumber
protected normalizeNumber: (num: any) => any;method obtainQueryRunner
protected obtainQueryRunner: () => QueryRunner;Creates a query builder used to execute sql queries inside this query builder.
method registerQueryBuilderClass
static registerQueryBuilderClass: (name: string, factory: any) => void;method relation
relation: { (propertyPath: string): RelationQueryBuilder<Entity>; <T extends ObjectLiteral>( entityTarget: EntityTarget<T>, propertyPath: string ): RelationQueryBuilder<T>;};Sets entity's relation with which this query builder gonna work.
method replacePropertyNamesForTheWholeQuery
protected replacePropertyNamesForTheWholeQuery: (statement: string) => string;Replaces all entity's propertyName to name in the given SQL string.
Parameter statement
method restore
restore: () => SoftDeleteQueryBuilder<any>;method select
select: { (): SelectQueryBuilder<Entity>; (selection: string, selectionAliasName?: string): SelectQueryBuilder<Entity>; (selection: string[]): SelectQueryBuilder<Entity>;};Creates SELECT query. Replaces all previous selections if they exist.
Creates SELECT query and selects given data. Replaces all previous selections if they exist.
method setParameter
setParameter: (key: string, value: any) => this;Sets parameter name and its value.
The key for this parameter may contain numbers, letters, underscores, or periods.
Parameter key
Parameter value
method setParameters
setParameters: (parameters: ObjectLiteral) => this;Adds all parameters from the given object.
Parameter parameters
method setQueryRunner
setQueryRunner: (queryRunner: QueryRunner) => this;Sets or overrides query builder's QueryRunner.
Parameter queryRunner
method softDelete
softDelete: () => SoftDeleteQueryBuilder<any>;method update
update: { (): UpdateQueryBuilder<Entity>; <Entity extends ObjectLiteral>( entity: EntityTarget<Entity> ): UpdateQueryBuilder<Entity>; ( updateSet: _QueryDeepPartialEntity< ObjectLiteral extends Entity ? unknown : Entity > ): UpdateQueryBuilder<Entity>; <Entity extends ObjectLiteral>( entity: EntityTarget<Entity>, updateSet?: _QueryDeepPartialEntity< ObjectLiteral extends Entity ? unknown : Entity > ): UpdateQueryBuilder<Entity>; ( tableName: string, updateSet?: _QueryDeepPartialEntity< ObjectLiteral extends Entity ? unknown : Entity > ): UpdateQueryBuilder<Entity>;};Creates UPDATE query and applies given update values.
Creates UPDATE query for the given entity.
Creates UPDATE query for the given entity and applies given update values.
Creates UPDATE query for the given table name and applies given update values.
method useTransaction
useTransaction: (enabled: boolean) => this;If set to true the query will be wrapped into a transaction.
Parameter enabled
method validateNumericInput
protected validateNumericInput: ( label: string, num: number | undefined) => number | undefined;Normalizes and validates a numeric query parameter, throwing if the result is NaN.
Parameter label
Parameter num
method validateOrderByCondition
protected validateOrderByCondition: (sort: OrderByCondition) => void;class QueryFailedError
class QueryFailedError<T extends Error = Error> extends TypeORMError {}Thrown when query execution has failed.
constructor
constructor( query: string, parameters: any[] | ObjectLiteral, driverError: Error);property driverError
readonly driverError: Error;property parameters
readonly parameters: any[] | ObjectLiteral;property query
readonly query: string;class QueryResult
class QueryResult<T = any> {}Result object returned by UpdateQueryBuilder execution.
class QueryRunnerAlreadyReleasedError
class QueryRunnerAlreadyReleasedError extends TypeORMError {}constructor
constructor();class QueryRunnerProviderAlreadyReleasedError
class QueryRunnerProviderAlreadyReleasedError extends TypeORMError {}Thrown when consumer tries to use query runner from query runner provider after it was released.
constructor
constructor();class RelationQueryBuilder
class RelationQueryBuilder< Entity extends ObjectLiteral> extends QueryBuilder<Entity> {}Allows to work with entity relations and perform specific operations with those relations.
todo: add transactions everywhere
property "@instanceof"
readonly '@instanceof': Symbol;method add
add: (value: any | any[]) => Promise<void>;Adds (binds) given value to entity relation. Value can be entity, entity id or entity id map (if entity has composite ids). Value also can be array of entities, array of entity ids or array of entity id maps (if entity has composite ids). Works only for many-to-many and one-to-many relations. For many-to-one and one-to-one use #set method instead.
Parameter value
method addAndRemove
addAndRemove: (added: any | any[], removed: any | any[]) => Promise<void>;Adds (binds) and removes (unbinds) given values to/from entity relation. Value can be entity, entity id or entity id map (if entity has composite ids). Value also can be array of entities, array of entity ids or array of entity id maps (if entity has composite ids). Works only for many-to-many and one-to-many relations. For many-to-one and one-to-one use #set method instead.
Parameter added
Parameter removed
method getQuery
getQuery: () => string;Gets generated SQL query without parameters being replaced.
method loadMany
loadMany: <T = any>() => Promise<T[]>;Loads many entities (relational) from the relation. You can also provide ids of relational entities to filter by.
method loadOne
loadOne: <T = any>() => Promise<T | undefined>;Loads a single entity (relational) from the relation. You can also provide id of relational entity to filter by.
method of
of: (entity: any | any[]) => this;Sets entity (target) which relations will be updated.
Parameter entity
method remove
remove: (value: any | any[]) => Promise<void>;Removes (unbinds) given value from entity relation. Value can be entity, entity id or entity id map (if entity has composite ids). Value also can be array of entities, array of entity ids or array of entity id maps (if entity has composite ids). Works only for many-to-many and one-to-many relations. For many-to-one and one-to-one use #set method instead.
Parameter value
method set
set: (value: any) => Promise<void>;Sets entity relation's value. Value can be entity, entity id or entity id map (if entity has composite ids). Works only for many-to-one and one-to-one relations. For many-to-many and one-to-many relations use #add and #remove methods instead.
Parameter value
class Repository
class Repository<Entity extends ObjectLiteral> {}Repository is supposed to work with your entity objects. Find entities, insert, update, delete, etc.
constructor
constructor( target: EntityTarget<Entity>, manager: EntityManager, queryRunner?: QueryRunner);property manager
readonly manager: EntityManager;Entity Manager used by this repository.
property metadata
readonly metadata: EntityMetadata;Entity metadata of the entity current repository manages.
property queryRunner
readonly queryRunner?: QueryRunner;Query runner provider used for this repository.
property target
readonly target: EntityTarget<Entity>;Entity target that is managed by this repository. If this repository manages entity from schema, then it returns a name of that schema instead.
method average
average: ( columnName: PickKeysByType<Entity, number>, where?: FindOptionsWhere<Entity> | FindOptionsWhere<Entity>[]) => Promise<number | null>;Return the AVG of a column
Parameter columnName
Parameter where
method clear
clear: (options?: { cascade?: boolean }) => Promise<void>;Clears all the data from the given table/collection (truncates/drops it).
Note: this method uses TRUNCATE and may not work as you expect in transactions on some platforms.
Parameter options
Parameter
options.cascade
See Also
https://stackoverflow.com/a/5972738/925151
method count
count: (options?: FindManyOptions<Entity>) => Promise<number>;Counts entities that match given options. Useful for pagination.
Parameter options
method countBy
countBy: ( where: FindOptionsWhere<Entity> | FindOptionsWhere<Entity>[]) => Promise<number>;Counts entities that match given conditions. Useful for pagination.
Parameter where
method create
create: { (): Entity; (entityLikeArray: DeepPartial<Entity>[]): Entity[]; (entityLike: DeepPartial<Entity>): Entity;};Creates a new entity instance.
Creates new entities and copies all entity properties from given objects into their new entities. Note that it copies only properties that are present in entity schema.
Creates a new entity instance and copies all entity properties from this object into a new entity. Note that it copies only properties that are present in entity schema.
method createQueryBuilder
createQueryBuilder: ( alias?: string, queryRunner?: QueryRunner) => SelectQueryBuilder<Entity>;Creates a new query builder that can be used to build a SQL query.
Parameter alias
Parameter queryRunner
method decrement
decrement: ( conditions: FindOptionsWhere<Entity>, propertyPath: string, value: number | string) => Promise<UpdateResult>;Decrements some column by provided value of the entities matched given conditions.
Parameter conditions
Parameter propertyPath
Parameter value
method delete
delete: ( criteria: | string | string[] | number | number[] | Date | Date[] | ObjectId | ObjectId[] | FindOptionsWhere<Entity> | FindOptionsWhere<Entity>[]) => Promise<DeleteResult>;Deletes entities by a given criteria. Unlike save method executes a primitive operation without cascades, relations and other operations included. Executes fast and efficient DELETE query. Does not check if entity exist in the database.
Parameter criteria
method deleteAll
deleteAll: () => Promise<DeleteResult>;Deletes all entities of target type. This is a primitive operation without cascades, relations or other operations included. Executes fast and efficient DELETE query without WHERE clause.
WARNING! This method deletes ALL rows in the target table.
method exists
exists: (options?: FindManyOptions<Entity>) => Promise<boolean>;Checks whether any entity exists that matches the given options.
Parameter options
method existsBy
existsBy: ( where: FindOptionsWhere<Entity> | FindOptionsWhere<Entity>[]) => Promise<boolean>;Checks whether any entity exists that matches the given conditions.
Parameter where
method extend
extend: <CustomRepository>( customs: CustomRepository & ThisType<this & CustomRepository>) => this & CustomRepository;Extends repository with provided functions.
Parameter customs
method find
find: (options?: FindManyOptions<Entity>) => Promise<Entity[]>;Finds entities that match given find options.
Parameter options
method findAndCount
findAndCount: (options?: FindManyOptions<Entity>) => Promise<[Entity[], number]>;Finds entities that match given find options. Also counts all entities that match given conditions, but ignores pagination settings (from and take options).
Parameter options
method findAndCountBy
findAndCountBy: ( where: FindOptionsWhere<Entity> | FindOptionsWhere<Entity>[]) => Promise<[Entity[], number]>;Finds entities that match given WHERE conditions. Also counts all entities that match given conditions, but ignores pagination settings (from and take options).
Parameter where
method findBy
findBy: ( where: FindOptionsWhere<Entity> | FindOptionsWhere<Entity>[]) => Promise<Entity[]>;Finds entities that match given find options.
Parameter where
method findOne
findOne: (options: FindOneOptions<Entity>) => Promise<Entity | null>;Finds first entity by a given find options. If entity was not found in the database - returns null.
Parameter options
method findOneBy
findOneBy: ( where: FindOptionsWhere<Entity> | FindOptionsWhere<Entity>[]) => Promise<Entity | null>;Finds first entity that matches given where condition. If entity was not found in the database - returns null.
Parameter where
method findOneByOrFail
findOneByOrFail: ( where: FindOptionsWhere<Entity> | FindOptionsWhere<Entity>[]) => Promise<Entity>;Finds first entity that matches given where condition. If entity was not found in the database - rejects with error.
Parameter where
method findOneOrFail
findOneOrFail: (options: FindOneOptions<Entity>) => Promise<Entity>;Finds first entity by a given find options. If entity was not found in the database - rejects with error.
Parameter options
method getId
getId: (entity: Entity) => any;Gets entity mixed id.
Parameter entity
method hasId
hasId: (entity: Entity) => boolean;Checks if entity has an id. If entity composite compose ids, it will check them all.
Parameter entity
method increment
increment: ( conditions: FindOptionsWhere<Entity>, propertyPath: string, value: number | string) => Promise<UpdateResult>;Increments some column by provided value of the entities matched given conditions.
Parameter conditions
Parameter propertyPath
Parameter value
method insert
insert: ( entity: QueryDeepPartialEntity<Entity> | QueryDeepPartialEntity<Entity>[]) => Promise<InsertResult>;Inserts a given entity into the database. Unlike save method executes a primitive operation without cascades, relations and other operations included. Executes fast and efficient INSERT query. Does not check if entity exist in the database, so query will fail if duplicate entity is being inserted.
Parameter entity
method maximum
maximum: ( columnName: PickKeysByType<Entity, number>, where?: FindOptionsWhere<Entity> | FindOptionsWhere<Entity>[]) => Promise<number | null>;Return the MAX of a column
Parameter columnName
Parameter where
method merge
merge: ( mergeIntoEntity: Entity, ...entityLikes: DeepPartial<Entity>[]) => Entity;Merges multiple entities (or entity-like objects) into a given entity.
Parameter mergeIntoEntity
Parameter entityLikes
method minimum
minimum: ( columnName: PickKeysByType<Entity, number>, where?: FindOptionsWhere<Entity> | FindOptionsWhere<Entity>[]) => Promise<number | null>;Return the MIN of a column
Parameter columnName
Parameter where
method preload
preload: (entityLike: DeepPartial<Entity>) => Promise<Entity | undefined>;Creates a new entity from the given plain javascript object. If entity already exist in the database, then it loads it (and everything related to it), replaces all values with the new ones from the given object and returns this new entity. This new entity is actually a loaded from the db entity with all properties replaced from the new object.
Note that given entity-like object must have an entity id / primary key to find entity by. Returns undefined if entity with given id was not found.
Parameter entityLike
method query
query: <T = any>( query: string, parameters?: any[] | ObjectLiteral) => Promise<T>;Executes a raw SQL query and returns a raw database results. Raw query execution is supported only by relational databases (MongoDB is not supported).
Parameter query
Parameter parameters
See Also
[Official docs](https://typeorm.io/repository-api) for examples.
method recover
recover: { <T extends DeepPartial<Entity>>( entities: T[], options: SaveOptions & { reload: false } ): Promise<T[]>; <T extends DeepPartial<Entity>>( entities: T[], options?: SaveOptions ): Promise<(T & Entity)[]>; <T extends DeepPartial<Entity>>( entity: T, options: SaveOptions & { reload: false } ): Promise<T>; <T extends DeepPartial<Entity>>(entity: T, options?: SaveOptions): Promise< T & Entity >;};Recovers all given entities in the database.
Recovers a given entity in the database.
method remove
remove: { (entities: Entity[], options?: RemoveOptions): Promise<Entity[]>; (entity: Entity, options?: RemoveOptions): Promise<Entity>;};Removes a given entities from the database.
Removes a given entity from the database.
method restore
restore: ( criteria: | string | string[] | number | number[] | Date | Date[] | ObjectId | ObjectId[] | FindOptionsWhere<Entity> | FindOptionsWhere<Entity>[]) => Promise<UpdateResult>;Restores entities by a given criteria. Unlike save method executes a primitive operation without cascades, relations and other operations included. Executes fast and efficient UPDATE query. Does not check if entity exist in the database.
Parameter criteria
method save
save: { <T extends DeepPartial<Entity>>( entities: T[], options: SaveOptions & { reload: false } ): Promise<T[]>; <T extends DeepPartial<Entity>>( entities: T[], options?: SaveOptions ): Promise<(T & Entity)[]>; <T extends DeepPartial<Entity>>( entity: T, options: SaveOptions & { reload: false } ): Promise<T>; <T extends DeepPartial<Entity>>(entity: T, options?: SaveOptions): Promise< T & Entity >;};Saves all given entities in the database. If entities do not exist in the database then inserts, otherwise updates.
Saves a given entity in the database. If entity does not exist in the database then inserts, otherwise updates.
method softDelete
softDelete: ( criteria: | string | string[] | number | number[] | Date | Date[] | ObjectId | ObjectId[] | FindOptionsWhere<Entity> | FindOptionsWhere<Entity>[]) => Promise<UpdateResult>;Records the delete date of entities by a given criteria. Unlike save method executes a primitive operation without cascades, relations and other operations included. Executes fast and efficient UPDATE query. Does not check if entity exist in the database.
Parameter criteria
method softRemove
softRemove: { <T extends DeepPartial<Entity>>( entities: T[], options: SaveOptions & { reload: false } ): Promise<T[]>; <T extends DeepPartial<Entity>>( entities: T[], options?: SaveOptions ): Promise<(T & Entity)[]>; <T extends DeepPartial<Entity>>( entity: T, options: SaveOptions & { reload: false } ): Promise<T>; <T extends DeepPartial<Entity>>(entity: T, options?: SaveOptions): Promise< T & Entity >;};Records the delete date of all given entities.
Records the delete date of a given entity.
method sql
sql: <T = any>( strings: TemplateStringsArray, ...values: unknown[]) => Promise<T>;Tagged template function that executes raw SQL query and returns raw database results. Template expressions are automatically transformed into database parameters. Raw query execution is supported only by relational databases (MongoDB is not supported). Note: Don't call this as a regular function, it is meant to be used with backticks to tag a template literal.
Parameter strings
Parameter values
Example 1
repository.sql
SELECT * FROM table_name WHERE id = ${id}
method sum
sum: ( columnName: PickKeysByType<Entity, number>, where?: FindOptionsWhere<Entity> | FindOptionsWhere<Entity>[]) => Promise<number | null>;Return the SUM of a column
Parameter columnName
Parameter where
method update
update: ( criteria: | string | string[] | number | number[] | Date | Date[] | ObjectId | ObjectId[] | FindOptionsWhere<Entity> | FindOptionsWhere<Entity>[], partialEntity: QueryDeepPartialEntity<Entity>, options?: UpdateOptions) => Promise<UpdateResult>;Updates entity partially. Entity can be found by a given conditions. Unlike save method executes a primitive operation without cascades, relations and other operations included. Executes fast and efficient UPDATE query. Does not check if entity exist in the database.
Parameter criteria
Parameter partialEntity
Parameter options
method updateAll
updateAll: ( partialEntity: QueryDeepPartialEntity<Entity>, options?: UpdateOptions) => Promise<UpdateResult>;Updates all entities of target type, setting fields from supplied partial entity. This is a primitive operation without cascades, relations or other operations included. Executes fast and efficient UPDATE query without WHERE clause.
WARNING! This method updates ALL rows in the target table.
Parameter partialEntity
Parameter options
method upsert
upsert: ( entityOrEntities: | QueryDeepPartialEntity<Entity> | QueryDeepPartialEntity<Entity>[], conflictPathsOrOptions: string[] | UpsertOptions<Entity>) => Promise<InsertResult>;Inserts a given entity into the database, unless a unique constraint conflicts then updates the entity Unlike save method executes a primitive operation without cascades, relations and other operations included. Executes fast and efficient INSERT ... ON CONFLICT DO UPDATE/ON DUPLICATE KEY UPDATE query.
Parameter entityOrEntities
Parameter conflictPathsOrOptions
class RepositoryNotTreeError
class RepositoryNotTreeError extends TypeORMError {}Thrown when repository for the given class is not found.
constructor
constructor(entityClass: EntityTarget<any>);class ReturningStatementNotSupportedError
class ReturningStatementNotSupportedError extends TypeORMError {}Thrown when user tries to build a query with RETURNING / OUTPUT statement, but used database does not support it.
constructor
constructor();class SelectQueryBuilder
class SelectQueryBuilder<Entity extends ObjectLiteral> extends QueryBuilder<Entity> implements WhereExpressionBuilder {}Allows to build complex sql queries in a fashion way and execute those queries.
property "@instanceof"
readonly '@instanceof': Symbol;property conditions
protected conditions: string;property eagerLoadChain
protected eagerLoadChain: Set<string>;property findOptions
protected findOptions: FindManyOptions<any>;property joins
protected joins: { type: 'inner' | 'left'; alias: string; parentAlias: string; relationMetadata: RelationMetadata; select: boolean; selection: FindOptionsSelect<any> | undefined;}[];property orderBys
protected orderBys: { alias: string; direction: 'ASC' | 'DESC'; nulls?: 'NULLS FIRST' | 'NULLS LAST';}[];property relationMetadatas
protected relationMetadatas: RelationMetadata[];property selects
protected selects: string[];method addFrom
addFrom: { <T extends ObjectLiteral>( entityTarget: (qb: SelectQueryBuilder<any>) => SelectQueryBuilder<any>, aliasName: string ): SelectQueryBuilder<T>; <T extends ObjectLiteral>( entityTarget: EntityTarget<T>, aliasName: string ): SelectQueryBuilder<T>;};Specifies FROM which entity's table select/update/delete will be executed. Also sets a main string alias of the selection data.
method addGroupBy
addGroupBy: (groupBy: string) => this;Adds GROUP BY condition in the query builder.
Parameter groupBy
method addOrderBy
addOrderBy: ( sort: string, order?: 'ASC' | 'DESC', nulls?: 'NULLS FIRST' | 'NULLS LAST') => this;Adds ORDER BY condition in the query builder.
Parameter sort
Parameter order
Parameter nulls
method addSelect
addSelect: { ( selection: (qb: SelectQueryBuilder<any>) => SelectQueryBuilder<any>, selectionAliasName?: string ): this; (selection: string, selectionAliasName?: string): this; (selection: string[]): this;};Adds new selection to the SELECT query.
method andHaving
andHaving: (having: string, parameters?: ObjectLiteral) => this;Adds new AND HAVING condition in the query builder. Additionally you can add parameters used in where expression.
Parameter having
Parameter parameters
method andWhere
andWhere: ( where: | string | ObjectLiteral | Brackets | ObjectLiteral[] | ((qb: this) => string), parameters?: ObjectLiteral) => this;Adds new AND WHERE condition in the query builder. Additionally you can add parameters used in where expression.
Parameter where
Parameter parameters
method andWhereExists
andWhereExists: (subQuery: SelectQueryBuilder<any>) => this;Adds a new AND where EXISTS clause
Parameter subQuery
method andWhereInIds
andWhereInIds: (ids: any | any[]) => this;Adds new AND WHERE with conditions for the given ids.
Ids are mixed. It means if you have single primary key you can pass a simple id values, for example [1, 2, 3]. If you have multiple primary keys you need to pass object with property names and values specified, for example [{ firstId: 1, secondId: 2 }, { firstId: 2, secondId: 3 }, ...]
Parameter ids
method applyFindOptions
protected applyFindOptions: () => void;method buildEagerRelations
protected buildEagerRelations: ( relations: FindOptionsRelations<any>, selection: FindOptionsSelect<any> | undefined, metadata: EntityMetadata, alias: string, embedPrefix?: string) => void;method buildEscapedEntityColumnSelects
protected buildEscapedEntityColumnSelects: ( aliasName: string, metadata: EntityMetadata) => SelectQuery[];method buildOrder
protected buildOrder: ( order: FindOptionsOrder<any>, metadata: EntityMetadata, alias: string, embedPrefix?: string) => void;method buildRelations
protected buildRelations: ( relations: FindOptionsRelations<any>, selection: FindOptionsSelect<any> | undefined, metadata: EntityMetadata, alias: string, embedPrefix?: string, parentJoinType?: 'inner' | 'left') => void;method buildSelect
protected buildSelect: ( select: FindOptionsSelect<any>, metadata: EntityMetadata, alias: string, embedPrefix?: string) => void;method buildWhere
protected buildWhere: ( where: FindOptionsWhere<any>[] | FindOptionsWhere<any>, metadata: EntityMetadata, alias: string, embedPrefix?: string) => string;method cache
cache: { (enabled: boolean): this; (milliseconds: number): this; (id: any, milliseconds?: number): this;};Enables or disables query result caching.
Enables query result caching and sets in milliseconds in which cache will expire. If not set then global caching time will be used.
Enables query result caching and sets cache id and milliseconds in which cache will expire.
method concatRelationMetadata
concatRelationMetadata: (...relationMetadata: RelationMetadata[]) => void;Registers relation metadata for loading via separate queries when using the "query" relation load strategy. Duplicates (by propertyPath) are silently skipped.
Parameter relationMetadata
one or more relation metadata entries to register
method createGroupByExpression
protected createGroupByExpression: () => string;Creates "GROUP BY" part of SQL query.
method createHavingExpression
protected createHavingExpression: () => string;Creates "HAVING" part of SQL query.
method createJoinExpression
protected createJoinExpression: () => string;Creates "JOIN" part of SQL query.
method createLimitOffsetExpression
protected createLimitOffsetExpression: () => string;Creates "LIMIT" and "OFFSET" parts of SQL query.
method createLockExpression
protected createLockExpression: () => string;Returns
"LOCK" part of SQL query
method createOrderByCombinedWithSelectExpression
protected createOrderByCombinedWithSelectExpression: ( parentAlias: string) => [string, OrderByCondition];method createOrderByExpression
protected createOrderByExpression: () => string;Creates "ORDER BY" part of SQL query.
method createSelectDistinctExpression
protected createSelectDistinctExpression: () => string;Creates select | select distinct part of SQL query.
method createSelectExpression
protected createSelectExpression: () => string;Creates "SELECT FROM" part of SQL query.
method distinct
distinct: (distinct?: boolean) => this;Sets whether the selection is DISTINCT.
Parameter distinct
method distinctOn
distinctOn: (distinctOn: string[]) => this;Sets the distinct on clause for Postgres.
Parameter distinctOn
method executeCountQuery
protected executeCountQuery: (queryRunner: QueryRunner) => Promise<number>;method executeEntitiesAndRawResults
protected executeEntitiesAndRawResults: ( queryRunner: QueryRunner) => Promise<{ entities: Entity[]; raw: any[] }>;Executes sql generated by query builder and returns object with raw results and entities created from them.
Parameter queryRunner
method executeExistsQuery
protected executeExistsQuery: (queryRunner: QueryRunner) => Promise<boolean>;method findEntityColumnSelects
protected findEntityColumnSelects: ( aliasName: string, metadata: EntityMetadata) => SelectQuery[];method from
from: { <T extends ObjectLiteral>( entityTarget: (qb: SelectQueryBuilder<any>) => SelectQueryBuilder<any>, aliasName: string ): SelectQueryBuilder<T>; <T extends ObjectLiteral>( entityTarget: EntityTarget<T>, aliasName: string ): SelectQueryBuilder<T>;};Specifies FROM which entity's table select/update/delete will be executed. Also sets a main string alias of the selection data. Removes all previously set from-s.
method fromDummy
fromDummy: () => SelectQueryBuilder<any>;method getCount
getCount: () => Promise<number>;Gets count - number of entities selected by sql generated by this query builder. Count excludes all limitations set by offset, limit, skip, and take.
method getExists
getExists: () => Promise<boolean>;Gets exists Returns whether any rows exists matching current query.
method getMany
getMany: () => Promise<Entity[]>;Gets entities returned by execution of generated query builder sql.
method getManyAndCount
getManyAndCount: () => Promise<[Entity[], number]>;Executes built SQL query and returns entities and overall entities count (without limitation). This method is useful to build pagination.
method getOne
getOne: () => Promise<Entity | null>;Gets single entity returned by execution of generated query builder sql.
method getOneOrFail
getOneOrFail: () => Promise<Entity>;Gets the first entity returned by execution of generated query builder sql or rejects the returned promise on error.
method getQuery
getQuery: () => string;Gets generated SQL query without parameters being replaced.
method getRawAndEntities
getRawAndEntities: <T = any>() => Promise<{ entities: Entity[]; raw: T[] }>;Executes sql generated by query builder and returns object with raw results and entities created from them.
method getRawMany
getRawMany: <T = any>() => Promise<T[]>;Gets all raw results returned by execution of generated query builder sql.
method getRawOne
getRawOne: <T = any>() => Promise<T | undefined>;Gets first raw result returned by execution of generated query builder sql.
method getRelationJoinType
protected getRelationJoinType: ( relation: RelationMetadata, parentJoinType?: 'inner' | 'left') => 'inner' | 'left';method groupBy
groupBy: { (): this; (groupBy: string): this };Sets GROUP BY condition in the query builder. If you had previously GROUP BY expression defined, calling this function will override previously set GROUP BY conditions.
method having
having: (having: string, parameters?: ObjectLiteral) => this;Sets HAVING condition in the query builder. If you had previously HAVING expression defined, calling this function will override previously set HAVING conditions. Additionally you can add parameters used in where expression.
Parameter having
Parameter parameters
method innerJoin
innerJoin: { ( subQueryFactory: ( qb: SelectQueryBuilder<any> ) => SelectQueryBuilder<any>, alias: string, condition?: string, parameters?: ObjectLiteral ): this; ( property: string, alias: string, condition?: string, parameters?: ObjectLiteral ): this; ( entity: string | Function, alias: string, condition?: string, parameters?: ObjectLiteral ): this; ( tableName: string, alias: string, condition?: string, parameters?: ObjectLiteral ): this;};INNER JOINs (without selection) given subquery. You also need to specify an alias of the joined data. Optionally, you can add condition and parameters used in condition.
INNER JOINs (without selection) entity's property. Given entity property should be a relation. You also need to specify an alias of the joined data. Optionally, you can add condition and parameters used in condition.
INNER JOINs (without selection) given entity's table. You also need to specify an alias of the joined data. Optionally, you can add condition and parameters used in condition.
INNER JOINs (without selection) given table. You also need to specify an alias of the joined data. Optionally, you can add condition and parameters used in condition.
method innerJoinAndMapMany
innerJoinAndMapMany: { ( mapToProperty: string, subQueryFactory: ( qb: SelectQueryBuilder<any> ) => SelectQueryBuilder<any>, alias: string, condition?: string, parameters?: ObjectLiteral ): this; ( mapToProperty: string, property: string, alias: string, condition?: string, parameters?: ObjectLiteral ): this; ( mapToProperty: string, entity: string | Function, alias: string, condition?: string, parameters?: ObjectLiteral ): this; ( mapToProperty: string, tableName: string, alias: string, condition?: string, parameters?: ObjectLiteral ): this;};INNER JOINs given subquery, SELECTs the data returned by a join and MAPs all that data to some entity's property. This is extremely useful when you want to select some data and map it to some virtual property. It will assume that there are multiple rows of selecting data, and mapped result will be an array. Given entity property should be a relation. You also need to specify an alias of the joined data. Optionally, you can add condition and parameters used in condition.
INNER JOINs entity's property, SELECTs the data returned by a join and MAPs all that data to some entity's property. This is extremely useful when you want to select some data and map it to some virtual property. It will assume that there are multiple rows of selecting data, and mapped result will be an array. Given entity property should be a relation. You also need to specify an alias of the joined data. Optionally, you can add condition and parameters used in condition.
INNER JOINs entity's table, SELECTs the data returned by a join and MAPs all that data to some entity's property. This is extremely useful when you want to select some data and map it to some virtual property. It will assume that there are multiple rows of selecting data, and mapped result will be an array. You also need to specify an alias of the joined data. Optionally, you can add condition and parameters used in condition.
INNER JOINs table, SELECTs the data returned by a join and MAPs all that data to some entity's property. This is extremely useful when you want to select some data and map it to some virtual property. It will assume that there are multiple rows of selecting data, and mapped result will be an array. You also need to specify an alias of the joined data. Optionally, you can add condition and parameters used in condition.
method innerJoinAndMapOne
innerJoinAndMapOne: { ( mapToProperty: string, subQueryFactory: ( qb: SelectQueryBuilder<any> ) => SelectQueryBuilder<any>, alias: string, condition?: string, parameters?: ObjectLiteral, mapAsEntity?: Function | string ): this; ( mapToProperty: string, property: string, alias: string, condition?: string, parameters?: ObjectLiteral ): this; ( mapToProperty: string, entity: string | Function, alias: string, condition?: string, parameters?: ObjectLiteral ): this; ( mapToProperty: string, tableName: string, alias: string, condition?: string, parameters?: ObjectLiteral ): this;};INNER JOINs given subquery, SELECTs the data returned by a join and MAPs all that data to some entity's property. This is extremely useful when you want to select some data and map it to some virtual property. It will assume that there is a single row of selecting data, and mapped result will be a single selected value. Given entity property should be a relation. You also need to specify an alias of the joined data. Optionally, you can add condition and parameters used in condition.
INNER JOINs entity's property, SELECTs the data returned by a join and MAPs all that data to some entity's property. This is extremely useful when you want to select some data and map it to some virtual property. It will assume that there is a single row of selecting data, and mapped result will be a single selected value. Given entity property should be a relation. You also need to specify an alias of the joined data. Optionally, you can add condition and parameters used in condition.
INNER JOINs entity's table, SELECTs the data returned by a join and MAPs all that data to some entity's property. This is extremely useful when you want to select some data and map it to some virtual property. It will assume that there is a single row of selecting data, and mapped result will be a single selected value. You also need to specify an alias of the joined data. Optionally, you can add condition and parameters used in condition.
INNER JOINs table, SELECTs the data returned by a join and MAPs all that data to some entity's property. This is extremely useful when you want to select some data and map it to some virtual property. It will assume that there is a single row of selecting data, and mapped result will be a single selected value. You also need to specify an alias of the joined data. Optionally, you can add condition and parameters used in condition.
method innerJoinAndSelect
innerJoinAndSelect: { ( subQueryFactory: ( qb: SelectQueryBuilder<any> ) => SelectQueryBuilder<any>, alias: string, condition?: string, parameters?: ObjectLiteral ): this; ( property: string, alias: string, condition?: string, parameters?: ObjectLiteral ): this; ( entity: string | Function, alias: string, condition?: string, parameters?: ObjectLiteral ): this; ( tableName: string, alias: string, condition?: string, parameters?: ObjectLiteral ): this;};INNER JOINs given subquery and adds all selection properties to SELECT.. You also need to specify an alias of the joined data. Optionally, you can add condition and parameters used in condition.
INNER JOINs entity's property and adds all selection properties to SELECT. Given entity property should be a relation. You also need to specify an alias of the joined data. Optionally, you can add condition and parameters used in condition.
INNER JOINs entity and adds all selection properties to SELECT. You also need to specify an alias of the joined data. Optionally, you can add condition and parameters used in condition.
INNER JOINs table and adds all selection properties to SELECT. You also need to specify an alias of the joined data. Optionally, you can add condition and parameters used in condition.
method join
protected join: ( direction: 'INNER' | 'LEFT', entityOrProperty: | string | Function | ((qb: SelectQueryBuilder<any>) => SelectQueryBuilder<any>), aliasName: string, condition?: string, parameters?: ObjectLiteral, mapToProperty?: string, isMappingMany?: boolean, mapAsEntity?: Function | string) => void;method leftJoin
leftJoin: { ( subQueryFactory: ( qb: SelectQueryBuilder<any> ) => SelectQueryBuilder<any>, alias: string, condition?: string, parameters?: ObjectLiteral ): this; ( property: string, alias: string, condition?: string, parameters?: ObjectLiteral ): this; ( entity: string | Function, alias: string, condition?: string, parameters?: ObjectLiteral ): this; ( tableName: string, alias: string, condition?: string, parameters?: ObjectLiteral ): this;};LEFT JOINs (without selection) given subquery. You also need to specify an alias of the joined data. Optionally, you can add condition and parameters used in condition.
LEFT JOINs (without selection) entity's property. Given entity property should be a relation. You also need to specify an alias of the joined data. Optionally, you can add condition and parameters used in condition.
LEFT JOINs (without selection) entity's table. You also need to specify an alias of the joined data. Optionally, you can add condition and parameters used in condition.
LEFT JOINs (without selection) given table. You also need to specify an alias of the joined data. Optionally, you can add condition and parameters used in condition.
method leftJoinAndMapMany
leftJoinAndMapMany: { ( mapToProperty: string, subQueryFactory: ( qb: SelectQueryBuilder<any> ) => SelectQueryBuilder<any>, alias: string, condition?: string, parameters?: ObjectLiteral ): this; ( mapToProperty: string, property: string, alias: string, condition?: string, parameters?: ObjectLiteral ): this; ( mapToProperty: string, entity: string | Function, alias: string, condition?: string, parameters?: ObjectLiteral ): this; ( mapToProperty: string, tableName: string, alias: string, condition?: string, parameters?: ObjectLiteral ): this;};LEFT JOINs given subquery, SELECTs the data returned by a join and MAPs all that data to some entity's property. This is extremely useful when you want to select some data and map it to some virtual property. It will assume that there are multiple rows of selecting data, and mapped result will be an array. Given entity property should be a relation. You also need to specify an alias of the joined data. Optionally, you can add condition and parameters used in condition.
LEFT JOINs entity's property, SELECTs the data returned by a join and MAPs all that data to some entity's property. This is extremely useful when you want to select some data and map it to some virtual property. It will assume that there are multiple rows of selecting data, and mapped result will be an array. Given entity property should be a relation. You also need to specify an alias of the joined data. Optionally, you can add condition and parameters used in condition.
LEFT JOINs entity's table, SELECTs the data returned by a join and MAPs all that data to some entity's property. This is extremely useful when you want to select some data and map it to some virtual property. It will assume that there are multiple rows of selecting data, and mapped result will be an array. You also need to specify an alias of the joined data. Optionally, you can add condition and parameters used in condition.
LEFT JOINs table, SELECTs the data returned by a join and MAPs all that data to some entity's property. This is extremely useful when you want to select some data and map it to some virtual property. It will assume that there are multiple rows of selecting data, and mapped result will be an array. You also need to specify an alias of the joined data. Optionally, you can add condition and parameters used in condition.
method leftJoinAndMapOne
leftJoinAndMapOne: { ( mapToProperty: string, subQueryFactory: ( qb: SelectQueryBuilder<any> ) => SelectQueryBuilder<any>, alias: string, condition?: string, parameters?: ObjectLiteral, mapAsEntity?: Function | string ): this; ( mapToProperty: string, property: string, alias: string, condition?: string, parameters?: ObjectLiteral ): this; ( mapToProperty: string, entity: string | Function, alias: string, condition?: string, parameters?: ObjectLiteral ): this; ( mapToProperty: string, tableName: string, alias: string, condition?: string, parameters?: ObjectLiteral ): this;};LEFT JOINs given subquery, SELECTs the data returned by a join and MAPs all that data to some entity's property. This is extremely useful when you want to select some data and map it to some virtual property. It will assume that there is a single row of selecting data, and mapped result will be a single selected value. Given entity property should be a relation. You also need to specify an alias of the joined data. Optionally, you can add condition and parameters used in condition.
LEFT JOINs entity's property, SELECTs the data returned by a join and MAPs all that data to some entity's property. This is extremely useful when you want to select some data and map it to some virtual property. It will assume that there is a single row of selecting data, and mapped result will be a single selected value. Given entity property should be a relation. You also need to specify an alias of the joined data. Optionally, you can add condition and parameters used in condition.
LEFT JOINs entity's table, SELECTs the data returned by a join and MAPs all that data to some entity's property. This is extremely useful when you want to select some data and map it to some virtual property. It will assume that there is a single row of selecting data, and mapped result will be a single selected value. You also need to specify an alias of the joined data. Optionally, you can add condition and parameters used in condition.
LEFT JOINs table, SELECTs the data returned by a join and MAPs all that data to some entity's property. This is extremely useful when you want to select some data and map it to some virtual property. It will assume that there is a single row of selecting data, and mapped result will be a single selected value. You also need to specify an alias of the joined data. Optionally, you can add condition and parameters used in condition.
method leftJoinAndSelect
leftJoinAndSelect: { ( subQueryFactory: ( qb: SelectQueryBuilder<any> ) => SelectQueryBuilder<any>, alias: string, condition?: string, parameters?: ObjectLiteral ): this; ( property: string, alias: string, condition?: string, parameters?: ObjectLiteral ): this; ( entity: string | Function, alias: string, condition?: string, parameters?: ObjectLiteral ): this; ( tableName: string, alias: string, condition?: string, parameters?: ObjectLiteral ): this;};LEFT JOINs given subquery and adds all selection properties to SELECT.. You also need to specify an alias of the joined data. Optionally, you can add condition and parameters used in condition.
LEFT JOINs entity's property and adds all selection properties to SELECT. Given entity property should be a relation. You also need to specify an alias of the joined data. Optionally, you can add condition and parameters used in condition.
LEFT JOINs entity and adds all selection properties to SELECT. You also need to specify an alias of the joined data. Optionally, you can add condition and parameters used in condition.
LEFT JOINs table and adds all selection properties to SELECT. You also need to specify an alias of the joined data. Optionally, you can add condition and parameters used in condition.
method limit
limit: (limit?: number) => this;Sets LIMIT - maximum number of rows to be selected. NOTE that it may not work as you expect if you are using joins. If you want to implement pagination, and you are having join in your query, then use the take method instead.
Parameter limit
method loadAllRelationIds
loadAllRelationIds: (options?: { relations?: string[]; disableMixedMap?: boolean;}) => this;Loads all relation ids for all relations of the selected entity. All relation ids will be mapped to relation property themself. If array of strings is given then loads only relation ids of the given properties.
Parameter options
Parameter
options.relations
Parameter
options.disableMixedMap
method loadRawResults
protected loadRawResults: (queryRunner: QueryRunner) => Promise<any>;Loads raw results from the database.
Parameter queryRunner
method loadRelationIdAndMap
loadRelationIdAndMap: { ( mapToProperty: string, relationName: string, options?: { disableMixedMap?: boolean } ): this; ( mapToProperty: string, relationName: string, alias: string, queryBuilderFactory: ( qb: SelectQueryBuilder<any> ) => SelectQueryBuilder<any> ): this;};LEFT JOINs relation id and maps it into some entity's property. Optionally, you can add condition and parameters used in condition.
method maxExecutionTime
maxExecutionTime: (milliseconds: number) => this;Set max execution time.
Parameter milliseconds
method mergeExpressionMap
protected mergeExpressionMap: ( expressionMap: Partial<QueryExpressionMap>) => this;Merges into expression map given expression map properties.
Parameter expressionMap
method obtainQueryRunner
protected obtainQueryRunner: () => QueryRunner;Creates a query builder used to execute sql queries inside this query builder.
method offset
offset: (offset?: number) => this;Sets OFFSET - selection offset. NOTE that it may not work as you expect if you are using joins. If you want to implement pagination, and you are having join in your query, then use the skip method instead.
Parameter offset
method orderBy
orderBy: { (): this; ( sort: string, order?: 'ASC' | 'DESC', nulls?: 'NULLS FIRST' | 'NULLS LAST' ): this; (order: OrderByCondition): this;};Sets ORDER BY condition in the query builder. If you had previously ORDER BY expression defined, calling this function will override previously set ORDER BY conditions.
Calling order by without order set will remove all previously set order bys.
Sets ORDER BY condition in the query builder. If you had previously ORDER BY expression defined, calling this function will override previously set ORDER BY conditions.
method orHaving
orHaving: (having: string, parameters?: ObjectLiteral) => this;Adds new OR HAVING condition in the query builder. Additionally you can add parameters used in where expression.
Parameter having
Parameter parameters
method orWhere
orWhere: ( where: | string | ObjectLiteral | Brackets | ObjectLiteral[] | ((qb: this) => string), parameters?: ObjectLiteral) => this;Adds new OR WHERE condition in the query builder. Additionally you can add parameters used in where expression.
Parameter where
Parameter parameters
method orWhereExists
orWhereExists: (subQuery: SelectQueryBuilder<any>) => this;Adds a new OR where EXISTS clause
Parameter subQuery
method orWhereInIds
orWhereInIds: (ids: any | any[]) => this;Adds new OR WHERE with conditions for the given ids.
Ids are mixed. It means if you have single primary key you can pass a simple id values, for example [1, 2, 3]. If you have multiple primary keys you need to pass object with property names and values specified, for example [{ firstId: 1, secondId: 2 }, { firstId: 2, secondId: 3 }, ...]
Parameter ids
method select
select: { (): this; ( selection: (qb: SelectQueryBuilder<any>) => SelectQueryBuilder<any>, selectionAliasName?: string ): this; (selection: string, selectionAliasName?: string): this; (selection: string[]): this;};Creates SELECT query. Replaces all previous selections if they exist.
Creates SELECT query and selects given data. Replaces all previous selections if they exist.
method setFindOptions
setFindOptions: (findOptions: FindManyOptions<Entity>) => this;method setLock
setLock: { (lockMode: 'optimistic', lockVersion: number | Date): this; ( lockMode: | 'pessimistic_read' | 'pessimistic_write' | 'dirty_read' | 'for_no_key_update' | 'for_key_share', lockVersion?: undefined, lockTables?: string[] ): this;};Sets locking mode.
method setOnLocked
setOnLocked: (onLocked: 'nowait' | 'skip_locked') => this;Sets lock handling by adding NO WAIT or SKIP LOCKED.
Parameter onLocked
method setOption
setOption: (option: SelectQueryBuilderOption) => this;Sets extra options that can be used to configure how query builder works.
Parameter option
method skip
skip: (skip?: number) => this;Sets number of entities to skip.
Parameter skip
method stream
stream: () => Promise<ReadStream>;Executes built SQL query and returns raw data stream.
method subQuery
subQuery: () => SelectQueryBuilder<any>;Creates a subquery - query that can be used inside other queries.
method take
take: (take?: number) => this;Sets maximal number of entities to take.
Parameter take
method timeTravelQuery
timeTravelQuery: (timeTravelFn?: string | boolean) => this;Enables time travelling for the current query (only supported by cockroach currently)
Parameter timeTravelFn
method useIndex
useIndex: (indexes: string | string[]) => this;Set certain index(es) to be used by the query.
Parameter indexes
Name(s) of index(es) to be used.
method where
where: ( where: | string | ObjectLiteral | Brackets | ObjectLiteral[] | ((qb: this) => string), parameters?: ObjectLiteral) => this;Sets WHERE condition in the query builder. If you had previously WHERE expression defined, calling this function will override previously set WHERE conditions. Additionally you can add parameters used in where expression.
Parameter where
Parameter parameters
method whereExists
whereExists: (subQuery: SelectQueryBuilder<any>) => this;Sets a new where EXISTS clause
Parameter subQuery
method whereInIds
whereInIds: (ids: any | any[]) => this;Adds new AND WHERE with conditions for the given ids.
Ids are mixed. It means if you have single primary key you can pass a simple id values, for example [1, 2, 3]. If you have multiple primary keys you need to pass object with property names and values specified, for example [{ firstId: 1, secondId: 2 }, { firstId: 2, secondId: 3 }, ...]
Parameter ids
method withDeleted
withDeleted: () => this;Disables the global condition of "non-deleted" for the entity with delete date columns.
class SimpleConsoleLogger
class SimpleConsoleLogger extends AbstractLogger {}Performs logging of the events in TypeORM. This version of logger uses console to log events and does not use syntax highlighting.
method writeLog
protected writeLog: ( level: LogLevel, logMessage: LogMessage | LogMessage[], queryRunner?: QueryRunner) => void;Write log to specific output.
Parameter level
Parameter logMessage
Parameter queryRunner
class SubjectRemovedAndUpdatedError
class SubjectRemovedAndUpdatedError extends TypeORMError {}Thrown when same object is scheduled for remove and updation at the same time.
constructor
constructor(subject: Subject);class SubjectWithoutIdentifierError
class SubjectWithoutIdentifierError extends TypeORMError {}Thrown when operation is going to be executed on a subject without identifier. This error should never be thrown, however it still presents to prevent user from updation or removing the whole table. If this error occurs still, it most probably is an ORM internal problem which must be reported and fixed.
constructor
constructor(subject: Subject);class Table
class Table {}Table in the database represented in this class.
constructor
constructor(options?: TableOptions);property "@instanceof"
readonly '@instanceof': Symbol;property checks
checks: TableCheck[];Table check constraints.
property columns
columns: TableColumn[];Table columns.
property comment
comment?: string;Table comment. Not supported by all database types.
property database
database?: string;Database name that this table resides in if it applies.
property engine
engine?: string;Table engine.
property exclusions
exclusions: TableExclusion[];Table exclusion constraints.
property foreignKeys
foreignKeys: TableForeignKey[];Table foreign keys.
property indices
indices: TableIndex[];Table indices.
property justCreated
justCreated: boolean;Indicates if table was just created. This is needed, for example to check if we need to skip primary keys creation for new tables.
property name
name: string;May contain database name, schema name and table name, unless they're the current database.
E.g. myDB.mySchema.myTable
property primaryColumns
readonly primaryColumns: TableColumn[];property schema
schema?: string;Schema name that this table resides in if it applies.
property uniques
uniques: TableUnique[];Table unique constraints.
property withoutRowid
withoutRowid?: boolean;Enables Sqlite "WITHOUT ROWID" modifier for the "CREATE TABLE" statement
method addCheckConstraint
addCheckConstraint: (checkConstraint: TableCheck) => void;Adds check constraint.
Parameter checkConstraint
method addColumn
addColumn: (column: TableColumn) => void;Add column and creates its constraints.
Parameter column
method addExclusionConstraint
addExclusionConstraint: (exclusionConstraint: TableExclusion) => void;Adds exclusion constraint.
Parameter exclusionConstraint
method addForeignKey
addForeignKey: (foreignKey: TableForeignKey) => void;Adds foreign keys.
Parameter foreignKey
method addIndex
addIndex: (index: TableIndex, isMysql?: boolean) => void;Adds index.
Parameter index
Parameter isMysql
method addUniqueConstraint
addUniqueConstraint: (uniqueConstraint: TableUnique) => void;Adds unique constraint.
Parameter uniqueConstraint
method clone
clone: () => Table;Clones this table to a new table with all properties cloned.
method create
static create: (entityMetadata: EntityMetadata, driver: Driver) => Table;Creates table from a given entity metadata.
Parameter entityMetadata
Parameter driver
method findColumnByName
findColumnByName: (name: string) => TableColumn | undefined;method findColumnChecks
findColumnChecks: (column: TableColumn) => TableCheck[];Returns all column checks.
Parameter column
method findColumnForeignKeys
findColumnForeignKeys: (column: TableColumn) => TableForeignKey[];Returns all column foreign keys.
Parameter column
method findColumnIndices
findColumnIndices: (column: TableColumn) => TableIndex[];Returns all column indices.
Parameter column
method findColumnUniques
findColumnUniques: (column: TableColumn) => TableUnique[];Returns all column uniques.
Parameter column
method removeCheckConstraint
removeCheckConstraint: (removedCheck: TableCheck) => void;Removes check constraint.
Parameter removedCheck
method removeColumn
removeColumn: (column: TableColumn) => void;Remove column and its constraints.
Parameter column
method removeExclusionConstraint
removeExclusionConstraint: (removedExclusion: TableExclusion) => void;Removes exclusion constraint.
Parameter removedExclusion
method removeForeignKey
removeForeignKey: (removedForeignKey: TableForeignKey) => void;Removes foreign key.
Parameter removedForeignKey
method removeIndex
removeIndex: (tableIndex: TableIndex, isMysql?: boolean) => void;Removes index.
Parameter tableIndex
Parameter isMysql
method removeUniqueConstraint
removeUniqueConstraint: (removedUnique: TableUnique) => void;Removes unique constraint.
Parameter removedUnique
class TableCheck
class TableCheck {}Database's table check constraint stored in this class.
constructor
constructor(options: TableCheckOptions);property "@instanceof"
readonly '@instanceof': Symbol;property columnNames
columnNames?: string[];Column that contains this constraint.
property expression
expression?: string;Check expression.
property name
name?: string;Constraint name.
method clone
clone: () => TableCheck;Creates a new copy of this constraint with exactly same properties.
method create
static create: (checkMetadata: CheckMetadata) => TableCheck;Creates checks from the check metadata object.
Parameter checkMetadata
class TableColumn
class TableColumn {}Table's columns in the database represented in this class.
constructor
constructor(options?: TableColumnOptions);property "@instanceof"
readonly '@instanceof': Symbol;property asExpression
asExpression?: string;Generated column expression.
property charset
charset?: string;Defines column character set.
property collation
collation?: string;Defines column collation.
property comment
comment?: string;Column's comment.
property default
default?: any;Column's default value.
property enum
enum?: string[];Array of possible enumerated values.
property enumName
enumName?: string;Exact name of enum
property generatedIdentity
generatedIdentity?: 'ALWAYS' | 'BY DEFAULT';Identity column type. Supports only in Postgres 10+.
property generatedType
generatedType?: 'VIRTUAL' | 'STORED';Generated column type.
property generationStrategy
generationStrategy?: 'uuid' | 'rowid' | 'increment' | 'identity';Specifies generation strategy if this column will use auto increment.
rowidoption supported only in CockroachDB.
property isArray
isArray: boolean;Indicates if column stores array.
property isGenerated
isGenerated: boolean;Indicates if column is auto-generated sequence.
property isNullable
isNullable: boolean;Indicates if column is NULL, or is NOT NULL in the database.
property isPrimary
isPrimary: boolean;Indicates if column is a primary key.
property isUnique
isUnique: boolean;Indicates if column has unique value.
property length
length: string;Column type's length. Used only on some column types. For example type = "string" and length = "100" means that ORM will create a column with type varchar(100).
property name
name: string;Column name.
property onUpdate
onUpdate?: string;ON UPDATE trigger. Works only for MySQL.
property precision
precision?: number;The precision for a decimal (exact numeric) column (applies only for decimal column), which is the maximum number of digits that are stored for the values.
property primaryKeyConstraintName
primaryKeyConstraintName?: string;Name of the primary key constraint for primary column.
property scale
scale?: number;The scale for a decimal (exact numeric) column (applies only for decimal column), which represents the number of digits to the right of the decimal point and must not be greater than precision.
property spatialFeatureType
spatialFeatureType?: string;Spatial Feature Type (Geometry, Point, Polygon, etc.)
property srid
srid?: number;SRID (Spatial Reference ID (EPSG code))
property type
type: string;Column type.
property unsigned
unsigned: boolean;Puts UNSIGNED attribute on to numeric column. Works only for MySQL.
method clone
clone: () => TableColumn;Clones this column to a new column with exact same properties as this column has.
class TableExclusion
class TableExclusion {}Database's table exclusion constraint stored in this class.
constructor
constructor(options: TableExclusionOptions);property "@instanceof"
readonly '@instanceof': Symbol;property deferrable
deferrable?: string;Set this exclusion constraint as "DEFERRABLE" e.g. check constraints at start or at the end of a transaction
property expression
expression?: string;Exclusion expression.
property name
name?: string;Constraint name.
method clone
clone: () => TableExclusion;Creates a new copy of this constraint with exactly same properties.
method create
static create: (exclusionMetadata: ExclusionMetadata) => TableExclusion;Creates exclusions from the exclusion metadata object.
Parameter exclusionMetadata
class TableForeignKey
class TableForeignKey {}Foreign key from the database stored in this class.
constructor
constructor(options: TableForeignKeyOptions);property "@instanceof"
readonly '@instanceof': Symbol;property columnNames
columnNames: string[];Column names which included by this foreign key.
property deferrable
deferrable?: string;Set this foreign key constraint as "DEFERRABLE" e.g. check constraints at start or at the end of a transaction
property name
name?: string;Name of the foreign key constraint.
property onDelete
onDelete?: string;"ON DELETE" of this foreign key, e.g. what action database should perform when referenced stuff is being deleted.
property onUpdate
onUpdate?: string;"ON UPDATE" of this foreign key, e.g. what action database should perform when referenced stuff is being updated.
property referencedColumnNames
referencedColumnNames: string[];Column names which included by this foreign key.
property referencedDatabase
referencedDatabase?: string;Database of Table referenced in the foreign key.
property referencedSchema
referencedSchema?: string;Database of Table referenced in the foreign key.
property referencedTableName
referencedTableName: string;Table referenced in the foreign key.
method clone
clone: () => TableForeignKey;Creates a new copy of this foreign key with exactly same properties.
method create
static create: (metadata: ForeignKeyMetadata, driver: Driver) => TableForeignKey;Creates a new table foreign key from the given foreign key metadata.
Parameter metadata
Parameter driver
class TableIndex
class TableIndex {}Database's table index stored in this class.
constructor
constructor(options: TableIndexOptions);property "@instanceof"
readonly '@instanceof': Symbol;property columnNames
columnNames: string[];Columns included in this index.
property isConcurrent
isConcurrent: boolean;Create the index using the CONCURRENTLY modifier Works only in postgres.
property isFulltext
isFulltext: boolean;The FULLTEXT modifier indexes the entire column and does not allow prefixing. Works only in MySQL.
property isNullFiltered
isNullFiltered: boolean;NULL_FILTERED indexes are particularly useful for indexing sparse columns, where most rows contain a NULL value. In these cases, the NULL_FILTERED index can be considerably smaller and more efficient to maintain than a normal index that includes NULL values.
Works only in Spanner.
property isSpatial
isSpatial: boolean;The SPATIAL modifier indexes the entire column and does not allow indexed columns to contain NULL values. Works only in MySQL.
property isUnique
isUnique: boolean;Indicates if this index is unique.
property name
name?: string;Index name.
property parser
parser?: string;Fulltext parser. Works only in MySQL.
property type
type?: TableIndexTypes;The
typeoption defines the type of the index being created. Supported types include B-tree, Hash, GiST, SP-GiST, GIN, and BRIN This option is only applicable in PostgreSQL.
property where
where: string;Index filter condition.
method clone
clone: () => TableIndex;Creates a new copy of this index with exactly same properties.
method create
static create: (indexMetadata: IndexMetadata) => TableIndex;Creates index from the index metadata object.
Parameter indexMetadata
class TableUnique
class TableUnique {}Database's table unique constraint stored in this class.
constructor
constructor(options: TableUniqueOptions);property "@instanceof"
readonly '@instanceof': Symbol;property columnNames
columnNames: string[];Columns that contains this constraint.
property deferrable
deferrable?: string;Set this foreign key constraint as "DEFERRABLE" e.g. check constraints at start or at the end of a transaction
property name
name?: string;Constraint name.
method clone
clone: () => TableUnique;Creates a new copy of this constraint with exactly same properties.
method create
static create: (uniqueMetadata: UniqueMetadata) => TableUnique;Creates unique from the unique metadata object.
Parameter uniqueMetadata
class TransactionAlreadyStartedError
class TransactionAlreadyStartedError extends TypeORMError {}Thrown when transaction is already started and user tries to run it again.
constructor
constructor();class TransactionNotStartedError
class TransactionNotStartedError extends TypeORMError {}Thrown when transaction is not started yet and user tries to run commit or rollback.
constructor
constructor();class TreeRepository
class TreeRepository<Entity extends ObjectLiteral> extends Repository<Entity> {}Repository with additional functions to work with trees.
See Also
Repository
method countAncestors
countAncestors: (entity: Entity) => Promise<number>;Gets number of ancestors of the entity.
Parameter entity
method countDescendants
countDescendants: (entity: Entity) => Promise<number>;Gets number of descendants of the entity.
Parameter entity
method createAncestorsQueryBuilder
createAncestorsQueryBuilder: ( alias: string, closureTableAlias: string, entity: Entity) => SelectQueryBuilder<Entity>;Creates a query builder used to get ancestors of the entities in the tree.
Parameter alias
Parameter closureTableAlias
Parameter entity
method createDescendantsQueryBuilder
createDescendantsQueryBuilder: ( alias: string, closureTableAlias: string, entity: Entity) => SelectQueryBuilder<Entity>;Creates a query builder used to get descendants of the entities in a tree.
Parameter alias
Parameter closureTableAlias
Parameter entity
method findAncestors
findAncestors: (entity: Entity, options?: FindTreeOptions) => Promise<Entity[]>;Gets all parents (ancestors) of the given entity. Returns them all in a flat array.
Parameter entity
Parameter options
method findAncestorsTree
findAncestorsTree: ( entity: Entity, options?: FindTreeOptions) => Promise<Entity>;Gets all parents (ancestors) of the given entity. Returns them in a tree - nested into each other.
Parameter entity
Parameter options
method findDescendants
findDescendants: ( entity: Entity, options?: FindTreeOptions) => Promise<Entity[]>;Gets all children (descendants) of the given entity. Returns them all in a flat array.
Parameter entity
Parameter options
method findDescendantsTree
findDescendantsTree: ( entity: Entity, options?: FindTreeOptions) => Promise<Entity>;Gets all children (descendants) of the given entity. Returns them in a tree - nested into each other.
Parameter entity
Parameter options
method findRoots
findRoots: (options?: FindTreeOptions) => Promise<Entity[]>;Roots are entities that have no ancestors. Finds them all.
Parameter options
method findTrees
findTrees: (options?: FindTreeOptions) => Promise<Entity[]>;Gets complete trees for all roots in the table.
Parameter options
class TreeRepositoryNotSupportedError
class TreeRepositoryNotSupportedError extends TypeORMError {}constructor
constructor(driver: Driver);class TreeRepositoryUtils
class TreeRepositoryUtils {}Provides utilities for manipulating tree structures.
method buildChildrenEntityTree
static buildChildrenEntityTree: ( metadata: EntityMetadata, entity: any, entities: any[], relationMaps: { id: any; parentId: any }[], options: FindTreesOptions & { depth: number }) => void;method buildParentEntityTree
static buildParentEntityTree: ( metadata: EntityMetadata, entity: any, entities: any[], relationMaps: { id: any; parentId: any }[]) => void;method createRelationMaps
static createRelationMaps: ( manager: EntityManager, metadata: EntityMetadata, alias: string, rawResults: any[]) => { id: any; parentId: any }[];class TypeORMError
class TypeORMError extends Error {}constructor
constructor(message?: string);property name
readonly name: string;class UpdateQueryBuilder
class UpdateQueryBuilder<Entity extends ObjectLiteral> extends QueryBuilder<Entity> implements WhereExpressionBuilder {}Allows to build complex sql queries in a fashion way and execute those queries.
constructor
constructor( connectionOrQueryBuilder: DataSource | QueryBuilder<any>, queryRunner?: QueryRunner);property "@instanceof"
readonly '@instanceof': Symbol;method addOrderBy
addOrderBy: ( sort: string, order?: 'ASC' | 'DESC', nulls?: 'NULLS FIRST' | 'NULLS LAST') => this;Adds ORDER BY condition in the query builder.
Parameter sort
Parameter order
Parameter nulls
method andWhere
andWhere: ( where: | string | ObjectLiteral | Brackets | ObjectLiteral[] | ((qb: this) => string), parameters?: ObjectLiteral) => this;Adds new AND WHERE condition in the query builder. Additionally you can add parameters used in where expression.
Parameter where
Parameter parameters
method andWhereInIds
andWhereInIds: (ids: any | any[]) => this;Adds new AND WHERE with conditions for the given ids.
Parameter ids
method createLimitExpression
protected createLimitExpression: () => string;Creates "LIMIT" parts of SQL query.
method createOrderByExpression
protected createOrderByExpression: () => string;Creates "ORDER BY" part of SQL query.
method createUpdateExpression
protected createUpdateExpression: () => string;Creates UPDATE express used to perform insert query.
method execute
execute: () => Promise<UpdateResult>;Executes sql generated by query builder and returns raw database results.
method getQuery
getQuery: () => string;Gets generated SQL query without parameters being replaced.
method getValueSet
protected getValueSet: () => ObjectLiteral;Gets array of values need to be inserted into the target table.
method limit
limit: (limit?: number) => this;Sets LIMIT - maximum number of rows to be selected.
Parameter limit
method orderBy
orderBy: { (): this; ( sort: string, order?: 'ASC' | 'DESC', nulls?: 'NULLS FIRST' | 'NULLS LAST' ): this; (order: OrderByCondition): this;};Sets ORDER BY condition in the query builder. If you had previously ORDER BY expression defined, calling this function will override previously set ORDER BY conditions.
Calling order by without order set will remove all previously set order bys.
Sets ORDER BY condition in the query builder. If you had previously ORDER BY expression defined, calling this function will override previously set ORDER BY conditions.
method orWhere
orWhere: ( where: | string | ObjectLiteral | Brackets | ObjectLiteral[] | ((qb: this) => string), parameters?: ObjectLiteral) => this;Adds new OR WHERE condition in the query builder. Additionally you can add parameters used in where expression.
Parameter where
Parameter parameters
method orWhereInIds
orWhereInIds: (ids: any | any[]) => this;Adds new OR WHERE with conditions for the given ids.
Parameter ids
method output
output: { (columns: string[]): this; (output: string): this; (output: string | string[]): this;};Optional returning/output clause. This will return given column values.
Optional returning/output clause. Returning is a SQL string containing returning statement.
Optional returning/output clause.
method returning
returning: { (columns: string[]): this; (returning: string): this; (returning: string | string[]): this;};Optional returning/output clause. This will return given column values.
Optional returning/output clause. Returning is a SQL string containing returning statement.
Optional returning/output clause.
method set
set: (values: QueryDeepPartialEntity<Entity>) => this;Values needs to be updated.
Parameter values
method updateEntity
updateEntity: (enabled: boolean) => this;Indicates if entity must be updated after update operation. This may produce extra query or use RETURNING / OUTPUT statement (depend on database). Enabled by default.
Parameter enabled
method where
where: ( where: | string | ObjectLiteral | Brackets | ObjectLiteral[] | ((qb: this) => string), parameters?: ObjectLiteral) => this;Sets WHERE condition in the query builder. If you had previously WHERE expression defined, calling this function will override previously set WHERE conditions. Additionally you can add parameters used in where expression.
Parameter where
Parameter parameters
method whereEntity
whereEntity: (entity: Entity | Entity[]) => this;Indicates if entity must be updated after update operation. This may produce extra query or use RETURNING / OUTPUT statement (depend on database). Enabled by default.
Parameter entity
method whereInIds
whereInIds: (ids: any | any[]) => this;Sets WHERE condition in the query builder with a condition for the given ids. If you had previously WHERE expression defined, calling this function will override previously set WHERE conditions.
Parameter ids
class UpdateResult
class UpdateResult {}Result object returned by UpdateQueryBuilder execution.
property affected
affected?: number;Number of affected rows/documents Not all drivers support this
property generatedMaps
generatedMaps: ObjectLiteral[];Generated values returned by a database. Has entity-like structure (not just column database name and values).
property raw
raw: any;Raw SQL result returned by executed query.
method from
static from: (queryResult: QueryResult) => UpdateResult;class UpdateValuesMissingError
class UpdateValuesMissingError extends TypeORMError {}constructor
constructor();class UsingJoinColumnIsNotAllowedError
class UsingJoinColumnIsNotAllowedError extends TypeORMError {}constructor
constructor(entityMetadata: EntityMetadata, relation: RelationMetadata);class UsingJoinColumnOnlyOnOneSideAllowedError
class UsingJoinColumnOnlyOnOneSideAllowedError extends TypeORMError {}constructor
constructor(entityMetadata: EntityMetadata, relation: RelationMetadata);class UsingJoinTableIsNotAllowedError
class UsingJoinTableIsNotAllowedError extends TypeORMError {}constructor
constructor(entityMetadata: EntityMetadata, relation: RelationMetadata);class UsingJoinTableOnlyOnOneSideAllowedError
class UsingJoinTableOnlyOnOneSideAllowedError extends TypeORMError {}constructor
constructor(entityMetadata: EntityMetadata, relation: RelationMetadata);class View
class View {}View in the database represented in this class.
constructor
constructor(options?: ViewOptions);property "@instanceof"
readonly '@instanceof': Symbol;property database
database?: string;Database name that this view resides in if it applies.
property expression
expression: string | ((dataSource: DataSource) => SelectQueryBuilder<any>);View definition.
property indices
indices: TableIndex[];View Indices
property materialized
materialized: boolean;Indicates if view is materialized.
property name
name: string;View name
property schema
schema?: string;Schema name that this view resides in if it applies.
method addIndex
addIndex: (index: TableIndex) => void;Add index
Parameter index
method clone
clone: () => View;Clones this table to a new table with all properties cloned.
method create
static create: (entityMetadata: EntityMetadata, driver: Driver) => View;Creates view from a given entity metadata.
Parameter entityMetadata
Parameter driver
method removeIndex
removeIndex: (viewIndex: TableIndex) => void;Remove index
Parameter viewIndex
Interfaces
interface AfterQueryEvent
interface AfterQueryEvent extends QueryEvent {}property error
error?: any;The error thrown if the query was unsuccessful.
property executionTime
executionTime?: number;The duration of the query execution, in milliseconds.
property rawResults
rawResults?: any;The raw results from the database if the query was successful.
property success
success: boolean;Whether the query was successful.
interface BeforeQueryEvent
interface BeforeQueryEvent extends QueryEvent {}interface ColumnOptions
interface ColumnOptions extends ColumnCommonOptions {}Describes all column's options.
property array
array?: boolean;Indicates if this column is an array. Can be simply set to true or array length can be specified. Supported only by postgres.
property asExpression
asExpression?: string;Generated column expression.
property charset
charset?: string;Defines a column character set. Not supported by all database types.
property collation
collation?: string;Defines a column collation.
property comment
comment?: string;Column comment. Not supported by all database types.
property default
default?: any;Default database value.
property enum
enum?: (string | number)[] | Object;Array of possible enumerated values.
property enumName
enumName?: string;Exact name of enum
property foreignKeyConstraintName
foreignKeyConstraintName?: string;If this column is foreign key then this specifies the name for it.
property generatedIdentity
generatedIdentity?: 'ALWAYS' | 'BY DEFAULT';Identity column type. Supports only in Postgres 10+.
property generatedType
generatedType?: 'VIRTUAL' | 'STORED';Generated column type.
property hstoreType
hstoreType?: 'object' | 'string';Return type of HSTORE column. Returns value as string or as object.
property insert
insert?: boolean;Indicates if column is inserted by default. Default value is "true".
property length
length?: string | number;Column type's length. Used only on some column types. For example type = "string" and length = "100" means that ORM will create a column with type varchar(100).
property name
name?: string;Column name in the database.
property nullable
nullable?: boolean;Indicates if column's value can be set to NULL. Default value is "false".
property onUpdate
onUpdate?: string;ON UPDATE trigger. Works only for MySQL.
property precision
precision?: number | null;The precision for a decimal (exact numeric) column (applies only for decimal column), which is the maximum number of digits that are stored for the values.
property primary
primary?: boolean;Indicates if this column is a primary key. Same can be achieved when
@PrimaryColumndecorator is used.
property primaryKeyConstraintName
primaryKeyConstraintName?: string;If this column is primary key then this specifies the name for it.
property query
query?: (alias: string) => string;Query to be used to populate the column data. This query is used when generating the relational db script. The query function is called with the current entities alias either defined by the Entity Decorator or automatically
See Also
https://typeorm.io/decorator-reference#virtualcolumn for more details.
property scale
scale?: number;The scale for a decimal (exact numeric) column (applies only for decimal column), which represents the number of digits to the right of the decimal point and must not be greater than precision.
property select
select?: boolean;Indicates if column is always selected by QueryBuilder and find operations. Default value is "true".
property spatialFeatureType
spatialFeatureType?: string;Spatial Feature Type (Geometry, Point, Polygon, etc.)
property srid
srid?: number;SRID (Spatial Reference ID (EPSG code))
property transformer
transformer?: ValueTransformer | ValueTransformer[];Specifies a value transformer that is to be used to (un)marshal this column when reading or writing to the database.
property type
type?: ColumnType;Column type. Must be one of the value from the ColumnTypes class.
property unique
unique?: boolean;Specifies if column's value must be unique or not.
property unsigned
unsigned?: boolean;Puts UNSIGNED attribute on to numeric column. Works only for MySQL.
property update
update?: boolean;Indicates if column value is updated by "save" operation. If false, you'll be able to write this value only when you first time insert the object. Default value is "true".
property utc
utc?: boolean;Indicates if date values should be stored and retrieved in UTC timezone instead of local timezone. Only applies to "date" column type. Default value is "false" (uses local timezone for backward compatibility).
Example 1
\@Column({ type: "date", utc: true })birthDate: Date
interface Driver
interface Driver {}Driver organizes TypeORM communication with specific database management system.
property compareTableIndexTypes
compareTableIndexTypes?: (indexA: IndexMetadata, indexB: TableIndex) => boolean;Returns true if both indexes types are equivalent
property cteCapabilities
cteCapabilities: CteCapabilities;property database
database?: string;Database name used to perform all write queries.
todo: probably move into query runner.
property dataTypeDefaults
dataTypeDefaults: DataTypeDefaults;Default values of length, precision and scale depends on column data type. Used in the cases when length/precision/scale is not specified by user.
property dummyTableName
dummyTableName?: string;Dummy table name
property isReplicated
isReplicated: boolean;Indicates if replication is enabled.
property mappedDataTypes
mappedDataTypes: MappedColumnTypes;Orm has special columns and we need to know what database column types should be for those types. Column types are driver dependant.
property maxAliasLength
maxAliasLength?: number;Max length allowed by the DBMS for aliases (execution of queries).
property options
options: BaseDataSourceOptions;Data Source options.
property parametersPrefix
parametersPrefix?: string;The prefix used for the parameters
property schema
schema?: string;Schema name used to perform all write queries.
property spatialTypes
spatialTypes: ColumnType[];Gets list of spatial column data types.
property supportedDataTypes
supportedDataTypes: ColumnType[];Gets list of supported column data types by a driver.
property supportedIndexTypes
supportedIndexTypes?: TableIndexTypes[];Supported index types
property supportedIsolationLevels
supportedIsolationLevels: readonly IsolationLevel[];Isolation levels supported by this driver.
property supportedOnDeleteTypes
supportedOnDeleteTypes?: OnDeleteType[];Returns list of supported onDelete types by driver
property supportedOnUpdateTypes
supportedOnUpdateTypes?: OnUpdateType[];Returns list of supported onUpdate types by driver
property supportedUpsertTypes
supportedUpsertTypes: UpsertType[];Returns type of upsert supported by driver if any
property transactionSupport
transactionSupport: 'simple' | 'nested' | 'none';Represent transaction support by this driver
property treeSupport
treeSupport: boolean;Indicates if tree tables are supported by this driver.
property version
version?: string;Database version/release. Often requires a SQL query to the DB, so it is not always set
property withLengthColumnTypes
withLengthColumnTypes: ColumnType[];Gets list of column data types that support length by a driver.
property withPrecisionColumnTypes
withPrecisionColumnTypes: ColumnType[];Gets list of column data types that support precision by a driver.
property withScaleColumnTypes
withScaleColumnTypes: ColumnType[];Gets list of column data types that support scale by a driver.
method afterConnect
afterConnect: () => Promise<void>;Makes any action after connection (e.g. create extensions in Postgres driver).
method buildTableName
buildTableName: ( tableName: string, schema?: string, database?: string) => string;Build full table name with database name, schema name and table name. E.g. myDB.mySchema.myTable
method connect
connect: () => Promise<void>;Performs connection to the database. Depend on driver type it may create a connection pool.
method createFullType
createFullType: (column: TableColumn) => string;Normalizes "default" value of the column.
method createGeneratedMap
createGeneratedMap: ( metadata: EntityMetadata, insertResult: any, entityIndex?: number, entityNum?: number) => ObjectLiteral | undefined;Creates generated map of values generated or returned by database after INSERT query.
method createParameter
createParameter: (parameterName: string, index: number) => string;Creates an escaped parameter.
method createQueryRunner
createQueryRunner: (mode: ReplicationMode) => QueryRunner;Creates a query runner used for common queries.
method createSchemaBuilder
createSchemaBuilder: () => SchemaBuilder;Synchronizes database schema (creates tables, indices, etc).
method disconnect
disconnect: () => Promise<void>;Closes connection with database and releases all resources.
method escape
escape: (name: string) => string;Escapes a table name, column name or an alias.
todo: probably escape should be able to handle dots in the names and automatically escape them
method escapeQueryWithParameters
escapeQueryWithParameters: ( sql: string, parameters: ObjectLiteral) => [string, any[]];Replaces parameters in the given sql with special escaping character and an array of parameter names to be passed to a query.
method findChangedColumns
findChangedColumns: ( tableColumns: TableColumn[], columnMetadatas: ColumnMetadata[]) => ColumnMetadata[];Differentiate columns of this table and columns from the given column metadatas columns and returns only changed.
method getColumnLength
getColumnLength: (column: ColumnMetadata) => string;Calculates column length taking into account the default length values.
method isFullTextColumnTypeSupported
isFullTextColumnTypeSupported: () => boolean;Returns true if driver supports fulltext indices.
method isReturningSqlSupported
isReturningSqlSupported: (returningType: ReturningType) => boolean;Returns true if driver supports RETURNING / OUTPUT statement.
method isUUIDGenerationSupported
isUUIDGenerationSupported: () => boolean;Returns true if driver supports uuid values generation on its own.
method normalizeDefault
normalizeDefault: (columnMetadata: ColumnMetadata) => string | undefined;Normalizes "default" value of the column.
method normalizeIsUnique
normalizeIsUnique: (column: ColumnMetadata) => boolean;Normalizes "isUnique" value of the column.
method normalizeType
normalizeType: (column: { type?: ColumnType | string; length?: number | string; precision?: number | null; scale?: number; isArray?: boolean;}) => string;Transforms type of the given column to a database column type.
method obtainMasterConnection
obtainMasterConnection: () => Promise<any>;Obtains a new database connection to a master server. Used for replication. If replication is not setup then returns default connection's database connection.
method obtainSlaveConnection
obtainSlaveConnection: () => Promise<any>;Obtains a new database connection to a slave server. Used for replication. If replication is not setup then returns master (default) connection's database connection.
method parseTableName
parseTableName: ( target: EntityMetadata | Table | View | TableForeignKey | string) => { tableName: string; schema?: string; database?: string };Parse a target table name or other types and return a normalized table definition.
method prepareHydratedValue
prepareHydratedValue: (value: any, column: ColumnMetadata) => any;Prepares given value to a value to be persisted, based on its column type.
method preparePersistentValue
preparePersistentValue: (value: any, column: ColumnMetadata) => any;Prepares given value to a value to be persisted, based on its column type and metadata.
interface EntityOptions
interface EntityOptions {}Describes all entity's options.
property comment
comment?: string;Table comment. Not supported by all database types.
property database
database?: string;Database name. Used in Mysql and Sql Server.
property engine
engine?: string;Table's database engine type (like "InnoDB", "MyISAM", etc). It is used only during table creation. If you update this value and table is already created, it will not change table's engine type. Note that not all databases support this option.
property name
name?: string;Table name. If not specified then naming strategy will generate table name from entity name.
property orderBy
orderBy?: OrderByCondition | ((object: any) => OrderByCondition | any);Specifies a default order by used for queries from this table when no explicit order by is specified.
property schema
schema?: string;Schema name. Used in Postgres and Sql Server.
property synchronize
synchronize?: boolean;Indicates if schema synchronization is enabled or disabled for this entity. If it will be set to false then schema sync will and migrations ignore this entity. By default schema synchronization is enabled for all entities.
property withoutRowid
withoutRowid?: boolean;If set to 'true' this option disables Sqlite's default behaviour of secretly creating an integer primary key column named 'rowid' on table creation.
See Also
https://www.sqlite.org/withoutrowid.html.
interface EntitySchemaColumnOptions
interface EntitySchemaColumnOptions extends SpatialColumnOptions {}property array
array?: boolean;Indicates if this column is an array. Can be simply set to true or array length can be specified. Supported only by postgres.
property asExpression
asExpression?: string;Generated column expression.
property charset
charset?: string;Defines a column character set. Not supported by all database types.
property collation
collation?: string;Defines a column collation.
property columnDefinition
columnDefinition?: string;Extra column definition. Should be used only in emergency situations. Note that if you'll use this property auto schema generation will not work properly anymore. Avoid using it.
property comment
comment?: string;Column comment.
property createDate
createDate?: boolean;Indicates if this column is a created date column.
property default
default?: any;Default database value.
property deleteDate
deleteDate?: boolean;Indicates if this column is a delete date column.
property enum
enum?: any[] | Object;Array of possible enumerated values.
property enumName
enumName?: string;Exact name of enum
property foreignKey
foreignKey?: EntitySchemaColumnForeignKeyOptions;Foreign key options of this column.
property generated
generated?: true | 'increment' | 'uuid' | 'rowid';Specifies if this column will use AUTO_INCREMENT or not (e.g. generated number).
property generatedType
generatedType?: 'VIRTUAL' | 'STORED';Generated column type.
property hstoreType
hstoreType?: 'object' | 'string';Return type of HSTORE column. Returns value as string or as object.
property insert
insert?: boolean;Indicates if column is inserted by default. Default value is "true".
property length
length?: string | number;Column type's length. For example type = "string" and length = 100 means that ORM will create a column with type varchar(100).
property name
name?: string;Column name in the database.
property nullable
nullable?: boolean;Indicates if column's value can be set to NULL.
property objectId
objectId?: boolean;Indicates if this column is of type
ObjectId.
property onUpdate
onUpdate?: string;ON UPDATE trigger. Works only for MySQL.
property precision
precision?: number;The precision for a decimal (exact numeric) column (applies only for decimal column), which is the maximum number of digits that are stored for the values.
property primary
primary?: boolean;Indicates if this column is a primary column.
property primaryKeyConstraintName
primaryKeyConstraintName?: string;Name of the primary key constraint.
property query
query?: (alias: string) => string;Query to be used to populate the column data. This query is used when generating the relational db script. The query function is called with the current entities alias either defined by the Entity Decorator or automatically
See Also
https://typeorm.io/decorator-reference#virtualcolumn for more details.
property scale
scale?: number;The scale for a decimal (exact numeric) column (applies only for decimal column), which represents the number of digits to the right of the decimal point and must not be greater than precision.
property select
select?: boolean;Indicates if column is always selected by QueryBuilder and find operations. Default value is "true".
property transformer
transformer?: ValueTransformer | ValueTransformer[];Specifies a value transformer that is to be used to (un)marshal this column when reading or writing to the database.
property treeChildrenCount
treeChildrenCount?: boolean;Indicates if this column is a treeChildrenCount column.
property treeLevel
treeLevel?: boolean;Indicates if this column is a treeLevel column.
property type
type: ColumnType;Column type. Must be one of the value from the ColumnTypes class.
property unique
unique?: boolean;Specifies if column's value must be unique or not.
property unsigned
unsigned?: boolean;Puts UNSIGNED attribute on to numeric column. Works only for MySQL.
property update
update?: boolean;Indicates if column value is updated by "save" operation. If false you'll be able to write this value only when you first time insert the object. Default value is "true".
property updateDate
updateDate?: boolean;Indicates if this column is an update date column.
property version
version?: boolean;Indicates if this column is a version column.
property virtualProperty
virtualProperty?: boolean;Indicates if this column is a virtualProperty column.
interface EntitySchemaIndexOptions
interface EntitySchemaIndexOptions {}property columns
columns?: | ((object?: any) => | any[] | { [key: string]: number; }) | string[];Index column names.
property fulltext
fulltext?: boolean;The FULLTEXT modifier indexes the entire column and does not allow prefixing. Works only in MySQL.
property name
name?: string;Index name.
property nullFiltered
nullFiltered?: boolean;NULL_FILTERED indexes are particularly useful for indexing sparse columns, where most rows contain a NULL value. In these cases, the NULL_FILTERED index can be considerably smaller and more efficient to maintain than a normal index that includes NULL values.
Works only in Spanner.
property parser
parser?: string;Fulltext parser. Works only in MySQL.
property sparse
sparse?: boolean;If true, the index only references documents with the specified field. These indexes use less space but behave differently in some situations (particularly sorts). This option is only supported for mongodb database.
property spatial
spatial?: boolean;The SPATIAL modifier indexes the entire column and does not allow indexed columns to contain NULL values. Works only in MySQL and PostgreSQL.
property synchronize
synchronize?: boolean;Indicates if index must sync with database index.
property unique
unique?: boolean;Indicates if this index must be unique or not.
property where
where?: string;Index filter condition.
interface EntitySchemaRelationOptions
interface EntitySchemaRelationOptions {}property cascade
cascade?: | boolean | ('insert' | 'update' | 'remove' | 'soft-remove' | 'recover')[];If set to true then it means that related object can be allowed to be inserted / updated / removed to the db. This is option a shortcut if you would like to set cascadeInsert, cascadeUpdate and cascadeRemove to true.
property createForeignKeyConstraints
createForeignKeyConstraints?: boolean;Indicates whether foreign key constraints will be created for join columns. Can be used only for many-to-one and owner one-to-one relations. Defaults to true.
property default
default?: any;Default database value.
property deferrable
deferrable?: DeferrableType;Indicate if foreign key constraints can be deferred.
property eager
eager?: boolean;Indicates if this relation will be eagerly loaded.
property inverseSide
inverseSide?: string;Inverse side of the relation.
property joinColumn
joinColumn?: boolean | JoinColumnOptions | JoinColumnOptions[];Join column options of this column. If set to true then it simply means that it has a join column.
property joinTable
joinTable?: boolean | JoinTableOptions | JoinTableMultipleColumnsOptions;Join table options of this column. If set to true then it simply means that it has a join table.
property lazy
lazy?: boolean;Indicates if this relation will be lazily loaded.
property nullable
nullable?: boolean;Indicates if relation column value can be nullable or not.
property onDelete
onDelete?: OnDeleteType;Database cascade action on delete.
property onUpdate
onUpdate?: OnUpdateType;Database cascade action on update.
property orphanedRowAction
orphanedRowAction?: 'nullify' | 'delete' | 'soft-delete' | 'disable';When a parent is saved (with cascading but) without a child row that still exists in database, this will control what shall happen to them. delete will remove these rows from database. nullify will remove the relation key. skip will keep the relation intact. Removal of related item is only possible through its own repo.
property persistence
persistence?: boolean;Indicates if persistence is enabled for the relation. By default its enabled, but if you want to avoid any changes in the relation to be reflected in the database you can disable it. If its disabled you can only change a relation from inverse side of a relation or using relation query builder functionality. This is useful for performance optimization since its disabling avoid multiple extra queries during entity save.
property primary
primary?: boolean;Indicates if this relation will be a primary key. Can be used only for many-to-one and owner one-to-one relations.
property target
target: EntityTarget<any>;Indicates with which entity this relation is made.
property treeChildren
treeChildren?: boolean;Indicates if this is a children (can be only one-to-many relation) relation in the tree tables.
property treeParent
treeParent?: boolean;Indicates if this is a parent (can be only many-to-one relation) relation in the tree tables.
property type
type: RelationType;Type of relation. Can be one of the value of the RelationTypes class.
interface EntitySubscriberInterface
interface EntitySubscriberInterface<Entity = any> {}Classes that implement this interface are subscribers that subscribe for the specific events in the ORM.
method afterInsert
afterInsert: (event: InsertEvent<Entity>) => Promise<any> | void;Called after entity is inserted to the database.
method afterLoad
afterLoad: (entity: Entity, event?: LoadEvent<Entity>) => Promise<any> | void;Called after entity is loaded from the database.
For backward compatibility this signature is slightly different from the others.
eventwas added later but is always provided (it is only optional in the signature so that its introduction does not break compilation for existing subscribers).
method afterQuery
afterQuery: (event: AfterQueryEvent) => Promise<any> | void;Called after query is executed.
method afterRecover
afterRecover: (event: RecoverEvent<Entity>) => Promise<any> | void;Called after entity is recovered in the database.
method afterRemove
afterRemove: (event: RemoveEvent<Entity>) => Promise<any> | void;Called after entity is removed from the database.
method afterSoftRemove
afterSoftRemove: (event: SoftRemoveEvent<Entity>) => Promise<any> | void;Called after entity is soft removed from the database.
method afterTransactionCommit
afterTransactionCommit: (event: TransactionCommitEvent) => Promise<any> | void;Called after transaction is committed.
method afterTransactionRollback
afterTransactionRollback: ( event: TransactionRollbackEvent) => Promise<any> | void;Called after transaction rollback.
method afterTransactionStart
afterTransactionStart: (event: TransactionStartEvent) => Promise<any> | void;Called after transaction is started.
method afterUpdate
afterUpdate: (event: UpdateEvent<Entity>) => Promise<any> | void;Called after entity is updated in the database.
method beforeInsert
beforeInsert: (event: InsertEvent<Entity>) => Promise<any> | void;Called before entity is inserted to the database.
method beforeQuery
beforeQuery: (event: BeforeQueryEvent) => Promise<any> | void;Called before query is executed.
method beforeRecover
beforeRecover: (event: RecoverEvent<Entity>) => Promise<any> | void;Called before entity is recovered in the database.
method beforeRemove
beforeRemove: (event: RemoveEvent<Entity>) => Promise<any> | void;Called before entity is removed from the database.
method beforeSoftRemove
beforeSoftRemove: (event: SoftRemoveEvent<Entity>) => Promise<any> | void;Called before entity is soft removed from the database.
method beforeTransactionCommit
beforeTransactionCommit: (event: TransactionCommitEvent) => Promise<any> | void;Called before transaction is committed.
method beforeTransactionRollback
beforeTransactionRollback: ( event: TransactionRollbackEvent) => Promise<any> | void;Called before transaction rollback.
method beforeTransactionStart
beforeTransactionStart: (event: TransactionStartEvent) => Promise<any> | void;Called before transaction is started.
method beforeUpdate
beforeUpdate: (event: UpdateEvent<Entity>) => Promise<any> | void;Called before entity is updated in the database.
method listenTo
listenTo: () => Function | string;Returns the class of the entity to which events will listen. If this method is omitted, then subscriber will listen to events of all entities.
interface FindManyOptions
interface FindManyOptions<Entity = any> extends FindOneOptions<Entity> {}Defines a special criteria to find specific entities.
interface FindOneOptions
interface FindOneOptions<Entity = any> {}Defines a special criteria to find specific entity.
property cache
cache?: | boolean | number | { id: any; milliseconds: number; };Enables or disables query result caching.
property comment
comment?: string;Adds a comment with the supplied string in the generated query. This is helpful for debugging purposes, such as finding a specific query in the database server's logs, or for categorization using an APM product.
property loadEagerRelations
loadEagerRelations?: boolean;Indicates if eager relations should be loaded or not. By default, they are loaded when find methods are used.
property loadRelationIds
loadRelationIds?: | boolean | { relations?: string[]; disableMixedMap?: boolean; };If sets to true then loads all relation ids of the entity and maps them into relation values (not relation objects). If array of strings is given then loads only relation ids of the given properties.
property lock
lock?: | { mode: 'optimistic'; version: number | Date; } | { mode: | 'pessimistic_read' | 'pessimistic_write' | 'dirty_read' | 'for_no_key_update' | 'for_key_share'; tables?: string[]; onLocked?: 'nowait' | 'skip_locked'; };Indicates what locking mode should be used.
Note: For lock tables, you must specify the table names and not the relation names
property order
order?: FindOptionsOrder<Entity>;Order, in which entities should be ordered.
property relationLoadStrategy
relationLoadStrategy?: 'join' | 'query';Specifies how relations must be loaded - using "joins" or separate queries. If you are loading too much data with nested joins it's better to load relations using separate queries.
Default strategy is "join", but default can be customized in connection options.
property relations
relations?: FindOptionsRelations<Entity>;Indicates what relations of entity should be loaded (simplified left join form).
property select
select?: FindOptionsSelect<Entity>;Specifies what columns should be retrieved.
property transaction
transaction?: boolean;If this is set to true, SELECT query in a
findmethod will be executed in a transaction.
property where
where?: FindOptionsWhere<Entity>[] | FindOptionsWhere<Entity>;Simple condition that should be applied to match entities.
property withDeleted
withDeleted?: boolean;Indicates if soft-deleted rows should be included in entity result.
interface FindTreeOptions
interface FindTreeOptions {}Defines a special criteria to find specific entities.
interface IndexOptions
interface IndexOptions {}Describes all index options.
property background
background?: boolean;Builds the index in the background so that building an index an does not block other database activities. This option is only supported for mongodb database.
property concurrent
concurrent?: boolean;Create the index using the CONCURRENTLY modifier Works only in postgres.
property expireAfterSeconds
expireAfterSeconds?: number;Specifies a time to live, in seconds. This option is only supported for mongodb database.
property fulltext
fulltext?: boolean;The FULLTEXT modifier indexes the entire column and does not allow prefixing. Works only in MySQL.
property nullFiltered
nullFiltered?: boolean;NULL_FILTERED indexes are particularly useful for indexing sparse columns, where most rows contain a NULL value. In these cases, the NULL_FILTERED index can be considerably smaller and more efficient to maintain than a normal index that includes NULL values.
Works only in Spanner.
property parser
parser?: string;Fulltext parser. Works only in MySQL.
property sparse
sparse?: boolean;If true, the index only references documents with the specified field. These indexes use less space but behave differently in some situations (particularly sorts). This option is only supported for mongodb database.
property spatial
spatial?: boolean;The SPATIAL modifier indexes the entire column and does not allow indexed columns to contain NULL values. Works only in MySQL and PostgreSQL.
property type
type?: TableIndexTypes;The
typeoption defines the type of the index being created. Supported types include B-tree, Hash, GiST, SP-GiST, GIN, and BRIN This option is only applicable in PostgreSQL.
property unique
unique?: boolean;Indicates if this composite index must be unique or not.
property where
where?: string;Index filter condition.
interface InsertEvent
interface InsertEvent<Entity> extends BaseEvent {}InsertEvent is an object that broadcaster sends to the entity subscriber when entity is inserted to the database.
interface JoinColumnOptions
interface JoinColumnOptions {}Describes join column options.
property foreignKeyConstraintName
foreignKeyConstraintName?: string;Name of the foreign key constraint.
property name
name?: string;Name of the column.
property referencedColumnName
referencedColumnName?: string;Name of the column in the entity to which this column is referenced.
interface JoinTableOptions
interface JoinTableOptions {}Describes join table options.
property database
database?: string;Database where join table will be created. Works only in some databases (like mysql and mssql).
property inverseJoinColumn
inverseJoinColumn?: JoinColumnOptions;Second (inverse) column of the join table.
property joinColumn
joinColumn?: JoinColumnOptions;First column of the join table.
property name
name?: string;Name of the table that will be created to store values of the both tables (join table). By default is auto generated.
property schema
schema?: string;Schema where join table will be created. Works only in some databases (like postgres and mssql).
property synchronize
synchronize?: boolean;Indicates if schema synchronization is enabled or disabled junction table. If it will be set to false then schema sync will and migrations ignores junction table. By default schema synchronization is enabled.
interface LoadEvent
interface LoadEvent<Entity> extends BaseEvent {}LoadEvent is an object that broadcaster sends to the entity subscriber when an entity is loaded from the database.
interface Logger
interface Logger {}Performs logging of the events in TypeORM.
method log
log: ( level: 'log' | 'info' | 'warn', message: any, queryRunner?: QueryRunner) => any;Perform logging using given logger, or by default to the console. Log has its own level and message.
method logMigration
logMigration: (message: string, queryRunner?: QueryRunner) => any;Logs events from the migrations run process.
method logQuery
logQuery: ( query: string, parameters?: any[] | ObjectLiteral, queryRunner?: QueryRunner) => any;Logs query and parameters used in it.
method logQueryError
logQueryError: ( error: string | Error, query: string, parameters?: any[] | ObjectLiteral, queryRunner?: QueryRunner) => any;Logs query that is failed.
method logQuerySlow
logQuerySlow: ( time: number, query: string, parameters?: any[] | ObjectLiteral, queryRunner?: QueryRunner) => any;Logs query that is slow.
method logSchemaBuild
logSchemaBuild: (message: string, queryRunner?: QueryRunner) => any;Logs events from the schema build process.
interface MigrationInterface
interface MigrationInterface {}Migrations should implement this interface and all its methods.
property name
name?: string;Optional migration name, defaults to class name.
property transaction
transaction?: boolean;Optional flag to determine whether to run the migration in a transaction or not. Can only be used when
migrationsTransactionModeis either "each" or "none" Defaults totruewhenmigrationsTransactionModeis "each" Defaults tofalsewhenmigrationsTransactionModeis "none"
method down
down: (queryRunner: QueryRunner) => Promise<any>;Reverse the migrations.
method up
up: (queryRunner: QueryRunner) => Promise<any>;Run the migrations.
interface NamingStrategyInterface
interface NamingStrategyInterface {}Naming strategy defines how auto-generated names for such things like table name, or table column gonna be generated.
property materializedPathColumnName
materializedPathColumnName: string;Column name for materialized paths.
property nestedSetColumnNames
nestedSetColumnNames: { left: string; right: string;};Column names for nested sets.
method checkConstraintName
checkConstraintName: ( tableOrName: Table | string, expression: string, isEnum?: boolean) => string;Gets the name of the check constraint.
"isEnum" parameter is used to indicate if this check constraint used to handle "simple-enum" type for databases that are not supporting "enum" type out of the box. If "true", constraint is ignored during CHECK constraints synchronization.
method closureJunctionTableName
closureJunctionTableName: (originalClosureTableName: string) => string;Creates a table name for a junction table of a closure table.
Parameter originalClosureTableName
Name of the closure table which owns this junction table.
method columnName
columnName: ( propertyName: string, customName: string | undefined, embeddedPrefixes: string[]) => string;Gets the table's column name from the given property name.
method defaultConstraintName
defaultConstraintName: ( tableOrName: Table | string, columnName: string) => string;Gets the table's default constraint name from the given table name and column name.
method exclusionConstraintName
exclusionConstraintName: ( tableOrName: Table | string, expression: string) => string;Gets the name of the exclusion constraint.
method foreignKeyName
foreignKeyName: ( tableOrName: Table | string, columnNames: string[], referencedTablePath?: string, referencedColumnNames?: string[]) => string;Gets the name of the foreign key.
method indexName
indexName: ( tableOrName: Table | View | string, columns: string[], where?: string) => string;Gets the name of the index - simple and compose index.
method joinColumnName
joinColumnName: (relationName: string, referencedColumnName: string) => string;Gets the name of the join column used in the one-to-one and many-to-one relations.
method joinTableColumnDuplicationPrefix
joinTableColumnDuplicationPrefix: (columnName: string, index: number) => string;Columns in join tables can have duplicate names in case of self-referencing. This method provide a resolution for such column names.
method joinTableColumnName
joinTableColumnName: ( tableName: string, propertyName: string, columnName?: string) => string;Gets the name of the column used for columns in the junction tables.
The reverse?:boolean parameter denotes if the joinTableColumnName is called for the junctionColumn (false) or the inverseJunctionColumns (true)
method joinTableInverseColumnName
joinTableInverseColumnName: ( tableName: string, propertyName: string, columnName?: string) => string;Gets the name of the column used for columns in the junction tables from the invers side of the relationship.
method joinTableName
joinTableName: ( firstTableName: string, secondTableName: string, firstPropertyName: string, secondPropertyName: string) => string;Gets the name of the join table used in the many-to-many relations.
method prefixTableName
prefixTableName: (prefix: string, tableName: string) => string;Adds globally set prefix to the table name. This method is executed no matter if prefix was set or not. Table name is either user's given table name, either name generated from entity target. Note that table name comes here already normalized by #tableName method.
method primaryKeyName
primaryKeyName: (tableOrName: Table | string, columnNames: string[]) => string;Gets the table's primary key name from the given table name and column names.
method relationConstraintName
relationConstraintName: ( tableOrName: Table | string, columnNames: string[], where?: string) => string;Gets the relation constraint (UNIQUE or UNIQUE INDEX) name from the given table name, column names and WHERE condition, if UNIQUE INDEX used.
method relationName
relationName: (propertyName: string) => string;Gets the table's relation name from the given property name.
method tableName
tableName: (targetName: string, userSpecifiedName: string | undefined) => string;Normalizes table name.
Parameter targetName
Name of the target entity that can be used to generate a table name.
Parameter userSpecifiedName
For example if user specified a table name in a decorator, e.g.
@Entity("name")
method uniqueConstraintName
uniqueConstraintName: ( tableOrName: Table | string, columnNames: string[]) => string;Gets the table's unique constraint name from the given table name and column names.
interface ObjectLiteral
interface ObjectLiteral {}Interface of the simple literal object with any string keys.
index signature
[key: string]: any;interface QueryEvent
interface QueryEvent extends BaseEvent {}BeforeQueryEvent is an object that broadcaster sends to the entity subscriber before query is ran against the database.
property parameters
parameters?: any[] | ObjectLiteral;Parameters used in the query.
property query
query: string;Query that is being executed.
interface QueryRunner
interface QueryRunner extends AsyncDisposable {}Runs queries on a single database connection.
property broadcaster
readonly broadcaster: Broadcaster;Broadcaster used on this query runner to broadcast entity events.
property data
data: ObjectLiteral;Stores temporarily user data. Useful for sharing data with subscribers.
property dataSource
readonly dataSource: DataSource;DataSource used by this query runner.
property isReleased
readonly isReleased: boolean;Indicates if connection for this query runner is released. Once its released, query runner cannot run queries anymore.
property isTransactionActive
readonly isTransactionActive: boolean;Indicates if transaction is in progress.
property manager
readonly manager: EntityManager;Entity manager working only with this query runner.
method [Symbol.asyncDispose]
[Symbol.asyncDispose]: () => Promise<void>;method addColumn
addColumn: (table: Table | string, column: TableColumn) => Promise<void>;Adds a new column.
method addColumns
addColumns: (table: Table | string, columns: TableColumn[]) => Promise<void>;Adds new columns.
method afterMigration
afterMigration: () => Promise<void>;Called after migrations are run.
method beforeMigration
beforeMigration: () => Promise<void>;Called before migrations are run.
method changeColumn
changeColumn: ( table: Table | string, oldColumn: TableColumn | string, newColumn: TableColumn) => Promise<void>;Changes a column in the table.
method changeColumns
changeColumns: ( table: Table | string, changedColumns: { oldColumn: TableColumn; newColumn: TableColumn }[]) => Promise<void>;Changes columns in the table.
method changeTableComment
changeTableComment: ( tableOrName: Table | string, comment?: string) => Promise<void>;Change table comment. Only supports MySQL and MariaDB
method clearDatabase
clearDatabase: (database?: string) => Promise<void>;Removes all tables from the currently connected database. Be careful with using this method and avoid using it in production or migrations (because it can clear all your database).
method clearSqlMemory
clearSqlMemory: () => void;Flushes all memorized sqls.
method clearTable
clearTable: ( tableName: string, options?: { cascade?: boolean }) => Promise<void>;Clears all table contents. Note: this operation uses SQL's TRUNCATE query which cannot be reverted in transactions.
method commitTransaction
commitTransaction: () => Promise<void>;Commits transaction. Error will be thrown if transaction was not started.
method connect
connect: () => Promise<any>;Creates/uses database connection from the connection pool to perform further operations. Returns obtained database connection.
method createCheckConstraint
createCheckConstraint: ( table: Table | string, checkConstraint: TableCheck) => Promise<void>;Creates a new check constraint.
method createCheckConstraints
createCheckConstraints: ( table: Table | string, checkConstraints: TableCheck[]) => Promise<void>;Creates new check constraints.
method createDatabase
createDatabase: (database: string, ifNotExists?: boolean) => Promise<void>;Creates a new database.
method createExclusionConstraint
createExclusionConstraint: ( table: Table | string, exclusionConstraint: TableExclusion) => Promise<void>;Creates a new exclusion constraint.
method createExclusionConstraints
createExclusionConstraints: ( table: Table | string, exclusionConstraints: TableExclusion[]) => Promise<void>;Creates new exclusion constraints.
method createForeignKey
createForeignKey: ( table: Table | string, foreignKey: TableForeignKey) => Promise<void>;Creates a new foreign key.
method createForeignKeys
createForeignKeys: ( table: Table | string, foreignKeys: TableForeignKey[]) => Promise<void>;Creates new foreign keys.
method createIndex
createIndex: (table: Table | string, index: TableIndex) => Promise<void>;Creates a new index.
method createIndices
createIndices: (table: Table | string, indices: TableIndex[]) => Promise<void>;Creates new indices.
method createPrimaryKey
createPrimaryKey: ( table: Table | string, columnNames: string[], constraintName?: string) => Promise<void>;Creates a new primary key.
method createSchema
createSchema: (schemaPath: string, ifNotExists?: boolean) => Promise<void>;Creates a new table schema.
method createTable
createTable: ( table: Table, ifNotExists?: boolean, createForeignKeys?: boolean, createIndices?: boolean) => Promise<void>;Creates a new table.
method createUniqueConstraint
createUniqueConstraint: ( table: Table | string, uniqueConstraint: TableUnique) => Promise<void>;Creates a new unique constraint.
method createUniqueConstraints
createUniqueConstraints: ( table: Table | string, uniqueConstraints: TableUnique[]) => Promise<void>;Creates new unique constraints.
method createView
createView: ( view: View, syncWithMetadata?: boolean, oldView?: View) => Promise<void>;Creates a new view.
method disableSqlMemory
disableSqlMemory: () => void;Disables special query runner mode in which sql queries won't be executed started by calling enableSqlMemory() method.
Previously memorized sql will be flushed.
method dropCheckConstraint
dropCheckConstraint: ( table: Table | string, checkOrName: TableCheck | string, ifExists?: boolean) => Promise<void>;Drops a check constraint.
method dropCheckConstraints
dropCheckConstraints: ( table: Table | string, checkConstraints: TableCheck[], ifExists?: boolean) => Promise<void>;Drops check constraints.
method dropColumn
dropColumn: ( table: Table | string, column: TableColumn | string, ifExists?: boolean) => Promise<void>;Drops a column in the table.
method dropColumns
dropColumns: ( table: Table | string, columns: TableColumn[] | string[], ifExists?: boolean) => Promise<void>;Drops columns in the table.
method dropDatabase
dropDatabase: (database: string, ifExists?: boolean) => Promise<void>;Drops a database.
method dropExclusionConstraint
dropExclusionConstraint: ( table: Table | string, exclusionOrName: TableExclusion | string, ifExists?: boolean) => Promise<void>;Drops an exclusion constraint.
method dropExclusionConstraints
dropExclusionConstraints: ( table: Table | string, exclusionConstraints: TableExclusion[], ifExists?: boolean) => Promise<void>;Drops exclusion constraints.
method dropForeignKey
dropForeignKey: ( table: Table | string, foreignKeyOrName: TableForeignKey | string, ifExists?: boolean) => Promise<void>;Drops a foreign key.
method dropForeignKeys
dropForeignKeys: ( table: Table | string, foreignKeys: TableForeignKey[], ifExists?: boolean) => Promise<void>;Drops foreign keys.
method dropIndex
dropIndex: ( table: Table | string, index: TableIndex | string, ifExists?: boolean) => Promise<void>;Drops an index.
method dropIndices
dropIndices: ( table: Table | string, indices: TableIndex[], ifExists?: boolean) => Promise<void>;Drops indices.
method dropPrimaryKey
dropPrimaryKey: ( table: Table | string, constraintName?: string, ifExists?: boolean) => Promise<void>;Drops a primary key.
method dropSchema
dropSchema: ( schemaPath: string, ifExists?: boolean, isCascade?: boolean) => Promise<void>;Drops a table schema. For SqlServer can accept schema path (e.g. 'dbName.schemaName') as parameter. If schema path passed, it will drop schema in specified database.
method dropTable
dropTable: ( table: Table | string, ifExists?: boolean, dropForeignKeys?: boolean, dropIndices?: boolean) => Promise<void>;Drops a table.
method dropUniqueConstraint
dropUniqueConstraint: ( table: Table | string, uniqueOrName: TableUnique | string, ifExists?: boolean) => Promise<void>;Drops a unique constraint.
method dropUniqueConstraints
dropUniqueConstraints: ( table: Table | string, uniqueConstraints: TableUnique[], ifExists?: boolean) => Promise<void>;Drops unique constraints.
method dropView
dropView: (view: View | string, ifExists?: boolean) => Promise<void>;Drops a view.
method enableSqlMemory
enableSqlMemory: () => void;Enables special query runner mode in which sql queries won't be executed, instead they will be memorized into a special variable inside query runner. You can get memorized sql using getMemorySql() method.
method executeMemoryDownSql
executeMemoryDownSql: () => Promise<void>;Executes down sql queries.
method executeMemoryUpSql
executeMemoryUpSql: () => Promise<void>;Executes up sql queries.
method getCurrentDatabase
getCurrentDatabase: () => Promise<string | undefined>;Loads currently using database
method getCurrentSchema
getCurrentSchema: () => Promise<string | undefined>;Loads currently using database schema
method getDatabases
getDatabases: () => Promise<string[]>;Returns all available database names including system databases.
method getMemorySql
getMemorySql: () => SqlInMemory;Gets sql stored in the memory. Parameters in the sql are already replaced.
method getReplicationMode
getReplicationMode: () => ReplicationMode;Returns replication mode (ex:
masterorslave).
method getSchemas
getSchemas: (database?: string) => Promise<string[]>;Returns all available schema names including system schemas. If database parameter specified, returns schemas of that database. Useful for SQLServer and Postgres only.
method getTable
getTable: (tablePath: string) => Promise<Table | undefined>;Loads a table by a given name from the database.
method getTables
getTables: (tablePaths?: string[]) => Promise<Table[]>;Loads all tables from the database and returns them.
method getView
getView: (viewPath: string) => Promise<View | undefined>;Loads a view by a given name from the database.
method getViews
getViews: (viewPaths?: string[]) => Promise<View[]>;Loads all views from the database and returns them.
method hasColumn
hasColumn: (table: Table | string, columnName: string) => Promise<boolean>;Checks if a column exist in the table.
method hasDatabase
hasDatabase: (database: string) => Promise<boolean>;Checks if a database with the given name exist.
method hasSchema
hasSchema: (schema: string) => Promise<boolean>;Checks if a schema with the given name exist.
method hasTable
hasTable: (table: Table | string) => Promise<boolean>;Checks if a table with the given name exist.
method query
query: { ( query: string, parameters: any[] | ObjectLiteral | undefined, useStructuredResult: true ): Promise<QueryResult>; (query: string, parameters?: any[] | ObjectLiteral): Promise<any>;};Executes a given SQL query and returns raw database results.
Note: Parameters may be named if using mysql2 with extra.namedPlaceholders set: Example:
query("SELECT * FROM USERS WHERE name = :name and age = :age",{ name: "John", age: 24 },)Executes a given SQL query and returns raw database results.
method release
release: () => Promise<void>;Releases used database connection. You cannot use query runner methods after connection is released.
method renameColumn
renameColumn: ( table: Table | string, oldColumnOrName: TableColumn | string, newColumnOrName: TableColumn | string) => Promise<void>;Renames a column.
method renameTable
renameTable: ( oldTableOrName: Table | string, newTableName: string) => Promise<void>;Renames a table.
method rollbackTransaction
rollbackTransaction: () => Promise<void>;Rollbacks transaction. Error will be thrown if transaction was not started.
method sql
sql: <T = any>( strings: TemplateStringsArray, ...values: unknown[]) => Promise<T>;Tagged template function that executes raw SQL query and returns raw database results. Template expressions are automatically transformed into database parameters. Raw query execution is supported only by relational databases (MongoDB is not supported). Note: Don't call this as a regular function, it is meant to be used with backticks to tag a template literal.
Example 1
queryRunner.sql
SELECT * FROM table_name WHERE id = ${id}
method startTransaction
startTransaction: (isolationLevel?: IsolationLevel) => Promise<void>;Starts transaction.
method stream
stream: ( query: string, parameters?: any[], onEnd?: Function, onError?: Function) => Promise<ReadStream>;Returns raw data stream.
method updatePrimaryKeys
updatePrimaryKeys: ( table: Table | string, columns: TableColumn[]) => Promise<void>;Updates composite primary keys.
index signature
get connection(): DataSource;DataSource used by this query runner.
Deprecated
since 1.0.0. Use dataSource instance instead.
interface RecoverEvent
interface RecoverEvent<Entity> extends RemoveEvent<Entity> {}RecoverEvent is an object that broadcaster sends to the entity subscriber when entity is being recovered in the database.
interface RelationOptions
interface RelationOptions {}Describes all relation's options.
property cascade
cascade?: | boolean | ('insert' | 'update' | 'remove' | 'soft-remove' | 'recover')[];Sets cascades options for the given relation. If set to true then it means that related object can be allowed to be inserted or updated in the database. You can separately restrict cascades to insertion or updation using following syntax:
Example 1
cascade: ["insert", "update", "remove", "soft-remove", "recover"] // include or exclude one of them
property createForeignKeyConstraints
createForeignKeyConstraints?: boolean;Indicates whether foreign key constraints will be created for join columns. Can be used only for many-to-one and owner one-to-one relations. Defaults to true.
property deferrable
deferrable?: DeferrableType;Indicate if foreign key constraints can be deferred.
property eager
eager?: boolean;Set this relation to be eager. Eager relations are always loaded automatically when relation's owner entity is loaded using find* methods. Only using QueryBuilder prevents loading eager relations. Eager flag cannot be set from both sides of relation - you can eager load only one side of the relationship.
property lazy
lazy?: boolean;Set this relation to be lazy. Note: lazy relations are promises. When you call them they return promise which resolve relation result then. If your property's type is Promise then this relation is set to lazy automatically.
property nullable
nullable?: boolean;Indicates if relation column value can be nullable or not.
property onDelete
onDelete?: OnDeleteType;Database cascade action on delete.
property onUpdate
onUpdate?: OnUpdateType;Database cascade action on update.
property orphanedRowAction
orphanedRowAction?: 'nullify' | 'delete' | 'soft-delete' | 'disable';When a parent is saved (with cascading but) without a child row that still exists in database, this will control what shall happen to them. delete will remove these rows from database. nullify will remove the relation key. disable will keep the relation intact. Removal of related item is only possible through its own repo.
property persistence
persistence?: boolean;Indicates if persistence is enabled for the relation. By default its enabled, but if you want to avoid any changes in the relation to be reflected in the database you can disable it. If its disabled you can only change a relation from inverse side of a relation or using relation query builder functionality. This is useful for performance optimization since its disabling avoid multiple extra queries during entity save.
interface RemoveEvent
interface RemoveEvent<Entity> extends BaseEvent {}RemoveEvent is an object that broadcaster sends to the entity subscriber when entity is being removed to the database.
property databaseEntity
databaseEntity: Entity;Database representation of entity that is being removed.
property entity
entity?: Entity;Entity that is being removed. This may absent if entity is removed without being loaded (for examples by cascades).
property entityId
entityId?: any;Id or ids of the entity that is being removed.
property metadata
metadata: EntityMetadata;Metadata of the entity.
interface RemoveOptions
interface RemoveOptions {}Special options passed to Repository#remove and Repository#delete methods.
property chunk
chunk?: number;Breaks save execution into given number of chunks. For example, if you want to save 100,000 objects but you have issues with saving them, you can break them into 10 groups of 10,000 objects (by setting { chunk: 10000 }) and save each group separately. This option is needed to perform very big insertions when you have issues with underlying driver parameter number limitation.
property data
data?: any;Additional data to be passed with remove method. This data can be used in subscribers then.
property listeners
listeners?: boolean;Indicates if listeners and subscribers are called for this operation. By default they are enabled, you can disable them by setting { listeners: false } in save/remove options.
property transaction
transaction?: boolean;By default transactions are enabled and all queries in persistence operation are wrapped into the transaction. You can disable this behaviour by setting { transaction: false } in the persistence options.
interface SaveOptions
interface SaveOptions {}Special options passed to Repository#save, Repository#insert and Repository#update methods.
property chunk
chunk?: number;Breaks save execution into chunks of a given size. For example, if you want to save 100,000 objects but you have issues with saving them, you can break them into 10 groups of 10,000 objects (by setting { chunk: 10000 }) and save each group separately. This option is needed to perform very big insertions when you have issues with underlying driver parameter number limitation.
property data
data?: any;Additional data to be passed with persist method. This data can be used in subscribers then.
property listeners
listeners?: boolean;Indicates if listeners and subscribers are called for this operation. By default they are enabled, you can disable them by setting { listeners: false } in save/remove options.
property reload
reload?: boolean;Flag to determine whether the entity that is being persisted should be reloaded during the persistence operation.
It will work only on databases which do not support RETURNING / OUTPUT statement. Enabled by default.
property transaction
transaction?: boolean;By default transactions are enabled and all queries in persistence operation are wrapped into the transaction. You can disable this behaviour by setting { transaction: false } in the persistence options.
interface SoftRemoveEvent
interface SoftRemoveEvent<Entity> extends RemoveEvent<Entity> {}SoftRemoveEvent is an object that broadcaster sends to the entity subscriber when entity is being soft removed to the database.
interface TableCheckOptions
interface TableCheckOptions {}Database's table check constraint options.
property columnNames
columnNames?: string[];Column that contains this constraint.
property expression
expression?: string;Check expression.
property name
name?: string;Constraint name.
interface TableColumnOptions
interface TableColumnOptions {}Table's column options.
property asExpression
asExpression?: string;Generated column expression.
property charset
charset?: string;Defines column character set.
property collation
collation?: string;Defines column collation.
property comment
comment?: string;Column's comment.
property default
default?: any;Column's default value.
property enum
enum?: string[];Array of possible enumerated values.
property enumName
enumName?: string;Exact name of enum
property foreignKeyConstraintName
foreignKeyConstraintName?: string;If this column is foreign key then this specifies the name for it.
property generatedIdentity
generatedIdentity?: 'ALWAYS' | 'BY DEFAULT';Identity column type. Supports only in Postgres 10+.
property generatedType
generatedType?: 'VIRTUAL' | 'STORED';Generated column type.
property generationStrategy
generationStrategy?: 'uuid' | 'increment' | 'rowid' | 'identity';Specifies generation strategy if this column will use auto increment.
property isArray
isArray?: boolean;Indicates if column stores array.
property isGenerated
isGenerated?: boolean;Indicates if column is auto-generated sequence.
property isNullable
isNullable?: boolean;Indicates if column is NULL, or is NOT NULL in the database.
property isPrimary
isPrimary?: boolean;Indicates if column is a primary key.
property isUnique
isUnique?: boolean;Indicates if column has unique value.
property length
length?: string;Column type's length. Used only on some column types. For example type = "string" and length = "100" means that ORM will create a column with type varchar(100).
property name
name: string;Column name.
property onUpdate
onUpdate?: string;ON UPDATE trigger. Works only for MySQL.
property precision
precision?: number | null;The precision for a decimal (exact numeric) column (applies only for decimal column), which is the maximum number of digits that are stored for the values.
property primaryKeyConstraintName
primaryKeyConstraintName?: string;If this column is primary key then this specifies the name for it.
property scale
scale?: number;The scale for a decimal (exact numeric) column (applies only for decimal column), which represents the number of digits to the right of the decimal point and must not be greater than precision.
property spatialFeatureType
spatialFeatureType?: string;Spatial Feature Type (Geometry, Point, Polygon, etc.)
property srid
srid?: number;SRID (Spatial Reference ID (EPSG code))
property type
type: string;Column type.
property unsigned
unsigned?: boolean;Puts UNSIGNED attribute on to numeric column. Works only for MySQL.
interface TableExclusionOptions
interface TableExclusionOptions {}Database's table exclusion constraint options.
property deferrable
deferrable?: string;Set this exclusion constraint as "DEFERRABLE" e.g. check constraints at start or at the end of a transaction
property expression
expression?: string;Exclusion expression.
property name
name?: string;Constraint name.
interface TableForeignKeyOptions
interface TableForeignKeyOptions {}Foreign key options.
property columnNames
columnNames: string[];Column names which included by this foreign key.
property deferrable
deferrable?: string;Set this foreign key constraint as "DEFERRABLE" e.g. check constraints at start or at the end of a transaction
property name
name?: string;Name of the foreign key.
property onDelete
onDelete?: string;"ON DELETE" of this foreign key, e.g. what action database should perform when referenced stuff is being deleted.
property onUpdate
onUpdate?: string;"ON UPDATE" of this foreign key, e.g. what action database should perform when referenced stuff is being updated.
property referencedColumnNames
referencedColumnNames: string[];Column names which included by this foreign key.
property referencedDatabase
referencedDatabase?: string;Database of the Table referenced in the foreign key.
property referencedSchema
referencedSchema?: string;Schema of the Table referenced in the foreign key.
property referencedTableName
referencedTableName: string;Table referenced in the foreign key.
interface TableIndexOptions
interface TableIndexOptions {}Database's table index options.
property columnNames
columnNames: string[];Columns included in this index.
property isConcurrent
isConcurrent?: boolean;Builds the index using the concurrently option. This options is only supported for postgres database.
property isFulltext
isFulltext?: boolean;The FULLTEXT modifier indexes the entire column and does not allow prefixing. Supported only in MySQL & SAP HANA.
property isNullFiltered
isNullFiltered?: boolean;NULL_FILTERED indexes are particularly useful for indexing sparse columns, where most rows contain a NULL value. In these cases, the NULL_FILTERED index can be considerably smaller and more efficient to maintain than a normal index that includes NULL values.
Works only in Spanner.
property isSpatial
isSpatial?: boolean;The SPATIAL modifier indexes the entire column and does not allow indexed columns to contain NULL values. Works only in MySQL.
property isUnique
isUnique?: boolean;Indicates if this index is unique.
property name
name?: string;Constraint name.
property parser
parser?: string;Fulltext parser. Works only in MySQL.
property type
type?: TableIndexTypes;The
typeoption defines the type of the index being created. Supported types include B-tree, Hash, GiST, SP-GiST, GIN, and BRIN This option is only applicable in PostgreSQL.
property where
where?: string;Index filter condition.
interface TableOptions
interface TableOptions {}Table options.
property checks
checks?: TableCheckOptions[];Table check constraints.
property columns
columns?: TableColumnOptions[];Table columns.
property comment
comment?: string;Table comment. Not supported by all database types.
property database
database?: string;Table database.
property engine
engine?: string;Table engine.
property exclusions
exclusions?: TableExclusionOptions[];Table check constraints.
property foreignKeys
foreignKeys?: TableForeignKeyOptions[];Table foreign keys.
property indices
indices?: TableIndexOptions[];Table indices.
property justCreated
justCreated?: boolean;Indicates if table was just created. This is needed, for example to check if we need to skip primary keys creation for new tables.
property name
name: string;Table name.
property schema
schema?: string;Table schema.
property uniques
uniques?: TableUniqueOptions[];Table unique constraints.
property withoutRowid
withoutRowid?: boolean;Enables Sqlite "WITHOUT ROWID" modifier for the "CREATE TABLE" statement
interface TableUniqueOptions
interface TableUniqueOptions {}Database's table unique constraint options.
property columnNames
columnNames: string[];Columns that contains this constraint.
property deferrable
deferrable?: string;Set this foreign key constraint as "DEFERRABLE" e.g. check constraints at start or at the end of a transaction
property name
name?: string;Constraint name.
interface TransactionCommitEvent
interface TransactionCommitEvent extends BaseEvent {}TransactionCommitEvent is an object that broadcaster sends to the entity subscriber when an transaction is committed.
interface TransactionRollbackEvent
interface TransactionRollbackEvent extends BaseEvent {}TransactionRollbackEvent is an object that broadcaster sends to the entity subscriber on transaction rollback.
interface TransactionStartEvent
interface TransactionStartEvent extends BaseEvent {}TransactionStartEvent is an object that broadcaster sends to the entity subscriber before transaction is started.
interface UpdateEvent
interface UpdateEvent<Entity> extends BaseEvent {}UpdateEvent is an object that broadcaster sends to the entity subscriber when entity is being updated in the database.
property databaseEntity
databaseEntity: Entity;Updating entity in the database.
Is set only when one of the following methods are used: .save(), .remove(), .softRemove(), and .recover()
property entity
entity: ObjectLiteral | undefined;Updating entity.
Contains the same data that was passed to the updating method, be it the instance of an entity or the partial entity.
property metadata
metadata: EntityMetadata;Metadata of the entity.
property updatedColumns
updatedColumns: ColumnMetadata[];List of updated columns. In query builder has no affected
property updatedRelations
updatedRelations: RelationMetadata[];List of updated relations. In query builder has no affected
interface UpdateOptions
interface UpdateOptions {}Special options passed to Repository#update and updateAll.
property returning
returning?: ReturningOption;Allows selecting custom RETURNING / OUTPUT clause. Works only on drivers with returning support.
interface UpsertOptions
interface UpsertOptions<Entity> extends InsertOrUpdateOptions {}Special options passed to Repository#upsert
property conflictPaths
conflictPaths: | string[] | { [P in keyof Entity]?: true; };property returning
returning?: ReturningOption;Allows selecting custom RETURNING / OUTPUT clause. Works only on drivers with returning support.
property skipUpdateIfNoValuesChanged
skipUpdateIfNoValuesChanged?: boolean;If true, postgres will skip the update if no values would be changed (reduces writes)
property upsertType
upsertType?: UpsertType;Define the type of upsert to use (currently, CockroachDB only).
If none provided, it will use the default for the database (first one in the list)
interface ValueTransformer
interface ValueTransformer {}Interface for objects that deal with (un)marshalling data.
interface ViewOptions
interface ViewOptions {}View options.
property database
database?: string;Database name that this table resides in if it applies.
property expression
expression: string | ((dataSource: DataSource) => SelectQueryBuilder<any>);View expression.
property materialized
materialized?: boolean;Indicates if view is materialized
property name
name: string;View name.
property schema
schema?: string;Schema name that this table resides in if it applies.
interface WhereExpressionBuilder
interface WhereExpressionBuilder {}Query Builders can implement this interface to support where expression
method andWhere
andWhere: { (where: string, parameters?: ObjectLiteral): this; (where: Brackets, parameters?: ObjectLiteral): this; (where: ObjectLiteral, parameters?: ObjectLiteral): this; (where: ObjectLiteral[], parameters?: ObjectLiteral): this; (subQuery: (qb: this) => string, parameters?: ObjectLiteral): this;};Adds new AND WHERE condition in the query builder. Additionally you can add parameters used in where expression.
method andWhereInIds
andWhereInIds: (ids: any | any[]) => this;Adds new AND WHERE with conditions for the given ids.
Ids are mixed. It means if you have single primary key you can pass a simple id values, for example [1, 2, 3]. If you have multiple primary keys you need to pass object with property names and values specified, for example [{ firstId: 1, secondId: 2 }, { firstId: 2, secondId: 3 }, ...]
method orWhere
orWhere: { (where: string, parameters?: ObjectLiteral): this; (where: Brackets, parameters?: ObjectLiteral): this; (where: ObjectLiteral, parameters?: ObjectLiteral): this; (where: ObjectLiteral[], parameters?: ObjectLiteral): this; (subQuery: (qb: this) => string, parameters?: ObjectLiteral): this;};Adds new OR WHERE condition in the query builder. Additionally you can add parameters used in where expression.
method orWhereInIds
orWhereInIds: (ids: any | any[]) => this;Adds new OR WHERE with conditions for the given ids.
Ids are mixed. It means if you have single primary key you can pass a simple id values, for example [1, 2, 3]. If you have multiple primary keys you need to pass object with property names and values specified, for example [{ firstId: 1, secondId: 2 }, { firstId: 2, secondId: 3 }, ...]
method where
where: { (where: string, parameters?: ObjectLiteral): this; (where: Brackets, parameters?: ObjectLiteral): this; (where: ObjectLiteral, parameters?: ObjectLiteral): this; (where: ObjectLiteral[], parameters?: ObjectLiteral): this; (subQuery: (qb: this) => string, parameters?: ObjectLiteral): this;};Sets WHERE condition in the query builder. If you had previously WHERE expression defined, calling this function will override previously set WHERE conditions. Additionally you can add parameters used in where expression.
method whereInIds
whereInIds: (ids: any | any[]) => this;Sets WHERE condition in the query builder with a condition for the given ids. If you had previously WHERE expression defined, calling this function will override previously set WHERE conditions.
Ids are mixed. It means if you have single primary key you can pass a simple id values, for example [1, 2, 3]. If you have multiple primary keys you need to pass object with property names and values specified, for example [{ firstId: 1, secondId: 2 }, { firstId: 2, secondId: 3 }, ...]
Type Aliases
type ColumnType
type ColumnType = | WithPrecisionColumnType | WithLengthColumnType | UnsignedColumnType | SpatialColumnType | SimpleColumnType | BooleanConstructor | DateConstructor | NumberConstructor | StringConstructor;Any column type column can be.
type DatabaseType
type DatabaseType = | 'aurora-mysql' | 'aurora-postgres' | 'better-sqlite3' | 'capacitor' | 'cockroachdb' | 'cordova' | 'expo' | 'mariadb' | 'mongodb' | 'mssql' | 'mysql' | 'nativescript' | 'oracle' | 'postgres' | 'react-native' | 'sap' | 'spanner' | 'sqljs';Database type.
type DataSourceOptions
type DataSourceOptions = | AuroraMysqlDataSourceOptions | AuroraPostgresDataSourceOptions | BetterSqlite3DataSourceOptions | CapacitorDataSourceOptions | CockroachDataSourceOptions | CordovaDataSourceOptions | ExpoDataSourceOptions | MongoDataSourceOptions | MysqlDataSourceOptions | NativescriptDataSourceOptions | OracleDataSourceOptions | PostgresDataSourceOptions | ReactNativeDataSourceOptions | SapDataSourceOptions | SpannerDataSourceOptions | SqljsDataSourceOptions | SqlServerDataSourceOptions;DataSourceOptions is an interface with settings and options for specific DataSource.
type DeepPartial
type DeepPartial<T> = | T | (T extends Array<infer U> ? DeepPartial<U>[] : T extends Map<infer K, infer V> ? Map<DeepPartial<K>, DeepPartial<V>> : T extends Set<infer M> ? Set<DeepPartial<M>> : T extends object ? { [K in keyof T]?: DeepPartial<T[K]>; } : T);Same as Partial but goes deeper and makes Partial all its properties and sub-properties.
type EntityTarget
type EntityTarget<Entity> = | ObjectType<Entity> | EntitySchema<Entity> | string | { type: Entity; name: string; };Entity target.
type Feature
type Feature = { type: 'Feature'; geometry: Geometry; id?: string | number; bbox?: number[]; properties: { [name: string]: any; } | null;};A feature object which contains a geometry and associated properties. https://datatracker.ietf.org/doc/html/rfc7946#section-3.2
type FeatureCollection
type FeatureCollection = { type: 'FeatureCollection'; bbox?: number[]; features: Feature[];};A collection of feature objects. https://datatracker.ietf.org/doc/html/rfc7946#section-3.3
type FileLoggerOptions
type FileLoggerOptions = { /** * Specify custom path for the log file */ logPath: string;};File logging option.
type FindOperatorType
type FindOperatorType = | 'not' | 'lessThan' | 'lessThanOrEqual' | 'moreThan' | 'moreThanOrEqual' | 'equal' | 'between' | 'in' | 'any' | 'isNull' | 'ilike' | 'like' | 'raw' | 'arrayContains' | 'arrayContainedBy' | 'arrayOverlap' | 'and' | 'jsonContains' | 'or';List of types that FindOperator can be.
type FindOptionsOrder
type FindOptionsOrder<Entity> = { [P in keyof Entity]?: P extends 'toString' ? unknown : FindOptionsOrderProperty<NonNullable<Entity[P]>>;};Order by find options.
type FindOptionsOrderProperty
type FindOptionsOrderProperty<Property> = Property extends Promise<infer I> ? FindOptionsOrderProperty<NonNullable<I>> : Property extends Array<infer I> ? FindOptionsOrderProperty<NonNullable<I>> : Property extends Function ? never : Property extends string ? FindOptionsOrderValue : Property extends number ? FindOptionsOrderValue : Property extends boolean ? FindOptionsOrderValue : Property extends Uint8Array ? FindOptionsOrderValue : Property extends Date ? FindOptionsOrderValue : Property extends ObjectId ? FindOptionsOrderValue : Property extends object ? FindOptionsOrder<Property> | FindOptionsOrderValue : FindOptionsOrderValue;A single property handler for FindOptionsOrder.
type FindOptionsOrderValue
type FindOptionsOrderValue = | 'ASC' | 'DESC' | 'asc' | 'desc' | 1 | -1 | { direction?: 'asc' | 'desc' | 'ASC' | 'DESC'; nulls?: 'first' | 'last' | 'FIRST' | 'LAST'; };Value of order by in find options.
type FindOptionsRelations
type FindOptionsRelations<Entity> = { [P in keyof Entity]?: P extends 'toString' ? unknown : FindOptionsRelationsProperty<NonNullable<Entity[P]>>;};Relations find options.
type FindOptionsRelationsProperty
type FindOptionsRelationsProperty<Property> = Property extends Promise<infer I> ? FindOptionsRelationsProperty<NonNullable<I>> | boolean : Property extends Array<infer I> ? FindOptionsRelationsProperty<NonNullable<I>> | boolean : Property extends string ? never : Property extends number ? never : Property extends boolean ? never : Property extends Function ? never : Property extends Uint8Array ? never : Property extends Date ? never : Property extends ObjectId ? never : Property extends object ? FindOptionsRelations<Property> | boolean : boolean;A single property handler for FindOptionsRelations.
type FindOptionsSelect
type FindOptionsSelect<Entity> = { [P in keyof Entity]?: P extends 'toString' ? unknown : FindOptionsSelectProperty<NonNullable<Entity[P]>>;};Select find options.
type FindOptionsSelectProperty
type FindOptionsSelectProperty<Property> = Property extends Promise<infer I> ? FindOptionsSelectProperty<I> | boolean : Property extends Array<infer I> ? FindOptionsSelectProperty<I> | boolean : Property extends string ? boolean : Property extends number ? boolean : Property extends boolean ? boolean : Property extends Function ? never : Property extends Uint8Array ? boolean : Property extends Date ? boolean : Property extends ObjectId ? boolean : Property extends object ? FindOptionsSelect<Property> | boolean : boolean;A single property handler for FindOptionsSelect.
type FindOptionsWhere
type FindOptionsWhere<Entity> = { [P in keyof Entity]?: P extends 'toString' ? unknown : FindOptionsWhereProperty<NonNullable<Entity[P]>>;};Used for find operations.
type FindOptionsWhereProperty
type FindOptionsWhereProperty< PropertyToBeNarrowed, Property = PropertyToBeNarrowed> = PropertyToBeNarrowed extends Promise<infer I> ? FindOptionsWhereProperty<NonNullable<I>> : PropertyToBeNarrowed extends Array<infer I> ? FindOptionsWhereProperty<NonNullable<I>> : PropertyToBeNarrowed extends Function ? never : PropertyToBeNarrowed extends Uint8Array ? Property | FindOperator<Property> : PropertyToBeNarrowed extends Date ? Property | FindOperator<Property> : PropertyToBeNarrowed extends ObjectId ? Property | FindOperator<Property> : PropertyToBeNarrowed extends string ? Property | FindOperator<Property> : PropertyToBeNarrowed extends number ? Property | FindOperator<Property> : PropertyToBeNarrowed extends boolean ? Property | FindOperator<Property> : PropertyToBeNarrowed extends object ? | FindOptionsWhere<Property> | FindOptionsWhere<Property>[] | EqualOperator<Property> | FindOperator<any> | boolean | Property : Property | FindOperator<Property>;A single property handler for FindOptionsWhere.
The reason why we have both "PropertyToBeNarrowed" and "Property" is that Union is narrowed down when extends is used. It means the result of FindOptionsWhereProperty<1 | 2> doesn't include FindOperator<1 | 2> but FindOperator<1> | FindOperator<2>. So we keep the original Union as Original and pass it to the FindOperator too. Original remains Union as extends is not used for it.
type Geography
type Geography = Geometry;type GeoJSON
type GeoJSON = Geometry | Feature | FeatureCollection;Union of GeoJSON objects.
type Geometry
type Geometry = | Point | LineString | Polygon | MultiPoint | MultiLineString | MultiPolygon | GeometryCollection;Union of Geometry objects.
type GeometryCollection
type GeometryCollection = { type: 'GeometryCollection'; geometries: ( | Point | LineString | Polygon | MultiPoint | MultiLineString | MultiPolygon )[];};Geometry Collection https://datatracker.ietf.org/doc/html/rfc7946#section-3.1.8
type LineString
type LineString = { type: 'LineString'; coordinates: Position[];};LineString geometry object. https://datatracker.ietf.org/doc/html/rfc7946#section-3.1.4
type LoggerOptions
type LoggerOptions = boolean | 'all' | LogLevel[];Logging options.
type LogLevel
type LogLevel = 'query' | 'schema' | 'error' | 'warn' | 'info' | 'log' | 'migration';Log level.
type LogMessage
type LogMessage = { type?: LogMessageType; prefix?: string; message: string | number; format?: LogMessageFormat; parameters?: any[] | ObjectLiteral; additionalInfo?: Record<string, any>;};Log message.
type LogMessageFormat
type LogMessageFormat = 'sql';Log message format.
type LogMessageType
type LogMessageType = | 'log' | 'info' | 'warn' | 'error' | 'query' | 'query-error' | 'query-slow' | 'schema-build' | 'migration';Log message type.
type MixedList
type MixedList<T> = | T[] | { [key: string]: T; };List of T-s passed as an array or object map.
Example usage: entities as an array of imported using import * as syntax.
type MultiLineString
type MultiLineString = { type: 'MultiLineString'; coordinates: Position[][];};MultiLineString geometry object. https://datatracker.ietf.org/doc/html/rfc7946#section-3.1.5
type MultiPoint
type MultiPoint = { type: 'MultiPoint'; coordinates: Position[];};MultiPoint geometry object. https://datatracker.ietf.org/doc/html/rfc7946#section-3.1.3
type MultiPolygon
type MultiPolygon = { type: 'MultiPolygon'; coordinates: Position[][][];};MultiPolygon geometry object. https://datatracker.ietf.org/doc/html/rfc7946#section-3.1.7
type ObjectType
type ObjectType<T> = | { new (): T; } | Function;Represents some Type of the Object.
type OrderByCondition
type OrderByCondition = { [columnName: string]: | ('ASC' | 'DESC') | { order: 'ASC' | 'DESC'; nulls?: 'NULLS FIRST' | 'NULLS LAST'; };};Special object that defines order condition for ORDER BY in sql.
Example 1
{ "name": "ASC", "id": "DESC" }
type Point
type Point = { type: 'Point'; coordinates: Position;};Point geometry object. https://datatracker.ietf.org/doc/html/rfc7946#section-3.1.2
type Polygon
type Polygon = { type: 'Polygon'; coordinates: Position[][];};Polygon geometry object. https://datatracker.ietf.org/doc/html/rfc7946#section-3.1.6
type Position
type Position = number[];Position object. https://datatracker.ietf.org/doc/html/rfc7946#section-3.1.1
type PrepareLogMessagesOptions
type PrepareLogMessagesOptions = { highlightSql: boolean; formatSql: boolean; appendParameterAsComment: boolean; addColonToPrefix: boolean;};Options for prepare log messages
type PrimaryColumnOptions
type PrimaryColumnOptions = ColumnOptions & { nullable?: false;};Describes all primary key column's options. If specified, the nullable field must be set to false.
type QueryDeepPartialEntity
type QueryDeepPartialEntity<T> = _QueryDeepPartialEntity< ObjectLiteral extends T ? unknown : T>;Make all properties in T optional. Deep version.
type QueryPartialEntity
type QueryPartialEntity<T> = { [P in keyof T]?: T[P] | (() => string);};Make all properties in T optional
type Relation
type Relation<T> = T;Wrapper type for relation type definitions in entities. Used to circumvent ESM modules circular dependency issue caused by reflection metadata saving the type of the property.
Example 1
Usage example:
\@Entity()export default class User {\@OneToOne(() => Profile, profile => profile.user)profile: Relation<Profile>;}
type ReplicationMode
type ReplicationMode = 'master' | 'slave';type ReturningOption
type ReturningOption = string | string[];Describes allowed RETURNING clause shapes: either raw SQL string or list of column paths.
Package Files (231)
- common/DeepPartial.d.ts
- common/EntityTarget.d.ts
- common/MixedList.d.ts
- common/ObjectLiteral.d.ts
- common/ObjectType.d.ts
- common/RelationType.d.ts
- connection/ConnectionOptionsReader.d.ts
- data-source/DataSource.d.ts
- data-source/DataSourceOptions.d.ts
- decorator/Check.d.ts
- decorator/Exclusion.d.ts
- decorator/ForeignKey.d.ts
- decorator/Generated.d.ts
- decorator/Index.d.ts
- decorator/Unique.d.ts
- decorator/columns/Column.d.ts
- decorator/columns/CreateDateColumn.d.ts
- decorator/columns/DeleteDateColumn.d.ts
- decorator/columns/ObjectIdColumn.d.ts
- decorator/columns/PrimaryColumn.d.ts
- decorator/columns/PrimaryGeneratedColumn.d.ts
- decorator/columns/UpdateDateColumn.d.ts
- decorator/columns/VersionColumn.d.ts
- decorator/columns/ViewColumn.d.ts
- decorator/columns/VirtualColumn.d.ts
- decorator/entity-view/ViewEntity.d.ts
- decorator/entity/ChildEntity.d.ts
- decorator/entity/Entity.d.ts
- decorator/entity/TableInheritance.d.ts
- decorator/listeners/AfterInsert.d.ts
- decorator/listeners/AfterLoad.d.ts
- decorator/listeners/AfterRecover.d.ts
- decorator/listeners/AfterRemove.d.ts
- decorator/listeners/AfterSoftRemove.d.ts
- decorator/listeners/AfterUpdate.d.ts
- decorator/listeners/BeforeInsert.d.ts
- decorator/listeners/BeforeRecover.d.ts
- decorator/listeners/BeforeRemove.d.ts
- decorator/listeners/BeforeSoftRemove.d.ts
- decorator/listeners/BeforeUpdate.d.ts
- decorator/listeners/EventSubscriber.d.ts
- decorator/options/ColumnOptions.d.ts
- decorator/options/EntityOptions.d.ts
- decorator/options/IndexOptions.d.ts
- decorator/options/JoinColumnOptions.d.ts
- decorator/options/JoinTableOptions.d.ts
- decorator/options/RelationOptions.d.ts
- decorator/options/ValueTransformer.d.ts
- decorator/relations/JoinColumn.d.ts
- decorator/relations/JoinTable.d.ts
- decorator/relations/ManyToMany.d.ts
- decorator/relations/ManyToOne.d.ts
- decorator/relations/OneToMany.d.ts
- decorator/relations/OneToOne.d.ts
- decorator/relations/RelationId.d.ts
- decorator/tree/Tree.d.ts
- decorator/tree/TreeChildren.d.ts
- decorator/tree/TreeLevelColumn.d.ts
- decorator/tree/TreeParent.d.ts
- driver/Driver.d.ts
- driver/sqlserver/MssqlParameter.d.ts
- driver/types/ColumnTypes.d.ts
- driver/types/DatabaseType.d.ts
- driver/types/GeoJsonTypes.d.ts
- driver/types/ReplicationMode.d.ts
- entity-manager/EntityManager.d.ts
- entity-manager/MongoEntityManager.d.ts
- entity-schema/EntitySchema.d.ts
- entity-schema/EntitySchemaColumnOptions.d.ts
- entity-schema/EntitySchemaEmbeddedColumnOptions.d.ts
- entity-schema/EntitySchemaIndexOptions.d.ts
- entity-schema/EntitySchemaOptions.d.ts
- entity-schema/EntitySchemaRelationOptions.d.ts
- error/AlreadyHasActiveConnectionError.d.ts
- error/CannotAttachTreeChildrenEntityError.d.ts
- error/CannotConnectAlreadyConnectedError.d.ts
- error/CannotCreateEntityIdMapError.d.ts
- error/CannotDetermineEntityError.d.ts
- error/CannotExecuteNotConnectedError.d.ts
- error/CannotGetEntityManagerNotConnectedError.d.ts
- error/CannotReflectMethodParameterTypeError.d.ts
- error/CircularRelationsError.d.ts
- error/ColumnTypeUndefinedError.d.ts
- error/ConnectionIsNotSetError.d.ts
- error/ConnectionNotFoundError.d.ts
- error/DataTypeNotSupportedError.d.ts
- error/DriverOptionNotSetError.d.ts
- error/DriverPackageNotInstalledError.d.ts
- error/EntityMetadataNotFoundError.d.ts
- error/EntityNotFoundError.d.ts
- error/EntityPropertyNotFoundError.d.ts
- error/FindRelationsNotFoundError.d.ts
- error/ForbiddenTransactionModeOverrideError.d.ts
- error/InitializedRelationError.d.ts
- error/InsertValuesMissingError.d.ts
- error/LimitOnUpdateNotSupportedError.d.ts
- error/LockNotSupportedOnGivenDriverError.d.ts
- error/MetadataAlreadyExistsError.d.ts
- error/MetadataWithSuchNameAlreadyExistsError.d.ts
- error/MissingDeleteDateColumnError.d.ts
- error/MissingDriverError.d.ts
- error/MissingJoinColumnError.d.ts
- error/MissingJoinTableError.d.ts
- error/MissingPrimaryColumnError.d.ts
- error/MustBeEntityError.d.ts
- error/NamedPlaceholdersNotSupportedError.d.ts
- error/NoConnectionForRepositoryError.d.ts
- error/NoConnectionOptionError.d.ts
- error/NoNeedToReleaseEntityManagerError.d.ts
- error/NoVersionOrUpdateDateColumnError.d.ts
- error/OffsetWithoutLimitNotSupportedError.d.ts
- error/OptimisticLockCanNotBeUsedError.d.ts
- error/OptimisticLockVersionMismatchError.d.ts
- error/PersistedEntityNotFoundError.d.ts
- error/PessimisticLockTransactionRequiredError.d.ts
- error/PrimaryColumnCannotBeNullableError.d.ts
- error/QueryFailedError.d.ts
- error/QueryRunnerAlreadyReleasedError.d.ts
- error/QueryRunnerProviderAlreadyReleasedError.d.ts
- error/RepositoryNotTreeError.d.ts
- error/ReturningStatementNotSupportedError.d.ts
- error/SubjectRemovedAndUpdatedError.d.ts
- error/SubjectWithoutIdentifierError.d.ts
- error/TransactionAlreadyStartedError.d.ts
- error/TransactionNotStartedError.d.ts
- error/TreeRepositoryNotSupportedError.d.ts
- error/TypeORMError.d.ts
- error/UpdateValuesMissingError.d.ts
- error/UsingJoinColumnIsNotAllowedError.d.ts
- error/UsingJoinColumnOnlyOnOneSideAllowedError.d.ts
- error/UsingJoinTableIsNotAllowedError.d.ts
- error/UsingJoinTableOnlyOnOneSideAllowedError.d.ts
- find-options/EqualOperator.d.ts
- find-options/FindManyOptions.d.ts
- find-options/FindOneOptions.d.ts
- find-options/FindOperator.d.ts
- find-options/FindOperatorType.d.ts
- find-options/FindOptionsOrder.d.ts
- find-options/FindOptionsRelations.d.ts
- find-options/FindOptionsSelect.d.ts
- find-options/FindOptionsUtils.d.ts
- find-options/FindOptionsWhere.d.ts
- find-options/FindTreeOptions.d.ts
- find-options/OrderByCondition.d.ts
- find-options/operator/And.d.ts
- find-options/operator/Any.d.ts
- find-options/operator/ArrayContainedBy.d.ts
- find-options/operator/ArrayContains.d.ts
- find-options/operator/ArrayOverlap.d.ts
- find-options/operator/Between.d.ts
- find-options/operator/Equal.d.ts
- find-options/operator/ILike.d.ts
- find-options/operator/In.d.ts
- find-options/operator/IsNull.d.ts
- find-options/operator/JsonContains.d.ts
- find-options/operator/LessThan.d.ts
- find-options/operator/LessThanOrEqual.d.ts
- find-options/operator/Like.d.ts
- find-options/operator/MoreThan.d.ts
- find-options/operator/MoreThanOrEqual.d.ts
- find-options/operator/Not.d.ts
- find-options/operator/Or.d.ts
- find-options/operator/Raw.d.ts
- globals.d.ts
- index.d.ts
- logger/AbstractLogger.d.ts
- logger/AdvancedConsoleLogger.d.ts
- logger/FileLogger.d.ts
- logger/FormattedConsoleLogger.d.ts
- logger/Logger.d.ts
- logger/LoggerOptions.d.ts
- logger/SimpleConsoleLogger.d.ts
- metadata/EntityMetadata.d.ts
- migration/Migration.d.ts
- migration/MigrationExecutor.d.ts
- migration/MigrationInterface.d.ts
- naming-strategy/DefaultNamingStrategy.d.ts
- naming-strategy/NamingStrategyInterface.d.ts
- query-builder/Brackets.d.ts
- query-builder/DeleteQueryBuilder.d.ts
- query-builder/InsertQueryBuilder.d.ts
- query-builder/NotBrackets.d.ts
- query-builder/QueryBuilder.d.ts
- query-builder/QueryPartialEntity.d.ts
- query-builder/RelationQueryBuilder.d.ts
- query-builder/ReturningOption.d.ts
- query-builder/SelectQueryBuilder.d.ts
- query-builder/UpdateQueryBuilder.d.ts
- query-builder/WhereExpressionBuilder.d.ts
- query-builder/result/DeleteResult.d.ts
- query-builder/result/InsertResult.d.ts
- query-builder/result/UpdateResult.d.ts
- query-runner/QueryResult.d.ts
- query-runner/QueryRunner.d.ts
- repository/BaseEntity.d.ts
- repository/MongoRepository.d.ts
- repository/RemoveOptions.d.ts
- repository/Repository.d.ts
- repository/SaveOptions.d.ts
- repository/TreeRepository.d.ts
- repository/UpdateOptions.d.ts
- repository/UpsertOptions.d.ts
- schema-builder/options/TableCheckOptions.d.ts
- schema-builder/options/TableColumnOptions.d.ts
- schema-builder/options/TableExclusionOptions.d.ts
- schema-builder/options/TableForeignKeyOptions.d.ts
- schema-builder/options/TableIndexOptions.d.ts
- schema-builder/options/TableOptions.d.ts
- schema-builder/options/TableUniqueOptions.d.ts
- schema-builder/options/ViewOptions.d.ts
- schema-builder/table/Table.d.ts
- schema-builder/table/TableCheck.d.ts
- schema-builder/table/TableColumn.d.ts
- schema-builder/table/TableExclusion.d.ts
- schema-builder/table/TableForeignKey.d.ts
- schema-builder/table/TableIndex.d.ts
- schema-builder/table/TableUnique.d.ts
- schema-builder/view/View.d.ts
- subscriber/EntitySubscriberInterface.d.ts
- subscriber/event/InsertEvent.d.ts
- subscriber/event/LoadEvent.d.ts
- subscriber/event/QueryEvent.d.ts
- subscriber/event/RecoverEvent.d.ts
- subscriber/event/RemoveEvent.d.ts
- subscriber/event/SoftRemoveEvent.d.ts
- subscriber/event/TransactionCommitEvent.d.ts
- subscriber/event/TransactionRollbackEvent.d.ts
- subscriber/event/TransactionStartEvent.d.ts
- subscriber/event/UpdateEvent.d.ts
- util/InstanceChecker.d.ts
- util/TreeRepositoryUtils.d.ts
Dependencies (10)
Dev Dependencies (3)
Peer Dependencies (15)
Badge
To add a badge like this oneto your package's README, use the codes available below.
You may also use Shields.io to create a custom badge linking to https://www.jsdocs.io/package/typeorm.
- Markdown[](https://www.jsdocs.io/package/typeorm)
- HTML<a href="https://www.jsdocs.io/package/typeorm"><img src="https://img.shields.io/badge/jsDocs.io-reference-blue" alt="jsDocs.io"></a>
- Updated .
Package analyzed in 22482 ms. - Missing or incorrect documentation? Open an issue for this package.
