Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions docs/en_US/foreign_key_dialog.rst
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,14 @@ Use the fields in the *Definition* tab to define the foreign key constraint:
if any column is null, the row is not required to have a match in the
referenced table.

* Move the *Period?* switch to the *Yes* position to create a temporal foreign
key, which compares the last column pair on the *Columns* tab using
*PERIOD*: each referencing row's range must be covered by the ranges of the
matching referenced rows. The referenced columns must be a primary key or
unique constraint using *WITHOUT OVERLAPS*, the foreign key needs at least
two columns, and the *On update* and *On delete* actions are fixed at
*NO ACTION*. The default is *No*. This option is available on PostgreSQL 18
and later.
* Move the *Enforced?* switch to the *No* position to create the foreign key
as *NOT ENFORCED*; PostgreSQL records the constraint but does not check it
against the table content. A foreign key that is not enforced cannot be
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,7 @@ export default class ForeignKeySchema extends BaseUISchema {
confmatchtype: false,
convalidated: undefined,
conenforced: true,
conperiod: false,
columns: undefined,
confupdtype: 'a',
confdeltype: 'a',
Expand Down Expand Up @@ -252,6 +253,12 @@ export default class ForeignKeySchema extends BaseUISchema {
{label: 'FULL', value: true},
{label: 'SIMPLE', value: false},
], readonly: obj.isReadonly,
},{
id: 'conperiod', label: gettext('Period?'),
type: 'switch', group: gettext('Definition'), min_version: 180000,
readonly: obj.isReadonly,
helpMessage: gettext('Make this a temporal foreign key: the last column pair is compared with PERIOD, and the referenced key must use WITHOUT OVERLAPS.'),
helpMessageMode: ['edit', 'create'],
},{
id: 'conenforced', label: gettext('Enforced?'),
type: 'switch', group: gettext('Definition'), min_version: 180000,
Expand Down Expand Up @@ -416,24 +423,38 @@ export default class ForeignKeySchema extends BaseUISchema {
},{
id: 'confupdtype', label: gettext('On update'),
type:'select', group: gettext('Action'), mode: ['edit','create'],
deps: ['conperiod'],
// A foreign key using PERIOD only supports NO ACTION.
depChange: (state)=>{
if(state.conperiod) {
return {confupdtype: 'a'};
}
},
controlProps:{allowClear: false},
options: [
{label: 'NO ACTION', value: 'a'},
{label: 'RESTRICT', value: 'r'},
{label: 'CASCADE', value: 'c'},
{label: 'SET NULL', value: 'n'},
{label: 'SET DEFAULT', value: 'd'},
], readonly: obj.isReadonly,
], readonly: (state)=>obj.isReadonly(state) || state.conperiod,
},{
id: 'confdeltype', label: gettext('On delete'),
type:'select', group: gettext('Action'), mode: ['edit','create'],
deps: ['conperiod'],
// A foreign key using PERIOD only supports NO ACTION.
depChange: (state)=>{
if(state.conperiod) {
return {confdeltype: 'a'};
}
},
options: [
{label: 'NO ACTION', value: 'a'},
{label: 'RESTRICT', value: 'r'},
{label: 'CASCADE', value: 'c'},
{label: 'SET NULL', value: 'n'},
{label: 'SET DEFAULT', value: 'd'},
], readonly: obj.isReadonly,
], readonly: (state)=>obj.isReadonly(state) || state.conperiod,
}];
}

Expand All @@ -443,6 +464,11 @@ export default class ForeignKeySchema extends BaseUISchema {
return true;
}

if (state.conperiod && state.columns.length < 2) {
setError('columns', gettext('A foreign key using PERIOD needs at least two columns.'));
return true;
}

if (this.isNew(state)){
if (state.autoindex && isEmptyString(state.coveringindex)) {
setError('coveringindex', gettext('Please specify covering index name.'));
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
-- Constraint: FKey_period

-- ALTER TABLE IF EXISTS testschema.test_period_table DROP CONSTRAINT IF EXISTS "FKey_period";

ALTER TABLE IF EXISTS testschema.test_period_table
ADD CONSTRAINT "FKey_period" FOREIGN KEY (id, PERIOD valid_at)
REFERENCES testschema.test_period_ref_table (id, PERIOD valid_at) MATCH SIMPLE
ON UPDATE NO ACTION
ON DELETE NO ACTION;
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
ALTER TABLE IF EXISTS testschema.test_period_table
ADD CONSTRAINT "FKey_period" FOREIGN KEY (id, PERIOD valid_at)
REFERENCES testschema.test_period_ref_table (id, PERIOD valid_at) MATCH SIMPLE
ON UPDATE NO ACTION
ON DELETE NO ACTION;
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
-- Table: testschema.test_period_table

-- DROP TABLE IF EXISTS testschema.test_period_table;

CREATE TABLE IF NOT EXISTS testschema.test_period_table
(
id int4range,
valid_at daterange,
CONSTRAINT fk_period_table FOREIGN KEY (id, PERIOD valid_at)
REFERENCES testschema.test_period_ref_table (id, PERIOD valid_at) MATCH SIMPLE
ON UPDATE NO ACTION
ON DELETE NO ACTION
)

TABLESPACE pg_default;

ALTER TABLE IF EXISTS testschema.test_period_table
OWNER to <OWNER>;
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
CREATE TABLE testschema.test_period_table
(
id int4range,
valid_at daterange,
CONSTRAINT fk_period_table FOREIGN KEY (id, PERIOD valid_at)
REFERENCES testschema.test_period_ref_table (id, PERIOD valid_at) MATCH SIMPLE
ON UPDATE NO ACTION
ON DELETE NO ACTION
)

TABLESPACE pg_default;
Original file line number Diff line number Diff line change
Expand Up @@ -186,6 +186,125 @@
"name": "test_partitioned_table"
}
},
{
"type": "create",
"name": "Create Referenced Table with a WITHOUT OVERLAPS Primary Key",
"endpoint": "NODE-table.obj",
"sql_endpoint": "NODE-table.sql_id",
"data": {
"name": "test_period_ref_table",
"columns": [
{
"name": "id",
"cltype": "int4range"
},
{
"name": "valid_at",
"cltype": "daterange"
}
],
"is_partitioned": false,
"schema": "testschema",
"spcname": "pg_default"
},
"post_scenario_sql": "ALTER TABLE testschema.test_period_ref_table ADD CONSTRAINT test_period_ref_table_pkey PRIMARY KEY (id, valid_at WITHOUT OVERLAPS);",
"store_object_id": true
},
{
"type": "create",
"name": "Create Table with a Foreign Key using PERIOD",
"endpoint": "NODE-table.obj",
"sql_endpoint": "NODE-table.sql_id",
"msql_endpoint": "NODE-table.msql",
"data": {
"name": "test_period_table",
"columns": [
{
"name": "id",
"cltype": "int4range"
},
{
"name": "valid_at",
"cltype": "daterange"
}
],
"is_partitioned": false,
"schema": "testschema",
"spcname": "pg_default",
"foreign_key": [
{
"name": "fk_period_table",
"condeferrable": false,
"condeferred": false,
"confmatchtype": false,
"convalidated": true,
"conperiod": true,
"columns": [
{
"local_column": "id",
"references": "<test_period_ref_table>",
"referenced": "id"
},
{
"local_column": "valid_at",
"references": "<test_period_ref_table>",
"referenced": "valid_at"
}
],
"confupdtype": "a",
"confdeltype": "a",
"autoindex": false,
"coveringindex": ""
}
]
},
"expected_sql_file": "create_table_period.sql",
"expected_msql_file": "create_table_period_msql.sql",
"store_object_id": true
},
{
"type": "create",
"name": "Create Foreign Key Constraint using PERIOD",
"endpoint": "NODE-foreign_key.obj",
"sql_endpoint": "NODE-foreign_key.sql_id",
"msql_endpoint": "NODE-foreign_key.msql",
"data": {
"name": "FKey_period",
"condeferrable": false,
"condeferred": false,
"confmatchtype": false,
"convalidated": true,
"conperiod": true,
"columns": [
{
"local_column": "id",
"references": "<test_period_ref_table>",
"referenced": "id"
},
{
"local_column": "valid_at",
"references": "<test_period_ref_table>",
"referenced": "valid_at"
}
],
"confupdtype": "a",
"confdeltype": "a",
"autoindex": false,
"coveringindex": ""
},
"expected_sql_file": "create_foreign_key_period.sql",
"expected_msql_file": "create_foreign_key_period_msql.sql",
"preprocess_data": true
},
{
"type": "delete",
"name": "Drop Foreign Key using PERIOD",
"endpoint": "NODE-foreign_key.delete_id",
"data": {
"name": "FKey_period"
},
"post_scenario_sql": "DROP TABLE testschema.test_period_table, testschema.test_period_ref_table;"
},
{
"type": "create",
"name": "Create Second Table for Foreign Key",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -365,7 +365,8 @@ def table_constraint_comp(source_table, target_table):
'confupdtype', 'confdeltype',
'confdelsetcols',
'confmatchtype', 'convalidated',
'conislocal', 'refnsp', 'reftab']
'conperiod', 'conislocal',
'refnsp', 'reftab']
}

for constraint in ['primary_key', 'unique_constraint',
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
ALTER TABLE IF EXISTS {{ conn|qtIdent(data.schema, data.table) }}
ADD{% if data.name %} CONSTRAINT {{ conn|qtIdent(data.name) }}{% endif%} FOREIGN KEY ({% for columnobj in data.columns %}{% if loop.index != 1 %}
, {% endif %}{{ conn|qtIdent(columnobj.local_column)}}{% endfor %})
, {% endif %}{% if data.conperiod and loop.last %}PERIOD {% endif %}{{ conn|qtIdent(columnobj.local_column)}}{% endfor %})
REFERENCES {{ conn|qtIdent(data.remote_schema, data.remote_table) }} ({% for columnobj in data.columns %}{% if loop.index != 1 %}
, {% endif %}{{ conn|qtIdent(columnobj.referenced)}}{% endfor %}){% if data.confmatchtype is defined %} {% if data.confmatchtype %}MATCH FULL{% else %}MATCH SIMPLE{% endif%}{% endif%}{% if data.confupdtype is defined %}
, {% endif %}{% if data.conperiod and loop.last %}PERIOD {% endif %}{{ conn|qtIdent(columnobj.referenced)}}{% endfor %}){% if data.confmatchtype is defined %} {% if data.confmatchtype %}MATCH FULL{% else %}MATCH SIMPLE{% endif%}{% endif%}{% if data.confupdtype is defined %}

ON UPDATE{% if data.confupdtype == 'a' %}
NO ACTION{% elif data.confupdtype == 'r' %}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ SELECT ct.oid,
description as comment,
convalidated,
conenforced,
conperiod,
conislocal
FROM pg_catalog.pg_constraint ct
JOIN pg_catalog.pg_class cl ON cl.oid=conrelid
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,9 +53,9 @@
{% for data in foreign_key_data %}{% if loop.index != 1 %},{% endif %}

{% if data.name %}CONSTRAINT {{conn|qtIdent(data.name)}} {% endif %}FOREIGN KEY ({% for columnobj in data.columns %}{% if loop.index != 1 %}
, {% endif %}{{ conn|qtIdent(columnobj.local_column)}}{% endfor %})
, {% endif %}{% if data.conperiod and loop.last %}PERIOD {% endif %}{{ conn|qtIdent(columnobj.local_column)}}{% endfor %})
REFERENCES {{ conn|qtIdent(data.remote_schema, data.remote_table) }} ({% for columnobj in data.columns %}{% if loop.index != 1 %}
, {% endif %}{{ conn|qtIdent(columnobj.referenced)}}{% endfor %}) {% if data.confmatchtype %}MATCH FULL{% else %}MATCH SIMPLE{% endif%}
, {% endif %}{% if data.conperiod and loop.last %}PERIOD {% endif %}{{ conn|qtIdent(columnobj.referenced)}}{% endfor %}) {% if data.confmatchtype %}MATCH FULL{% else %}MATCH SIMPLE{% endif%}

ON UPDATE{% if data.confupdtype == 'a' %}
NO ACTION{% elif data.confupdtype == 'r' %}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,8 @@
ON DELETE SET NULL or SET DEFAULT action (#10815).

The foreign key update template cannot change the action, so a foreign key
whose column list differs must be dropped and recreated.
whose column list differs must be dropped and recreated. The same applies to
a foreign key whose PERIOD (PostgreSQL 18 temporal foreign key) differs.
"""

import copy
Expand All @@ -29,7 +30,7 @@ def _foreign_key(**overrides):
confdelsetcols=['author_id'], confmatchtype=False, conkey=[1, 2],
confkey=[1, 2], confrelid=16390, fknsp='app', fktab='posts',
refnspoid=16385, refnsp='app', reftab='tenants', comment=None,
convalidated=True, conislocal=True,
convalidated=True, conislocal=True, conperiod=False,
columns=[{'local_column': 'tenant_id', 'references': 16390,
'referenced': 'id'},
{'local_column': 'author_id', 'references': 16390,
Expand All @@ -45,18 +46,19 @@ class TestSchemaDiffFkDeleteSetColumnsUnit(BaseTestGenerator):

scenarios = [
('A foreign key whose SET NULL column list differs is recreated',
dict(target_cols=None, recreated=True)),
dict(target=dict(confdelsetcols=None), recreated=True)),
('A foreign key whose SET NULL column list changes is recreated',
dict(target_cols=['tenant_id'], recreated=True)),
dict(target=dict(confdelsetcols=['tenant_id']), recreated=True)),
('A foreign key with the same SET NULL column list is unchanged',
dict(target_cols=['author_id'], recreated=False)),
dict(target=dict(), recreated=False)),
('A foreign key whose PERIOD differs is recreated',
dict(target=dict(conperiod=True), recreated=True)),
]

def runTest(self):
source = {'schema': 'app', 'foreign_key': [_foreign_key()]}
target = {'schema': 'app', 'foreign_key': [
_foreign_key(oid=17420, confrelid=17390,
confdelsetcols=self.target_cols)]}
_foreign_key(oid=17420, confrelid=17390, **self.target)]}

diff = SchemaDiffTableCompare.table_constraint_comp(
copy.deepcopy(source), copy.deepcopy(target))['foreign_key']
Expand Down
17 changes: 17 additions & 0 deletions web/regression/javascript/schema_ui_files/foreign_key.ui.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -256,6 +256,16 @@ describe('ForeignKeySchema', ()=>{
expect(field.readonly({oid: 1234, conenforced: true})).toBe(true);
});

it('a foreign key using PERIOD only allows NO ACTION', ()=>{
for(const id of ['confupdtype', 'confdeltype']) {
let field = _.find(schemaObj.fields, (f)=>f.id==id);
expect(field.depChange({conperiod: true})).toEqual({[id]: 'a'});
expect(field.depChange({conperiod: false})).toBeUndefined();
expect(field.readonly({conperiod: true})).toBe(true);
expect(field.readonly({conperiod: false})).toBeFalsy();
}
});

it('table column addition is a no-op for a removed foreign key', ()=>{
schemaObj.top = new TableSchema({}, null);
expect(getFieldDepChange(schemaObj, 'columns')(undefined, ['columns'], null, {
Expand Down Expand Up @@ -286,6 +296,13 @@ describe('ForeignKeySchema', ()=>{

state.coveringindex = 'asdas';
expect(schemaObj.validate(state, setError)).toBe(false);

state.conperiod = true;
expect(schemaObj.validate(state, setError)).toBe(true);
expect(setError).toHaveBeenCalledWith('columns', 'A foreign key using PERIOD needs at least two columns.');

state.columns = ['id', 'valid_at'];
expect(schemaObj.validate(state, setError)).toBe(false);
});
});

Loading