Repository navigation
Decision: order solutions by SPARQL rules, with a fixed order where SPARQL leaves it open #63
CharmingGroot
announced in
Announcements
Replies: 1 comment
Resolved: the order comes from the outermost queryThe "to review" item about relying on PostgreSQL to keep a subquery's order is resolved in PR #64 (second commit): SQL does not guarantee that order, so nothing relies on it any more.
해결: 순서는 가장 바깥 질의가 정한다PostgreSQL이 서브쿼리 순서를 유지한다는 데 기대던 검토 항목은 PR #64(두 번째 커밋)에서 해결했다. SQL은 그 순서를 보장하지 않으므로 이제 거기에 기대지 않는다.
|
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
ORDER BYputs solutions in an order that SPARQL 1.1 only partly defines (15.1 ORDER BY). It fixes the order between kinds of terms, lowest first: no value (an unbound variable, or an expression that is an error), blank nodes, IRIs, RDF literals. IRIs compare as simple literals, by code point. Two literals compare with the<operator where the operator mapping defines it (17.3 Operator Mapping): numbers by value with XPath type promotion, simple literals andxsd:stringby code point,xsd:boolean, andxsd:dateTime. Everything else is left open: "SPARQL does not define a total ordering of all possible RDF terms", for example a simple literal against a number or a language-tagged literal, or two literals of an unsupported datatype. Ties, where every comparator gives the same term, have no order either.The modifiers apply in a fixed order (18.2.5 Converting Solution Modifiers): OrderBy, Project, Distinct, then Slice for
OFFSETandLIMIT; Project and Distinct keep the order OrderBy gives (18.5, Definitions: Project, Distinct, Slice).In SQL the same comparator can read columns of different SQL types in different
UNIONbranches (Discussion #60), severalOPTIONALparts (Discussion #55), templates, constants and expressions, and PostgreSQL orders each type its own way: text by the database collation,NULLlast, NaN above every number.FILTERcomparisons already follow the operator mapping (Discussion #57).Decision
Sort keys
float8and exactly asnumeric(or as integers when only integers occur),bool,timestamp/timestamptz,date,time, text underCOLLATE "C"(IRIs, blank node labels, lexical forms), and the language tag. A row has values only in its rank's slots, so rows of one rank compare by those alone. Only the slots some value can use are rendered, and the rank only where it can differ between rows.DESCreverses every slot, so no value comes last.OPTIONALparts is the first part that matched (CASE WHEN part matched THEN ... END, the sort-key form of theCOALESCEDiscussion Decision: translate OPTIONAL to nested LEFT JOINs translated part by part #55 planned), no value where none did; a boolean expression is itsFILTERSQL, no value where it is an error;STR,LANGandDATATYPEas inFILTER.SELECTsorts by expressions over its tables. When a comparator reads one required column of one kind (numbers, booleans, dateTimes, dates), the rank is constant and the slot is the column itself:ORDER BY t0."price" DESC LIMIT $1uses an index onprice(measured on PostgreSQL 17 with 100,000 rows: Index Scan Backward, 0.02 ms). Anything else (several branches,DISTINCT, duplicates removed in a subquery) selects the slots as typed columns in every branch and sorts the subquery's rows:SELECT q.x FROM (... UNION ALL ...) q ORDER BY q."o1_rank", q."o1_text" COLLATE "C".Where SPARQL defines the order
float8first and exactly second keeps both: decimals that round to the same double still sort exactly, and a double and a decimal that are equal as doubles are equal, as XPath says.COLLATE "C"compares UTF-8 bytes, which is code point order; in a database whose encoding is not UTF-8 the query is rejected, as forFILTER.falsebeforetrue; dateTimes by instant, within one kind of time zone.Where SPARQL leaves the order open (this engine's choice)
dateandtimecolumns (chronological) and by lexical form otherwise.numericNaN and infinities, ill-typed decimals (Discussion Decision: encode FILTER errors as SQL NULL and compare by the SPARQL operator mapping #57), where PostgreSQL puts them. Equal numbers of different terms (1and1.0,10and1.0E1) in the order of the exact slot, whichDESCreverses.dateandtimestampcolumns are the plain literals"-infinity"and"infinity". With other strings in the comparator they sort among them by code point; otherwise they stay at the ends of the column's order, which is valid since their order against dates and dateTimes is open and"-infinity"comes before"infinity". This keeps atimestampcolumn sorting as it is.LIMIT and OFFSET
LIMIT $n::int8 OFFSET $m::int8), so they apply afterDISTINCTand projection, and to the wholeUNION. Values beyondint8are capped, which no result reaches.row limit + 1rows to tell a cut-off result; a queryLIMITat or below the row limit leaves at most that many rows, so it is never reported as truncated. A query with its ownLIMITorOFFSETis read as a subquery under the engine'sLIMIT, since oneSELECTtakes oneLIMIT.Rejected (UnsupportedFeature)
ORDER BYover a variable thatSELECT DISTINCTdoes not project: Distinct keeps one solution for several that the comparator can put at different places, which no single position represents.FILTER);realcolumns (their literal is the double of the shortest decimal form, Discussion Decision: encode FILTER errors as SQL NULL and compare by the SPARQL operator mapping #57); literals of one datatype that would sort in two different slots (adatecolumn and a text column withrr:datatype xsd:date); and, as inFILTER, other functions, arithmetic, and strings that SQL cannot compute (STRof adatecolumn).Differential comparison
ORDER BYover projected variables, each result must be in the order above where SPARQL defines it, checked by an independent comparator inv12n-difftest; ties and pairs that<does not order pass in any order. Comparators the results do not show (hidden variables, expressions) need the same sequence, so such cases avoid ties.LIMITorOFFSET, solutions only one engine returned must be unordered against those only the other returned (a slice cutting through a tie); withoutORDER BY, only their number is compared.To review
cast_to_text, the row-limitcount(*) OVER ()); this is relied on, not guaranteed by SQL.ORDER BYover a hidden variable underSELECT DISTINCTis rejected rather than ordered by the first occurrence.v12n explainhas no column types and shows every column sorted as a string.Results
Differential tests: a new case
tests/diff/0008-order(33 queries: integers with ties, decimals, doubles, booleans, dateTimes, strings, IRIs, unbound values first and last, several comparators, numbers across datatypes, mixed kinds of terms,OPTIONALandUNION, a variable of twoOPTIONALparts, hidden and expression comparators,LIMIT/OFFSETcutting ties, withDISTINCT, withoutORDER BY, beyond the result) matches Ontop in 30; 2 are the collation difference of #26 (Ontop orders strings by the database collation, en_US.utf8, so "époxy" and Hangul land elsewhere), and 1 is rejected by design (ORDER BYover a variableSELECT DISTINCTdoes not project).0001-mdr/ordered-findingsis no longer rejected and matches Ontop. All 258 queries pass: 233 match Ontop (up from 202 of 225), 12 known mismatches, 6 Ontop errors, 7 rejected. Database tests cover what Ontop cannot show: NaN and infinities, decimals one double cannot tell apart, infinite timestamps, the row limit against a queryLIMIT, and the index scan.References
배경
ORDER BY는 solution을 정렬하는데, SPARQL 1.1은 그 순서를 일부만 정한다(15.1 ORDER BY). term 종류 사이의 순서는 정해져 있다. 낮은 것부터 값 없음(unbound 변수, 또는 오류인 식), blank node, IRI, RDF 리터럴이다. IRI는 simple literal로서, 즉 code point로 비교한다. 두 리터럴은 operator mapping이<를 정의하는 경우 그것으로 비교한다(17.3 Operator Mapping). 숫자는 XPath 타입 승격을 거친 값으로, simple literal과xsd:string은 code point로,xsd:boolean,xsd:dateTime도 정의된다. 나머지는 열려 있다. "SPARQL은 가능한 모든 RDF term의 전순서를 정의하지 않는다." 예를 들어 simple literal과 숫자, 언어 태그 리터럴, 지원하지 않는 datatype의 두 리터럴이 그렇다. 모든 비교자가 같은 term을 내는 동점에도 순서가 없다.수정자는 정해진 순서로 적용된다(18.2.5 Converting Solution Modifiers). OrderBy, Project, Distinct, 그다음
OFFSET과LIMIT의 Slice다. Project와 Distinct는 OrderBy가 정한 순서를 유지한다(18.5의 Project, Distinct, Slice 정의).SQL에서는 같은 비교자가
UNION가지마다 SQL 타입이 다른 컬럼(Discussion #60), 여러OPTIONAL부분(Discussion #55), 템플릿, 상수, 식을 읽을 수 있고, PostgreSQL은 타입마다 제 방식으로 정렬한다. text는 DB collation으로,NULL은 마지막에, NaN은 모든 숫자 위에 둔다.FILTER비교는 이미 operator mapping을 따른다(Discussion #57).결정
정렬 키
float8로 한 값과numeric으로 정확히 한 값(정수만 있으면 정수 그대로),bool,timestamp/timestamptz,date,time,COLLATE "C"인 text(IRI, blank node 라벨, lexical form), 언어 태그. 행은 자기 rank의 슬롯에만 값을 가지므로 같은 rank의 행은 그 슬롯들로만 비교된다. 어떤 값이 쓸 수 있는 슬롯만 만들고, rank는 행마다 다를 수 있을 때만 만든다.DESC는 모든 슬롯을 뒤집으므로 값 없음이 마지막이 된다.OPTIONAL부분이 바인딩하는 변수는 처음 일치한 부분의 term(CASE WHEN 부분 일치 THEN ... END, Discussion #55가 계획한COALESCE의 정렬 키 형태)이고 아무 부분도 일치하지 않으면 값 없음이다. boolean 식은 그FILTERSQL이고 오류면 값 없음이다.STR,LANG,DATATYPE은FILTER와 같다.SELECT하나는 테이블 위의 식으로 정렬한다. 비교자가 한 종류(숫자, boolean, dateTime, date)의 필수 컬럼 하나를 읽으면 rank는 상수이고 슬롯은 컬럼 자체다.ORDER BY t0."price" DESC LIMIT $1은price의 인덱스를 쓴다(PostgreSQL 17, 10만 행에서 측정: Index Scan Backward, 0.02ms). 그 밖의 경우(가지 여럿,DISTINCT, 서브쿼리에서 중복 제거)에는 모든 가지가 슬롯을 타입이 있는 컬럼으로 고르고 서브쿼리의 행을 정렬한다:SELECT q.x FROM (... UNION ALL ...) q ORDER BY q."o1_rank", q."o1_text" COLLATE "C".SPARQL이 순서를 정한 경우
float8먼저, 정확한 값을 다음에 정렬하면 둘 다 지켜진다. 같은 double로 반올림되는 decimal도 정확히 정렬되고, double로 같은 double과 decimal은 XPath대로 같다.COLLATE "C"는 UTF-8 바이트를 비교하고 이는 code point 순서다. 인코딩이 UTF-8이 아닌 DB에서는FILTER처럼 거절한다.false가true앞, dateTime은 시점 순(한 종류의 시간대 안에서).SPARQL이 순서를 열어 둔 경우(이 엔진의 선택)
date·time컬럼은 컬럼 자체 순서(시간 순), 그 밖에는 lexical form 순.numeric의 NaN과 무한대(ill-typed decimal, Discussion Decision: encode FILTER errors as SQL NULL and compare by the SPARQL operator mapping #57)는 PostgreSQL이 두는 자리. term이 다른 같은 수(1과1.0,10과1.0E1)는 정확한 값 슬롯의 순서이고DESC가 뒤집는다.date,timestamp컬럼의 무한값은 plain literal"-infinity","infinity"다. 비교자에 다른 문자열이 있으면 그 사이에서 code point로 정렬하고, 없으면 컬럼 순서의 양 끝에 둔다. date·dateTime과의 순서는 열려 있고"-infinity"가"infinity"앞이므로 올바르다. 그래서timestamp컬럼은 그대로 정렬된다.LIMIT과 OFFSET
LIMIT $n::int8 OFFSET $m::int8). 그래서DISTINCT와 투영 뒤에,UNION전체에 적용된다.int8을 넘는 값은 상한으로 줄인다(어떤 결과도 그만큼 크지 않다).행 상한 + 1행을 읽어 잘린 결과를 가린다. 질의의LIMIT이 행 상한 이하이면 결과가 그 이하이므로 잘림으로 보고하지 않는다. 자체LIMIT이나OFFSET이 있는 질의는 엔진의LIMIT아래 서브쿼리로 읽는다(SELECT하나에는LIMIT이 하나뿐).거절(UnsupportedFeature)
SELECT DISTINCT가 투영하지 않는 변수에 대한ORDER BY: Distinct는 비교자가 서로 다른 자리에 둘 수 있는 여러 solution을 하나로 남기므로, 그 하나가 설 자리가 없다.FILTER와 같이 암묵적 시간대 문제),real컬럼(리터럴이 가장 짧은 십진 표기의 double이라서, Discussion Decision: encode FILTER errors as SQL NULL and compare by the SPARQL operator mapping #57), 같은 datatype의 리터럴이 서로 다른 슬롯에서 정렬되는 경우(date컬럼과rr:datatype xsd:date인 text 컬럼), 그리고FILTER와 같이 다른 함수, 산술, SQL이 계산할 수 없는 문자열(date컬럼의STR).차등 비교
ORDER BY면, 각 결과가 SPARQL이 정한 곳에서는 위 순서여야 하고 이를v12n-difftest의 독립 비교자로 확인한다. 동점과<가 정하지 않는 쌍은 어떤 순서든 통과한다. 결과에 보이지 않는 비교자(숨은 변수, 식)는 같은 순서열이어야 하므로 그런 케이스는 동점을 피한다.LIMIT이나OFFSET이 있으면 한 엔진만 돌려준 solution은 다른 엔진만 돌려준 solution과 순서가 없어야 한다(slice가 동점을 자른 경우).ORDER BY가 없으면 개수만 비교한다.검토 요청
cast_to_text, 행 상한의count(*) OVER ()) PostgreSQL이 서브쿼리 순서를 유지한다는 데 기댄다. SQL이 보장하지는 않는다.SELECT DISTINCT에서 숨은 변수로 정렬하는 것은 첫 출현 순서로 정하지 않고 거절한다.v12n explain은 컬럼 타입을 모르므로 모든 컬럼을 문자열로 정렬하는 SQL을 보여준다.결과
차등 테스트: 새 케이스
tests/diff/0008-order(질의 33개: 동점이 있는 정수, decimal, double, boolean, dateTime, 문자열, IRI, 앞·뒤의 unbound, 비교자 여러 개, datatype이 섞인 숫자, 종류가 섞인 term,OPTIONAL과UNION,OPTIONAL부분 둘이 바인딩하는 변수, 숨은 비교자와 식 비교자, 동점을 자르는LIMIT/OFFSET,DISTINCT와 함께,ORDER BY없이, 결과보다 큰 값)는 30개가 Ontop과 같고, 2개는 #26의 collation 차이(Ontop은 DB collation en_US.utf8로 문자열을 정렬해 "époxy"와 한글이 다른 자리에 옴), 1개는 의도된 거절(SELECT DISTINCT가 투영하지 않는 변수에 대한ORDER BY)이다.0001-mdr/ordered-findings는 더 이상 거절되지 않고 Ontop과 같다. 전체 258개 질의가 통과한다. Ontop과 일치 233(이전 225개 중 202), 알려진 차이 12, Ontop 오류 6, 거절 7. Ontop이 보여줄 수 없는 경우(NaN과 무한대, double 하나로는 구별되지 않는 decimal, 무한 timestamp, 질의LIMIT과 행 상한, 인덱스 스캔)는 DB 테스트로 확인한다.참고
All reactions