Ir al contenido

Agregar una columna con una migración ​

Traducción automática

Esta página se tradujo automáticamente del inglés y todavía no la revisó un hablante nativo; las correcciones son bienvenidas en GitHub. Si algo no coincide, vale el original en inglés.

Tarea: los productos necesitan una cantidad en stock, y la base de datos ya existe.

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

La primera migración creó la tabla:

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

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

El cambio es un segundo archivo. Las migraciones se ejecutan en orden, cada una una vez, cada una en su propia transacción; una migración ya aplicada nunca se edita:

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>

Cada prueba empieza con una base de datos construida por las migraciones, así que la prueba ve el esquema que recibe una instalación nueva:

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

¿Prefieres escribir el esquema que quieres y dejar que Quantum escriba la migración? Ver quantum migrate plan en Project Structure (en inglés). Ver DB-6 y DB-8.

Licencia MIT · Hecho con VitePress