starter-kit/migrations/000003_create_user_roles_table.up.sql
ulflow_phattt2901 e8aeef6013
Some checks failed
CI Pipeline / Security Scan (push) Successful in 2m53s
CI Pipeline / Lint (push) Failing after 2m43s
CI Pipeline / Build (push) Has been skipped
CI Pipeline / Test (push) Has been skipped
CI Pipeline / Notification (push) Successful in 2s
feat: add database migrations and enhance Makefile with environment loading
2025-06-04 07:32:51 +07:00

36 lines
1.1 KiB
SQL

-- +goose Up
-- +goose StatementBegin
-- 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 INTEGER 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
$$;
-- +goose StatementEnd
-- +goose Down
-- +goose StatementBegin
DROP TABLE IF EXISTS user_roles CASCADE;
-- +goose StatementEnd