-- ============================================================ -- Lab 3: Messenger database initialization -- PostgreSQL 15+ -- ============================================================ -- USERS CREATE TABLE IF NOT EXISTS users ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), username VARCHAR(32) UNIQUE NOT NULL, display_name VARCHAR(100) NOT NULL, password_hash VARCHAR(255) NOT NULL, created_at TIMESTAMPTZ NOT NULL DEFAULT NOW() ); -- Ensure defaults also exist when upgrading an older database. ALTER TABLE users ALTER COLUMN id SET DEFAULT gen_random_uuid(); ALTER TABLE users ALTER COLUMN created_at SET DEFAULT NOW(); -- CHATS CREATE TABLE IF NOT EXISTS chats ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), title VARCHAR(100) NOT NULL, created_at TIMESTAMPTZ NOT NULL DEFAULT NOW() ); ALTER TABLE chats ALTER COLUMN id SET DEFAULT gen_random_uuid(); ALTER TABLE chats ALTER COLUMN created_at SET DEFAULT NOW(); -- CHAT MEMBERS CREATE TABLE IF NOT EXISTS chat_members ( chat_id UUID NOT NULL REFERENCES chats(id) ON DELETE CASCADE, user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, PRIMARY KEY (chat_id, user_id) ); CREATE INDEX IF NOT EXISTS idx_chat_members_user ON chat_members(user_id); -- MESSAGES CREATE TABLE IF NOT EXISTS messages ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), chat_id UUID NOT NULL REFERENCES chats(id) ON DELETE CASCADE, sender_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, text VARCHAR(4000) NOT NULL, created_at TIMESTAMPTZ NOT NULL DEFAULT NOW() ); ALTER TABLE messages ALTER COLUMN id SET DEFAULT gen_random_uuid(); ALTER TABLE messages ALTER COLUMN created_at SET DEFAULT NOW(); CREATE INDEX IF NOT EXISTS idx_messages_chat_pagination ON messages(chat_id, created_at, id); -- SESSIONS CREATE TABLE IF NOT EXISTS sessions ( token VARCHAR(128) PRIMARY KEY, user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, expires_at TIMESTAMPTZ NOT NULL, created_at TIMESTAMPTZ NOT NULL DEFAULT NOW() ); CREATE INDEX IF NOT EXISTS idx_sessions_user ON sessions(user_id); CREATE INDEX IF NOT EXISTS idx_sessions_expiration ON sessions(expires_at); -- IDEMPOTENCY KEYS CREATE TABLE IF NOT EXISTS idempotency_keys ( user_id UUID NOT NULL, method VARCHAR(16) NOT NULL, path TEXT NOT NULL, key VARCHAR(128) NOT NULL, request_hash VARCHAR(64) NOT NULL, response_status INT NOT NULL, response_body JSONB NOT NULL, created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), PRIMARY KEY (user_id, method, path, key) ); CREATE INDEX IF NOT EXISTS idx_idempotency_created_at ON idempotency_keys(created_at); -- ============================================================ -- End of migration -- ============================================================