AnyhowStep / tsql

A SQL query-builder/ORM
37 stars 3 forks source link

Potential hack for integer-safe addition in SQLite #253

Open AnyhowStep opened 4 years ago

AnyhowStep commented 4 years ago
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 commented 4 years ago

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

AnyhowStep commented 4 years ago

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 commented 4 years ago

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.