cornucopia-rs / cornucopia

Generate type-checked Rust from your PostgreSQL.
Other
755 stars 31 forks source link

Query parser doesn't ignore embedded comments #239

Open jgallagher opened 2 months ago

jgallagher commented 2 months ago

Hi! I tried to give cornucopia a spin with some fairly involved queries, and got some strange errors back. I think the cause is that I tried to use a query with several comments embedded in it, and cornucopia seems to try to parse those as SQL, which can throw all kinds of things off. Some simple examples based on this query (which is obviously fine):

--! foo
SELECT :foo::int8;

If we add a comment with a colon, cornucopia no longer realizes that :foo is a bind parameter:

--! foo
SELECT
  -- comment with a colon:
  :foo::int8;
Error:   × Couldn't prepare query: db error: ERROR: at or near ":": syntax error
  │ DETAIL: source SQL:
  │ SELECT
  │   -- comment with a colon:
  │   :foo::int8
  │   ^
  │ HINT: try \h SELECT
   ╭─[queries/rack.sql:1:1]
 1 │ --! foo
   ·     ─┬─
   ·      ╰── error occurs near this location
 2 │ SELECT
   ╰────

If we add a comment with a semicolon, cornucopia thinks that ends the query:

--! foo
SELECT
  -- comment with a semicolon; then more comment text
  :foo::int8;
Error:   × Couldn't parse queries
   ╭─[queries/rack.sql:2:1]
 2 │ SELECT
 3 │   -- comment with a semicolon; then more comment text
   ·                                ┬
   ·                                ╰── unexpected token
 4 │   :foo::int8;
   ╰────
  help: found 't' but one of end of input, - was expected

I took a very brief look at parse_sql_query, but am not familiar enough with chumsky to suggest a fix - sorry!