techtools
Головна / research / lab / pg-bench / src / schema3.ts

schema3.ts

TypeScript · 105 рядків

1// Структура v3 (обговорення 06.10.2026):
2//   — таблиць звірки немає: контрольна точка — поля checked_quantity / checked_at у product_stock;
3//   — журнал без первинного ключа й без індексу за item_id (колонка лишається для аудиту),
4//     один індекс (warehouse_id, product_id, created_at), розділи за місяцем;
5//     після закриття періоду розділ старший за два місяці відключається в схему wms_archive;
6//   — архів записів розділено за місяцем архівування.
7
8export const MONTHS = (() => {
9  const out: { tag: string; from: string; to: string }[] = [];
10  for (let i = -1; i <= 13; i++) {
11    const d = new Date(Date.UTC(2027, i, 1));
12    const e = new Date(Date.UTC(2027, i + 1, 1));
13    out.push({ tag: d.toISOString().slice(0, 7).replace('-', '_'), from: d.toISOString().slice(0, 10), to: e.toISOString().slice(0, 10) });
14  }
15  return out;
16})();
17
18const ITEM_COLS = `
19  warehouse_id    smallint NOT NULL,
20  product_id      int      NOT NULL,
21  is_container    boolean  NOT NULL DEFAULT false,
22  pack_type       smallint NOT NULL,
23  status          smallint NOT NULL,
24  pack_size       int      NOT NULL,
25  pack_count      int      NOT NULL,
26  quantity        int      NOT NULL,
27  contained_in_id bigint,
28  source_id       bigint,
29  receipt_id      bigint,
30  mfg_date        date,
31  expiry_date     date,
32  received_at     timestamptz NOT NULL,
33  location_id     int      NOT NULL,
34  label_code      text,
35  serial_number   text`;
36
37export const DDL_V3 = `
38DROP SCHEMA IF EXISTS wms CASCADE;
39DROP SCHEMA IF EXISTS wms_archive CASCADE;
40CREATE SCHEMA wms;
41CREATE SCHEMA wms_archive;   -- відключені (закриті) розділи журналу
42SET search_path = wms;
43
44CREATE TABLE category (
45  id smallint PRIMARY KEY, name text NOT NULL,
46  pack1 int NOT NULL, pack1_type smallint NOT NULL, pack2 int, pack2_type smallint,
47  life_min int NOT NULL, life_max int NOT NULL, serial boolean NOT NULL DEFAULT false
48);
49INSERT INTO category VALUES
50 (1,'Кріплення',10,1,100,2,1825,3650,false),
51 (2,'Свічки',4,2,40,3,1825,3650,false),
52 (3,'Фільтри',1,0,12,3,1095,1825,false),
53 (4,'Гальмівні колодки',1,0,10,3,1095,1825,false),
54 (5,'Лампи',10,2,100,3,1825,3650,false),
55 (6,'Герметики',12,2,NULL,NULL,365,720,false),
56 (7,'Масла',4,2,NULL,NULL,1095,1825,false),
57 (8,'Підшипники і ремені',10,2,NULL,NULL,1095,2555,false),
58 (9,'Дорогі вузли',1,0,NULL,NULL,1825,3650,true);
59
60CREATE TABLE product (
61  id              int GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
62  brand_id        smallint NOT NULL,
63  sku             text     NOT NULL,
64  category_id     smallint NOT NULL REFERENCES category,
65  shelf_life_days int,
66  UNIQUE (brand_id, sku)
67);
68
69-- Стан товару на складі: фізичний і доступний залишок + контрольна точка звірки (замість двох таблиць).
70CREATE TABLE product_stock (
71  warehouse_id     smallint NOT NULL,
72  product_id       int      NOT NULL,
73  quantity         int      NOT NULL,
74  available        int      NOT NULL,
75  checked_quantity int      NOT NULL DEFAULT 0,
76  checked_at       timestamptz,
77  PRIMARY KEY (warehouse_id, product_id)
78);
79
80CREATE TABLE inventory_item (id bigint GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, ${ITEM_COLS});
81CREATE INDEX ix_item_wh_product ON inventory_item (warehouse_id, product_id);
82CREATE INDEX ix_item_container ON inventory_item (contained_in_id) WHERE contained_in_id IS NOT NULL;
83CREATE INDEX ix_item_expiry ON inventory_item (status, expiry_date);
84
85CREATE TABLE inventory_item_archive (id bigint NOT NULL, ${ITEM_COLS},
86  archived_at timestamptz NOT NULL, quantity_final int NOT NULL) PARTITION BY RANGE (archived_at);
87${MONTHS.map((m) => `CREATE TABLE inventory_item_archive_${m.tag} PARTITION OF inventory_item_archive FOR VALUES FROM ('${m.from}') TO ('${m.to}');`).join('\n')}
88CREATE INDEX ix_arch_id ON inventory_item_archive (id);
89
90-- Журнал: без PK і без індексу за item_id.
91CREATE TABLE inventory_transaction (
92  created_at      timestamptz NOT NULL,
93  warehouse_id    smallint NOT NULL,
94  type            smallint NOT NULL,
95  product_id      int      NOT NULL,
96  item_id         bigint   NOT NULL,
97  qty_delta       int      NOT NULL,
98  doc_id          bigint,
99  related_item_id bigint,
100  user_id         int
101) PARTITION BY RANGE (created_at);
102${MONTHS.map((m) => `CREATE TABLE inventory_transaction_${m.tag} PARTITION OF inventory_transaction FOR VALUES FROM ('${m.from}') TO ('${m.to}');`).join('\n')}
103CREATE INDEX ix_tx_wh_product ON inventory_transaction (warehouse_id, product_id, created_at);
104`;
105