Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

CASE expression and integer typing #97

Closed
suhabe opened this issue Oct 11, 2021 · 3 comments
Closed

CASE expression and integer typing #97

suhabe opened this issue Oct 11, 2021 · 3 comments

Comments

@suhabe
Copy link

suhabe commented Oct 11, 2021

The following go-jet code is giving the error below on Postgres:

	var dest[]struct {
		NumPassed int64
	}
	
	err := SELECT(SUM(CASE().WHEN(Benchmark.Passed.IS_TRUE()).
				THEN(Int(1)).
				ELSE(Int(0))).AS("num_passed")).
		FROM(Benchmark).
		Query(tx, &dest)
pq: function sum(text) does not exist

It seems like its interpreting the CASE expression as a string when it should interpret it as Int. When I print out the SQL statement using DebugSql() and copy/paste it directly into Postgres's client, it works correctly. But through go-jet, I get the error above.

 db=# select SUM((CASE WHEN benchmark.passed THEN 1 ELSE 2 END)) AS "num_passed" from benchmark;

 num_passed 
------------
         12

(1 row)
@go-jet
Copy link
Owner

go-jet commented Oct 11, 2021

.DebugSql() is not the statement executed with Query(tx, &dest). It's parameterized statement returned with .Sql(). In parameterized statement ints are replaced with placeholder, and in situations like this, postgres interpreter does not have enough information to deduce the type of the CASE expression. Solution would be to cast CASE expression to integer:

SUM(
    CAST(CASE .....).AS_INTEGER(),
)

@suhabe
Copy link
Author

suhabe commented Oct 11, 2021

That worked! Thank you very much.

@suhabe suhabe closed this as completed Oct 11, 2021
@go-jet go-jet mentioned this issue Jan 20, 2022
@go-jet
Copy link
Owner

go-jet commented Jan 20, 2022

With the Release 2.7.0, expression casting can be avoided by using one of the bit specific integer literal constructor - Int8, Uint8, Int16 etc...
These literal constructor will automatically add a type cast for postgres queries.

err := SELECT(SUM(CASE().WHEN(Benchmark.Passed.IS_TRUE()).
			THEN(Int32(1)).
			ELSE(Int32(0))).AS("num_passed")).
	FROM(Benchmark).
	Query(tx, &dest)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants