tracker-sparql-expression.vala 50 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
/*
 * Copyright (C) 2008-2010, Nokia
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the
 * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA  02110-1301, USA.
 */

class Tracker.Sparql.Expression : Object {
21
	weak Query query;
22

23
	const int MAX_VARIABLES_FOR_IN = 20;
24 25 26 27 28
	const string XSD_NS = "http://www.w3.org/2001/XMLSchema#";
	const string FN_NS = "http://www.w3.org/2005/xpath-functions#";
	const string FTS_NS = "http://www.tracker-project.org/ontologies/fts#";
	const string TRACKER_NS = "http://www.tracker-project.org/ontologies/tracker#";

29 30 31 32 33 34
	enum TimeFormatType {
		SECONDS,
		MINUTES,
		HOURS
	}

35 36
	string? fts_sql;

37 38 39 40 41 42 43 44 45 46 47 48
	public Expression (Query query) {
		this.query = query;
	}

	Context context {
		get { return query.context; }
	}

	Pattern pattern {
		get { return query.pattern; }
	}

49
	inline bool next () throws Sparql.Error {
50 51 52 53 54 55 56 57 58 59 60
		return query.next ();
	}

	inline SparqlTokenType current () {
		return query.current ();
	}

	inline SparqlTokenType last () {
		return query.last ();
	}

61
	inline bool accept (SparqlTokenType type) throws Sparql.Error {
62 63 64
		return query.accept (type);
	}

65
	Sparql.Error get_error (string msg) {
66 67 68
		return query.get_error (msg);
	}

69
	bool expect (SparqlTokenType type) throws Sparql.Error {
70 71 72 73 74 75 76 77 78 79 80 81
		return query.expect (type);
	}

	string get_last_string (int strip = 0) {
		return query.get_last_string (strip);
	}

	string escape_sql_string_literal (string literal) {
		return "'%s'".printf (string.joinv ("''", literal.split ("'")));
	}

	bool maybe_numeric (PropertyType type) {
82
		return (type == PropertyType.INTEGER || type == PropertyType.DOUBLE || type == PropertyType.DATE || type == PropertyType.DATETIME || type == PropertyType.UNKNOWN);
83 84
	}

85 86 87 88
	void append_collate (StringBuilder sql) {
		sql.append_printf (" COLLATE %s", COLLATION_NAME);
	}

89
	void skip_bracketted_expression () throws Sparql.Error {
90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
		expect (SparqlTokenType.OPEN_PARENS);
		while (true) {
			switch (current ()) {
			case SparqlTokenType.OPEN_PARENS:
				// skip nested bracketted expression
				skip_bracketted_expression ();
				continue;
			case SparqlTokenType.CLOSE_PARENS:
			case SparqlTokenType.EOF:
				break;
			default:
				next ();
				continue;
			}
			break;
		}
		expect (SparqlTokenType.CLOSE_PARENS);
	}

109
	internal void skip_select_variables () throws Sparql.Error {
110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131
		while (true) {
			switch (current ()) {
			case SparqlTokenType.OPEN_PARENS:
				skip_bracketted_expression ();
				continue;
			case SparqlTokenType.FROM:
			case SparqlTokenType.WHERE:
			case SparqlTokenType.OPEN_BRACE:
			case SparqlTokenType.GROUP:
			case SparqlTokenType.ORDER:
			case SparqlTokenType.LIMIT:
			case SparqlTokenType.OFFSET:
			case SparqlTokenType.EOF:
				break;
			default:
				next ();
				continue;
			}
			break;
		}
	}

132
	internal PropertyType translate_select_expression (StringBuilder sql, bool subquery, int variable_index) throws Sparql.Error {
133
		Variable variable = null;
134
		bool expect_close_parens = false;
135
		bool as_handled = false;
136 137 138

		long begin = sql.len;
		var type = PropertyType.UNKNOWN;
139
		if (current () == SparqlTokenType.VAR) {
140 141 142 143 144 145 146
			type = translate_expression (sql);
			// we need variable name in case of compositional subqueries
			variable = context.get_variable (get_last_string ().substring (1));

			if (variable.binding == null) {
				throw get_error ("use of undefined variable `%s'".printf (variable.name));
			}
147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167
		} else if (accept (SparqlTokenType.OPEN_PARENS)) {
			if (current () == SparqlTokenType.SELECT) {
				// no parenthesis around expression
				// deprecated but supported for backward compatibility
				sql.append ("(");
				var select_context = pattern.translate_select (sql, true, true);
				sql.append (")");

				expect (SparqlTokenType.CLOSE_PARENS);
				type = select_context.type;
			} else {
				type = translate_expression (sql);
				if (accept (SparqlTokenType.CLOSE_PARENS)) {
					// missing AS
					// deprecated but supported for backward compatibility
				} else {
					// syntax from SPARQL 1.1 Draft
					// (Expression AS Var)
					expect_close_parens = true;
				}
			}
168
		} else {
169 170
			// no parenthesis around expression
			// deprecated but supported for backward compatibility
171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188
			type = translate_expression (sql);
		}

		if (!subquery) {
			convert_expression_to_string (sql, type, begin);
		}

		if (accept (SparqlTokenType.AS)) {
			if (accept (SparqlTokenType.PN_PREFIX)) {
				// deprecated but supported for backward compatibility
				// (...) AS foo
				variable = context.get_variable (get_last_string ());
			} else {
				// syntax from SPARQL 1.1 Draft
				// (...) AS ?foo
				expect (SparqlTokenType.VAR);
				variable = context.get_variable (get_last_string ().substring (1));
			}
189
			sql.append_printf (" AS %s", variable.sql_expression);
190
			as_handled = true;
191 192 193 194 195 196 197 198 199 200

			if (subquery) {
				var binding = new VariableBinding ();
				binding.data_type = type;
				binding.variable = variable;
				binding.sql_expression = variable.sql_expression;
				pattern.add_variable_binding (new StringBuilder (), binding, VariableState.BOUND);
			}
		}

201 202 203 204 205 206 207 208 209
		if (pattern.fts_subject != null) {
			if (variable == null) {
				// FTS matches still need aliases as the outer MATCH query
				// will fetch futher values from the joined select
				variable = context.get_variable ("var%d".printf (variable_index + 1));
			}

			if (fts_sql == null) {
				pattern.fts_variables += variable.sql_expression;
210 211 212 213

				if (as_handled == false) {
					sql.append_printf (" AS %s", variable.sql_expression);
				}
214 215 216 217 218 219
			} else {
				pattern.fts_variables += fts_sql;
				pattern.queries_fts_data = true;
			}
		}

220 221 222 223
		if (expect_close_parens) {
			expect (SparqlTokenType.CLOSE_PARENS);
		}

224 225 226 227 228 229
		if (variable != null) {
			int state = context.var_set.lookup (variable);
			if (state == 0) {
				state = VariableState.BOUND;
			}
			context.select_var_set.insert (variable, state);
230

231
			((SelectContext) context).variable_names += variable.name;
232
		} else {
233
			((SelectContext) context).variable_names += "var%d".printf (variable_index + 1);
234 235
		}

236 237
		fts_sql = null;

238 239 240
		return type;
	}

241
	void translate_expression_as_order_condition (StringBuilder sql) throws Sparql.Error {
242 243 244 245 246 247 248 249
		long begin = sql.len;
		if (translate_expression (sql) == PropertyType.RESOURCE) {
			// ID => Uri
			sql.insert (begin, "(SELECT Uri FROM Resource WHERE ID = ");
			sql.append (")");
		}
	}

250
	internal void translate_order_condition (StringBuilder sql) throws Sparql.Error {
251 252 253 254 255 256 257 258 259 260 261
		if (accept (SparqlTokenType.ASC)) {
			translate_expression_as_order_condition (sql);
			sql.append (" ASC");
		} else if (accept (SparqlTokenType.DESC)) {
			translate_expression_as_order_condition (sql);
			sql.append (" DESC");
		} else {
			translate_expression_as_order_condition (sql);
		}
	}

262
	void translate_bound_call (StringBuilder sql) throws Sparql.Error {
263 264 265 266 267 268 269 270
		expect (SparqlTokenType.BOUND);
		expect (SparqlTokenType.OPEN_PARENS);
		sql.append ("(");
		translate_expression (sql);
		sql.append (" IS NOT NULL)");
		expect (SparqlTokenType.CLOSE_PARENS);
	}

271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295
	PropertyType translate_if_call (StringBuilder sql) throws Sparql.Error {
		expect (SparqlTokenType.IF);
		expect (SparqlTokenType.OPEN_PARENS);

		// condition
		sql.append ("(CASE ");
		translate_expression (sql);

		// if condition is true
		sql.append (" WHEN 1 THEN ");
		expect (SparqlTokenType.COMMA);
		var type = translate_expression (sql);

		// if condition is false
		sql.append (" WHEN 0 THEN ");
		expect (SparqlTokenType.COMMA);
		translate_expression (sql);

		sql.append (" ELSE NULL END)");

		expect (SparqlTokenType.CLOSE_PARENS);

		return type;
	}

296
	void translate_regex (StringBuilder sql) throws Sparql.Error {
297 298 299 300 301 302
		expect (SparqlTokenType.REGEX);
		expect (SparqlTokenType.OPEN_PARENS);
		sql.append ("SparqlRegex(");
		translate_expression_as_string (sql);
		sql.append (", ");
		expect (SparqlTokenType.COMMA);
303 304 305 306
		// SQLite's sqlite3_set_auxdata doesn't work correctly with bound
		// strings for the regex in function_sparql_regex.
		// translate_expression (sql);
		sql.append (escape_sql_string_literal (parse_string_literal ()));
307 308
		sql.append (", ");
		if (accept (SparqlTokenType.COMMA)) {
309 310 311
			// Same as above
			// translate_expression (sql);
			sql.append (escape_sql_string_literal (parse_string_literal ()));
312 313 314 315 316 317 318
		} else {
			sql.append ("''");
		}
		sql.append (")");
		expect (SparqlTokenType.CLOSE_PARENS);
	}

319
	void translate_exists (StringBuilder sql) throws Sparql.Error {
320 321 322 323 324
		sql.append ("(");
		pattern.translate_exists (sql);
		sql.append (")");
	}

325 326 327 328 329 330 331 332 333
	internal static void append_expression_as_string (StringBuilder sql, string expression, PropertyType type) {
		long begin = sql.len;
		sql.append (expression);
		convert_expression_to_string (sql, type, begin);
	}

	static void convert_expression_to_string (StringBuilder sql, PropertyType type, long begin) {
		switch (type) {
		case PropertyType.STRING:
334
		case PropertyType.INTEGER:
335
			// nothing to convert
336 337
			// do not use CAST to convert integers to strings as this breaks use
			// of index when sorting by variable introduced in select expression
338 339 340 341 342 343 344 345 346 347 348
			break;
		case PropertyType.RESOURCE:
			// ID => Uri
			sql.insert (begin, "(SELECT Uri FROM Resource WHERE ID = ");
			sql.append (")");
			break;
		case PropertyType.BOOLEAN:
			// 0/1 => false/true
			sql.insert (begin, "CASE ");
			sql.append (" WHEN 1 THEN 'true' WHEN 0 THEN 'false' ELSE NULL END");
			break;
349 350 351 352 353
		case PropertyType.DATE:
			// ISO 8601 format
			sql.insert (begin, "strftime (\"%Y-%m-%d\", ");
			sql.append (", \"unixepoch\")");
			break;
354 355
		case PropertyType.DATETIME:
			// ISO 8601 format
356 357
			sql.insert (begin, "SparqlFormatTime (");
			sql.append (")");
358 359 360 361 362 363 364 365 366
			break;
		default:
			// let sqlite convert the expression to string
			sql.insert (begin, "CAST (");
			sql.append (" AS TEXT)");
			break;
		}
	}

367
	void translate_expression_as_string (StringBuilder sql) throws Sparql.Error {
368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394
		switch (current ()) {
		case SparqlTokenType.IRI_REF:
		case SparqlTokenType.PN_PREFIX:
		case SparqlTokenType.COLON:
			// handle IRI literals separately as it wouldn't work for unknown IRIs otherwise
			var binding = new LiteralBinding ();
			bool is_var;
			binding.literal = pattern.parse_var_or_term (null, out is_var);
			if (accept (SparqlTokenType.OPEN_PARENS)) {
				// function call
				long begin = sql.len;
				var type = translate_function (sql, binding.literal);
				expect (SparqlTokenType.CLOSE_PARENS);
				convert_expression_to_string (sql, type, begin);
			} else {
				sql.append ("?");
				query.bindings.append (binding);
			}
			break;
		default:
			long begin = sql.len;
			var type = translate_expression (sql);
			convert_expression_to_string (sql, type, begin);
			break;
		}
	}

395
	void translate_str (StringBuilder sql) throws Sparql.Error {
396 397 398 399 400 401 402 403
		expect (SparqlTokenType.STR);
		expect (SparqlTokenType.OPEN_PARENS);

		translate_expression_as_string (sql);

		expect (SparqlTokenType.CLOSE_PARENS);
	}

404
	void translate_isuri (StringBuilder sql) throws Sparql.Error {
405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428
		if (!accept (SparqlTokenType.ISURI)) {
			expect (SparqlTokenType.ISIRI);
		}

		expect (SparqlTokenType.OPEN_PARENS);

		sql.append ("?");
		var new_binding = new LiteralBinding ();
		new_binding.data_type = PropertyType.INTEGER;

		if (current() == SparqlTokenType.IRI_REF) {
			new_binding.literal = "1";
			next ();
		} else if (translate_expression (new StringBuilder ()) == PropertyType.RESOURCE) {
			new_binding.literal = "1";
		} else {
			new_binding.literal = "0";
		}

		query.bindings.append (new_binding);

		expect (SparqlTokenType.CLOSE_PARENS);
	}

429
	void translate_datatype (StringBuilder sql) throws Sparql.Error {
430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457
		expect (SparqlTokenType.DATATYPE);
		expect (SparqlTokenType.OPEN_PARENS);

		if (accept (SparqlTokenType.VAR)) {
			string variable_name = get_last_string().substring(1);
			var variable = context.get_variable (variable_name);

			if (variable.binding == null) {
				throw get_error ("`%s' is not a valid variable".printf (variable.name));
			}

			if (variable.binding.data_type == PropertyType.RESOURCE || variable.binding.type == null) {
				throw get_error ("Invalid FILTER");
			}

			sql.append ("(SELECT ID FROM Resource WHERE Uri = ?)");

			var new_binding = new LiteralBinding ();
			new_binding.literal = variable.binding.type.uri;
			query.bindings.append (new_binding);

		} else {
			throw get_error ("Invalid FILTER");
		}

		expect (SparqlTokenType.CLOSE_PARENS);
	}

458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496
	void translate_date (StringBuilder sql, string format) throws Sparql.Error {
		sql.append_printf ("strftime (\"%s\", ", format);

		if (accept (SparqlTokenType.VAR)) {
			string variable_name = get_last_string ().substring (1);
			var variable = context.get_variable (variable_name);
			sql.append (variable.get_extra_sql_expression ("localDate"));
			sql.append (" * 24 * 3600");
		} else {
			translate_primary_expression (sql);
		}

		sql.append (", \"unixepoch\")");
	}

	void translate_time (StringBuilder sql, TimeFormatType type) throws Sparql.Error {
		sql.append ("(");
		if (accept (SparqlTokenType.VAR)) {
			string variable_name = get_last_string ().substring (1);
			var variable = context.get_variable (variable_name);
			sql.append (variable.get_extra_sql_expression ("localTime"));
		} else {
			translate_primary_expression (sql);
		}

		switch (type) {
		case TimeFormatType.SECONDS:
			sql.append ("% 60");
			break;
		case TimeFormatType.MINUTES:
			sql.append (" / 60 % 60");
			break;
		case TimeFormatType.HOURS:
			sql.append (" / 3600 % 24");
			break;
		}
		sql.append (")");
	}

497
	PropertyType translate_function (StringBuilder sql, string uri) throws Sparql.Error {
498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516
		if (uri == XSD_NS + "string") {
			// conversion to string
			translate_expression_as_string (sql);

			return PropertyType.STRING;
		} else if (uri == XSD_NS + "integer") {
			// conversion to integer
			sql.append ("CAST (");
			translate_expression_as_string (sql);
			sql.append (" AS INTEGER)");

			return PropertyType.INTEGER;
		} else if (uri == XSD_NS + "double") {
			// conversion to double
			sql.append ("CAST (");
			translate_expression_as_string (sql);
			sql.append (" AS REAL)");

			return PropertyType.DOUBLE;
517 518 519 520 521 522
		} else if (uri == TRACKER_NS + "case-fold") {
			// conversion to string
			sql.append ("SparqlCaseFold (");
			translate_expression_as_string (sql);
			sql.append (")");
			return PropertyType.STRING;
523
		} else if (uri == TRACKER_NS + "ascii-lower-case") {
524 525 526 527 528
			// conversion to string
			sql.append ("lower (");
			translate_expression_as_string (sql);
			sql.append (")");
			return PropertyType.STRING;
529 530 531 532 533 534
		} else if (uri == FN_NS + "lower-case") {
			// conversion to string
			sql.append ("SparqlLowerCase (");
			translate_expression_as_string (sql);
			sql.append (")");
			return PropertyType.STRING;
535 536 537 538 539
		} else if (uri == FN_NS + "upper-case") {
			sql.append ("SparqlUpperCase (");
			translate_expression_as_string (sql);
			sql.append (")");
			return PropertyType.STRING;
540 541 542 543 544 545 546 547 548
		} else if (uri == TRACKER_NS + "normalize") {
			// conversion to string
			sql.append ("SparqlNormalize (");
			translate_expression_as_string (sql);
			sql.append (", ");
			expect (SparqlTokenType.COMMA);
			translate_expression_as_string (sql);
			sql.append (")");
			return PropertyType.STRING;
549 550 551 552 553 554
		} else if (uri == TRACKER_NS + "unaccent") {
			// conversion to string
			sql.append ("SparqlUnaccent (");
			translate_expression_as_string (sql);
			sql.append (")");
			return PropertyType.STRING;
555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570
		} else if (uri == FN_NS + "contains") {
			// fn:contains('A','B') => 'A' GLOB '*B*'
			sql.append ("(");
			translate_expression_as_string (sql);
			sql.append (" GLOB ");
			expect (SparqlTokenType.COMMA);

			sql.append ("?");
			var binding = new LiteralBinding ();
			binding.literal = "*%s*".printf (parse_string_literal ());
			query.bindings.append (binding);

			sql.append (")");

			return PropertyType.BOOLEAN;
		} else if (uri == FN_NS + "starts-with") {
571 572 573
			// fn:starts-with('A','B') => 'A' BETWEEN 'B' AND 'B\u0010fffd'
			// 0010fffd always sorts last

574
			translate_expression_as_string (sql);
575 576
			sql.append (" BETWEEN ");

577
			expect (SparqlTokenType.COMMA);
578
			string prefix = parse_string_literal ();
579 580 581

			sql.append ("?");
			var binding = new LiteralBinding ();
582
			binding.literal = prefix;
583 584
			query.bindings.append (binding);

585 586 587 588
			sql.append (" AND ");

			sql.append ("?");
			binding = new LiteralBinding ();
589
			binding.literal = prefix + COLLATION_LAST_CHAR.to_string ();
590
			query.bindings.append (binding);
591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607

			return PropertyType.BOOLEAN;
		} else if (uri == FN_NS + "ends-with") {
			// fn:ends-with('A','B') => 'A' GLOB '*B'
			sql.append ("(");
			translate_expression_as_string (sql);
			sql.append (" GLOB ");
			expect (SparqlTokenType.COMMA);

			sql.append ("?");
			var binding = new LiteralBinding ();
			binding.literal = "*%s".printf (parse_string_literal ());
			query.bindings.append (binding);

			sql.append (")");

			return PropertyType.BOOLEAN;
608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623
		} else if (uri == FN_NS + "substring") {
			sql.append ("substr(");
			translate_expression_as_string (sql);

			sql.append (", ");
			expect (SparqlTokenType.COMMA);
			translate_expression_as_string (sql);

			if (accept (SparqlTokenType.COMMA)) {
			      sql.append (", ");
			      translate_expression_as_string (sql);
			}

			sql.append (")");

			return PropertyType.STRING;
624
		} else if (uri == FN_NS + "concat") {
625
			translate_expression_as_string (sql);
626 627
			sql.append ("||");
			expect (SparqlTokenType.COMMA);
628
			translate_expression_as_string (sql);
629 630
			while (accept (SparqlTokenType.COMMA)) {
			      sql.append ("||");
631
			      translate_expression_as_string (sql);
632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655
			}

			return PropertyType.STRING;
		} else if (uri == FN_NS + "string-join") {
			sql.append ("SparqlStringJoin(");
			expect (SparqlTokenType.OPEN_PARENS);

			translate_expression_as_string (sql);
			sql.append (", ");
			expect (SparqlTokenType.COMMA);
			translate_expression_as_string (sql);
			while (accept (SparqlTokenType.COMMA)) {
			      sql.append (", ");
			      translate_expression_as_string (sql);
			}

			expect (SparqlTokenType.CLOSE_PARENS);
			sql.append (",");
			expect (SparqlTokenType.COMMA);
			translate_expression (sql);
			sql.append (")");

			return PropertyType.STRING;
		} else if (uri == FN_NS + "year-from-dateTime") {
656
			translate_date (sql, "%Y");
657 658
			return PropertyType.INTEGER;
		} else if (uri == FN_NS + "month-from-dateTime") {
659
			translate_date (sql, "%m");
660 661
			return PropertyType.INTEGER;
		} else if (uri == FN_NS + "day-from-dateTime") {
662
			translate_date (sql, "%d");
663 664
			return PropertyType.INTEGER;
		} else if (uri == FN_NS + "hours-from-dateTime") {
665
			translate_time (sql, TimeFormatType.HOURS);
666 667
			return PropertyType.INTEGER;
		} else if (uri == FN_NS + "minutes-from-dateTime") {
668
			translate_time (sql, TimeFormatType.MINUTES);
669 670
			return PropertyType.INTEGER;
		} else if (uri == FN_NS + "seconds-from-dateTime") {
671
			translate_time (sql, TimeFormatType.SECONDS);
672 673 674 675 676 677 678 679 680 681 682
			return PropertyType.INTEGER;
		} else if (uri == FN_NS + "timezone-from-dateTime") {
			expect (SparqlTokenType.VAR);
			string variable_name = get_last_string ().substring (1);
			var variable = context.get_variable (variable_name);

			sql.append ("(");
			sql.append (variable.get_extra_sql_expression ("localDate"));
			sql.append (" * 24 * 3600 + ");
			sql.append (variable.get_extra_sql_expression ("localTime"));
			sql.append ("- ");
683
			sql.append ("CAST (");
684
			sql.append (variable.sql_expression);
685
			sql.append (" AS INTEGER)");
686 687 688
			sql.append (")");

			return PropertyType.INTEGER;
689
		} else if (uri == FN_NS + "replace") {
690
			sql.append ("SparqlReplace(");
691 692 693 694 695 696 697 698 699 700
			translate_expression_as_string (sql);
			sql.append (", ");

			expect (SparqlTokenType.COMMA);
			translate_expression_as_string (sql);
			sql.append (", ");

			expect (SparqlTokenType.COMMA);
			translate_expression_as_string (sql);

701 702 703 704
			if (accept (SparqlTokenType.COMMA)) {
				sql.append (", ");
				sql.append (escape_sql_string_literal (parse_string_literal ()));
			}
705 706
			sql.append (")");
			return PropertyType.STRING;
707 708 709 710 711 712 713 714 715
		} else if (uri == FTS_NS + "rank") {
			bool is_var;
			string v = pattern.parse_var_or_term (null, out is_var);
			sql.append_printf ("\"%s_u_rank\"", v);

			return PropertyType.DOUBLE;
		} else if (uri == FTS_NS + "offsets") {
			bool is_var;
			string v = pattern.parse_var_or_term (null, out is_var);
716
			var variable = context.get_variable (v);
717

718
			sql.append (variable.sql_expression);
Carlos Garnacho's avatar
Carlos Garnacho committed
719
			fts_sql = "tracker_offsets(\"fts5\")";
720 721 722 723 724
			return PropertyType.STRING;
		} else if (uri == FTS_NS + "snippet") {
			bool is_var;

			string v = pattern.parse_var_or_term (null, out is_var);
725 726
			var variable = context.get_variable (v);
			var fts = new StringBuilder ();
727

Carlos Garnacho's avatar
Carlos Garnacho committed
728 729 730 731
			fts.append_printf ("snippet(\"fts5\"");

			// lookup column
			fts.append (", -1");
732

733
			// "start match" text
734
			if (accept (SparqlTokenType.COMMA)) {
735 736
				fts.append (", ");
				translate_expression_as_string (fts);
737

738 739 740 741 742 743
				// "end match" text
				expect (SparqlTokenType.COMMA);
				fts.append (", ");
				translate_expression_as_string (fts);
			} else {
				fts.append(",'',''");
744 745
			}

746
			// "ellipsis" text
747
			if (accept (SparqlTokenType.COMMA)) {
748 749 750 751
				fts.append (", ");
				translate_expression_as_string (fts);
			} else {
				fts.append (", '...'");
752 753
			}

754 755 756 757 758 759 760 761 762 763 764 765
			// Approximate number of words in context
			if (accept (SparqlTokenType.COMMA)) {
				fts.append (", ");
				translate_expression_as_string (fts);
			} else {
				fts.append (", 5");
			}

			fts.append (")");

			fts_sql = fts.str;
			sql.append (variable.sql_expression);
766
			return PropertyType.STRING;
767 768 769 770 771 772 773
		} else if (uri == TRACKER_NS + "id") {
			var type = translate_expression (sql);
			if (type != PropertyType.RESOURCE) {
				throw get_error ("expected resource");
			}

			return PropertyType.INTEGER;
774
		} else if (uri == TRACKER_NS + "uri") {
775 776 777
			var type = translate_expression (sql);
			if (type != PropertyType.INTEGER) {
				throw get_error ("expected integer ID");
778 779
			}

780
			return PropertyType.RESOURCE;
781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823
		} else if (uri == TRACKER_NS + "cartesian-distance") {
			sql.append ("SparqlCartesianDistance(");
			translate_expression (sql);
			sql.append (", ");
			expect (SparqlTokenType.COMMA);
			translate_expression (sql);
			sql.append (", ");
			expect (SparqlTokenType.COMMA);
			translate_expression (sql);
			sql.append (", ");
			expect (SparqlTokenType.COMMA);
			translate_expression (sql);
			sql.append (")");

			return PropertyType.DOUBLE;
		} else if (uri == TRACKER_NS + "haversine-distance") {
			sql.append ("SparqlHaversineDistance(");
			translate_expression (sql);
			sql.append (", ");
			expect (SparqlTokenType.COMMA);
			translate_expression (sql);
			sql.append (", ");
			expect (SparqlTokenType.COMMA);
			translate_expression (sql);
			sql.append (", ");
			expect (SparqlTokenType.COMMA);
			translate_expression (sql);
			sql.append (")");

			return PropertyType.DOUBLE;
		} else if (uri == TRACKER_NS + "coalesce") {
			sql.append ("COALESCE(");
			translate_expression_as_string (sql);
			sql.append (", ");
			expect (SparqlTokenType.COMMA);
			translate_expression_as_string (sql);
			while (accept (SparqlTokenType.COMMA)) {
			      sql.append (", ");
			      translate_expression_as_string (sql);
			}
			sql.append (")");

			return PropertyType.STRING;
824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839
		} else if (uri == TRACKER_NS + "uri-is-parent") {
			sql.append ("SparqlUriIsParent(");
			translate_expression_as_string (sql);
			sql.append (", ");
			expect (SparqlTokenType.COMMA);

			translate_expression_as_string (sql);
			sql.append (")");

			return PropertyType.BOOLEAN;
		} else if (uri == TRACKER_NS + "uri-is-descendant") {
			sql.append ("SparqlUriIsDescendant(");
			translate_expression_as_string (sql);
			sql.append (", ");
			expect (SparqlTokenType.COMMA);

840 841 842 843 844
                        translate_expression_as_string (sql);
                        while (accept (SparqlTokenType.COMMA)) {
			      sql.append (", ");
			      translate_expression_as_string (sql);
			}
845 846 847
			sql.append (")");

			return PropertyType.BOOLEAN;
848 849 850 851 852 853 854 855 856 857 858 859 860
		} else if (uri == TRACKER_NS + "string-from-filename") {
			sql.append ("SparqlStringFromFilename(");
			translate_expression_as_string (sql);
			sql.append (")");

			return PropertyType.STRING;
		} else {
			// support properties as functions
			var prop = Ontologies.get_property_by_uri (uri);
			if (prop == null) {
				throw get_error ("Unknown function");
			}

861 862 863
			var expr = new StringBuilder ();
			translate_expression (expr);

864 865 866 867 868 869 870 871 872 873 874
			string value_separator = ",";
			string? graph_separator = null;

			if (accept (SparqlTokenType.COMMA)) {
				value_separator = parse_string_literal ();

				if (accept (SparqlTokenType.COMMA)) {
					graph_separator = parse_string_literal ();
				}
			}

875
			if (prop.multiple_values) {
876
				// multi-valued property
877 878 879 880
				sql.append ("(SELECT GROUP_CONCAT(");
				long begin = sql.len;
				sql.append_printf ("\"%s\"", prop.name);
				convert_expression_to_string (sql, prop.data_type, begin);
881 882 883 884 885
				if (graph_separator != null) {
					sql.append_printf (" || %s || COALESCE((SELECT Uri FROM Resource WHERE ID = \"%s:graph\"), '')", escape_sql_string_literal (graph_separator), prop.name);
				}
				sql.append_printf (",%s)", escape_sql_string_literal (value_separator));
				sql.append_printf (" FROM \"%s\" WHERE ID = %s)", prop.table_name, expr.str);
886 887 888

				return PropertyType.STRING;
			} else {
889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906
				// single-valued property
				if (graph_separator == null) {
					sql.append_printf ("(SELECT \"%s\" FROM \"%s\" WHERE ID = %s)", prop.name, prop.table_name, expr.str);

					if (prop.data_type == PropertyType.STRING) {
						append_collate (sql);
					}

					return prop.data_type;
				} else {
					sql.append ("(SELECT ");
					long begin = sql.len;
					sql.append_printf ("\"%s\"", prop.name);
					convert_expression_to_string (sql, prop.data_type, begin);
					sql.append_printf (" || %s || COALESCE((SELECT Uri FROM Resource WHERE ID = \"%s:graph\"), '')", escape_sql_string_literal (graph_separator), prop.name);
					sql.append_printf (" FROM \"%s\" WHERE ID = %s)", prop.table_name, expr.str);

					return PropertyType.STRING;
907
				}
908 909 910 911
			}
		}
	}

912
	PropertyType parse_type_uri () throws Sparql.Error {
913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955
		string type_iri;
		PropertyType type;

		if (accept (SparqlTokenType.IRI_REF)) {
			type_iri = get_last_string (1);
		} else if (accept (SparqlTokenType.PN_PREFIX)) {
			string ns = get_last_string ();
			expect (SparqlTokenType.COLON);
			type_iri = query.resolve_prefixed_name (ns, get_last_string ().substring (1));
		} else {
			expect (SparqlTokenType.COLON);
			type_iri = query.resolve_prefixed_name ("", get_last_string ().substring (1));
		}

		if (type_iri == XSD_NS + "boolean") {
			type = PropertyType.BOOLEAN;
		} else if (type_iri == XSD_NS + "integer" ||
		           type_iri == XSD_NS + "nonPositiveInteger" ||
		           type_iri == XSD_NS + "negativeInteger" ||
		           type_iri == XSD_NS + "long" ||
		           type_iri == XSD_NS + "int" ||
		           type_iri == XSD_NS + "short" ||
		           type_iri == XSD_NS + "byte" ||
		           type_iri == XSD_NS + "nonNegativeInteger" ||
		           type_iri == XSD_NS + "unsignedLong" ||
		           type_iri == XSD_NS + "unsignedInt" ||
		           type_iri == XSD_NS + "unsignedShort" ||
		           type_iri == XSD_NS + "unsignedByte" ||
		           type_iri == XSD_NS + "positiveInteger") {
			type = PropertyType.INTEGER;
		} else if (type_iri == XSD_NS + "double") {
			type = PropertyType.DOUBLE;
		} else if (type_iri == XSD_NS + "date") {
			type = PropertyType.DATE;
		} else if (type_iri == XSD_NS + "dateTime") {
			type = PropertyType.DATETIME;
		} else {
			type = PropertyType.STRING;
		}

		return type;
	}

956
	internal string parse_string_literal (out PropertyType type = null) throws Sparql.Error {
Jürg Billeter's avatar
Jürg Billeter committed
957 958
		type = PropertyType.STRING;

959 960 961 962 963 964 965 966
		next ();
		switch (last ()) {
		case SparqlTokenType.STRING_LITERAL1:
		case SparqlTokenType.STRING_LITERAL2:
			var sb = new StringBuilder ();

			string s = get_last_string (1);
			string* p = s;
967
			string* end = p + s.length;
968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996
			while ((long) p < (long) end) {
				string* q = Posix.strchr (p, '\\');
				if (q == null) {
					sb.append_len (p, (long) (end - p));
					p = end;
				} else {
					sb.append_len (p, (long) (q - p));
					p = q + 1;
					switch (((char*) p)[0]) {
					case '\'':
					case '"':
					case '\\':
						sb.append_c (((char*) p)[0]);
						break;
					case 'b':
						sb.append_c ('\b');
						break;
					case 'f':
						sb.append_c ('\f');
						break;
					case 'n':
						sb.append_c ('\n');
						break;
					case 'r':
						sb.append_c ('\r');
						break;
					case 't':
						sb.append_c ('\t');
						break;
997 998 999 1000 1001 1002
					case 'u':
						char* ptr = (char*) p + 1;
						unichar c = (((unichar) ptr[0].xdigit_value () * 16 + ptr[1].xdigit_value ()) * 16 + ptr[2].xdigit_value ()) * 16 + ptr[3].xdigit_value ();
						sb.append_unichar (c);
						p += 4;
						break;
1003 1004 1005 1006 1007 1008
					}
					p++;
				}
			}

			if (accept (SparqlTokenType.DOUBLE_CIRCUMFLEX)) {
1009
				// typed literal
Jürg Billeter's avatar
Jürg Billeter committed
1010
				type = parse_type_uri ();
1011 1012 1013 1014 1015 1016 1017 1018
			}

			return sb.str;
		case SparqlTokenType.STRING_LITERAL_LONG1:
		case SparqlTokenType.STRING_LITERAL_LONG2:
			string result = get_last_string (3);

			if (accept (SparqlTokenType.DOUBLE_CIRCUMFLEX)) {
1019
				// typed literal
Jürg Billeter's avatar
Jürg Billeter committed
1020
				type = parse_type_uri ();
1021 1022 1023 1024 1025 1026 1027 1028
			}

			return result;
		default:
			throw get_error ("expected string literal");
		}
	}

1029
	PropertyType translate_uri_expression (StringBuilder sql, string uri) throws Sparql.Error {
1030 1031 1032 1033 1034 1035 1036
		if (accept (SparqlTokenType.OPEN_PARENS)) {
			// function
			var result = translate_function (sql, uri);
			expect (SparqlTokenType.CLOSE_PARENS);
			return result;
		} else {
			// resource
1037
			sql.append ("COALESCE((SELECT ID FROM Resource WHERE Uri = ?), 0)");
1038 1039 1040 1041 1042 1043 1044
			var binding = new LiteralBinding ();
			binding.literal = uri;
			query.bindings.append (binding);
			return PropertyType.RESOURCE;
		}
	}

1045
	PropertyType translate_primary_expression (StringBuilder sql) throws Sparql.Error {
1046 1047
		PropertyType type;

1048 1049 1050 1051 1052 1053 1054 1055 1056 1057
		switch (current ()) {
		case SparqlTokenType.OPEN_PARENS:
			return translate_bracketted_expression (sql);
		case SparqlTokenType.IRI_REF:
			next ();
			return translate_uri_expression (sql, get_last_string (1));
		case SparqlTokenType.DECIMAL:
		case SparqlTokenType.DOUBLE:
			next ();

1058 1059 1060 1061
			if (query.no_cache) {
				sql.append (get_last_string ());
			} else {
				sql.append ("?");
1062

1063 1064 1065 1066
				var binding = new LiteralBinding ();
				binding.literal = get_last_string ();
				query.bindings.append (binding);
			}
1067 1068 1069 1070 1071

			return PropertyType.DOUBLE;
		case SparqlTokenType.TRUE:
			next ();

1072 1073 1074 1075
			if (query.no_cache) {
				sql.append ("1");
			} else {
				sql.append ("?");
1076

1077 1078 1079 1080 1081
				var binding = new LiteralBinding ();
				binding.literal = "1";
				binding.data_type = PropertyType.INTEGER;
				query.bindings.append (binding);
			}
1082 1083 1084 1085 1086

			return PropertyType.BOOLEAN;
		case SparqlTokenType.FALSE:
			next ();

1087 1088 1089 1090
			if (query.no_cache) {
				sql.append ("0");
			} else {
				sql.append ("?");
1091

1092 1093 1094 1095 1096
				var binding = new LiteralBinding ();
				binding.literal = "0";
				binding.data_type = PropertyType.INTEGER;
				query.bindings.append (binding);
			}
1097 1098 1099 1100 1101 1102

			return PropertyType.BOOLEAN;
		case SparqlTokenType.STRING_LITERAL1:
		case SparqlTokenType.STRING_LITERAL2:
		case SparqlTokenType.STRING_LITERAL_LONG1:
		case SparqlTokenType.STRING_LITERAL_LONG2:
1103
			var literal = parse_string_literal (out type);
1104

1105 1106
			switch (type) {
			case PropertyType.INTEGER:
1107
			case PropertyType.BOOLEAN:
1108
			case PropertyType.DOUBLE:
1109
			case PropertyType.DATE:
1110
			case PropertyType.DATETIME:
1111 1112 1113 1114 1115 1116 1117 1118 1119
				if (query.no_cache) {
					sql.append (escape_sql_string_literal (literal));
				} else {
					var binding = new LiteralBinding ();
					binding.literal = literal;
					binding.data_type = type;
					query.bindings.append (binding);
					sql.append ("?");
				}
1120 1121
				return type;
			default:
1122 1123 1124 1125 1126 1127 1128 1129
				if (query.no_cache) {
					sql.append (escape_sql_string_literal (literal));
				} else {
					var binding = new LiteralBinding ();
					binding.literal = literal;
					query.bindings.append (binding);
					sql.append ("?");
				}
1130
				append_collate (sql);
1131 1132
				return PropertyType.STRING;
			}
1133 1134 1135
		case SparqlTokenType.INTEGER:
			next ();

1136 1137 1138 1139
			if (query.no_cache) {
				sql.append (get_last_string ());
			} else {
				sql.append ("?");
1140

1141 1142 1143 1144 1145
				var binding = new LiteralBinding ();
				binding.literal = get_last_string ();
				binding.data_type = PropertyType.INTEGER;
				query.bindings.append (binding);
			}
1146 1147 1148 1149 1150 1151

			return PropertyType.INTEGER;
		case SparqlTokenType.VAR:
			next ();
			string variable_name = get_last_string ().substring (1);
			var variable = context.get_variable (variable_name);
1152

1153
			if (context.need_binding_expression && variable.binding != null) {
1154 1155 1156 1157
				sql.append (variable.binding.sql_expression);
			} else {
				sql.append (variable.sql_expression);
			}
1158 1159

			if (variable.binding == null) {
1160
				return PropertyType.UNKNOWN;
1161
			} else {
1162 1163 1164
				if (variable.binding.data_type == PropertyType.STRING) {
					append_collate (sql);
				}
1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183
				return variable.binding.data_type;
			}
		case SparqlTokenType.STR:
			translate_str (sql);
			return PropertyType.STRING;
		case SparqlTokenType.LANG:
			next ();
			sql.append ("''");
			return PropertyType.STRING;
		case SparqlTokenType.LANGMATCHES:
			next ();
			sql.append ("0");
			return PropertyType.BOOLEAN;
		case SparqlTokenType.DATATYPE:
			translate_datatype (sql);
			return PropertyType.RESOURCE;
		case SparqlTokenType.BOUND:
			translate_bound_call (sql);
			return PropertyType.BOOLEAN;
1184 1185 1186 1187 1188 1189
		case SparqlTokenType.COALESCE:
			next ();
			expect (SparqlTokenType.OPEN_PARENS);
			var result = translate_function (sql, TRACKER_NS + "coalesce");
			expect (SparqlTokenType.CLOSE_PARENS);
			return result;
1190 1191 1192 1193 1194 1195
		case SparqlTokenType.CONCAT:
			next ();
			expect (SparqlTokenType.OPEN_PARENS);
			var result = translate_function (sql, FN_NS + "concat");
			expect (SparqlTokenType.CLOSE_PARENS);
			return result;
1196 1197 1198 1199 1200 1201
		case SparqlTokenType.CONTAINS:
			next ();
			expect (SparqlTokenType.OPEN_PARENS);
			var result = translate_function (sql, FN_NS + "contains");
			expect (SparqlTokenType.CLOSE_PARENS);
			return result;
1202 1203 1204 1205 1206 1207 1208 1209
		case SparqlTokenType.ENCODE_FOR_URI:
			next ();
			expect (SparqlTokenType.OPEN_PARENS);
			sql.append ("SparqlEncodeForUri (");
			translate_expression_as_string (sql);
			sql.append (")");
			expect (SparqlTokenType.CLOSE_PARENS);
			return PropertyType.STRING;
1210 1211
		case SparqlTokenType.IF:
			return translate_if_call (sql);
1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237
		case SparqlTokenType.SAMETERM:
			next ();
			expect (SparqlTokenType.OPEN_PARENS);
			sql.append ("(");
			translate_expression (sql);
			sql.append (" = ");
			expect (SparqlTokenType.COMMA);
			translate_expression (sql);
			sql.append (")");
			expect (SparqlTokenType.CLOSE_PARENS);
			return PropertyType.BOOLEAN;
		case SparqlTokenType.ISIRI:
		case SparqlTokenType.ISURI:
			translate_isuri (sql);
			return PropertyType.BOOLEAN;
		case SparqlTokenType.ISBLANK:
			next ();
			expect (SparqlTokenType.OPEN_PARENS);
			next ();
			// TODO: support ISBLANK properly
			sql.append ("0");
			expect (SparqlTokenType.CLOSE_PARENS);
			return PropertyType.BOOLEAN;
		case SparqlTokenType.ISLITERAL:
			next ();
			return PropertyType.BOOLEAN;
1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249
		case SparqlTokenType.LCASE:
			next ();
			expect (SparqlTokenType.OPEN_PARENS);
			var result = translate_function (sql, FN_NS + "lower-case");
			expect (SparqlTokenType.CLOSE_PARENS);
			return result;
		case SparqlTokenType.UCASE:
			next ();
			expect (SparqlTokenType.OPEN_PARENS);
			var result = translate_function (sql, FN_NS + "upper-case");
			expect (SparqlTokenType.CLOSE_PARENS);
			return result;
1250 1251 1252 1253 1254 1255
		case SparqlTokenType.STRLEN:
			next ();
			sql.append ("LENGTH(");
			type = translate_aggregate_expression (sql);
			sql.append (")");
			return PropertyType.INTEGER;
1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267
		case SparqlTokenType.STRSTARTS:
			next ();
			expect (SparqlTokenType.OPEN_PARENS);
			var result = translate_function (sql, FN_NS + "starts-with");
			expect (SparqlTokenType.CLOSE_PARENS);
			return result;
		case SparqlTokenType.STRENDS:
			next ();
			expect (SparqlTokenType.OPEN_PARENS);
			var result = translate_function (sql, FN_NS + "ends-with");
			expect (SparqlTokenType.CLOSE_PARENS);
			return result;
1268 1269 1270 1271 1272 1273
		case SparqlTokenType.SUBSTR:
			next ();
			expect (SparqlTokenType.OPEN_PARENS);
			var result = translate_function (sql, FN_NS + "substring");
			expect (SparqlTokenType.CLOSE_PARENS);
			return result;
1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295
		case SparqlTokenType.STRBEFORE:
			next ();
			expect (SparqlTokenType.OPEN_PARENS);
			sql.append ("SparqlStringBefore (");
			translate_expression_as_string (sql);
			expect (SparqlTokenType.COMMA);
			sql.append (",");
			translate_expression_as_string (sql);
			sql.append (")");
			expect (SparqlTokenType.CLOSE_PARENS);
			return PropertyType.STRING;
		case SparqlTokenType.STRAFTER:
			next ();
			expect (SparqlTokenType.OPEN_PARENS);
			sql.append ("SparqlStringAfter (");
			translate_expression_as_string (sql);
			expect (SparqlTokenType.COMMA);
			sql.append (",");
			translate_expression_as_string (sql);
			sql.append (")");
			expect (SparqlTokenType.CLOSE_PARENS);
			return PropertyType.STRING;
1296 1297
		case SparqlTokenType.REGEX:
			translate_regex (sql);
1298
			query.no_cache = true;
1299
			return PropertyType.BOOLEAN;
1300 1301 1302 1303
		case SparqlTokenType.EXISTS:
		case SparqlTokenType.NOT:
			translate_exists (sql);
			return PropertyType.BOOLEAN;
1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333
		case SparqlTokenType.COUNT:
			next ();
			sql.append ("COUNT(");
			translate_aggregate_expression (sql);
			sql.append (")");
			return PropertyType.INTEGER;
		case SparqlTokenType.SUM:
			next ();
			sql.append ("SUM(");
			type = translate_aggregate_expression (sql);
			sql.append (")");
			return type;
		case SparqlTokenType.AVG:
			next ();
			sql.append ("AVG(");
			type = translate_aggregate_expression (sql);
			sql.append (")");
			return type;
		case SparqlTokenType.MIN:
			next ();
			sql.append ("MIN(");
			type = translate_aggregate_expression (sql);
			sql.append (")");
			return type;
		case SparqlTokenType.MAX:
			next ();
			sql.append ("MAX(");
			type = translate_aggregate_expression (sql);
			sql.append (")");
			return type;
1334 1335 1336 1337 1338 1339
		case SparqlTokenType.ABS:
			next ();
			sql.append ("ABS(");
			type = translate_aggregate_expression (sql);
			sql.append (")");
			return type;
1340 1341 1342 1343 1344 1345
		case SparqlTokenType.ROUND:
			next ();
			sql.append ("ROUND(");
			type = translate_aggregate_expression (sql);
			sql.append (")");
			return type;
1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357
		case SparqlTokenType.CEIL:
			next ();
			sql.append ("SparqlCeil(");
			type = translate_aggregate_expression (sql);
			sql.append (")");
			return type;
		case SparqlTokenType.FLOOR:
			next ();
			sql.append ("SparqlFloor(");
			type = translate_aggregate_expression (sql);
			sql.append (")");
			return type;
1358 1359 1360 1361 1362 1363
		case SparqlTokenType.RAND:
			next ();
			expect (SparqlTokenType.OPEN_PARENS);
			expect (SparqlTokenType.CLOSE_PARENS);
			sql.append ("SparqlRand()");
			return PropertyType.DOUBLE;
1364 1365 1366 1367 1368 1369
		case SparqlTokenType.NOW:
			next ();
			expect (SparqlTokenType.OPEN_PARENS);
			expect (SparqlTokenType.CLOSE_PARENS);
			sql.append ("strftime('%s', 'now')");
			return PropertyType.DATETIME;
1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405
		case SparqlTokenType.SECONDS:
			next ();
			expect (SparqlTokenType.OPEN_PARENS);
			var result = translate_function (sql, FN_NS + "seconds-from-dateTime");
			expect (SparqlTokenType.CLOSE_PARENS);
			return result;
		case SparqlTokenType.MINUTES:
			next ();
			expect (SparqlTokenType.OPEN_PARENS);
			var result = translate_function (sql, FN_NS + "minutes-from-dateTime");
			expect (SparqlTokenType.CLOSE_PARENS);
			return result;
		case SparqlTokenType.HOURS:
			next ();
			expect (SparqlTokenType.OPEN_PARENS);
			var result = translate_function (sql, FN_NS + "hours-from-dateTime");
			expect (SparqlTokenType.CLOSE_PARENS);
			return result;
		case SparqlTokenType.DAY:
			next ();
			expect (SparqlTokenType.OPEN_PARENS);
			var result = translate_function (sql, FN_NS + "day-from-dateTime");
			expect (SparqlTokenType.CLOSE_PARENS);
			return result;
		case SparqlTokenType.MONTH:
			next ();
			expect (SparqlTokenType.OPEN_PARENS);
			var result = translate_function (sql, FN_NS + "month-from-dateTime");
			expect (SparqlTokenType.CLOSE_PARENS);
			return result;
		case SparqlTokenType.YEAR:
			next ();
			expect (SparqlTokenType.OPEN_PARENS);
			var result = translate_function (sql, FN_NS + "year-from-dateTime");
			expect (SparqlTokenType.CLOSE_PARENS);
			return result;
1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429
		case SparqlTokenType.MD5:
			next ();
			sql.append ("SparqlChecksum(");
			type = translate_aggregate_expression (sql);
			sql.append (", \"md5\")");
			return type;
		case SparqlTokenType.SHA1:
			next ();
			sql.append ("SparqlChecksum(");
			type = translate_aggregate_expression (sql);
			sql.append (", \"sha1\")");
			return type;
		case SparqlTokenType.SHA256:
			next ();
			sql.append ("SparqlChecksum(");
			type = translate_aggregate_expression (sql);
			sql.append (", \"sha256\")");
			return type;
		case SparqlTokenType.SHA512:
			next ();
			sql.append ("SparqlChecksum(");
			type = translate_aggregate_expression (sql);
			sql.append (", \"sha512\")");
			return type;
1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440
		case SparqlTokenType.GROUP_CONCAT:
			next ();
			sql.append ("GROUP_CONCAT(");
			expect (SparqlTokenType.OPEN_PARENS);
			translate_expression_as_string (sql);
			sql.append (", ");
			expect (SparqlTokenType.COMMA);
			sql.append (escape_sql_string_literal (parse_string_literal ()));
			sql.append (")");
			expect (SparqlTokenType.CLOSE_PARENS);
			return PropertyType.STRING;
1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455
		case SparqlTokenType.PN_PREFIX:
			next ();
			string ns = get_last_string ();
			expect (SparqlTokenType.COLON);
			string uri = query.resolve_prefixed_name (ns, get_last_string ().substring (1));
			return translate_uri_expression (sql, uri);
		case SparqlTokenType.COLON:
			next ();
			string uri = query.resolve_prefixed_name ("", get_last_string ().substring (1));
			return translate_uri_expression (sql, uri);
		default:
			throw get_error ("expected primary expression");
		}
	}

1456
	PropertyType translate_unary_expression (StringBuilder sql) throws Sparql.Error {
1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475
		if (accept (SparqlTokenType.OP_NEG)) {
			sql.append ("NOT (");
			var optype = translate_primary_expression (sql);
			sql.append (")");
			if (optype != PropertyType.BOOLEAN) {
				throw get_error ("expected boolean expression");
			}
			return PropertyType.BOOLEAN;
		} else if (accept (SparqlTokenType.PLUS)) {
			return translate_primary_expression (sql);
		} else if (accept (SparqlTokenType.MINUS)) {
			sql.append ("-(");
			var optype = translate_primary_expression (sql);
			sql.append (")");
			return optype;
		}
		return translate_primary_expression (sql);
	}

1476
	PropertyType translate_multiplicative_expression (StringBuilder sql) throws Sparql.Error {
1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506
		long begin = sql.len;
		var optype = translate_unary_expression (sql);
		while (true) {
			if (accept (SparqlTokenType.STAR)) {
				if (!maybe_numeric (optype)) {
					throw get_error ("expected numeric operand");
				}
				sql.insert (begin, "(");
				sql.append (" * ");
				if (!maybe_numeric (translate_unary_expression (sql))) {
					throw get_error ("expected numeric operand");
				}
				sql.append (")");
			} else if (accept (SparqlTokenType.DIV)) {
				if (!maybe_numeric (optype)) {
					throw get_error ("expected numeric operand");
				}
				sql.insert (begin, "(");
				sql.append (" / ");
				if (!maybe_numeric (translate_unary_expression (sql))) {
					throw get_error ("expected numeric operand");
				}
				sql.append (")");
			} else {
				break;
			}
		}
		return optype;
	}

1507
	PropertyType translate_additive_expression (StringBuilder sql) throws Sparql.Error {
1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537
		long begin = sql.len;
		var optype = translate_multiplicative_expression (sql);
		while (true) {
			if (accept (SparqlTokenType.PLUS)) {
				if (!maybe_numeric (optype)) {
					throw get_error ("expected numeric operand");
				}
				sql.insert (begin, "(");
				sql.append (" + ");
				if (!maybe_numeric (translate_multiplicative_expression (sql))) {
					throw get_error ("expected numeric operand");
				}
				sql.append (")");
			} else if (accept (SparqlTokenType.MINUS)) {
				if (!maybe_numeric (optype)) {
					throw get_error ("expected numeric operand");
				}
				sql.insert (begin, "(");
				sql.append (" - ");
				if (!maybe_numeric (translate_multiplicative_expression (sql))) {
					throw get_error ("expected numeric operand");
				}
				sql.append (")");
			} else {
				break;
			}
		}
		return optype;
	}

1538
	PropertyType translate_numeric_expression (StringBuilder sql) throws Sparql.Error {
1539 1540 1541
		return translate_additive_expression (sql);
	}

1542
	PropertyType process_relational_expression (StringBuilder sql, long begin, uint n_bindings, PropertyType op1type, string operator) throws Sparql.Error {
1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553
		sql.insert (begin, "(");
		sql.append (operator);
		var op2type = translate_numeric_expression (sql);
		sql.append (")");
		if ((op1type == PropertyType.DATETIME && op2type == PropertyType.STRING)
		    || (op1type == PropertyType.STRING && op2type == PropertyType.DATETIME)) {
			// TODO: improve performance (linked list)
			if (query.bindings.length () == n_bindings + 1) {
				// trigger string => datetime conversion
				query.bindings.last ().data.data_type = PropertyType.DATETIME;
			}
1554 1555 1556 1557 1558 1559 1560
		} else if ((op1type == PropertyType.DATE && op2type == PropertyType.STRING)
		           || (op1type == PropertyType.STRING && op2type == PropertyType.DATE)) {
			// TODO: improve performance (linked list)
			if (query.bindings.length () == n_bindings + 1) {
				// trigger string => date conversion
				query.bindings.last ().data.data_type = PropertyType.DATE;
			}
1561 1562 1563 1564
		}
		return PropertyType.BOOLEAN;
	}

1565
	PropertyType translate_in (StringBuilder sql, bool not) throws Sparql.Error {
1566

1567 1568
		int in_variable_count = 0;

1569 1570 1571 1572
		if (not) {
			sql.append (" NOT");
		}

1573 1574
		expect (SparqlTokenType.OPEN_PARENS);
		sql.append (" IN (");
1575
		if (!accept (SparqlTokenType.CLOSE_PARENS)) {
1576
			in_variable_count++;
1577
			translate_expression (sql);
1578 1579
			while (accept (SparqlTokenType.COMMA)) {
				sql.append (", ");
1580 1581 1582 1583 1584 1585 1586

				in_variable_count++;

				if (in_variable_count > MAX_VARIABLES_FOR_IN && !query.no_cache) {
					query.no_cache = true;
				}

1587
				translate_expression (sql);
1588 1589
			}
			expect (SparqlTokenType.CLOSE_PARENS);
1590 1591
		}
		sql.append (")");
1592

1593 1594 1595
		return PropertyType.BOOLEAN;
	}

1596
	PropertyType translate_relational_expression (StringBuilder sql) throws Sparql.Error {
1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612
		long begin = sql.len;
		// TODO: improve performance (linked list)
		uint n_bindings = query.bindings.length ();
		var optype = translate_numeric_expression (sql);
		if (accept (SparqlTokenType.OP_GE)) {
			return process_relational_expression (sql, begin, n_bindings, optype, " >= ");
		} else if (accept (SparqlTokenType.OP_EQ)) {
			return process_relational_expression (sql, begin, n_bindings, optype, " = ");
		} else if (accept (SparqlTokenType.OP_NE)) {
			return process_relational_expression (sql, begin, n_bindings, optype, " <> ");
		} else if (accept (SparqlTokenType.OP_LT)) {
			return process_relational_expression (sql, begin, n_bindings, optype, " < ");
		} else if (accept (SparqlTokenType.OP_LE)) {
			return process_relational_expression (sql, begin, n_bindings, optype, " <= ");
		} else if (accept (SparqlTokenType.OP_GT)) {
			return process_relational_expression (sql, begin, n_bindings, optype, " > ");
1613
		} else if (accept (SparqlTokenType.OP_IN)) {
1614
			return translate_in (sql, false);
1615 1616
		} else if (accept (SparqlTokenType.NOT)) {
			expect (SparqlTokenType.OP_IN);
1617
			return translate_in (sql, true);
1618 1619 1620 1621
		}
		return optype;
	}

1622
	PropertyType translate_value_logical (StringBuilder sql) throws Sparql.Error {
1623 1624 1625
		return translate_relational_expression (sql);
	}

1626
	PropertyType translate_conditional_and_expression (StringBuilder sql) throws Sparql.Error {
1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643
		long begin = sql.len;
		var optype = translate_value_logical (sql);
		while (accept (SparqlTokenType.OP_AND)) {
			if (optype != PropertyType.BOOLEAN) {
				throw get_error ("expected boolean expression");
			}
			sql.insert (begin, "(");
			sql.append (" AND ");
			optype = translate_value_logical (sql);
			sql.append (")");
			if (optype != PropertyType.BOOLEAN) {
				throw get_error ("expected boolean expression");
			}
		}
		return optype;
	}

1644
	PropertyType translate_conditional_or_expression (StringBuilder sql) throws Sparql.Error {
1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661
		long begin = sql.len;
		var optype = translate_conditional_and_expression (sql);
		while (accept (SparqlTokenType.OP_OR)) {
			if (optype != PropertyType.BOOLEAN) {
				throw get_error ("expected boolean expression");
			}
			sql.insert (begin, "(");
			sql.append (" OR ");
			optype = translate_conditional_and_expression (sql);
			sql.append (")");
			if (optype != PropertyType.BOOLEAN) {
				throw get_error ("expected boolean expression");
			}
		}
		return optype;
	}

1662
	internal PropertyType translate_expression (StringBuilder sql) throws Sparql.Error {
1663 1664 1665
		return translate_conditional_or_expression (sql);
	}

1666
	PropertyType translate_bracketted_expression (StringBuilder sql) throws Sparql.Error {
1667 1668 1669 1670 1671 1672
		expect (SparqlTokenType.OPEN_PARENS);

		if (current () == SparqlTokenType.SELECT) {
			// scalar subquery

			sql.append ("(");
1673
			var select_context = pattern.translate_select (sql, true, true);
1674 1675 1676
			sql.append (")");

			expect (SparqlTokenType.CLOSE_PARENS);
1677
			return select_context.type;
1678 1679 1680 1681 1682 1683 1684
		}

		var optype = translate_expression (sql);
		expect (SparqlTokenType.CLOSE_PARENS);
		return optype;
	}

1685
	PropertyType translate_aggregate_expression (StringBuilder sql) throws Sparql.Error {
1686 1687 1688 1689
		expect (SparqlTokenType.OPEN_PARENS);
		if (accept (SparqlTokenType.DISTINCT)) {
			sql.append ("DISTINCT ");
		}
1690 1691

		bool is_var = (current () == SparqlTokenType.VAR);
1692
		var optype = translate_expression (sql);
1693 1694 1695 1696 1697 1698 1699 1700

		if (is_var) {
			var variable = context.get_variable (get_last_string ().substring (1));
			if (variable.binding == null) {
				throw get_error ("use of undefined variable `%s'".printf (variable.name));
			}
		}

1701 1702 1703 1704
		expect (SparqlTokenType.CLOSE_PARENS);
		return optype;
	}

1705
	internal PropertyType translate_constraint (StringBuilder sql) throws Sparql.Error {
1706 1707 1708 1709 1710 1711
		switch (current ()) {
		case SparqlTokenType.STR:
		case SparqlTokenType.LANG:
		case SparqlTokenType.LANGMATCHES:
		case SparqlTokenType.DATATYPE:
		case SparqlTokenType.BOUND:
1712
		case SparqlTokenType.IF:
1713 1714 1715 1716 1717 1718
		case SparqlTokenType.SAMETERM:
		case SparqlTokenType.ISIRI:
		case SparqlTokenType.ISURI:
		case SparqlTokenType.ISBLANK:
		case SparqlTokenType.ISLITERAL:
		case SparqlTokenType.REGEX:
1719 1720
		case SparqlTokenType.EXISTS:
		case SparqlTokenType.NOT:
1721 1722 1723 1724 1725 1726
			return translate_primary_expression (sql);
		default:
			return translate_bracketted_expression (sql);
		}
	}
}