Repository navigation
Decision: remove a referenced scan only where a foreign key gives every row one row of the same types #200
Replies: 1 comment
|
PR #212 (#198) changes condition 3 of "Which foreign keys". A referencing column no longer has to be ChangeA key whose referencing columns may be Why the result is the samePostgreSQL checks a foreign key on every row whose key columns are all non- The fingerprint check covers the nullability of the referencing columns. Adding or dropping Results
The item "Nullable referencing columns (#198)" under "What is not removed" no longer applies. PR #212(#198)는 「어떤 외래 키」의 3번 조건을 변경한다. 참조하는 컬럼이 더 이상 변경참조하는 컬럼이 결과가 같은 이유PostgreSQL은 키 컬럼이 모두 지문 확인은 참조 컬럼의 NULL 허용 여부를 포함한다. 결과
「없애지 않는 것」의 「NULL 허용 참조 컬럼(#198)」 항목은 더 이상 해당하지 않는다. |
Uh oh!
There was an error while loading. Please reload this page.
Background
A referencing object map (R2RML §8) joins the parent logical table on its join conditions, and the unfolded SQL scans the parent table even when the query only needs the parent's subject, which is built from the referenced key:
?o ex:placedBy ?cisorders t0 JOIN customers t1 ON t1.id = t0.customer_id. A template join to a class of the referenced table (?o ex:buyer ?c . ?c a ex:Customer) gives the same join. Issue #112 asks to remove such scans when a foreign key makes them redundant. Discussion #84 merges two scans of one table that a key pins to one row; this rule removes a scan of another table and reads its columns from the referencing row, so its conditions differ.Decision
Which foreign keys
From the catalog snapshot (Discussion #187), a foreign key of a table
CreferencingPqualifies whenconvalidated; a key addedNOT VALIDdoes not hold for the rows that were there),Chas no inheritance children, unless it is partitioned: a scan ofCreads the children's rows, which do not inherit the key,NOT NULL: PostgreSQL checks a key only on rows whose columns are all non-NULL(MATCH SIMPLE), and the join drops a row with aNULL,Pthat identifies a row by SQL=as in Discussion Decision: merge scans of a table only where a not-null key pins them to one row #84 (every columnNOT NULL, the column's collation and the type's default operator class, a type compared by=without a cast or term key), and every unique key on exactly those columns does: the foreign key compares with the equality of one of them, and the catalog does not say which,ColumnTypeequal), and every referencing and referenced column compares under a deterministic collation (pg_collation.collisdeterministic, PostgreSQL 12). Within one such type, values that=finds equal have the same natural lexical form (R2RML §10.2); across types such asint4andint8, the SQL that builds a term can differ. Under a nondeterministic collation=finds different strings equal ('abc'and'ABC'under one that ignores case): the join of R2RML §8 still pairs them, but the parent's term is built from the parent's value, so the child's value would build a different IRI. A column of anrr:sqlQueryview has no keys and never qualifies.Pis the logical table the key names: the stored parts of therr:tableNameequal those of the referenced table asregclassprints it.regclassleaves out the schema where the search path finds the table, so a mapping that names it with its schema is not recognized.Which scans
A scan
tPofPis removed next to a scantCofCwhenOPTIONALpart,tP.p = tC.cfor every pair of the key, in key order: anrr:joinConditionequality, or a term comparison of the two plain columns (no base IRI, same datatype), as template decomposition writes it,tPother than the referenced ones, anywhere: select list, conditions of every scope,FILTER,ORDER BYand computed values.Every reference to
tP.pbecomestC.c, the aliases aftertPand the table ranges ofOPTIONALparts shift down, the columnstPfixed (#41) are fixed intC, the equalitiestC.c = tC.cin that scope are dropped, and repeated conditions are dropped. The step runs inCatalogPlan::newafter self-join merging, until no scan is left to remove, so a parent scan that merging gives other columns is kept.Why the result is the same
Every row of
tChas non-NULLkey columns, so the foreign key guarantees a row ofPwithp = c, and the unique key makes it the only one. The scope's conditions then keep exactly the combinations with that row intP, one per combination without it. In each of themtP.pandtC.care values of one type that=finds equal, so every term, comparison, sort key and duplicate test built fromtP.pgives the same result fromtC.c. Where anOPTIONALpart does not match, both areNULL. The dropped equalities compare aNOT NULLcolumn with itself.The snapshot entry of
Pstays among the entries the fingerprint check covers, since the plan relies on its unique key; the key itself is in the fingerprint ofC. Dropping it, adding an inheritance child or dropping aNOT NULLmakes the check fail, and the query is planned again with the join.What is not removed
Pin another scope thantC, such as across anOPTIONAL: there it decides whether the part matches.Pcompared with constants only (<customer/1> a ex:Customer): nothing joins it on the key.NOT VALID, different column types, a referenced key without an exact unique index, a join that pairs the columns differently from the key, and a parent whose other columns are read.Limits
=in joins andFILTERon the assumption that=finds equal only identical strings, which nondeterministic collations break. That is an engine-wide question, tracked in Text comparisons give wrong results under nondeterministic collations #197.Results
The differential case
tests/diff/0015-foreign-keyshas 22 queries (referencing object maps, template joins to a class, a text key, a composite key in and out of key order, a self-reference, a nullable reference, a reference of another type,OPTIONALinside and across,DISTINCT,ORDER BYwithLIMIT,FILTER,UNION). Before CI, each query was run withv12n queryon the case's data loaded twice, with and without its foreign keys; all results were equal. PostgreSQL tests cover which keys qualify (aNOT VALIDkey, an inheritance child, a nullable column,bigintagainstinteger, a unique index withtext_pattern_ops, a key under a nondeterministic ICU collation) and the fingerprint check after a key is dropped. Without the collation condition, the collation test returnslabel/abcfor a row whose parent isABC. The case passes theDifferential / ontopCI job. No bench query has a join the rule removes; on the bench queries, query time is unchanged (within ±3%, PR #193).References
배경
참조 객체 맵(R2RML §8)은 조인 조건으로 부모 논리 테이블을 조인하고, 쿼리가 참조 키로 만드는 부모 subject만 필요해도 펼친 SQL은 부모 테이블을 스캔한다.
?o ex:placedBy ?c는orders t0 JOIN customers t1 ON t1.id = t0.customer_id다. 참조되는 테이블의 클래스와 템플릿으로 조인하는 경우(?o ex:buyer ?c . ?c a ex:Customer)도 같은 조인이 된다. #112는 외래 키 때문에 불필요한 이런 스캔을 없애도록 요청한다. Discussion #84는 키가 한 행으로 고정하는 같은 테이블의 두 스캔을 합친다. 이 규칙은 다른 테이블의 스캔을 없애고 그 컬럼을 참조하는 행에서 읽으므로 조건이 다르다.결정
어떤 외래 키
카탈로그 스냅샷(Discussion #187)에서 테이블
C가P를 참조하는 외래 키는 다음을 모두 만족할 때 쓴다.convalidated).NOT VALID로 추가한 키는 이미 있던 행에는 성립하지 않는다.C가 분할 테이블이 아니면 상속 자식 테이블이 없음.C의 스캔은 자식의 행도 읽는데, 자식은 키를 상속하지 않는다.NOT NULL. PostgreSQL은 키 컬럼이 모두NULL이 아닌 행만 검사하고(MATCH SIMPLE), 조인은NULL이 있는 행을 버린다.=로 행을 식별하는P의 유일 키(모든 컬럼NOT NULL, 컬럼 자신의 collation과 타입의 기본 연산자 클래스, 캐스트나 항 키 없이=로 비교하는 타입)이고, 정확히 그 컬럼들에 걸린 유일 키가 모두 그러함. 외래 키는 그중 하나의 동등성으로 비교하는데 카탈로그는 어느 것인지 알려 주지 않는다.ColumnType동일), 참조하는 컬럼과 참조되는 컬럼이 모두 결정적 collation으로 비교됨(pg_collation.collisdeterministic, PostgreSQL 12). 한 타입 안에서는=로 같은 값의 자연 어휘 형식이 같다(R2RML §10.2).int4와int8처럼 타입이 다르면 항을 만드는 SQL이 다를 수 있다. 비결정적 collation에서는=가 다른 문자열도 같다고 본다(대소문자를 무시하는 collation에서'abc'와'ABC'). R2RML §8의 조인은 그래도 두 행을 짝짓지만 부모의 항은 부모의 값으로 만들므로, 자식의 값으로 만들면 다른 IRI가 된다.rr:sqlQuery뷰의 컬럼은 키가 없어 해당하지 않는다.P가 키가 가리키는 논리 테이블임.rr:tableName을 저장된 이름으로 나눈 부분이regclass가 출력한 참조 테이블 이름의 부분과 같다.regclass는 검색 경로가 찾는 테이블의 스키마를 생략하므로, 스키마를 붙여 쓴 매핑은 인식하지 않는다.어떤 스캔
P의 스캔tP는C의 스캔tC와 함께 다음을 만족할 때 없앤다.OPTIONAL부분의 직속.tP.p = tC.c를 요구함.rr:joinCondition등식, 또는 템플릿 분해가 쓰는 두 일반 컬럼의 항 비교(기준 IRI 없음, 같은 데이터타입).FILTER,ORDER BY, 계산 값 어디에서도 참조되는 컬럼 외의tP컬럼을 읽지 않음.tP.p를 읽는 곳은 모두tC.c로 바꾸고,tP뒤 별칭과OPTIONAL부분의 테이블 범위를 하나씩 당기고,tP가 고정하던 컬럼(#41)은tC에서 고정하고, 그 범위의tC.c = tC.c등식과 중복 조건을 버린다. 이 단계는CatalogPlan::new에서 self-join 합치기 다음에 없앨 스캔이 없을 때까지 실행되므로, 합치기로 다른 컬럼을 읽게 된 부모 스캔은 남는다.결과가 같은 이유
tC의 모든 행은 키 컬럼이NULL이 아니므로 외래 키가p = c인P의 행을 보장하고, 유일 키 때문에 그 행은 하나뿐이다. 따라서 범위의 조건이 남기는 조합은 정확히tP에 그 행이 있는 조합이고,tP없는 조합과 하나씩 대응한다. 각 조합에서tP.p와tC.c는=로 같은 한 타입의 값이므로,tP.p로 만든 항, 비교, 정렬 키, 중복 판단은tC.c로 만들어도 같다.OPTIONAL부분이 맞지 않는 곳에서는 둘 다NULL이다. 버리는 등식은NOT NULL컬럼을 자기와 비교한다.계획이
P의 유일 키에 의존하므로P의 스냅샷 항목은 지문 확인 대상에 남고, 키 자체는C의 지문에 들어 있다. 키 삭제, 상속 자식 추가,NOT NULL삭제가 있으면 확인이 실패하고 쿼리는 조인을 포함해 다시 계획된다.없애지 않는 것
tC와 다른 범위의P스캔(예:OPTIONAL너머). 그 스캔이 부분이 맞는지를 정한다.P스캔(<customer/1> a ex:Customer). 키로 조인되지 않는다.NOT VALID키, 다른 컬럼 타입, 정확한 유일 인덱스가 없는 참조 키, 키와 다르게 컬럼을 짝짓는 조인, 다른 컬럼을 읽는 부모.한계
FILTER에서=가 같은 문자열만 같다고 보는 가정으로 텍스트를 SQL=로 비교하며, 비결정적 collation은 이 가정을 깬다. 엔진 전체의 문제이므로 #197에서 다룬다.결과
차등 케이스
tests/diff/0015-foreign-keys에 쿼리 22개가 있다(참조 객체 맵, 클래스로의 템플릿 조인, 텍스트 키, 키 순서대로와 순서를 바꾼 복합 키, 자기 참조, NULL 허용 참조, 다른 타입의 참조,OPTIONAL안과 너머,DISTINCT,ORDER BY와LIMIT,FILTER,UNION). CI 전에 케이스 데이터를 외래 키가 있는 스키마와 없는 스키마에 각각 적재하고 모든 쿼리를v12n query로 실행해 결과가 같음을 확인했다. PostgreSQL 테스트는 어떤 키가 해당하는지(NOT VALID키, 상속 자식, NULL 허용 컬럼,integer를 참조하는bigint,text_pattern_ops유일 인덱스, 비결정적 ICU collation의 키)와 키를 삭제한 뒤의 지문 확인을 다룬다. collation 조건을 빼면 collation 테스트가 부모가ABC인 행에label/abc를 반환한다. 이 케이스는 CI의Differential / ontop잡을 통과한다. 이 규칙이 없애는 조인이 있는 벤치 쿼리는 없고, 벤치 쿼리의 시간은 변하지 않았다(±3% 이내, PR #193).참고
All reactions