表结构生成器
介绍
Schema
类提供了与数据库无关的表操作方式。
在开始之前,确定已经配置好了DatabaseManager
,参考基本操作章节。
from orator import DatabaseManager, Schema
config = {
'mysql': {
'driver': 'mysql',
'host': 'localhost',
'database': 'database',
'username': 'root',
'password': '',
'prefix': ''
}
}
db = DatabaseManager(config)
schema = Schema(db)
创建和删除表
要创建表,使用create
方法:
with schema.create('users') as table:
table.increments('id')
table
变量是Blueprint
实例,可以用来定义表。
要重名表,使用rename
方法:
schema.rename('from', 'to')
要指定操作数据库进行表结构更改,使用connection
方法:
with schema.connection('foo').create('users') as table:
table.increments('id')
要删除表,你可以使用drop
或者drop_if_exists
方法:
schema.drop('users')
schema.drop_if_exists('users')
添加字段
要更新已经存在的表,需要使用table
方法:
with schema.table('users') as table:
table.string('email')
表构造器支持各种列数据库类型:
COMMAND | DESCRIPTION |
---|---|
table.big_increments('id') |
使用大整数自增ID |
table.big_integer('votes') |
BIGINT 类型 |
table.binary('data') |
BLOB 类型 |
table.boolean('confirmed') |
BOOLEAN 类型 |
table.char('name', 4) |
固定长度的CHAR类型 |
table.date('created_on') |
DATE 类型 |
table.datetime('created_at') |
DATETIME 类型 |
table.decimal('amount', 5, 2) |
带有字段长度,小数位数的DECIMAL |
table.double('column', 15, 8) |
DOUBLE 类型,总长15位,小数8位 |
table.enum('choices', ['foo', 'bar']) |
ENUM 类型 |
table.float('amount') |
FLOAT 类型 |
table.increments('id') |
I自增ID(主键) |
table.integer('votes') |
INTEGER 类型 |
table.json('options') |
JSON 类型 |
table.long_text('description') |
LONGTEXT 类型 |
table.medium_integer('votes') |
MEDIUMINT 类型 |
table.medium_text('description') |
MEDIUMTEXT 类型 |
table.morphs('taggable') |
加入 INTEGER类型的 taggable_id 字段和STRING类型的taggable_type 字段 |
table.nullable_timestamps() |
同timestamps() , 支持 NULLs |
table.small_integer('votes') |
SMALLINT 类型 |
table.soft_deletes() |
加入deleted_at字段以支持软删除 |
table.string('email') |
VARCHAR 类型 |
table.string('votes', 100) |
带有长度的VARCHAR类型 |
table.text('description') |
TEXT 类型 |
table.time('sunrise') |
TIME 类型 |
table.timestamp('added_at') |
TIMESTAMP 类型 |
table.timestamps() |
加入TIMESTAMP类型 created_at 和 updated_at 字段 |
.nullable() |
指定该字段支持NULL值 |
.default(value) |
定义默认值 |
.unsigned() |
设置 INTEGER 为 UNSIGNED 类型 |
修改字段
有时你可能需要修改已经存在的字段。例如,你可能希望增加字符串字段的长度。我们通过使用change
方法来实现。例如,让我们将name
字段长度从25增长为50:
with schema.table('users') as table:
table.string('name', 50).change()
你还可以修改字段允许空值:
with schema.table('user') as table:
table.string('name', 50).nullable().change()
字段变更特性,当前还是试验beta阶段。我们鼓励如果遇到任何问题可以提供issu
或者bug
到Github 仓库。
重命名字段
使用rename_column
方法来重命名字段:
with schema.table('users') as table:
table.rename_column('from', 'to')
MySQL 5.6.6之前版本, 重命名字段名外键不支持自动更新,你需要删除外键约束,重建外键约束。
with schema.table('posts') as table:
table.drop_foreign('posts_user_id_foreign')
table.rename_column('user_id', 'author_id')
table.foreign('author_id').references('id').on('users')
之后版本,Orator也许会自动处理。
重命名特性,还处理beta测试阶段(尤其是SQLite)。鼓励使用过程中遇到任何问题提交到 Github 仓库。
删除字段
要删除一个字段,我们可以使用drop_column
方法:
从表中删除字段
with schema.table('users') as table:
table.drop_column('votes')
从表中删除多个字段
with schema.table('users') as table:
table.drop_column('votes', 'avatar', 'location')
检查是否存在
你可以简单使用has_table
和has_column
方法来检查表和字段是否存在:
检查表是否存在
if schema.has_table('users'):
# ...
检查字段是否存在:
if schema.has_column('users', 'email'):
# ...
增加索引
结构构造器支持索引。有两种方式,第一种是在字段中定义:
table.string('email').unique()
或者,可以在单独的行来增加。以下是所有支持的索引类型:
COMMAND | DESCRIPTION |
---|---|
table.primary('id') |
设为主键 |
table.primary(['first', 'last']) |
组合主键 |
table.unique('email') |
唯一索引 |
table.index('state') |
基础索引 |
MySQL
和PostgreSQL
对索引字段有长度限制。所以,如果列名太长,可以使用name
关键字来指定索引名字:
table.index(
['field_with_really_long_name',
'another_field_with_long_name'],
name='my_uniq_idx'
)
删除索引
要删除指定索引。Orator必须指定索引名称。Orator为索引分配名称方式为,列名称和索引类型串联起来。例如:
COMMAND | DESCRIPTION |
---|---|
table.drop_primary('user_id_primary') |
删除"users"表主键 |
table.drop_unique('user_email_unique') |
删除"users"表email字段唯一索引 |
table.drop_index('geo_state_index') |
从geo表中删除state的索引 |
外键
orator同样支持给表增加外键约束:
table.integer('user_id').unsigned()
table.foreign('user_id').references('id').on('users')
本例中,我们将创建一个user_id
字段,并且引用users
表的id
字段。确保在创建外键前先创建了列!
你还可以指定外键约束一些操作行为,例如"on delete"或者"on update":
table.foreign('user_id')
.references('id').on('users')
.on_delete('cascade')
要删除一个外键,可以使用drop_foregin
方法。它命名方法和其他索引一致:
table.drop_foreign('posts_user_id_foreign')
当创建一个外键引用的是自增整型,确保外键字段为unsigned
。
默认,SQLite不支持ON DELETE
和ON UPDATE
语句。ORator通过如下SQL查询来解决:
PRAGMA foreign_keys = ON
如果你不想要此行为,只需要将配置参数的foregin_keys
设置为False
:
config = {
'sqlite': {
'driver': 'sqlite',
'database': ':memory:',
'foreign_keys': False
}
}
删除时间戳和软删除
要删除timestamp
, nullable_timestamp
或者soft_deletes
字段,使用如下方法:
COMMAND | DESCRIPTION |
---|---|
table.drop_timestamps() |
删除 created_at 和 deleted_at 字段 |
table.drop_soft_deletes() |
删除 deleted_at 字段 |
本译文仅用于学习和交流目的,转载请务必注明文章译者、出处、和本文链接
我们的翻译工作遵照 CC 协议,如果我们的工作有侵犯到您的权益,请及时联系我们。