EvgSkv / logica

Logica is a logic programming language that compiles to SQL. It runs on DuckDB, Google BigQuery, PostgreSQL and SQLite.
https://logica.dev
Apache License 2.0
1.77k stars 93 forks source link

Even numbers (in tutorial) does not work for sqlite #149

Open RAbraham opened 3 years ago

RAbraham commented 3 years ago

Hi, If I run this, I don't get even numbers.

%%logica Even
@Engine("sqlite");

Z(x) :- x in Range(20);

Even(x) :- Z(x), Z(x / 2);
print('Even numbers:', ', '.join(map(str, Even['col0'])))
Even numbers: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19

This is the generated SQL:

The following query is stored at Even_sql variable.
SELECT
  x_4.value AS col0
FROM
  JSON_EACH((select json_group_array(n) from (with recursive t as(select 0 as n union all select n + 1 as n from t where n + 1 < 20) select n from t))) as x_4, JSON_EACH((select json_group_array(n) from (with recursive t as(select 0 as n union all select n + 1 as n from t where n + 1 < 20) select n from t))) as x_6
WHERE
  (x_6.value = ((x_4.value) / (2)));
EvgSkv commented 3 years ago

Apparently this is because integer division in SQLite results in an integer number. To make example work we need to do it as follows:

%%logica Even
@Engine("sqlite");

Z(x) :- x in Range(20);

Even(x) :- Z(x), Z(x / 2.0);

We should either change the original (because this form works in BQ as well), or create a standalone SQLite tutorial.

RAbraham commented 3 years ago

changing the original works 👍 . fyi, this happens in postgres too. I'll leave this open if you like to use it as a bookmark but please feel free to close it.