Skip to content

Commit

Permalink
Merge pull request #3643 from mathesar-foundation/bigint_casting_code…
Browse files Browse the repository at this point in the history
…_std

Add SQL code standard for casting OIDs to bigint
  • Loading branch information
mathemancer authored Jun 27, 2024
2 parents 90309d0 + b67da61 commit 518cede
Showing 1 changed file with 23 additions and 0 deletions.
23 changes: 23 additions & 0 deletions db/sql/STANDARDS.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,4 +58,27 @@ From [OWASP](https://owasp.org/www-project-proactive-controls/v3/en/c4-encode-es

Always qualify system catalog tables by prefixing them with `pg_catalog.`. If you don't, then user-defined tables can shadow the system catalog tables, breaking core functionality.

## Casting OIDs to JSON

Always cast OID values to `bigint` before putting them in JSON (or jsonb).

_Don't_ cast OID values to `integer`.

This is because the [`oid` type](https://www.postgresql.org/docs/current/datatype-oid.html) is an _unsigned_ 32-bit integer whereas the `integer` type is a _signed_ 32-bit integer. That means it's possible for a database to have OID values which don't fit into the `integer` type.

For example, putting a large OID value into JSON by casting it to an integer will cause overflow:

```SQL
SELECT jsonb_build_object('foo', 3333333333::oid::integer); -- ❌ Bad
```

> `{"foo": -961633963}`
Instead, cast it to `bigint`

```SQL
SELECT jsonb_build_object('foo', 3333333333::oid::bigint); -- ✅ Good
```

> `{"foo": 3333333333}`

0 comments on commit 518cede

Please sign in to comment.