The standard librarySlide 73 of 86
73WHEREThe standard library

Optional filters: WHERE { }

Grammar: where-block, sql-item
WHERE{sql-item}
where-block = "WHERE" "{" { sql-item } "}" ;
ifexpression{sql-body}orand{sql-item}
sql-item = "if" expression "{" sql-body "}" | ( "or" | "and" ) "{" { sql-item } "}" ;As the compiler reads it; §2.8 of the specification is out of date here.

A search screen with four boxes on it is four optional predicates, and building that SQL as text is where both SQL injection and WHERE 1 = 1 come from. A WHERE block replaces it: it ANDs together the predicates whose conditions hold, and a nested or { } or and { } switches the connective for the group inside it.

A group that contributes nothing disappears instead of leaving a dangling connective, and a group that contributes more than one predicate is parenthesised. When no predicate holds there is no WHERE at all, so there is no 1 = 1 to write, or to read in a log. Every branch's text is fixed at compile time; the only thing decided at run time is which branches are included, and the values are still bound as parameters.

Two things a WHERE block deliberately cannot do:

  • A column name or a sort direction can never be a parameter: ORDER BY {col} would sort every row by the same constant string. Make that choice a variant type and write one query per ordering, each answering with the same hive.sql.Fragment<Row[dyn]>.
  • SQL you really do assemble yourself goes through hive.sql.unsafe, which is untyped by design and easy to find.
type Colony {
	name:   Str
	apiary: Str
	frames: Int
}

query findColonies(apiary: Str, minFrames: Int, small: Bool, huge: Bool): Colony[dyn] {
	SELECT name, apiary, frames FROM colonies
	WHERE {
		if apiary != ""  { apiary = {apiary} }
		if minFrames > 0 { frames >= {minFrames} }
		or {
			if small { frames < 4 }
			if huge  { frames > 10 }
		}
	}
	ORDER BY name
}

proc main(): void {
	opened := hive.sql.pool(hive.sql.DatabaseDriver.SQLite(), "file::memory:?cache=shared", 1, 1)
	if opened is Result.Ok(db) {
		hive.sql.unsafe(db, "CREATE TABLE colonies (name TEXT, apiary TEXT, frames INTEGER)")
		hive.sql.unsafe(db, "INSERT INTO colonies VALUES ('north', 'orchard', 12)")
		hive.sql.unsafe(db, "INSERT INTO colonies VALUES ('south', 'orchard', 2)")
		hive.sql.unsafe(db, "INSERT INTO colonies VALUES ('east', 'meadow', 7)")

		// Everything off: no predicate holds, so there is no WHERE at all.
		if hive.sql.run(db, findColonies("", 0, false, false)) is Result.Ok(all) {
			echo len(all)
		}
		// apiary AND frames >= 5 AND (frames > 10).
		if hive.sql.run(db, findColonies("orchard", 5, false, true)) is Result.Ok(some) {
			echo some
		}
		hive.sql.close(db)
	}
}