#!../src/tops  -s ../sys  -u ../usr

"sql" missing
IF 
    # "tops not compiled with SQLITE; cannot run sql" . nl
    halt 
THEN

# Make some temp file names, delete them if they already exist.
time "/tmp/sql_a_%lld.db" format is TMPDB_1
time "/tmp/sql_b_%lld.db" format is TMPDB_2
"/bin/rm -f " TMPDB_1 cat shell
"/bin/rm -f " TMPDB_2 cat shell

# create a database from an empty file
"/bin/touch " TMPDB_1 cat shell
TMPDB_1 db_open is DBH
DBH "create table A(n text, i integer, x float)"  sql
DBH "insert into A values('first',  1,  1.1    )" sql
DBH "insert into A values('second', 2, -2.1    )" sql
DBH "insert into A values('third',  3,  3.14159)" sql
DBH "insert into A values('fourth', 4,  4.5E-6 )" sql

# Select a single row.  All results should be scalars.
DBH "select * from A where i = 2" sql
3 = IF  # expecting three stack items from the query (not counting this value)
    'second' <> IF         # 1st query result should be string 'second'
        "sql: query failure -- expected string 'second' " . nl
        HALT
    ELSE
        "sql: 1 OK" . nl
    THEN
    2 <> IF                # 2nd query result should be integer '2'
        "sql: query failure -- expected integer '2' " . nl
        HALT
    ELSE
        "sql: 2 OK" . nl
    THEN
    2.1 + abs 1.0E-9 > IF  # 3rd query result should be float '-2.1'
        "sql: query failure -- expected float '-2.1' " . nl
        HALT
    ELSE
        "sql: 3 OK" . nl
    THEN
ELSE
    "sql: query 1 failure -- bad result count" . nl
    HALT
THEN

# Select the integer values.  Should get back the vector [1, 2, 3, 4].
DBH "select i from A order by i" sql ( 1 list_1_to_4 )
1 = IF  # expecting one stack item from the query (not counting this value)
    1 4 uniform 1 + #  ( list_1_to_4 --- list_1_to_4 [1, 2, 3, 4] )
    -               #  ( [0, 0, 0, 0] )
    abs maxfetch drop drop
    0= IF
        "sql: 4 OK" . nl
    ELSE
        "sql: query failure -- expected array [1, 2, 3, 4] " . nl
        HALT
    THEN
ELSE
    "sql: query 2 failure -- bad result count" . nl
    HALT
THEN

DBH db_close

"/bin/rm -f " TMPDB_1 cat shell
"/bin/rm -f " TMPDB_2 cat shell
