CLEAR ALL
PRINT LINE CENTER "SQLite Database Interface",,RGB(0,0,255)
PRINT

db$="Chinook.db"
DB 1 OPEN db$ 'LOG "db.log"
printTables()
PRINT

PRINT "Enter a SQL command, TABLES to print tables, DESC <table> to describe a table, or nothing to quit."
DO
    INK RGB(255,255,0)
    LINE INPUT "> ";sql$
    c$=LCASE$(TRIM$(sql$))
    IF c$="" THEN
        DB 1 CLOSE:END
    ELSE IF c$="tables" THEN
        printTables()
    ELSE IF LEFT$(c$,5)="desc " THEN
        describe(LTRIM$(MID$(LTRIM$(sql$),6)))
    ELSE
        runSQL(sql$,0)
    END IF
LOOP

FUNCTION printTables()
    SHARE db$
    INK RGB(0,255,0)
    PRINT db$
    INK RGB(255,255,255)
    t$=DB.ALLTABLES$(1)
    FOR i=1 TO PARSECOUNT(t$)
        PRINT "    " PARSE$(t$,i)
    NEXT i
END FUNCTION

FUNCTION describe(t$)
    INK RGB(255,128,0)
    PRINT t$
    runSQL("SELECT name,type FROM pragma_table_info('"+t$+"')",4)
END FUNCTION

FUNCTION runSQL(sql$,t)
    DB 1 QUERY sql$
    e$=DB.ERROR$(1)
    IF e$="" THEN
        INK RGB(255,255,255)
        DO
            DB 1 READ NEXT
            IF EOQ(1) THEN EXIT DO
            PRINT TAB(t);
            FOR i=1 TO DB.FIELDCOUNT(1)-1
                PRINT DB.VALUE$(1,i) ",";
            NEXT i
            PRINT DB.VALUE$(1,i)
        LOOP
    ELSE
        INK RGB(255,0,0)
        PRINT e$
    END IF
END FUNCTION
