;-------------------------------------------------------------------
; Procedures for convenient work with SQLite database angine.
;-------------------------------------------------------------------

;-------------------------------------------------------------------
; If the file in [.ptrFileName] exists, the function opens it.
; if the file does not exists, new database is created and the
; initialization script from [.ptrInitScript] is executed on it.
;
; Returns:
;    CF: 0 - database was open successfully
;      eax = 0 - Existing database was open successfuly.
;      eax = 1 - New database was created and init script was
;                executed successfully.
;      eax = 2 - New database was created but init script exits
;                with error.
;    CF: 1 - the database could not be open. (error)
;-------------------------------------------------------------------
proc OpenOrCreate, .ptrFileName, .ptrDatabase, .ptrInitScript
   .hSQL dd ?
.ptrNext dd ?
begin
        push    esi ebx

        mov     esi, [.ptrDatabase]
        cinvoke sqliteOpen, [.ptrFileName], esi
        test    eax, eax
        jz      .openok
        stc
        pop     esi
        return

.openok:
        xor     ebx, ebx
        cinvoke sqliteExec, [esi], .sqlCheckEmpty, .AbortCallback, ebx, ebx
        cmp     eax, SQLITE_ABORT
        je      .finish

        cinvoke sqliteExec, [esi], [.ptrInitScript], -1, ebx, ebx, ebx
        inc     ebx
        test    eax, eax     ; SQLITE_OK
        jz      .finish

        inc     ebx

.finish:
        cinvoke sqliteFinalize, [.hSQL]
        mov     eax, ebx
        clc
        pop     ebx esi
        return

.AbortCallback:
        xor     eax, eax
        inc     eax
        retn

.sqlCheckEmpty db 'select * from sqlite_master',0

endp
