Search code examples
nestjstypeorm

TypeORM query existing view from Database


For reference: I am using NestJS (TypeORM) with a SQL Server Database

Is there a way in TypeORM to query an existing view on a database? I am aware of the View Entity of TypeORM, but the description of the options list the "expression" parameter as required. Since the view already exists on the database, I don't need (and don't want to) recreate it in my backend.

I've found that some people do something like this:

import { ViewEntity} from 'typeorm';

@ViewEntity({
    expression: 'select * from database_view'}) 

}
export class View {}

But that seems more like a workaround, rather an actual solution?

What is also interesting is that I do not get an error if I just use the @ViewEntity without the expression property like so:

import { ViewEntity} from 'typeorm';

@ViewEntity() 
export class View extends BaseEntity {
   @Column()
   col1: string
}

The documentation regarding the ViewEntity also leaves a lot of room for interpretation in my opinion: "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()"

The first sentence to me sounds like I am able to map to an (existing) view on the database, but the second sentence then says you need to "create a view entity".

So the question: What would be the proper way to query an existing View on the database, without recreating the View in the backend?


Solution

  • I agree that the documentation is confusing, 'expression' option is not required and you can use 'synchronize' option.

    https://github.com/typeorm/typeorm/blob/master/src/decorator/options/ViewEntityOptions.ts

    @ViewEntity({
      name: 'existing_view',
      synchronize: false
    })
    

    or

    @ViewEntity('existing_view', {
      synchronize: false
    })