信息架构中的 referential_constraints.unique_constraint_* 列的 NULL 值

本文介绍了信息架构中的 referential_constraints.unique_constraint_* 列的 NULL 值的处理方法,对大家解决问题具有一定的参考价值

问题描述

在 Postgres 10 中,我声明了以下内容:

创建表 test_abc (pk 整数不为空,id 整数不为 NULL,id2 整数不为空,主键 (pk));创建唯一索引 test_abc_ids ON test_abc(id,id2);

然后是第二个表,其 FK 引用第一个表:

创建表 test_def (id 整数不为空,abc_id 整数,abc_id2 整数,主键(id),FOREIGN KEY (abc_id,abc_id2) 引用 test_abc(id,id2));

现在考虑这个查询的输出:

SELECT unique_constraint_catalog, unique_constraint_schema, unique_constraint_nameFROM information_schema.referential_constraints rWHERE r.constraint_name = 'test_def_abc_id_fkey'----------------------空 空 空

所有 unique_constraint_* 列都有一个空值.

Postgres 文档看来,这些元列应该包含

<块引用>

包含外键约束引用的唯一或主键约束的[对象]的名称(始终为当前数据库)

问题:我肯定在同一个数据库中,并且 test_abc 表上声明的唯一索引是唯一约束(否则我将无法声明 FK 开头),那么为什么这些列空吗?

我正在使用带有一些连接的 referential_constraints 来获取有关由我的外键引用的列的信息,但是这样我就错过了所有使用索引设置唯一约束的那些.

解决方案

测试设置

您假设约束名称 test_def_abc_id_fkey,这是您在 Postgres 11 或更早版本中设置的默认名称.不过值得注意的是,Postgres 12 的默认名称已得到改进,其中相同的设置会产生 test_def_abc_id_abc_id2_fkey.Postgres 12 的发行说明:

<块引用>
  • 为外键选择默认约束名称时使用所有键列的名称 (Peter Eisentraut)

    以前,约束名称中只包含第一列名称,导致多列外键不明确.

见:

db<>小提琴这里

所以让我们为 FK 约束使用显式名称 test_def_abc_fkey 以避免混淆:

CREATE TABLE test_abc (pk int 主键, id int NOT NULL, id2 int NOT NULL);创建唯一索引 test_abc_ids ON test_abc(id,id2);创建表 test_def (id int 主键, abc_id 整数, abc_id2 整数, 约束 test_def_abc_fkey -- !外键 (abc_id,abc_id2) 参考 test_abc(id,id2));

适用于 Postgres 9.5 - Postgres 12.
即使在 Postgres 9.3 中.
(我一直有错误的印象,需要一个实际的约束.)

回答

您通过查询信息架构的观察结果:

选择 *FROM information_schema.referential_constraintsWHERE constraint_name = 'test_def_abc_fkey';——明确的名字

我们得到一行,但是 unique_constraint_catalogunique_constraint_schemaunique_constraint_name 三个字段是 NULL.

解释似乎很简单.正如手册所说,这些列描述:

<块引用>

...外键约束引用的唯一键或主键约束

但是没有 UNIQUE 约束,只是一个UNIQUE index.UNIQUE 约束是使用 Postgres 中的 UNIQUE 索引实现的.约束由 SQL 标准定义,索引是实现细节.存在与您发现的差异一样的差异.相关:

使用实际 UNIQUE constraint 的相同测试按预期显示数据:

db<>小提琴这里

所以这似乎是有道理的.特别是因为 信息模式 也是由 SQL 标准委员会和索引定义的没有标准化,只有约束.(信息模式视图中没有索引信息.)

一切都清楚了吗?不完全是.

然而

还有另一个信息架构视图key_column_usage.它的最后一列描述为:

<块引用>

position_in_unique_constraint ... 对于外键约束,引用列在其唯一约束内的序号位置(计数从 1 开始);否则为空

粗体强调我的.此处,列在 index 中的序号位置无论如何都会列出:

选择 *FROM information_schema.key_column_usageWHERE constraint_name = 'test_def_abc_fkey';

见:

db<>小提琴这里

似乎不一致.

更糟糕的是,手册声称创建 FOREIGN KEY 约束需要一个实际的 PRIMARY KEYUNIQUE 约束:

<块引用>

外键必须引用为主键或形成唯一约束.这意味着引用的列总是有一个索引(主键或唯一的索引约束);因此检查引用行是否匹配将高效.

似乎是一个文档错误?如果没有人能指出我哪里出错了,我会提交一个错误报告.

相关:

解决方案

<块引用>

我正在使用带有一些连接的 referential_constraints 来获取有关由我的外键引用的列的信息,但是这样我就错过了所有使用索引设置唯一约束的那些.

在 Postgres 中,系统目录是真实的真实来源.见:

所以你可以使用这样的东西(就像我在 fiddle以上):

SELECT c.conname, c.conrelid::regclass AS fk_table, k1.fk_columns, c.confrelid::regclass AS ref_table, k2.ref_key_columnsFROM pg_catalog.pg_constraint c左连接横向 (选择数组(选择一个.attnameFROM pg_catalog.pg_attribute 一个, unnest(c.conkey) WITH ORDINALITY AS k(attnum, ord)其中 a.attrelid = c.conrelidAND a.attnum = k.attnum由 k.ord 订购) 作为 fk_columns) k1 ON 真左连接横向 (选择数组(选择一个.attnameFROM pg_catalog.pg_attribute 一个, unnest(c.confkey) WITH ORDINALITY AS k(attnum, ord)哪里 a.attrelid = c.confrelidAND a.attnum = k.attnum由 k.ord 订购) 作为 ref_key_columns) k2 ONWHERE conname = 'test_def_abc_fkey';

返回:

<上一页>同名 |fk_table |fk_columns |参考表 |ref_key_columns:---------------- |:------- |:--------------- |:-------- |:--------------test_def_abc_fkey |测试定义 |{abc_id,abc_id2} |test_abc |{id,id2}

相关:

In Postgres 10 I have declared the following:

create table test_abc (
    pk integer not null,
    id integer not NULL,
    id2 integer not null,
    PRIMARY KEY (pk)
);
CREATE UNIQUE INDEX test_abc_ids ON test_abc(id,id2);

And then a second table with a FK referencing the first:

create table test_def (
    id integer not null,
    abc_id integer,
    abc_id2 integer,
    PRIMARY KEY (id),
    FOREIGN KEY (abc_id,abc_id2) references test_abc(id,id2)
);

Now consider the output of this query:

SELECT unique_constraint_catalog, unique_constraint_schema, unique_constraint_name
FROM   information_schema.referential_constraints r
WHERE  r.constraint_name = 'test_def_abc_id_fkey'
----------------------
NULL NULL NULL

All unique_constraint_* columns have a null value.

From the Postgres documentation it seems these meta columns should contain the

name of the [object] that contains the unique or primary key constraint that the foreign key constraint references (always the current database)

Question: I'm surely in the same database, and the unique index declared on test_abc table is a unique constraint (otherwise I wouldn't be able to declare the FK to begin with), so why are these columns empty?

I'm using the referential_constraints with some joins to get information about the columns referenced by my foreign keys, but this way I'm missing all those where the unique constraint is set with an index.

解决方案

Test setup

You assume the constraint name test_def_abc_id_fkey, the default name resulting from your setup in Postgres 11 or older. Worth noting, though, that default names have been improved for Postgres 12, where the same setup results in test_def_abc_id_abc_id2_fkey. The release notes for Postgres 12:

  • Use all key columns' names when selecting default constraint names for foreign keys (Peter Eisentraut)

    Previously, only the first column name was included in the constraint name, resulting in ambiguity for multi-column foreign keys.

See:

db<>fiddle here

So let's use the explicit name test_def_abc_fkey for the FK constraint to avoid confusion:

CREATE TABLE test_abc (
  pk  int PRIMARY KEY
, id  int NOT NULL
, id2 int NOT NULL
);

CREATE UNIQUE INDEX test_abc_ids ON test_abc(id,id2);

CREATE TABLE test_def (
  id      int PRIMARY KEY
, abc_id  int
, abc_id2 int
, CONSTRAINT test_def_abc_fkey  -- !
     FOREIGN KEY (abc_id,abc_id2) REFERENCES test_abc(id,id2)
);

And that works in Postgres 9.5 - Postgres 12.
Even in Postgres 9.3.
(I had been under wrong impression an actual constraint would be required.)

Answer

Your observation from querying the information schema holds:

SELECT *
FROM   information_schema.referential_constraints
WHERE  constraint_name = 'test_def_abc_fkey';  -- unequivocal name

We get a row, but the three fields unique_constraint_catalog, unique_constraint_schema and unique_constraint_name are NULL.

The explanation seems simple. Those columns describe, as the manual puts it:

... the unique or primary key constraint that the foreign key constraint references

But there is no UNIQUE constraint, just a UNIQUE index. A UNIQUE constraint is implemented using a UNIQUE index in Postgres. Constraints are defined by the SQL standard, indexes are implementation details. There are differences like the one you discovered. Related:

The same test with an actual UNIQUE constraint shows data as expected:

db<>fiddle here

So this seems to make sense. Especially since the information schema is also defined by the SQL standards committee and indexes are not standardized, only constraints. (No index information in information schema views.)

All clear? Not quite.

However

There is another information schema view key_column_usage. Its last column is described as:

position_in_unique_constraint ... For a foreign-key constraint, ordinal position of the referenced column within its unique constraint (count starts at 1); otherwise null

Bold emphasis mine. Here, the ordinal position of the column in the index is listed anyway:

SELECT *
FROM   information_schema.key_column_usage
WHERE  constraint_name = 'test_def_abc_fkey';

See:

db<>fiddle here

Seems inconsistent.

What's worse, the manual claims that an actual PRIMARY KEY or UNIQUE constraint would be required for the creation of a FOREIGN KEY constraint:

A foreign key must reference columns that either are a primary key or form a unique constraint. This means that the referenced columns always have an index (the one underlying the primary key or unique constraint); so checks on whether a referencing row has a match will be efficient.

Seems to be a documentation bug? If nobody can point out where I am going wrong here, I'll file a bug report.

Related:

Solution

I'm using the referential_constraints with some joins to get information about the columns referenced by my foreign keys, but this way I'm missing all those where the unique constraint is set with an index.

In Postgres, the system catalog is the actual source of truth. See:

So you could use something like this (like I also added in the fiddle above):

SELECT c.conname
     , c.conrelid::regclass  AS fk_table, k1.fk_columns
     , c.confrelid::regclass AS ref_table, k2.ref_key_columns
FROM   pg_catalog.pg_constraint c
LEFT   JOIN LATERAL (
   SELECT ARRAY (
      SELECT a.attname
      FROM   pg_catalog.pg_attribute a
           , unnest(c.conkey) WITH ORDINALITY AS k(attnum, ord)
      WHERE  a.attrelid = c.conrelid
      AND    a.attnum = k.attnum
      ORDER  BY k.ord
      ) AS fk_columns
   ) k1 ON true
LEFT   JOIN LATERAL (
   SELECT ARRAY (
      SELECT a.attname
      FROM   pg_catalog.pg_attribute a
           , unnest(c.confkey) WITH ORDINALITY AS k(attnum, ord)
      WHERE  a.attrelid = c.confrelid
      AND    a.attnum = k.attnum
      ORDER  BY k.ord
      ) AS ref_key_columns
   ) k2 ON true
WHERE  conname = 'test_def_abc_fkey';

Returns:

conname           | fk_table | fk_columns       | ref_table | ref_key_columns
:---------------- | :------- | :--------------- | :-------- | :--------------
test_def_abc_fkey | test_def | {abc_id,abc_id2} | test_abc  | {id,id2}       

Related:

这篇关于信息架构中的 referential_constraints.unique_constraint_* 列的 NULL 值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,WP2

admin_action_{$_REQUEST[‘action’]}

do_action( "admin_action_{$_REQUEST[‘action’]}" )动作钩子::在发送“Action”请求变量时激发。Action Hook: Fires when an ‘action’ request variable is sent.目录锚点:#说明#源码说明(Description)钩子名称的动态部分$_REQUEST['action']引用从GET或POST请求派生的操作。源码(Source)更新版本源码位置使用被使用2.6.0 wp-admin/admin.php:...

日期:2020-09-02 17:44:16 浏览:1155

admin_footer-{$GLOBALS[‘hook_suffix’]}

do_action( "admin_footer-{$GLOBALS[‘hook_suffix’]}", string $hook_suffix )操作挂钩:在默认页脚脚本之后打印脚本或数据。Action Hook: Print scripts or data after the default footer scripts.目录锚点:#说明#参数#源码说明(Description)钩子名的动态部分,$GLOBALS['hook_suffix']引用当前页的全局钩子后缀。参数(Parameters)参数类...

日期:2020-09-02 17:44:20 浏览:1056

customize_save_{$this->id_data[‘base’]}

do_action( "customize_save_{$this-&gt;id_data[‘base’]}", WP_Customize_Setting $this )动作钩子::在调用WP_Customize_Setting::save()方法时激发。Action Hook: Fires when the WP_Customize_Setting::save() method is called.目录锚点:#说明#参数#源码说明(Description)钩子名称的动态部分,$this->id_data...

日期:2020-08-15 15:47:24 浏览:795

customize_value_{$this->id_data[‘base’]}

apply_filters( "customize_value_{$this-&gt;id_data[‘base’]}", mixed $default )过滤器::过滤未作为主题模式或选项处理的自定义设置值。Filter Hook: Filter a Customize setting value not handled as a theme_mod or option.目录锚点:#说明#参数#源码说明(Description)钩子名称的动态部分,$this->id_date['base'],指的是设置...

日期:2020-08-15 15:47:24 浏览:882

get_comment_author_url

过滤钩子:过滤评论作者的URL。Filter Hook: Filters the comment author’s URL.目录锚点:#源码源码(Source)更新版本源码位置使用被使用 wp-includes/comment-template.php:32610...

日期:2020-08-10 23:06:14 浏览:923

network_admin_edit_{$_GET[‘action’]}

do_action( "network_admin_edit_{$_GET[‘action’]}" )操作挂钩:启动请求的处理程序操作。Action Hook: Fires the requested handler action.目录锚点:#说明#源码说明(Description)钩子名称的动态部分$u GET['action']引用请求的操作的名称。源码(Source)更新版本源码位置使用被使用3.1.0 wp-admin/network/edit.php:3600...

日期:2020-08-02 09:56:09 浏览:867

network_sites_updated_message_{$_GET[‘updated’]}

apply_filters( "network_sites_updated_message_{$_GET[‘updated’]}", string $msg )筛选器挂钩:在网络管理中筛选特定的非默认站点更新消息。Filter Hook: Filters a specific, non-default site-updated message in the Network admin.目录锚点:#说明#参数#源码说明(Description)钩子名称的动态部分$_GET['updated']引用了非默认的...

日期:2020-08-02 09:56:03 浏览:852

pre_wp_is_site_initialized

过滤器::过滤在访问数据库之前是否初始化站点的检查。Filter Hook: Filters the check for whether a site is initialized before the database is accessed.目录锚点:#源码源码(Source)更新版本源码位置使用被使用 wp-includes/ms-site.php:93910...

日期:2020-07-29 10:15:38 浏览:824

WordPress 的SEO 教学:如何在网站中加入关键字(Meta Keywords)与Meta 描述(Meta Description)?

你想在WordPress 中添加关键字和meta 描述吗?关键字和meta 描述使你能够提高网站的SEO。在本文中,我们将向你展示如何在WordPress 中正确添加关键字和meta 描述。为什么要在WordPress 中添加关键字和Meta 描述?关键字和说明让搜寻引擎更了解您的帖子和页面的内容。关键词是人们寻找您发布的内容时,可能会搜索的重要词语或片语。而Meta Description则是对你的页面和文章的简要描述。如果你想要了解更多关于中继标签的资讯,可以参考Google的说明。Meta 关键字和描...

日期:2020-10-03 21:18:25 浏览:1684

谷歌的SEO是什么

SEO (Search Engine Optimization)中文是搜寻引擎最佳化,意思近于「关键字自然排序」、「网站排名优化」。简言之,SEO是以搜索引擎(如Google、Bing)为曝光媒体的行销手法。例如搜寻「wordpress教学」,会看到本站的「WordPress教学:12个课程…」排行Google第一:关键字:wordpress教学、wordpress课程…若搜寻「网站架设」,则会看到另一个网页排名第1:关键字:网站架设、架站…以上两个网页,每月从搜寻引擎导入自然流量,达2万4千:每月「有机搜...

日期:2020-10-30 17:23:57 浏览:1293