question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Raw queries with count() selected return strange non integer values

See original GitHub issue

Bug description

While trying to work around this bug https://github.com/prisma/prisma/issues/14539 I noticed strange behavior when selected count().

How to reproduce

The following query:

const tagsWithCount = await prisma.$queryRawUnsafe<any[]>(`
      SELECT 
        t.id,
        t.name,
        t.path,
        COUNT(s.id) as _count
      FROM tags t
      LEFT JOIN posts_tags st on t.id = st.tag_id 
      LEFT JOIN posts s ON st.post_id = s.id
      GROUP BY
        t.id, 
        t.name, 
        t.path
      ORDER BY
        _count DESC
`)

returns rows like this:

{ 
id: 1, 
name: 'tag1', 
path: 'tag1', 
_count: 319n 
}

You may see that the _count field is not really integer. It has a strange suffix - “n”.

Expected behavior

The _count field in the resulting data set should only contain integer values.

Prisma information

model Post {
  id                      Int           @id @default(autoincrement()) @db.UnsignedInt
 
  postTags          PostTag[]

  @@map("posts")
}
model Tag {
  id                      Int             @id @default(autoincrement()) @db.UnsignedInt
  
  postTags           PostTag[]

  @@map("tags")
}

model PostTag {
  postId                 Int             @map("post_id") @db.UnsignedInt
  tagId                   Int             @map("tag_id") @db.UnsignedInt

  post                   Post           @relation(fields: [postId], references: [id], onDelete: Cascade)
  tag                     Tag             @relation(fields: [tagId], references: [id], onDelete: Cascade)

  @@id([postId, tagId])

  @@map("posts_tags")
}

Environment & setup

  • OS: Docker: node:16-alpine (Linux)
  • Database: Docker: mariadb:10.7
  • Node.js version: v16.14.2

Prisma Version

    "@prisma/client": "^4.1.1"
    "prisma": "^4.1.1"

Issue Analytics

  • State:open
  • Created a year ago
  • Reactions:1
  • Comments:13 (5 by maintainers)

github_iconTop GitHub Comments

2reactions
janpiocommented, Sep 8, 2022

I don’t think that your table column types are relevant here @kkomelin. You are asking your database to return the result of COUNT() and that is indeed bigint for MariaDB: https://mariadb.com/kb/en/count/ In Javascript bigints can not be represented with normal Numbers, hence the Bigint as well on that side. Everything else would lead to potentially invalid data - and that is the one thing that is unacceptable for a ORM.

Prisma can not do better than to highlight specific thigns in the docs that might be unexpected (although technically correct and logical) to our users. In my discussion with @SevInf I basically tried to figure out if that is the case and worth the effort here. I could imagine a sentence “Note that if you use an aggregate function like COUNT() in SQL on some providers you might get a bigint value which initially might be not intuitive, but matches what the database returns.” and then a link to maybe how to handle strange bigint numbers.

2reactions
dariusj18commented, Aug 21, 2022

This is because Prisma now “correctly” creates counts as bigint’s (int64) which is what mariadb/mysql and postgres return them as by default. BigInt is not fully supported, ex. I you try and serialize it nodejs’s default JSON serializer will throw an error.

I just ran into this, my solution is to cast the count as a string.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Flask-SQLAlchemy different record count for .count() and .all()
My query do multiple Joins, than the raw result can bring back multiple rows of the same primary key, each row is counted...
Read more >
Group By, Having & Count - Kaggle
COUNT() is an example of an aggregate function, which takes many values and returns one. (Other examples of aggregate functions include SUM(), AVG(),...
Read more >
SQL SELECT statement with COUNT() function - DigitalOcean
SQL SELECT COUNT() function can be used along with DISTINCT clause to count and display the number of rows representing unique(non-repeated)  ...
Read more >
Database Engine events and errors - SQL Server
The number of SELECT values must match the number of INSERT columns. ... 525, 16, No, The column that was returned from the...
Read more >
Bit Twiddling Hacks - Stanford Computer Graphics Laboratory
Computing parity (1 if an odd number of bits set, 0 otherwise) ... Select the bit position (from the most-significant bit) with the...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found