Annotation of sql/sqlite/parser3sqlite.C, revision 1.10

1.1       misha       1: /** @file
                      2:        Parser SQLite driver.
                      3: 
                      4:        (c) Dmitry "Creator" Bobrik, 2004
                      5: */
1.10    ! misha       6: //static const char *RCSId="$Id: parser3sqlite.C,v 1.9 2008-07-03 07:17:25 misha Exp $"; 
1.1       misha       7: 
                      8: #include "config_includes.h"
                      9: 
                     10: #include "pa_sql_driver.h"
                     11: //#include "windows.h"  // for messagebox
                     12: 
                     13: #define NO_CLIENT_LONG_LONG
                     14: #include "sqlite3.h"
                     15: #include "ltdl.h"
                     16: 
1.9       misha      17: #define MAX_COLS   500
1.1       misha      18: #define MAX_STRING 0x400
                     19: #define MAX_NUMBER 20
                     20: 
1.4       misha      21: #define SQLITE_DEFAULT_CHARSET "UTF-8"
                     22: 
1.1       misha      23: #if _MSC_VER
                     24: #      define snprintf _snprintf
                     25: #      define strcasecmp _stricmp
                     26: #endif
                     27: 
                     28: static char *lsplit(char *string, char delim) {
1.6       misha      29:        if(string) {
1.1       misha      30:                char *v=strchr(string, delim);
1.6       misha      31:                if(v) {
1.1       misha      32:                        *v=0;
                     33:                        return v+1;
                     34:                }
1.6       misha      35:        }
                     36:        return 0;
1.1       misha      37: }
                     38: 
                     39: static char *lsplit(char **string_ref, char delim) {
1.6       misha      40:        char *result=*string_ref;
1.1       misha      41:        char *next=lsplit(*string_ref, delim);
1.6       misha      42:        *string_ref=next;
                     43:        return result;
1.1       misha      44: }
                     45: 
                     46: static void toupper_str(char *out, const char *in, size_t size) {
                     47:        while(size--)
                     48:                *out++=(char)toupper(*in++);
                     49: }
                     50: 
                     51: struct Connection {
                     52:        SQL_Driver_services* services;
                     53: 
                     54:        sqlite3* handle;
1.6       misha      55:        const char* client_charset;
                     56:        bool multi_statements;
1.1       misha      57:        bool autocommit;
                     58: };
                     59: 
                     60: 
                     61: 
                     62: /**
                     63:        SQLite server driver
                     64: */
                     65: class SQLite_Driver : public SQL_Driver {
                     66: public:
                     67: 
                     68:        SQLite_Driver() : SQL_Driver() {
                     69:        }
                     70: 
                     71:        /// get api version
                     72:        int api_version() { return SQL_DRIVER_API_VERSION; }
1.4       misha      73: 
1.1       misha      74:        /// initialize driver by loading sql dynamic link library
                     75:        const char *initialize(char *dlopen_file_spec) {
                     76:                return dlopen_file_spec?
                     77:                        dlink(dlopen_file_spec):"client library column is empty";
                     78:        }
1.4       misha      79: 
1.1       misha      80:        /**     connect
                     81:                @param url
1.8       misha      82:                        format: @b db-file|:memory:|temporary:?
                     83:                        autocommit=1&                   // =0 disable autocommit. in this case 1 connect == 1 transaction.
                     84:                                                                        //      or you can use begin/commit|rollback explicitly
                     85:                        multi_statements=0&             // =1 allow many statements in 1 query
                     86:                        ClientCharset=UTF-8             // will transcode to/from specified charset instead of UTF-8 (default for sqlite)
1.1       misha      87:        */
                     88:        void connect(
1.6       misha      89:                                char *url, 
                     90:                                SQL_Driver_services& services, 
                     91:                                void **connection_ref ///< output: Connection*
1.4       misha      92:                ){
1.1       misha      93: 
1.4       misha      94:                Connection& connection=*(Connection *)services.malloc(sizeof(Connection));
1.6       misha      95:                *connection_ref=&connection;
1.4       misha      96:                connection.services=&services;
1.6       misha      97: 
                     98:                connection.client_charset=SQLITE_DEFAULT_CHARSET;       
                     99:                connection.multi_statements=false;
1.4       misha     100:                connection.autocommit=true;
1.1       misha     101: 
1.6       misha     102:                char* db_path=0;
                    103:                char* db=url;
                    104:                char* options=lsplit(db, '?');
                    105: 
1.8       misha     106:                if(strcmp(db, ":memory:")==0){ // in-memory temporary DB
1.6       misha     107:                        db_path=db;
1.8       misha     108:                } else if(strcmp(db, ":temporary:")==0){ // on-disk temporary DB
1.6       misha     109:                        // do nothing: empty path mean temporary table on disk
1.8       misha     110:                } else {
                    111:                        char* document_root=(char*)services.request_document_root();
                    112:                        if(!document_root) // path to DB-file which was specified by user is path from document_root as anywhere in parser
                    113:                                services._throw("document_root is empty");
                    114: 
                    115:                        db_path=(char*)services.malloc_atomic(strlen(document_root)+1+strlen(db)+1);
1.9       misha     116:                        strcpy(db_path, document_root);
                    117:                        strcat(db_path, "/");
                    118:                        strcat(db_path, db);
1.5       misha     119:                }
1.4       misha     120: 
1.6       misha     121:                //services._throw(db_path);
                    122: 
                    123:                while(options){
                    124:                        if(char* key=lsplit(&options, '&')){
1.4       misha     125:                                if(*key) {
1.6       misha     126:                                        if(char* value=lsplit(key, '=')){
1.8       misha     127:                                                if(strcasecmp(key, "multi_statements")==0){
1.6       misha     128:                                                        if(atoi(value)!=0)
                    129:                                                                connection.multi_statements=true;
                    130:                                                } else if(strcasecmp(key, "autocommit")==0){
1.4       misha     131:                                                        if(atoi(value)==0)
                    132:                                                                connection.autocommit=false;
                    133:                                                        continue;
1.8       misha     134:                                                } else if(strcmp(key, "ClientCharset")==0){
1.6       misha     135:                                                        toupper_str(value, value, strlen(value));
                    136:                                                        connection.client_charset=value;
                    137:                                                        continue;
1.4       misha     138:                                                } else
                    139:                                                        services._throw("unknown connect option" /*key*/);
                    140:                                        } else 
                    141:                                                services._throw("connect option without =value" /*key*/);
                    142:                                }
                    143:                        }
                    144:                }
                    145: 
                    146:                // transcode database_name from $request:charset to UTF-8
1.6       misha     147:                if(db_path && _transcode_required(connection, SQLITE_DEFAULT_CHARSET)){
                    148:                        size_t length=strlen(db_path);
                    149:                        services.transcode((const char*)db_path, length,
                    150:                                (const char*&)db_path, length,
                    151:                                services.request_charset(),
                    152:                                SQLITE_DEFAULT_CHARSET);
                    153: 
                    154:                }
1.4       misha     155:                
1.1       misha     156: 
1.6       misha     157:                int rc=sqlite3_open(db_path, &connection.handle);
1.5       misha     158:                if(rc!=SQLITE_OK){
1.6       misha     159:                        const char* error_msg=sqlite3_errmsg(connection.handle);
1.1       misha     160:                        sqlite3_close(connection.handle);
1.6       misha     161:                        _throw(connection, error_msg);
1.1       misha     162:                }
1.6       misha     163:                
                    164:                _begin_transaction(connection);
1.1       misha     165:        }
                    166: 
1.6       misha     167:        void disconnect(void *aconnection){
1.1       misha     168:                Connection& connection=*static_cast<Connection*>(aconnection);
                    169:                sqlite3_close(connection.handle);
                    170:                connection.handle=0;
1.4       misha     171:        }
1.1       misha     172: 
1.6       misha     173:        void commit(void *aconnection){
1.1       misha     174:                Connection& connection=*static_cast<Connection*>(aconnection);
                    175:                if(!connection.autocommit)
1.6       misha     176:                        _execute_cmd(connection, "COMMIT");
                    177: 
                    178:                _begin_transaction(connection);
1.1       misha     179:        }
1.4       misha     180: 
1.6       misha     181:        void rollback(void *aconnection){
1.1       misha     182:                Connection& connection=*static_cast<Connection*>(aconnection);
                    183:                if(!connection.autocommit)
1.6       misha     184:                        _execute_cmd(connection, "ROLLBACK");
                    185: 
                    186:                _begin_transaction(connection);
1.1       misha     187:        }
                    188: 
1.6       misha     189:        bool ping(void *aconnection){
                    190:                return true; // not needed
1.1       misha     191:        }
                    192: 
1.6       misha     193:        const char* quote(void *aconnection, const char *from, unsigned int length){
1.1       misha     194:                Connection& connection=*static_cast<Connection*>(aconnection);
                    195:                /*
                    196:                        You must allocate the to buffer to be at least length*2+1 bytes long. 
1.4       misha     197:                        In the worse case, each character may need to be encoded as using two bytes, 
                    198:                        and you need room for the terminating null byte.
1.1       misha     199:                */
                    200:                char *result=(char*)connection.services->malloc_atomic(length*2+1);
                    201:                char *to=result;
                    202:                while(length--) {
1.10    ! misha     203:                        if(*from=='\'') // ' -> ''
1.1       misha     204:                                *to++='\'';
                    205:                        *to++=*from++;
                    206:                }
                    207:                *to=0;
                    208:                return result;
                    209:        }
1.4       misha     210: 
1.1       misha     211:        void query(void *aconnection, 
1.6       misha     212:                        const char *astatement, 
                    213:                        size_t placeholders_count, Placeholder* placeholders, 
                    214:                        unsigned long offset, unsigned long limit,
                    215:                        SQL_Driver_query_event_handlers& handlers
                    216:                ){
1.1       misha     217: 
                    218:                Connection& connection=*static_cast<Connection*>(aconnection);
                    219:                SQL_Driver_services& services=*connection.services;
                    220: 
                    221:                if(placeholders_count>0)
1.5       misha     222:                        services._throw("bind variables not supported yet");
1.9       misha     223:                
                    224:                const char* request_charset=services.request_charset();
                    225:                const char* client_charset=connection.client_charset;
1.6       misha     226:                bool transcode_needed=_transcode_required(connection);
                    227: 
                    228:                // transcode query from $request:charset to ?ClientCharset
                    229:                if(transcode_needed){
                    230:                        size_t length=strlen(astatement);
                    231:                        services.transcode(astatement, length,
                    232:                                astatement, length,
1.9       misha     233:                                request_charset,
                    234:                                client_charset);
1.4       misha     235:                }
                    236:                
1.1       misha     237:                const char *statement;
1.6       misha     238:                if(offset || limit!=SQL_NO_LIMIT){
1.1       misha     239:                        size_t statement_size=strlen(astatement);
                    240:                        char *statement_limited=(char *)services.malloc_atomic(
1.6       misha     241:                                statement_size+MAX_NUMBER*2+8/* LIMIT #,#*/+1);
1.1       misha     242:                        char *cur=statement_limited;
1.6       misha     243:                        memcpy(cur, astatement, statement_size);
                    244:                        cur+=statement_size;
                    245:                        cur+=sprintf(cur, " LIMIT ");
1.1       misha     246:                        if(offset)
                    247:                                cur+=snprintf(cur, MAX_NUMBER+1, "%u,", offset);
1.6       misha     248:                        if(limit!=SQL_NO_LIMIT)
1.1       misha     249:                                cur+=snprintf(cur, MAX_NUMBER, "%u", limit);
                    250:                        statement=statement_limited;
                    251:                } else
                    252:                        statement=astatement;
                    253: 
                    254: 
                    255:                const char *pzTail;
1.6       misha     256:                int next_statement_length=0;
1.1       misha     257:                sqlite3_stmt *SQL;
                    258:                int rc;
                    259:                SQL_Error sql_error;
1.5       misha     260:                bool failed=false;
1.1       misha     261: 
                    262:                do{ // cycling through SQL commands
1.6       misha     263:                        rc=sqlite3_prepare(connection.handle, statement, -1, &SQL, &pzTail);
                    264:                        next_statement_length=strlen(pzTail);
1.4       misha     265:                        if(rc!=SQLITE_OK){
1.8       misha     266:                                //sqlite3_free((char*)pzTail);
1.4       misha     267:                                _throw(connection, sqlite3_errmsg(connection.handle));
1.6       misha     268:                        }
                    269:                        if(!connection.multi_statements && next_statement_length>0){ // multi statements was not allowed but pzTail point to not empty one
1.8       misha     270:                                //sqlite3_free((char*)pzTail);
                    271:                                _throw(connection, "multi statements are not allowed until opption ?multi_statements=1 in connect string is specified.");
1.1       misha     272:                        }
                    273:                        
1.6       misha     274:                        #define CHECK(afailed) if(afailed){ failed=true; goto cleanup; }
1.1       misha     275: 
1.6       misha     276:                        int column_count=sqlite3_column_count(SQL);
1.1       misha     277: 
1.6       misha     278:                        if(!column_count){ // empty result: insert|delete|update|...
                    279:                                rc=sqlite3_step(SQL);
1.1       misha     280:                        } else {
1.9       misha     281:                                if(column_count>MAX_COLS)
                    282:                                        column_count=MAX_COLS;
                    283: 
                    284:                                int column_types[MAX_COLS];
                    285:                                bool transcode_column[MAX_COLS];
                    286: 
1.6       misha     287:                                for(int i=0; i<column_count; i++){
                    288:                                        const char *column_name=sqlite3_column_name(SQL, i);
                    289:                                        size_t length=strlen(column_name);
1.1       misha     290: 
                    291:                                        char* strm=(char*)services.malloc_atomic(length+1);
                    292:                                        memcpy(strm, column_name, length+1);
1.6       misha     293:                                        const char* str=strm;
                    294:                                        // transcode column name from ?ClientCharset to $request:charset 
                    295:                                        if(transcode_needed){
1.4       misha     296:                                                services.transcode(str, length,
                    297:                                                        str, length,
1.9       misha     298:                                                        client_charset,
                    299:                                                        request_charset);
1.4       misha     300:                                        }
                    301:                                                        
1.6       misha     302:                                        CHECK(handlers.add_column(sql_error, (const char*)str, length));
1.1       misha     303:                                }
                    304:                                CHECK(handlers.before_rows(sql_error));
                    305: 
1.5       misha     306:                                const char *str;
1.6       misha     307:                                size_t length=0;
1.9       misha     308:                                bool first_row=true;
1.1       misha     309: 
                    310:                                do{
1.6       misha     311:                                        rc=sqlite3_step(SQL);
                    312:                                        if(rc==SQLITE_ROW){ // new line!!
1.1       misha     313: 
                    314:                                                CHECK(handlers.add_row(sql_error));
                    315: 
1.6       misha     316:                                                for(int i=0; i<column_count; i++){
1.9       misha     317:                                                        if(first_row){
                    318:                                                                column_types[i]=sqlite3_column_type(SQL, i);
                    319:                                                                switch(column_types[i]){
                    320:                                                                        case SQLITE_INTEGER:
                    321:                                                                        case SQLITE_FLOAT:
                    322:                                                                        case SQLITE_NULL:
                    323:                                                                                transcode_column[i]=false;
                    324:                                                                                break;
                    325:                                                                        default:
                    326:                                                                                transcode_column[i]=transcode_needed;
                    327:                                                                                break;
                    328:                                                                }
                    329:                                                        }
                    330: 
1.6       misha     331:                                                        // SQLite allow to get value of any type using sqlite3_column_text function
1.9       misha     332:                                                        switch(column_types[i]){
1.2       misha     333:                                                                case SQLITE_NULL:
1.6       misha     334:                                                                        length=0;
1.4       misha     335:                                                                        str=NULL;
1.2       misha     336:                                                                        break;
1.6       misha     337:                                                                case SQLITE_BLOB:
                    338:                                                                        str=(const char*)sqlite3_column_blob(SQL, i);
                    339:                                                                        length=(size_t)sqlite3_column_bytes(SQL, i);
                    340:                                                                        break;
1.9       misha     341:                                                                default: // anything else?
1.5       misha     342:                                                                        str=(const char*)sqlite3_column_text(SQL, i);
1.6       misha     343:                                                                        length=(size_t)sqlite3_column_bytes(SQL, i);
1.1       misha     344:                                                                        break;
                    345:                                                        }
                    346: 
1.4       misha     347:                                                        if(length){
                    348:                                                                char* strm=(char*)services.malloc_atomic(length+1);
                    349:                                                                memcpy(strm, str, length+1);
1.5       misha     350:                                                                str=strm;
1.4       misha     351: 
1.9       misha     352:                                                                if(transcode_column[i]){
                    353:                                                                        // transcode cell value from ?ClientCharset to $request:charset
1.4       misha     354:                                                                        services.transcode(str, length,
                    355:                                                                                str, length,
1.9       misha     356:                                                                                client_charset,
                    357:                                                                                request_charset);
1.4       misha     358:                                                                }
                    359:                                                        } else
1.6       misha     360:                                                                str=0;
1.4       misha     361:                                                        
                    362:                                                        CHECK(handlers.add_row_cell(sql_error, str, length));
1.1       misha     363: 
                    364:                                                }
1.9       misha     365:                                                first_row=false;
1.1       misha     366:                                        }
1.6       misha     367:                                } while(rc==SQLITE_BUSY || rc==SQLITE_ROW);
1.1       misha     368: 
1.6       misha     369:                        }
1.1       misha     370: 
1.6       misha     371:                        if(rc==SQLITE_ERROR || rc==SQLITE_MISUSE){
1.4       misha     372:                                _throw(connection, sqlite3_errmsg(connection.handle));
1.1       misha     373:                        }
                    374: 
                    375:        cleanup:
                    376:                        sqlite3_finalize(SQL);
1.6       misha     377:                        statement=pzTail;
                    378:                } while (next_statement_length>0);
1.1       misha     379: 
                    380:                if(failed)
1.5       misha     381:                        services._throw(sql_error);
1.1       misha     382:        }
                    383: 
1.4       misha     384: private:
1.6       misha     385:        void _begin_transaction(Connection& connection) {
                    386:                if(!connection.autocommit){
                    387:                        _execute_cmd(connection, "BEGIN");
                    388:                }
                    389:        }
                    390: 
                    391:        void _execute_cmd(Connection& connection, const char* statement){
                    392:                char* zErr;
                    393:                int rc=sqlite3_exec(connection.handle, statement, 0, 0, &zErr);
                    394:                if(rc!=SQLITE_OK){
                    395:                        size_t length=strlen(zErr);
                    396:                        char* err_msg=(char *)connection.services->malloc_atomic(length+1);
                    397:                        memcpy(err_msg, zErr, length);
                    398: 
                    399:                        sqlite3_free(zErr);
                    400:                        _throw(connection, err_msg);
                    401:                }
                    402: 
                    403:        }
                    404: 
                    405:        void _throw(Connection& connection, const char* aerr_msg){
                    406:                size_t length=strlen(aerr_msg);
                    407:                if(length && _transcode_required(connection)){
                    408:                        // transcode server error message from ?ClientCharset to $request:charset 
                    409:                        connection.services->transcode(aerr_msg, length,
                    410:                                aerr_msg, length,
                    411:                                connection.client_charset,
                    412:                                connection.services->request_charset());
                    413:                }
                    414:                connection.services->_throw(aerr_msg);
                    415:        }
                    416: 
                    417:        bool _transcode_required(Connection& connection, const char* charset=0){
                    418:                return (strcmp(charset?charset:connection.client_charset, connection.services->request_charset())!=0);
                    419:        }
                    420: 
1.4       misha     421: 
1.1       misha     422: private: // sqlite client library funcs
                    423: 
                    424:        typedef int (*t_sqlite3_open)(const char *filename, sqlite3 **ppDb); t_sqlite3_open sqlite3_open;
                    425: 
                    426:        typedef int (*t_sqlite3_close)(sqlite3 *); t_sqlite3_close sqlite3_close;
                    427: 
                    428:        typedef int (*t_sqlite3_exec)(sqlite3*, const char *sql, sqlite3_callback, void *, char **errmsg); t_sqlite3_exec sqlite3_exec;
                    429: 
                    430:        typedef void (*t_sqlite3_free)(char *z); t_sqlite3_free sqlite3_free;
                    431: 
                    432:        typedef const char *(* t_sqlite3_errmsg)(sqlite3*); t_sqlite3_errmsg sqlite3_errmsg;
                    433: 
                    434:        typedef int (* t_sqlite3_prepare)(sqlite3 *db, const char *zSql, int nBytes, sqlite3_stmt **ppStmt, const char **pzTail); t_sqlite3_prepare sqlite3_prepare;
                    435: 
                    436:        typedef int (* t_sqlite3_column_count)(sqlite3_stmt *pStmt); t_sqlite3_column_count sqlite3_column_count;
                    437: 
                    438:        typedef int (* t_sqlite3_finalize)(sqlite3_stmt *pStmt); t_sqlite3_finalize sqlite3_finalize;
                    439: 
                    440:        typedef const char *(* t_sqlite3_column_name)(sqlite3_stmt*,int); t_sqlite3_column_name sqlite3_column_name;
                    441: 
                    442:        typedef int (* t_sqlite3_step)(sqlite3_stmt*); t_sqlite3_step sqlite3_step;
                    443: 
                    444:        typedef int (* t_sqlite3_column_type)(sqlite3_stmt*, int iCol); t_sqlite3_column_type sqlite3_column_type;
                    445: 
                    446:        typedef const unsigned char *(* t_sqlite3_column_text)(sqlite3_stmt*, int iCol); t_sqlite3_column_text sqlite3_column_text;
                    447: 
1.6       misha     448:        typedef const unsigned char *(* t_sqlite3_column_blob)(sqlite3_stmt*, int iCol); t_sqlite3_column_blob sqlite3_column_blob;
                    449: 
                    450:        typedef int (* t_sqlite3_column_bytes)(sqlite3_stmt*, int iCol); t_sqlite3_column_bytes sqlite3_column_bytes;
                    451: 
1.5       misha     452: 
1.1       misha     453: private: // sqlite client library funcs linking
                    454: 
                    455:        const char *dlink(const char *dlopen_file_spec) {
                    456:                if(lt_dlinit())
                    457:                        return lt_dlerror();
                    458:         lt_dlhandle handle=lt_dlopen(dlopen_file_spec);
                    459:         if (!handle) {
                    460:             if(const char* result=lt_dlerror())
                    461:                return result;
                    462: 
                    463:                        return "can not open the dynamic link module";
                    464:                }
                    465: 
                    466:                #define DSLINK(name, action) \
                    467:                        name=(t_##name)lt_dlsym(handle, #name); \
                    468:                                if(!name) \
                    469:                                        action;
                    470: 
                    471:                #define DLINK(name) DSLINK(name, return "function " #name " was not found")
                    472:                #define SLINK(name) DSLINK(name, name=subst_##name)
                    473:                
                    474:                DLINK(sqlite3_open);
                    475:                DLINK(sqlite3_close);
                    476:                DLINK(sqlite3_exec);
                    477:                DLINK(sqlite3_free);
                    478:                DLINK(sqlite3_errmsg);
                    479:                DLINK(sqlite3_prepare);
                    480:                DLINK(sqlite3_column_count);
                    481:                DLINK(sqlite3_finalize);
                    482:                DLINK(sqlite3_column_name);
                    483:                DLINK(sqlite3_step);
                    484:                DLINK(sqlite3_column_type);
                    485:                DLINK(sqlite3_column_text);
1.6       misha     486:                DLINK(sqlite3_column_blob);
                    487:                DLINK(sqlite3_column_bytes);
1.1       misha     488:                return 0;
                    489:        }
                    490: 
                    491: };
                    492: 
                    493: extern "C" SQL_Driver *SQL_DRIVER_CREATE() {
                    494:        return new SQLite_Driver();
                    495: }

E-mail: