 ! Copyright (C) 2007, 2008 Alex Chapman
 ! See http://factorcode.org/license.txt for BSD license.
-USING: arrays assocs kernel math namespaces sequences sqlite ;
+USING: arrays assocs kernel math namespaces new-slots sequences sqlite ;
 IN: semantic-db.db
 
 ! sqlite utils

        "select" , dup fields-sql , dup "from" , tables-sql , conditions-sql ,
    ] { } make " " join ;

: prepare-query ( query -- )
    [ query-sql prepare ] keep set-query-statement ;

: bind-query ( query -- )
    dup query-args over query-statement bindings swap set-query-statement ;

: (retrieve) ( statement query -- result )
    query-fields swap [ field-retriever call ] curry each ;

: retrieve ( query -- )
    dup query-statement over [ (retrieve) ] curry sqlite-map
    swap set-query-results ;
   ! dup query-statement over query-retriever sqlite-map swap set-query-results ;

: finalize-query ( query -- )
    query-statement dup sqlite-finalize f swap set-query-statement ;

PRIVATE>
    

    query construct-boa ;

: invalidate-query ( query -- query )
    f >>results ;

: add-field ( field query -- query )
    dup invalidate-query fields>> push ;

: add-table ( table query -- query )
    dup invalidate-query tables>> push ;

: add-condition ( condition query -- query )
    tuck invalidate-query conditions>> push ;

: add-arg ( arg key query -- query )
    [ invalidate-query args>> set-at ] keep ;

<PRIVATE

: field-sql ( field -- sql )
    [ dup table>> % CHAR: . , name>> % ] "" make ;

: fields-sql ( query -- sql )
    fields>> dup length [
        [ field-sql ] map ", " join
    ] [
        drop "*"
    ] if ;

: tables-sql ( query -- sql )
    tables>> ", " join ;

: conditions-sql ( query -- sql )
    conditions>> dup length [
        " and " join "where " swap append
    ] [
        drop ""
