数据源选项
什么是 DataSourceOptions?
DataSourceOptions 是你在创建新的 DataSource 实例时传入的数据源配置。不同的 RDBMS 有各自特定的选项。
通用数据源选项
type- RDBMS 类型。你必须指定所使用的数据库引擎。可选值为:"mysql"、"postgres"、"cockroachdb"、"sap"、"spanner"、"mariadb"、"cordova"、"react-native"、"nativescript"、"sqljs"、"oracle"、"mssql"、"mongodb"、"aurora-mysql"、"aurora-postgres"、"expo"、"better-sqlite3"、"capacitor"。该选项是 必填 的。extra- 传递给底层驱动的额外选项。如果你想给底层数据库驱动传更多设置,就用它。entities- 要为该数据源加载并使用的实体或实体 Schema。它接受实体类、实体 schema 类,以及用于加载的目录路径。目录支持 glob 模式。示例:entities: [Post, Category, "entities/*.js", "modules/**/entities/*.js"]。进一步了解实体。进一步了解实体 Schema。subscribers- 要为该数据源加载并使用的订阅者。它接受实体类以及用于加载的目录。目录支持 glob 模式。示例:subscribers: [PostSubscriber, AppSubscriber, "subscribers/*.js", "modules/**/subscribers/*.js"]。进一步了解订阅者。logging- 表示是否启用日志。如果设为true,则查询日志和错误日志都会被启用。你也可以指定要启用哪些类型的日志,例如["query", "error", "schema"]。进一步了解日志。logger- 用于记录日志的日志记录器。可选值为 "advanced-console"、"formatted-console"、"simple-console" 和 "file"。默认是 "advanced-console"。你也可以指定一个实现了Logger接口的日志记录器类。进一步了解日志。maxQueryExecutionTime- 如果查询执行时间超过给定的最大执行时间(单位毫秒),日志记录器就会记录这条查询。poolSize- 配置池中活跃连接的最大数量。namingStrategy- 用于为数据库中的表和列命名的命名策略。entityPrefix- 为该数据源上的所有表(或集合)添加给定字符串作为前缀。entitySkipConstructor- 表示 TypeORM 在从数据库反序列化实体时是否应跳过构造函数。注意,不调用构造函数时,私有属性和默认属性都不会按预期工作。dropSchema- 每次初始化数据源时都删除结构。请谨慎使用该选项,不要在生产环境中使用——否则你会丢失全部生产数据。该选项在调试和开发阶段很有用。synchronize- 表示是否在每次应用启动时自动创建数据库结构。请谨慎使用该选项,不要在生产环境中使用——否则你可能丢失生产数据。该选项在调试和开发阶段很有用。作为替代方案,你可以使用 CLI 运行 schema:sync 命令。注意,对 MongoDB 数据库它不会创建结构,因为 MongoDB 是无模式的。它只会通过创建索引来同步。migrations- 要为该数据源加载并使用的迁移migrationsRun- 表示是否在每次应用启动时自动运行迁移。migrationsTableName- 数据库中用于存放已执行迁移信息的表名。migrationsTransactionMode- 控制运行迁移时的事务模式。metadataTableName- 数据库中用于存放表元数据信息的表名。默认情况下,这张表叫 "typeorm_metadata"。cache- 启用实体结果缓存。你也可以在这里配置缓存类型和其他缓存选项。在这里阅读更多关于缓存的内容。isolateWhereStatements- 启用 where 语句隔离,自动用括号包裹每个 where 子句。例如.where("user.firstName = :search OR user.lastName = :search")会变成WHERE (user.firstName = ? OR user.lastName = ?),而不是WHERE user.firstName = ? OR user.lastName = ?invalidWhereValuesBehavior- 控制高层操作(查找操作、repository 方法、EntityManager 方法)中 where 条件里 null 与 undefined 值的处理方式。不直接影响 QueryBuilder 的.where()。null的行为选项:'ignore'- 跳过值为 null 的属性'sql-null'- 把 null 转换为 SQL NULL'throw'(默认)- 抛出错误
undefined的行为选项:'ignore'- 跳过值为 undefined 的属性'throw'(默认)- 抛出错误
示例:
invalidWhereValuesBehavior: { null: 'sql-null', undefined: 'ignore' }。进一步了解 null 与 undefined 的处理。
数据源选项示例
下面是一个针对 mysql 的数据源选项小示例:
{
host: "localhost",
port: 3306,
username: "test",
password: "test",
database: "test",
logging: true,
synchronize: true,
entities: [__dirname + "/entities/**/*{.js,.ts}"],
subscribers: [__dirname + "/subscribers/**/*{.js,.ts}"],
entitySchemas: [__dirname + "/schemas/**/*.json"],
migrations: [__dirname + "/migrations/**/*{.js,.ts}"]
}What is DataSourceOptions?
DataSourceOptions is a data source configuration you pass when you create a new DataSource instance. Different RDBMS-es have their own specific options.
Common data source options
type- RDBMS type. You must specify what database engine you use. Possible values are: "mysql", "postgres", "cockroachdb", "sap", "spanner", "mariadb", "cordova", "react-native", "nativescript", "sqljs", "oracle", "mssql", "mongodb", "aurora-mysql", "aurora-postgres", "expo", "better-sqlite3", "capacitor". This option is required.extra- Extra options to be passed to the underlying driver. Use it if you want to pass extra settings to the underlying database driver.entities- Entities, or Entity Schemas, to be loaded and used for this data source. It accepts entity classes, entity schema classes, and directory paths from which to load. Directories support glob patterns. Example:entities: [Post, Category, "entities/*.js", "modules/**/entities/*.js"]. Learn more about Entities. Learn more about Entity Schemas.subscribers- Subscribers to be loaded and used for this data source. It accepts both entity classes and directories from which to load. Directories support glob patterns. Example:subscribers: [PostSubscriber, AppSubscriber, "subscribers/*.js", "modules/**/subscribers/*.js"]. Learn more about Subscribers.logging- Indicates if logging is enabled or not. If set totruethen query and error logging will be enabled. You can also specify different types of logging to be enabled, for example["query", "error", "schema"]. Learn more about Logging.logger- Logger to be used for logging purposes. Possible values are "advanced-console", "formatted-console", "simple-console" and "file". Default is "advanced-console". You can also specify a logger class that implementsLoggerinterface. Learn more about Logging.maxQueryExecutionTime- If query execution time exceed this given max execution time (in milliseconds) then logger will log this query.poolSize- Configure maximum number of active connections is the pool.namingStrategy- Naming strategy to be used to name tables and columns in the database.entityPrefix- Prefixes with the given string all tables (or collections) on this data source.entitySkipConstructor- Indicates if TypeORM should skip constructors when deserializing entities from the database. Note that when you do not call the constructor both private properties and default properties will not operate as expected.dropSchema- Drops the schema each time data source is being initialized. Be careful with this option and don't use this in production - otherwise you'll lose all production data. This option is useful during debug and development.synchronize- Indicates if database schema should be auto created on every application launch. Be careful with this option and don't use this in production - otherwise you can lose production data. This option is useful during debug and development. As an alternative to it, you can use CLI and run schema:sync command. Note that for MongoDB database it does not create schema, because MongoDB is schemaless. Instead, it syncs just by creating indexes.migrations- Migrations to be loaded and used for this data sourcemigrationsRun- Indicates if migrations should be auto-run on every application launch.migrationsTableName- Name of the table in the database which is going to contain information about executed migrations.migrationsTransactionMode- Controls transaction mode when running migrations.metadataTableName- Name of the table in the database which is going to contain information about table metadata. By default, this table is called "typeorm_metadata".cache- Enables entity result caching. You can also configure cache type and other cache options here. Read more about caching here.isolateWhereStatements- Enables where statement isolation, wrapping each where clause in brackets automatically. eg..where("user.firstName = :search OR user.lastName = :search")becomesWHERE (user.firstName = ? OR user.lastName = ?)instead ofWHERE user.firstName = ? OR user.lastName = ?invalidWhereValuesBehavior- Controls how null and undefined values are handled in where conditions for high-level operations (find operations, repository methods, EntityManager methods). Does not affect QueryBuilder's.where()directly.nullbehavior options:'ignore'- skips null properties'sql-null'- transforms null to SQL NULL'throw'(default) - throws an error
undefinedbehavior options:'ignore'- skips undefined properties'throw'(default) - throws an error
Example:
invalidWhereValuesBehavior: { null: 'sql-null', undefined: 'ignore' }.Learn more about Null and Undefined Handling.
Data Source Options example
Here is a small example of data source options for mysql:
{
host: "localhost",
port: 3306,
username: "test",
password: "test",
database: "test",
logging: true,
synchronize: true,
entities: [__dirname + "/entities/**/*{.js,.ts}"],
subscribers: [__dirname + "/subscribers/**/*{.js,.ts}"],
entitySchemas: [__dirname + "/schemas/**/*.json"],
migrations: [__dirname + "/migrations/**/*{.js,.ts}"]
}