Skip to content

Ignore column when generating migration #11277

Closed

Description

@alexeychikk

Feature Description

There is an option to ignore entity when generating migration

@Entity({ synchronize: false })

But there is no such option for @Column().

The Solution

It would be nice to have @Column({ synchronize: false })

Considered Alternatives

I didn't find any alternatives to this

Additional Context

The problem is that I have a column like this one:

  @Column({ insert: false, update: false, select: false })
  fooBar?: boolean;

It's not persisted to DB, I assign a result of custom .addSelect(...) to it.
But when I generate a migration, typeorm treats it as real column and generates ALTER TABLE ... for it.
So I need a mechanism to ignore a column in migration generation.

Relevant Database Driver(s)

  • aurora-mysql
  • aurora-postgres
  • better-sqlite3
  • cockroachdb
  • cordova
  • expo
  • mongodb
  • mysql
  • nativescript
  • oracle
  • postgres
  • react-native
  • sap
  • spanner
  • sqlite
  • sqlite-abstract
  • sqljs
  • sqlserver

Are you willing to resolve this issue by submitting a Pull Request?

No, I don’t have the time and I’m okay to wait for the community / maintainers to resolve this issue.

Activity

  1. alumni commented on Feb 7, 2025

    @alumni
    Collaborator

    Then add the property to the entity class, but don't add the column decorator 😉

    A more complex example would be this: https://typeorm.io/select-query-builder#joining-and-mapping-functionality

    The profilePhoto property is not decorated in any way (it's not a column nor a relation), but you can simply specify it and fill the value via the queryBuilder, like in your example.

  2. alexeychikk commented on Feb 10, 2025

    @alexeychikk
    Author

    @alumni This doesn't work if I need to select some primitive data and assign to entity's field. It seems to only work with actual joins. And if I just don't add the column decorator, the field will be stripped out when typeorm deserializes data into entity class instances when I call qb.getMany().

  3. alexeychikk commented on Feb 10, 2025

    @alexeychikk
    Author

    I came up with the following workaround:

    import { getMetadataArgsStorage } from 'typeorm';
    
    export function IgnoredColumn(): PropertyDecorator {
      return (target: object, propertyKey: string | symbol) => {
        getMetadataArgsStorage().columns.push({
          target: target.constructor,
          propertyName: propertyKey as string,
          mode: 'virtual-property',
          options: {
            insert: false,
            update: false,
            select: false,
          },
        });
      };
    }
    
    @Entity()
    class MyEntity {
      //...
      @IgnoredColumn()
      fooBar?: boolean;
      //...
    }
  4. alumni commented on Feb 10, 2025

    @alumni
    Collaborator

    I think the workaround would not be needed. This should work:

    class MyEntity {
      @Column()
      id: number;
    
      fooBar?: number;
    }
    
    entities = await conn.createQueryBuilder()
      .from(MyEntity, 'M')
      .addSelect('"M"."id" + 1', 'fooBar')
      .getMany();

    Alternatively, you can use a VirtualColumn (if the formula is always the same):

    class MyEntity {
      @Column()
      id: number;
    
      @VirtualColumn('number', { query: (alias) => `${alias}."id" + 1` })
      fooBar: number;
    }
    
    entities = await conn.createQueryBuilder()
      .from(MyEntity, 'M')
      .getMany();

    In the last release a bug was introduced, where the virtual column is not automatically selected (workaround: manually add it with addSelect), but hopefully we'll fix this in the next release (there are multiple PRs trying to fix it).

  5. alexeychikk commented on Feb 10, 2025

    @alexeychikk
    Author

    @alumni The first option just doesn't work. As I already mentioned above, typeorm strips out all non-column fields. Here is an example sandbox that proves this https://codesandbox.io/p/devbox/heuristic-shirley-85hmd6?file=%2Fsrc%2Fmain.ts%3A60%2C18&workspaceId=ws_C6Tehm4iGBaoLuffpPd45F

    Second option is not suitable for me because I need query builder instance.

  6. jovanadjuric commented on Feb 10, 2025

    @jovanadjuric
    Contributor

    You can add an @AfterLoad() entity listener to your entity that would set the value of your undecorated field every time the entity is loaded. Would that make sense for your use case?

  7. alexeychikk commented on Feb 10, 2025

    @alexeychikk
    Author

    @jovanadjuric No, unfortunately that doesn't work for me, because the data I need to assign to the non-persistent field exists only in the query builder, as a complex select expression.

  8. alumni commented on Feb 10, 2025

    @alumni
    Collaborator

    getMany doesn't work because RawSqlResultsToEntityTransformer only handles properties that is aware of (columns, relations etc.). We use getRawMany instead to get unknown columns.

    AfterLoad does not have access to the raw result. You can use it only to calculate something based on the information that is already available in the entity.

    The workaround above is a simplified version of what VirtualColumn does (sets mode = 'virtual-property', which BTW, already implies that it's not insertable nor updatable). The special thing about VirtualColumn is that it requires a way to calculate the value (and you can't toggle if it's selectable by default or not).

    I'm not sure how selecting is done for the SQLite driver, seems we do a SELECT * which ignores VirtualColumns. Other drivers are explicitly adding the columns to the select clause (including the query for the virtual column).

  9. alexeychikk commented on Feb 10, 2025

    @alexeychikk
    Author

    @alumni getRawMany implies that I'll have to map raw records into entities myself which is very inconvenient when I have a custom complex query builder, that has multiple nested joins etc.
    Thanks for you help anyway.

  10. TLCRATEAM commented on Aug 1, 2025

    @TLCRATEAM

    hi @alexeychikk, had you found the solution?
    I'm facing the same issue now. However I don't want to use the @VirtualColumn decorator since it always excecutes when query, which affects the query performance if the virtual column is a complex sql.

  11. alexeychikk commented on Aug 1, 2025

    @alexeychikk
    Author

    @TLCRATEAM I use this:

    import { getMetadataArgsStorage } from 'typeorm/globals';
    
    export function IgnoredColumn({ name }: { name?: string } = {}): PropertyDecorator {
      return (target: object, propertyKey: string | symbol) => {
        getMetadataArgsStorage().columns.push({
          target: target.constructor,
          propertyName: propertyKey as string,
          mode: 'virtual-property',
          options: {
            insert: false,
            update: false,
            select: false,
            name,
          },
        });
      };
    }
    
    @Entity()
    class MyEntity {
      @Column()
      regularColumn: string;
    
      @IgnoredColumn()
      yourColumn: whatever;
    }
  12. TLCRATEAM commented on Aug 1, 2025

    @TLCRATEAM

    @alexeychikk ah thank you
    I choose this approach (custom decorator) as well :D

  13. alumni commented on Aug 2, 2025

    @alumni
    Collaborator

    @VirtualColumn is the correct answer. Will allow the users to make it initially non-selectable in #11586.

  14. TLCRATEAM commented on Aug 4, 2025

    @TLCRATEAM

    @VirtualColumn is the correct answer. Will allow the users to make it initially non-selectable in #11586.

    Thank you @alumni .
    Good to hear that.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions