在编辑器中
语言服务器了解每个模型的字段。它会在->where(、->order_by(、->create(等处补全这些字段,并在->with(中补全关系。模型中不存在的字段会被报告为 KS5013(参见错误)。where lambda 的参数即为该模型的记录,因此 fn(p) => $p. 也会补全其字段。
模型选项中的名称,例如 hidden: [data] 或 index: [team_id],同样也是模型的字段。编辑器会自动补全这些名称,你可以将鼠标悬停在上面,或跳转到其定义。迁移中的列名也同样适用。Index(columns: [‸]) 和 Key(columns: [‸]) 会提供其周围 CreateTable 的字段。引用表名的步骤(例如 AddIndex(table: 'posts', columns: [‸]) 或 DropField(table: 'posts', name: ‸))会提供该表在当前位置所具有的列。这些列来自文件中此前的迁移和上方的步骤;如果没有任何迁移创建该表,则来自模型。表中不存在的名称会报告为 KS5013。
<KScript.Migration>
<CreateTable name="note_files">
<Field name="id" type="int" key="yes" auto="yes" />
<Field name="note_id" type="int" references="board_notes" />
<Index columns="note_id" />
</CreateTable>
</KScript.Migration>import KScript.Data
Migration {
CreateTable(name: 'note_files') {
Field(name: 'id', type: int, key, auto)
Field(name: 'note_id', type: int, references: 'board_notes')
Index(columns: [note_id])
}
}将鼠标悬停在某个查询方法上,即可大致查看该调用链将发送的 SQL,其中值以 ? 表示:
SELECT * FROM posts
WHERE views > ? AND author_id = ?
ORDER BY created_at DESC
LIMIT ?当项目包含迁移时,若某个模型与迁移生成的结构不一致,则会报告 KS5014,并附上 kscript db diff 将要写入的第一处变更,例如 add field users.bio。
迁移部分同样会在你输入时进行检查。列的type:必须与其模型字段所需的一致,枚举列的values:必须与该字段枚举的值一致。当color: NoteColor作用于BoardNote和enum NoteColor { yellow, pink, blue }时,列的写法必须如下:
<KScript.Migration>
<CreateTable name="board_notes">
<Field name="id" type="int" key="yes" auto="yes" />
<Field name="color" type="enum" values="yellow, pink, blue" default="'yellow'" />
</CreateTable>
</KScript.Migration>import KScript.Data
Migration {
CreateTable(name: 'board_notes') {
Field(name: 'id', type: int, key, auto)
Field(name: 'color', type: enum, values: [yellow, pink, blue], default: 'yellow')
}
}NoteColor 中没有的单词(例如 values: [yellow, pink, ajcn])会在该单词处报错(如果看起来像拼写错误,还会给出修正建议),并且列表会提示它仍需要 blue。一旦后续的迁移再次修改该列,较早的那个迁移就不再处理:只有最后一次写入该列的迁移需要与模型保持一致。
枚举列也可以直接从枚举本身获取其可选值,因此无需手动复制列表。在values:中指定枚举名称,导入方式与其他类型相同,default:即可提供并校验其中的值:
<KScript.Migration>
<import path="../../types/note-color.kscript" as="colours" />
<CreateTable name="board_notes">
<Field name="id" type="int" key="yes" auto="yes" />
<Field name="color" type="enum" values="colours.NoteColor" default="'yellow'" />
</CreateTable>
</KScript.Migration>import KScript.Data
import "../../types/note-color.kscript" as colours
Migration {
CreateTable(name: 'board_notes') {
Field(name: 'id', type: int, key, auto)
Field(name: 'color', type: enum, values: colours.NoteColor, default: 'yellow')
}
}迁移运行时会保留该枚举当前包含的词。之后新增到枚举中的词仍需要新的迁移(由kscript db diff生成),因为已经运行过的迁移不会再次运行。default:必须是枚举中的某个词:如果枚举删除了该词,编辑器会标记默认值,迁移将报错停止,而不会创建列。