starter-kit/migrations/000003_create_user_roles_table.up.sql
ulflow_phattt2901 b572653d97
All checks were successful
CI Pipeline / Build (push) Successful in 1m17s
CI Pipeline / Notification (push) Successful in 1s
CI Pipeline / Lint (push) Successful in 3m25s
CI Pipeline / Test (push) Successful in 4m6s
CI Pipeline / Security Scan (push) Successful in 6m13s
fix: implement user roles and authentication system with tests
2025-06-05 20:00:50 +07:00

27 lines
986 B
SQL

-- Tạo bảng mà không có ràng buộc
CREATE TABLE IF NOT EXISTS user_roles (
user_id UUID NOT NULL,
role_id UUID NOT NULL,
created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (user_id, role_id)
);
-- Tạo index cho hiệu suất truy vấn tốt hơn
CREATE INDEX idx_user_roles_user_id ON user_roles(user_id);
CREATE INDEX idx_user_roles_role_id ON user_roles(role_id);
-- Thêm ràng buộc khóa ngoại nếu bảng tồn tại
DO $$
BEGIN
IF EXISTS (SELECT 1 FROM information_schema.tables WHERE table_name = 'users') THEN
ALTER TABLE user_roles ADD CONSTRAINT fk_user_roles_user
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE;
END IF;
IF EXISTS (SELECT 1 FROM information_schema.tables WHERE table_name = 'roles') THEN
ALTER TABLE user_roles ADD CONSTRAINT fk_user_roles_role
FOREIGN KEY (role_id) REFERENCES roles(id) ON DELETE CASCADE;
END IF;
END
$$;