4 ** The author disclaims copyright to this source code. In place of
5 ** a legal notice, here is a blessing:
7 ** May you do good and not evil.
8 ** May you find forgiveness for yourself and forgive others.
9 ** May you share freely, never taking more than you give.
11 *************************************************************************
12 ** Main file for the SQLite library. The routines in this file
13 ** implement the programmer interface to the library. Routines in
14 ** other files are for internal use by SQLite and should not be
15 ** accessed by users of the library.
20 #include "sqliteInt.h"
24 ** Execute SQL code. Return one of the SQLITE_ success/failure
25 ** codes. Also write an error message into memory obtained from
26 ** malloc() and make *pzErrMsg point to that message.
28 ** If the SQL is a query, then for each row in the query result
29 ** the xCallback() function is called. pArg becomes the first
30 ** argument to xCallback(). If xCallback=NULL then no callback
31 ** is invoked, even for queries.
34 sqlite3 *db, /* The database on which the SQL executes */
35 const char *zSql, /* The SQL to be executed */
36 sqlite3_callback xCallback, /* Invoke this callback routine */
37 void *pArg, /* First argument to xCallback() */
38 char **pzErrMsg /* Write error messages here */
41 const char *zLeftover;
42 sqlite3_stmt *pStmt = 0;
48 if( zSql==0 ) return SQLITE_OK;
50 sqlite3_mutex_enter(db->mutex);
51 while( (rc==SQLITE_OK || (rc==SQLITE_SCHEMA && (++nRetry)<2)) && zSql[0] ){
56 rc = sqlite3_prepare(db, zSql, -1, &pStmt, &zLeftover);
57 assert( rc==SQLITE_OK || pStmt==0 );
62 /* this happens for a comment or white-space */
69 nCol = sqlite3_column_count(pStmt);
70 azCols = sqlite3DbMallocZero(db, 2*nCol*sizeof(const char *) + 1);
77 rc = sqlite3_step(pStmt);
79 /* Invoke the callback function if required */
80 if( xCallback && (SQLITE_ROW==rc ||
81 (SQLITE_DONE==rc && !nCallback && db->flags&SQLITE_NullCallback)) ){
83 for(i=0; i<nCol; i++){
84 azCols[i] = (char *)sqlite3_column_name(pStmt, i);
89 azVals = &azCols[nCol];
90 for(i=0; i<nCol; i++){
91 azVals[i] = (char *)sqlite3_column_text(pStmt, i);
94 if( xCallback(pArg, nCol, azVals, azCols) ){
100 if( rc!=SQLITE_ROW ){
101 rc = sqlite3_finalize(pStmt);
103 if( rc!=SQLITE_SCHEMA ){
106 while( isspace((unsigned char)zSql[0]) ) zSql++;
112 sqlite3_free(azCols);
117 if( pStmt ) sqlite3_finalize(pStmt);
118 if( azCols ) sqlite3_free(azCols);
120 rc = sqlite3ApiExit(db, rc);
121 if( rc!=SQLITE_OK && rc==sqlite3_errcode(db) && pzErrMsg ){
122 int nErrMsg = 1 + strlen(sqlite3_errmsg(db));
123 *pzErrMsg = sqlite3_malloc(nErrMsg);
125 memcpy(*pzErrMsg, sqlite3_errmsg(db), nErrMsg);
127 }else if( pzErrMsg ){
131 assert( (rc&db->errMask)==rc );
132 sqlite3_mutex_leave(db->mutex);