跳到正文

用迁移添加一列 ​

机器翻译

本页由英文原文机器翻译而来,尚未经过母语审校,欢迎在 GitHub 上提出修改。内容如有出入,以英文原文为准。

任务: 商品需要一个库存数量,而数据库已经存在了。

yaml
# Recipe: change the schema with a new migration, never by editing an old one.
paths:
  components: ./components
  migrations: ./migrations

datasources:
  db:
    driver: sqlite
    database: ./data/shop.db

第一个迁移创建了数据表:

sql
CREATE TABLE products (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    name TEXT NOT NULL
);

INSERT INTO products (name) VALUES ('Mug'), ('Sticker');

修改是第二个文件。迁移按顺序运行,每个只运行一次,每个都在自己的事务中; 已经应用的迁移永远不要编辑:

sql
-- Rows that already exist get the default.
ALTER TABLE products ADD COLUMN stock INTEGER NOT NULL DEFAULT 0;

UPDATE products SET stock = 12 WHERE name = 'Mug';
bash
quantum migrate up
xml
<q:component name="Products">
  <q:query name="products" datasource="db">
    SELECT name, stock FROM products ORDER BY name
  </q:query>

  <ui:window title="Products">
    <ui:table source="{products}">
      <ui:column key="name" label="Name" />
      <ui:column key="stock" label="In stock" />
    </ui:table>
  </ui:window>
</q:component>

每个测试都从由迁移构建的数据库开始,所以测试看到的是全新安装得到的数据表结构:

xml
<q:test name="both migrations ran, in order" page="/">
  <test:visit />
  <test:expect text="In stock" />
  <test:expect table="products" count="1" where="name = 'Mug' AND stock = 12" />
  <test:expect table="products" count="1" where="name = 'Sticker' AND stock = 0" />
</q:test>
text
tests/stock.test.q
  PASS  both migrations ran, in order
1 passed, 0 failed

更想写出你想要的数据表结构,让 Quantum 来写迁移?参见 Project Structure(英文)中的 quantum migrate plan。 参见 DB-6 和 DB-8。

MIT 许可证 · 使用 VitePress 构建