Repository navigation
Decision: encode FILTER errors as SQL NULL and compare by the SPARQL operator mapping #57
CharmingGroot
announced in
Announcements
Replies: 1 comment
Addendum: STR, LANG, DATATYPE and REGEX (PR #58)
추가: STR, LANG, DATATYPE, REGEX (PR #58)
|
0 replies
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
FILTERkeeps a solution only where its expression's effective boolean value is true, and the expression can also be an error: an unbound variable, or operands the operator mapping has no row for, such as a number and a string. An error is not false.error || trueis true,error && falseis false, and!erroris an error (SPARQL 1.1 §17.2, Filter Evaluation), soFILTER(!(?x = 5))must drop a row where?xis unbound or a string. A translation that renders a type error as SQLfalsegives wrong answers as soon as a negation is involved.The comparisons themselves depend on the datatypes of the operands (SPARQL 1.1 §17.3, Operator Mapping): numbers by value with XPath type promotion, simple literals and
xsd:stringby code point,xsd:boolean,xsd:dateTimeby instant, and RDFterm-equal for everything else. Here a column withoutrr:datatypegets its datatype from its SQL type (R2RML §10.2), which only the database knows, and Discussion #21 planned how a constant meets a column of another type. Where the filter sits also matters (§18.2.2.6, Translate Graph Patterns): a group's filters apply to the whole group and see only its variables, and a filter insideOPTIONALbecomes the LeftJoin's expression, evaluated over both sides (Discussion #55 leftLeftJoin::conditionsfor it).Decision
Errors are SQL
NULLNULLfor an error. SQL'sAND,ORandNOTtreatNULLexactly as SPARQL's&&,||and!treat an error (the truth table in §17.2 is Kleene's three-valued logic), andWHEREandONkeep a row only where the condition is true. So the logical operators map one to one, and every leaf that can be an error renders asNULL, neverfalse: a type error isNULL::bool.BOUND. An unbound variable is SQLNULL. A variable that onlyOPTIONALparts bind is read throughCASE WHEN <part matched> THEN <comparison> ... END, whose missingELSEisNULL; with several parts, the first that matched gives the value (bound sources of one row are the same term, Discussion Decision: translate OPTIONAL to nested LEFT JOINs translated part by part #55).BOUNDiscol IS NOT NULL(orORover the parts), neverNULL. A variable not bound by the filter's group at all makes the comparisonNULL::boolat planning time.WHEREorON, and underAND/ORthere, false and error both drop the row, so a leaf may render either way; underNOTit may not. Constants compared as RDF terms are checked by the round trip of Discussion Decision: compare query constants as RDF terms and check them before binding #21 and bound toNULLwhen no value can match them; that isfalsefor the term comparison, so underNOTsuch a comparison is wrapped incoalesce(..., false). Outside negation the plaincol = $1stays, so the index is used.param_required: binding one toNULLfails its comparison, not the branch.Scope
sparql::parsekeepsFilter(expr, P)for a group's filters andLeftJoin(L, R, expr)for a filter insideOPTIONAL. A group filter goes into the conditions of the scope it was evaluated in, compiled against the variables of that group only, so{ ?s ex:name ?n { ?s ex:qty ?q FILTER(?n = "x") } }is an error for every row, as the algebra says.OPTIONALis compiled against the merged variables of both sides and goes into that part'sONclause. A nested part does not see the outer left side (each part is translated on its own, Discussion Decision: translate OPTIONAL to nested LEFT JOINs translated part by part #55).ONmeans "does not match". Read literally, Diff (§18.5) keeps a left solution only where the expression is false for every compatible right solution, so an error would drop it from both Filter and Diff. SQL'sLEFT JOINkeeps the left row withNULLs where theONis not true, which is also what Ontop (through SQL), Jena and RDF4J do. To review: this follows the common reading, not the literal one.Comparisons
xsd:string=as RDF terms (col = $1), ordering withCOLLATE "C".xsd:booleanfalse < true, as in PostgreSQL.xsd:dateTimetimestampwith constants without a time zone,timestamptzwith zoned constants normalized to UTC.=is RDFterm-equal: the same term is true, a literal and an IRI are false, two different literals are an error;<and the others are errors.?qty > 5isqty > $1::int8and?qty = 7.0isqty = $1::int8on anint4column (cross-type integer operators keep the index), and anumericcolumn compares with$1::numeric. Deviation from Discussion Decision: compare query constants as RDF terms and check them before binding #21: its plan was "convert the constant when exactly representable, otherwise false". That holds for=with integers and decimals, but not with doubles: XPath comparesnumeric 0.1 = 0.1e0after promoting the decimal to a double (true), while the exact double 0.1000000000000000055… is not representable as the decimal 0.1 (false). It also has no answer for<. So a fraction against an integer column compares ascol::numeric < $1::numeric, and any double constant ascol::float8 op $1::float8, both exact and both without the index on the column.NaN = NaNand orders it last: afloat8column is compared withAND col <> 'NaN'::float8, a NaN constant makes the comparisonfalse, and-0 = 0holds in both. AnumericNaN or ±Infinity has noxsd:decimallexical form, so its literal is ill-typed: comparing it is an error (CASE WHEN col::text NOT IN ('NaN', 'Infinity', '-Infinity') THEN ... END), two equal ones are the same term, and its effective boolean value is false.date/timestampvalues ±infinity are plain literals in results, so dateTime comparisons checkisfinite(col).fn:comparewith the codepoint collation is byte order underCOLLATE "C"only in UTF-8; the adapter readsserver_encodingwhen it connects and rejects string ordering in other encodings. Ontop orders by the database collation instead ("écrou" > "z"is true here, false there), recorded as a known mismatch under Record Ontop's value matching for uuid and errors on ill-typed dates #26.xsd:date,xsd:hexBinary, custom datatypes) and two language-tagged literals:<and the others are rejected;=on language-tagged literals is accepted outside negation, where the specification's error and an extension'sfalseboth drop the row, and rejected under it. Literals of different datatypes (?n = 5on a string) are a plain type error.realcolumns (their literal is the double of the shortest decimal form, not the value widened), columns with anrr:datatypethat is a numeric, boolean or dateTime datatype other than their natural one (SQL would have to parse their lexical forms),xsd:floatand the derived integer types as constants, dateTime constants outside years 1-9999 or finer than a microsecond,sameTermoverreal/double precisioncolumns (PostgreSQL's-0 = 0makescol = $1wrong for terms), and strings containing NUL.<> 0and not NaN, strings and language-tagged literals non-empty, ill-typed numerics and booleans false, everything else an error.isIRI,isBlankandisLiteralare decided by the term map's term type.Not in this step
STR,LANG,DATATYPEandREGEX(with the XPath-to-PostgreSQL regular expression mapping) follow in a second pull request for #50.IN, arithmetic and the other functions stay rejected.Results
Differential tests: a new case
tests/diff/0006-filter(37 queries overint4,int8,numeric,float8,text,bool,timestamp,timestamptz,date, language-tagged and IRI terms, with unbound variables, filters inside, after and nested inOPTIONAL, and a nested group) matches Ontop in 33, 1 is the collation mismatch above (#26), and 3 are rejected by design.0001-mdr/filter-severityis no longer rejected and matches Ontop. All 182 queries pass (158 match Ontop, 10 known mismatches, 6 Ontop errors, 8 rejected), up from 145 (124 matching). Cases Ontop cannot show (NaN, infinities, uuid constants that cannot match, rejected types) are database tests inv12n-postgres.References
배경
FILTER는 식의 effective boolean value가 true인 solution만 남기고, 식은 오류가 될 수도 있다. unbound 변수나, 숫자와 문자열처럼 operator mapping에 행이 없는 피연산자가 그렇다. 오류는 false가 아니다.error || true는 true,error && false는 false,!error는 오류다(SPARQL 1.1 §17.2, Filter Evaluation). 그래서FILTER(!(?x = 5))는?x가 unbound이거나 문자열인 행을 버려야 한다. 타입 오류를 SQLfalse로 옮기면 부정이 들어가는 순간 틀린 답이 나온다.비교 자체도 피연산자의 datatype에 달려 있다(SPARQL 1.1 §17.3, Operator Mapping). 숫자는 XPath 타입 승격을 따르는 값 비교, simple literal과
xsd:string은 코드 포인트 비교,xsd:boolean,xsd:dateTime은 시각 비교, 나머지는 RDFterm-equal이다. 여기서rr:datatype이 없는 컬럼의 datatype은 SQL 타입에서 오고(R2RML §10.2) 그것은 데이터베이스만 알며, 상수가 다른 타입의 컬럼과 만나는 방법은 Discussion #21에서 계획했다. 필터가 놓인 자리도 중요하다(§18.2.2.6, Translate Graph Patterns). 그룹의 필터는 그룹 전체에 적용되고 그 그룹의 변수만 보며,OPTIONAL안의 필터는 LeftJoin의 식이 되어 양쪽을 합친 solution에서 평가된다(Discussion #55가 이를 위해LeftJoin::conditions를 남겨 두었다).결정
오류는 SQL
NULLNULL로 나타내는 nullable SQL boolean이다. SQL의AND,OR,NOT은 SPARQL의&&,||,!가 오류를 다루는 것과 똑같이NULL을 다루고(§17.2의 진리표는 Kleene 3치 논리다),WHERE와ON은 조건이 true인 행만 남긴다. 그래서 논리 연산자는 그대로 옮기고, 오류가 될 수 있는 모든 말단은false가 아니라NULL로 렌더링한다. 타입 오류는NULL::bool이다.BOUND를 빼면 오류다. unbound 변수는 SQLNULL이다.OPTIONAL부분만 바인딩하는 변수는CASE WHEN <부분 일치> THEN <비교> ... END로 읽고,ELSE가 없으니NULL이다. 부분이 여럿이면 먼저 일치한 부분이 값을 준다(한 행에서 바인딩된 출처는 같은 term, Discussion Decision: translate OPTIONAL to nested LEFT JOINs translated part by part #55).BOUND는col IS NOT NULL(부분이 여럿이면OR)이고NULL이 되지 않는다. 필터의 그룹이 전혀 바인딩하지 않는 변수는 계획 단계에서 비교가NULL::bool이 된다.WHERE나ON바로 아래, 그리고 그 아래의AND/OR안에서는 false와 오류 모두 행을 버리므로 말단을 어느 쪽으로 렌더링해도 된다.NOT아래에서는 안 된다. RDF term으로 비교하는 상수는 Discussion #21의 왕복 검사를 거치고, 어떤 값과도 일치할 수 없으면NULL로 바인딩된다. term 비교로는false이므로NOT아래에서는 그 비교를coalesce(..., false)로 감싼다. 부정 밖에서는col = $1을 그대로 두어 인덱스를 쓴다.param_required가 아니다.NULL로 바인딩되면 그 비교만 실패하고 가지는 남는다.범위
sparql::parse는 그룹의 필터를Filter(expr, P)로,OPTIONAL안의 필터를LeftJoin(L, R, expr)로 남긴다. 그룹 필터는 그것이 평가되는 scope의 조건으로 들어가고 그 그룹의 변수로만 컴파일되므로,{ ?s ex:name ?n { ?s ex:qty ?q FILTER(?n = "x") } }는 algebra가 말하는 대로 모든 행에서 오류다.OPTIONAL안의 필터는 양쪽을 합친 변수로 컴파일되어 그 부분의ON절에 들어간다. 중첩 부분은 바깥 왼쪽을 보지 않는다(부분마다 따로 번역, Discussion Decision: translate OPTIONAL to nested LEFT JOINs translated part by part #55).ON안의 오류는 "일치하지 않음"이다. 글자 그대로 읽으면 Diff(§18.5)는 호환되는 모든 오른쪽 solution에서 식이 false일 때만 왼쪽 solution을 남기므로, 오류면 Filter와 Diff 양쪽에서 빠진다. SQLLEFT JOIN은ON이 true가 아니면 왼쪽 행을NULL과 함께 남기고, Ontop(SQL을 거침), Jena, RDF4J도 그렇게 한다. 검토 필요: 글자 그대로의 해석이 아니라 일반적인 해석을 따랐다.비교
xsd:string=는 RDF term 비교(col = $1), 순서는COLLATE "C".xsd:booleanfalse < true.xsd:dateTimetimestamp, 시간대 있는 상수는 UTC로 정규화해timestamptz.=는 RDFterm-equal: 같은 term이면 true, literal과 IRI는 false, 서로 다른 두 literal은 오류.<등은 오류.int4컬럼에서?qty > 5는qty > $1::int8,?qty = 7.0은qty = $1::int8(정수 타입 간 연산자로 인덱스 유지)이고,numeric컬럼은$1::numeric과 비교한다. Discussion #21과 다른 점: 그 계획은 "정확히 표현되면 상수를 바꾸고 아니면 false"였다. integer와 decimal의=에서는 맞지만 double에서는 아니다. XPath는numeric 0.1 = 0.1e0을 decimal을 double로 승격해서 비교하고(true), 정확한 double 값 0.1000000000000000055…는 decimal 0.1로 표현되지 않는다(false).<에는 답이 없기도 하다. 그래서 정수 컬럼과 소수는col::numeric < $1::numeric, double 상수는col::float8 op $1::float8로 비교한다. 둘 다 정확하지만 컬럼 인덱스는 못 쓴다.NaN = NaN이고 NaN을 맨 뒤에 둔다. 그래서float8컬럼은AND col <> 'NaN'::float8과 함께 비교하고, NaN 상수는 비교를false로 만들며,-0 = 0은 양쪽에서 성립한다.numericNaN과 ±Infinity는xsd:decimallexical form이 없어 그 literal은 ill-typed다. 비교하면 오류(CASE WHEN col::text NOT IN ('NaN', 'Infinity', '-Infinity') THEN ... END), 같은 값 둘은 같은 term, effective boolean value는 false다.date/timestamp의 ±infinity는 결과에서 plain literal이므로 dateTime 비교는isfinite(col)을 확인한다.fn:compare는 UTF-8에서만COLLATE "C"의 바이트 순서와 같다. 어댑터는 연결할 때server_encoding을 읽고 다른 인코딩에서는 문자열 순서 비교를 거절한다. Ontop은 데이터베이스 collation으로 정렬한다(여기서는"écrou" > "z"가 true, Ontop에서는 false). #26에 알려진 불일치로 기록했다.xsd:date,xsd:hexBinary, 사용자 datatype)과 언어 태그가 있는 두 literal은<등을 거절한다. 언어 태그 literal의=는 명세의 오류와 확장의false가 모두 행을 버리는 부정 밖에서는 받고, 부정 아래에서는 거절한다. datatype이 다른 literal(문자열에?n = 5)은 그냥 타입 오류다.real컬럼 비교(literal은 값을 넓힌 double이 아니라 최단 소수 표기의 double), natural datatype과 다른 numeric·boolean·dateTimerr:datatype이 붙은 컬럼(SQL이 lexical form을 읽어야 함),xsd:float와 파생 정수 타입 상수, 1~9999년 밖이나 마이크로초보다 잘게 나뉜 dateTime 상수,real/double precision컬럼의sameTerm(PostgreSQL의-0 = 0때문에col = $1이 term 비교로 틀림), NUL이 든 문자열.<> 0이고 NaN이 아님, 문자열과 언어 태그 literal은 비어 있지 않음, ill-typed 숫자와 boolean은 false, 나머지는 오류.isIRI,isBlank,isLiteral은 term map의 term type으로 정한다.이번 단계에 없는 것
STR,LANG,DATATYPE,REGEX(XPath 정규식을 PostgreSQL 정규식으로 옮기는 규칙 포함)는 #50의 두 번째 PR에서 다룬다.IN, 산술, 다른 함수는 계속 거절한다.결과
차등 테스트: 새 케이스
tests/diff/0006-filter(int4,int8,numeric,float8,text,bool,timestamp,timestamptz,date, 언어 태그와 IRI term에 걸친 37개 질의. unbound 변수,OPTIONAL안·뒤·중첩 필터, 중첩 그룹 포함)는 33개가 Ontop과 같고, 1개는 위 collation 불일치(#26), 3개는 설계상 거절이다.0001-mdr/filter-severity는 더 이상 거절되지 않고 Ontop과 같다. 전체 182개 통과(Ontop 일치 158, 알려진 불일치 10, Ontop 오류 6, 거절 8). 이전 145개(일치 124)에서 늘었다. Ontop으로 보일 수 없는 경우(NaN, infinity, 일치할 수 없는 uuid 상수, 거절되는 타입)는v12n-postgres의 데이터베이스 테스트로 확인한다.참고
All reactions