Repository navigation
Decision: translate OPTIONAL to nested LEFT JOINs translated part by part #55
CharmingGroot
announced in
Announcements
Replies: 0 comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Background
OPTIONALis the SPARQL algebra's LeftJoin: every solution of the left side is kept, extended by each compatible solution of the right side where there are some (SPARQL 1.1 Query, 18.5 SPARQL Algebra, Definition: LeftJoin; 18.6 Evaluation Semantics). Compatible means that every variable bound on both sides has the same term (18.3 Basic Graph Patterns, Definition: Compatible Mappings), so a variable unbound on one side matches anything. AFILTERinsideOPTIONALbecomes the LeftJoin's expression (18.2.2.6 Translate Graph Patterns), not a filter over the result.Until #49 the engine unfolded one basic graph pattern into UNION branches of inner joins, with one term per variable. Three things do not fit that shape: the right side of a LeftJoin does not distribute over a union, a variable can be unbound in some rows, and a variable can be bound by more than one part of the pattern.
Decision
sparql::parsekeepsBgp,JoinandLeftJoin(joins of basic graph patterns are still merged). Only the required triple patterns, those outside every LeftJoin's right side, choose the UNION branches, since Join and LeftJoin distribute over a union on their left side.LEFT JOINperOPTIONALpart, inside its branch. The part's tables are joined among themselves (in parentheses when there are several) and theONclause holds the part's own conditions and its link to the left side. NestedOPTIONALis a nestedLEFT JOIN; patterns written after anOPTIONAL(Join(LeftJoin(A, B), C)) are joined after it. Table aliases stay flat (t0,t1, ...), so term comparison, template decomposition, typed columns (Generate UNION SQL that works when a variable spans columns of different types #24), column-name resolution and key-based deduplication (Decision: count each triple once, keep bag semantics for solutions #41) work unchanged across the left join. Every condition belongs to a scope (the branch or one part):NOT NULLchecks of a part go to itsON, and a constant that cannot match fails only its part (RenderedSql::param_required).NULL; compatibility with a possibly unbound side is(side IS NULL OR equal). This happens only when a shared variable is bound by an earlierOPTIONALor by one nested in the part (non-well-designed patterns). Such conditions cannot use an index on the column; well-designed patterns keep plain equalities.OPTIONALparts keeps one source per part, selected as separate columns, and its value is the first bound one in the row (ProjectedTerm::terms). Bound sources of one row are the same term, so this isCOALESCEdone while building terms, which avoids resolving SQL types or term shapes across columns. Sources nested in a part that already binds the variable are dropped. A constant term of anOPTIONALpart comes with a flag column (CASE WHEN col IS NOT NULL THEN true END).NULLfor its columns, typed after the other branches bywith_union_types.FILTERinsideOPTIONAL(Support FILTER expressions with SPARQL error semantics #50); anOPTIONALpart that more than one combination of triples maps can match, which needs aUNIONinside theLEFT JOIN(belongs with Support UNION in queries #51);SELECT DISTINCTover a variable that only severalOPTIONALparts bind, since the same term then sits in different columns.What later steps build on
FILTERinsideOPTIONALbecomes one more condition of the part'sLeftJoin::conditions, rendered in itsON. Expressions over a variable with several sources (andBOUND) have to consider each source, e.g.CASEover them.LEFT JOIN. "Bound in one branch, unbound in the other" is already representable (SqlExpr::Unbound, typed inwith_union_types).COALESCEof their sort keys); unbound sorts first.Results
Differential tests: a new case
tests/diff/0005-optional(17 queries: match and no match, shared variables, nested and sequentialOPTIONAL, patterns afterOPTIONAL, variables unbound on the left,OPTIONALover a class from several triples maps, duplicates on the optional side, constants,DISTINCT, an empty left side, an unmatchable constant) matches Ontop in all 16 supported queries;0001-mdr/optional-criticalityis no longer rejected. All 145 queries pass (122 match Ontop, 10 known mismatches, 7 Ontop errors, 6 rejected), up from 128 (105 matching).References
배경
OPTIONAL은 SPARQL algebra의 LeftJoin이다. 왼쪽의 해는 모두 남고, 오른쪽에 호환되는 해가 있으면 그 해마다 확장된다(SPARQL 1.1 Query, 18.5 SPARQL Algebra의 Definition: LeftJoin, 18.6 Evaluation Semantics). 호환은 양쪽에 모두 바인딩된 변수의 term이 같다는 뜻이다(18.3 Basic Graph Patterns의 Definition: Compatible Mappings). 그래서 한쪽에서 unbound인 변수는 어떤 값과도 호환된다.OPTIONAL안의FILTER는 결과 전체를 거르는 조건이 아니라 LeftJoin의 식이 된다(18.2.2.6 Translate Graph Patterns).#49 전까지 엔진은 basic graph pattern 하나를 inner join으로 된 UNION 가지로 펼쳤고, 변수마다 term이 하나였다. 이 구조에 맞지 않는 점이 셋 있다. LeftJoin의 오른쪽은 union에 대해 분배되지 않고, 변수가 어떤 행에서는 unbound일 수 있고, 한 변수를 패턴의 여러 부분이 바인딩할 수 있다.
결정
sparql::parse가Bgp,Join,LeftJoin을 유지한다(basic graph pattern끼리의 join은 지금처럼 합친다). UNION 가지는 필수 triple pattern, 즉 어떤 LeftJoin의 오른쪽에도 속하지 않은 패턴만으로 고른다. Join과 LeftJoin은 왼쪽의 union에 대해 분배되기 때문이다.OPTIONAL부분마다 가지 안에LEFT JOIN하나. 부분의 테이블끼리 먼저 조인하고(여러 개면 괄호로 묶음),ON에는 부분 자체의 조건과 왼쪽과의 연결 조건을 둔다. 중첩OPTIONAL은 중첩LEFT JOIN이 되고,OPTIONAL뒤에 쓴 패턴(Join(LeftJoin(A, B), C))은 그 뒤에 조인한다. 테이블 별칭은 평평하게 유지되므로(t0,t1, ...) term 비교, 템플릿 분해, 타입별 컬럼(Generate UNION SQL that works when a variable spans columns of different types #24), 컬럼 이름 해석, 키 기반 중복 제거(Decision: count each triple once, keep bag semantics for solutions #41)가 left join을 넘어서도 그대로 동작한다. 모든 조건은 scope(가지 전체 또는 부분 하나)에 속한다. 부분의NOT NULL검사는 그 부분의ON에 들어가고, 일치할 수 없는 상수는 가지 전체가 아니라 그 부분만 실패시킨다(RenderedSql::param_required).NULL이고, unbound일 수 있는 쪽과의 호환은(그쪽 IS NULL OR 같음)이다. 공유 변수를 앞선OPTIONAL이나 부분 안에 중첩된OPTIONAL만 바인딩할 때(well-designed가 아닌 패턴)에만 생긴다. 이 조건은 컬럼의 인덱스를 쓰지 못한다. well-designed 패턴은 단순 등호를 유지한다.OPTIONAL부분만 바인딩하는 변수는 부분마다 출처를 하나씩 두고 각각 별도 컬럼으로 고르며, 값은 그 행에서 처음 바인딩된 출처다(ProjectedTerm::terms). 한 행에서 바인딩된 출처들은 같은 term이므로 term을 만들 때 하는COALESCE와 같고, 컬럼 사이의 SQL 타입이나 term 모양을 맞출 필요가 없다. 이미 그 변수를 바인딩하는 부분 안에 중첩된 출처는 버린다.OPTIONAL부분의 상수 term에는 플래그 컬럼(CASE WHEN col IS NOT NULL THEN true END)을 붙인다.NULL을 고르고, 타입은with_union_types가 다른 가지에 맞춘다.OPTIONAL안의FILTER(Support FILTER expressions with SPARQL error semantics #50), triples map 조합 여러 개가 일치할 수 있는OPTIONAL부분(LEFT JOIN안에UNION이 필요하므로 #51에서 다룸), 여러OPTIONAL부분만 바인딩하는 변수에 대한SELECT DISTINCT(같은 term이 서로 다른 컬럼에 있게 되므로).다음 단계가 기대는 부분
OPTIONAL안의FILTER는 부분의LeftJoin::conditions에 조건 하나로 더해져ON에 렌더링된다. 출처가 여럿인 변수에 대한 식(과BOUND)은 출처를 모두 고려해야 한다(예: 출처들에 대한CASE).LEFT JOIN안에 파생 relation이 필요하다. "한 가지에서는 바인딩, 다른 가지에서는 unbound"는 이미 표현할 수 있다(SqlExpr::Unbound,with_union_types에서 타입 지정).COALESCE). unbound가 가장 앞이다.결과
차등 테스트: 새 케이스
tests/diff/0005-optional(질의 17개: 일치·불일치, 공유 변수, 중첩·연속OPTIONAL,OPTIONAL뒤의 패턴, 왼쪽에서 unbound인 변수, 여러 triples map에서 오는 클래스 위의OPTIONAL, optional 쪽의 중복, 상수,DISTINCT, 빈 왼쪽, 일치할 수 없는 상수)에서 지원하는 질의 16개 모두 Ontop과 결과가 같다.0001-mdr/optional-criticality는 더 이상 거절되지 않는다. 전체 145개 질의가 통과한다(Ontop과 일치 122, 알려진 차이 10, Ontop 오류 7, 거절 6). 이전에는 128개 중 105개가 일치했다.참고
All reactions