MySQL / MariaDB
MySQL、MariaDB 和 Amazon Aurora MySQL 都被支持为 TypeORM 驱动。
安装
npm install mysql2数据源选项
通用数据源选项请参阅数据源选项。你可以使用数据源类型 mysql、mariadb 和 aurora-mysql 来连接相应的数据库。
url- 建立连接的连接 url。请注意,其他数据源选项会覆盖从 url 中设置的参数。host- 数据库主机。port- 数据库主机端口。mysql 默认端口是3306。username- 数据库用户名。password- 数据库密码。database- 数据库名。socketPath- 数据库 socket 路径。poolSize- 每个连接中连接池应包含的最大客户端数量。charset和collation- 连接所用的字符集 / 排序规则。如果指定了 SQL 层面的字符集(例如 utf8mb4),则使用该字符集的默认排序规则。timezone- MySQL 服务器上配置的时区。它用于在服务器日期/时间值与 JavaScript Date 对象之间互相转换类型。可以是local、Z,或+HH:MM、-HH:MM形式的偏移量。(默认:local)connectTimeout- 初始连接 MySQL 服务器期间发生超时前的毫秒数。(默认:10000)acquireTimeout- 初始连接 MySQL 服务器期间发生超时前的毫秒数。它与connectTimeout的区别在于它管控的是 TCP 连接超时,而 connectTimeout 不是。(默认:10000)insecureAuth- 允许连接那些要求使用旧版(不安全)认证方法的 MySQL 实例。(默认:false)supportBigNumbers- 在处理数据库中的大数字(BIGINT和DECIMAL列)时,你应当启用该选项(默认:true)bigNumberStrings- 同时启用supportBigNumbers和bigNumberStrings会强制大数字(BIGINT和DECIMAL列)始终以 JavaScript String 对象返回(默认:true)。启用supportBigNumbers但不启用bigNumberStrings时,只有当大数字无法用 JavaScript Number 对象准确表示时(即超出[-2^53, +2^53]范围时)才返回 String 对象,否则返回 Number 对象。如果supportBigNumbers被禁用,该选项会被忽略。dateStrings- 强制日期类型(TIMESTAMP、DATETIME、DATE)以字符串返回,而不是膨胀为 JavaScript Date 对象。可以是 true/false,也可以是类型名数组,数组中的类型保持为字符串。(默认:false)debug- 把协议细节打印到 stdout。可以是 true/false,也可以是应被打印的数据包类型名数组。(默认:false)trace- 在 Error 上生成堆栈跟踪,以包含库入口的调用位置("长堆栈跟踪")。对大多数调用有轻微性能损耗。(默认:true)multipleStatements- 允许每条查询包含多条 mysql 语句。请谨慎使用,它可能扩大 SQL 注入攻击的范围。(默认:false)legacySpatialSupport- 使用GeomFromText和AsText这类旧版空间函数,它们在 MySQL 8.0 中已被符合标准的ST_GeomFromText或ST_AsText取代。(默认:false)flags- 要使用的连接标志列表,用于替代默认标志。也可以把默认标志加入黑名单。更多信息请查看 Connection Flags。ssl- 带 SSL 参数的对象,或包含 SSL 配置文件名的字符串。参见 SSL 选项。enableQueryTimeout- 如果为 maxQueryExecutionTime 指定了值,那么除了在查询超过该时间上限时生成一条警告日志外,指定的 maxQueryExecutionTime 值还会被用作该查询的超时时间。更多信息请查看 mysql timeouts。
更多选项可以加到 extra 对象中,它们会被直接传给客户端库。更多内容见 mysql2 文档。
列类型
bit、int、integer、tinyint、smallint、mediumint、bigint、float、double、double precision、dec、decimal、numeric、fixed、bool、boolean、date、datetime、timestamp、time、year、char、nchar、national char、varchar、nvarchar、national varchar、text、tinytext、mediumtext、blob、longtext、tinyblob、mediumblob、longblob、enum、set、json、binary、varbinary、geometry、point、linestring、polygon、multipoint、multilinestring、multipolygon、geometrycollection、uuid、inet4、inet6
注意:
uuid、inet4和inet6仅在 MariaDB 中可用,并且需要相应的版本支持。
enum 列类型
参见 enum 列类型。
set 列类型
set 列类型受 mariadb 和 mysql 支持。有多种可能的列定义方式:
使用 TypeScript 枚举:
export enum UserRole {
ADMIN = "admin",
EDITOR = "editor",
GHOST = "ghost",
}
@Entity()
export class User {
@PrimaryGeneratedColumn()
id: number
@Column({
type: "set",
enum: UserRole,
default: [UserRole.GHOST, UserRole.EDITOR],
})
roles: UserRole[]
}使用带 set 值的数组:
export type UserRoleType = "admin" | "editor" | "ghost"
@Entity()
export class User {
@PrimaryGeneratedColumn()
id: number
@Column({
type: "set",
enum: ["admin", "editor", "ghost"],
default: ["ghost", "editor"],
})
roles: UserRoleType[]
}向量类型
MySQL, MariaDB and Amazon Aurora MySQL are supported as TypeORM drivers.
Installation
npm install mysql2Data Source Options
See Data Source Options for the common data source options. You can use the data source types mysql, mariadb and aurora-mysql to connect to the respective databases.
url- Connection url where the connection is performed. Please note that other data source options will override parameters set from url.host- Database host.port- Database host port. Default mysql port is3306.username- Database username.password- Database password.database- Database name.socketPath- Database socket path.poolSize- Maximum number of clients the pool should contain for each connection.charsetandcollation- The charset/collation for the connection. If an SQL-level charset is specified (like utf8mb4) then the default collation for that charset is used.timezone- the timezone configured on the MySQL server. This is used to typecast server date/time values to JavaScript Date object and vice versa. This can belocal,Z, or an offset in the form+HH:MMor-HH:MM. (Default:local)connectTimeout- The milliseconds before a timeout occurs during the initial connection to the MySQL server. (Default:10000)acquireTimeout- The milliseconds before a timeout occurs during the initial connection to the MySQL server. It differs fromconnectTimeoutas it governs the TCP connection timeout whereas connectTimeout does not. (default:10000)insecureAuth- Allow connecting to MySQL instances that ask for the old (insecure) authentication method. (Default:false)supportBigNumbers- When dealing with big numbers (BIGINTandDECIMALcolumns) in the database, you should enable this option (Default:true)bigNumberStrings- Enabling bothsupportBigNumbersandbigNumberStringsforces big numbers (BIGINTandDECIMALcolumns) to be always returned as JavaScript String objects (Default:true). EnablingsupportBigNumbersbut leavingbigNumberStringsdisabled will return big numbers as String objects only when they cannot be accurately represented with JavaScript Number objects (which happens when they exceed the[-2^53, +2^53]range), otherwise they will be returned as Number objects. This option is ignored ifsupportBigNumbersis disabled.dateStrings- Force date types (TIMESTAMP,DATETIME,DATE) to be returned as strings rather than inflated into JavaScript Date objects. Can be true/false or an array of type names to keep as strings. (Default:false)debug- Prints protocol details to stdout. Can be true/false or an array of packet type names that should be printed. (Default:false)trace- Generates stack traces on Error to include call site of library entrance ("long stack traces"). Slight performance penalty for most calls. (Default:true)multipleStatements- Allow multiple mysql statements per query. Be careful with this, it could increase the scope of SQL injection attacks. (Default:false)legacySpatialSupport- Use legacy spatial functions likeGeomFromTextandAsTextwhich have been replaced by the standard-compliantST_GeomFromTextorST_AsTextin MySQL 8.0. (Default:false)flags- List of connection flags to use other than the default ones. It is also possible to blacklist default ones. For more information, check Connection Flags.ssl- object with SSL parameters or a string containing the name of the SSL profile. See SSL options.enableQueryTimeout- If a value is specified for maxQueryExecutionTime, in addition to generating a warning log when a query exceeds this time limit, the specified maxQueryExecutionTime value is also used as the timeout for the query. For more information, check mysql timeouts.
Additional options can be added to the extra object and will be passed directly to the client library. See more in the mysql2 documentation.
Column Types
bit, int, integer, tinyint, smallint, mediumint, bigint, float, double, double precision, dec, decimal, numeric, fixed, bool, boolean, date, datetime, timestamp, time, year, char, nchar, national char, varchar, nvarchar, national varchar, text, tinytext, mediumtext, blob, longtext, tinyblob, mediumblob, longblob, enum, set, json, binary, varbinary, geometry, point, linestring, polygon, multipoint, multilinestring, multipolygon, geometrycollection, uuid, inet4, inet6
Note:
uuid,inet4, andinet6are only available for MariaDB and for the respective versions that made them available.
enum column type
See enum column type.
set column type
set column type is supported by mariadb and mysql. There are various possible column definitions:
Using TypeScript enums:
export enum UserRole {
ADMIN = "admin",
EDITOR = "editor",
GHOST = "ghost",
}
@Entity()
export class User {
@PrimaryGeneratedColumn()
id: number
@Column({
type: "set",
enum: UserRole,
default: [UserRole.GHOST, UserRole.EDITOR],
})
roles: UserRole[]
}Using an array with set values:
export type UserRoleType = "admin" | "editor" | "ghost"
@Entity()
export class User {
@PrimaryGeneratedColumn()
id: number
@Column({
type: "set",
enum: ["admin", "editor", "ghost"],
default: ["ghost", "editor"],
})
roles: UserRoleType[]
}Vector Types
MySQL supports the VECTOR type since version 9.0, while in MariaDB, vectors are available since 11.7.