1/*
2   +----------------------------------------------------------------------+
3   | PHP Version 7                                                        |
4   +----------------------------------------------------------------------+
5   | Copyright (c) 1997-2014 The PHP Group                                |
6   +----------------------------------------------------------------------+
7   | This source file is subject to version 3.01 of the PHP license,      |
8   | that is bundled with this package in the file LICENSE, and is        |
9   | available through the world-wide-web at the following url:           |
10   | http://www.php.net/license/3_01.txt                                  |
11   | If you did not receive a copy of the PHP license and are unable to   |
12   | obtain it through the world-wide-web, please send a note to          |
13   | license@php.net so we can mail you a copy immediately.               |
14   +----------------------------------------------------------------------+
15   | Authors: Scott MacVicar <scottmac@php.net>                           |
16   +----------------------------------------------------------------------+
17*/
18
19/* $Id$ */
20
21#ifdef HAVE_CONFIG_H
22#include "config.h"
23#endif
24
25#include "php.h"
26#include "php_ini.h"
27#include "ext/standard/info.h"
28#include "php_sqlite3.h"
29#include "php_sqlite3_structs.h"
30#include "main/SAPI.h"
31
32#include <sqlite3.h>
33
34#include "zend_exceptions.h"
35#include "zend_interfaces.h"
36#include "SAPI.h"
37
38ZEND_DECLARE_MODULE_GLOBALS(sqlite3)
39
40static PHP_GINIT_FUNCTION(sqlite3);
41static int php_sqlite3_authorizer(void *autharg, int access_type, const char *arg3, const char *arg4, const char *arg5, const char *arg6);
42static void sqlite3_param_dtor(zval *data);
43static int php_sqlite3_compare_stmt_zval_free(php_sqlite3_free_list **free_list, zval *statement);
44
45/* {{{ Error Handler
46*/
47static void php_sqlite3_error(php_sqlite3_db_object *db_obj, char *format, ...)
48{
49    va_list arg;
50    char    *message;
51
52    va_start(arg, format);
53    vspprintf(&message, 0, format, arg);
54    va_end(arg);
55
56    if (db_obj && db_obj->exception) {
57        zend_throw_exception(zend_exception_get_default(), message, 0);
58    } else {
59        php_error_docref(NULL, E_WARNING, "%s", message);
60    }
61
62    if (message) {
63        efree(message);
64    }
65}
66/* }}} */
67
68#define SQLITE3_CHECK_INITIALIZED(db_obj, member, class_name) \
69    if (!(db_obj) || !(member)) { \
70        php_sqlite3_error(db_obj, "The " #class_name " object has not been correctly initialised"); \
71        RETURN_FALSE; \
72    }
73
74#define SQLITE3_CHECK_INITIALIZED_STMT(member, class_name) \
75    if (!(member)) { \
76        php_error_docref(NULL, E_WARNING, "The " #class_name " object has not been correctly initialised"); \
77        RETURN_FALSE; \
78    }
79
80/* {{{ PHP_INI
81*/
82PHP_INI_BEGIN()
83    STD_PHP_INI_ENTRY("sqlite3.extension_dir",  NULL, PHP_INI_SYSTEM, OnUpdateString, extension_dir, zend_sqlite3_globals, sqlite3_globals)
84PHP_INI_END()
85/* }}} */
86
87/* Handlers */
88static zend_object_handlers sqlite3_object_handlers;
89static zend_object_handlers sqlite3_stmt_object_handlers;
90static zend_object_handlers sqlite3_result_object_handlers;
91
92/* Class entries */
93zend_class_entry *php_sqlite3_sc_entry;
94zend_class_entry *php_sqlite3_stmt_entry;
95zend_class_entry *php_sqlite3_result_entry;
96
97/* {{{ proto void SQLite3::open(String filename [, int Flags [, string Encryption Key]])
98   Opens a SQLite 3 Database, if the build includes encryption then it will attempt to use the key. */
99PHP_METHOD(sqlite3, open)
100{
101    php_sqlite3_db_object *db_obj;
102    zval *object = getThis();
103    char *filename, *encryption_key, *fullpath;
104    size_t filename_len, encryption_key_len = 0;
105    zend_long flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE;
106    zend_error_handling error_handling;
107
108    db_obj = Z_SQLITE3_DB_P(object);
109    zend_replace_error_handling(EH_THROW, NULL, &error_handling);
110
111    if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS(), "p|ls", &filename, &filename_len, &flags, &encryption_key, &encryption_key_len)) {
112        zend_restore_error_handling(&error_handling);
113        return;
114    }
115
116    zend_restore_error_handling(&error_handling);
117
118    if (db_obj->initialised) {
119        zend_throw_exception(zend_exception_get_default(), "Already initialised DB Object", 0);
120    }
121
122    if (strlen(filename) != filename_len) {
123        return;
124    }
125    if (memcmp(filename, ":memory:", sizeof(":memory:")) != 0) {
126        if (!(fullpath = expand_filepath(filename, NULL))) {
127            zend_throw_exception(zend_exception_get_default(), "Unable to expand filepath", 0);
128            return;
129        }
130
131#if PHP_API_VERSION < 20100412
132        if (PG(safe_mode) && (!php_checkuid(fullpath, NULL, CHECKUID_CHECK_FILE_AND_DIR))) {
133            zend_throw_exception_ex(zend_exception_get_default(), 0, "safe_mode prohibits opening %s", fullpath);
134            efree(fullpath);
135            return;
136        }
137#endif
138
139        if (php_check_open_basedir(fullpath)) {
140            zend_throw_exception_ex(zend_exception_get_default(), 0, "open_basedir prohibits opening %s", fullpath);
141            efree(fullpath);
142            return;
143        }
144    } else {
145        fullpath = estrdup(filename);
146    }
147
148#if SQLITE_VERSION_NUMBER >= 3005000
149    if (sqlite3_open_v2(fullpath, &(db_obj->db), flags, NULL) != SQLITE_OK) {
150#else
151    if (sqlite3_open(fullpath, &(db_obj->db)) != SQLITE_OK) {
152#endif
153        zend_throw_exception_ex(zend_exception_get_default(), 0, "Unable to open database: %s", sqlite3_errmsg(db_obj->db));
154        if (fullpath) {
155            efree(fullpath);
156        }
157        return;
158    }
159
160#if SQLITE_HAS_CODEC
161    if (encryption_key_len > 0) {
162        if (sqlite3_key(db_obj->db, encryption_key, encryption_key_len) != SQLITE_OK) {
163            zend_throw_exception_ex(zend_exception_get_default(), 0, "Unable to open database: %s", sqlite3_errmsg(db_obj->db));
164            return;
165        }
166    }
167#endif
168
169    db_obj->initialised = 1;
170
171#if PHP_API_VERSION < 20100412
172    if (PG(safe_mode) || (PG(open_basedir) && *PG(open_basedir))) {
173#else
174    if (PG(open_basedir) && *PG(open_basedir)) {
175#endif
176        sqlite3_set_authorizer(db_obj->db, php_sqlite3_authorizer, NULL);
177    }
178
179    if (fullpath) {
180        efree(fullpath);
181    }
182}
183/* }}} */
184
185/* {{{ proto bool SQLite3::close()
186   Close a SQLite 3 Database. */
187PHP_METHOD(sqlite3, close)
188{
189    php_sqlite3_db_object *db_obj;
190    zval *object = getThis();
191    int errcode;
192    db_obj = Z_SQLITE3_DB_P(object);
193
194    if (zend_parse_parameters_none() == FAILURE) {
195        return;
196    }
197
198    if (db_obj->initialised) {
199        zend_llist_clean(&(db_obj->free_list));
200        if(db_obj->db) {
201            errcode = sqlite3_close(db_obj->db);
202            if (errcode != SQLITE_OK) {
203                php_sqlite3_error(db_obj, "Unable to close database: %d, %s", errcode, sqlite3_errmsg(db_obj->db));
204                RETURN_FALSE;
205            }
206        }
207        db_obj->initialised = 0;
208    }
209
210    RETURN_TRUE;
211}
212/* }}} */
213
214/* {{{ proto bool SQLite3::exec(String Query)
215   Executes a result-less query against a given database. */
216PHP_METHOD(sqlite3, exec)
217{
218    php_sqlite3_db_object *db_obj;
219    zval *object = getThis();
220    zend_string *sql;
221    char *errtext = NULL;
222    db_obj = Z_SQLITE3_DB_P(object);
223
224    SQLITE3_CHECK_INITIALIZED(db_obj, db_obj->initialised, SQLite3)
225
226    if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS(), "S", &sql)) {
227        return;
228    }
229
230    if (sqlite3_exec(db_obj->db, sql->val, NULL, NULL, &errtext) != SQLITE_OK) {
231        php_sqlite3_error(db_obj, "%s", errtext);
232        sqlite3_free(errtext);
233        RETURN_FALSE;
234    }
235
236    RETURN_TRUE;
237}
238/* }}} */
239
240/* {{{ proto Array SQLite3::version()
241   Returns the SQLite3 Library version as a string constant and as a number. */
242PHP_METHOD(sqlite3, version)
243{
244    if (zend_parse_parameters_none() == FAILURE) {
245        return;
246    }
247
248    array_init(return_value);
249
250    add_assoc_string(return_value, "versionString", (char*)sqlite3_libversion());
251    add_assoc_long(return_value, "versionNumber", sqlite3_libversion_number());
252
253    return;
254}
255/* }}} */
256
257/* {{{ proto int SQLite3::lastInsertRowID()
258   Returns the rowid of the most recent INSERT into the database from the database connection. */
259PHP_METHOD(sqlite3, lastInsertRowID)
260{
261    php_sqlite3_db_object *db_obj;
262    zval *object = getThis();
263    db_obj = Z_SQLITE3_DB_P(object);
264
265    SQLITE3_CHECK_INITIALIZED(db_obj, db_obj->initialised, SQLite3)
266
267    if (zend_parse_parameters_none() == FAILURE) {
268        return;
269    }
270
271    RETURN_LONG(sqlite3_last_insert_rowid(db_obj->db));
272}
273/* }}} */
274
275/* {{{ proto int SQLite3::lastErrorCode()
276   Returns the numeric result code of the most recent failed sqlite API call for the database connection. */
277PHP_METHOD(sqlite3, lastErrorCode)
278{
279    php_sqlite3_db_object *db_obj;
280    zval *object = getThis();
281    db_obj = Z_SQLITE3_DB_P(object);
282
283    SQLITE3_CHECK_INITIALIZED(db_obj, db_obj->db, SQLite3)
284
285    if (zend_parse_parameters_none() == FAILURE) {
286        return;
287    }
288
289    RETURN_LONG(sqlite3_errcode(db_obj->db));
290}
291/* }}} */
292
293/* {{{ proto string SQLite3::lastErrorMsg()
294   Returns english text describing the most recent failed sqlite API call for the database connection. */
295PHP_METHOD(sqlite3, lastErrorMsg)
296{
297    php_sqlite3_db_object *db_obj;
298    zval *object = getThis();
299    db_obj = Z_SQLITE3_DB_P(object);
300
301    SQLITE3_CHECK_INITIALIZED(db_obj, db_obj->db, SQLite3)
302
303    if (zend_parse_parameters_none() == FAILURE) {
304        return;
305    }
306
307    RETVAL_STRING((char *)sqlite3_errmsg(db_obj->db));
308}
309/* }}} */
310
311/* {{{ proto bool SQLite3::busyTimeout(int msecs)
312   Sets a busy handler that will sleep until database is not locked or timeout is reached. Passing a value less than or equal to zero turns off all busy handlers. */
313PHP_METHOD(sqlite3, busyTimeout)
314{
315    php_sqlite3_db_object *db_obj;
316    zval *object = getThis();
317    zend_long ms;
318    int return_code;
319    db_obj = Z_SQLITE3_DB_P(object);
320
321    SQLITE3_CHECK_INITIALIZED(db_obj, db_obj->initialised, SQLite3)
322
323    if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS(), "l", &ms)) {
324        return;
325    }
326
327    return_code = sqlite3_busy_timeout(db_obj->db, ms);
328    if (return_code != SQLITE_OK) {
329        php_sqlite3_error(db_obj, "Unable to set busy timeout: %d, %s", return_code, sqlite3_errmsg(db_obj->db));
330        RETURN_FALSE;
331    }
332
333    RETURN_TRUE;
334}
335/* }}} */
336
337
338#ifndef SQLITE_OMIT_LOAD_EXTENSION
339/* {{{ proto bool SQLite3::loadExtension(String Shared Library)
340   Attempts to load an SQLite extension library. */
341PHP_METHOD(sqlite3, loadExtension)
342{
343    php_sqlite3_db_object *db_obj;
344    zval *object = getThis();
345    char *extension, *lib_path, *extension_dir, *errtext = NULL;
346    char fullpath[MAXPATHLEN];
347    size_t extension_len, extension_dir_len;
348    db_obj = Z_SQLITE3_DB_P(object);
349
350    SQLITE3_CHECK_INITIALIZED(db_obj, db_obj->initialised, SQLite3)
351
352    if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS(), "s", &extension, &extension_len)) {
353        return;
354    }
355
356#ifdef ZTS
357    if ((strncmp(sapi_module.name, "cgi", 3) != 0) &&
358        (strcmp(sapi_module.name, "cli") != 0) &&
359        (strncmp(sapi_module.name, "embed", 5) != 0)
360    ) {     php_sqlite3_error(db_obj, "Not supported in multithreaded Web servers");
361        RETURN_FALSE;
362    }
363#endif
364
365    if (!SQLITE3G(extension_dir)) {
366        php_sqlite3_error(db_obj, "SQLite Extension are disabled");
367        RETURN_FALSE;
368    }
369
370    if (extension_len == 0) {
371        php_sqlite3_error(db_obj, "Empty string as an extension");
372        RETURN_FALSE;
373    }
374
375    extension_dir = SQLITE3G(extension_dir);
376    extension_dir_len = strlen(SQLITE3G(extension_dir));
377
378    if (IS_SLASH(extension_dir[extension_dir_len-1])) {
379        spprintf(&lib_path, 0, "%s%s", extension_dir, extension);
380    } else {
381        spprintf(&lib_path, 0, "%s%c%s", extension_dir, DEFAULT_SLASH, extension);
382    }
383
384    if (!VCWD_REALPATH(lib_path, fullpath)) {
385        php_sqlite3_error(db_obj, "Unable to load extension at '%s'", lib_path);
386        efree(lib_path);
387        RETURN_FALSE;
388    }
389
390    efree(lib_path);
391
392    if (strncmp(fullpath, extension_dir, extension_dir_len) != 0) {
393        php_sqlite3_error(db_obj, "Unable to open extensions outside the defined directory");
394        RETURN_FALSE;
395    }
396
397    /* Extension loading should only be enabled for when we attempt to load */
398    sqlite3_enable_load_extension(db_obj->db, 1);
399    if (sqlite3_load_extension(db_obj->db, fullpath, 0, &errtext) != SQLITE_OK) {
400        php_sqlite3_error(db_obj, "%s", errtext);
401        sqlite3_free(errtext);
402        sqlite3_enable_load_extension(db_obj->db, 0);
403        RETURN_FALSE;
404    }
405    sqlite3_enable_load_extension(db_obj->db, 0);
406
407    RETURN_TRUE;
408}
409/* }}} */
410#endif
411
412/* {{{ proto int SQLite3::changes()
413  Returns the number of database rows that were changed (or inserted or deleted) by the most recent SQL statement. */
414PHP_METHOD(sqlite3, changes)
415{
416    php_sqlite3_db_object *db_obj;
417    zval *object = getThis();
418    db_obj = Z_SQLITE3_DB_P(object);
419
420    SQLITE3_CHECK_INITIALIZED(db_obj, db_obj->initialised, SQLite3)
421
422    if (zend_parse_parameters_none() == FAILURE) {
423        return;
424    }
425
426    RETURN_LONG(sqlite3_changes(db_obj->db));
427}
428/* }}} */
429
430/* {{{ proto String SQLite3::escapeString(String value)
431   Returns a string that has been properly escaped. */
432PHP_METHOD(sqlite3, escapeString)
433{
434    zend_string *sql;
435    char *ret;
436
437    if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS(), "S", &sql)) {
438        return;
439    }
440
441    if (sql->len) {
442        ret = sqlite3_mprintf("%q", sql->val);
443        if (ret) {
444            RETVAL_STRING(ret);
445            sqlite3_free(ret);
446        }
447    } else {
448        RETURN_EMPTY_STRING();
449    }
450}
451/* }}} */
452
453/* {{{ proto SQLite3Stmt SQLite3::prepare(String Query)
454   Returns a prepared SQL statement for execution. */
455PHP_METHOD(sqlite3, prepare)
456{
457    php_sqlite3_db_object *db_obj;
458    php_sqlite3_stmt *stmt_obj;
459    zval *object = getThis();
460    zend_string *sql;
461    int errcode;
462    php_sqlite3_free_list *free_item;
463
464    db_obj = Z_SQLITE3_DB_P(object);
465
466    SQLITE3_CHECK_INITIALIZED(db_obj, db_obj->initialised, SQLite3)
467
468    if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS(), "S", &sql)) {
469        return;
470    }
471
472    if (!sql->len) {
473        RETURN_FALSE;
474    }
475
476    object_init_ex(return_value, php_sqlite3_stmt_entry);
477    stmt_obj = Z_SQLITE3_STMT_P(return_value);
478    stmt_obj->db_obj = db_obj;
479    ZVAL_COPY(&stmt_obj->db_obj_zval, object);
480
481    errcode = sqlite3_prepare_v2(db_obj->db, sql->val, sql->len, &(stmt_obj->stmt), NULL);
482    if (errcode != SQLITE_OK) {
483        php_sqlite3_error(db_obj, "Unable to prepare statement: %d, %s", errcode, sqlite3_errmsg(db_obj->db));
484        zval_dtor(return_value);
485        RETURN_FALSE;
486    }
487
488    stmt_obj->initialised = 1;
489
490    free_item = emalloc(sizeof(php_sqlite3_free_list));
491    free_item->stmt_obj = stmt_obj;
492    ZVAL_COPY_VALUE(&free_item->stmt_obj_zval, return_value);
493
494    zend_llist_add_element(&(db_obj->free_list), &free_item);
495}
496/* }}} */
497
498/* {{{ proto SQLite3Result SQLite3::query(String Query)
499   Returns true or false, for queries that return data it will return a SQLite3Result object. */
500PHP_METHOD(sqlite3, query)
501{
502    php_sqlite3_db_object *db_obj;
503    php_sqlite3_result *result;
504    php_sqlite3_stmt *stmt_obj;
505    zval *object = getThis();
506    zval stmt;
507    zend_string *sql;
508    char *errtext = NULL;
509    int return_code;
510    db_obj = Z_SQLITE3_DB_P(object);
511
512    SQLITE3_CHECK_INITIALIZED(db_obj, db_obj->initialised, SQLite3)
513
514    if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS(), "S", &sql)) {
515        return;
516    }
517
518    if (!sql->len) {
519        RETURN_FALSE;
520    }
521
522    /* If there was no return value then just execute the query */
523    if (!USED_RET()) {
524        if (sqlite3_exec(db_obj->db, sql->val, NULL, NULL, &errtext) != SQLITE_OK) {
525            php_sqlite3_error(db_obj, "%s", errtext);
526            sqlite3_free(errtext);
527        }
528        return;
529    }
530
531    object_init_ex(&stmt, php_sqlite3_stmt_entry);
532    stmt_obj = Z_SQLITE3_STMT_P(&stmt);
533    stmt_obj->db_obj = db_obj;
534    ZVAL_COPY(&stmt_obj->db_obj_zval, object);
535
536    return_code = sqlite3_prepare_v2(db_obj->db, sql->val, sql->len, &(stmt_obj->stmt), NULL);
537    if (return_code != SQLITE_OK) {
538        php_sqlite3_error(db_obj, "Unable to prepare statement: %d, %s", return_code, sqlite3_errmsg(db_obj->db));
539        zval_ptr_dtor(&stmt);
540        RETURN_FALSE;
541    }
542
543    stmt_obj->initialised = 1;
544
545    object_init_ex(return_value, php_sqlite3_result_entry);
546    result = Z_SQLITE3_RESULT_P(return_value);
547    result->db_obj = db_obj;
548    result->stmt_obj = stmt_obj;
549    ZVAL_COPY_VALUE(&result->stmt_obj_zval, &stmt);
550
551    return_code = sqlite3_step(result->stmt_obj->stmt);
552
553    switch (return_code) {
554        case SQLITE_ROW: /* Valid Row */
555        case SQLITE_DONE: /* Valid but no results */
556        {
557            php_sqlite3_free_list *free_item;
558            free_item = emalloc(sizeof(php_sqlite3_free_list));
559            free_item->stmt_obj = stmt_obj;
560            free_item->stmt_obj_zval = stmt;
561            zend_llist_add_element(&(db_obj->free_list), &free_item);
562            sqlite3_reset(result->stmt_obj->stmt);
563            break;
564        }
565        default:
566            php_sqlite3_error(db_obj, "Unable to execute statement: %s", sqlite3_errmsg(db_obj->db));
567            sqlite3_finalize(stmt_obj->stmt);
568            stmt_obj->initialised = 0;
569            zval_dtor(return_value);
570            RETURN_FALSE;
571    }
572}
573/* }}} */
574
575static void sqlite_value_to_zval(sqlite3_stmt *stmt, int column, zval *data) /* {{{ */
576{
577    switch (sqlite3_column_type(stmt, column)) {
578        case SQLITE_INTEGER:
579            if ((sqlite3_column_int64(stmt, column)) >= INT_MAX || sqlite3_column_int64(stmt, column) <= INT_MIN) {
580                ZVAL_STRINGL(data, (char *)sqlite3_column_text(stmt, column), sqlite3_column_bytes(stmt, column));
581            } else {
582                ZVAL_LONG(data, sqlite3_column_int64(stmt, column));
583            }
584            break;
585
586        case SQLITE_FLOAT:
587            ZVAL_DOUBLE(data, sqlite3_column_double(stmt, column));
588            break;
589
590        case SQLITE_NULL:
591            ZVAL_NULL(data);
592            break;
593
594        case SQLITE3_TEXT:
595            ZVAL_STRING(data, (char*)sqlite3_column_text(stmt, column));
596            break;
597
598        case SQLITE_BLOB:
599        default:
600            ZVAL_STRINGL(data, (char*)sqlite3_column_blob(stmt, column), sqlite3_column_bytes(stmt, column));
601    }
602}
603/* }}} */
604
605/* {{{ proto SQLite3Result SQLite3::querySingle(String Query [, bool entire_row = false])
606   Returns a string of the first column, or an array of the entire row. */
607PHP_METHOD(sqlite3, querySingle)
608{
609    php_sqlite3_db_object *db_obj;
610    zval *object = getThis();
611    zend_string *sql;
612    char *errtext = NULL;
613    int return_code;
614    zend_bool entire_row = 0;
615    sqlite3_stmt *stmt;
616    db_obj = Z_SQLITE3_DB_P(object);
617
618    SQLITE3_CHECK_INITIALIZED(db_obj, db_obj->initialised, SQLite3)
619
620    if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS(), "S|b", &sql, &entire_row)) {
621        return;
622    }
623
624    if (!sql->len) {
625        RETURN_FALSE;
626    }
627
628    /* If there was no return value then just execute the query */
629    if (!USED_RET()) {
630        if (sqlite3_exec(db_obj->db, sql->val, NULL, NULL, &errtext) != SQLITE_OK) {
631            php_sqlite3_error(db_obj, "%s", errtext);
632            sqlite3_free(errtext);
633        }
634        return;
635    }
636
637    return_code = sqlite3_prepare_v2(db_obj->db, sql->val, sql->len, &stmt, NULL);
638    if (return_code != SQLITE_OK) {
639        php_sqlite3_error(db_obj, "Unable to prepare statement: %d, %s", return_code, sqlite3_errmsg(db_obj->db));
640        RETURN_FALSE;
641    }
642
643    return_code = sqlite3_step(stmt);
644
645    switch (return_code) {
646        case SQLITE_ROW: /* Valid Row */
647        {
648            if (!entire_row) {
649                sqlite_value_to_zval(stmt, 0, return_value);
650            } else {
651                int i = 0;
652                array_init(return_value);
653                for (i = 0; i < sqlite3_data_count(stmt); i++) {
654                    zval data;
655                    sqlite_value_to_zval(stmt, i, &data);
656                    add_assoc_zval(return_value, (char*)sqlite3_column_name(stmt, i), &data);
657                }
658            }
659            break;
660        }
661        case SQLITE_DONE: /* Valid but no results */
662        {
663            if (!entire_row) {
664                RETVAL_NULL();
665            } else {
666                array_init(return_value);
667            }
668            break;
669        }
670        default:
671            php_sqlite3_error(db_obj, "Unable to execute statement: %s", sqlite3_errmsg(db_obj->db));
672            RETVAL_FALSE;
673    }
674    sqlite3_finalize(stmt);
675}
676/* }}} */
677
678static int sqlite3_do_callback(struct php_sqlite3_fci *fc, zval *cb, int argc, sqlite3_value **argv, sqlite3_context *context, int is_agg) /* {{{ */
679{
680    zval *zargs = NULL;
681    zval retval;
682    int i;
683    int ret;
684    int fake_argc;
685    php_sqlite3_agg_context *agg_context = NULL;
686
687    if (is_agg) {
688        is_agg = 2;
689    }
690
691    fake_argc = argc + is_agg;
692
693    fc->fci.size = sizeof(fc->fci);
694    fc->fci.function_table = EG(function_table);
695    ZVAL_COPY_VALUE(&fc->fci.function_name, cb);
696    fc->fci.symbol_table = NULL;
697    fc->fci.object = NULL;
698    fc->fci.retval = &retval;
699    fc->fci.param_count = fake_argc;
700
701    /* build up the params */
702
703    if (fake_argc) {
704        zargs = (zval *)safe_emalloc(fake_argc, sizeof(zval), 0);
705    }
706
707    if (is_agg) {
708        /* summon the aggregation context */
709        agg_context = (php_sqlite3_agg_context *)sqlite3_aggregate_context(context, sizeof(php_sqlite3_agg_context));
710
711        if (Z_ISUNDEF(agg_context->zval_context)) {
712            ZVAL_NULL(&agg_context->zval_context);
713        }
714        ZVAL_COPY_VALUE(&zargs[0], &agg_context->zval_context);
715        ZVAL_LONG(&zargs[1], agg_context->row_count);
716    }
717
718    for (i = 0; i < argc; i++) {
719        switch (sqlite3_value_type(argv[i])) {
720            case SQLITE_INTEGER:
721#if ZEND_LONG_MAX > 2147483647
722                ZVAL_LONG(&zargs[i + is_agg], sqlite3_value_int64(argv[i]));
723#else
724                ZVAL_LONG(&zargs[i + is_agg], sqlite3_value_int(argv[i]));
725#endif
726                break;
727
728            case SQLITE_FLOAT:
729                ZVAL_DOUBLE(&zargs[i + is_agg], sqlite3_value_double(argv[i]));
730                break;
731
732            case SQLITE_NULL:
733                ZVAL_NULL(&zargs[i + is_agg]);
734                break;
735
736            case SQLITE_BLOB:
737            case SQLITE3_TEXT:
738            default:
739                ZVAL_STRINGL(&zargs[i + is_agg], (char*)sqlite3_value_text(argv[i]), sqlite3_value_bytes(argv[i]));
740                break;
741        }
742    }
743
744    fc->fci.params = zargs;
745
746    if ((ret = zend_call_function(&fc->fci, &fc->fcc)) == FAILURE) {
747        php_error_docref(NULL, E_WARNING, "An error occurred while invoking the callback");
748    }
749
750    /* clean up the params */
751    if (fake_argc) {
752        for (i = is_agg; i < argc + is_agg; i++) {
753            zval_ptr_dtor(&zargs[i]);
754        }
755        if (is_agg) {
756            zval_ptr_dtor(&zargs[1]);
757        }
758        efree(zargs);
759    }
760
761    if (!is_agg || !argv) {
762        /* only set the sqlite return value if we are a scalar function,
763         * or if we are finalizing an aggregate */
764        if (!Z_ISUNDEF(retval)) {
765            switch (Z_TYPE(retval)) {
766                case IS_LONG:
767#if ZEND_LONG_MAX > 2147483647
768                    sqlite3_result_int64(context, Z_LVAL(retval));
769#else
770                    sqlite3_result_int(context, Z_LVAL(retval));
771#endif
772                    break;
773
774                case IS_NULL:
775                    sqlite3_result_null(context);
776                    break;
777
778                case IS_DOUBLE:
779                    sqlite3_result_double(context, Z_DVAL(retval));
780                    break;
781
782                default:
783                    convert_to_string_ex(&retval);
784                    sqlite3_result_text(context, Z_STRVAL(retval), Z_STRLEN(retval), SQLITE_TRANSIENT);
785                    break;
786            }
787        } else {
788            sqlite3_result_error(context, "failed to invoke callback", 0);
789        }
790
791        if (agg_context && !Z_ISUNDEF(agg_context->zval_context)) {
792            zval_ptr_dtor(&agg_context->zval_context);
793        }
794    } else {
795        /* we're stepping in an aggregate; the return value goes into
796         * the context */
797        if (agg_context && !Z_ISUNDEF(agg_context->zval_context)) {
798            zval_ptr_dtor(&agg_context->zval_context);
799        }
800        ZVAL_COPY_VALUE(&agg_context->zval_context, &retval);
801        ZVAL_UNDEF(&retval);
802    }
803
804    if (!Z_ISUNDEF(retval)) {
805        zval_ptr_dtor(&retval);
806    }
807    return ret;
808}
809/* }}}*/
810
811static void php_sqlite3_callback_func(sqlite3_context *context, int argc, sqlite3_value **argv) /* {{{ */
812{
813    php_sqlite3_func *func = (php_sqlite3_func *)sqlite3_user_data(context);
814
815    sqlite3_do_callback(&func->afunc, &func->func, argc, argv, context, 0);
816}
817/* }}}*/
818
819static void php_sqlite3_callback_step(sqlite3_context *context, int argc, sqlite3_value **argv) /* {{{ */
820{
821    php_sqlite3_func *func = (php_sqlite3_func *)sqlite3_user_data(context);
822    php_sqlite3_agg_context *agg_context = (php_sqlite3_agg_context *)sqlite3_aggregate_context(context, sizeof(php_sqlite3_agg_context));
823
824    agg_context->row_count++;
825
826    sqlite3_do_callback(&func->astep, &func->step, argc, argv, context, 1);
827}
828/* }}} */
829
830static void php_sqlite3_callback_final(sqlite3_context *context) /* {{{ */
831{
832    php_sqlite3_func *func = (php_sqlite3_func *)sqlite3_user_data(context);
833    php_sqlite3_agg_context *agg_context = (php_sqlite3_agg_context *)sqlite3_aggregate_context(context, sizeof(php_sqlite3_agg_context));
834
835    agg_context->row_count = 0;
836
837    sqlite3_do_callback(&func->afini, &func->fini, 0, NULL, context, 1);
838}
839/* }}} */
840
841static int php_sqlite3_callback_compare(void *coll, int a_len, const void *a, int b_len, const void* b) /* {{{ */
842{
843    php_sqlite3_collation *collation = (php_sqlite3_collation*)coll;
844    zval *zargs = NULL;
845    zval retval;
846    int ret;
847
848
849    collation->fci.fci.size = (sizeof(collation->fci.fci));
850    collation->fci.fci.function_table = EG(function_table);
851    ZVAL_COPY_VALUE(&collation->fci.fci.function_name, &collation->cmp_func);
852    collation->fci.fci.symbol_table = NULL;
853    collation->fci.fci.object = NULL;
854    collation->fci.fci.retval = &retval;
855    collation->fci.fci.param_count = 2;
856
857    zargs = safe_emalloc(2, sizeof(zval), 0);
858    ZVAL_STRINGL(&zargs[0], a, a_len);
859    ZVAL_STRINGL(&zargs[1], b, b_len);
860
861    collation->fci.fci.params = zargs;
862
863    if ((ret = zend_call_function(&collation->fci.fci, &collation->fci.fcc)) == FAILURE) {
864        php_error_docref(NULL, E_WARNING, "An error occurred while invoking the compare callback");
865    }
866
867    zval_ptr_dtor(&zargs[0]);
868    zval_ptr_dtor(&zargs[1]);
869    efree(zargs);
870
871    //retval ought to contain a ZVAL_LONG by now
872    // (the result of a comparison, i.e. most likely -1, 0, or 1)
873    //I suppose we could accept any scalar return type, though.
874    if (Z_TYPE(retval) != IS_LONG){
875        php_error_docref(NULL, E_WARNING, "An error occurred while invoking the compare callback (invalid return type).  Collation behaviour is undefined.");
876    }else{
877        ret = Z_LVAL(retval);
878    }
879
880    zval_ptr_dtor(&retval);
881
882    return ret;
883}
884/* }}} */
885
886/* {{{ proto bool SQLite3::createFunction(string name, mixed callback [, int argcount])
887   Allows registration of a PHP function as a SQLite UDF that can be called within SQL statements. */
888PHP_METHOD(sqlite3, createFunction)
889{
890    php_sqlite3_db_object *db_obj;
891    zval *object = getThis();
892    php_sqlite3_func *func;
893    char *sql_func;
894    size_t sql_func_len;
895    zval *callback_func;
896    zend_string *callback_name;
897    zend_long sql_func_num_args = -1;
898    db_obj = Z_SQLITE3_DB_P(object);
899
900    SQLITE3_CHECK_INITIALIZED(db_obj, db_obj->initialised, SQLite3)
901
902    if (zend_parse_parameters(ZEND_NUM_ARGS(), "sz|l", &sql_func, &sql_func_len, &callback_func, &sql_func_num_args) == FAILURE) {
903        return;
904    }
905
906    if (!sql_func_len) {
907        RETURN_FALSE;
908    }
909
910    if (!zend_is_callable(callback_func, 0, &callback_name)) {
911        php_sqlite3_error(db_obj, "Not a valid callback function %s", callback_name->val);
912        zend_string_release(callback_name);
913        RETURN_FALSE;
914    }
915    zend_string_release(callback_name);
916
917    func = (php_sqlite3_func *)ecalloc(1, sizeof(*func));
918
919    if (sqlite3_create_function(db_obj->db, sql_func, sql_func_num_args, SQLITE_UTF8, func, php_sqlite3_callback_func, NULL, NULL) == SQLITE_OK) {
920        func->func_name = estrdup(sql_func);
921
922        ZVAL_COPY(&func->func, callback_func);
923
924        func->argc = sql_func_num_args;
925        func->next = db_obj->funcs;
926        db_obj->funcs = func;
927
928        RETURN_TRUE;
929    }
930    efree(func);
931
932    RETURN_FALSE;
933}
934/* }}} */
935
936/* {{{ proto bool SQLite3::createAggregate(string name, mixed step, mixed final [, int argcount])
937   Allows registration of a PHP function for use as an aggregate. */
938PHP_METHOD(sqlite3, createAggregate)
939{
940    php_sqlite3_db_object *db_obj;
941    zval *object = getThis();
942    php_sqlite3_func *func;
943    char *sql_func;
944    zend_string *callback_name;
945    size_t sql_func_len;
946    zval *step_callback, *fini_callback;
947    zend_long sql_func_num_args = -1;
948    db_obj = Z_SQLITE3_DB_P(object);
949
950    SQLITE3_CHECK_INITIALIZED(db_obj, db_obj->initialised, SQLite3)
951
952    if (zend_parse_parameters(ZEND_NUM_ARGS(), "szz|l", &sql_func, &sql_func_len, &step_callback, &fini_callback, &sql_func_num_args) == FAILURE) {
953        return;
954    }
955
956    if (!sql_func_len) {
957        RETURN_FALSE;
958    }
959
960    if (!zend_is_callable(step_callback, 0, &callback_name)) {
961        php_sqlite3_error(db_obj, "Not a valid callback function %s", callback_name->val);
962        zend_string_release(callback_name);
963        RETURN_FALSE;
964    }
965    zend_string_release(callback_name);
966
967    if (!zend_is_callable(fini_callback, 0, &callback_name)) {
968        php_sqlite3_error(db_obj, "Not a valid callback function %s", callback_name->val);
969        zend_string_release(callback_name);
970        RETURN_FALSE;
971    }
972    zend_string_release(callback_name);
973
974    func = (php_sqlite3_func *)ecalloc(1, sizeof(*func));
975
976    if (sqlite3_create_function(db_obj->db, sql_func, sql_func_num_args, SQLITE_UTF8, func, NULL, php_sqlite3_callback_step, php_sqlite3_callback_final) == SQLITE_OK) {
977        func->func_name = estrdup(sql_func);
978
979        ZVAL_COPY(&func->step, step_callback);
980        ZVAL_COPY(&func->fini, fini_callback);
981
982        func->argc = sql_func_num_args;
983        func->next = db_obj->funcs;
984        db_obj->funcs = func;
985
986        RETURN_TRUE;
987    }
988    efree(func);
989
990    RETURN_FALSE;
991}
992/* }}} */
993
994/* {{{ proto bool SQLite3::createCollation(string name, mixed callback)
995   Registers a PHP function as a comparator that can be used with the SQL COLLATE operator. Callback must accept two strings and return an integer (as strcmp()). */
996PHP_METHOD(sqlite3, createCollation)
997{
998    php_sqlite3_db_object *db_obj;
999    zval *object = getThis();
1000    php_sqlite3_collation *collation;
1001    char *collation_name;
1002    zend_string *callback_name;
1003    size_t collation_name_len;
1004    zval *callback_func;
1005    db_obj = Z_SQLITE3_DB_P(object);
1006
1007    SQLITE3_CHECK_INITIALIZED(db_obj, db_obj->initialised, SQLite3)
1008
1009    if (zend_parse_parameters(ZEND_NUM_ARGS(), "sz", &collation_name, &collation_name_len, &callback_func) == FAILURE) {
1010        RETURN_FALSE;
1011    }
1012
1013    if (!collation_name_len) {
1014        RETURN_FALSE;
1015    }
1016
1017    if (!zend_is_callable(callback_func, 0, &callback_name)) {
1018        php_sqlite3_error(db_obj, "Not a valid callback function %s", callback_name->val);
1019        zend_string_release(callback_name);
1020        RETURN_FALSE;
1021    }
1022    zend_string_release(callback_name);
1023
1024    collation = (php_sqlite3_collation *)ecalloc(1, sizeof(*collation));
1025    if (sqlite3_create_collation(db_obj->db, collation_name, SQLITE_UTF8, collation, php_sqlite3_callback_compare) == SQLITE_OK) {
1026        collation->collation_name = estrdup(collation_name);
1027
1028        ZVAL_COPY(&collation->cmp_func, callback_func);
1029
1030        collation->next = db_obj->collations;
1031        db_obj->collations = collation;
1032
1033        RETURN_TRUE;
1034    }
1035    efree(collation);
1036
1037    RETURN_FALSE;
1038}
1039/* }}} */
1040
1041typedef struct {
1042    sqlite3_blob *blob;
1043    size_t       position;
1044    size_t       size;
1045} php_stream_sqlite3_data;
1046
1047static size_t php_sqlite3_stream_write(php_stream *stream, const char *buf, size_t count)
1048{
1049/*  php_stream_sqlite3_data *sqlite3_stream = (php_stream_sqlite3_data *) stream->abstract; */
1050
1051    return 0;
1052}
1053
1054static size_t php_sqlite3_stream_read(php_stream *stream, char *buf, size_t count)
1055{
1056    php_stream_sqlite3_data *sqlite3_stream = (php_stream_sqlite3_data *) stream->abstract;
1057
1058    if (sqlite3_stream->position + count >= sqlite3_stream->size) {
1059        count = sqlite3_stream->size - sqlite3_stream->position;
1060        stream->eof = 1;
1061    }
1062    if (count) {
1063        if (sqlite3_blob_read(sqlite3_stream->blob, buf, count, sqlite3_stream->position) != SQLITE_OK) {
1064            return 0;
1065        }
1066        sqlite3_stream->position += count;
1067    }
1068    return count;
1069}
1070
1071static int php_sqlite3_stream_close(php_stream *stream, int close_handle)
1072{
1073    php_stream_sqlite3_data *sqlite3_stream = (php_stream_sqlite3_data *) stream->abstract;
1074
1075    if (sqlite3_blob_close(sqlite3_stream->blob) != SQLITE_OK) {
1076        /* Error occurred, but it still closed */
1077    }
1078
1079    efree(sqlite3_stream);
1080
1081    return 0;
1082}
1083
1084static int php_sqlite3_stream_flush(php_stream *stream)
1085{
1086    /* do nothing */
1087    return 0;
1088}
1089
1090/* {{{ */
1091static int php_sqlite3_stream_seek(php_stream *stream, zend_off_t offset, int whence, zend_off_t *newoffs)
1092{
1093    php_stream_sqlite3_data *sqlite3_stream = (php_stream_sqlite3_data *) stream->abstract;
1094
1095    switch(whence) {
1096        case SEEK_CUR:
1097            if (offset < 0) {
1098                if (sqlite3_stream->position < (size_t)(-offset)) {
1099                    sqlite3_stream->position = 0;
1100                    *newoffs = -1;
1101                    return -1;
1102                } else {
1103                    sqlite3_stream->position = sqlite3_stream->position + offset;
1104                    *newoffs = sqlite3_stream->position;
1105                    stream->eof = 0;
1106                    return 0;
1107                }
1108            } else {
1109                if (sqlite3_stream->position + (size_t)(offset) > sqlite3_stream->size) {
1110                    sqlite3_stream->position = sqlite3_stream->size;
1111                    *newoffs = -1;
1112                    return -1;
1113                } else {
1114                    sqlite3_stream->position = sqlite3_stream->position + offset;
1115                    *newoffs = sqlite3_stream->position;
1116                    stream->eof = 0;
1117                    return 0;
1118                }
1119            }
1120        case SEEK_SET:
1121            if (sqlite3_stream->size < (size_t)(offset)) {
1122                sqlite3_stream->position = sqlite3_stream->size;
1123                *newoffs = -1;
1124                return -1;
1125            } else {
1126                sqlite3_stream->position = offset;
1127                *newoffs = sqlite3_stream->position;
1128                stream->eof = 0;
1129                return 0;
1130            }
1131        case SEEK_END:
1132            if (offset > 0) {
1133                sqlite3_stream->position = sqlite3_stream->size;
1134                *newoffs = -1;
1135                return -1;
1136            } else if (sqlite3_stream->size < (size_t)(-offset)) {
1137                sqlite3_stream->position = 0;
1138                *newoffs = -1;
1139                return -1;
1140            } else {
1141                sqlite3_stream->position = sqlite3_stream->size + offset;
1142                *newoffs = sqlite3_stream->position;
1143                stream->eof = 0;
1144                return 0;
1145            }
1146        default:
1147            *newoffs = sqlite3_stream->position;
1148            return -1;
1149    }
1150}
1151/* }}} */
1152
1153
1154static int php_sqlite3_stream_cast(php_stream *stream, int castas, void **ret)
1155{
1156    return FAILURE;
1157}
1158
1159static int php_sqlite3_stream_stat(php_stream *stream, php_stream_statbuf *ssb)
1160{
1161    php_stream_sqlite3_data *sqlite3_stream = (php_stream_sqlite3_data *) stream->abstract;
1162    ssb->sb.st_size = sqlite3_stream->size;
1163    return 0;
1164}
1165
1166static php_stream_ops php_stream_sqlite3_ops = {
1167    php_sqlite3_stream_write,
1168    php_sqlite3_stream_read,
1169    php_sqlite3_stream_close,
1170    php_sqlite3_stream_flush,
1171    "SQLite3",
1172    php_sqlite3_stream_seek,
1173    php_sqlite3_stream_cast,
1174    php_sqlite3_stream_stat
1175};
1176
1177/* {{{ proto resource SQLite3::openBlob(string table, string column, int rowid [, string dbname])
1178   Open a blob as a stream which we can read / write to. */
1179PHP_METHOD(sqlite3, openBlob)
1180{
1181    php_sqlite3_db_object *db_obj;
1182    zval *object = getThis();
1183    char *table, *column, *dbname = "main";
1184    size_t table_len, column_len, dbname_len;
1185    zend_long rowid, flags = 0;
1186    sqlite3_blob *blob = NULL;
1187    php_stream_sqlite3_data *sqlite3_stream;
1188    php_stream *stream;
1189
1190    db_obj = Z_SQLITE3_DB_P(object);
1191
1192    SQLITE3_CHECK_INITIALIZED(db_obj, db_obj->initialised, SQLite3)
1193
1194    if (zend_parse_parameters(ZEND_NUM_ARGS(), "ssl|s", &table, &table_len, &column, &column_len, &rowid, &dbname, &dbname_len) == FAILURE) {
1195        return;
1196    }
1197
1198    if (sqlite3_blob_open(db_obj->db, dbname, table, column, rowid, flags, &blob) != SQLITE_OK) {
1199        php_sqlite3_error(db_obj, "Unable to open blob: %s", sqlite3_errmsg(db_obj->db));
1200        RETURN_FALSE;
1201    }
1202
1203    sqlite3_stream = emalloc(sizeof(php_stream_sqlite3_data));
1204    sqlite3_stream->blob = blob;
1205    sqlite3_stream->position = 0;
1206    sqlite3_stream->size = sqlite3_blob_bytes(blob);
1207
1208    stream = php_stream_alloc(&php_stream_sqlite3_ops, sqlite3_stream, 0, "rb");
1209
1210    if (stream) {
1211        php_stream_to_zval(stream, return_value);
1212    } else {
1213        RETURN_FALSE;
1214    }
1215}
1216/* }}} */
1217
1218/* {{{ proto bool SQLite3::enableExceptions([bool enableExceptions = false])
1219   Enables an exception error mode. */
1220PHP_METHOD(sqlite3, enableExceptions)
1221{
1222    php_sqlite3_db_object *db_obj;
1223    zval *object = getThis();
1224    zend_bool enableExceptions = 0;
1225
1226    db_obj = Z_SQLITE3_DB_P(object);
1227
1228    if (zend_parse_parameters(ZEND_NUM_ARGS(), "|b", &enableExceptions) == FAILURE) {
1229        return;
1230    }
1231
1232    RETVAL_BOOL(db_obj->exception);
1233
1234    db_obj->exception = enableExceptions;
1235}
1236/* }}} */
1237
1238/* {{{ proto int SQLite3Stmt::paramCount()
1239   Returns the number of parameters within the prepared statement. */
1240PHP_METHOD(sqlite3stmt, paramCount)
1241{
1242    php_sqlite3_stmt *stmt_obj;
1243    zval *object = getThis();
1244    stmt_obj = Z_SQLITE3_STMT_P(object);
1245
1246    if (zend_parse_parameters_none() == FAILURE) {
1247        return;
1248    }
1249
1250    SQLITE3_CHECK_INITIALIZED_STMT(stmt_obj->stmt, SQLite3Stmt);
1251
1252    RETURN_LONG(sqlite3_bind_parameter_count(stmt_obj->stmt));
1253}
1254/* }}} */
1255
1256/* {{{ proto bool SQLite3Stmt::close()
1257   Closes the prepared statement. */
1258PHP_METHOD(sqlite3stmt, close)
1259{
1260    php_sqlite3_stmt *stmt_obj;
1261    zval *object = getThis();
1262    stmt_obj = Z_SQLITE3_STMT_P(object);
1263
1264    if (zend_parse_parameters_none() == FAILURE) {
1265        return;
1266    }
1267
1268    if(stmt_obj->db_obj) {
1269            zend_llist_del_element(&(stmt_obj->db_obj->free_list), object, (int (*)(void *, void *)) php_sqlite3_compare_stmt_zval_free);
1270    }
1271
1272    RETURN_TRUE;
1273}
1274/* }}} */
1275
1276/* {{{ proto bool SQLite3Stmt::reset()
1277   Reset the prepared statement to the state before it was executed, bindings still remain. */
1278PHP_METHOD(sqlite3stmt, reset)
1279{
1280    php_sqlite3_stmt *stmt_obj;
1281    zval *object = getThis();
1282    stmt_obj = Z_SQLITE3_STMT_P(object);
1283
1284    if (zend_parse_parameters_none() == FAILURE) {
1285        return;
1286    }
1287
1288    SQLITE3_CHECK_INITIALIZED_STMT(stmt_obj->stmt, SQLite3Stmt);
1289
1290    if (sqlite3_reset(stmt_obj->stmt) != SQLITE_OK) {
1291        php_sqlite3_error(stmt_obj->db_obj, "Unable to reset statement: %s", sqlite3_errmsg(sqlite3_db_handle(stmt_obj->stmt)));
1292        RETURN_FALSE;
1293    }
1294    RETURN_TRUE;
1295}
1296/* }}} */
1297
1298/* {{{ proto bool SQLite3Stmt::clear()
1299   Clear all current bound parameters. */
1300PHP_METHOD(sqlite3stmt, clear)
1301{
1302    php_sqlite3_stmt *stmt_obj;
1303    zval *object = getThis();
1304    stmt_obj = Z_SQLITE3_STMT_P(object);
1305
1306    if (zend_parse_parameters_none() == FAILURE) {
1307        return;
1308    }
1309
1310    SQLITE3_CHECK_INITIALIZED_STMT(stmt_obj->stmt, SQLite3Stmt);
1311
1312    if (sqlite3_clear_bindings(stmt_obj->stmt) != SQLITE_OK) {
1313        php_sqlite3_error(stmt_obj->db_obj, "Unable to clear statement: %s", sqlite3_errmsg(sqlite3_db_handle(stmt_obj->stmt)));
1314        RETURN_FALSE;
1315    }
1316
1317    RETURN_TRUE;
1318}
1319/* }}} */
1320
1321/* {{{ proto bool SQLite3Stmt::readOnly()
1322   Returns true if a statement is definitely read only */
1323PHP_METHOD(sqlite3stmt, readOnly)
1324{
1325    php_sqlite3_stmt *stmt_obj;
1326    zval *object = getThis();
1327    stmt_obj = Z_SQLITE3_STMT_P(object);
1328
1329    if (zend_parse_parameters_none() == FAILURE) {
1330        return;
1331    }
1332
1333    SQLITE3_CHECK_INITIALIZED_STMT(stmt_obj->stmt, SQLite3Stmt);
1334
1335#if SQLITE_VERSION_NUMBER >= 3007004
1336    if (sqlite3_stmt_readonly(stmt_obj->stmt)) {
1337        RETURN_TRUE;
1338    }
1339#endif
1340    RETURN_FALSE;
1341}
1342/* }}} */
1343
1344static int register_bound_parameter_to_sqlite(struct php_sqlite3_bound_param *param, php_sqlite3_stmt *stmt) /* {{{ */
1345{
1346    HashTable *hash;
1347    hash = stmt->bound_params;
1348
1349    if (!hash) {
1350        ALLOC_HASHTABLE(hash);
1351        zend_hash_init(hash, 13, NULL, sqlite3_param_dtor, 0);
1352        stmt->bound_params = hash;
1353    }
1354
1355    /* We need a : prefix to resolve a name to a parameter number */
1356    if (param->name) {
1357        if (param->name->val[0] != ':') {
1358            /* pre-increment for character + 1 for null */
1359            zend_string *temp = zend_string_alloc(param->name->len + 1, 0);
1360            temp->val[0] = ':';
1361            memmove(temp->val + 1, param->name->val, param->name->len + 1);
1362            param->name = temp;
1363        } else {
1364            param->name = zend_string_init(param->name->val, param->name->len, 0);
1365        }
1366        /* do lookup*/
1367        param->param_number = sqlite3_bind_parameter_index(stmt->stmt, param->name->val);
1368    }
1369
1370    if (param->param_number < 1) {
1371        zend_string_release(param->name);
1372        return 0;
1373    }
1374
1375    if (param->param_number >= 1) {
1376        zend_hash_index_del(hash, param->param_number);
1377    }
1378
1379    if (param->name) {
1380        zend_hash_update_mem(hash, param->name, param, sizeof(struct php_sqlite3_bound_param));
1381    } else {
1382        zend_hash_index_update_mem(hash, param->param_number, param, sizeof(struct php_sqlite3_bound_param));
1383    }
1384
1385    return 1;
1386}
1387/* }}} */
1388
1389/* {{{ proto bool SQLite3Stmt::bindParam(int parameter_number, mixed parameter [, int type])
1390   Bind Parameter to a stmt variable. */
1391PHP_METHOD(sqlite3stmt, bindParam)
1392{
1393    php_sqlite3_stmt *stmt_obj;
1394    zval *object = getThis();
1395    struct php_sqlite3_bound_param param = {0};
1396    zval *parameter;
1397    stmt_obj = Z_SQLITE3_STMT_P(object);
1398
1399    param.param_number = -1;
1400    param.type = SQLITE3_TEXT;
1401
1402    if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS(), "lz|l", &param.param_number, &parameter, &param.type) == FAILURE) {
1403        if (zend_parse_parameters(ZEND_NUM_ARGS(), "Sz|l", &param.name, &parameter, &param.type) == FAILURE) {
1404            return;
1405        }
1406    }
1407
1408    SQLITE3_CHECK_INITIALIZED_STMT(stmt_obj->stmt, SQLite3Stmt);
1409
1410    ZVAL_COPY(&param.parameter, parameter);
1411
1412    if (!register_bound_parameter_to_sqlite(&param, stmt_obj)) {
1413        if (!Z_ISUNDEF(param.parameter)) {
1414            zval_ptr_dtor(&(param.parameter));
1415            ZVAL_UNDEF(&param.parameter);
1416        }
1417        RETURN_FALSE;
1418    }
1419    RETURN_TRUE;
1420}
1421/* }}} */
1422
1423/* {{{ proto bool SQLite3Stmt::bindValue(int parameter_number, mixed parameter [, int type])
1424   Bind Value of a parameter to a stmt variable. */
1425PHP_METHOD(sqlite3stmt, bindValue)
1426{
1427    php_sqlite3_stmt *stmt_obj;
1428    zval *object = getThis();
1429    struct php_sqlite3_bound_param param = {0};
1430    zval *parameter;
1431    stmt_obj = Z_SQLITE3_STMT_P(object);
1432
1433    param.param_number = -1;
1434    param.type = SQLITE3_TEXT;
1435
1436    if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS(), "lz/|l", &param.param_number, &parameter, &param.type) == FAILURE) {
1437        if (zend_parse_parameters(ZEND_NUM_ARGS(), "Sz/|l", &param.name, &parameter, &param.type) == FAILURE) {
1438            return;
1439        }
1440    }
1441
1442    SQLITE3_CHECK_INITIALIZED_STMT(stmt_obj->stmt, SQLite3Stmt);
1443
1444    ZVAL_COPY(&param.parameter, parameter);
1445
1446    if (!register_bound_parameter_to_sqlite(&param, stmt_obj)) {
1447        if (!Z_ISUNDEF(param.parameter)) {
1448            zval_ptr_dtor(&(param.parameter));
1449            ZVAL_UNDEF(&param.parameter);
1450        }
1451        RETURN_FALSE;
1452    }
1453    RETURN_TRUE;
1454}
1455/* }}} */
1456
1457/* {{{ proto SQLite3Result SQLite3Stmt::execute()
1458   Executes a prepared statement and returns a result set object. */
1459PHP_METHOD(sqlite3stmt, execute)
1460{
1461    php_sqlite3_stmt *stmt_obj;
1462    php_sqlite3_result *result;
1463    zval *object = getThis();
1464    int return_code = 0;
1465    struct php_sqlite3_bound_param *param;
1466
1467    stmt_obj = Z_SQLITE3_STMT_P(object);
1468
1469    if (zend_parse_parameters_none() == FAILURE) {
1470        return;
1471    }
1472
1473    SQLITE3_CHECK_INITIALIZED(stmt_obj->db_obj, stmt_obj->initialised, SQLite3)
1474
1475    if (stmt_obj->bound_params) {
1476        ZEND_HASH_FOREACH_PTR(stmt_obj->bound_params, param) {
1477            zval *parameter;
1478            /* parameter must be a reference? */
1479            if (Z_ISREF(param->parameter)) {
1480                parameter = Z_REFVAL(param->parameter);
1481            } else {
1482                parameter = &param->parameter;
1483            }
1484
1485            /* If the ZVAL is null then it should be bound as that */
1486            if (Z_TYPE_P(parameter) == IS_NULL) {
1487                sqlite3_bind_null(stmt_obj->stmt, param->param_number);
1488                continue;
1489            }
1490
1491            switch (param->type) {
1492                case SQLITE_INTEGER:
1493                    convert_to_long(parameter);
1494#if ZEND_LONG_MAX > 2147483647
1495                    sqlite3_bind_int64(stmt_obj->stmt, param->param_number, Z_LVAL_P(parameter));
1496#else
1497                    sqlite3_bind_int(stmt_obj->stmt, param->param_number, Z_LVAL_P(parameter));
1498#endif
1499                    break;
1500
1501                case SQLITE_FLOAT:
1502                    /* convert_to_double(parameter);*/
1503                    sqlite3_bind_double(stmt_obj->stmt, param->param_number, Z_DVAL_P(parameter));
1504                    break;
1505
1506                case SQLITE_BLOB:
1507                {
1508                    php_stream *stream = NULL;
1509                    zend_string *buffer;
1510                    if (Z_TYPE_P(parameter) == IS_RESOURCE) {
1511                        php_stream_from_zval_no_verify(stream, parameter);
1512                        if (stream == NULL) {
1513                            php_sqlite3_error(stmt_obj->db_obj, "Unable to read stream for parameter %ld", param->param_number);
1514                            RETURN_FALSE;
1515                        }
1516                        buffer = php_stream_copy_to_mem(stream, PHP_STREAM_COPY_ALL, 0);
1517                    } else {
1518                        convert_to_string(parameter);
1519                        buffer = Z_STR_P(parameter);
1520                    }
1521
1522                    sqlite3_bind_blob(stmt_obj->stmt, param->param_number, buffer->val, buffer->len, SQLITE_TRANSIENT);
1523
1524                    if (stream) {
1525                        zend_string_release(buffer);
1526                    }
1527                    break;
1528                }
1529
1530                case SQLITE3_TEXT:
1531                    convert_to_string(parameter);
1532                    sqlite3_bind_text(stmt_obj->stmt, param->param_number, Z_STRVAL_P(parameter), Z_STRLEN_P(parameter), SQLITE_STATIC);
1533                    break;
1534
1535                case SQLITE_NULL:
1536                    sqlite3_bind_null(stmt_obj->stmt, param->param_number);
1537                    break;
1538
1539                default:
1540                    php_sqlite3_error(stmt_obj->db_obj, "Unknown parameter type: %pd for parameter %pd", param->type, param->param_number);
1541                    RETURN_FALSE;
1542            }
1543        } ZEND_HASH_FOREACH_END();
1544    }
1545
1546    return_code = sqlite3_step(stmt_obj->stmt);
1547
1548    switch (return_code) {
1549        case SQLITE_ROW: /* Valid Row */
1550        case SQLITE_DONE: /* Valid but no results */
1551        {
1552            sqlite3_reset(stmt_obj->stmt);
1553            object_init_ex(return_value, php_sqlite3_result_entry);
1554            result = Z_SQLITE3_RESULT_P(return_value);
1555
1556            result->is_prepared_statement = 1;
1557            result->db_obj = stmt_obj->db_obj;
1558            result->stmt_obj = stmt_obj;
1559            ZVAL_COPY(&result->stmt_obj_zval, object);
1560
1561            break;
1562        }
1563        case SQLITE_ERROR:
1564            sqlite3_reset(stmt_obj->stmt);
1565
1566        default:
1567            php_sqlite3_error(stmt_obj->db_obj, "Unable to execute statement: %s", sqlite3_errmsg(sqlite3_db_handle(stmt_obj->stmt)));
1568            zval_dtor(return_value);
1569            RETURN_FALSE;
1570    }
1571
1572    return;
1573}
1574/* }}} */
1575
1576/* {{{ proto int SQLite3Stmt::__construct(SQLite3 dbobject, String Statement)
1577   __constructor for SQLite3Stmt. */
1578PHP_METHOD(sqlite3stmt, __construct)
1579{
1580    php_sqlite3_stmt *stmt_obj;
1581    php_sqlite3_db_object *db_obj;
1582    zval *object = getThis();
1583    zval *db_zval;
1584    zend_string *sql;
1585    int errcode;
1586    zend_error_handling error_handling;
1587    php_sqlite3_free_list *free_item;
1588
1589    stmt_obj = Z_SQLITE3_STMT_P(object);
1590    zend_replace_error_handling(EH_THROW, NULL, &error_handling);
1591
1592    if (zend_parse_parameters(ZEND_NUM_ARGS(), "OS", &db_zval, php_sqlite3_sc_entry, &sql) == FAILURE) {
1593        zend_restore_error_handling(&error_handling);
1594        return;
1595    }
1596
1597    db_obj = Z_SQLITE3_DB_P(db_zval);
1598
1599    SQLITE3_CHECK_INITIALIZED(db_obj, db_obj->initialised, SQLite3)
1600
1601    zend_restore_error_handling(&error_handling);
1602
1603    if (!sql->len) {
1604        RETURN_FALSE;
1605    }
1606
1607    stmt_obj->db_obj = db_obj;
1608    ZVAL_COPY(&stmt_obj->db_obj_zval, db_zval);
1609
1610    errcode = sqlite3_prepare_v2(db_obj->db, sql->val, sql->len, &(stmt_obj->stmt), NULL);
1611    if (errcode != SQLITE_OK) {
1612        php_sqlite3_error(db_obj, "Unable to prepare statement: %d, %s", errcode, sqlite3_errmsg(db_obj->db));
1613        zval_dtor(return_value);
1614        RETURN_FALSE;
1615    }
1616    stmt_obj->initialised = 1;
1617
1618    free_item = emalloc(sizeof(php_sqlite3_free_list));
1619    free_item->stmt_obj = stmt_obj;
1620    //??  free_item->stmt_obj_zval = getThis();
1621    ZVAL_COPY_VALUE(&free_item->stmt_obj_zval, object);
1622
1623    zend_llist_add_element(&(db_obj->free_list), &free_item);
1624}
1625/* }}} */
1626
1627/* {{{ proto int SQLite3Result::numColumns()
1628   Number of columns in the result set. */
1629PHP_METHOD(sqlite3result, numColumns)
1630{
1631    php_sqlite3_result *result_obj;
1632    zval *object = getThis();
1633    result_obj = Z_SQLITE3_RESULT_P(object);
1634
1635    SQLITE3_CHECK_INITIALIZED(result_obj->db_obj, result_obj->stmt_obj->initialised, SQLite3Result)
1636
1637    if (zend_parse_parameters_none() == FAILURE) {
1638        return;
1639    }
1640
1641    RETURN_LONG(sqlite3_column_count(result_obj->stmt_obj->stmt));
1642}
1643/* }}} */
1644
1645/* {{{ proto string SQLite3Result::columnName(int column)
1646   Returns the name of the nth column. */
1647PHP_METHOD(sqlite3result, columnName)
1648{
1649    php_sqlite3_result *result_obj;
1650    zval *object = getThis();
1651    zend_long column = 0;
1652    char *column_name;
1653    result_obj = Z_SQLITE3_RESULT_P(object);
1654
1655    SQLITE3_CHECK_INITIALIZED(result_obj->db_obj, result_obj->stmt_obj->initialised, SQLite3Result)
1656
1657    if (zend_parse_parameters(ZEND_NUM_ARGS(), "l", &column) == FAILURE) {
1658        return;
1659    }
1660    column_name = (char*) sqlite3_column_name(result_obj->stmt_obj->stmt, column);
1661
1662    if (column_name == NULL) {
1663        RETURN_FALSE;
1664    }
1665
1666    RETVAL_STRING(column_name);
1667}
1668/* }}} */
1669
1670/* {{{ proto int SQLite3Result::columnType(int column)
1671   Returns the type of the nth column. */
1672PHP_METHOD(sqlite3result, columnType)
1673{
1674    php_sqlite3_result *result_obj;
1675    zval *object = getThis();
1676    zend_long column = 0;
1677    result_obj = Z_SQLITE3_RESULT_P(object);
1678
1679    SQLITE3_CHECK_INITIALIZED(result_obj->db_obj, result_obj->stmt_obj->initialised, SQLite3Result)
1680
1681    if (zend_parse_parameters(ZEND_NUM_ARGS(), "l", &column) == FAILURE) {
1682        return;
1683    }
1684
1685    if (result_obj->complete) {
1686        RETURN_FALSE;
1687    }
1688
1689    RETURN_LONG(sqlite3_column_type(result_obj->stmt_obj->stmt, column));
1690}
1691/* }}} */
1692
1693/* {{{ proto array SQLite3Result::fetchArray([int mode])
1694   Fetch a result row as both an associative or numerically indexed array or both. */
1695PHP_METHOD(sqlite3result, fetchArray)
1696{
1697    php_sqlite3_result *result_obj;
1698    zval *object = getThis();
1699    int i, ret;
1700    zend_long mode = PHP_SQLITE3_BOTH;
1701    result_obj = Z_SQLITE3_RESULT_P(object);
1702
1703    SQLITE3_CHECK_INITIALIZED(result_obj->db_obj, result_obj->stmt_obj->initialised, SQLite3Result)
1704
1705    if (zend_parse_parameters(ZEND_NUM_ARGS(), "|l", &mode) == FAILURE) {
1706        return;
1707    }
1708
1709    ret = sqlite3_step(result_obj->stmt_obj->stmt);
1710    switch (ret) {
1711        case SQLITE_ROW:
1712            /* If there was no return value then just skip fetching */
1713            if (!USED_RET()) {
1714                return;
1715            }
1716
1717            array_init(return_value);
1718
1719            for (i = 0; i < sqlite3_data_count(result_obj->stmt_obj->stmt); i++) {
1720                zval data;
1721
1722                sqlite_value_to_zval(result_obj->stmt_obj->stmt, i, &data);
1723
1724                if (mode & PHP_SQLITE3_NUM) {
1725                    add_index_zval(return_value, i, &data);
1726                }
1727
1728                if (mode & PHP_SQLITE3_ASSOC) {
1729                    if (mode & PHP_SQLITE3_NUM) {
1730                        if (Z_REFCOUNTED(data)) {
1731                            Z_ADDREF(data);
1732                        }
1733                    }
1734                    add_assoc_zval(return_value, (char*)sqlite3_column_name(result_obj->stmt_obj->stmt, i), &data);
1735                }
1736            }
1737            break;
1738
1739        case SQLITE_DONE:
1740            result_obj->complete = 1;
1741            RETURN_FALSE;
1742            break;
1743
1744        default:
1745            php_sqlite3_error(result_obj->db_obj, "Unable to execute statement: %s", sqlite3_errmsg(sqlite3_db_handle(result_obj->stmt_obj->stmt)));
1746    }
1747}
1748/* }}} */
1749
1750/* {{{ proto bool SQLite3Result::reset()
1751   Resets the result set back to the first row. */
1752PHP_METHOD(sqlite3result, reset)
1753{
1754    php_sqlite3_result *result_obj;
1755    zval *object = getThis();
1756    result_obj = Z_SQLITE3_RESULT_P(object);
1757
1758    SQLITE3_CHECK_INITIALIZED(result_obj->db_obj, result_obj->stmt_obj->initialised, SQLite3Result)
1759
1760    if (zend_parse_parameters_none() == FAILURE) {
1761        return;
1762    }
1763
1764    if (sqlite3_reset(result_obj->stmt_obj->stmt) != SQLITE_OK) {
1765        RETURN_FALSE;
1766    }
1767
1768    result_obj->complete = 0;
1769
1770    RETURN_TRUE;
1771}
1772/* }}} */
1773
1774/* {{{ proto bool SQLite3Result::finalize()
1775   Closes the result set. */
1776PHP_METHOD(sqlite3result, finalize)
1777{
1778    php_sqlite3_result *result_obj;
1779    zval *object = getThis();
1780    result_obj = Z_SQLITE3_RESULT_P(object);
1781
1782    SQLITE3_CHECK_INITIALIZED(result_obj->db_obj, result_obj->stmt_obj->initialised, SQLite3Result)
1783
1784    if (zend_parse_parameters_none() == FAILURE) {
1785        return;
1786    }
1787
1788    /* We need to finalize an internal statement */
1789    if (result_obj->is_prepared_statement == 0) {
1790        zend_llist_del_element(&(result_obj->db_obj->free_list), &result_obj->stmt_obj_zval,
1791            (int (*)(void *, void *)) php_sqlite3_compare_stmt_zval_free);
1792    } else {
1793        sqlite3_reset(result_obj->stmt_obj->stmt);
1794    }
1795
1796    RETURN_TRUE;
1797}
1798/* }}} */
1799
1800/* {{{ proto int SQLite3Result::__construct()
1801   __constructor for SQLite3Result. */
1802PHP_METHOD(sqlite3result, __construct)
1803{
1804    zend_throw_exception(zend_exception_get_default(), "SQLite3Result cannot be directly instantiated", 0);
1805}
1806/* }}} */
1807
1808/* {{{ arginfo */
1809ZEND_BEGIN_ARG_INFO(arginfo_sqlite3_open, 0)
1810    ZEND_ARG_INFO(0, filename)
1811    ZEND_ARG_INFO(0, flags)
1812    ZEND_ARG_INFO(0, encryption_key)
1813ZEND_END_ARG_INFO()
1814
1815ZEND_BEGIN_ARG_INFO(arginfo_sqlite3_busytimeout, 0)
1816    ZEND_ARG_INFO(0, ms)
1817ZEND_END_ARG_INFO()
1818
1819#ifndef SQLITE_OMIT_LOAD_EXTENSION
1820ZEND_BEGIN_ARG_INFO(arginfo_sqlite3_loadextension, 0)
1821    ZEND_ARG_INFO(0, shared_library)
1822ZEND_END_ARG_INFO()
1823#endif
1824
1825ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite3_escapestring, 0, 0, 1)
1826    ZEND_ARG_INFO(0, value)
1827ZEND_END_ARG_INFO()
1828
1829ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite3_query, 0, 0, 1)
1830    ZEND_ARG_INFO(0, query)
1831ZEND_END_ARG_INFO()
1832
1833ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite3_querysingle, 0, 0, 1)
1834    ZEND_ARG_INFO(0, query)
1835    ZEND_ARG_INFO(0, entire_row)
1836ZEND_END_ARG_INFO()
1837
1838ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite3_createfunction, 0, 0, 2)
1839    ZEND_ARG_INFO(0, name)
1840    ZEND_ARG_INFO(0, callback)
1841    ZEND_ARG_INFO(0, argument_count)
1842ZEND_END_ARG_INFO()
1843
1844ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite3_createaggregate, 0, 0, 3)
1845    ZEND_ARG_INFO(0, name)
1846    ZEND_ARG_INFO(0, step_callback)
1847    ZEND_ARG_INFO(0, final_callback)
1848    ZEND_ARG_INFO(0, argument_count)
1849ZEND_END_ARG_INFO()
1850
1851ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite3_createcollation, 0, 0, 2)
1852    ZEND_ARG_INFO(0, name)
1853    ZEND_ARG_INFO(0, callback)
1854ZEND_END_ARG_INFO()
1855
1856ZEND_BEGIN_ARG_INFO_EX(argingo_sqlite3_openblob, 0, 0, 3)
1857    ZEND_ARG_INFO(0, table)
1858    ZEND_ARG_INFO(0, column)
1859    ZEND_ARG_INFO(0, rowid)
1860    ZEND_ARG_INFO(0, dbname)
1861ZEND_END_ARG_INFO()
1862
1863ZEND_BEGIN_ARG_INFO_EX(argingo_sqlite3_enableexceptions, 0, 0, 1)
1864    ZEND_ARG_INFO(0, enableExceptions)
1865ZEND_END_ARG_INFO()
1866
1867ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite3stmt_bindparam, 0, 0, 2)
1868    ZEND_ARG_INFO(0, param_number)
1869    ZEND_ARG_INFO(1, param)
1870    ZEND_ARG_INFO(0, type)
1871ZEND_END_ARG_INFO()
1872
1873ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite3stmt_bindvalue, 0, 0, 2)
1874    ZEND_ARG_INFO(0, param_number)
1875    ZEND_ARG_INFO(0, param)
1876    ZEND_ARG_INFO(0, type)
1877ZEND_END_ARG_INFO()
1878
1879ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite3stmt_construct, 0, 0, 1)
1880    ZEND_ARG_INFO(0, sqlite3)
1881ZEND_END_ARG_INFO()
1882
1883ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite3result_columnname, 0, 0, 1)
1884    ZEND_ARG_INFO(0, column_number)
1885ZEND_END_ARG_INFO()
1886
1887ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite3result_columntype, 0, 0, 1)
1888    ZEND_ARG_INFO(0, column_number)
1889ZEND_END_ARG_INFO()
1890
1891ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite3result_fetcharray, 0, 0, 1)
1892    ZEND_ARG_INFO(0, mode)
1893ZEND_END_ARG_INFO()
1894
1895ZEND_BEGIN_ARG_INFO(arginfo_sqlite3_void, 0)
1896ZEND_END_ARG_INFO()
1897/* }}} */
1898
1899/* {{{ php_sqlite3_class_methods */
1900static zend_function_entry php_sqlite3_class_methods[] = {
1901    PHP_ME(sqlite3,     open,               arginfo_sqlite3_open, ZEND_ACC_PUBLIC)
1902    PHP_ME(sqlite3,     close,              arginfo_sqlite3_void, ZEND_ACC_PUBLIC)
1903    PHP_ME(sqlite3,     exec,               arginfo_sqlite3_query, ZEND_ACC_PUBLIC)
1904    PHP_ME(sqlite3,     version,            arginfo_sqlite3_void, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC)
1905    PHP_ME(sqlite3,     lastInsertRowID,    arginfo_sqlite3_void, ZEND_ACC_PUBLIC)
1906    PHP_ME(sqlite3,     lastErrorCode,      arginfo_sqlite3_void, ZEND_ACC_PUBLIC)
1907    PHP_ME(sqlite3,     lastErrorMsg,       arginfo_sqlite3_void, ZEND_ACC_PUBLIC)
1908    PHP_ME(sqlite3,     busyTimeout,        arginfo_sqlite3_busytimeout, ZEND_ACC_PUBLIC)
1909#ifndef SQLITE_OMIT_LOAD_EXTENSION
1910    PHP_ME(sqlite3,     loadExtension,      arginfo_sqlite3_loadextension, ZEND_ACC_PUBLIC)
1911#endif
1912    PHP_ME(sqlite3,     changes,            arginfo_sqlite3_void, ZEND_ACC_PUBLIC)
1913    PHP_ME(sqlite3,     escapeString,       arginfo_sqlite3_escapestring, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC)
1914    PHP_ME(sqlite3,     prepare,            arginfo_sqlite3_query, ZEND_ACC_PUBLIC)
1915    PHP_ME(sqlite3,     query,              arginfo_sqlite3_query, ZEND_ACC_PUBLIC)
1916    PHP_ME(sqlite3,     querySingle,        arginfo_sqlite3_querysingle, ZEND_ACC_PUBLIC)
1917    PHP_ME(sqlite3,     createFunction,     arginfo_sqlite3_createfunction, ZEND_ACC_PUBLIC)
1918    PHP_ME(sqlite3,     createAggregate,    arginfo_sqlite3_createaggregate, ZEND_ACC_PUBLIC)
1919    PHP_ME(sqlite3,     createCollation,    arginfo_sqlite3_createcollation, ZEND_ACC_PUBLIC)
1920    PHP_ME(sqlite3,     openBlob,           argingo_sqlite3_openblob, ZEND_ACC_PUBLIC)
1921    PHP_ME(sqlite3,     enableExceptions,   argingo_sqlite3_enableexceptions, ZEND_ACC_PUBLIC)
1922    /* Aliases */
1923    PHP_MALIAS(sqlite3, __construct, open, arginfo_sqlite3_open, ZEND_ACC_PUBLIC|ZEND_ACC_CTOR)
1924    PHP_FE_END
1925};
1926/* }}} */
1927
1928/* {{{ php_sqlite3_stmt_class_methods */
1929static zend_function_entry php_sqlite3_stmt_class_methods[] = {
1930    PHP_ME(sqlite3stmt, paramCount, arginfo_sqlite3_void, ZEND_ACC_PUBLIC)
1931    PHP_ME(sqlite3stmt, close,      arginfo_sqlite3_void, ZEND_ACC_PUBLIC)
1932    PHP_ME(sqlite3stmt, reset,      arginfo_sqlite3_void, ZEND_ACC_PUBLIC)
1933    PHP_ME(sqlite3stmt, clear,      arginfo_sqlite3_void, ZEND_ACC_PUBLIC)
1934    PHP_ME(sqlite3stmt, execute,    arginfo_sqlite3_void, ZEND_ACC_PUBLIC)
1935    PHP_ME(sqlite3stmt, bindParam,  arginfo_sqlite3stmt_bindparam, ZEND_ACC_PUBLIC)
1936    PHP_ME(sqlite3stmt, bindValue,  arginfo_sqlite3stmt_bindvalue, ZEND_ACC_PUBLIC)
1937    PHP_ME(sqlite3stmt, readOnly,   arginfo_sqlite3_void, ZEND_ACC_PUBLIC)
1938    PHP_ME(sqlite3stmt, __construct, arginfo_sqlite3stmt_construct, ZEND_ACC_PRIVATE|ZEND_ACC_CTOR)
1939    PHP_FE_END
1940};
1941/* }}} */
1942
1943/* {{{ php_sqlite3_result_class_methods */
1944static zend_function_entry php_sqlite3_result_class_methods[] = {
1945    PHP_ME(sqlite3result, numColumns,       arginfo_sqlite3_void, ZEND_ACC_PUBLIC)
1946    PHP_ME(sqlite3result, columnName,       arginfo_sqlite3result_columnname, ZEND_ACC_PUBLIC)
1947    PHP_ME(sqlite3result, columnType,       arginfo_sqlite3result_columntype, ZEND_ACC_PUBLIC)
1948    PHP_ME(sqlite3result, fetchArray,       arginfo_sqlite3result_fetcharray, ZEND_ACC_PUBLIC)
1949    PHP_ME(sqlite3result, reset,            arginfo_sqlite3_void, ZEND_ACC_PUBLIC)
1950    PHP_ME(sqlite3result, finalize,         arginfo_sqlite3_void, ZEND_ACC_PUBLIC)
1951    PHP_ME(sqlite3result, __construct,      arginfo_sqlite3_void, ZEND_ACC_PRIVATE|ZEND_ACC_CTOR)
1952    PHP_FE_END
1953};
1954/* }}} */
1955
1956/* {{{ Authorization Callback
1957*/
1958static int php_sqlite3_authorizer(void *autharg, int access_type, const char *arg3, const char *arg4, const char *arg5, const char *arg6)
1959{
1960    switch (access_type) {
1961        case SQLITE_ATTACH:
1962        {
1963            if (memcmp(arg3, ":memory:", sizeof(":memory:")) && *arg3) {
1964
1965#if PHP_API_VERSION < 20100412
1966                if (PG(safe_mode) && (!php_checkuid(arg3, NULL, CHECKUID_CHECK_FILE_AND_DIR))) {
1967                    return SQLITE_DENY;
1968                }
1969#endif
1970
1971                if (php_check_open_basedir(arg3)) {
1972                    return SQLITE_DENY;
1973                }
1974            }
1975            return SQLITE_OK;
1976        }
1977
1978        default:
1979            /* access allowed */
1980            return SQLITE_OK;
1981    }
1982}
1983/* }}} */
1984
1985/* {{{ php_sqlite3_free_list_dtor
1986*/
1987static void php_sqlite3_free_list_dtor(void **item)
1988{
1989    php_sqlite3_free_list *free_item = (php_sqlite3_free_list *)*item;
1990
1991    if (free_item->stmt_obj && free_item->stmt_obj->initialised) {
1992        sqlite3_finalize(free_item->stmt_obj->stmt);
1993        free_item->stmt_obj->initialised = 0;
1994    }
1995    efree(*item);
1996}
1997/* }}} */
1998
1999static int php_sqlite3_compare_stmt_zval_free(php_sqlite3_free_list **free_list, zval *statement ) /* {{{ */
2000{
2001    return  ((*free_list)->stmt_obj->initialised && Z_PTR_P(statement) == Z_PTR((*free_list)->stmt_obj_zval));
2002}
2003/* }}} */
2004
2005static int php_sqlite3_compare_stmt_free( php_sqlite3_free_list **free_list, sqlite3_stmt *statement ) /* {{{ */
2006{
2007    return ((*free_list)->stmt_obj->initialised && statement == (*free_list)->stmt_obj->stmt);
2008}
2009/* }}} */
2010
2011static void php_sqlite3_object_free_storage(zend_object *object) /* {{{ */
2012{
2013    php_sqlite3_db_object *intern = php_sqlite3_db_from_obj(object);
2014    php_sqlite3_func *func;
2015    php_sqlite3_collation *collation;
2016
2017    if (!intern) {
2018        return;
2019    }
2020
2021    while (intern->funcs) {
2022        func = intern->funcs;
2023        intern->funcs = func->next;
2024        if (intern->initialised && intern->db) {
2025            sqlite3_create_function(intern->db, func->func_name, func->argc, SQLITE_UTF8, func, NULL, NULL, NULL);
2026        }
2027
2028        efree((char*)func->func_name);
2029
2030        if (!Z_ISUNDEF(func->func)) {
2031            zval_ptr_dtor(&func->func);
2032        }
2033        if (!Z_ISUNDEF(func->step)) {
2034            zval_ptr_dtor(&func->step);
2035        }
2036        if (!Z_ISUNDEF(func->fini)) {
2037            zval_ptr_dtor(&func->fini);
2038        }
2039        efree(func);
2040    }
2041
2042    while (intern->collations){
2043        collation = intern->collations;
2044        intern->collations = collation->next;
2045        if (intern->initialised && intern->db){
2046            sqlite3_create_collation(intern->db, collation->collation_name, SQLITE_UTF8, NULL, NULL);
2047        }
2048        efree((char*)collation->collation_name);
2049        if (!Z_ISUNDEF(collation->cmp_func)) {
2050            zval_ptr_dtor(&collation->cmp_func);
2051        }
2052        efree(collation);
2053    }
2054
2055    if (intern->initialised && intern->db) {
2056        sqlite3_close(intern->db);
2057        intern->initialised = 0;
2058    }
2059
2060    zend_object_std_dtor(&intern->zo);
2061}
2062/* }}} */
2063
2064static void php_sqlite3_stmt_object_free_storage(zend_object *object) /* {{{ */
2065{
2066    php_sqlite3_stmt *intern = php_sqlite3_stmt_from_obj(object);
2067
2068    if (!intern) {
2069        return;
2070    }
2071
2072    if (intern->bound_params) {
2073        zend_hash_destroy(intern->bound_params);
2074        FREE_HASHTABLE(intern->bound_params);
2075        intern->bound_params = NULL;
2076    }
2077
2078    if (intern->initialised) {
2079        zend_llist_del_element(&(intern->db_obj->free_list), intern->stmt,
2080            (int (*)(void *, void *)) php_sqlite3_compare_stmt_free);
2081    }
2082
2083    if (!Z_ISUNDEF(intern->db_obj_zval)) {
2084        zval_ptr_dtor(&intern->db_obj_zval);
2085    }
2086
2087    zend_object_std_dtor(&intern->zo);
2088}
2089/* }}} */
2090
2091static void php_sqlite3_result_object_free_storage(zend_object *object) /* {{{ */
2092{
2093    php_sqlite3_result *intern = php_sqlite3_result_from_obj(object);
2094
2095    if (!intern) {
2096        return;
2097    }
2098
2099    if (!Z_ISNULL(intern->stmt_obj_zval)) {
2100        if (intern->stmt_obj->initialised) {
2101            sqlite3_reset(intern->stmt_obj->stmt);
2102        }
2103
2104        zval_ptr_dtor(&intern->stmt_obj_zval);
2105    }
2106
2107    zend_object_std_dtor(&intern->zo);
2108}
2109/* }}} */
2110
2111static zend_object *php_sqlite3_object_new(zend_class_entry *class_type) /* {{{ */
2112{
2113    php_sqlite3_db_object *intern;
2114
2115    /* Allocate memory for it */
2116    intern = ecalloc(1, sizeof(php_sqlite3_db_object) + sizeof(zval) * (class_type->default_properties_count - 1));
2117
2118    /* Need to keep track of things to free */
2119    zend_llist_init(&(intern->free_list),  sizeof(php_sqlite3_free_list *), (llist_dtor_func_t)php_sqlite3_free_list_dtor, 0);
2120
2121    zend_object_std_init(&intern->zo, class_type);
2122    object_properties_init(&intern->zo, class_type);
2123
2124    intern->zo.handlers = &sqlite3_object_handlers;
2125
2126    return &intern->zo;
2127}
2128/* }}} */
2129
2130static zend_object *php_sqlite3_stmt_object_new(zend_class_entry *class_type) /* {{{ */
2131{
2132    php_sqlite3_stmt *intern;
2133
2134    /* Allocate memory for it */
2135    intern = ecalloc(1, sizeof(php_sqlite3_stmt) + sizeof(zval) * (class_type->default_properties_count - 1));
2136
2137    zend_object_std_init(&intern->zo, class_type);
2138    object_properties_init(&intern->zo, class_type);
2139
2140    intern->zo.handlers = &sqlite3_stmt_object_handlers;
2141
2142    return &intern->zo;
2143}
2144/* }}} */
2145
2146static zend_object *php_sqlite3_result_object_new(zend_class_entry *class_type) /* {{{ */
2147{
2148    php_sqlite3_result *intern;
2149
2150    /* Allocate memory for it */
2151    intern = ecalloc(1, sizeof(php_sqlite3_result) + sizeof(zval) * (class_type->default_properties_count - 1));
2152
2153    zend_object_std_init(&intern->zo, class_type);
2154    object_properties_init(&intern->zo, class_type);
2155
2156    intern->zo.handlers = &sqlite3_result_object_handlers;
2157
2158    return &intern->zo;
2159}
2160/* }}} */
2161
2162static void sqlite3_param_dtor(zval *data) /* {{{ */
2163{
2164    struct php_sqlite3_bound_param *param = (struct php_sqlite3_bound_param*)Z_PTR_P(data);
2165
2166    if (param->name) {
2167        zend_string_release(param->name);
2168    }
2169
2170    if (!Z_ISNULL(param->parameter)) {
2171        zval_ptr_dtor(&(param->parameter));
2172        ZVAL_UNDEF(&param->parameter);
2173    }
2174    efree(param);
2175}
2176/* }}} */
2177
2178/* {{{ PHP_MINIT_FUNCTION
2179*/
2180PHP_MINIT_FUNCTION(sqlite3)
2181{
2182    zend_class_entry ce;
2183
2184#if defined(ZTS)
2185    /* Refuse to load if this wasn't a threasafe library loaded */
2186    if (!sqlite3_threadsafe()) {
2187        php_error_docref(NULL, E_WARNING, "A thread safe version of SQLite is required when using a thread safe version of PHP.");
2188        return FAILURE;
2189    }
2190#endif
2191
2192    memcpy(&sqlite3_object_handlers, zend_get_std_object_handlers(), sizeof(zend_object_handlers));
2193    memcpy(&sqlite3_stmt_object_handlers, zend_get_std_object_handlers(), sizeof(zend_object_handlers));
2194    memcpy(&sqlite3_result_object_handlers, zend_get_std_object_handlers(), sizeof(zend_object_handlers));
2195
2196    /* Register SQLite 3 Class */
2197    INIT_CLASS_ENTRY(ce, "SQLite3", php_sqlite3_class_methods);
2198    ce.create_object = php_sqlite3_object_new;
2199    sqlite3_object_handlers.offset = XtOffsetOf(php_sqlite3_db_object, zo);
2200    sqlite3_object_handlers.clone_obj = NULL;
2201    sqlite3_object_handlers.free_obj = php_sqlite3_object_free_storage;
2202    php_sqlite3_sc_entry = zend_register_internal_class(&ce);
2203
2204    /* Register SQLite 3 Prepared Statement Class */
2205    INIT_CLASS_ENTRY(ce, "SQLite3Stmt", php_sqlite3_stmt_class_methods);
2206    ce.create_object = php_sqlite3_stmt_object_new;
2207    sqlite3_stmt_object_handlers.offset = XtOffsetOf(php_sqlite3_stmt, zo);
2208    sqlite3_stmt_object_handlers.clone_obj = NULL;
2209    sqlite3_stmt_object_handlers.free_obj = php_sqlite3_stmt_object_free_storage;
2210    php_sqlite3_stmt_entry = zend_register_internal_class(&ce);
2211
2212    /* Register SQLite 3 Result Class */
2213    INIT_CLASS_ENTRY(ce, "SQLite3Result", php_sqlite3_result_class_methods);
2214    ce.create_object = php_sqlite3_result_object_new;
2215    sqlite3_result_object_handlers.offset = XtOffsetOf(php_sqlite3_result, zo);
2216    sqlite3_result_object_handlers.clone_obj = NULL;
2217    sqlite3_result_object_handlers.free_obj = php_sqlite3_result_object_free_storage;
2218    php_sqlite3_result_entry = zend_register_internal_class(&ce);
2219
2220    REGISTER_INI_ENTRIES();
2221
2222    REGISTER_LONG_CONSTANT("SQLITE3_ASSOC", PHP_SQLITE3_ASSOC, CONST_CS | CONST_PERSISTENT);
2223    REGISTER_LONG_CONSTANT("SQLITE3_NUM", PHP_SQLITE3_NUM, CONST_CS | CONST_PERSISTENT);
2224    REGISTER_LONG_CONSTANT("SQLITE3_BOTH", PHP_SQLITE3_BOTH, CONST_CS | CONST_PERSISTENT);
2225
2226    REGISTER_LONG_CONSTANT("SQLITE3_INTEGER", SQLITE_INTEGER, CONST_CS | CONST_PERSISTENT);
2227    REGISTER_LONG_CONSTANT("SQLITE3_FLOAT", SQLITE_FLOAT, CONST_CS | CONST_PERSISTENT);
2228    REGISTER_LONG_CONSTANT("SQLITE3_TEXT", SQLITE3_TEXT, CONST_CS | CONST_PERSISTENT);
2229    REGISTER_LONG_CONSTANT("SQLITE3_BLOB", SQLITE_BLOB, CONST_CS | CONST_PERSISTENT);
2230    REGISTER_LONG_CONSTANT("SQLITE3_NULL", SQLITE_NULL, CONST_CS | CONST_PERSISTENT);
2231
2232    REGISTER_LONG_CONSTANT("SQLITE3_OPEN_READONLY", SQLITE_OPEN_READONLY, CONST_CS | CONST_PERSISTENT);
2233    REGISTER_LONG_CONSTANT("SQLITE3_OPEN_READWRITE", SQLITE_OPEN_READWRITE, CONST_CS | CONST_PERSISTENT);
2234    REGISTER_LONG_CONSTANT("SQLITE3_OPEN_CREATE", SQLITE_OPEN_CREATE, CONST_CS | CONST_PERSISTENT);
2235
2236    return SUCCESS;
2237}
2238/* }}} */
2239
2240/* {{{ PHP_MSHUTDOWN_FUNCTION
2241*/
2242PHP_MSHUTDOWN_FUNCTION(sqlite3)
2243{
2244    UNREGISTER_INI_ENTRIES();
2245
2246    return SUCCESS;
2247}
2248/* }}} */
2249
2250/* {{{ PHP_MINFO_FUNCTION
2251*/
2252PHP_MINFO_FUNCTION(sqlite3)
2253{
2254    php_info_print_table_start();
2255    php_info_print_table_header(2, "SQLite3 support", "enabled");
2256    php_info_print_table_row(2, "SQLite3 module version", PHP_SQLITE3_VERSION);
2257    php_info_print_table_row(2, "SQLite Library", sqlite3_libversion());
2258    php_info_print_table_end();
2259
2260    DISPLAY_INI_ENTRIES();
2261}
2262/* }}} */
2263
2264/* {{{ PHP_GINIT_FUNCTION
2265*/
2266static PHP_GINIT_FUNCTION(sqlite3)
2267{
2268#if defined(COMPILE_DL_SQLITE3) && defined(ZTS)
2269    ZEND_TSRMLS_CACHE_UPDATE;
2270#endif
2271    memset(sqlite3_globals, 0, sizeof(*sqlite3_globals));
2272}
2273/* }}} */
2274
2275/* {{{ sqlite3_module_entry
2276*/
2277zend_module_entry sqlite3_module_entry = {
2278    STANDARD_MODULE_HEADER,
2279    "sqlite3",
2280    NULL,
2281    PHP_MINIT(sqlite3),
2282    PHP_MSHUTDOWN(sqlite3),
2283    NULL,
2284    NULL,
2285    PHP_MINFO(sqlite3),
2286    PHP_SQLITE3_VERSION,
2287    PHP_MODULE_GLOBALS(sqlite3),
2288    PHP_GINIT(sqlite3),
2289    NULL,
2290    NULL,
2291    STANDARD_MODULE_PROPERTIES_EX
2292};
2293/* }}} */
2294
2295#ifdef COMPILE_DL_SQLITE3
2296#ifdef ZTS
2297ZEND_TSRMLS_CACHE_DEFINE;
2298#endif
2299ZEND_GET_MODULE(sqlite3)
2300#endif
2301
2302/*
2303 * Local variables:
2304 * tab-width: 4
2305 * c-basic-offset: 4
2306 * End:
2307 * vim600: sw=4 ts=4 fdm=marker
2308 * vim<600: sw=4 ts=4
2309 */
2310