問題描述
轉儲文件中視圖預定義的目的是什麼 (What is the purpose of views' predefinitions in dump file)
我正在開發我們正在使用的項目 :sql
模式格式 用於 Active Record 轉儲程序(以支持更複雜的邏輯,如觸發器)。
我們有很多視圖,我可以在 database/structure.sql
文件中看到其中一些具有帶有 NULL
的“預定義”模式就像:
CREATE VIEW public.my_view AS
SELECT
NULL::integer AS record_id,
NULL::integer AS another_record_id,
NULL::double precision AS some_field;
然後,數千行之後,添加了定義:
CREATE OR REPLACE VIEW public.my_view AS
‑‑ actual query
我看不到模式“預定義”和定義之間的任何對視圖的引用我的 SQL 查詢。還,還有其他立即創建的視圖(沒有該架構“預定義”)。
我正在查看 Active Record 文檔,但找不到任何提示。Rails 在後台使用 pg_dump
,但我在 pg_dump
文檔中也沒有看到任何相關內容。
為什麼有些視圖需要預先定義架構,而其他人則沒有,即使在 database/structure.sql
文件中的預定義和實際定義之間沒有引用它們?是否在使用另一種結構(如物化視圖或其他東西)時防止某些競爭條件?
pg_dump
文檔中也沒有看到任何相關內容。 為什麼有些視圖需要預先定義架構,而其他視圖則不需要't,即使 database/structure.sql
文件中的預定義和實際定義之間沒有引用它們?是否在使用另一種結構(如物化視圖或其他東西)時防止某些競爭條件?
pg_dump
文檔中也沒有看到任何相關內容。 為什麼有些視圖需要預先定義架構,而其他視圖則不需要't,即使 database/structure.sql
文件中的預定義和實際定義之間沒有引用它們?是否在使用另一種結構(如物化視圖或其他東西)時防止某些競爭條件?
參考解法
方法 1:
This is because views can have circular dependencies like this:
CREATE SCHEMA s;
CREATE OR REPLACE VIEW s.v AS SELECT 1 a;
CREATE OR REPLACE VIEW s.w AS SELECT a FROM s.v;
CREATE OR REPLACE VIEW s.v AS SELECT a FROM s.w;
Those views can't be queried in this form. E.g. select * from s.w
produces:
SQL Error [42P17]: ERROR: infinite recursion detected in rules for relation "w"
But running the following pg_dump
command:
pg_dump ‑U postgres ‑d postgres ‑s ‑n s
Produces this output:
CREATE SCHEMA s;
CREATE VIEW s.v AS
SELECT
NULL::integer AS a;
CREATE VIEW s.w AS
SELECT v.a
FROM s.v;
CREATE OR REPLACE VIEW s.v AS
SELECT w.a
FROM s.w;
As you can see, there's your dummy view which has to be created, because s.v
couldn't access the not‑yet existing s.w
at the point of creation.
You can also find this logic in pg_dump.c
's createDummyViewAsClause
function, whose documentation reads:
/*
* Create a dummy AS clause for a view. This is used when the real view
* definition has to be postponed because of circular dependencies.
* We must duplicate the view's external properties ‑‑ column names and types
* (including collation) ‑‑ so that it works for subsequent references. [...]
*/
(by Maciej Małecki、Lukas Eder)