sqlc-dev / sqlc

Generate type-safe code from SQL
https://sqlc.dev
MIT License
13.51k stars 810 forks source link

Parameter parser can't handle some math operators #3674

Open artnez opened 3 weeks ago

artnez commented 3 weeks ago

Version

1.27.0

What happened?

Let's start with what actually works:

select * from users where age = $1 + $2;

Say we wanted the parameters to be named. This also works:

select * from users where age = sqlc.arg(a) + sqlc.arg(b);

However, this breaks the parser:

select * from users where age = @first + @second;

'edited query syntax is invalid: syntax error at or near "nd"'

Ok. We'll want to cast these named parameters anyway. So let's try that:

select * from users where age = @first::integer + @second::integer;

'edit stop location is out of bounds'

PC LOAD LETTER? What does that mean?

What if we mangle our SQL to get sqlc to work? (no stranger to that!)

select * from users where age = cast(@first as integer) + cast(@second as integer);

We Did It™ 🎉

It seems like the parser doesn't like certain operators but handles others just fine. Let's go through a list of Postgres operators: https://www.postgresql.org/docs/7.4/functions-math.html

select * from users where age = @first + @second; -- broken
select * from users where age = @first - @second; -- broken
select * from users where age = @first * @second; -- broken
select * from users where age = @first / @second; -- broken
select * from users where age = @first % @second; -- broken
select * from users where age = @first ^ @second; -- broken
select * from users where age = @first |/ @second; -- works (also, TIL)
select * from users where age = @first ||/ @second; -- works
select * from users where age = @first ! @second; -- works
select * from users where age = @first !! @second; -- works
select * from users where age = @first @ @second; -- broken... hmmm...
select * from users where age = @first & @second; -- works
select * from users where age = @first | @second; -- works
select * from users where age = @first # @second; -- works
select * from users where age = @first ~ @second; -- works
select * from users where age = @first << @second; -- works
select * from users where age = @first >> @second; -- works

Relevant log output

No response

Database schema

No response

SQL queries

No response

Configuration

No response

Playground URL

No response

What operating system are you using?

No response

What database engines are you using?

No response

What type of code are you generating?

No response