Something went wrong. Try again.
SQL frontend over the catalog engine
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306(*--------------------------------------------------------------------------- Copyright (c) 2025 Thomas Gazagnaire. All rights reserved. SPDX-License-Identifier: ISC ---------------------------------------------------------------------------*)
open Ast
let pp_comma ppf () = Fmt.string ppf ", "
(* A name reads back as itself bare only where the lexer reads it as an identifier: every character is one an unquoted identifier holds, and the word is none of the lexer's keywords. *)let is_plain name = name <> "" && (match name.[0] with 'a' .. 'z' | 'A' .. 'Z' | '_' -> true | _ -> false) && String.for_all (function | 'a' .. 'z' | 'A' .. 'Z' | '0' .. '9' | '_' -> true | _ -> false) name && not (Lexer.is_keyword name)
let ident name = if String.contains name '\000' then invalid_arg "Render.ident: SQL text ends at a 0x00, so a name cannot hold one"; if is_plain name then name else "\"" ^ String.concat "\"\"" (String.split_on_char '"' name) ^ "\""
let pp_ident ppf name = Fmt.string ppf (ident name)
let pp_string ppf s = Fmt.pf ppf "'%s'" (String.concat "''" (String.split_on_char '\'' s))
let pp_hex ppf s = String.iter (fun c -> Fmt.pf ppf "%02x" (Char.code c)) s
let pp_float ppf f = if Float.is_nan f then Fmt.string ppf "NULL" else if f = Float.infinity then Fmt.string ppf "9.0e+999" else if f = Float.neg_infinity then Fmt.string ppf "-9.0e+999" else let s = Fmt.str "%.17g" f in if String.exists (function '.' | 'e' | 'E' -> true | _ -> false) s then Fmt.string ppf s else Fmt.pf ppf "%s.0" s
let pp_value ppf = function | Null -> Fmt.string ppf "NULL" | Int i -> Fmt.pf ppf "%Ld" i | Float f -> pp_float ppf f | Text s -> pp_string ppf s | Blob s -> Fmt.pf ppf "x'%a'" pp_hex s
let pp_binop ppf op = Fmt.string ppf (match op with | Eq -> "=" | Neq -> "<>" | Lt -> "<" | Le -> "<=" | Gt -> ">" | Ge -> ">=" | And -> "AND" | Or -> "OR" | Like -> "LIKE" | Glob -> "GLOB" | Add -> "+" | Sub -> "-" | Mul -> "*" | Div -> "/" | Mod -> "%" | Bit_and -> "&" | Bit_or -> "|" | Shl -> "<<" | Shr -> ">>" | Concat -> "||" | Json_get -> "->" | Json_get_text -> "->>")
(* The word a RAISE action is written with. REPLACE and Unspecified are not among the four RAISE takes; they reach here only from a hand-built node. *)let raise_action = function | Ignore -> "IGNORE" | Abort -> "ABORT" | Fail -> "FAIL" | Rollback -> "ROLLBACK" | Replace -> "REPLACE" | Unspecified -> "ABORT"
let pp_table_ref ppf (tr : table_ref) = match tr.alias with | None -> pp_ident ppf tr.name | Some a -> Fmt.pf ppf "%a %a" pp_ident tr.name pp_ident a
let pp_set_op ppf op = Fmt.pf ppf " %s " (Ast.set_op_keyword op)
let rec pp_expr ppf = function | Lit v -> pp_value ppf v (* the token as the source spelled it, which reparses as the same literal *) | Numeral s -> Fmt.string ppf s | Truth s -> Fmt.string ppf s (* The number is which bound value the placeholder reads, so it is written: rendered bare, two placeholders read in the reverse of the order they stand in come back reading in that order. [?NNN] is one-based (lang_expr.html#varparam) where the index here counts from zero, and a placeholder still carrying {!Param_number.unnumbered} has no number to write. *) | Param i when i < 0 -> Fmt.char ppf '?' | Param i -> Fmt.pf ppf "?%d" (i + 1) | Named_param s -> Fmt.string ppf s | Col (None, n) -> pp_ident ppf n | Col (Some t, n) -> Fmt.pf ppf "%a.%a" pp_ident t pp_ident n | Schema_col (s, t, n) -> Fmt.pf ppf "%a.%a.%a" pp_ident s pp_ident t pp_ident n | Star -> Fmt.char ppf '*' | Qualified_star q -> Fmt.pf ppf "%a.*" pp_ident q | Unop_not e -> Fmt.pf ppf "(NOT %a)" pp_expr e | Unary_plus e -> Fmt.pf ppf "+%a" pp_expr e | Unary_minus e -> let operand = Fmt.str "%a" pp_expr e in let sep = if String.starts_with ~prefix:"-" operand then " " else "" in Fmt.pf ppf "-%s%s" sep operand | Binary (op, a, b) -> Fmt.pf ppf "(%a %a %a)" pp_expr a pp_binop op pp_expr b | Is_null e -> Fmt.pf ppf "(%a IS NULL)" pp_expr e | Is_not_null e -> Fmt.pf ppf "(%a IS NOT NULL)" pp_expr e | Is (a, b) -> Fmt.pf ppf "(%a IS %a)" pp_expr a pp_expr b | In_list (e, l) -> Fmt.pf ppf "(%a IN (%a))" pp_expr e (Fmt.list ~sep:pp_comma pp_expr) l | In_select (e, s) -> Fmt.pf ppf "(%a IN (%a))" pp_expr e pp_select s | Scalar_select s -> Fmt.pf ppf "(%a)" pp_select s | Exists s -> Fmt.pf ppf "(EXISTS (%a))" pp_select s (* the collation is a name, so it is written by the renderer for one: bare where it can be, quoted where a bare spelling would be two tokens *) | Collate (e, c) -> Fmt.pf ppf "(%a COLLATE %a)" pp_expr e pp_ident c (* a stated affinity has no spelling: the expression reads as it is *) | Affinity (e, _) -> pp_expr ppf e (* The three CURRENT_* keywords are zero-argument calls with no argument list in the grammar, so they render as the bare word: written [f()] the output would not re-parse, here or through the sqlite3 CLI. *) | Func ((("current_timestamp" | "current_date" | "current_time") as name), []) -> Fmt.string ppf (String.uppercase_ascii name) | Raise (action, None) -> Fmt.pf ppf "RAISE(%s)" (raise_action action) | Raise (action, Some m) -> Fmt.pf ppf "RAISE(%s, %a)" (raise_action action) pp_expr m | Func (name, [ Star ]) -> Fmt.pf ppf "%a(*)" pp_ident name | Func (name, args) -> Fmt.pf ppf "%a(%a)" pp_ident name (Fmt.list ~sep:pp_comma pp_expr) args | Distinct_agg (name, e) -> Fmt.pf ppf "%a(DISTINCT %a)" pp_ident name pp_expr e | Filter (a, p) -> Fmt.pf ppf "%a FILTER (WHERE %a)" pp_expr a pp_expr p | Ordered_agg (Func (name, args), ob) -> Fmt.pf ppf "%a(%a ORDER BY %a)" pp_ident name (Fmt.list ~sep:pp_comma pp_expr) args (Fmt.list ~sep:pp_comma pp_order) ob | Ordered_agg (a, ob) -> Fmt.pf ppf "%a ORDER BY %a" pp_expr a (Fmt.list ~sep:pp_comma pp_order) ob | Window (a, w) -> Fmt.pf ppf "%a OVER (%a)" pp_expr a pp_window w (* and so is the type a CAST names *) | Cast (e, ty) -> Fmt.pf ppf "CAST(%a AS %a)" pp_expr e pp_ident ty | Case (base, branches, els) -> Fmt.pf ppf "(CASE"; (match base with None -> () | Some b -> Fmt.pf ppf " %a" pp_expr b); List.iter (fun (c, r) -> Fmt.pf ppf " WHEN %a THEN %a" pp_expr c pp_expr r) branches; (match els with None -> () | Some e -> Fmt.pf ppf " ELSE %a" pp_expr e); Fmt.pf ppf " END)"
(* The clauses of a window, each written only if it is there, in the order the grammar takes them: an empty specification is [OVER ()]. The frame is one of them -- it names which rows of the partition the function folds, so a window read back without it answers different numbers. *)and pp_window ppf (w : window) = let clause pp = function [] -> [] | l -> [ Fmt.str "%a" pp l ] in let parts = clause (fun ppf l -> Fmt.pf ppf "PARTITION BY %a" (Fmt.list ~sep:pp_comma pp_expr) l) w.partition @ clause (fun ppf l -> Fmt.pf ppf "ORDER BY %a" (Fmt.list ~sep:pp_comma pp_order) l) w.order @ match w.frame with None -> [] | Some f -> [ Fmt.str "%a" pp_frame f ] in Fmt.string ppf (String.concat " " parts)
(* Both bounds, always: the single-bound spelling ([RANGE UNBOUNDED PRECEDING]) is the [BETWEEN lo AND CURRENT ROW] it desugars to at the parser (parse.y's [frame_opt ::= range_or_rows frame_bound_s]), and what the AST holds is that frame rather than the words it was written in. *)and pp_frame ppf (f : frame) = Fmt.pf ppf "%s BETWEEN %a AND %a" (if f.rows then "ROWS" else "RANGE") pp_frame_bound f.start pp_frame_bound f.end_
and pp_frame_bound ppf = function | Unbounded_preceding -> Fmt.string ppf "UNBOUNDED PRECEDING" | Preceding e -> Fmt.pf ppf "%a PRECEDING" pp_expr e | Current_row -> Fmt.string ppf "CURRENT ROW" | Following e -> Fmt.pf ppf "%a FOLLOWING" pp_expr e | Unbounded_following -> Fmt.string ppf "UNBOUNDED FOLLOWING"
and pp_result_col ppf (rc : result_col) = match rc.alias with | None -> pp_expr ppf rc.expr | Some a -> Fmt.pf ppf "%a AS %a" pp_expr rc.expr pp_ident a
and pp_order ppf (e, dir) = Fmt.pf ppf "%a%s" pp_expr e (match dir with Asc -> "" | Desc -> " DESC")
and pp_join ppf j = let kw = match j.type_ with | Inner -> "JOIN" | Cross -> "CROSS JOIN" | Semi _ -> "EXISTS JOIN" | Left -> "LEFT JOIN" | Right -> "RIGHT JOIN" | Full -> "FULL OUTER JOIN" in if j.natural then Fmt.pf ppf " NATURAL %s %a" kw pp_table_ref j.table else if j.using <> [] then Fmt.pf ppf " %s %a USING (%a)" kw pp_table_ref j.table (Fmt.list ~sep:pp_comma pp_ident) j.using else match j.on with | None -> Fmt.pf ppf " %s %a" kw pp_table_ref j.table | Some on -> Fmt.pf ppf " %s %a ON %a" kw pp_table_ref j.table pp_expr on
and pp_from ppf : Ast.from_clause -> unit = function | Unit -> () | Table tr -> pp_table_ref ppf tr | Select { fs_select; fs_alias } -> ( match fs_alias with | None -> Fmt.pf ppf "(%a)" pp_select fs_select | Some a -> Fmt.pf ppf "(%a) %a" pp_select fs_select pp_ident a) | Values rows -> let pp_tuple ppf t = Fmt.pf ppf "(%a)" (Fmt.list ~sep:pp_comma pp_expr) t in Fmt.pf ppf "(VALUES %a)" (Fmt.list ~sep:pp_comma pp_tuple) rows | Table_function { tf_name; tf_args; tf_alias } -> Fmt.pf ppf "%a(%a)" pp_ident tf_name (Fmt.list ~sep:pp_comma pp_expr) tf_args; Option.iter (fun a -> Fmt.pf ppf " %a" pp_ident a) tf_alias
and pp_cte ppf (c : Ast.cte) = match c.columns with | [] -> Fmt.pf ppf "%a AS (%a)" pp_ident c.name pp_select c.query | cols -> Fmt.pf ppf "%a (%a) AS (%a)" pp_ident c.name (Fmt.list ~sep:pp_comma pp_ident) cols pp_select c.query
(* A core: SELECT cols / FROM / WHERE / GROUP BY, no WITH / compound / ORDER BY / LIMIT (those wrap the whole compound). *)and pp_core ppf s = Fmt.pf ppf "SELECT %s%a" (if s.distinct then "DISTINCT " else "") (Fmt.list ~sep:pp_comma pp_result_col) s.cols; (match s.from with Unit -> () | f -> Fmt.pf ppf " FROM %a" pp_from f); Fmt.pf ppf "%a" (Fmt.list ~sep:Fmt.nop pp_join) s.joins; (match s.where with None -> () | Some w -> Fmt.pf ppf " WHERE %a" pp_expr w); (match s.group_by with | [] -> () | l -> Fmt.pf ppf " GROUP BY %a" (Fmt.list ~sep:pp_comma pp_expr) l); match s.having with None -> () | Some h -> Fmt.pf ppf " HAVING %a" pp_expr h
and pp_select ppf s = (match s.ctes with | [] -> () | l -> Fmt.pf ppf "WITH %a " (Fmt.list ~sep:pp_comma pp_cte) l); pp_core ppf s; List.iter (fun (op, arm) -> pp_set_op ppf op; pp_core ppf arm) s.compound; (match s.order_by with | [] -> () | l -> Fmt.pf ppf " ORDER BY %a" (Fmt.list ~sep:pp_comma pp_order) l); (match s.limit with None -> () | Some n -> Fmt.pf ppf " LIMIT %a" pp_expr n); match s.offset with None -> () | Some o -> Fmt.pf ppf " OFFSET %a" pp_expr o
let pp_default_clause ppf e = match e with | Lit _ | Truth _ | Numeral _ | Func (("current_timestamp" | "current_date" | "current_time"), []) (* pp_expr parenthesises each of these itself *) | Unop_not _ | Binary _ | Is_null _ | Is_not_null _ | Is _ | In_list _ | In_select _ | Scalar_select _ | Exists _ | Collate _ | Case _ -> pp_expr ppf e | Param _ | Named_param _ | Col _ | Schema_col _ | Star | Qualified_star _ | Raise _ | Func _ | Distinct_agg _ | Filter _ | Ordered_agg _ | Window _ | Cast _ | Unary_plus _ | Unary_minus _ | Affinity _ -> Fmt.pf ppf "(%a)" pp_expr e
let expr e = Fmt.str "%a" pp_expr elet default_clause e = Fmt.str "%a" pp_default_clause elet select s = Fmt.str "%a" pp_select s