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

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

E-mail: