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

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

E-mail: