|
| 1 | +-- SPDX-FileCopyrightText: Copyright 2024 The Minder Authors |
| 2 | +-- SPDX-License-Identifier: Apache-2.0 |
| 3 | + |
| 4 | +BEGIN; |
| 5 | + |
| 6 | +-- This migration adds storage support for data sources. The only |
| 7 | +-- constraints we enforce at the database layer are |
| 8 | +-- |
| 9 | +-- * functions can only reference one data source, and must be deleted |
| 10 | +-- if the data source is deleted |
| 11 | +-- * data sources are tied to a project, and must be deleted if the |
| 12 | +-- project is deleted |
| 13 | +-- * rule types can reference one or more data source, and we want to |
| 14 | +-- prevent deletion of a data source if there's a rule type |
| 15 | +-- referencing it |
| 16 | +-- |
| 17 | +-- The first two are simple foreign keys, while the third one is |
| 18 | +-- enforced by the lack of `ON DELETE ...` clause in the |
| 19 | +-- `rule_type_data_sources` table. |
| 20 | +-- |
| 21 | +-- We also want to prevent the creation of a data source with a given |
| 22 | +-- name if another data source with the same name exists in the |
| 23 | +-- project hierarchy. I'm not sure how to express this as a database |
| 24 | +-- constraint, nor I believe this would be efficient, so we decided to |
| 25 | +-- let the application layer enforce that as we do with profiles. |
| 26 | + |
| 27 | +CREATE TABLE data_sources( |
| 28 | + id UUID NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY, |
| 29 | + name TEXT NOT NULL, |
| 30 | + display_name TEXT NOT NULL, |
| 31 | + project_id UUID NOT NULL, |
| 32 | + created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(), |
| 33 | + updated_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(), |
| 34 | + FOREIGN KEY (project_id) REFERENCES projects(id) ON DELETE CASCADE |
| 35 | +); |
| 36 | + |
| 37 | +CREATE UNIQUE INDEX data_sources_name_lower_idx ON data_sources (project_id, lower(name)); |
| 38 | + |
| 39 | +CREATE TABLE data_sources_functions( |
| 40 | + id UUID NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY, |
| 41 | + name TEXT NOT NULL, |
| 42 | + type TEXT NOT NULL, |
| 43 | + data_source_id UUID NOT NULL, |
| 44 | + definition JSONB NOT NULL, |
| 45 | + created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(), |
| 46 | + updated_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(), |
| 47 | + FOREIGN KEY (data_source_id) REFERENCES data_sources(id) ON DELETE CASCADE |
| 48 | +); |
| 49 | + |
| 50 | +CREATE UNIQUE INDEX data_sources_functions_name_lower_idx ON data_sources_functions (data_source_id, lower(name)); |
| 51 | + |
| 52 | +CREATE TABLE rule_type_data_sources( |
| 53 | + rule_type_id UUID NOT NULL, |
| 54 | + data_sources_id UUID NOT NULL, |
| 55 | + FOREIGN KEY (rule_type_id) REFERENCES rule_type(id), |
| 56 | + FOREIGN KEY (data_sources_id) REFERENCES data_sources(id), |
| 57 | + UNIQUE (rule_type_id, data_sources_id) |
| 58 | +); |
| 59 | + |
| 60 | +COMMIT; |
0 commit comments