tsql icon indicating copy to clipboard operation
tsql copied to clipboard

Potential hack for integer-safe addition in SQLite

Open AnyhowStep opened this issue 5 years ago • 3 comments
trafficstars

SELECT 
9223372036854775807,
9223372036854775807+9223372036854775807, -- Casts to real and gives lossy result
typeof(9223372036854775807),
typeof(9223372036854775807+9223372036854775807);

SELECT
(SELECT SUM(x) FROM (SELECT 9223372036854775807 AS x UNION ALL SELECT 9223372036854775807)); -- integer overflow error

According to the SQLite documentation, https://www.sqlite.org/lang_aggfunc.html

Sum() will throw an "integer overflow" exception if all inputs are integers or NULL and an integer overflow occurs at any point during the computation.

AnyhowStep avatar Feb 18 '20 21:02 AnyhowStep

We are abusing an aggregate function, derived table, and compound query just to get integer overflow errors...

AnyhowStep avatar Feb 18 '20 21:02 AnyhowStep

I don't know what madness inspired me to come up with this workaround. I regret it now because I'm seriously considering this...

user-defined functions are more "elegant" but it means having to always create it, and the AST isn't technically portable unless the special bigint_add() function is added to every SQLite database you want to run the query on

AnyhowStep avatar Feb 18 '20 21:02 AnyhowStep

We want a throw-on-overflow addition operator, and not a cast-on-overflow operator, because of this,

SELECT
(9223372036854775807+9223372036854775807)/9973

This should throw. But on SQLite, we get 1849668512354311.8

It is decidedly not an integer.

AnyhowStep avatar Feb 18 '20 21:02 AnyhowStep