Files
web_work/migrations/002_add_cart_orders.sql
kirill.khorkov f4f57bd153 fix
2025-12-17 01:24:01 +03:00

51 lines
2.0 KiB
SQL

CREATE TABLE IF NOT EXISTS cart (
cart_id SERIAL PRIMARY KEY,
user_id INTEGER REFERENCES users(user_id) ON DELETE CASCADE,
product_id INTEGER REFERENCES products(product_id) ON DELETE CASCADE,
quantity INTEGER DEFAULT 1 CHECK (quantity > 0),
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
UNIQUE(user_id, product_id)
);
CREATE TABLE IF NOT EXISTS orders (
order_id SERIAL PRIMARY KEY,
order_number VARCHAR(50) UNIQUE NOT NULL,
user_id INTEGER REFERENCES users(user_id) ON DELETE SET NULL,
customer_name VARCHAR(100) NOT NULL,
customer_email VARCHAR(255) NOT NULL,
customer_phone VARCHAR(20) NOT NULL,
delivery_address TEXT NOT NULL,
delivery_region VARCHAR(100),
postal_code VARCHAR(20),
delivery_method VARCHAR(50) DEFAULT 'courier',
payment_method VARCHAR(50) DEFAULT 'card',
subtotal DECIMAL(10, 2) NOT NULL,
discount_amount DECIMAL(10, 2) DEFAULT 0,
delivery_price DECIMAL(10, 2) DEFAULT 0,
final_amount DECIMAL(10, 2) NOT NULL,
promo_code VARCHAR(50),
status VARCHAR(30) DEFAULT 'pending',
notes TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
completed_at TIMESTAMP
);
CREATE TABLE IF NOT EXISTS order_items (
item_id SERIAL PRIMARY KEY,
order_id INTEGER REFERENCES orders(order_id) ON DELETE CASCADE,
product_id INTEGER REFERENCES products(product_id) ON DELETE SET NULL,
product_name VARCHAR(200) NOT NULL,
product_price DECIMAL(10, 2) NOT NULL,
quantity INTEGER NOT NULL CHECK (quantity > 0),
total_price DECIMAL(10, 2) NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX IF NOT EXISTS idx_cart_user ON cart(user_id);
CREATE INDEX IF NOT EXISTS idx_orders_user ON orders(user_id);
CREATE INDEX IF NOT EXISTS idx_orders_status ON orders(status);
CREATE INDEX IF NOT EXISTS idx_orders_created ON orders(created_at);
CREATE INDEX IF NOT EXISTS idx_order_items_order ON order_items(order_id);