1/*
2   +----------------------------------------------------------------------+
3   | PHP Version 7                                                        |
4   +----------------------------------------------------------------------+
5   | Copyright (c) 1997-2016 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_ce_exception, 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
107	db_obj = Z_SQLITE3_DB_P(object);
108
109	if (FAILURE == zend_parse_parameters_throw(ZEND_NUM_ARGS(), "p|ls", &filename, &filename_len, &flags, &encryption_key, &encryption_key_len)) {
110		return;
111	}
112
113	if (db_obj->initialised) {
114		zend_throw_exception(zend_ce_exception, "Already initialised DB Object", 0);
115	}
116
117	if (strlen(filename) != filename_len) {
118		return;
119	}
120	if (memcmp(filename, ":memory:", sizeof(":memory:")) != 0) {
121		if (!(fullpath = expand_filepath(filename, NULL))) {
122			zend_throw_exception(zend_ce_exception, "Unable to expand filepath", 0);
123			return;
124		}
125
126		if (php_check_open_basedir(fullpath)) {
127			zend_throw_exception_ex(zend_ce_exception, 0, "open_basedir prohibits opening %s", fullpath);
128			efree(fullpath);
129			return;
130		}
131	} else {
132		fullpath = estrdup(filename);
133	}
134
135#if SQLITE_VERSION_NUMBER >= 3005000
136	if (sqlite3_open_v2(fullpath, &(db_obj->db), flags, NULL) != SQLITE_OK) {
137#else
138	if (sqlite3_open(fullpath, &(db_obj->db)) != SQLITE_OK) {
139#endif
140		zend_throw_exception_ex(zend_ce_exception, 0, "Unable to open database: %s", sqlite3_errmsg(db_obj->db));
141		if (fullpath) {
142			efree(fullpath);
143		}
144		return;
145	}
146
147#if SQLITE_HAS_CODEC
148	if (encryption_key_len > 0) {
149		if (sqlite3_key(db_obj->db, encryption_key, encryption_key_len) != SQLITE_OK) {
150			zend_throw_exception_ex(zend_ce_exception, 0, "Unable to open database: %s", sqlite3_errmsg(db_obj->db));
151			return;
152		}
153	}
154#endif
155
156	db_obj->initialised = 1;
157
158	if (PG(open_basedir) && *PG(open_basedir)) {
159		sqlite3_set_authorizer(db_obj->db, php_sqlite3_authorizer, NULL);
160	}
161
162	if (fullpath) {
163		efree(fullpath);
164	}
165}
166/* }}} */
167
168/* {{{ proto bool SQLite3::close()
169   Close a SQLite 3 Database. */
170PHP_METHOD(sqlite3, close)
171{
172	php_sqlite3_db_object *db_obj;
173	zval *object = getThis();
174	int errcode;
175	db_obj = Z_SQLITE3_DB_P(object);
176
177	if (zend_parse_parameters_none() == FAILURE) {
178		return;
179	}
180
181	if (db_obj->initialised) {
182        zend_llist_clean(&(db_obj->free_list));
183		if(db_obj->db) {
184            errcode = sqlite3_close(db_obj->db);
185            if (errcode != SQLITE_OK) {
186			    php_sqlite3_error(db_obj, "Unable to close database: %d, %s", errcode, sqlite3_errmsg(db_obj->db));
187                RETURN_FALSE;
188		    }
189        }
190		db_obj->initialised = 0;
191	}
192
193	RETURN_TRUE;
194}
195/* }}} */
196
197/* {{{ proto bool SQLite3::exec(String Query)
198   Executes a result-less query against a given database. */
199PHP_METHOD(sqlite3, exec)
200{
201	php_sqlite3_db_object *db_obj;
202	zval *object = getThis();
203	zend_string *sql;
204	char *errtext = NULL;
205	db_obj = Z_SQLITE3_DB_P(object);
206
207	SQLITE3_CHECK_INITIALIZED(db_obj, db_obj->initialised, SQLite3)
208
209	if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS(), "S", &sql)) {
210		return;
211	}
212
213	if (sqlite3_exec(db_obj->db, ZSTR_VAL(sql), NULL, NULL, &errtext) != SQLITE_OK) {
214		php_sqlite3_error(db_obj, "%s", errtext);
215		sqlite3_free(errtext);
216		RETURN_FALSE;
217	}
218
219	RETURN_TRUE;
220}
221/* }}} */
222
223/* {{{ proto Array SQLite3::version()
224   Returns the SQLite3 Library version as a string constant and as a number. */
225PHP_METHOD(sqlite3, version)
226{
227	if (zend_parse_parameters_none() == FAILURE) {
228		return;
229	}
230
231	array_init(return_value);
232
233	add_assoc_string(return_value, "versionString", (char*)sqlite3_libversion());
234	add_assoc_long(return_value, "versionNumber", sqlite3_libversion_number());
235
236	return;
237}
238/* }}} */
239
240/* {{{ proto int SQLite3::lastInsertRowID()
241   Returns the rowid of the most recent INSERT into the database from the database connection. */
242PHP_METHOD(sqlite3, lastInsertRowID)
243{
244	php_sqlite3_db_object *db_obj;
245	zval *object = getThis();
246	db_obj = Z_SQLITE3_DB_P(object);
247
248	SQLITE3_CHECK_INITIALIZED(db_obj, db_obj->initialised, SQLite3)
249
250	if (zend_parse_parameters_none() == FAILURE) {
251		return;
252	}
253
254	RETURN_LONG(sqlite3_last_insert_rowid(db_obj->db));
255}
256/* }}} */
257
258/* {{{ proto int SQLite3::lastErrorCode()
259   Returns the numeric result code of the most recent failed sqlite API call for the database connection. */
260PHP_METHOD(sqlite3, lastErrorCode)
261{
262	php_sqlite3_db_object *db_obj;
263	zval *object = getThis();
264	db_obj = Z_SQLITE3_DB_P(object);
265
266	SQLITE3_CHECK_INITIALIZED(db_obj, db_obj->db, SQLite3)
267
268	if (zend_parse_parameters_none() == FAILURE) {
269		return;
270	}
271
272	if (db_obj->initialised) {
273		RETURN_LONG(sqlite3_errcode(db_obj->db));
274	} else {
275		RETURN_LONG(0);
276	}
277}
278/* }}} */
279
280/* {{{ proto string SQLite3::lastErrorMsg()
281   Returns english text describing the most recent failed sqlite API call for the database connection. */
282PHP_METHOD(sqlite3, lastErrorMsg)
283{
284	php_sqlite3_db_object *db_obj;
285	zval *object = getThis();
286	db_obj = Z_SQLITE3_DB_P(object);
287
288	SQLITE3_CHECK_INITIALIZED(db_obj, db_obj->db, SQLite3)
289
290	if (zend_parse_parameters_none() == FAILURE) {
291		return;
292	}
293
294	if (db_obj->initialised) {
295		RETURN_STRING((char *)sqlite3_errmsg(db_obj->db));
296	} else {
297		RETURN_EMPTY_STRING();
298	}
299}
300/* }}} */
301
302/* {{{ proto bool SQLite3::busyTimeout(int msecs)
303   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. */
304PHP_METHOD(sqlite3, busyTimeout)
305{
306	php_sqlite3_db_object *db_obj;
307	zval *object = getThis();
308	zend_long ms;
309	int return_code;
310	db_obj = Z_SQLITE3_DB_P(object);
311
312	SQLITE3_CHECK_INITIALIZED(db_obj, db_obj->initialised, SQLite3)
313
314	if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS(), "l", &ms)) {
315		return;
316	}
317
318	return_code = sqlite3_busy_timeout(db_obj->db, ms);
319	if (return_code != SQLITE_OK) {
320		php_sqlite3_error(db_obj, "Unable to set busy timeout: %d, %s", return_code, sqlite3_errmsg(db_obj->db));
321		RETURN_FALSE;
322	}
323
324	RETURN_TRUE;
325}
326/* }}} */
327
328
329#ifndef SQLITE_OMIT_LOAD_EXTENSION
330/* {{{ proto bool SQLite3::loadExtension(String Shared Library)
331   Attempts to load an SQLite extension library. */
332PHP_METHOD(sqlite3, loadExtension)
333{
334	php_sqlite3_db_object *db_obj;
335	zval *object = getThis();
336	char *extension, *lib_path, *extension_dir, *errtext = NULL;
337	char fullpath[MAXPATHLEN];
338	size_t extension_len, extension_dir_len;
339	db_obj = Z_SQLITE3_DB_P(object);
340
341	SQLITE3_CHECK_INITIALIZED(db_obj, db_obj->initialised, SQLite3)
342
343	if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS(), "s", &extension, &extension_len)) {
344		return;
345	}
346
347#ifdef ZTS
348	if ((strncmp(sapi_module.name, "cgi", 3) != 0) &&
349		(strcmp(sapi_module.name, "cli") != 0) &&
350		(strncmp(sapi_module.name, "embed", 5) != 0)
351	) {		php_sqlite3_error(db_obj, "Not supported in multithreaded Web servers");
352		RETURN_FALSE;
353	}
354#endif
355
356	if (!SQLITE3G(extension_dir)) {
357		php_sqlite3_error(db_obj, "SQLite Extension are disabled");
358		RETURN_FALSE;
359	}
360
361	if (extension_len == 0) {
362		php_sqlite3_error(db_obj, "Empty string as an extension");
363		RETURN_FALSE;
364	}
365
366	extension_dir = SQLITE3G(extension_dir);
367	extension_dir_len = strlen(SQLITE3G(extension_dir));
368
369	if (IS_SLASH(extension_dir[extension_dir_len-1])) {
370		spprintf(&lib_path, 0, "%s%s", extension_dir, extension);
371	} else {
372		spprintf(&lib_path, 0, "%s%c%s", extension_dir, DEFAULT_SLASH, extension);
373	}
374
375	if (!VCWD_REALPATH(lib_path, fullpath)) {
376		php_sqlite3_error(db_obj, "Unable to load extension at '%s'", lib_path);
377		efree(lib_path);
378		RETURN_FALSE;
379	}
380
381	efree(lib_path);
382
383	if (strncmp(fullpath, extension_dir, extension_dir_len) != 0) {
384		php_sqlite3_error(db_obj, "Unable to open extensions outside the defined directory");
385		RETURN_FALSE;
386	}
387
388	/* Extension loading should only be enabled for when we attempt to load */
389	sqlite3_enable_load_extension(db_obj->db, 1);
390	if (sqlite3_load_extension(db_obj->db, fullpath, 0, &errtext) != SQLITE_OK) {
391		php_sqlite3_error(db_obj, "%s", errtext);
392		sqlite3_free(errtext);
393		sqlite3_enable_load_extension(db_obj->db, 0);
394		RETURN_FALSE;
395	}
396	sqlite3_enable_load_extension(db_obj->db, 0);
397
398	RETURN_TRUE;
399}
400/* }}} */
401#endif
402
403/* {{{ proto int SQLite3::changes()
404  Returns the number of database rows that were changed (or inserted or deleted) by the most recent SQL statement. */
405PHP_METHOD(sqlite3, changes)
406{
407	php_sqlite3_db_object *db_obj;
408	zval *object = getThis();
409	db_obj = Z_SQLITE3_DB_P(object);
410
411	SQLITE3_CHECK_INITIALIZED(db_obj, db_obj->initialised, SQLite3)
412
413	if (zend_parse_parameters_none() == FAILURE) {
414		return;
415	}
416
417	RETURN_LONG(sqlite3_changes(db_obj->db));
418}
419/* }}} */
420
421/* {{{ proto String SQLite3::escapeString(String value)
422   Returns a string that has been properly escaped. */
423PHP_METHOD(sqlite3, escapeString)
424{
425	zend_string *sql;
426	char *ret;
427
428	if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS(), "S", &sql)) {
429		return;
430	}
431
432	if (ZSTR_LEN(sql)) {
433		ret = sqlite3_mprintf("%q", ZSTR_VAL(sql));
434		if (ret) {
435			RETVAL_STRING(ret);
436			sqlite3_free(ret);
437		}
438	} else {
439		RETURN_EMPTY_STRING();
440	}
441}
442/* }}} */
443
444/* {{{ proto SQLite3Stmt SQLite3::prepare(String Query)
445   Returns a prepared SQL statement for execution. */
446PHP_METHOD(sqlite3, prepare)
447{
448	php_sqlite3_db_object *db_obj;
449	php_sqlite3_stmt *stmt_obj;
450	zval *object = getThis();
451	zend_string *sql;
452	int errcode;
453	php_sqlite3_free_list *free_item;
454
455	db_obj = Z_SQLITE3_DB_P(object);
456
457	SQLITE3_CHECK_INITIALIZED(db_obj, db_obj->initialised, SQLite3)
458
459	if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS(), "S", &sql)) {
460		return;
461	}
462
463	if (!ZSTR_LEN(sql)) {
464		RETURN_FALSE;
465	}
466
467	object_init_ex(return_value, php_sqlite3_stmt_entry);
468	stmt_obj = Z_SQLITE3_STMT_P(return_value);
469	stmt_obj->db_obj = db_obj;
470	ZVAL_COPY(&stmt_obj->db_obj_zval, object);
471
472	errcode = sqlite3_prepare_v2(db_obj->db, ZSTR_VAL(sql), ZSTR_LEN(sql), &(stmt_obj->stmt), NULL);
473	if (errcode != SQLITE_OK) {
474		php_sqlite3_error(db_obj, "Unable to prepare statement: %d, %s", errcode, sqlite3_errmsg(db_obj->db));
475		zval_dtor(return_value);
476		RETURN_FALSE;
477	}
478
479	stmt_obj->initialised = 1;
480
481	free_item = emalloc(sizeof(php_sqlite3_free_list));
482	free_item->stmt_obj = stmt_obj;
483	ZVAL_COPY_VALUE(&free_item->stmt_obj_zval, return_value);
484
485	zend_llist_add_element(&(db_obj->free_list), &free_item);
486}
487/* }}} */
488
489/* {{{ proto SQLite3Result SQLite3::query(String Query)
490   Returns true or false, for queries that return data it will return a SQLite3Result object. */
491PHP_METHOD(sqlite3, query)
492{
493	php_sqlite3_db_object *db_obj;
494	php_sqlite3_result *result;
495	php_sqlite3_stmt *stmt_obj;
496	zval *object = getThis();
497	zval stmt;
498	zend_string *sql;
499	char *errtext = NULL;
500	int return_code;
501	db_obj = Z_SQLITE3_DB_P(object);
502
503	SQLITE3_CHECK_INITIALIZED(db_obj, db_obj->initialised, SQLite3)
504
505	if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS(), "S", &sql)) {
506		return;
507	}
508
509	if (!ZSTR_LEN(sql)) {
510		RETURN_FALSE;
511	}
512
513	/* If there was no return value then just execute the query */
514	if (!USED_RET()) {
515		if (sqlite3_exec(db_obj->db, ZSTR_VAL(sql), NULL, NULL, &errtext) != SQLITE_OK) {
516			php_sqlite3_error(db_obj, "%s", errtext);
517			sqlite3_free(errtext);
518		}
519		return;
520	}
521
522	object_init_ex(&stmt, php_sqlite3_stmt_entry);
523	stmt_obj = Z_SQLITE3_STMT_P(&stmt);
524	stmt_obj->db_obj = db_obj;
525	ZVAL_COPY(&stmt_obj->db_obj_zval, object);
526
527	return_code = sqlite3_prepare_v2(db_obj->db, ZSTR_VAL(sql), ZSTR_LEN(sql), &(stmt_obj->stmt), NULL);
528	if (return_code != SQLITE_OK) {
529		php_sqlite3_error(db_obj, "Unable to prepare statement: %d, %s", return_code, sqlite3_errmsg(db_obj->db));
530		zval_ptr_dtor(&stmt);
531		RETURN_FALSE;
532	}
533
534	stmt_obj->initialised = 1;
535
536	object_init_ex(return_value, php_sqlite3_result_entry);
537	result = Z_SQLITE3_RESULT_P(return_value);
538	result->db_obj = db_obj;
539	result->stmt_obj = stmt_obj;
540	ZVAL_COPY_VALUE(&result->stmt_obj_zval, &stmt);
541
542	return_code = sqlite3_step(result->stmt_obj->stmt);
543
544	switch (return_code) {
545		case SQLITE_ROW: /* Valid Row */
546		case SQLITE_DONE: /* Valid but no results */
547		{
548			php_sqlite3_free_list *free_item;
549			free_item = emalloc(sizeof(php_sqlite3_free_list));
550			free_item->stmt_obj = stmt_obj;
551			free_item->stmt_obj_zval = stmt;
552			zend_llist_add_element(&(db_obj->free_list), &free_item);
553			sqlite3_reset(result->stmt_obj->stmt);
554			break;
555		}
556		default:
557			php_sqlite3_error(db_obj, "Unable to execute statement: %s", sqlite3_errmsg(db_obj->db));
558			sqlite3_finalize(stmt_obj->stmt);
559			stmt_obj->initialised = 0;
560			zval_dtor(return_value);
561			RETURN_FALSE;
562	}
563}
564/* }}} */
565
566static void sqlite_value_to_zval(sqlite3_stmt *stmt, int column, zval *data) /* {{{ */
567{
568	switch (sqlite3_column_type(stmt, column)) {
569		case SQLITE_INTEGER:
570			if ((sqlite3_column_int64(stmt, column)) >= INT_MAX || sqlite3_column_int64(stmt, column) <= INT_MIN) {
571				ZVAL_STRINGL(data, (char *)sqlite3_column_text(stmt, column), sqlite3_column_bytes(stmt, column));
572			} else {
573				ZVAL_LONG(data, sqlite3_column_int64(stmt, column));
574			}
575			break;
576
577		case SQLITE_FLOAT:
578			ZVAL_DOUBLE(data, sqlite3_column_double(stmt, column));
579			break;
580
581		case SQLITE_NULL:
582			ZVAL_NULL(data);
583			break;
584
585		case SQLITE3_TEXT:
586			ZVAL_STRING(data, (char*)sqlite3_column_text(stmt, column));
587			break;
588
589		case SQLITE_BLOB:
590		default:
591			ZVAL_STRINGL(data, (char*)sqlite3_column_blob(stmt, column), sqlite3_column_bytes(stmt, column));
592	}
593}
594/* }}} */
595
596/* {{{ proto SQLite3Result SQLite3::querySingle(String Query [, bool entire_row = false])
597   Returns a string of the first column, or an array of the entire row. */
598PHP_METHOD(sqlite3, querySingle)
599{
600	php_sqlite3_db_object *db_obj;
601	zval *object = getThis();
602	zend_string *sql;
603	char *errtext = NULL;
604	int return_code;
605	zend_bool entire_row = 0;
606	sqlite3_stmt *stmt;
607	db_obj = Z_SQLITE3_DB_P(object);
608
609	SQLITE3_CHECK_INITIALIZED(db_obj, db_obj->initialised, SQLite3)
610
611	if (FAILURE == zend_parse_parameters(ZEND_NUM_ARGS(), "S|b", &sql, &entire_row)) {
612		return;
613	}
614
615	if (!ZSTR_LEN(sql)) {
616		RETURN_FALSE;
617	}
618
619	/* If there was no return value then just execute the query */
620	if (!USED_RET()) {
621		if (sqlite3_exec(db_obj->db, ZSTR_VAL(sql), NULL, NULL, &errtext) != SQLITE_OK) {
622			php_sqlite3_error(db_obj, "%s", errtext);
623			sqlite3_free(errtext);
624		}
625		return;
626	}
627
628	return_code = sqlite3_prepare_v2(db_obj->db, ZSTR_VAL(sql), ZSTR_LEN(sql), &stmt, NULL);
629	if (return_code != SQLITE_OK) {
630		php_sqlite3_error(db_obj, "Unable to prepare statement: %d, %s", return_code, sqlite3_errmsg(db_obj->db));
631		RETURN_FALSE;
632	}
633
634	return_code = sqlite3_step(stmt);
635
636	switch (return_code) {
637		case SQLITE_ROW: /* Valid Row */
638		{
639			if (!entire_row) {
640				sqlite_value_to_zval(stmt, 0, return_value);
641			} else {
642				int i = 0;
643				array_init(return_value);
644				for (i = 0; i < sqlite3_data_count(stmt); i++) {
645					zval data;
646					sqlite_value_to_zval(stmt, i, &data);
647					add_assoc_zval(return_value, (char*)sqlite3_column_name(stmt, i), &data);
648				}
649			}
650			break;
651		}
652		case SQLITE_DONE: /* Valid but no results */
653		{
654			if (!entire_row) {
655				RETVAL_NULL();
656			} else {
657				array_init(return_value);
658			}
659			break;
660		}
661		default:
662			php_sqlite3_error(db_obj, "Unable to execute statement: %s", sqlite3_errmsg(db_obj->db));
663			RETVAL_FALSE;
664	}
665	sqlite3_finalize(stmt);
666}
667/* }}} */
668
669static int sqlite3_do_callback(struct php_sqlite3_fci *fc, zval *cb, int argc, sqlite3_value **argv, sqlite3_context *context, int is_agg) /* {{{ */
670{
671	zval *zargs = NULL;
672	zval retval;
673	int i;
674	int ret;
675	int fake_argc;
676	php_sqlite3_agg_context *agg_context = NULL;
677
678	if (is_agg) {
679		is_agg = 2;
680	}
681
682	fake_argc = argc + is_agg;
683
684	fc->fci.size = sizeof(fc->fci);
685	fc->fci.function_table = EG(function_table);
686	ZVAL_COPY_VALUE(&fc->fci.function_name, cb);
687	fc->fci.symbol_table = NULL;
688	fc->fci.object = NULL;
689	fc->fci.retval = &retval;
690	fc->fci.param_count = fake_argc;
691
692	/* build up the params */
693
694	if (fake_argc) {
695		zargs = (zval *)safe_emalloc(fake_argc, sizeof(zval), 0);
696	}
697
698	if (is_agg) {
699		/* summon the aggregation context */
700		agg_context = (php_sqlite3_agg_context *)sqlite3_aggregate_context(context, sizeof(php_sqlite3_agg_context));
701
702		if (Z_ISUNDEF(agg_context->zval_context)) {
703			ZVAL_NULL(&agg_context->zval_context);
704		}
705		ZVAL_DUP(&zargs[0], &agg_context->zval_context);
706		ZVAL_LONG(&zargs[1], agg_context->row_count);
707	}
708
709	for (i = 0; i < argc; i++) {
710		switch (sqlite3_value_type(argv[i])) {
711			case SQLITE_INTEGER:
712#if ZEND_LONG_MAX > 2147483647
713				ZVAL_LONG(&zargs[i + is_agg], sqlite3_value_int64(argv[i]));
714#else
715				ZVAL_LONG(&zargs[i + is_agg], sqlite3_value_int(argv[i]));
716#endif
717				break;
718
719			case SQLITE_FLOAT:
720				ZVAL_DOUBLE(&zargs[i + is_agg], sqlite3_value_double(argv[i]));
721				break;
722
723			case SQLITE_NULL:
724				ZVAL_NULL(&zargs[i + is_agg]);
725				break;
726
727			case SQLITE_BLOB:
728			case SQLITE3_TEXT:
729			default:
730				ZVAL_STRINGL(&zargs[i + is_agg], (char*)sqlite3_value_text(argv[i]), sqlite3_value_bytes(argv[i]));
731				break;
732		}
733	}
734
735	fc->fci.params = zargs;
736
737	if ((ret = zend_call_function(&fc->fci, &fc->fcc)) == FAILURE) {
738		php_error_docref(NULL, E_WARNING, "An error occurred while invoking the callback");
739	}
740
741	if (is_agg) {
742		zval_ptr_dtor(&zargs[0]);
743	}
744
745	/* clean up the params */
746	if (fake_argc) {
747		for (i = is_agg; i < argc + is_agg; i++) {
748			zval_ptr_dtor(&zargs[i]);
749		}
750		if (is_agg) {
751			zval_ptr_dtor(&zargs[1]);
752		}
753		efree(zargs);
754	}
755
756	if (!is_agg || !argv) {
757		/* only set the sqlite return value if we are a scalar function,
758		 * or if we are finalizing an aggregate */
759		if (!Z_ISUNDEF(retval)) {
760			switch (Z_TYPE(retval)) {
761				case IS_LONG:
762#if ZEND_LONG_MAX > 2147483647
763					sqlite3_result_int64(context, Z_LVAL(retval));
764#else
765					sqlite3_result_int(context, Z_LVAL(retval));
766#endif
767					break;
768
769				case IS_NULL:
770					sqlite3_result_null(context);
771					break;
772
773				case IS_DOUBLE:
774					sqlite3_result_double(context, Z_DVAL(retval));
775					break;
776
777				default:
778					convert_to_string_ex(&retval);
779					sqlite3_result_text(context, Z_STRVAL(retval), Z_STRLEN(retval), SQLITE_TRANSIENT);
780					break;
781			}
782		} else {
783			sqlite3_result_error(context, "failed to invoke callback", 0);
784		}
785
786		if (agg_context && !Z_ISUNDEF(agg_context->zval_context)) {
787			zval_ptr_dtor(&agg_context->zval_context);
788		}
789	} else {
790		/* we're stepping in an aggregate; the return value goes into
791		 * the context */
792		if (agg_context && !Z_ISUNDEF(agg_context->zval_context)) {
793			zval_ptr_dtor(&agg_context->zval_context);
794		}
795		ZVAL_COPY_VALUE(&agg_context->zval_context, &retval);
796		ZVAL_UNDEF(&retval);
797	}
798
799	if (!Z_ISUNDEF(retval)) {
800		zval_ptr_dtor(&retval);
801	}
802	return ret;
803}
804/* }}}*/
805
806static void php_sqlite3_callback_func(sqlite3_context *context, int argc, sqlite3_value **argv) /* {{{ */
807{
808	php_sqlite3_func *func = (php_sqlite3_func *)sqlite3_user_data(context);
809
810	sqlite3_do_callback(&func->afunc, &func->func, argc, argv, context, 0);
811}
812/* }}}*/
813
814static void php_sqlite3_callback_step(sqlite3_context *context, int argc, sqlite3_value **argv) /* {{{ */
815{
816	php_sqlite3_func *func = (php_sqlite3_func *)sqlite3_user_data(context);
817	php_sqlite3_agg_context *agg_context = (php_sqlite3_agg_context *)sqlite3_aggregate_context(context, sizeof(php_sqlite3_agg_context));
818
819	agg_context->row_count++;
820
821	sqlite3_do_callback(&func->astep, &func->step, argc, argv, context, 1);
822}
823/* }}} */
824
825static void php_sqlite3_callback_final(sqlite3_context *context) /* {{{ */
826{
827	php_sqlite3_func *func = (php_sqlite3_func *)sqlite3_user_data(context);
828	php_sqlite3_agg_context *agg_context = (php_sqlite3_agg_context *)sqlite3_aggregate_context(context, sizeof(php_sqlite3_agg_context));
829
830	agg_context->row_count = 0;
831
832	sqlite3_do_callback(&func->afini, &func->fini, 0, NULL, context, 1);
833}
834/* }}} */
835
836static int php_sqlite3_callback_compare(void *coll, int a_len, const void *a, int b_len, const void* b) /* {{{ */
837{
838	php_sqlite3_collation *collation = (php_sqlite3_collation*)coll;
839	zval *zargs = NULL;
840	zval retval;
841	int ret;
842
843	collation->fci.fci.size = (sizeof(collation->fci.fci));
844	collation->fci.fci.function_table = EG(function_table);
845	ZVAL_COPY_VALUE(&collation->fci.fci.function_name, &collation->cmp_func);
846	collation->fci.fci.symbol_table = NULL;
847	collation->fci.fci.object = NULL;
848	collation->fci.fci.retval = &retval;
849	collation->fci.fci.param_count = 2;
850
851	zargs = safe_emalloc(2, sizeof(zval), 0);
852	ZVAL_STRINGL(&zargs[0], a, a_len);
853	ZVAL_STRINGL(&zargs[1], b, b_len);
854
855	collation->fci.fci.params = zargs;
856
857	if (!EG(exception)) {
858		//Exception occurred on previous callback. Don't attempt to call function
859		if ((ret = zend_call_function(&collation->fci.fci, &collation->fci.fcc)) == FAILURE) {
860			php_error_docref(NULL, E_WARNING, "An error occurred while invoking the compare callback");
861		}
862	} else {
863		ZVAL_UNDEF(&retval);
864	}
865
866	zval_ptr_dtor(&zargs[0]);
867	zval_ptr_dtor(&zargs[1]);
868	efree(zargs);
869
870	if (EG(exception)) {
871		ret = 0;
872	} else if (Z_TYPE(retval) != IS_LONG){
873		//retval ought to contain a ZVAL_LONG by now
874		// (the result of a comparison, i.e. most likely -1, 0, or 1)
875		//I suppose we could accept any scalar return type, though.
876		php_error_docref(NULL, E_WARNING, "An error occurred while invoking the compare callback (invalid return type).  Collation behaviour is undefined.");
877	} else {
878		ret = Z_LVAL(retval);
879	}
880
881	zval_ptr_dtor(&retval);
882
883	return ret;
884}
885/* }}} */
886
887/* {{{ proto bool SQLite3::createFunction(string name, mixed callback [, int argcount])
888   Allows registration of a PHP function as a SQLite UDF that can be called within SQL statements. */
889PHP_METHOD(sqlite3, createFunction)
890{
891	php_sqlite3_db_object *db_obj;
892	zval *object = getThis();
893	php_sqlite3_func *func;
894	char *sql_func;
895	size_t sql_func_len;
896	zval *callback_func;
897	zend_string *callback_name;
898	zend_long sql_func_num_args = -1;
899	db_obj = Z_SQLITE3_DB_P(object);
900
901	SQLITE3_CHECK_INITIALIZED(db_obj, db_obj->initialised, SQLite3)
902
903	if (zend_parse_parameters(ZEND_NUM_ARGS(), "sz|l", &sql_func, &sql_func_len, &callback_func, &sql_func_num_args) == FAILURE) {
904		return;
905	}
906
907	if (!sql_func_len) {
908		RETURN_FALSE;
909	}
910
911	if (!zend_is_callable(callback_func, 0, &callback_name)) {
912		php_sqlite3_error(db_obj, "Not a valid callback function %s", ZSTR_VAL(callback_name));
913		zend_string_release(callback_name);
914		RETURN_FALSE;
915	}
916	zend_string_release(callback_name);
917
918	func = (php_sqlite3_func *)ecalloc(1, sizeof(*func));
919
920	if (sqlite3_create_function(db_obj->db, sql_func, sql_func_num_args, SQLITE_UTF8, func, php_sqlite3_callback_func, NULL, NULL) == SQLITE_OK) {
921		func->func_name = estrdup(sql_func);
922
923		ZVAL_COPY(&func->func, callback_func);
924
925		func->argc = sql_func_num_args;
926		func->next = db_obj->funcs;
927		db_obj->funcs = func;
928
929		RETURN_TRUE;
930	}
931	efree(func);
932
933	RETURN_FALSE;
934}
935/* }}} */
936
937/* {{{ proto bool SQLite3::createAggregate(string name, mixed step, mixed final [, int argcount])
938   Allows registration of a PHP function for use as an aggregate. */
939PHP_METHOD(sqlite3, createAggregate)
940{
941	php_sqlite3_db_object *db_obj;
942	zval *object = getThis();
943	php_sqlite3_func *func;
944	char *sql_func;
945	zend_string *callback_name;
946	size_t sql_func_len;
947	zval *step_callback, *fini_callback;
948	zend_long sql_func_num_args = -1;
949	db_obj = Z_SQLITE3_DB_P(object);
950
951	SQLITE3_CHECK_INITIALIZED(db_obj, db_obj->initialised, SQLite3)
952
953	if (zend_parse_parameters(ZEND_NUM_ARGS(), "szz|l", &sql_func, &sql_func_len, &step_callback, &fini_callback, &sql_func_num_args) == FAILURE) {
954		return;
955	}
956
957	if (!sql_func_len) {
958		RETURN_FALSE;
959	}
960
961	if (!zend_is_callable(step_callback, 0, &callback_name)) {
962		php_sqlite3_error(db_obj, "Not a valid callback function %s", ZSTR_VAL(callback_name));
963		zend_string_release(callback_name);
964		RETURN_FALSE;
965	}
966	zend_string_release(callback_name);
967
968	if (!zend_is_callable(fini_callback, 0, &callback_name)) {
969		php_sqlite3_error(db_obj, "Not a valid callback function %s", ZSTR_VAL(callback_name));
970		zend_string_release(callback_name);
971		RETURN_FALSE;
972	}
973	zend_string_release(callback_name);
974
975	func = (php_sqlite3_func *)ecalloc(1, sizeof(*func));
976
977	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) {
978		func->func_name = estrdup(sql_func);
979
980		ZVAL_COPY(&func->step, step_callback);
981		ZVAL_COPY(&func->fini, fini_callback);
982
983		func->argc = sql_func_num_args;
984		func->next = db_obj->funcs;
985		db_obj->funcs = func;
986
987		RETURN_TRUE;
988	}
989	efree(func);
990
991	RETURN_FALSE;
992}
993/* }}} */
994
995/* {{{ proto bool SQLite3::createCollation(string name, mixed callback)
996   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()). */
997PHP_METHOD(sqlite3, createCollation)
998{
999	php_sqlite3_db_object *db_obj;
1000	zval *object = getThis();
1001	php_sqlite3_collation *collation;
1002	char *collation_name;
1003	zend_string *callback_name;
1004	size_t collation_name_len;
1005	zval *callback_func;
1006	db_obj = Z_SQLITE3_DB_P(object);
1007
1008	SQLITE3_CHECK_INITIALIZED(db_obj, db_obj->initialised, SQLite3)
1009
1010	if (zend_parse_parameters(ZEND_NUM_ARGS(), "sz", &collation_name, &collation_name_len, &callback_func) == FAILURE) {
1011		RETURN_FALSE;
1012	}
1013
1014	if (!collation_name_len) {
1015		RETURN_FALSE;
1016	}
1017
1018	if (!zend_is_callable(callback_func, 0, &callback_name)) {
1019		php_sqlite3_error(db_obj, "Not a valid callback function %s", ZSTR_VAL(callback_name));
1020		zend_string_release(callback_name);
1021		RETURN_FALSE;
1022	}
1023	zend_string_release(callback_name);
1024
1025	collation = (php_sqlite3_collation *)ecalloc(1, sizeof(*collation));
1026	if (sqlite3_create_collation(db_obj->db, collation_name, SQLITE_UTF8, collation, php_sqlite3_callback_compare) == SQLITE_OK) {
1027		collation->collation_name = estrdup(collation_name);
1028
1029		ZVAL_COPY(&collation->cmp_func, callback_func);
1030
1031		collation->next = db_obj->collations;
1032		db_obj->collations = collation;
1033
1034		RETURN_TRUE;
1035	}
1036	efree(collation);
1037
1038	RETURN_FALSE;
1039}
1040/* }}} */
1041
1042typedef struct {
1043	sqlite3_blob *blob;
1044	size_t		 position;
1045	size_t       size;
1046} php_stream_sqlite3_data;
1047
1048static size_t php_sqlite3_stream_write(php_stream *stream, const char *buf, size_t count)
1049{
1050/*	php_stream_sqlite3_data *sqlite3_stream = (php_stream_sqlite3_data *) stream->abstract; */
1051
1052	return 0;
1053}
1054
1055static size_t php_sqlite3_stream_read(php_stream *stream, char *buf, size_t count)
1056{
1057	php_stream_sqlite3_data *sqlite3_stream = (php_stream_sqlite3_data *) stream->abstract;
1058
1059	if (sqlite3_stream->position + count >= sqlite3_stream->size) {
1060		count = sqlite3_stream->size - sqlite3_stream->position;
1061		stream->eof = 1;
1062	}
1063	if (count) {
1064		if (sqlite3_blob_read(sqlite3_stream->blob, buf, count, sqlite3_stream->position) != SQLITE_OK) {
1065			return 0;
1066		}
1067		sqlite3_stream->position += count;
1068	}
1069	return count;
1070}
1071
1072static int php_sqlite3_stream_close(php_stream *stream, int close_handle)
1073{
1074	php_stream_sqlite3_data *sqlite3_stream = (php_stream_sqlite3_data *) stream->abstract;
1075
1076	if (sqlite3_blob_close(sqlite3_stream->blob) != SQLITE_OK) {
1077		/* Error occurred, but it still closed */
1078	}
1079
1080	efree(sqlite3_stream);
1081
1082	return 0;
1083}
1084
1085static int php_sqlite3_stream_flush(php_stream *stream)
1086{
1087	/* do nothing */
1088	return 0;
1089}
1090
1091/* {{{ */
1092static int php_sqlite3_stream_seek(php_stream *stream, zend_off_t offset, int whence, zend_off_t *newoffs)
1093{
1094	php_stream_sqlite3_data *sqlite3_stream = (php_stream_sqlite3_data *) stream->abstract;
1095
1096	switch(whence) {
1097		case SEEK_CUR:
1098			if (offset < 0) {
1099				if (sqlite3_stream->position < (size_t)(-offset)) {
1100					sqlite3_stream->position = 0;
1101					*newoffs = -1;
1102					return -1;
1103				} else {
1104					sqlite3_stream->position = sqlite3_stream->position + offset;
1105					*newoffs = sqlite3_stream->position;
1106					stream->eof = 0;
1107					return 0;
1108				}
1109			} else {
1110				if (sqlite3_stream->position + (size_t)(offset) > sqlite3_stream->size) {
1111					sqlite3_stream->position = sqlite3_stream->size;
1112					*newoffs = -1;
1113					return -1;
1114				} else {
1115					sqlite3_stream->position = sqlite3_stream->position + offset;
1116					*newoffs = sqlite3_stream->position;
1117					stream->eof = 0;
1118					return 0;
1119				}
1120			}
1121		case SEEK_SET:
1122			if (sqlite3_stream->size < (size_t)(offset)) {
1123				sqlite3_stream->position = sqlite3_stream->size;
1124				*newoffs = -1;
1125				return -1;
1126			} else {
1127				sqlite3_stream->position = offset;
1128				*newoffs = sqlite3_stream->position;
1129				stream->eof = 0;
1130				return 0;
1131			}
1132		case SEEK_END:
1133			if (offset > 0) {
1134				sqlite3_stream->position = sqlite3_stream->size;
1135				*newoffs = -1;
1136				return -1;
1137			} else if (sqlite3_stream->size < (size_t)(-offset)) {
1138				sqlite3_stream->position = 0;
1139				*newoffs = -1;
1140				return -1;
1141			} else {
1142				sqlite3_stream->position = sqlite3_stream->size + offset;
1143				*newoffs = sqlite3_stream->position;
1144				stream->eof = 0;
1145				return 0;
1146			}
1147		default:
1148			*newoffs = sqlite3_stream->position;
1149			return -1;
1150	}
1151}
1152/* }}} */
1153
1154
1155static int php_sqlite3_stream_cast(php_stream *stream, int castas, void **ret)
1156{
1157	return FAILURE;
1158}
1159
1160static int php_sqlite3_stream_stat(php_stream *stream, php_stream_statbuf *ssb)
1161{
1162	php_stream_sqlite3_data *sqlite3_stream = (php_stream_sqlite3_data *) stream->abstract;
1163	ssb->sb.st_size = sqlite3_stream->size;
1164	return 0;
1165}
1166
1167static php_stream_ops php_stream_sqlite3_ops = {
1168	php_sqlite3_stream_write,
1169	php_sqlite3_stream_read,
1170	php_sqlite3_stream_close,
1171	php_sqlite3_stream_flush,
1172	"SQLite3",
1173	php_sqlite3_stream_seek,
1174	php_sqlite3_stream_cast,
1175	php_sqlite3_stream_stat
1176};
1177
1178/* {{{ proto resource SQLite3::openBlob(string table, string column, int rowid [, string dbname])
1179   Open a blob as a stream which we can read / write to. */
1180PHP_METHOD(sqlite3, openBlob)
1181{
1182	php_sqlite3_db_object *db_obj;
1183	zval *object = getThis();
1184	char *table, *column, *dbname = "main";
1185	size_t table_len, column_len, dbname_len;
1186	zend_long rowid, flags = 0;
1187	sqlite3_blob *blob = NULL;
1188	php_stream_sqlite3_data *sqlite3_stream;
1189	php_stream *stream;
1190
1191	db_obj = Z_SQLITE3_DB_P(object);
1192
1193	SQLITE3_CHECK_INITIALIZED(db_obj, db_obj->initialised, SQLite3)
1194
1195	if (zend_parse_parameters(ZEND_NUM_ARGS(), "ssl|s", &table, &table_len, &column, &column_len, &rowid, &dbname, &dbname_len) == FAILURE) {
1196		return;
1197	}
1198
1199	if (sqlite3_blob_open(db_obj->db, dbname, table, column, rowid, flags, &blob) != SQLITE_OK) {
1200		php_sqlite3_error(db_obj, "Unable to open blob: %s", sqlite3_errmsg(db_obj->db));
1201		RETURN_FALSE;
1202	}
1203
1204	sqlite3_stream = emalloc(sizeof(php_stream_sqlite3_data));
1205	sqlite3_stream->blob = blob;
1206	sqlite3_stream->position = 0;
1207	sqlite3_stream->size = sqlite3_blob_bytes(blob);
1208
1209	stream = php_stream_alloc(&php_stream_sqlite3_ops, sqlite3_stream, 0, "rb");
1210
1211	if (stream) {
1212		php_stream_to_zval(stream, return_value);
1213	} else {
1214		RETURN_FALSE;
1215	}
1216}
1217/* }}} */
1218
1219/* {{{ proto bool SQLite3::enableExceptions([bool enableExceptions = false])
1220   Enables an exception error mode. */
1221PHP_METHOD(sqlite3, enableExceptions)
1222{
1223	php_sqlite3_db_object *db_obj;
1224	zval *object = getThis();
1225	zend_bool enableExceptions = 0;
1226
1227	db_obj = Z_SQLITE3_DB_P(object);
1228
1229	if (zend_parse_parameters(ZEND_NUM_ARGS(), "|b", &enableExceptions) == FAILURE) {
1230		return;
1231	}
1232
1233	RETVAL_BOOL(db_obj->exception);
1234
1235	db_obj->exception = enableExceptions;
1236}
1237/* }}} */
1238
1239/* {{{ proto int SQLite3Stmt::paramCount()
1240   Returns the number of parameters within the prepared statement. */
1241PHP_METHOD(sqlite3stmt, paramCount)
1242{
1243	php_sqlite3_stmt *stmt_obj;
1244	zval *object = getThis();
1245	stmt_obj = Z_SQLITE3_STMT_P(object);
1246
1247	if (zend_parse_parameters_none() == FAILURE) {
1248		return;
1249	}
1250
1251	SQLITE3_CHECK_INITIALIZED(stmt_obj->db_obj, stmt_obj->initialised, SQLite3);
1252	SQLITE3_CHECK_INITIALIZED_STMT(stmt_obj->stmt, SQLite3Stmt);
1253
1254	RETURN_LONG(sqlite3_bind_parameter_count(stmt_obj->stmt));
1255}
1256/* }}} */
1257
1258/* {{{ proto bool SQLite3Stmt::close()
1259   Closes the prepared statement. */
1260PHP_METHOD(sqlite3stmt, close)
1261{
1262	php_sqlite3_stmt *stmt_obj;
1263	zval *object = getThis();
1264	stmt_obj = Z_SQLITE3_STMT_P(object);
1265
1266	if (zend_parse_parameters_none() == FAILURE) {
1267		return;
1268	}
1269
1270	SQLITE3_CHECK_INITIALIZED(stmt_obj->db_obj, stmt_obj->initialised, SQLite3);
1271
1272	if(stmt_obj->db_obj) {
1273        	zend_llist_del_element(&(stmt_obj->db_obj->free_list), object, (int (*)(void *, void *)) php_sqlite3_compare_stmt_zval_free);
1274	}
1275
1276	RETURN_TRUE;
1277}
1278/* }}} */
1279
1280/* {{{ proto bool SQLite3Stmt::reset()
1281   Reset the prepared statement to the state before it was executed, bindings still remain. */
1282PHP_METHOD(sqlite3stmt, reset)
1283{
1284	php_sqlite3_stmt *stmt_obj;
1285	zval *object = getThis();
1286	stmt_obj = Z_SQLITE3_STMT_P(object);
1287
1288	if (zend_parse_parameters_none() == FAILURE) {
1289		return;
1290	}
1291
1292	SQLITE3_CHECK_INITIALIZED(stmt_obj->db_obj, stmt_obj->initialised, SQLite3);
1293	SQLITE3_CHECK_INITIALIZED_STMT(stmt_obj->stmt, SQLite3Stmt);
1294
1295	if (sqlite3_reset(stmt_obj->stmt) != SQLITE_OK) {
1296		php_sqlite3_error(stmt_obj->db_obj, "Unable to reset statement: %s", sqlite3_errmsg(sqlite3_db_handle(stmt_obj->stmt)));
1297		RETURN_FALSE;
1298	}
1299	RETURN_TRUE;
1300}
1301/* }}} */
1302
1303/* {{{ proto bool SQLite3Stmt::clear()
1304   Clear all current bound parameters. */
1305PHP_METHOD(sqlite3stmt, clear)
1306{
1307	php_sqlite3_stmt *stmt_obj;
1308	zval *object = getThis();
1309	stmt_obj = Z_SQLITE3_STMT_P(object);
1310
1311	if (zend_parse_parameters_none() == FAILURE) {
1312		return;
1313	}
1314
1315	SQLITE3_CHECK_INITIALIZED(stmt_obj->db_obj, stmt_obj->initialised, SQLite3);
1316	SQLITE3_CHECK_INITIALIZED_STMT(stmt_obj->stmt, SQLite3Stmt);
1317
1318	if (sqlite3_clear_bindings(stmt_obj->stmt) != SQLITE_OK) {
1319		php_sqlite3_error(stmt_obj->db_obj, "Unable to clear statement: %s", sqlite3_errmsg(sqlite3_db_handle(stmt_obj->stmt)));
1320		RETURN_FALSE;
1321	}
1322
1323	RETURN_TRUE;
1324}
1325/* }}} */
1326
1327/* {{{ proto bool SQLite3Stmt::readOnly()
1328   Returns true if a statement is definitely read only */
1329PHP_METHOD(sqlite3stmt, readOnly)
1330{
1331	php_sqlite3_stmt *stmt_obj;
1332	zval *object = getThis();
1333	stmt_obj = Z_SQLITE3_STMT_P(object);
1334
1335	if (zend_parse_parameters_none() == FAILURE) {
1336		return;
1337	}
1338
1339	SQLITE3_CHECK_INITIALIZED(stmt_obj->db_obj, stmt_obj->initialised, SQLite3);
1340	SQLITE3_CHECK_INITIALIZED_STMT(stmt_obj->stmt, SQLite3Stmt);
1341
1342#if SQLITE_VERSION_NUMBER >= 3007004
1343	if (sqlite3_stmt_readonly(stmt_obj->stmt)) {
1344		RETURN_TRUE;
1345	}
1346#endif
1347	RETURN_FALSE;
1348}
1349/* }}} */
1350
1351static int register_bound_parameter_to_sqlite(struct php_sqlite3_bound_param *param, php_sqlite3_stmt *stmt) /* {{{ */
1352{
1353	HashTable *hash;
1354	hash = stmt->bound_params;
1355
1356	if (!hash) {
1357		ALLOC_HASHTABLE(hash);
1358		zend_hash_init(hash, 13, NULL, sqlite3_param_dtor, 0);
1359		stmt->bound_params = hash;
1360	}
1361
1362	/* We need a : prefix to resolve a name to a parameter number */
1363	if (param->name) {
1364		if (ZSTR_VAL(param->name)[0] != ':') {
1365			/* pre-increment for character + 1 for null */
1366			zend_string *temp = zend_string_alloc(ZSTR_LEN(param->name) + 1, 0);
1367			ZSTR_VAL(temp)[0] = ':';
1368			memmove(ZSTR_VAL(temp) + 1, ZSTR_VAL(param->name), ZSTR_LEN(param->name) + 1);
1369			param->name = temp;
1370		} else {
1371			param->name = zend_string_init(ZSTR_VAL(param->name), ZSTR_LEN(param->name), 0);
1372		}
1373		/* do lookup*/
1374		param->param_number = sqlite3_bind_parameter_index(stmt->stmt, ZSTR_VAL(param->name));
1375	}
1376
1377	if (param->param_number < 1) {
1378		zend_string_release(param->name);
1379		return 0;
1380	}
1381
1382	if (param->param_number >= 1) {
1383		zend_hash_index_del(hash, param->param_number);
1384	}
1385
1386	if (param->name) {
1387		zend_hash_update_mem(hash, param->name, param, sizeof(struct php_sqlite3_bound_param));
1388	} else {
1389		zend_hash_index_update_mem(hash, param->param_number, param, sizeof(struct php_sqlite3_bound_param));
1390	}
1391
1392	return 1;
1393}
1394/* }}} */
1395
1396/* {{{ proto bool SQLite3Stmt::bindParam(int parameter_number, mixed parameter [, int type])
1397   Bind Parameter to a stmt variable. */
1398PHP_METHOD(sqlite3stmt, bindParam)
1399{
1400	php_sqlite3_stmt *stmt_obj;
1401	zval *object = getThis();
1402	struct php_sqlite3_bound_param param = {0};
1403	zval *parameter;
1404	stmt_obj = Z_SQLITE3_STMT_P(object);
1405
1406	param.param_number = -1;
1407	param.type = SQLITE3_TEXT;
1408
1409	if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS(), "lz|l", &param.param_number, &parameter, &param.type) == FAILURE) {
1410		if (zend_parse_parameters(ZEND_NUM_ARGS(), "Sz|l", &param.name, &parameter, &param.type) == FAILURE) {
1411			return;
1412		}
1413	}
1414
1415	SQLITE3_CHECK_INITIALIZED(stmt_obj->db_obj, stmt_obj->initialised, SQLite3);
1416	SQLITE3_CHECK_INITIALIZED_STMT(stmt_obj->stmt, SQLite3Stmt);
1417
1418	ZVAL_COPY(&param.parameter, parameter);
1419
1420	if (!register_bound_parameter_to_sqlite(&param, stmt_obj)) {
1421		if (!Z_ISUNDEF(param.parameter)) {
1422			zval_ptr_dtor(&(param.parameter));
1423			ZVAL_UNDEF(&param.parameter);
1424		}
1425		RETURN_FALSE;
1426	}
1427	RETURN_TRUE;
1428}
1429/* }}} */
1430
1431/* {{{ proto bool SQLite3Stmt::bindValue(int parameter_number, mixed parameter [, int type])
1432   Bind Value of a parameter to a stmt variable. */
1433PHP_METHOD(sqlite3stmt, bindValue)
1434{
1435	php_sqlite3_stmt *stmt_obj;
1436	zval *object = getThis();
1437	struct php_sqlite3_bound_param param = {0};
1438	zval *parameter;
1439	stmt_obj = Z_SQLITE3_STMT_P(object);
1440
1441	param.param_number = -1;
1442	param.type = SQLITE3_TEXT;
1443
1444	if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS(), "lz/|l", &param.param_number, &parameter, &param.type) == FAILURE) {
1445		if (zend_parse_parameters(ZEND_NUM_ARGS(), "Sz/|l", &param.name, &parameter, &param.type) == FAILURE) {
1446			return;
1447		}
1448	}
1449
1450	SQLITE3_CHECK_INITIALIZED(stmt_obj->db_obj, stmt_obj->initialised, SQLite3);
1451	SQLITE3_CHECK_INITIALIZED_STMT(stmt_obj->stmt, SQLite3Stmt);
1452
1453	ZVAL_COPY(&param.parameter, parameter);
1454
1455	if (!register_bound_parameter_to_sqlite(&param, stmt_obj)) {
1456		if (!Z_ISUNDEF(param.parameter)) {
1457			zval_ptr_dtor(&(param.parameter));
1458			ZVAL_UNDEF(&param.parameter);
1459		}
1460		RETURN_FALSE;
1461	}
1462	RETURN_TRUE;
1463}
1464/* }}} */
1465
1466/* {{{ proto SQLite3Result SQLite3Stmt::execute()
1467   Executes a prepared statement and returns a result set object. */
1468PHP_METHOD(sqlite3stmt, execute)
1469{
1470	php_sqlite3_stmt *stmt_obj;
1471	php_sqlite3_result *result;
1472	zval *object = getThis();
1473	int return_code = 0;
1474	struct php_sqlite3_bound_param *param;
1475
1476	stmt_obj = Z_SQLITE3_STMT_P(object);
1477
1478	if (zend_parse_parameters_none() == FAILURE) {
1479		return;
1480	}
1481
1482	SQLITE3_CHECK_INITIALIZED(stmt_obj->db_obj, stmt_obj->initialised, SQLite3);
1483
1484	if (stmt_obj->bound_params) {
1485		ZEND_HASH_FOREACH_PTR(stmt_obj->bound_params, param) {
1486			zval *parameter;
1487			/* parameter must be a reference? */
1488			if (Z_ISREF(param->parameter)) {
1489				parameter = Z_REFVAL(param->parameter);
1490			} else {
1491				parameter = &param->parameter;
1492			}
1493
1494			/* If the ZVAL is null then it should be bound as that */
1495			if (Z_TYPE_P(parameter) == IS_NULL) {
1496				sqlite3_bind_null(stmt_obj->stmt, param->param_number);
1497				continue;
1498			}
1499
1500			switch (param->type) {
1501				case SQLITE_INTEGER:
1502					convert_to_long(parameter);
1503#if ZEND_LONG_MAX > 2147483647
1504					sqlite3_bind_int64(stmt_obj->stmt, param->param_number, Z_LVAL_P(parameter));
1505#else
1506					sqlite3_bind_int(stmt_obj->stmt, param->param_number, Z_LVAL_P(parameter));
1507#endif
1508					break;
1509
1510				case SQLITE_FLOAT:
1511					/* convert_to_double(parameter);*/
1512					sqlite3_bind_double(stmt_obj->stmt, param->param_number, Z_DVAL_P(parameter));
1513					break;
1514
1515				case SQLITE_BLOB:
1516				{
1517					php_stream *stream = NULL;
1518					zend_string *buffer = NULL;
1519					if (Z_TYPE_P(parameter) == IS_RESOURCE) {
1520						php_stream_from_zval_no_verify(stream, parameter);
1521						if (stream == NULL) {
1522							php_sqlite3_error(stmt_obj->db_obj, "Unable to read stream for parameter %ld", param->param_number);
1523							RETURN_FALSE;
1524						}
1525						buffer = php_stream_copy_to_mem(stream, PHP_STREAM_COPY_ALL, 0);
1526					} else {
1527						buffer = zval_get_string(parameter);
1528					}
1529
1530					if (buffer) {
1531						sqlite3_bind_blob(stmt_obj->stmt, param->param_number, ZSTR_VAL(buffer), ZSTR_LEN(buffer), SQLITE_TRANSIENT);
1532						zend_string_release(buffer);
1533					} else {
1534						sqlite3_bind_null(stmt_obj->stmt, param->param_number);
1535					}
1536					break;
1537				}
1538
1539				case SQLITE3_TEXT:
1540					convert_to_string(parameter);
1541					sqlite3_bind_text(stmt_obj->stmt, param->param_number, Z_STRVAL_P(parameter), Z_STRLEN_P(parameter), SQLITE_STATIC);
1542					break;
1543
1544				case SQLITE_NULL:
1545					sqlite3_bind_null(stmt_obj->stmt, param->param_number);
1546					break;
1547
1548				default:
1549					php_sqlite3_error(stmt_obj->db_obj, "Unknown parameter type: %pd for parameter %pd", param->type, param->param_number);
1550					RETURN_FALSE;
1551			}
1552		} ZEND_HASH_FOREACH_END();
1553	}
1554
1555	return_code = sqlite3_step(stmt_obj->stmt);
1556
1557	switch (return_code) {
1558		case SQLITE_ROW: /* Valid Row */
1559		case SQLITE_DONE: /* Valid but no results */
1560		{
1561			sqlite3_reset(stmt_obj->stmt);
1562			object_init_ex(return_value, php_sqlite3_result_entry);
1563			result = Z_SQLITE3_RESULT_P(return_value);
1564
1565			result->is_prepared_statement = 1;
1566			result->db_obj = stmt_obj->db_obj;
1567			result->stmt_obj = stmt_obj;
1568			ZVAL_COPY(&result->stmt_obj_zval, object);
1569
1570			break;
1571		}
1572		case SQLITE_ERROR:
1573			sqlite3_reset(stmt_obj->stmt);
1574
1575		default:
1576			php_sqlite3_error(stmt_obj->db_obj, "Unable to execute statement: %s", sqlite3_errmsg(sqlite3_db_handle(stmt_obj->stmt)));
1577			zval_dtor(return_value);
1578			RETURN_FALSE;
1579	}
1580
1581	return;
1582}
1583/* }}} */
1584
1585/* {{{ proto int SQLite3Stmt::__construct(SQLite3 dbobject, String Statement)
1586   __constructor for SQLite3Stmt. */
1587PHP_METHOD(sqlite3stmt, __construct)
1588{
1589	php_sqlite3_stmt *stmt_obj;
1590	php_sqlite3_db_object *db_obj;
1591	zval *object = getThis();
1592	zval *db_zval;
1593	zend_string *sql;
1594	int errcode;
1595	zend_error_handling error_handling;
1596	php_sqlite3_free_list *free_item;
1597
1598	stmt_obj = Z_SQLITE3_STMT_P(object);
1599
1600	if (zend_parse_parameters_throw(ZEND_NUM_ARGS(), "OS", &db_zval, php_sqlite3_sc_entry, &sql) == FAILURE) {
1601		return;
1602	}
1603
1604	db_obj = Z_SQLITE3_DB_P(db_zval);
1605
1606	zend_replace_error_handling(EH_THROW, NULL, &error_handling);
1607	SQLITE3_CHECK_INITIALIZED(db_obj, db_obj->initialised, SQLite3)
1608	zend_restore_error_handling(&error_handling);
1609
1610	if (!ZSTR_LEN(sql)) {
1611		RETURN_FALSE;
1612	}
1613
1614	stmt_obj->db_obj = db_obj;
1615	ZVAL_COPY(&stmt_obj->db_obj_zval, db_zval);
1616
1617	errcode = sqlite3_prepare_v2(db_obj->db, ZSTR_VAL(sql), ZSTR_LEN(sql), &(stmt_obj->stmt), NULL);
1618	if (errcode != SQLITE_OK) {
1619		php_sqlite3_error(db_obj, "Unable to prepare statement: %d, %s", errcode, sqlite3_errmsg(db_obj->db));
1620		zval_dtor(return_value);
1621		RETURN_FALSE;
1622	}
1623	stmt_obj->initialised = 1;
1624
1625	free_item = emalloc(sizeof(php_sqlite3_free_list));
1626	free_item->stmt_obj = stmt_obj;
1627	//??  free_item->stmt_obj_zval = getThis();
1628	ZVAL_COPY_VALUE(&free_item->stmt_obj_zval, object);
1629
1630	zend_llist_add_element(&(db_obj->free_list), &free_item);
1631}
1632/* }}} */
1633
1634/* {{{ proto int SQLite3Result::numColumns()
1635   Number of columns in the result set. */
1636PHP_METHOD(sqlite3result, numColumns)
1637{
1638	php_sqlite3_result *result_obj;
1639	zval *object = getThis();
1640	result_obj = Z_SQLITE3_RESULT_P(object);
1641
1642	SQLITE3_CHECK_INITIALIZED(result_obj->db_obj, result_obj->stmt_obj->initialised, SQLite3Result)
1643
1644	if (zend_parse_parameters_none() == FAILURE) {
1645		return;
1646	}
1647
1648	RETURN_LONG(sqlite3_column_count(result_obj->stmt_obj->stmt));
1649}
1650/* }}} */
1651
1652/* {{{ proto string SQLite3Result::columnName(int column)
1653   Returns the name of the nth column. */
1654PHP_METHOD(sqlite3result, columnName)
1655{
1656	php_sqlite3_result *result_obj;
1657	zval *object = getThis();
1658	zend_long column = 0;
1659	char *column_name;
1660	result_obj = Z_SQLITE3_RESULT_P(object);
1661
1662	SQLITE3_CHECK_INITIALIZED(result_obj->db_obj, result_obj->stmt_obj->initialised, SQLite3Result)
1663
1664	if (zend_parse_parameters(ZEND_NUM_ARGS(), "l", &column) == FAILURE) {
1665		return;
1666	}
1667	column_name = (char*) sqlite3_column_name(result_obj->stmt_obj->stmt, column);
1668
1669	if (column_name == NULL) {
1670		RETURN_FALSE;
1671	}
1672
1673	RETVAL_STRING(column_name);
1674}
1675/* }}} */
1676
1677/* {{{ proto int SQLite3Result::columnType(int column)
1678   Returns the type of the nth column. */
1679PHP_METHOD(sqlite3result, columnType)
1680{
1681	php_sqlite3_result *result_obj;
1682	zval *object = getThis();
1683	zend_long column = 0;
1684	result_obj = Z_SQLITE3_RESULT_P(object);
1685
1686	SQLITE3_CHECK_INITIALIZED(result_obj->db_obj, result_obj->stmt_obj->initialised, SQLite3Result)
1687
1688	if (zend_parse_parameters(ZEND_NUM_ARGS(), "l", &column) == FAILURE) {
1689		return;
1690	}
1691
1692	if (result_obj->complete) {
1693		RETURN_FALSE;
1694	}
1695
1696	RETURN_LONG(sqlite3_column_type(result_obj->stmt_obj->stmt, column));
1697}
1698/* }}} */
1699
1700/* {{{ proto array SQLite3Result::fetchArray([int mode])
1701   Fetch a result row as both an associative or numerically indexed array or both. */
1702PHP_METHOD(sqlite3result, fetchArray)
1703{
1704	php_sqlite3_result *result_obj;
1705	zval *object = getThis();
1706	int i, ret;
1707	zend_long mode = PHP_SQLITE3_BOTH;
1708	result_obj = Z_SQLITE3_RESULT_P(object);
1709
1710	SQLITE3_CHECK_INITIALIZED(result_obj->db_obj, result_obj->stmt_obj->initialised, SQLite3Result)
1711
1712	if (zend_parse_parameters(ZEND_NUM_ARGS(), "|l", &mode) == FAILURE) {
1713		return;
1714	}
1715
1716	ret = sqlite3_step(result_obj->stmt_obj->stmt);
1717	switch (ret) {
1718		case SQLITE_ROW:
1719			/* If there was no return value then just skip fetching */
1720			if (!USED_RET()) {
1721				return;
1722			}
1723
1724			array_init(return_value);
1725
1726			for (i = 0; i < sqlite3_data_count(result_obj->stmt_obj->stmt); i++) {
1727				zval data;
1728
1729				sqlite_value_to_zval(result_obj->stmt_obj->stmt, i, &data);
1730
1731				if (mode & PHP_SQLITE3_NUM) {
1732					add_index_zval(return_value, i, &data);
1733				}
1734
1735				if (mode & PHP_SQLITE3_ASSOC) {
1736					if (mode & PHP_SQLITE3_NUM) {
1737						if (Z_REFCOUNTED(data)) {
1738							Z_ADDREF(data);
1739						}
1740					}
1741					add_assoc_zval(return_value, (char*)sqlite3_column_name(result_obj->stmt_obj->stmt, i), &data);
1742				}
1743			}
1744			break;
1745
1746		case SQLITE_DONE:
1747			result_obj->complete = 1;
1748			RETURN_FALSE;
1749			break;
1750
1751		default:
1752			php_sqlite3_error(result_obj->db_obj, "Unable to execute statement: %s", sqlite3_errmsg(sqlite3_db_handle(result_obj->stmt_obj->stmt)));
1753	}
1754}
1755/* }}} */
1756
1757/* {{{ proto bool SQLite3Result::reset()
1758   Resets the result set back to the first row. */
1759PHP_METHOD(sqlite3result, reset)
1760{
1761	php_sqlite3_result *result_obj;
1762	zval *object = getThis();
1763	result_obj = Z_SQLITE3_RESULT_P(object);
1764
1765	SQLITE3_CHECK_INITIALIZED(result_obj->db_obj, result_obj->stmt_obj->initialised, SQLite3Result)
1766
1767	if (zend_parse_parameters_none() == FAILURE) {
1768		return;
1769	}
1770
1771	if (sqlite3_reset(result_obj->stmt_obj->stmt) != SQLITE_OK) {
1772		RETURN_FALSE;
1773	}
1774
1775	result_obj->complete = 0;
1776
1777	RETURN_TRUE;
1778}
1779/* }}} */
1780
1781/* {{{ proto bool SQLite3Result::finalize()
1782   Closes the result set. */
1783PHP_METHOD(sqlite3result, finalize)
1784{
1785	php_sqlite3_result *result_obj;
1786	zval *object = getThis();
1787	result_obj = Z_SQLITE3_RESULT_P(object);
1788
1789	SQLITE3_CHECK_INITIALIZED(result_obj->db_obj, result_obj->stmt_obj->initialised, SQLite3Result)
1790
1791	if (zend_parse_parameters_none() == FAILURE) {
1792		return;
1793	}
1794
1795	/* We need to finalize an internal statement */
1796	if (result_obj->is_prepared_statement == 0) {
1797		zend_llist_del_element(&(result_obj->db_obj->free_list), &result_obj->stmt_obj_zval,
1798			(int (*)(void *, void *)) php_sqlite3_compare_stmt_zval_free);
1799	} else {
1800		sqlite3_reset(result_obj->stmt_obj->stmt);
1801	}
1802
1803	RETURN_TRUE;
1804}
1805/* }}} */
1806
1807/* {{{ proto int SQLite3Result::__construct()
1808   __constructor for SQLite3Result. */
1809PHP_METHOD(sqlite3result, __construct)
1810{
1811	zend_throw_exception(zend_ce_exception, "SQLite3Result cannot be directly instantiated", 0);
1812}
1813/* }}} */
1814
1815/* {{{ arginfo */
1816ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite3_open, 0, 0, 1)
1817	ZEND_ARG_INFO(0, filename)
1818	ZEND_ARG_INFO(0, flags)
1819	ZEND_ARG_INFO(0, encryption_key)
1820ZEND_END_ARG_INFO()
1821
1822ZEND_BEGIN_ARG_INFO(arginfo_sqlite3_busytimeout, 0)
1823	ZEND_ARG_INFO(0, ms)
1824ZEND_END_ARG_INFO()
1825
1826#ifndef SQLITE_OMIT_LOAD_EXTENSION
1827ZEND_BEGIN_ARG_INFO(arginfo_sqlite3_loadextension, 0)
1828	ZEND_ARG_INFO(0, shared_library)
1829ZEND_END_ARG_INFO()
1830#endif
1831
1832ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite3_escapestring, 0, 0, 1)
1833	ZEND_ARG_INFO(0, value)
1834ZEND_END_ARG_INFO()
1835
1836ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite3_query, 0, 0, 1)
1837	ZEND_ARG_INFO(0, query)
1838ZEND_END_ARG_INFO()
1839
1840ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite3_querysingle, 0, 0, 1)
1841	ZEND_ARG_INFO(0, query)
1842	ZEND_ARG_INFO(0, entire_row)
1843ZEND_END_ARG_INFO()
1844
1845ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite3_createfunction, 0, 0, 2)
1846	ZEND_ARG_INFO(0, name)
1847	ZEND_ARG_INFO(0, callback)
1848	ZEND_ARG_INFO(0, argument_count)
1849ZEND_END_ARG_INFO()
1850
1851ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite3_createaggregate, 0, 0, 3)
1852	ZEND_ARG_INFO(0, name)
1853	ZEND_ARG_INFO(0, step_callback)
1854	ZEND_ARG_INFO(0, final_callback)
1855	ZEND_ARG_INFO(0, argument_count)
1856ZEND_END_ARG_INFO()
1857
1858ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite3_createcollation, 0, 0, 2)
1859	ZEND_ARG_INFO(0, name)
1860	ZEND_ARG_INFO(0, callback)
1861ZEND_END_ARG_INFO()
1862
1863ZEND_BEGIN_ARG_INFO_EX(argingo_sqlite3_openblob, 0, 0, 3)
1864	ZEND_ARG_INFO(0, table)
1865	ZEND_ARG_INFO(0, column)
1866	ZEND_ARG_INFO(0, rowid)
1867	ZEND_ARG_INFO(0, dbname)
1868ZEND_END_ARG_INFO()
1869
1870ZEND_BEGIN_ARG_INFO_EX(argingo_sqlite3_enableexceptions, 0, 0, 1)
1871	ZEND_ARG_INFO(0, enableExceptions)
1872ZEND_END_ARG_INFO()
1873
1874ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite3stmt_bindparam, 0, 0, 2)
1875	ZEND_ARG_INFO(0, param_number)
1876	ZEND_ARG_INFO(1, param)
1877	ZEND_ARG_INFO(0, type)
1878ZEND_END_ARG_INFO()
1879
1880ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite3stmt_bindvalue, 0, 0, 2)
1881	ZEND_ARG_INFO(0, param_number)
1882	ZEND_ARG_INFO(0, param)
1883	ZEND_ARG_INFO(0, type)
1884ZEND_END_ARG_INFO()
1885
1886ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite3stmt_construct, 0, 0, 1)
1887	ZEND_ARG_INFO(0, sqlite3)
1888ZEND_END_ARG_INFO()
1889
1890ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite3result_columnname, 0, 0, 1)
1891	ZEND_ARG_INFO(0, column_number)
1892ZEND_END_ARG_INFO()
1893
1894ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite3result_columntype, 0, 0, 1)
1895	ZEND_ARG_INFO(0, column_number)
1896ZEND_END_ARG_INFO()
1897
1898ZEND_BEGIN_ARG_INFO_EX(arginfo_sqlite3result_fetcharray, 0, 0, 0)
1899	ZEND_ARG_INFO(0, mode)
1900ZEND_END_ARG_INFO()
1901
1902ZEND_BEGIN_ARG_INFO(arginfo_sqlite3_void, 0)
1903ZEND_END_ARG_INFO()
1904/* }}} */
1905
1906/* {{{ php_sqlite3_class_methods */
1907static zend_function_entry php_sqlite3_class_methods[] = {
1908	PHP_ME(sqlite3,		open,				arginfo_sqlite3_open, ZEND_ACC_PUBLIC)
1909	PHP_ME(sqlite3,		close,				arginfo_sqlite3_void, ZEND_ACC_PUBLIC)
1910	PHP_ME(sqlite3,		exec,				arginfo_sqlite3_query, ZEND_ACC_PUBLIC)
1911	PHP_ME(sqlite3,		version,			arginfo_sqlite3_void, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC)
1912	PHP_ME(sqlite3,		lastInsertRowID,	arginfo_sqlite3_void, ZEND_ACC_PUBLIC)
1913	PHP_ME(sqlite3,		lastErrorCode,		arginfo_sqlite3_void, ZEND_ACC_PUBLIC)
1914	PHP_ME(sqlite3,		lastErrorMsg,		arginfo_sqlite3_void, ZEND_ACC_PUBLIC)
1915	PHP_ME(sqlite3,		busyTimeout,		arginfo_sqlite3_busytimeout, ZEND_ACC_PUBLIC)
1916#ifndef SQLITE_OMIT_LOAD_EXTENSION
1917	PHP_ME(sqlite3,		loadExtension,		arginfo_sqlite3_loadextension, ZEND_ACC_PUBLIC)
1918#endif
1919	PHP_ME(sqlite3,		changes,			arginfo_sqlite3_void, ZEND_ACC_PUBLIC)
1920	PHP_ME(sqlite3,		escapeString,		arginfo_sqlite3_escapestring, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC)
1921	PHP_ME(sqlite3,		prepare,			arginfo_sqlite3_query, ZEND_ACC_PUBLIC)
1922	PHP_ME(sqlite3,		query,				arginfo_sqlite3_query, ZEND_ACC_PUBLIC)
1923	PHP_ME(sqlite3,		querySingle,		arginfo_sqlite3_querysingle, ZEND_ACC_PUBLIC)
1924	PHP_ME(sqlite3,		createFunction,		arginfo_sqlite3_createfunction, ZEND_ACC_PUBLIC)
1925	PHP_ME(sqlite3,		createAggregate,	arginfo_sqlite3_createaggregate, ZEND_ACC_PUBLIC)
1926	PHP_ME(sqlite3,		createCollation,	arginfo_sqlite3_createcollation, ZEND_ACC_PUBLIC)
1927	PHP_ME(sqlite3,		openBlob,			argingo_sqlite3_openblob, ZEND_ACC_PUBLIC)
1928	PHP_ME(sqlite3,		enableExceptions,	argingo_sqlite3_enableexceptions, ZEND_ACC_PUBLIC)
1929	/* Aliases */
1930	PHP_MALIAS(sqlite3,	__construct, open, arginfo_sqlite3_open, ZEND_ACC_PUBLIC|ZEND_ACC_CTOR)
1931	PHP_FE_END
1932};
1933/* }}} */
1934
1935/* {{{ php_sqlite3_stmt_class_methods */
1936static zend_function_entry php_sqlite3_stmt_class_methods[] = {
1937	PHP_ME(sqlite3stmt, paramCount,	arginfo_sqlite3_void, ZEND_ACC_PUBLIC)
1938	PHP_ME(sqlite3stmt, close,		arginfo_sqlite3_void, ZEND_ACC_PUBLIC)
1939	PHP_ME(sqlite3stmt, reset,		arginfo_sqlite3_void, ZEND_ACC_PUBLIC)
1940	PHP_ME(sqlite3stmt, clear,		arginfo_sqlite3_void, ZEND_ACC_PUBLIC)
1941	PHP_ME(sqlite3stmt, execute,	arginfo_sqlite3_void, ZEND_ACC_PUBLIC)
1942	PHP_ME(sqlite3stmt, bindParam,	arginfo_sqlite3stmt_bindparam, ZEND_ACC_PUBLIC)
1943	PHP_ME(sqlite3stmt, bindValue,	arginfo_sqlite3stmt_bindvalue, ZEND_ACC_PUBLIC)
1944	PHP_ME(sqlite3stmt, readOnly,	arginfo_sqlite3_void, ZEND_ACC_PUBLIC)
1945	PHP_ME(sqlite3stmt, __construct, arginfo_sqlite3stmt_construct, ZEND_ACC_PRIVATE|ZEND_ACC_CTOR)
1946	PHP_FE_END
1947};
1948/* }}} */
1949
1950/* {{{ php_sqlite3_result_class_methods */
1951static zend_function_entry php_sqlite3_result_class_methods[] = {
1952	PHP_ME(sqlite3result, numColumns,		arginfo_sqlite3_void, ZEND_ACC_PUBLIC)
1953	PHP_ME(sqlite3result, columnName,		arginfo_sqlite3result_columnname, ZEND_ACC_PUBLIC)
1954	PHP_ME(sqlite3result, columnType,		arginfo_sqlite3result_columntype, ZEND_ACC_PUBLIC)
1955	PHP_ME(sqlite3result, fetchArray,		arginfo_sqlite3result_fetcharray, ZEND_ACC_PUBLIC)
1956	PHP_ME(sqlite3result, reset,			arginfo_sqlite3_void, ZEND_ACC_PUBLIC)
1957	PHP_ME(sqlite3result, finalize,			arginfo_sqlite3_void, ZEND_ACC_PUBLIC)
1958	PHP_ME(sqlite3result, __construct, 		arginfo_sqlite3_void, ZEND_ACC_PRIVATE|ZEND_ACC_CTOR)
1959	PHP_FE_END
1960};
1961/* }}} */
1962
1963/* {{{ Authorization Callback
1964*/
1965static int php_sqlite3_authorizer(void *autharg, int access_type, const char *arg3, const char *arg4, const char *arg5, const char *arg6)
1966{
1967	switch (access_type) {
1968		case SQLITE_ATTACH:
1969		{
1970			if (memcmp(arg3, ":memory:", sizeof(":memory:")) && *arg3) {
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 && 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) + zend_object_properties_size(class_type));
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) + zend_object_properties_size(class_type));
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) + zend_object_properties_size(class_type));
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