View entity is a class that maps to a database view. You can create a view entity by defining a new class and mark it with @ViewEntity():
@ViewEntity() accepts following options:
name - view name. If not specified, then view name is generated from entity class name.
database - database name in selected DB server.
schema - schema name.
expression - view definition. Required parameter.
dependsOn - List of other views on which the current views depends. If your view uses another view in it's definition, you can add it here so that migrations are generated in the correct order.
expression can be string with properly escaped columns and tables, depend on database used (postgres in example):
@ViewEntity({ expression:` SELECT "post"."id" AS "id", "post"."name" AS "name", "category"."name" AS "categoryName" FROM "post" "post" LEFT JOIN "category" "category" ON "post"."categoryId" = "category"."id" `})
Note: parameter binding is not supported due to drivers limitations. Use the literal parameters instead.
@ViewEntity({expression: (dataSource:DataSource) => dataSource.createQueryBuilder().select("post.id","id").addSelect("post.name","name").addSelect("category.name","categoryName").from(Post,"post").leftJoin(Category,"category","category.id = post.categoryId").where("category.name = :name", { name:"Cars" }) // <-- this is wrong.where("category.name = 'Cars'") // <-- and this is right})
Each view entity must be registered in your data source options:
To map data from view into the correct entity columns you must mark entity columns with @ViewColumn() decorator and specify these columns as select statement aliases.
example with string expression definition:
import { ViewEntity, ViewColumn } from"typeorm"@ViewEntity({ expression:` SELECT "post"."id" AS "id", "post"."name" AS "name", "category"."name" AS "categoryName" FROM "post" "post" LEFT JOIN "category" "category" ON "post"."categoryId" = "category"."id" `,})exportclassPostCategory { @ViewColumn() id:number @ViewColumn() name:string @ViewColumn() categoryName:string}
transformer: { from(value: DatabaseType): EntityType, to(value: EntityType): DatabaseType } - Used to unmarshal properties of arbitrary type DatabaseType supported by the database into a type EntityType. Arrays of transformers are also supported and are applied in reverse order when reading. Note that because database views are read-only, transformer.to(value) will never be used.
Materialized View Indices
There's support for creation of indices for materialized views if using PostgreSQL.