Skip to content

Modify driver.supportedDataTypes to support installed Postgres extension data type. Bypass validation for a column. #10056

Closed

Description

@w1am

Feature Description

I'm using the pgvector extension in my database, which allows me to store data in a vector datatype and perform vector operations such as nearest neighbors with SELECT * FROM items WHERE embedding <-> '[3,1,2]' < 5;. However, TypeORM seems to have an entity validator method that verifies whether the datatype defined in my entity exists.

For instance, the following won't work because the vector datatype doesn't natively exist.

@Entity('items')
export class Item extends BaseEntity {
  @PrimaryGeneratedColumn("increment")
  name: number;

  @Column("vector")
  embedding: number[];
}

In raw SQL, this is how I would achieve it:

CREATE TABLE items (id bigserial PRIMARY KEY, embedding vector(3));
INSERT INTO items (embedding) VALUES ('[1,2,3]'), ('[4,5,6]');
SELECT * FROM items ORDER BY embedding <-> '[3,1,2]' LIMIT 5;

Is there a way to modify or bypass the validation for a column? I could create this column using raw SQL, but that defeats the purpose of using an ORM. Of course, bypassing seems like a terrible idea. Is there a way to do this?

The Solution

I would like to bypass the entity validation for a specific column, as I'm using a custom extension, pgvector, in my database. Defining the type in the TypeORM entity results in a validation error, since the vector datatype isn't natively supported by PostgreSQL.

As a side note, I've installed the extension manually using the command CREATE EXTENSION vector.

Considered Alternatives

I could create this column using raw SQL, but that defeats the purpose of using an ORM.

Additional Context

You may refer to the pgvector documentation https://github.com/pgvector/pgvector

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?

Yes, I have the time, but I don't know how to start. I would need guidance.

I no longer have the time as I'm not actively working on projects that use TypeORM.

Activity

  1. changed the title [-]Modify `driver.supportedDataTypes` to support installed Postgres extension data type. Can I bypass validation for a column?[/-] [+]Modify `driver.supportedDataTypes` to support installed Postgres extension data type. Bypass validation for a column.[/+] on May 17, 2023
  2. Ginden commented on May 17, 2023

    @Ginden
    Contributor

    You can use my work from this PR: #8625

    I'm too busy to complete it, so feel free to rebase/merge and add some tests.

  3. purerosefallen commented on Jun 14, 2023

    @purerosefallen

    How about directly support pgvector in TypeORM? as currently AIGC becoming a thing.

  4. dasheck0 commented on Jun 19, 2023

    @dasheck0

    +1

  5. Thore1954 commented on Jun 25, 2023

    @Thore1954

    I could create this column using raw SQL, but that defeats the purpose of using an ORM.

    ORMs are simply a mapping between tables and classes. As far as typeorm is concerned, the vector datatype is just a string.
    See langchain-ai/langchainjs#1436 for reference.

  6. Marlinski commented on Jul 8, 2023

    @Marlinski

    +1 much needed!

  7. wpride commented on Jul 28, 2023

    @wpride

    I could create this column using raw SQL, but that defeats the purpose of using an ORM.

    ORMs are simply a mapping between tables and classes. As far as typeorm is concerned, the vector datatype is just a string. See hwchase17/langchainjs#1436 for reference.

    Not when it comes to generating migrations

  8. Thore1954 commented on Jul 29, 2023

    @Thore1954

    I could create this column using raw SQL, but that defeats the purpose of using an ORM.

    ORMs are simply a mapping between tables and classes. As far as typeorm is concerned, the vector datatype is just a string. See hwchase17/langchainjs#1436 for reference.

    Not when it comes to generating migrations

    Migrations are in fact raw SQL!

  9. wpride commented on Jul 29, 2023

    @wpride

    I could create this column using raw SQL, but that defeats the purpose of using an ORM.

    ORMs are simply a mapping between tables and classes. As far as typeorm is concerned, the vector datatype is just a string. See hwchase17/langchainjs#1436 for reference.

    Not when it comes to generating migrations

    Migrations are in fact raw SQL!

    That is a fact, I don't know what else they might be. This ORM happens to generate that SQL based on the column annotation. So no, as far as TypeORM is concerned this is not just a string.

  10. Thore1954 commented on Jul 29, 2023

    @Thore1954

    I could create this column using raw SQL, but that defeats the purpose of using an ORM.

    ORMs are simply a mapping between tables and classes. As far as typeorm is concerned, the vector datatype is just a string. See hwchase17/langchainjs#1436 for reference.

    Not when it comes to generating migrations

    Migrations are in fact raw SQL!

    That is a fact, I don't know what else they might be. This ORM happens to generate that SQL based on the column annotation. So no, as far as TypeORM is concerned this is not just a string.

    I happen to write my own migrations (old habits). However, I don't think modifying the generated SQL and replacing character varying with vector would be a problem. Everything else works just the same.

  11. Thore1954 commented on Jul 29, 2023

    @Thore1954

    That being said, I do believe it's a good idea to support pgvector out of the box similar to PostGIS (#2423).

  12. nrathi commented on Sep 3, 2023

    @nrathi

    What's the right workaround type for a vector column:

    @Column({ type: "jsonb" }) or @Column("numeric", { array: true })?

  13. mlois-efimob commented on Mar 11, 2024

    @mlois-efimob

    I worked with other ORMs, and all of them that I remember have some form to define custom data types, this happens in a lot of databases, PostgreSQL is one of this cases where can be user defined types, extensions, and so on.

    Supporting custom column data types allow for all this use cases to fit the common use case for the library, we are exploring this kind of modification. At this time for example we have some tables that have a xid8 data type, that is not supported by typeorm. We workaround by marking the entity as not synced and making all the migration changes by hand, not very fun.

  14. rabin999 commented on Jul 2, 2024

    @rabin999

    It's very painful to achieve this due to the lack of extensibility, any lead on this ?

  15. bkmashiro commented on Aug 31, 2024

    @bkmashiro

    This may bypass datatype check:

    const AppDataSource = new DataSource({
       // your config
    })
    
    // @ts-ignore TypeORM does not support but the database supports
    AppDataSource.driver.supportedDataTypes.push('vector') // add your datatypes here
    
    AppDataSource.initialize()

    To work with Nest.js TypeOrmModule:

    TypeOrmModule.forRootAsync({
      // ... your config
      dataSourceFactory: async (options) => {
        const dataSource = new DataSource(options)
        // @ts-ignore TypeORM does not support but the database supports
        dataSource.driver.supportedDataTypes.push('vector')
        await dataSource.initialize()
        return dataSource
      }
    }),

    Not sure if this will break any functions, but at least it creates table.

    Hope this helps.

  16. itsisaf commented on Feb 4, 2025

    @itsisaf

    This worked for me,
    As bkmashiro said Not sure if this will break any functions, but at least it creates table.

    dataSourceFactory: async (options) => {
            const dataSource = new DataSource(options);
            dataSource.driver.supportedDataTypes.push(
              'vector' as WithLengthColumnType,
            );
            dataSource.driver.withLengthColumnTypes.push(
              'vector' as WithLengthColumnType,
            );
            await dataSource.initialize();
            return dataSource;
          },
    
  17. rohitkhatri commented on Mar 1, 2025

    @rohitkhatri

    Even after adding this, typescript still gives error when using

    @Column({ type: 'vector' })
    embedding: any;

    Below is the error:

    No overload matches this call.
      The last overload gave the following error.
        Object literal may only specify known properties, and 'type' does not exist in type '(type?: any) => Function'.
    
  18. bkmashiro commented on Mar 2, 2025

    @bkmashiro

    Even after adding this, typescript still gives error when using

    @Column({ type: 'vector' })
    embedding: any;

    Below is the error:

    No overload matches this call.
      The last overload gave the following error.
        Object literal may only specify known properties, and 'type' does not exist in type '(type?: any) => Function'.
    

    This issue arises from TypeScript’s strict type checking. Since TypeORM does not natively support the vector type, its type definitions do not recognize it. To bypass this, you can use @ts-expect-error:

    // @ts-expect-error
    @Column('vector')
    embedding: any;

    This suppresses the TypeScript error while still allowing the column definition to work.

    Keep in mind that the dataSourceFactory approach mentioned earlier is intended to bypass TypeORM’s runtime type checks. However, TypeScript’s type system operates at compile time, so you’ll need both workarounds to ensure smooth functionality.

  19. draungminoo commented on Mar 6, 2025

    @draungminoo
    I had to implement these steps to use Postgres vector with TypeORM and Nest.js.

    app.module.ts

    @Module({
      controllers: [AppController, EmrDowntimePcController],
      imports: [
        // TypeORM configuration
        TypeOrmModule.forRootAsync({
          useFactory: () => AppDbConfig,
          dataSourceFactory: async (options) => {
            const dataSource = new DataSource(options);
    
            // Push vector into length column type
            dataSource.driver.supportedDataTypes.push(
              'vector' as WithLengthColumnType,
            );
            dataSource.driver.withLengthColumnTypes.push(
              'vector' as WithLengthColumnType,
            );
    
            // Initialize datasource
            await dataSource.initialize();
    
            return dataSource;
          },
        }),
      ],
      providers: [
        { provide: APP_FILTER, useClass: AppExceptionFilter },
        { provide: APP_GUARD, useClass: AppGuard },
        { provide: SOCKET_IO_ADAPTER, useClass: SocketIoAdapter },
      ],
    })
    export class AppModule {
      constructor() {}
    }

    entity.ts

    @Entity()
    export class LangchainFeed extends AbstractUuidEntity<LangchainFeed> {
      @Column({ type: 'vector' as any, nullable: true }) // Use type vector here but need to cast as any, otherwise TS will show an error
      embedding_vector: number[];
    
      @Column({ type: 'text' })
      document_content: string;
    
      @Column({ type: 'text' })
      collection_name: string;
    
      @Column({ type: 'jsonb', nullable: true })
      extra_metadata: Record<string, any>;
    
      @Column({ type: 'int', nullable: true })
      chunk_size: number;
    
      @Column({ type: 'int', nullable: true })
      chunk_overlap: number;
    
      @Column({ type: 'text', nullable: true })
      group: string;
    
      @BeforeUpdate()
      @BeforeInsert()
      stringifyVector() {
        // Convert number array to string format, so that Postgres understands it as a vector
        // e.g. '[0.9, 0.1, 0.7]'
        if (this.embedding_vector && Array.isArray(this.embedding_vector)) {
          this.embedding_vector = JSON.stringify(this.embedding_vector) as any;
        }
      }
    }

    abstract-uuid-entity.ts

    import { PrimaryColumn } from 'typeorm';
    import { v7 as uuidv7 } from 'uuid';
    import { AbstractEntityNoPrimary } from './entity-no-primary.abstract';
    
    export class AbstractUuidEntity<T> extends AbstractEntityNoPrimary<T> {
      @PrimaryColumn({
        type: 'uuid',
      })
      id: string;
    
      constructor(entity: Partial<T>) {
        // Super entity
        super(entity);
    
        // Assign entity
        Object.assign(this, entity);
    
        // Assign UUID
        if (!this.id) {
          this.id = uuidv7();
        }
      }
    }
  20. self-assigned this
    on May 3, 2025
  21. nilsabegg commented on Aug 7, 2025

    @nilsabegg

    @draungminoo Thank you so much, worked for me!

  22. reopened this on Aug 7, 2025
  23. piotr-szewczyk commented on May 23, 2026

    @piotr-szewczyk

    Wanted to drop my workaround here in case it saves someone a debugging session — I actually shipped a migration that dropped the column before I noticed.

    If you leave the vector column unmapped on the entity (because @column({ type: "vector" }) throws DataTypeNotSupportedError), the migration generator decides the column is "extra" and emits DROP COLUMN "embedding" next time someone runs migration:generate. Same thing for the HNSW index — TypeORM doesn't know about USING hnsw so it just wants to nuke it.

    1. The catch here is that supportedDataTypes is set in the driver's constructor, not on the prototype — so trying to push to PostgresDriver.prototype.supportedDataTypes at import time blows up with "Cannot read properties of undefined". I hooked connect() instead, which runs once per DataSource before any entity validation:
    // pgvector-typeorm.ts
    import { fromSql, toSql } from "pgvector";
    import { ValueTransformer } from "typeorm";
    import { PostgresDriver } from "typeorm/driver/postgres/PostgresDriver";
    
    const VECTOR_TYPE = "vector" as never;
    const originalConnect = PostgresDriver.prototype.connect;
    
    PostgresDriver.prototype.connect = function (this: PostgresDriver) {
        if (this.supportedDataTypes && !this.supportedDataTypes.includes(VECTOR_TYPE)) {
            this.supportedDataTypes.push(VECTOR_TYPE);
        }
        return originalConnect.call(this);
    };
    
    export const vectorTransformer: ValueTransformer = {
        to: (v: number[] | null | undefined) => (v == null ? v : toSql(v)),
        from: (v: string | null) => (v == null ? v : fromSql(v))
    };

    Import this to your ormconfig.ts (or wherever your DataSource lives), so it runs both for the app and for the CLI:

    import "./pgvector-typeorm";
    1. Entity column.
    @Column({ type: "vector" as never, name: "embedding", select: false, transformer: vectorTransformer })
    embedding: number[];
    1. HNSW index. With it the generator stops touching the index:
    @Index("idx_schema_embedding_vector", ["embedding"], { synchronize: false } as never)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions