korma / Korma

Tasty SQL for Clojure.
http://sqlkorma.com
1.47k stars 222 forks source link

Selecting the count of a table #325

Closed Banashek closed 9 years ago

Banashek commented 9 years ago

So I'm writing some tests, and I just want to select the count of my users table while testing to make sure my delete-user function works.

Here is the migration:

CREATE TABLE IF NOT EXISTS users
(id serial PRIMARY KEY,
 name text UNIQUE,
 pass text );

Here is the entity:

(declare users)

(defentity users
  (pk :id)
  (table :users)
  (entity-fields :name :pass))

Here is what I'm trying to run:

(select e/users (aggregate (count :*) :cnt))

Here is the error I'm getting:

PSQLException ERROR: column "users.name" must appear in the GROUP BY clause or be used in an aggregate function

Korma is generating this sql:

"SELECT \"users\".\"name\", \"users\".\"pass\", COUNT(\"users\".*) AS \"cnt\" FROM \"users\""

And here is the sql that deep down I really want to run (or some variation of course):

select count(*) from users;

Is there a way via korma that I can run this? An ad-hoc sql would be good as well.

Or should I just figure out a different way to run ad-hoc sql in my app?

Thanks.

immoh commented 9 years ago

The fields defined as entity-fields will be always included in the result set, so you need to remove it from entity definition.

You can achieve the same by not using entity for your query but keyword table name instead:

(select :users (aggregate (count :*) :cnt))

or run ad hoc sql using exec-raw:

(exec-raw "select count(*) from users")
Banashek commented 9 years ago

Awesome!

That was exactly what I needed.

Thank you for the prompt and helpful answer.