LuaSQLite3

Changes On Branch session
Login

Many hyperlinks are disabled.
Use anonymous login to enable hyperlinks.

Changes In Branch session Excluding Merge-Ins

This is equivalent to a diff from ba0ad5e0f0 to e84f306d86

2023-06-23
21:43
Add support for comercial CEROD feature if available

Contributed by: Rudolf Adamkovič check-in: ffcc9234f0 user: javier tags: trunk

2023-05-12
04:53
Update de/serialize to report errors and only be available when configured. Leaf check-in: e84f306d86 user: paulclinger tags: session
04:51
Update to compile with Lua 5.1. check-in: 6ece6d4ed6 user: paulclinger tags: session
2022-11-28
00:26
[Author: Paul K.] Add session support.

Apply patch "as is" from the github diff. check-in: 062ecf97a5 user: javier tags: session

2021-09-07
13:51
Link to slqlite docs on multiple library copies. check-in: ba0ad5e0f0 user: javier tags: trunk
13:20
Add note warning against statically linking separate copies of SQLite. check-in: 21108a8672 user: javier tags: trunk

Added examples/session.lua.




































































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34

local function showdata(db)
	for r in db:nrows("select * from foo") do print("select: ", r.k,
			r.a, r.b, r.c)
	end
end


local sqlite3 = require("lsqlite3")
local db = sqlite3.open_memory()
local ses = db:create_session()

print("create", db:exec("create table foo(k primary key, a, b, c)"))
print("insert", db:exec("insert into foo(k, a, b, c) values (1, 'v1', 'v1', 'v1')"))

ses:attach()
print("update/1", db:exec("update foo set a = 'v2', b = 'v2' where k = 1"))
showdata(db)
local cs2 = ses:changeset()

print("update/2", db:exec("update foo set a = 'v3', b = 'v1' where k = 1"))
showdata(db)
local cs3 = ses:changeset()

print("apply1/abort", db:apply_changeset(cs2,
	function(...) print("filter", ...) return 1 end,
	function(...) print("conflict", ...) return sqlite3.CHANGESET_ABORT end))
showdata(db)

local cs4 = db:concat_changeset { db:invert_changeset(cs3), cs2, cs3 }
print("apply2/no-conflict", db:apply_changeset(cs4,
	function(...) print("filter", ...) return 1 end,
	function(...) print("conflict", ...) return sqlite3.CHANGESET_REPLACE end))
showdata(db)
Changes to lsqlite3-0.9.5-1.rockspec.
25
26
27
28
29
30
31

32



33
34
35
36
37
38
39
    }
}
build = {
    type = "builtin",
    modules = {
        lsqlite3 = {
            sources = { "lsqlite3.c" },

            defines = {'LSQLITE_VERSION="0.9.5"'},



            libraries = { "sqlite3" },
            incdirs = { "$(SQLITE_INCDIR)" },
            libdirs = { "$(SQLITE_LIBDIR)" }
        },
    },
	copy_directories = { 'doc', 'examples' }
}







>
|
>
>
>







25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
    }
}
build = {
    type = "builtin",
    modules = {
        lsqlite3 = {
            sources = { "lsqlite3.c" },
            defines = {
                'LSQLITE_VERSION="0.9.5"',
                'SQLITE_ENABLE_SESSION',
                'SQLITE_ENABLE_PREUPDATE_HOOK'
            },
            libraries = { "sqlite3" },
            incdirs = { "$(SQLITE_INCDIR)" },
            libdirs = { "$(SQLITE_LIBDIR)" }
        },
    },
	copy_directories = { 'doc', 'examples' }
}
Changes to lsqlite3.c.
25
26
27
28
29
30
31

32
33
34
35


















36
37
38
39
40
41
42
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE     *
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                *
************************************************************************/

#include <stdlib.h>
#include <string.h>
#include <assert.h>


#define LUA_LIB
#include "lua.h"
#include "lauxlib.h"



















#if LUA_VERSION_NUM > 501
/*
** Lua 5.2
*/
#ifndef lua_strlen
#define lua_strlen lua_rawlen







>




>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE     *
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                *
************************************************************************/

#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <stdbool.h>

#define LUA_LIB
#include "lua.h"
#include "lauxlib.h"

#define STR_HELPER(x) #x
#define STR(x) STR_HELPER(x)

#if LUA_VERSION_NUM < 502
/*
** Lua 5.1 (or LuaJIT)
*/

#ifndef LUA_OK
#define LUA_OK 0
#endif

#ifndef luaL_len
#define luaL_len lua_objlen
#endif

#endif

#if LUA_VERSION_NUM > 501
/*
** Lua 5.2
*/
#ifndef lua_strlen
#define lua_strlen lua_rawlen
106
107
108
109
110
111
112



113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130











131
132
133
134
135
136
137
    int progress_cb;    /* progress handler */
    int progress_udata;

    int trace_cb;       /* trace callback */
    int trace_udata;

#if !defined(LSQLITE_OMIT_UPDATE_HOOK) || !LSQLITE_OMIT_UPDATE_HOOK




    int update_hook_cb; /* update_hook callback */
    int update_hook_udata;

    int commit_hook_cb; /* commit_hook callback */
    int commit_hook_udata;

    int rollback_hook_cb; /* rollback_hook callback */
    int rollback_hook_udata;

#endif
};

static const char *sqlite_meta      = ":sqlite3";
static const char *sqlite_vm_meta   = ":sqlite3:vm";
static const char *sqlite_bu_meta   = ":sqlite3:bu";
static const char *sqlite_ctx_meta  = ":sqlite3:ctx";
static int sqlite_ctx_meta_ref;












/* Lua 5.3 introduced an integer type, but depending on the implementation, it could be 32 
** or 64 bits (or something else?). This helper macro tries to do "the right thing."
*/

#if LUA_VERSION_NUM > 502
#define PUSH_INT64(L,i64in,fallback) \







>
>
>


















>
>
>
>
>
>
>
>
>
>
>







125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
    int progress_cb;    /* progress handler */
    int progress_udata;

    int trace_cb;       /* trace callback */
    int trace_udata;

#if !defined(LSQLITE_OMIT_UPDATE_HOOK) || !LSQLITE_OMIT_UPDATE_HOOK

    int wal_hook_cb;    /* wal_hook callback */
    int wal_hook_udata;

    int update_hook_cb; /* update_hook callback */
    int update_hook_udata;

    int commit_hook_cb; /* commit_hook callback */
    int commit_hook_udata;

    int rollback_hook_cb; /* rollback_hook callback */
    int rollback_hook_udata;

#endif
};

static const char *sqlite_meta      = ":sqlite3";
static const char *sqlite_vm_meta   = ":sqlite3:vm";
static const char *sqlite_bu_meta   = ":sqlite3:bu";
static const char *sqlite_ctx_meta  = ":sqlite3:ctx";
static int sqlite_ctx_meta_ref;
#ifdef SQLITE_ENABLE_SESSION
static const char *const sqlite_ses_meta  = ":sqlite3:ses";
static const char *const sqlite_reb_meta  = ":sqlite3:reb";
static const char *const sqlite_itr_meta  = ":sqlite3:itr";
static int sqlite_ses_meta_ref;
static int sqlite_reb_meta_ref;
static int sqlite_itr_meta_ref;
#endif
/* global config configuration */
static int log_cb = LUA_NOREF; /* log callback */
static int log_udata;

/* Lua 5.3 introduced an integer type, but depending on the implementation, it could be 32 
** or 64 bits (or something else?). This helper macro tries to do "the right thing."
*/

#if LUA_VERSION_NUM > 502
#define PUSH_INT64(L,i64in,fallback) \
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
    svm->has_values = 0;
    svm->vm = NULL;
    svm->temp = 0;

    /* add an entry on the database table: svm -> db to keep db live while svm is live */
    lua_pushlightuserdata(L, db);     /* db sql svm_ud db_lud -- */
    lua_rawget(L, LUA_REGISTRYINDEX); /* db sql svm_ud reg[db_lud] -- */
    lua_pushlightuserdata(L, svm);    /* db sql svm_ud reg[db_lud] svm_lud -- */
    lua_pushvalue(L, -5);             /* db sql svm_ud reg[db_lud] svm_lud db -- */
    lua_rawset(L, -3);                /* (reg[db_lud])[svm_lud] = db ; set the db for this vm */
    lua_pop(L, 1);                    /* db sql svm_ud -- */

    return svm;
}

static int cleanupvm(lua_State *L, sdb_vm *svm) {

    /* remove entry in database table - no harm if not present in the table */
    lua_pushlightuserdata(L, svm->db);
    lua_rawget(L, LUA_REGISTRYINDEX);
    lua_pushlightuserdata(L, svm);
    lua_pushnil(L);
    lua_rawset(L, -3);
    lua_pop(L, 1);

    svm->columns = 0;
    svm->has_values = 0;

    if (!svm->vm) return 0;

    lua_pushinteger(L, sqlite3_finalize(svm->vm));
    svm->vm = NULL;
    return 1;
}

static int stepvm(lua_State *L, sdb_vm *svm) {
	(void)L;







|
|
|






<
<
<
<
<
<
<
<
<




<







243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258









259
260
261
262

263
264
265
266
267
268
269
    svm->has_values = 0;
    svm->vm = NULL;
    svm->temp = 0;

    /* add an entry on the database table: svm -> db to keep db live while svm is live */
    lua_pushlightuserdata(L, db);     /* db sql svm_ud db_lud -- */
    lua_rawget(L, LUA_REGISTRYINDEX); /* db sql svm_ud reg[db_lud] -- */
    lua_pushvalue(L, -2);             /* db sql svm_ud reg[db_lud] svm_ud -- */
    lua_pushvalue(L, -5);             /* db sql svm_ud reg[db_lud] svm_ud db -- */
    lua_rawset(L, -3);                /* (reg[db_lud])[svm_ud] = db ; set the db for this vm */
    lua_pop(L, 1);                    /* db sql svm_ud -- */

    return svm;
}

static int cleanupvm(lua_State *L, sdb_vm *svm) {









    svm->columns = 0;
    svm->has_values = 0;

    if (!svm->vm) return 0;

    lua_pushinteger(L, sqlite3_finalize(svm->vm));
    svm->vm = NULL;
    return 1;
}

static int stepvm(lua_State *L, sdb_vm *svm) {
	(void)L;
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
static int dbvm_isopen(lua_State *L) {
    sdb_vm *svm = lsqlite_getvm(L, 1);
    lua_pushboolean(L, svm->vm != NULL ? 1 : 0);
    return 1;
}

static int dbvm_tostring(lua_State *L) {
    char buff[39];
    sdb_vm *svm = lsqlite_getvm(L, 1);
    if (svm->vm == NULL)
        strcpy(buff, "closed");
    else
        sprintf(buff, "%p", svm);
    lua_pushfstring(L, "sqlite virtual machine (%s)", buff);
    return 1;
}

static int dbvm_gc(lua_State *L) {
    sdb_vm *svm = lsqlite_getvm(L, 1);
    if (svm->vm != NULL)  /* ignore closed vms */
        cleanupvm(L, svm);
    return 0;
}

static int dbvm_step(lua_State *L) {
    int result;
    sdb_vm *svm = lsqlite_checkvm(L, 1);








|










<
<
|







285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302


303
304
305
306
307
308
309
310
static int dbvm_isopen(lua_State *L) {
    sdb_vm *svm = lsqlite_getvm(L, 1);
    lua_pushboolean(L, svm->vm != NULL ? 1 : 0);
    return 1;
}

static int dbvm_tostring(lua_State *L) {
    char buff[40];
    sdb_vm *svm = lsqlite_getvm(L, 1);
    if (svm->vm == NULL)
        strcpy(buff, "closed");
    else
        sprintf(buff, "%p", svm);
    lua_pushfstring(L, "sqlite virtual machine (%s)", buff);
    return 1;
}

static int dbvm_gc(lua_State *L) {


    cleanupvm(L, lsqlite_getvm(L, 1));
    return 0;
}

static int dbvm_step(lua_State *L) {
    int result;
    sdb_vm *svm = lsqlite_checkvm(L, 1);

630
631
632
633
634
635
636


637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656




657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677

678

679



680

681

682
683
684
685
686
687
688
689
690
691
692


693
694
695
696
697
698
699
700
701
702
703
704
705
706

707
708
709
710
711
712
713
714
715
716
717
718
719
720


721
722
723
724
725
726
727
    sdb *db = (sdb*)lua_newuserdata(L, sizeof(sdb));
    db->L = L;
    db->db = NULL;  /* database handle is currently `closed' */
    db->func = NULL;

    db->busy_cb =
    db->busy_udata =


    db->progress_cb =
    db->progress_udata =
    db->trace_cb =
    db->trace_udata = 
#if !defined(LSQLITE_OMIT_UPDATE_HOOK) || !LSQLITE_OMIT_UPDATE_HOOK
    db->update_hook_cb =
    db->update_hook_udata =
    db->commit_hook_cb =
    db->commit_hook_udata =
    db->rollback_hook_cb =
    db->rollback_hook_udata =
#endif
     LUA_NOREF;

    luaL_getmetatable(L, sqlite_meta);
    lua_setmetatable(L, -2);        /* set metatable */

    /* to keep track of 'open' virtual machines */
    lua_pushlightuserdata(L, db);
    lua_newtable(L);




    lua_rawset(L, LUA_REGISTRYINDEX);

    return db;
}

static int cleanupdb(lua_State *L, sdb *db) {
    sdb_func *func;
    sdb_func *func_next;
    int top;
    int result;

    /* free associated virtual machines */
    lua_pushlightuserdata(L, db);
    lua_rawget(L, LUA_REGISTRYINDEX);

    /* close all used handles */
    top = lua_gettop(L);
    lua_pushnil(L);
    while (lua_next(L, -2)) {
        sdb_vm *svm = lua_touserdata(L, -2); /* key: vm; val: sql text */
        cleanupvm(L, svm);



        lua_settop(L, top);



        lua_pushnil(L);

    }


    lua_pop(L, 1); /* pop vm table */

    /* remove entry in lua registry table */
    lua_pushlightuserdata(L, db);
    lua_pushnil(L);
    lua_rawset(L, LUA_REGISTRYINDEX);

    /* 'free' all references */
    luaL_unref(L, LUA_REGISTRYINDEX, db->busy_cb);
    luaL_unref(L, LUA_REGISTRYINDEX, db->busy_udata);


    luaL_unref(L, LUA_REGISTRYINDEX, db->progress_cb);
    luaL_unref(L, LUA_REGISTRYINDEX, db->progress_udata);
    luaL_unref(L, LUA_REGISTRYINDEX, db->trace_cb);
    luaL_unref(L, LUA_REGISTRYINDEX, db->trace_udata);
#if !defined(LSQLITE_OMIT_UPDATE_HOOK) || !LSQLITE_OMIT_UPDATE_HOOK
    luaL_unref(L, LUA_REGISTRYINDEX, db->update_hook_cb);
    luaL_unref(L, LUA_REGISTRYINDEX, db->update_hook_udata);
    luaL_unref(L, LUA_REGISTRYINDEX, db->commit_hook_cb);
    luaL_unref(L, LUA_REGISTRYINDEX, db->commit_hook_udata);
    luaL_unref(L, LUA_REGISTRYINDEX, db->rollback_hook_cb);
    luaL_unref(L, LUA_REGISTRYINDEX, db->rollback_hook_udata);
#endif

    /* close database */

    result = sqlite3_close(db->db);
    db->db = NULL;

    /* free associated memory with created functions */
    func = db->func;
    while (func) {
        func_next = func->next;
        luaL_unref(L, LUA_REGISTRYINDEX, func->fn_step);
        luaL_unref(L, LUA_REGISTRYINDEX, func->fn_finalize);
        luaL_unref(L, LUA_REGISTRYINDEX, func->udata);
        free(func);
        func = func_next;
    }
    db->func = NULL;


    return result;
}

static sdb *lsqlite_getdb(lua_State *L, int index) {
    sdb *db = (sdb*)luaL_checkudata(L, index, sqlite_meta);
    if (db == NULL) luaL_typerror(L, index, "sqlite database");
    return db;







>
>












|




|

|
>
>
>
>





|
<
<
<
<
|





<



|
>
|
>
|
>
>
>
|
>
|
>

|









>
>













|
>
|













>
>







651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689




690
691
692
693
694
695

696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
    sdb *db = (sdb*)lua_newuserdata(L, sizeof(sdb));
    db->L = L;
    db->db = NULL;  /* database handle is currently `closed' */
    db->func = NULL;

    db->busy_cb =
    db->busy_udata =
    db->wal_hook_cb =
    db->wal_hook_udata =
    db->progress_cb =
    db->progress_udata =
    db->trace_cb =
    db->trace_udata = 
#if !defined(LSQLITE_OMIT_UPDATE_HOOK) || !LSQLITE_OMIT_UPDATE_HOOK
    db->update_hook_cb =
    db->update_hook_udata =
    db->commit_hook_cb =
    db->commit_hook_udata =
    db->rollback_hook_cb =
    db->rollback_hook_udata =
#endif
        LUA_NOREF;

    luaL_getmetatable(L, sqlite_meta);
    lua_setmetatable(L, -2);        /* set metatable */

    /* to keep track of 'open' virtual machines; make keys week */
    lua_pushlightuserdata(L, db);
    lua_newtable(L);                    // t
    lua_newtable(L);                    // t mt
    lua_pushstring(L, "k");             // t mt v
    lua_setfield(L, -2, "__mode");      // t mt
    lua_setmetatable(L, -2);            // t
    lua_rawset(L, LUA_REGISTRYINDEX);

    return db;
}

/* cleanup all vms or just temporary ones */




static void closevms(lua_State *L, sdb *db, int temp) {
    /* free associated virtual machines */
    lua_pushlightuserdata(L, db);
    lua_rawget(L, LUA_REGISTRYINDEX);

    /* close all used handles */

    lua_pushnil(L);
    while (lua_next(L, -2)) {
        sdb_vm *svm = lua_touserdata(L, -2); /* key: vm; val: sql text */
        if ((!temp || svm->temp)) lua_pop(L, cleanupvm(L, svm));
        lua_pop(L, 1); /* pop value; leave key in the stack */
    }
}

static int cleanupdb(lua_State *L, sdb *db) {
    sdb_func *func;
    sdb_func *func_next;
    int top = lua_gettop(L);
    int result;

    if (!db->db) return SQLITE_MISUSE;

    closevms(L, db, 0);

    /* remove entry in lua registry table */
    lua_pushlightuserdata(L, db);
    lua_pushnil(L);
    lua_rawset(L, LUA_REGISTRYINDEX);

    /* 'free' all references */
    luaL_unref(L, LUA_REGISTRYINDEX, db->busy_cb);
    luaL_unref(L, LUA_REGISTRYINDEX, db->busy_udata);
    luaL_unref(L, LUA_REGISTRYINDEX, db->wal_hook_cb);
    luaL_unref(L, LUA_REGISTRYINDEX, db->wal_hook_udata);
    luaL_unref(L, LUA_REGISTRYINDEX, db->progress_cb);
    luaL_unref(L, LUA_REGISTRYINDEX, db->progress_udata);
    luaL_unref(L, LUA_REGISTRYINDEX, db->trace_cb);
    luaL_unref(L, LUA_REGISTRYINDEX, db->trace_udata);
#if !defined(LSQLITE_OMIT_UPDATE_HOOK) || !LSQLITE_OMIT_UPDATE_HOOK
    luaL_unref(L, LUA_REGISTRYINDEX, db->update_hook_cb);
    luaL_unref(L, LUA_REGISTRYINDEX, db->update_hook_udata);
    luaL_unref(L, LUA_REGISTRYINDEX, db->commit_hook_cb);
    luaL_unref(L, LUA_REGISTRYINDEX, db->commit_hook_udata);
    luaL_unref(L, LUA_REGISTRYINDEX, db->rollback_hook_cb);
    luaL_unref(L, LUA_REGISTRYINDEX, db->rollback_hook_udata);
#endif

    /* close database; _v2 is intended for use with garbage collected languages
       and where the order in which destructors are called is arbitrary. */
    result = sqlite3_close_v2(db->db);
    db->db = NULL;

    /* free associated memory with created functions */
    func = db->func;
    while (func) {
        func_next = func->next;
        luaL_unref(L, LUA_REGISTRYINDEX, func->fn_step);
        luaL_unref(L, LUA_REGISTRYINDEX, func->fn_finalize);
        luaL_unref(L, LUA_REGISTRYINDEX, func->udata);
        free(func);
        func = func_next;
    }
    db->func = NULL;

    lua_settop(L, top);
    return result;
}

static sdb *lsqlite_getdb(lua_State *L, int index) {
    sdb *db = (sdb*)luaL_checkudata(L, index, sqlite_meta);
    if (db == NULL) luaL_typerror(L, index, "sqlite database");
    return db;
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
static lcontext *lsqlite_checkcontext(lua_State *L, int index) {
    lcontext *ctx = lsqlite_getcontext(L, index);
    if (ctx->ctx == NULL) luaL_argerror(L, index, "invalid sqlite context");
    return ctx;
}

static int lcontext_tostring(lua_State *L) {
    char buff[39];
    lcontext *ctx = lsqlite_getcontext(L, 1);
    if (ctx->ctx == NULL)
        strcpy(buff, "closed");
    else
        sprintf(buff, "%p", ctx->ctx);
    lua_pushfstring(L, "sqlite function context (%s)", buff);
    return 1;







|







796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
static lcontext *lsqlite_checkcontext(lua_State *L, int index) {
    lcontext *ctx = lsqlite_getcontext(L, index);
    if (ctx->ctx == NULL) luaL_argerror(L, index, "invalid sqlite context");
    return ctx;
}

static int lcontext_tostring(lua_State *L) {
    char buff[41];
    lcontext *ctx = lsqlite_getcontext(L, 1);
    if (ctx->ctx == NULL)
        strcpy(buff, "closed");
    else
        sprintf(buff, "%p", ctx->ctx);
    lua_pushfstring(L, "sqlite function context (%s)", buff);
    return 1;
941
942
943
944
945
946
947

























948
949
950
951
952
953
954
static int db_db_filename(lua_State *L) {
    sdb *db = lsqlite_checkdb(L, 1);
    const char *db_name = luaL_checkstring(L, 2);
    /* sqlite3_db_filename may return NULL, in that case Lua pushes nil... */
    lua_pushstring(L, sqlite3_db_filename(db->db, db_name));
    return 1;
}


























/*
** Registering SQL functions:
*/

static void db_push_value(lua_State *L, sqlite3_value *value) {
    switch (sqlite3_value_type(value)) {







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
static int db_db_filename(lua_State *L) {
    sdb *db = lsqlite_checkdb(L, 1);
    const char *db_name = luaL_checkstring(L, 2);
    /* sqlite3_db_filename may return NULL, in that case Lua pushes nil... */
    lua_pushstring(L, sqlite3_db_filename(db->db, db_name));
    return 1;
}

static int pusherr(lua_State *L, int rc) {
    lua_pushnil(L);
    lua_pushinteger(L, rc);
    return 2;
}

static int pusherrstr(lua_State *L, char *str) {
    lua_pushnil(L);
    lua_pushstring(L, str);
    return 2;
}

static int db_wal_checkpoint(lua_State *L) {
    sdb *db = lsqlite_checkdb(L, 1);
    int eMode = luaL_optinteger(L, 2, SQLITE_CHECKPOINT_PASSIVE);
    const char *db_name = luaL_optstring(L, 3, NULL);
    int nLog, nCkpt;
    if (sqlite3_wal_checkpoint_v2(db->db, db_name, eMode, &nLog, &nCkpt) != SQLITE_OK) {
        return pusherr(L, sqlite3_errcode(db->db));
    }
    lua_pushinteger(L, nLog);
    lua_pushinteger(L, nCkpt);
    return 2;
}

/*
** Registering SQL functions:
*/

static void db_push_value(lua_State *L, sqlite3_value *value) {
    switch (sqlite3_value_type(value)) {
1248
1249
1250
1251
1252
1253
1254




















































1255
1256
1257
1258
1259
1260
1261
    }

    lua_pushboolean(L,0); /* so, assert(load_extension(...)) works */
    lua_pushstring(L,errmsg);
    sqlite3_free(errmsg);
    return 2;
}





















































/*
** trace callback:
** Params: database, callback function, userdata
**
** callback function:
** Params: userdata, sql







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
    }

    lua_pushboolean(L,0); /* so, assert(load_extension(...)) works */
    lua_pushstring(L,errmsg);
    sqlite3_free(errmsg);
    return 2;
}

/*
** wal_hook callback:
** Params: database, callback function, userdata
**
** callback function:
** Params: userdata, db handle, database name, number of wal file pages
*/
static int db_wal_hook_callback(void *user, sqlite3 *dbh, char const *dbname, int pnum) {
    sdb *db = (sdb*)user;
    lua_State *L = db->L;
    int top = lua_gettop(L);

    /* setup lua callback call */
    lua_rawgeti(L, LUA_REGISTRYINDEX, db->wal_hook_cb);    /* get callback */
    lua_rawgeti(L, LUA_REGISTRYINDEX, db->wal_hook_udata); /* get callback user data */
    lua_pushstring(L, dbname); /* hook database name */
    lua_pushinteger(L, pnum);

    if (lua_pcall(L, 3, 0, 0) != LUA_OK) return lua_error(L);

    lua_settop(L, top);
    return SQLITE_OK;
}

static int db_wal_hook(lua_State *L) {
    sdb *db = lsqlite_checkdb(L, 1);

    luaL_unref(L, LUA_REGISTRYINDEX, db->wal_hook_cb);
    luaL_unref(L, LUA_REGISTRYINDEX, db->wal_hook_udata);
    if (lua_gettop(L) < 2 || lua_isnil(L, 2)) {
        db->wal_hook_cb =
        db->wal_hook_udata = LUA_NOREF;

        /* clear hook handler */
        sqlite3_wal_hook(db->db, NULL, NULL);
    }
    else {
        luaL_checktype(L, 2, LUA_TFUNCTION);

        /* make sure we have an userdata field (even if nil) */
        lua_settop(L, 3);

        db->wal_hook_udata = luaL_ref(L, LUA_REGISTRYINDEX);
        db->wal_hook_cb = luaL_ref(L, LUA_REGISTRYINDEX);

        /* set hook handler */
        sqlite3_wal_hook(db->db, db_wal_hook_callback, db);
    }

    return 0;
}

/*
** trace callback:
** Params: database, callback function, userdata
**
** callback function:
** Params: userdata, sql
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348

1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371

    lua_settop(L, top);
}

static int db_update_hook(lua_State *L) {
    sdb *db = lsqlite_checkdb(L, 1);

    if (lua_gettop(L) < 2 || lua_isnil(L, 2)) {
        luaL_unref(L, LUA_REGISTRYINDEX, db->update_hook_cb);
        luaL_unref(L, LUA_REGISTRYINDEX, db->update_hook_udata);


        db->update_hook_cb =
        db->update_hook_udata = LUA_NOREF;

        /* clear update_hook handler */
        sqlite3_update_hook(db->db, NULL, NULL);
    }
    else {
        luaL_checktype(L, 2, LUA_TFUNCTION);

        /* make sure we have an userdata field (even if nil) */
        lua_settop(L, 3);

        luaL_unref(L, LUA_REGISTRYINDEX, db->update_hook_cb);
        luaL_unref(L, LUA_REGISTRYINDEX, db->update_hook_udata);

        db->update_hook_udata = luaL_ref(L, LUA_REGISTRYINDEX);
        db->update_hook_cb = luaL_ref(L, LUA_REGISTRYINDEX);

        /* set update_hook handler */
        sqlite3_update_hook(db->db, db_update_hook_callback, db);
    }








<
|
|
>













<
<
<







1450
1451
1452
1453
1454
1455
1456

1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472



1473
1474
1475
1476
1477
1478
1479

    lua_settop(L, top);
}

static int db_update_hook(lua_State *L) {
    sdb *db = lsqlite_checkdb(L, 1);


    luaL_unref(L, LUA_REGISTRYINDEX, db->update_hook_cb);
    luaL_unref(L, LUA_REGISTRYINDEX, db->update_hook_udata);
    if (lua_gettop(L) < 2 || lua_isnil(L, 2)) {

        db->update_hook_cb =
        db->update_hook_udata = LUA_NOREF;

        /* clear update_hook handler */
        sqlite3_update_hook(db->db, NULL, NULL);
    }
    else {
        luaL_checktype(L, 2, LUA_TFUNCTION);

        /* make sure we have an userdata field (even if nil) */
        lua_settop(L, 3);




        db->update_hook_udata = luaL_ref(L, LUA_REGISTRYINDEX);
        db->update_hook_cb = luaL_ref(L, LUA_REGISTRYINDEX);

        /* set update_hook handler */
        sqlite3_update_hook(db->db, db_update_hook_callback, db);
    }

1398
1399
1400
1401
1402
1403
1404
1405
1406
1407

1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
    lua_settop(L, top);
    return rollback;
}

static int db_commit_hook(lua_State *L) {
    sdb *db = lsqlite_checkdb(L, 1);

    if (lua_gettop(L) < 2 || lua_isnil(L, 2)) {
        luaL_unref(L, LUA_REGISTRYINDEX, db->commit_hook_cb);
        luaL_unref(L, LUA_REGISTRYINDEX, db->commit_hook_udata);


        db->commit_hook_cb =
        db->commit_hook_udata = LUA_NOREF;

        /* clear commit_hook handler */
        sqlite3_commit_hook(db->db, NULL, NULL);
    }
    else {
        luaL_checktype(L, 2, LUA_TFUNCTION);

        /* make sure we have an userdata field (even if nil) */
        lua_settop(L, 3);

        luaL_unref(L, LUA_REGISTRYINDEX, db->commit_hook_cb);
        luaL_unref(L, LUA_REGISTRYINDEX, db->commit_hook_udata);

        db->commit_hook_udata = luaL_ref(L, LUA_REGISTRYINDEX);
        db->commit_hook_cb = luaL_ref(L, LUA_REGISTRYINDEX);

        /* set commit_hook handler */
        sqlite3_commit_hook(db->db, db_commit_hook_callback, db);
    }








<
|
|
>













<
<
<







1506
1507
1508
1509
1510
1511
1512

1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528



1529
1530
1531
1532
1533
1534
1535
    lua_settop(L, top);
    return rollback;
}

static int db_commit_hook(lua_State *L) {
    sdb *db = lsqlite_checkdb(L, 1);


    luaL_unref(L, LUA_REGISTRYINDEX, db->commit_hook_cb);
    luaL_unref(L, LUA_REGISTRYINDEX, db->commit_hook_udata);
    if (lua_gettop(L) < 2 || lua_isnil(L, 2)) {

        db->commit_hook_cb =
        db->commit_hook_udata = LUA_NOREF;

        /* clear commit_hook handler */
        sqlite3_commit_hook(db->db, NULL, NULL);
    }
    else {
        luaL_checktype(L, 2, LUA_TFUNCTION);

        /* make sure we have an userdata field (even if nil) */
        lua_settop(L, 3);




        db->commit_hook_udata = luaL_ref(L, LUA_REGISTRYINDEX);
        db->commit_hook_cb = luaL_ref(L, LUA_REGISTRYINDEX);

        /* set commit_hook handler */
        sqlite3_commit_hook(db->db, db_commit_hook_callback, db);
    }

1453
1454
1455
1456
1457
1458
1459
1460
1461
1462

1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485

    lua_settop(L, top);
}

static int db_rollback_hook(lua_State *L) {
    sdb *db = lsqlite_checkdb(L, 1);

    if (lua_gettop(L) < 2 || lua_isnil(L, 2)) {
        luaL_unref(L, LUA_REGISTRYINDEX, db->rollback_hook_cb);
        luaL_unref(L, LUA_REGISTRYINDEX, db->rollback_hook_udata);


        db->rollback_hook_cb =
        db->rollback_hook_udata = LUA_NOREF;

        /* clear rollback_hook handler */
        sqlite3_rollback_hook(db->db, NULL, NULL);
    }
    else {
        luaL_checktype(L, 2, LUA_TFUNCTION);

        /* make sure we have an userdata field (even if nil) */
        lua_settop(L, 3);

        luaL_unref(L, LUA_REGISTRYINDEX, db->rollback_hook_cb);
        luaL_unref(L, LUA_REGISTRYINDEX, db->rollback_hook_udata);

        db->rollback_hook_udata = luaL_ref(L, LUA_REGISTRYINDEX);
        db->rollback_hook_cb = luaL_ref(L, LUA_REGISTRYINDEX);

        /* set rollback_hook handler */
        sqlite3_rollback_hook(db->db, db_rollback_hook_callback, db);
    }








<
|
|
>













<
<
<







1558
1559
1560
1561
1562
1563
1564

1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580



1581
1582
1583
1584
1585
1586
1587

    lua_settop(L, top);
}

static int db_rollback_hook(lua_State *L) {
    sdb *db = lsqlite_checkdb(L, 1);


    luaL_unref(L, LUA_REGISTRYINDEX, db->rollback_hook_cb);
    luaL_unref(L, LUA_REGISTRYINDEX, db->rollback_hook_udata);
    if (lua_gettop(L) < 2 || lua_isnil(L, 2)) {

        db->rollback_hook_cb =
        db->rollback_hook_udata = LUA_NOREF;

        /* clear rollback_hook handler */
        sqlite3_rollback_hook(db->db, NULL, NULL);
    }
    else {
        luaL_checktype(L, 2, LUA_TFUNCTION);

        /* make sure we have an userdata field (even if nil) */
        lua_settop(L, 3);




        db->rollback_hook_udata = luaL_ref(L, LUA_REGISTRYINDEX);
        db->rollback_hook_cb = luaL_ref(L, LUA_REGISTRYINDEX);

        /* set rollback_hook handler */
        sqlite3_rollback_hook(db->db, db_rollback_hook_callback, db);
    }

1699
1700
1701
1702
1703
1704
1705
1706
1707
1708

1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
    lua_settop(L, top);
    return retry;
}

static int db_busy_handler(lua_State *L) {
    sdb *db = lsqlite_checkdb(L, 1);

    if (lua_gettop(L) < 2 || lua_isnil(L, 2)) {
        luaL_unref(L, LUA_REGISTRYINDEX, db->busy_cb);
        luaL_unref(L, LUA_REGISTRYINDEX, db->busy_udata);


        db->busy_cb =
        db->busy_udata = LUA_NOREF;

        /* clear busy handler */
        sqlite3_busy_handler(db->db, NULL, NULL);
    }
    else {
        luaL_checktype(L, 2, LUA_TFUNCTION);
        /* make sure we have an userdata field (even if nil) */
        lua_settop(L, 3);

        luaL_unref(L, LUA_REGISTRYINDEX, db->busy_cb);
        luaL_unref(L, LUA_REGISTRYINDEX, db->busy_udata);

        db->busy_udata = luaL_ref(L, LUA_REGISTRYINDEX);
        db->busy_cb = luaL_ref(L, LUA_REGISTRYINDEX);

        /* set busy handler */
        sqlite3_busy_handler(db->db, db_busy_callback, db);
    }








<
|
|
>












<
<
<







1801
1802
1803
1804
1805
1806
1807

1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822



1823
1824
1825
1826
1827
1828
1829
    lua_settop(L, top);
    return retry;
}

static int db_busy_handler(lua_State *L) {
    sdb *db = lsqlite_checkdb(L, 1);


    luaL_unref(L, LUA_REGISTRYINDEX, db->busy_cb);
    luaL_unref(L, LUA_REGISTRYINDEX, db->busy_udata);
    if (lua_gettop(L) < 2 || lua_isnil(L, 2)) {

        db->busy_cb =
        db->busy_udata = LUA_NOREF;

        /* clear busy handler */
        sqlite3_busy_handler(db->db, NULL, NULL);
    }
    else {
        luaL_checktype(L, 2, LUA_TFUNCTION);
        /* make sure we have an userdata field (even if nil) */
        lua_settop(L, 3);




        db->busy_udata = luaL_ref(L, LUA_REGISTRYINDEX);
        db->busy_cb = luaL_ref(L, LUA_REGISTRYINDEX);

        /* set busy handler */
        sqlite3_busy_handler(db->db, db_busy_callback, db);
    }

2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073



















































































































































































































































































































































































































































































































































































































































2074
2075
2076
2077
2078
2079
2080

/* unpacked version of db:rows */
static int db_urows(lua_State *L) {
    return db_do_rows(L, db_next_row);
}

static int db_tostring(lua_State *L) {
    char buff[32];
    sdb *db = lsqlite_getdb(L, 1);
    if (db->db == NULL)
        strcpy(buff, "closed");
    else
        sprintf(buff, "%p", lua_touserdata(L, 1));
    lua_pushfstring(L, "sqlite database (%s)", buff);
    return 1;
}

static int db_close(lua_State *L) {
    sdb *db = lsqlite_checkdb(L, 1);
    lua_pushinteger(L, cleanupdb(L, db));
    return 1;
}

static int db_close_vm(lua_State *L) {
    sdb *db = lsqlite_checkdb(L, 1);
    /* cleanup temporary only tables? */
    int temp = lua_toboolean(L, 2);

    /* free associated virtual machines */
    lua_pushlightuserdata(L, db);
    lua_rawget(L, LUA_REGISTRYINDEX);

    /* close all used handles */
    lua_pushnil(L);
    while (lua_next(L, -2)) {
        sdb_vm *svm = lua_touserdata(L, -2); /* key: vm; val: sql text */

        if ((!temp || svm->temp) && svm->vm)
        {
            sqlite3_finalize(svm->vm);
            svm->vm = NULL;
        }

        /* leave key in the stack */
        lua_pop(L, 1);
    }
    return 0;
}

/* From: Wolfgang Oertl
When using lsqlite3 in a multithreaded environment, each thread has a separate Lua 
environment, but full userdata structures can't be passed from one thread to another.
This is possible with lightuserdata, however. See: lsqlite_open_ptr().
*/
static int db_get_ptr(lua_State *L) {
    sdb *db = lsqlite_checkdb(L, 1);
    lua_pushlightuserdata(L, db->db);
    return 1;
}

static int db_gc(lua_State *L) {
    sdb *db = lsqlite_getdb(L, 1);
    if (db->db != NULL)  /* ignore closed databases */
        cleanupdb(L, db);
    return 0;
}




















































































































































































































































































































































































































































































































































































































































/*
** =======================================================
** General library functions
** =======================================================
*/








|

















<
|
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<




















>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131

2132



















2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786

/* unpacked version of db:rows */
static int db_urows(lua_State *L) {
    return db_do_rows(L, db_next_row);
}

static int db_tostring(lua_State *L) {
    char buff[33];
    sdb *db = lsqlite_getdb(L, 1);
    if (db->db == NULL)
        strcpy(buff, "closed");
    else
        sprintf(buff, "%p", lua_touserdata(L, 1));
    lua_pushfstring(L, "sqlite database (%s)", buff);
    return 1;
}

static int db_close(lua_State *L) {
    sdb *db = lsqlite_checkdb(L, 1);
    lua_pushinteger(L, cleanupdb(L, db));
    return 1;
}

static int db_close_vm(lua_State *L) {
    sdb *db = lsqlite_checkdb(L, 1);

    closevms(L, db, lua_toboolean(L, 2));



















    return 0;
}

/* From: Wolfgang Oertl
When using lsqlite3 in a multithreaded environment, each thread has a separate Lua 
environment, but full userdata structures can't be passed from one thread to another.
This is possible with lightuserdata, however. See: lsqlite_open_ptr().
*/
static int db_get_ptr(lua_State *L) {
    sdb *db = lsqlite_checkdb(L, 1);
    lua_pushlightuserdata(L, db->db);
    return 1;
}

static int db_gc(lua_State *L) {
    sdb *db = lsqlite_getdb(L, 1);
    if (db->db != NULL)  /* ignore closed databases */
        cleanupdb(L, db);
    return 0;
}

#ifdef SQLITE_ENABLE_DESERIALIZE

static int db_serialize(lua_State *L) {
    sdb *db = lsqlite_checkdb(L, 1);
    sqlite_int64 size = 0;

    char *buffer = (char *)sqlite3_serialize(db->db, "main", &size, 0);
    if (buffer == NULL)
        return pusherrstr(L, "failed to serialize");

    lua_pushlstring(L, buffer, size);
    free(buffer);
    return 1;
}

static int db_deserialize(lua_State *L) {
    sdb *db = lsqlite_checkdb(L, 1);
    size_t size = 0;

    const char *buffer = luaL_checklstring(L, 2, &size);
    if (buffer == NULL || size == 0)
        return pusherrstr(L, "failed to deserialize");

    unsigned char *sqlbuf = memcpy(sqlite3_malloc(size), buffer, size);
    sqlite3_deserialize(db->db, "main", sqlbuf, size, size,
        SQLITE_DESERIALIZE_FREEONCLOSE + SQLITE_DESERIALIZE_RESIZEABLE);
    lua_pushinteger(L, SQLITE_OK);
    return 1;
}

#endif

#ifdef SQLITE_ENABLE_SESSION

/*
** =======================================================
** Iterator functions (for session support)
** =======================================================
*/

typedef struct {
    sqlite3_changeset_iter *itr;
    bool collectable;
} liter;

static liter *lsqlite_makeiter(lua_State *L, sqlite3_changeset_iter *piter, bool collectable) {
    liter *litr = (liter*)lua_newuserdata(L, sizeof(liter));
    lua_rawgeti(L, LUA_REGISTRYINDEX, sqlite_itr_meta_ref);
    lua_setmetatable(L, -2);
    litr->itr = piter;
    litr->collectable = collectable;
    return litr;
}

static liter *lsqlite_getiter(lua_State *L, int index) {
    return (liter *)luaL_checkudata(L, index, sqlite_itr_meta);
}

static liter *lsqlite_checkiter(lua_State *L, int index) {
    liter *litr = lsqlite_getiter(L, index);
    if (litr->itr == NULL) luaL_argerror(L, index, "invalid sqlite iterator");
    return litr;
}

static int liter_finalize(lua_State *L) {
    liter *litr = lsqlite_getiter(L, 1);
    int rc;
    if (litr->itr) {
        if (!litr->collectable) {
            return pusherr(L, SQLITE_CORRUPT);
        }
        if ((rc = sqlite3changeset_finalize(litr->itr)) != SQLITE_OK) {
            return pusherr(L, rc);
        }
        litr->itr = NULL;
    }
    lua_pushboolean(L, 1);
    return 1;
}

static int liter_gc(lua_State *L) {
    return liter_finalize(L);
}

static int liter_tostring(lua_State *L) {
    char buff[33];
    liter *litr = lsqlite_getiter(L, 1);
    if (litr->itr == NULL)
        strcpy(buff, "closed");
    else
        sprintf(buff, "%p", litr->itr);
    lua_pushfstring(L, "sqlite iterator (%s)", buff);
    return 1;
}

static int liter_table(
        lua_State *L,
        int (*iter_func)(sqlite3_changeset_iter *pIter, int val, sqlite3_value **ppValue)
) {
    const char *zTab;
    int n, rc, nCol, Op, bIndirect;
    sqlite3_value *pVal;
    liter *litr = lsqlite_checkiter(L, 1);
    sqlite3changeset_op(litr->itr, &zTab, &nCol, &Op, &bIndirect);
    lua_createtable(L, nCol, 0);
    for (n = 0; n < nCol; n++) {
        if ((rc = (*iter_func)(litr->itr, n, &pVal)) != LUA_OK) {
            return pusherr(L, rc);
        }
        if (pVal) {
            db_push_value(L, pVal);
        } else {
            // push `false` to indicate that the value wasn't changed
            // and not included in the record and to keep table valid
            lua_pushboolean(L, 0);
        }
        lua_rawseti(L, -2, n+1);
    }
    return 1;
}

static int liter_new(lua_State *L) {
    return liter_table(L, sqlite3changeset_new);
}

static int liter_old(lua_State *L) {
    return liter_table(L, sqlite3changeset_old);
}

static int liter_conflict(lua_State *L) {
    return liter_table(L, sqlite3changeset_conflict);
}

static int liter_op(lua_State *L) {
    const char *zTab;
    int rc, nCol, Op, bIndirect;
    liter *litr = lsqlite_checkiter(L, 1);

    if ((rc = sqlite3changeset_op(litr->itr, &zTab, &nCol, &Op, &bIndirect)) != LUA_OK) {
        return pusherr(L, rc);
    }
    lua_pushstring(L, zTab);
    lua_pushinteger(L, Op);
    lua_pushboolean(L, bIndirect);
    return 3;
}

static int liter_fk_conflicts(lua_State *L) {
    int rc, nOut;
    liter *litr = lsqlite_checkiter(L, 1);
    if ((rc = sqlite3changeset_fk_conflicts(litr->itr, &nOut)) != LUA_OK) {
        return pusherr(L, rc);
    }
    lua_pushinteger(L, nOut);
    return 1;
}

static int liter_next(lua_State *L) {
    liter *litr = lsqlite_checkiter(L, 1);
    if (!litr->collectable) {
        return pusherr(L, SQLITE_CORRUPT);
    }
    lua_pushinteger(L, sqlite3changeset_next(litr->itr));
    return 1;
}

static int liter_pk(lua_State *L) {
    const char *zTab;
    int n, rc, nCol;
    unsigned char *abPK;
    liter *litr = lsqlite_checkiter(L, 1);
    if ((rc = sqlite3changeset_pk(litr->itr, &abPK, &nCol)) != LUA_OK) {
        return pusherr(L, rc);
    }
    lua_createtable(L, nCol, 0);
    for (n = 0; n < nCol; n++) {
        lua_pushboolean(L, abPK[n]);
        lua_rawseti(L, -2, n+1);
    }
    return 1;
}

/*
** =======================================================
** Rebaser functions (for session support)
** =======================================================
*/

typedef struct {
    sqlite3_rebaser *reb;
} lrebaser;

static lrebaser *lsqlite_makerebaser(lua_State *L, sqlite3_rebaser *reb) {
    lrebaser *lreb = (lrebaser*)lua_newuserdata(L, sizeof(lrebaser));
    lua_rawgeti(L, LUA_REGISTRYINDEX, sqlite_reb_meta_ref);
    lua_setmetatable(L, -2);
    lreb->reb = reb;
    return lreb;
}

static lrebaser *lsqlite_getrebaser(lua_State *L, int index) {
    return (lrebaser *)luaL_checkudata(L, index, sqlite_reb_meta);
}

static lrebaser *lsqlite_checkrebaser(lua_State *L, int index) {
    lrebaser *lreb = lsqlite_getrebaser(L, index);
    if (lreb->reb == NULL) luaL_argerror(L, index, "invalid sqlite rebaser");
    return lreb;
}

static int lrebaser_delete(lua_State *L) {
    lrebaser *lreb = lsqlite_getrebaser(L, 1);
    if (lreb->reb != NULL) {
      sqlite3rebaser_delete(lreb->reb);
      lreb->reb = NULL;
    }
    return 0;
}

static int lrebaser_gc(lua_State *L) {
    return lrebaser_delete(L);
}

static int lrebaser_tostring(lua_State *L) {
    char buff[32];
    lrebaser *lreb = lsqlite_getrebaser(L, 1);
    if (lreb->reb == NULL)
        strcpy(buff, "closed");
    else
        sprintf(buff, "%p", lreb->reb);
    lua_pushfstring(L, "sqlite rebaser (%s)", buff);
    return 1;
}

static int lrebaser_rebase(lua_State *L) {
    lrebaser *lreb = lsqlite_checkrebaser(L, 1);
    const char *cset = luaL_checkstring(L, 2);
    int nset = lua_strlen(L, 2);
    int rc;
    int size;
    void *buf;

    if ((rc = sqlite3rebaser_rebase(lreb->reb, nset, cset, &size, &buf)) != SQLITE_OK) {
        return pusherr(L, rc);
    }
    lua_pushlstring(L, buf, size);
    sqlite3_free(buf);
    return 1;
}

static int db_create_rebaser(lua_State *L) {
    sqlite3_rebaser *reb;
    int rc;

    if ((rc = sqlite3rebaser_create(&reb)) != SQLITE_OK) {
        return pusherr(L, rc);
    }
    (void)lsqlite_makerebaser(L, reb);
    return 1;
}

/* session/changeset callbacks */

static int changeset_conflict_cb = LUA_NOREF;
static int changeset_filter_cb = LUA_NOREF;
static int changeset_cb_udata = LUA_NOREF;
static int session_filter_cb = LUA_NOREF;
static int session_cb_udata = LUA_NOREF;

static int db_changeset_conflict_callback(
        void *user,               /* Copy of sixth arg to _apply_v2() */
        int eConflict,            /* DATA, MISSING, CONFLICT, CONSTRAINT */
        sqlite3_changeset_iter *p /* Handle describing change and conflict */
) {
    // return default code if no callback is provided
    if (changeset_conflict_cb == LUA_NOREF) return SQLITE_CHANGESET_OMIT;
    sdb *db = (sdb*)user;
    lua_State *L = db->L;
    int top = lua_gettop(L);
    int result, isint;
    const char *zTab;
    int nCol, Op, bIndirect;

    if (sqlite3changeset_op(p, &zTab, &nCol, &Op, &bIndirect) != LUA_OK) {
        lua_pushliteral(L, "invalid return from changeset iterator");
        return lua_error(L);
    }

    lua_rawgeti(L, LUA_REGISTRYINDEX, changeset_conflict_cb); /* get callback */
    lua_rawgeti(L, LUA_REGISTRYINDEX, changeset_cb_udata); /* get callback user data */
    lua_pushinteger(L, eConflict);
    (void)lsqlite_makeiter(L, p, 0);
    lua_pushstring(L, zTab);
    lua_pushinteger(L, Op);
    lua_pushboolean(L, bIndirect);

    if (lua_pcall(L, 6, 1, 0) != LUA_OK) return lua_error(L);

    result = lua_tointegerx(L, -1, &isint); /* use result if there was no error */
    if (!isint) {
        lua_pushliteral(L, "non-integer returned from conflict callback");
        return lua_error(L);
    }

    lua_settop(L, top);
    return result;
}

static int db_filter_callback(
        void *user,       /* Context */
        const char *zTab, /* Table name */
        int filter_cb,
        int filter_udata
) {
    // allow the table if no filter callback is provided
    if (filter_cb == LUA_NOREF || filter_cb == LUA_REFNIL) return 1;
    sdb *db = (sdb*)user;
    lua_State *L = db->L;
    int top = lua_gettop(L);
    int result, isint;

    lua_rawgeti(L, LUA_REGISTRYINDEX, filter_cb); /* get callback */
    lua_pushstring(L, zTab);
    lua_rawgeti(L, LUA_REGISTRYINDEX, filter_udata); /* get callback user data */

    if (lua_pcall(L, 2, 1, 0) != LUA_OK) return lua_error(L);

    // allow 0/1 and false/true to be returned
    // returning 0/false skips the table
    result = lua_tointegerx(L, -1, &isint); /* use result if there was no error */
    if (!isint && !lua_isboolean(L, -1)) {
        lua_pushliteral(L, "non-integer and non-boolean returned from filter callback");
        return lua_error(L);
    }
    if (!isint) result = lua_toboolean(L, -1);

    lua_settop(L, top);
    return result;
}

static int db_changeset_filter_callback(
        void *user,      /* Copy of sixth arg to _apply_v2() */
        const char *zTab /* Table name */
) {
    return db_filter_callback(user, zTab, changeset_filter_cb, changeset_cb_udata);
}

static int db_session_filter_callback(
        void *user,      /* Copy of third arg to session_attach() */
        const char *zTab /* Table name */
) {
    return db_filter_callback(user, zTab, session_filter_cb, session_cb_udata);
}

/*
** =======================================================
** Session functions
** =======================================================
*/

typedef struct {
    sqlite3_session *ses;
    sdb *db; // keep track of the DB this session is for
} lsession;

static lsession *lsqlite_makesession(lua_State *L, sqlite3_session *ses, sdb *db) {
    lsession *lses = (lsession*)lua_newuserdata(L, sizeof(lsession));
    lua_rawgeti(L, LUA_REGISTRYINDEX, sqlite_ses_meta_ref);
    lua_setmetatable(L, -2);
    lses->ses = ses;
    lses->db = db;
    return lses;
}

static lsession *lsqlite_getsession(lua_State *L, int index) {
    return (lsession *)luaL_checkudata(L, index, sqlite_ses_meta);
}

static lsession *lsqlite_checksession(lua_State *L, int index) {
    lsession *lses = lsqlite_getsession(L, index);
    if (lses->ses == NULL) luaL_argerror(L, index, "invalid sqlite session");
    return lses;
}

static int lsession_attach(lua_State *L) {
    lsession *lses = lsqlite_checksession(L, 1);
    int rc;
    // allow either a table or a callback function to filter tables
    const char *zTab = lua_type(L, 2) == LUA_TFUNCTION
        ? NULL
        : luaL_optstring(L, 2, NULL);
    if ((rc = sqlite3session_attach(lses->ses, zTab)) != SQLITE_OK) {
        return pusherr(L, rc);
    }
    // allow to pass a filter callback,
    // but only one shared for all sessions where this callback is used
    if (lua_type(L, 2) == LUA_TFUNCTION) {
        // TBD: does this *also* need to be done in cleanupvm?
        luaL_unref(L, LUA_REGISTRYINDEX, session_filter_cb);
        luaL_unref(L, LUA_REGISTRYINDEX, session_cb_udata);
        lua_settop(L, 3);  // add udata even if it's not provided
        session_cb_udata = luaL_ref(L, LUA_REGISTRYINDEX);
        session_filter_cb = luaL_ref(L, LUA_REGISTRYINDEX);
        sqlite3session_table_filter(lses->ses,
            db_session_filter_callback, lses->db);
    }
    lua_pushboolean(L, 1);
    return 1;
}

static int lsession_isempty(lua_State *L) {
    lsession *lses = lsqlite_checksession(L, 1);
    lua_pushboolean(L, sqlite3session_isempty(lses->ses));
    return 1;
}

static int lsession_diff(lua_State *L) {
    lsession *lses = lsqlite_checksession(L, 1);
    const char *zFromDb = luaL_checkstring(L, 2);
    const char *zTbl = luaL_checkstring(L, 3);
    int rc = sqlite3session_diff(lses->ses, zFromDb, zTbl, NULL);
    if (rc != SQLITE_OK) return pusherr(L, rc);
    lua_pushboolean(L, 1);
    return 1;
}

static int lsession_bool(
        lua_State *L,
        int (*session_func)(sqlite3_session *ses, int val)
) {
    lsession *lses = lsqlite_checksession(L, 1);
    int val = lua_isboolean(L, 2)
        ? lua_toboolean(L, 2)
        : luaL_optinteger(L, 2, -1);
    lua_pushboolean(L, (*session_func)(lses->ses, val));
    return 1;
}

static int lsession_indirect(lua_State *L) {
    return lsession_bool(L, sqlite3session_indirect);
}

static int lsession_enable(lua_State *L) {
    return lsession_bool(L, sqlite3session_enable);
}

static int lsession_getset(
        lua_State *L,
        int (*session_setfunc)(sqlite3_session *ses, int *size, void **buf)
) {
    lsession *lses = lsqlite_checksession(L, 1);
    int rc;
    int size;
    void *buf;

    if ((rc = (*session_setfunc)(lses->ses, &size, &buf)) != SQLITE_OK) {
        return pusherr(L, rc);
    }
    lua_pushlstring(L, buf, size);
    sqlite3_free(buf);
    return 1;
}

static int lsession_changeset(lua_State *L) {
    return lsession_getset(L, sqlite3session_changeset);
}

static int lsession_patchset(lua_State *L) {
    return lsession_getset(L, sqlite3session_patchset);
}

static int lsession_delete(lua_State *L) {
    lsession *lses = lsqlite_getsession(L, 1);
    if (lses->ses != NULL) {
      sqlite3session_delete(lses->ses);
      lses->ses = NULL;
    }
    return 0;
}

static int lsession_tostring(lua_State *L) {
    char buff[32];
    lsession *lses = lsqlite_getsession(L, 1);
    if (lses->ses == NULL)
        strcpy(buff, "closed");
    else
        sprintf(buff, "%p", lses->ses);
    lua_pushfstring(L, "sqlite session (%s)", buff);
    return 1;
}

static int db_create_session(lua_State *L) {
    sdb *db = lsqlite_checkdb(L, 1);
    const char *zDb = luaL_optstring(L, 2, "main");
    sqlite3_session *ses;

    if (sqlite3session_create(db->db, zDb, &ses) != SQLITE_OK) {
        return pusherr(L, sqlite3_errcode(db->db));
    }
    (void)lsqlite_makesession(L, ses, db);
    return 1;
}

static int db_iterate_changeset(lua_State *L) {
    sqlite3_changeset_iter *p;
    sdb *db = lsqlite_checkdb(L, 1);
    const char *cset = luaL_checkstring(L, 2);
    int nset = lua_strlen(L, 2);
    int flags = luaL_optinteger(L, 3, 0);
    int rc;

    if ((rc = sqlite3changeset_start_v2(&p, nset, cset, flags)) != SQLITE_OK) {
        return pusherr(L, rc);
    }
    (void)lsqlite_makeiter(L, p, 1);
    return 1;
}

static int db_invert_changeset(lua_State *L) {
    sdb *db = lsqlite_checkdb(L, 1);
    const char *cset = luaL_checkstring(L, 2);
    int nset = lua_strlen(L, 2);
    int rc;
    int size;
    void *buf;

    if ((rc = sqlite3changeset_invert(nset, cset, &size, &buf)) != SQLITE_OK) {
        return pusherr(L, rc);
    }
    lua_pushlstring(L, buf, size);
    sqlite3_free(buf);
    return 1;
}

static int db_concat_changeset(lua_State *L) {
    sdb *db = lsqlite_checkdb(L, 1);
    int size, nset;
    void *buf, *cset;
    sqlite3_changegroup *pGrp;

    luaL_checktype(L, 2, LUA_TTABLE);
    int n = luaL_len(L, 2);
    int rc = sqlite3changegroup_new(&pGrp);
    for (int i = 1; rc == SQLITE_OK && i <= n; i++) {
        lua_rawgeti(L, 2, i);
        cset = (void*)lua_tostring(L, -1);
        nset = lua_strlen(L, -1);
        rc = sqlite3changegroup_add(pGrp, nset, cset);
        lua_pop(L, 1);  // pop the string
    }
    if (rc == SQLITE_OK) rc = sqlite3changegroup_output(pGrp, &size, &buf);
    sqlite3changegroup_delete(pGrp);

    if (rc != SQLITE_OK) return pusherr(L, rc);
    lua_pushlstring(L, buf, size);
    sqlite3_free(buf);
    return 1;
}

static int db_apply_changeset(lua_State *L) {
    sdb *db = lsqlite_checkdb(L, 1);
    const char *cset = luaL_checkstring(L, 2);
    int nset = lua_strlen(L, 2);
    int top = lua_gettop(L);
    int rc;
    int flags = 0;
    void *pRebase;
    int nRebase;
    lrebaser *lreb = NULL;

    // parameters: db, changeset[[, filter cb], conflict cb[, udata[, rebaser[, flags]]]]

    // TBD: does this *also* need to be done in cleanupvm?
    if (changeset_cb_udata != LUA_NOREF) {
        luaL_unref(L, LUA_REGISTRYINDEX, changeset_conflict_cb);
        luaL_unref(L, LUA_REGISTRYINDEX, changeset_filter_cb);
        luaL_unref(L, LUA_REGISTRYINDEX, changeset_cb_udata);

        changeset_conflict_cb =
        changeset_filter_cb =
        changeset_cb_udata = LUA_NOREF;
    }

    // check for conflict/filter callback type if provided
    if (top >= 3) {
        luaL_checktype(L, 3, LUA_TFUNCTION);
        // if no filter callback, insert a dummy one to simplify stack handling
        if (lua_type(L, 4) != LUA_TFUNCTION) {
            lua_pushnil(L);
            lua_insert(L, 3);
            top = lua_gettop(L);
        }
    }
    if (top >= 6) lreb = lsqlite_checkrebaser(L, 6);
    if (top >= 7) flags = luaL_checkinteger(L, 7);
    if (top >= 4) {  // two callback are guaranteed to be on the stack in this case
        // shorten stack or extend to set udata to `nil` if not provided
        lua_settop(L, 5);
        changeset_cb_udata = luaL_ref(L, LUA_REGISTRYINDEX);
        changeset_conflict_cb = luaL_ref(L, LUA_REGISTRYINDEX);
        changeset_filter_cb = luaL_ref(L, LUA_REGISTRYINDEX);
    }

    rc = sqlite3changeset_apply_v2(db->db, nset, (void*)cset,
                                   db_changeset_filter_callback,
                                   db_changeset_conflict_callback,
                                   db, // context
                                   lreb ? &pRebase : 0,
                                   lreb ? &nRebase : 0,
                                   flags);

    if (rc != SQLITE_OK) return pusherr(L, sqlite3_errcode(db->db));

    if (lreb) { // if rebaser is present
        rc = sqlite3rebaser_configure(lreb->reb, nRebase, pRebase);
        if (rc == SQLITE_OK) lua_pushstring(L, pRebase);
        sqlite3_free(pRebase);
        if (rc == SQLITE_OK) return 1;
        return pusherr(L, rc);
    }

    lua_pushboolean(L, 1);
    return 1;
}

#endif

/*
** =======================================================
** General library functions
** =======================================================
*/

2107
2108
2109
2110
2111
2112
2113

2114
2115
2116
2117
2118
2119
2120
    }
    lua_pushstring(L, oldtemp);
    return 1;
}
#endif

static int lsqlite_do_open(lua_State *L, const char *filename, int flags) {

    sdb *db = newdb(L); /* create and leave in stack */

    if (SQLITE3_OPEN(filename, &db->db, flags) == SQLITE_OK) {
        /* database handle already in the stack - return it */
        return 1;
    }








>







2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
    }
    lua_pushstring(L, oldtemp);
    return 1;
}
#endif

static int lsqlite_do_open(lua_State *L, const char *filename, int flags) {
    sqlite3_initialize(); /* initialize the engine if hasn't been done yet */
    sdb *db = newdb(L); /* create and leave in stack */

    if (SQLITE3_OPEN(filename, &db->db, flags) == SQLITE_OK) {
        /* database handle already in the stack - return it */
        return 1;
    }

2159
2160
2161
2162
2163
2164
2165






























































2166
2167
2168
2169
2170
2171
2172
    if (rc != SQLITE_OK)
        luaL_argerror(L, 1, "not a valid SQLite3 pointer");

    db = newdb(L); /* create and leave in stack */
    db->db = db_ptr;
    return 1;
}































































static int lsqlite_newindex(lua_State *L) {
    lua_pushliteral(L, "attempt to change readonly table");
    lua_error(L);
    return 0;
}








>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
    if (rc != SQLITE_OK)
        luaL_argerror(L, 1, "not a valid SQLite3 pointer");

    db = newdb(L); /* create and leave in stack */
    db->db = db_ptr;
    return 1;
}

/*
** Log callback:
** Params: user, result code, log message
** Returns: none
*/
static void log_callback(void* user, int rc, const char *msg) {
    if (log_cb != LUA_NOREF) {
        lua_State *L = (lua_State*)user;

        /* setup lua callback call */
        int top = lua_gettop(L);
        lua_rawgeti(L, LUA_REGISTRYINDEX, log_cb);    /* get callback */
        lua_rawgeti(L, LUA_REGISTRYINDEX, log_udata); /* get callback user data */
        lua_pushinteger(L, rc);
        lua_pushstring(L, msg);

        if (lua_pcall(L, 3, 0, 0) != LUA_OK) lua_error(L);

        lua_settop(L, top);
    }
}

static int lsqlite_config(lua_State *L) {
    int rc = SQLITE_MISUSE;
    int option = luaL_checkint(L, 1);

    switch (option) {
        case SQLITE_CONFIG_SINGLETHREAD:
        case SQLITE_CONFIG_MULTITHREAD:
        case SQLITE_CONFIG_SERIALIZED:
            if ((rc = sqlite3_config(option)) == SQLITE_OK) {
                lua_pushinteger(L, rc);
                return 1;
            }
            break;
        case SQLITE_CONFIG_LOG:
            /* make sure we have an userdata field (even if nil) */
            lua_settop(L, 3);

            // prepate to return current (possibly nil) values
            lua_pushinteger(L, SQLITE_OK);
            lua_rawgeti(L, LUA_REGISTRYINDEX, log_cb);    /* get callback */
            lua_rawgeti(L, LUA_REGISTRYINDEX, log_udata); /* get callback user data */

            luaL_unref(L, LUA_REGISTRYINDEX, log_cb);
            luaL_unref(L, LUA_REGISTRYINDEX, log_udata);
            if (lua_isnil(L, 2)) {
                log_cb =
                log_udata = LUA_NOREF;
            }
            else {
                luaL_checktype(L, 2, LUA_TFUNCTION);
                lua_pushvalue(L, 2);
                lua_pushvalue(L, 3);
                log_udata = luaL_ref(L, LUA_REGISTRYINDEX);
                log_cb = luaL_ref(L, LUA_REGISTRYINDEX);
            }
            return 3;  // return OK and previous callback and userdata
    }
    return pusherr(L, rc);
}

static int lsqlite_newindex(lua_State *L) {
    lua_pushliteral(L, "attempt to change readonly table");
    lua_error(L);
    return 0;
}

2251
2252
2253
2254
2255
2256
2257
2258

























2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275

2276
2277
2278
2279
2280
2281
2282
2283
2284
2285

2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301














2302
2303
2304
2305
2306
2307
2308
    SC(OPEN_CREATE)
    SC(OPEN_URI)
    SC(OPEN_MEMORY)
    SC(OPEN_NOMUTEX)
    SC(OPEN_FULLMUTEX)
    SC(OPEN_SHAREDCACHE)
    SC(OPEN_PRIVATECACHE)
    

























    /* terminator */
    { NULL, 0 }
};

/* ======================================================= */

static const luaL_Reg dblib[] = {
    {"isopen",              db_isopen               },
    {"last_insert_rowid",   db_last_insert_rowid    },
    {"changes",             db_changes              },
    {"total_changes",       db_total_changes        },
    {"errcode",             db_errcode              },
    {"error_code",          db_errcode              },
    {"errmsg",              db_errmsg               },
    {"error_message",       db_errmsg               },
    {"interrupt",           db_interrupt            },
    {"db_filename",         db_db_filename          },


    {"create_function",     db_create_function      },
    {"create_aggregate",    db_create_aggregate     },
    {"create_collation",    db_create_collation     },
    {"load_extension",      db_load_extension       },

    {"trace",               db_trace                },
    {"progress_handler",    db_progress_handler     },
    {"busy_timeout",        db_busy_timeout         },
    {"busy_handler",        db_busy_handler         },

#if !defined(LSQLITE_OMIT_UPDATE_HOOK) || !LSQLITE_OMIT_UPDATE_HOOK
    {"update_hook",         db_update_hook          },
    {"commit_hook",         db_commit_hook          },
    {"rollback_hook",       db_rollback_hook        },
#endif

    {"prepare",             db_prepare              },
    {"rows",                db_rows                 },
    {"urows",               db_urows                },
    {"nrows",               db_nrows                },

    {"exec",                db_exec                 },
    {"execute",             db_exec                 },
    {"close",               db_close                },
    {"close_vm",            db_close_vm             },
    {"get_ptr",             db_get_ptr              },















    {"__tostring",          db_tostring             },
    {"__gc",                db_gc                   },

    {NULL, NULL}
};








|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>

















>










>
















>
>
>
>
>
>
>
>
>
>
>
>
>
>







3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
    SC(OPEN_CREATE)
    SC(OPEN_URI)
    SC(OPEN_MEMORY)
    SC(OPEN_NOMUTEX)
    SC(OPEN_FULLMUTEX)
    SC(OPEN_SHAREDCACHE)
    SC(OPEN_PRIVATECACHE)

    /* config flags */
    SC(CONFIG_SINGLETHREAD)
    SC(CONFIG_MULTITHREAD)
    SC(CONFIG_SERIALIZED)
    SC(CONFIG_LOG)

    /* checkpoint flags */
    SC(CHECKPOINT_PASSIVE)
    SC(CHECKPOINT_FULL)
    SC(CHECKPOINT_RESTART)
    SC(CHECKPOINT_TRUNCATE)

#ifdef SQLITE_ENABLE_SESSION
    /* session constants */
    SC(CHANGESETAPPLY_NOSAVEPOINT)
    SC(CHANGESET_DATA)
    SC(CHANGESET_NOTFOUND)
    SC(CHANGESET_CONFLICT)
    SC(CHANGESET_CONSTRAINT)
    SC(CHANGESET_FOREIGN_KEY)
    SC(CHANGESET_OMIT)
    SC(CHANGESET_REPLACE)
    SC(CHANGESET_ABORT)
#endif

    /* terminator */
    { NULL, 0 }
};

/* ======================================================= */

static const luaL_Reg dblib[] = {
    {"isopen",              db_isopen               },
    {"last_insert_rowid",   db_last_insert_rowid    },
    {"changes",             db_changes              },
    {"total_changes",       db_total_changes        },
    {"errcode",             db_errcode              },
    {"error_code",          db_errcode              },
    {"errmsg",              db_errmsg               },
    {"error_message",       db_errmsg               },
    {"interrupt",           db_interrupt            },
    {"db_filename",         db_db_filename          },
    {"wal_checkpoint",      db_wal_checkpoint       },

    {"create_function",     db_create_function      },
    {"create_aggregate",    db_create_aggregate     },
    {"create_collation",    db_create_collation     },
    {"load_extension",      db_load_extension       },

    {"trace",               db_trace                },
    {"progress_handler",    db_progress_handler     },
    {"busy_timeout",        db_busy_timeout         },
    {"busy_handler",        db_busy_handler         },
    {"wal_hook",            db_wal_hook             },
#if !defined(LSQLITE_OMIT_UPDATE_HOOK) || !LSQLITE_OMIT_UPDATE_HOOK
    {"update_hook",         db_update_hook          },
    {"commit_hook",         db_commit_hook          },
    {"rollback_hook",       db_rollback_hook        },
#endif

    {"prepare",             db_prepare              },
    {"rows",                db_rows                 },
    {"urows",               db_urows                },
    {"nrows",               db_nrows                },

    {"exec",                db_exec                 },
    {"execute",             db_exec                 },
    {"close",               db_close                },
    {"close_vm",            db_close_vm             },
    {"get_ptr",             db_get_ptr              },

#ifdef SQLITE_ENABLE_SESSION
    {"create_session",      db_create_session       },
    {"create_rebaser",      db_create_rebaser       },
    {"apply_changeset",     db_apply_changeset      },
    {"invert_changeset",    db_invert_changeset     },
    {"concat_changeset",    db_concat_changeset     },
    {"iterate_changeset",   db_iterate_changeset    },
#endif

#ifdef SQLITE_ENABLE_DESERIALIZE
    {"serialize",           db_serialize            },
    {"deserialize",         db_deserialize          },
#endif

    {"__tostring",          db_tostring             },
    {"__gc",                db_gc                   },

    {NULL, NULL}
};

2381
2382
2383
2384
2385
2386
2387
2388










































2389
2390
2391
2392

2393
2394
2395
2396
2397
2398
2399
    {"pagecount",   dbbu_pagecount  },
    {"finish",      dbbu_finish     },

/*  {"__tostring",  dbbu_tostring   },   */
    {"__gc",        dbbu_gc         },
    {NULL, NULL}
};











































static const luaL_Reg sqlitelib[] = {
    {"lversion",        lsqlite_lversion        },
    {"version",         lsqlite_version         },
    {"complete",        lsqlite_complete        },

#ifndef _WIN32
    {"temp_directory",  lsqlite_temp_directory  },
#endif
    {"open",            lsqlite_open            },
    {"open_memory",     lsqlite_open_memory     },
    {"open_ptr",        lsqlite_open_ptr        },









>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>




>







3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
    {"pagecount",   dbbu_pagecount  },
    {"finish",      dbbu_finish     },

/*  {"__tostring",  dbbu_tostring   },   */
    {"__gc",        dbbu_gc         },
    {NULL, NULL}
};

#ifdef SQLITE_ENABLE_SESSION

static const luaL_Reg seslib[] = {
    {"attach",          lsession_attach         },
    {"changeset",       lsession_changeset      },
    {"patchset",        lsession_patchset       },
    {"isempty",         lsession_isempty        },
    {"indirect",        lsession_indirect       },
    {"enable",          lsession_enable         },
    {"diff",            lsession_diff           },
    {"delete",          lsession_delete         },

    {"__tostring",      lsession_tostring       },
    {NULL, NULL}
};

static const luaL_Reg reblib[] = {
    {"rebase",          lrebaser_rebase         },
    {"delete",          lrebaser_delete         },

    {"__tostring",      lrebaser_tostring       },
    {"__gc",            lrebaser_gc             },
    {NULL, NULL}
};

static const luaL_Reg itrlib[] = {
    {"op",              liter_op                },
    {"pk",              liter_pk                },
    {"new",             liter_new               },
    {"old",             liter_old               },
    {"next",            liter_next              },
    {"conflict",        liter_conflict          },
    {"finalize",        liter_finalize          },
    {"fk_conflicts",    liter_fk_conflicts      },

    {"__tostring",      liter_tostring          },
    {"__gc",            liter_gc                },
    {NULL, NULL}
};

#endif

static const luaL_Reg sqlitelib[] = {
    {"lversion",        lsqlite_lversion        },
    {"version",         lsqlite_version         },
    {"complete",        lsqlite_complete        },
    {"config",          lsqlite_config          },
#ifndef _WIN32
    {"temp_directory",  lsqlite_temp_directory  },
#endif
    {"open",            lsqlite_open            },
    {"open_memory",     lsqlite_open_memory     },
    {"open_ptr",        lsqlite_open_ptr        },

2413
2414
2415
2416
2417
2418
2419



2420
2421
2422
2423
2424
2425
2426















2427
2428
2429
2430
2431
2432
2433
    luaL_openlib(L, NULL, lib, 0);

    /* remove metatable from stack */
    lua_pop(L, 1);
}

LUALIB_API int luaopen_lsqlite3(lua_State *L) {



    create_meta(L, sqlite_meta, dblib);
    create_meta(L, sqlite_vm_meta, vmlib);
    create_meta(L, sqlite_bu_meta, dbbulib);
    create_meta(L, sqlite_ctx_meta, ctxlib);

    luaL_getmetatable(L, sqlite_ctx_meta);
    sqlite_ctx_meta_ref = luaL_ref(L, LUA_REGISTRYINDEX);
















    /* register (local) sqlite metatable */
    luaL_register(L, "sqlite3", sqlitelib);

    {
        int i = 0;
        /* add constants to global table */







>
>
>







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
    luaL_openlib(L, NULL, lib, 0);

    /* remove metatable from stack */
    lua_pop(L, 1);
}

LUALIB_API int luaopen_lsqlite3(lua_State *L) {
    /* call config before calling initialize */
    sqlite3_config(SQLITE_CONFIG_LOG, log_callback, L);

    create_meta(L, sqlite_meta, dblib);
    create_meta(L, sqlite_vm_meta, vmlib);
    create_meta(L, sqlite_bu_meta, dbbulib);
    create_meta(L, sqlite_ctx_meta, ctxlib);

    luaL_getmetatable(L, sqlite_ctx_meta);
    sqlite_ctx_meta_ref = luaL_ref(L, LUA_REGISTRYINDEX);

#ifdef SQLITE_ENABLE_SESSION
    create_meta(L, sqlite_ses_meta, seslib);
    create_meta(L, sqlite_reb_meta, reblib);
    create_meta(L, sqlite_itr_meta, itrlib);

    luaL_getmetatable(L, sqlite_ses_meta);
    sqlite_ses_meta_ref = luaL_ref(L, LUA_REGISTRYINDEX);

    luaL_getmetatable(L, sqlite_reb_meta);
    sqlite_reb_meta_ref = luaL_ref(L, LUA_REGISTRYINDEX);

    luaL_getmetatable(L, sqlite_itr_meta);
    sqlite_itr_meta_ref = luaL_ref(L, LUA_REGISTRYINDEX);
#endif

    /* register (local) sqlite metatable */
    luaL_register(L, "sqlite3", sqlitelib);

    {
        int i = 0;
        /* add constants to global table */
Changes to lsqlite3complete-0.9.5-1.rockspec.
20
21
22
23
24
25
26


27



28
29
30
31
32
33
34
    "lua >= 5.1, < 5.5"
}
build = {
    type = "builtin",
    modules = {
        lsqlite3complete = {
            sources = { "lsqlite3.c", "sqlite3.c" },


            defines = {'LSQLITE_VERSION="0.9.5"', 'luaopen_lsqlite3=luaopen_lsqlite3complete'}



        },
    },
    platforms = {
        unix = {
            modules = {
                lsqlite3complete = {
                    libraries = { "pthread", "m", "dl" }







>
>
|
>
>
>







20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
    "lua >= 5.1, < 5.5"
}
build = {
    type = "builtin",
    modules = {
        lsqlite3complete = {
            sources = { "lsqlite3.c", "sqlite3.c" },
            defines = {
                'LSQLITE_VERSION="0.9.5"',
                'luaopen_lsqlite3=luaopen_lsqlite3complete',
                'SQLITE_ENABLE_SESSION',
                'SQLITE_ENABLE_PREUPDATE_HOOK'
            }
        },
    },
    platforms = {
        unix = {
            modules = {
                lsqlite3complete = {
                    libraries = { "pthread", "m", "dl" }