JhHardwareWRS_BackPoint/scripts/migrate_report_allocations.py
2026-07-25 02:30:02 +08:00

90 lines
3.5 KiB
Python

from pathlib import Path
import sys
from sqlalchemy import text
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT))
from app.database import engine # noqa: E402
def index_exists(conn, table_name: str, index_name: str) -> bool:
return bool(
conn.execute(
text(
"""
SELECT COUNT(1)
FROM information_schema.statistics
WHERE table_schema = DATABASE()
AND table_name = :table_name
AND index_name = :index_name
"""
),
{"table_name": table_name, "index_name": index_name},
).scalar()
)
def create_index(conn, table_name: str, index_name: str, columns: str) -> None:
if not index_exists(conn, table_name, index_name):
conn.execute(text(f"CREATE INDEX {index_name} ON {table_name} ({columns})"))
def main() -> None:
with engine.begin() as conn:
conn.execute(
text(
"""
CREATE TABLE IF NOT EXISTS production_report_allocations (
id BIGINT NOT NULL AUTO_INCREMENT,
report_id BIGINT NOT NULL,
report_item_id BIGINT NULL,
attendance_point_name VARCHAR(128) NOT NULL DEFAULT '',
employee_phone VARCHAR(20) NOT NULL DEFAULT '',
allocation_date DATE NOT NULL,
day_minutes DECIMAL(10, 2) NOT NULL DEFAULT 0,
overtime_minutes DECIMAL(10, 2) NOT NULL DEFAULT 0,
night_minutes DECIMAL(10, 2) NOT NULL DEFAULT 0,
effective_minutes DECIMAL(10, 2) NOT NULL DEFAULT 0,
good_qty DECIMAL(12, 2) NOT NULL DEFAULT 0,
defect_qty DECIMAL(12, 2) NOT NULL DEFAULT 0,
scrap_qty DECIMAL(12, 2) NOT NULL DEFAULT 0,
changeover_count DECIMAL(12, 2) NOT NULL DEFAULT 0,
reference_wage DECIMAL(12, 2) NOT NULL DEFAULT 0,
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (id),
CONSTRAINT fk_report_allocations_report
FOREIGN KEY (report_id) REFERENCES production_reports (id)
ON DELETE CASCADE,
CONSTRAINT fk_report_allocations_item
FOREIGN KEY (report_item_id) REFERENCES production_report_items (id)
ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
"""
)
)
create_index(conn, "production_report_allocations", "idx_report_allocations_report", "report_id")
create_index(conn, "production_report_allocations", "idx_report_allocations_item", "report_item_id")
create_index(conn, "production_report_allocations", "idx_report_allocations_date", "allocation_date")
create_index(
conn,
"production_report_allocations",
"idx_report_allocations_point_date",
"attendance_point_name, allocation_date",
)
create_index(
conn,
"production_report_allocations",
"idx_report_allocations_employee_date",
"employee_phone, allocation_date",
)
print("report allocations schema migrated")
if __name__ == "__main__":
main()