You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TypeORM对接Oracle:如何移除DDL命令中的双引号?

TypeORM 0.3.x 适配Oracle无引号表/列的解决方案

方案1:实体类显式指定无引号标识符

直接通过@Entity()和@Column()装饰器的name参数,指定大写的无引号名称(Oracle默认会将无引号标识符转为大写),让TypeORM生成的DDL和CRUD操作都使用该名称。

示例代码:

import { Entity, Column, PrimaryGeneratedColumn } from "typeorm";

@Entity({ name: "USERS" }) // 直接指定大写表名
export class User {
  @PrimaryGeneratedColumn({ name: "ID" })
  id: number;

  @Column({ name: "NAME", length: 30 })
  name: string;
}

配置后,Oracle会将USERS识别为无引号对象,客户端直接执行select * from users或select * from USERS都能正常查询。

方案2:全局配置自定义命名策略

通过自定义命名策略,强制TypeORM生成大写无引号的标识符,无需逐个实体配置。

步骤1:创建自定义命名策略

import { SnakeNamingStrategy } from "typeorm";

export class OracleUpperCaseNamingStrategy extends SnakeNamingStrategy {
  tableName(className: string, customName: string): string {
    return customName ? customName.toUpperCase() : super.tableName(className, customName).toUpperCase();
  }

  columnName(propertyName: string, customName: string, embeddedPrefixes: string[]): string {
    return customName ? customName.toUpperCase() : super.columnName(propertyName, customName, embeddedPrefixes).toUpperCase();
  }
}

步骤2:在数据源配置中应用策略

import { DataSource } from "typeorm";
import { OracleUpperCaseNamingStrategy } from "./OracleUpperCaseNamingStrategy";
import { User } from "./entities/User";

export const AppDataSource = new DataSource({
  type: "oracle",
  host: "localhost",
  port: 1521,
  username: "your_username",
  password: "your_password",
  sid: "ORCL",
  entities: [User],
  migrations: ["src/migrations/**/*.ts"],
  namingStrategy: new OracleUpperCaseNamingStrategy(), // 启用自定义策略
});

方案3:迁移脚本与实体配置对齐

如果已手动编写迁移创建无引号表,需确保实体类的name参数与迁移中的表/列名完全一致(大写),避免TypeORM访问错误的带引号对象。

示例迁移脚本SQL:

CREATE TABLE USERS (
  ID NUMBER,
  NAME VARCHAR2(30)
);

对应的实体类必须指定@Entity({ name: "USERS" })及列的name属性,确保标识符匹配。

关键注意事项

  • Oracle无引号标识符会自动转为大写,实体配置的名称必须与数据库中实际对象的大写名称一致。
  • 不要混合使用带引号和无引号标识符,避免生成两个独立的数据库对象。

内容的提问来源于stack exchange,提问作者Joao Luiz Cadore

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 15:03:26