freshyo/apps/backend/wrangler-commands.md
2026-08-08 12:40:19 +05:30

64 lines
2.8 KiB
Markdown

1. wrangler d1 migrations apply freshyo-backend-dev --config wrangler.dev.toml --remote
# run migrations on remote db. migrations folder should be in the wrangler.toml file
2. wrangler d1 execute freshyo-backend-dev \
--config wrangler.dev.toml \
--file dumps/latest.sql --remote
# run a single file
wrangler d1 execute freshyo-dev \
--config wrangler.dev.toml \
--file ../../packages/db_helper_sqlite/drizzle/0002_sku_split.sql
# ============================================================================
# Importing `wrangler d1 export` dumps locally (--local)
# ============================================================================
## Why it can fail with `no such table: main.<table>`
`wrangler d1 export` writes tables in `sqlite_master` rowid order, which is the
order tables were *historically created*. Any migration that **drops & re-creates**
a table (e.g. the SKU split does `DROP TABLE product_info` + rename) pushes that
parent table to the END of the dump.
So the dump can create + populate a child table (e.g. `product_skus`, which has
`FOREIGN KEY (product_id) REFERENCES product_info(id)`) BEFORE its parent
(`product_info`) exists. Loading into an empty DB then fails with:
no such table: main.product_info
## Why the usual fixes DON'T work
- `PRAGMA foreign_keys=OFF` — is a **no-op inside a transaction**, and
`wrangler d1 execute --local` runs the whole file as ONE transaction.
- `PRAGMA defer_foreign_keys=TRUE` (already at the top of every export) — only
defers *row-level* FK checks, not the "parent table doesn't exist" error.
The only real fix is **ordering** the tables.
## How to check after every export
grep -nE '^CREATE TABLE|REFERENCES' dumps/<dump>.sql
For every `REFERENCES x(...)`, confirm the `CREATE TABLE "x"` line appears
BEFORE the referencing table's `CREATE TABLE`.
## How to hand-fix
Cut the parent table's block (`CREATE TABLE ...` + all its `INSERT ...` lines)
and paste it ABOVE the child table's block. Then verify it loads cleanly:
sqlite3 :memory: "PRAGMA foreign_keys=ON; BEGIN; .read dumps/<dump>.sql; COMMIT;"
This should exit 0 with no error. (Example already applied to `latest_1.sql` and
`local_8_aug.sql`: `product_info` was moved above `product_skus`.)
## When to re-check
After ANY new `wrangler d1 export`, especially once a migration that re-creates
tables has been applied. This is a general trap, not specific to one dump.
> The SKU-split migration re-creates these tables in this historical order:
> `product_skus`, `sku_features`, `product_market_stats`, `product_info`,
> `cart_items`, `order_items`, `product_combos`. Exports put `product_info`
> AFTER its child `product_skus` — every fresh export needs `product_info`
> moved above `product_skus` (or the whole chain checked) before local import.