Files
Bkk1234 dd65e9061f Add Julia+Postgres calculation service with shared golden vectors
- service/: Julia HTTP API (HTTP.jl + LibPQ), formulas.jl as source of truth
- service/db/001_init.sql: calculation_runs (append-only), provinces, eto_monthly
- tests/golden/vectors.json: single fixture set enforced on both JS and Julia
- .gitignore: keep secrets (DB env, contracts, financial records, ransomware note) out
- AGENTS.md: document service commands and formula-change rule
2026-11-16 01:59:22 +07:00

60 lines
2.9 KiB
PL/PgSQL

-- 001_init.sql — สคีมาเริ่มต้นของ farm-planning API (PostgreSQL 17)
-- ใช้: psql -U <user> -d farm_planning -f service/db/001_init.sql
-- หลักการ: เก็บ "ทุกครั้งที่คำนวณ" แบบ append-only (input + result เป็น jsonb)
-- ห้ามแก้ผลเก่า — ถ้าสูตรเปลี่ยนให้เพิ่ม formula_version ในแถวใหม่
BEGIN;
CREATE EXTENSION IF NOT EXISTS pgcrypto; -- gen_random_uuid()
-- ---------------------------------------------------------------
-- 1) ผลการคำนวณทุกครั้ง (audit trail + ใช้ทำ golden test ได้)
-- ---------------------------------------------------------------
CREATE TABLE IF NOT EXISTS calculation_runs (
run_id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
calculation_kind text NOT NULL, -- 'crop_water' | 'reservoir'
input_payload jsonb NOT NULL,
result_payload jsonb NOT NULL,
formula_version text NOT NULL DEFAULT '1.0',
engine text NOT NULL DEFAULT 'julia', -- julia | js-offline
client_version text, -- build ของเว็บที่เรียก
created_at timestamptz NOT NULL DEFAULT now(),
CONSTRAINT calculation_kind_known
CHECK (calculation_kind IN ('crop_water', 'reservoir'))
);
CREATE INDEX IF NOT EXISTS calculation_runs_kind_created_idx
ON calculation_runs (calculation_kind, created_at DESC);
-- ---------------------------------------------------------------
-- 2) ข้อมูลอ้างอิง: ETo รายจังหวัด (โหลดจาก data/climate/eto_by_region.json)
-- ---------------------------------------------------------------
CREATE TABLE IF NOT EXISTS provinces (
province_id serial PRIMARY KEY,
region_id text NOT NULL,
region_name_th text NOT NULL,
province_name_th text NOT NULL,
UNIQUE (region_id, province_name_th)
);
CREATE TABLE IF NOT EXISTS eto_monthly (
province_id int NOT NULL REFERENCES provinces (province_id) ON DELETE CASCADE,
month_number smallint NOT NULL CHECK (month_number BETWEEN 1 AND 12),
eto_mm_per_day numeric(6, 3) NOT NULL CHECK (eto_mm_per_day > 0),
source_reference text,
PRIMARY KEY (province_id, month_number)
);
-- ---------------------------------------------------------------
-- 3) มุมมองสรุปการใช้งาน (ไม่บังคับ ใช้ตอนตรวจ)
-- ---------------------------------------------------------------
CREATE OR REPLACE VIEW calculation_runs_daily AS
SELECT calculation_kind,
date_trunc('day', created_at) AS run_date,
count(*) AS runs
FROM calculation_runs
GROUP BY 1, 2
ORDER BY 2 DESC;
COMMIT;