from __future__ import annotations import argparse import sqlite3 from pathlib import Path SCHEMA = """ CREATE TABLE customers ( id INTEGER PRIMARY KEY, name TEXT NOT NULL, city TEXT NOT NULL, industry TEXT NOT NULL, created_at TEXT NOT NULL ); CREATE TABLE products ( id INTEGER PRIMARY KEY, name TEXT NOT NULL, category TEXT NOT NULL, unit_price REAL NOT NULL CHECK (unit_price >= 0) ); CREATE TABLE orders ( id INTEGER PRIMARY KEY, customer_id INTEGER NOT NULL REFERENCES customers(id), ordered_at TEXT NOT NULL, status TEXT NOT NULL CHECK (status IN ('paid', 'pending', 'cancelled')) ); CREATE TABLE order_items ( order_id INTEGER NOT NULL REFERENCES orders(id), product_id INTEGER NOT NULL REFERENCES products(id), quantity INTEGER NOT NULL CHECK (quantity > 0), PRIMARY KEY (order_id, product_id) ); """ CUSTOMERS = [ (1, "华东智造", "上海", "制造", "2025-01-10"), (2, "南方零售", "深圳", "零售", "2025-02-16"), (3, "京华科技", "北京", "科技", "2025-03-08"), (4, "西部能源", "成都", "能源", "2025-04-21"), (5, "海峡物流", "厦门", "物流", "2025-05-12"), ] PRODUCTS = [ (1, "智能分析标准版", "AI软件", 1299.0), (2, "智能分析企业版", "AI软件", 4999.0), (3, "数据治理服务", "专业服务", 8000.0), (4, "API调用包", "云服务", 699.0), ] ORDERS = [ (101, 1, "2026-07-05", "paid"), (102, 2, "2026-07-18", "paid"), (103, 1, "2026-08-02", "paid"), (104, 3, "2026-08-09", "paid"), (105, 4, "2026-08-20", "cancelled"), (106, 5, "2026-09-01", "paid"), (107, 2, "2026-09-12", "pending"), (108, 3, "2026-09-20", "paid"), ] ORDER_ITEMS = [ (101, 1, 2), (101, 4, 3), (102, 2, 1), (103, 3, 1), (103, 4, 5), (104, 2, 2), (105, 3, 2), (106, 1, 3), (107, 4, 10), (108, 2, 1), (108, 3, 1), ] def build_database(path: Path) -> None: path.parent.mkdir(parents=True, exist_ok=True) if path.exists(): path.unlink() with sqlite3.connect(path) as connection: connection.execute("PRAGMA foreign_keys = ON") connection.executescript(SCHEMA) connection.executemany("INSERT INTO customers VALUES (?, ?, ?, ?, ?)", CUSTOMERS) connection.executemany("INSERT INTO products VALUES (?, ?, ?, ?)", PRODUCTS) connection.executemany("INSERT INTO orders VALUES (?, ?, ?, ?)", ORDERS) connection.executemany("INSERT INTO order_items VALUES (?, ?, ?)", ORDER_ITEMS) connection.commit() def main() -> None: parser = argparse.ArgumentParser(description="创建SQL Agent教程使用的SQLite演示数据库") parser.add_argument("--output", type=Path, default=Path(__file__).with_name("sales_demo.db")) args = parser.parse_args() build_database(args.output.resolve()) print(f"已创建演示数据库:{args.output.resolve()}") if __name__ == "__main__": main()