A tiny WHERE evaluator

To see why injection works, build the part of a database that reads a WHERE clause: comparisons joined by AND and OR, where AND binds tighter, and -- starts a comment.

What to build

Evaluate WHERE clauses over a small in-memory table and print the matching rows.

Requirements

  • Line 1: the column names, separated by spaces. Line 2: N, then N rows of values separated by spaces (values have no spaces or quotes).
  • Each remaining line is a WHERE clause, made of comparisons A = B joined by AND and OR (any case). A and B are column names or quoted strings like 'x' (where '' inside a string means one quote). There are no parentheses or NOT.
  • Everything from -- to the end of the line is a comment and is ignored.
  • AND binds tighter than OR, as in SQL.
  • For each clause print the matching rows' first-column values separated by spaces, no rows if none match, or error if the clause cannot be read (an unterminated string, an unknown column, or a missing part).

Input

As described.

Output

One line per clause.

Constraints

Up to 10 columns, 20 rows and 20 clauses.

Example

Input:

name pin
3
rahim 4821
anika 9302
admin 7777
name = 'rahim' AND pin = '4821'
name = '' OR '1'='1' --' AND pin = 'x'

Output:

rahim
rahim anika admin

Why it works

Splitting on OR first and then on AND gives AND the tighter binding, so a OR b AND c means a OR (b AND c); a quote in pasted input can end a string early and add a whole new OR branch, which is SQL injection.

Examples

Example 1 · Input
name pin
3
rahim 4821
anika 9302
admin 7777
name = 'rahim' AND pin = '4821'
name = '' OR '1'='1' --' AND pin = 'x'
Expected output
rahim
rahim anika admin
Example 2 · Input
name pin
3
rahim 4821
anika 9302
admin 7777
name = 'admin' --' AND pin = ''
name = 'rahim' AND pin = '0000'
Expected output
admin
no rows

Hints

Hint 1

Tokenize first: strings, words, and =.

Hint 2

An OR-list of AND-lists of comparisons is enough without parentheses: a row matches if any AND-list is fully true.

Solution

Show one correct solution (try it yourself first)
const columns = prompt().trim().split(/\s+/);
const n = Number(prompt());
const rows = [];
for (let k = 0; k < n; k++) rows.push(prompt().trim().split(/\s+/));
function tokenize(s) {
  const out = [];
  let i = 0;
  while (i < s.length) {
    if (s.startsWith("--", i)) break;
    const c = s[i];
    if (/\s/.test(c)) i++;
    else if (c === "=") { out.push({ t: "eq" }); i++; }
    else if (c === "'") {
      let v = "";
      i++;
      for (;;) {
        if (i >= s.length) throw new Error("string");
        if (s[i] === "'" && s[i + 1] === "'") { v += "'"; i += 2; }
        else if (s[i] === "'") { i++; break; }
        else v += s[i++];
      }
      out.push({ t: "str", v });
    } else if (/[A-Za-z0-9_]/.test(c)) {
      let w = "";
      while (i < s.length && /[A-Za-z0-9_]/.test(s[i])) w += s[i++];
      const u = w.toUpperCase();
      out.push(u === "AND" || u === "OR" ? { t: u } : { t: "id", v: w });
    } else throw new Error("char");
  }
  return out;
}
function parse(tokens) {
  const ors = [[]];
  let k = 0;
  const operand = () => {
    const x = tokens[k++];
    if (!x || (x.t !== "str" && x.t !== "id")) throw new Error("operand");
    if (x.t === "id" && !columns.includes(x.v)) throw new Error("column");
    return x;
  };
  for (;;) {
    const a = operand();
    if (!tokens[k] || tokens[k++].t !== "eq") throw new Error("eq");
    const b = operand();
    ors[ors.length - 1].push([a, b]);
    if (k >= tokens.length) break;
    const op = tokens[k++];
    if (op.t === "OR") ors.push([]);
    else if (op.t !== "AND") throw new Error("op");
  }
  return ors;
}
let line = prompt();
while (line !== null) {
  try {
    const ors = parse(tokenize(line));
    const val = (x, row) => (x.t === "str" ? x.v : row[columns.indexOf(x.v)]);
    const hits = rows.filter((row) => ors.some((ands) => ands.every(([a, b]) => val(a, row) === val(b, row))));
    console.log(hits.length ? hits.map((r) => r[0]).join(" ") : "no rows");
  } catch {
    console.log("error");
  }
  line = prompt();
}

▶ Open this solution in the compiler, then press Visualize to watch it run step by step

Lesson: SQL injection and parameterized queries →