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

1.1       misha       1: /** @file
                      2:        Parser SQLite driver.
                      3: 
                      4:        (c) Dmitry "Creator" Bobrik, 2004
                      5: */
1.4     ! misha       6: //static const char *RCSId="$Id: parser3sqlite.C,v 1.3 2007-12-27 14:24:21 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) {
                     28:     if(string) {
                     29:                char *v=strchr(string, delim);
                     30:                if(v) {
                     31:                        *v=0;
                     32:                        return v+1;
                     33:                }
                     34:     }
                     35:     return 0;
                     36: }
                     37: 
                     38: static char *lsplit(char **string_ref, char delim) {
                     39:     char *result=*string_ref;
                     40:        char *next=lsplit(*string_ref, delim);
                     41:     *string_ref=next;
                     42:     return result;
                     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;
                     54:        const char* cstrClientCharset;
                     55:        bool autocommit;
                     56: };
                     57: 
                     58: 
                     59: 
                     60: /**
                     61:        SQLite server driver
                     62: */
                     63: class SQLite_Driver : public SQL_Driver {
                     64: public:
                     65: 
                     66:        SQLite_Driver() : SQL_Driver() {
                     67:        }
                     68: 
                     69:        /// get api version
                     70:        int api_version() { return SQL_DRIVER_API_VERSION; }
1.4     ! misha      71: 
1.1       misha      72:        /// initialize driver by loading sql dynamic link library
                     73:        const char *initialize(char *dlopen_file_spec) {
                     74:                return dlopen_file_spec?
                     75:                        dlink(dlopen_file_spec):"client library column is empty";
                     76:        }
1.4     ! misha      77: 
1.1       misha      78:        /**     connect
                     79:                @param url
1.4     ! misha      80:                        format: @b [localhost/]dbfile?
        !            81:                        ClientCharset=UTF-8&
        !            82:                        autocommit=1
1.1       misha      83:        */
                     84:        void connect(
1.4     ! misha      85:                        char *url, 
        !            86:                        SQL_Driver_services& services, 
        !            87:                        void **connection_ref ///< output: Connection*
        !            88:                ){
1.1       misha      89: 
                     90:                int rc;
                     91: 
1.4     ! misha      92:                Connection& connection=*(Connection *)services.malloc(sizeof(Connection));
        !            93:                connection.services=&services;
        !            94:                connection.cstrClientCharset=SQLITE_DEFAULT_CHARSET;    
        !            95:                connection.autocommit=true;
1.1       misha      96: 
1.4     ! misha      97:                char *db = url;
        !            98:                char *options = lsplit(db, '?');
1.1       misha      99: 
1.4     ! misha     100:                char *db_path=(char*)services.malloc(strlen((char*)services.request_document_root()) + strlen(db) + 2); 
        !           101:                db_path=strncat(db_path, (char*)services.request_document_root(), MAX_STRING);
        !           102:                db_path+="/";
        !           103:                db_path=strncat(db_path, db, MAX_STRING);
        !           104: 
        !           105:                while(options) {
        !           106:                        if(char *key=lsplit(&options, '&')) {
        !           107:                                if(*key) {
        !           108:                                        if(char *value=lsplit(key, '=')) {
        !           109:                                                if(strcmp(key, "ClientCharset" )==0) { // transcoding with parser
        !           110:                                                        toupper_str(value, value, strlen(value));
        !           111:                                                        connection.cstrClientCharset=value;
        !           112:                                                        continue;
        !           113:                                                } else if(strcasecmp(key, "autocommit")==0) {
        !           114:                                                        if(atoi(value)==0)
        !           115:                                                                connection.autocommit=false;
        !           116:                                                        continue;
        !           117:                                                } else
        !           118:                                                        services._throw("unknown connect option" /*key*/);
        !           119:                                        } else 
        !           120:                                                services._throw("connect option without =value" /*key*/);
        !           121:                                }
        !           122:                        }
        !           123:                }
        !           124: 
        !           125:                // transcode database_name from $request:charset to UTF-8
        !           126:                size_t transcoded_db_path_size;
        !           127:                const char* sdb = db_path;
        !           128:                services.transcode(sdb, strlen(db_path),
        !           129:                        sdb, transcoded_db_path_size,
        !           130:                        services.request_charset(),
        !           131:                        SQLITE_DEFAULT_CHARSET);
        !           132:                
        !           133:                 rc = sqlite3_open(db_path, &connection.handle);
1.1       misha     134: 
                    135:                if( SQLITE_OK != rc ){
1.4     ! misha     136:                        const char* errmsg = sqlite3_errmsg(connection.handle);
        !           137:                        _throw(connection, errmsg);
1.1       misha     138:                        sqlite3_close(connection.handle);
                    139:                }
                    140: 
                    141:                *connection_ref=&connection;
1.4     ! misha     142:                
        !           143:                if(!connection.autocommit)
        !           144:                        exec(connection, "SET AUTOCOMMIT=0");
        !           145:                        
1.1       misha     146:        }
                    147: 
                    148:        void exec(Connection& connection, const char* statement) {
                    149:                char *zErr;
                    150:                int rc;
1.4     ! misha     151:                rc=sqlite3_exec(connection.handle, statement, 0, 0, &zErr);
        !           152:                if(rc!=SQLITE_OK){
        !           153:                        _throw(connection, zErr);
        !           154:                        sqlite3_free(zErr); // error? can't free memory after throw
1.1       misha     155:                }
                    156: 
                    157:        }
                    158: 
                    159:        void disconnect(void *aconnection) {
                    160:                Connection& connection=*static_cast<Connection*>(aconnection);
                    161:                sqlite3_close(connection.handle);
                    162:                connection.handle=0;
1.4     ! misha     163:        }
1.1       misha     164: 
                    165:        void commit(void *aconnection) {
                    166:                Connection& connection=*static_cast<Connection*>(aconnection);
                    167:                if(!connection.autocommit)
1.4     ! misha     168:                        exec(connection, "COMMIT");
1.1       misha     169:        }
1.4     ! misha     170: 
1.1       misha     171:        void rollback(void *aconnection) {
                    172:                Connection& connection=*static_cast<Connection*>(aconnection);
                    173:                if(!connection.autocommit)
1.4     ! misha     174:                        exec(connection, "ROLLBACK");
1.1       misha     175:        }
                    176: 
                    177:        bool ping(void *aconnection) {
1.4     ! misha     178:                return true;  // not needed
1.1       misha     179:        }
                    180: 
                    181:        const char* quote(void *aconnection, const char *from, unsigned int length) {
                    182:                Connection& connection=*static_cast<Connection*>(aconnection);
                    183:                /*
                    184:                        You must allocate the to buffer to be at least length*2+1 bytes long. 
1.4     ! misha     185:                        In the worse case, each character may need to be encoded as using two bytes, 
        !           186:                        and you need room for the terminating null byte.
1.1       misha     187:                */
                    188:                char *result=(char*)connection.services->malloc_atomic(length*2+1);
                    189:                char *to=result;
                    190:                while(length--) {
                    191:                        if(*from=='\'') { // ' -> ''
                    192:                                *to++='\'';
1.4     ! misha     193:                        } else if(*from=='\"') { // " -> ""
        !           194:                                *to++='\"';
1.1       misha     195:                        }
                    196:                        *to++=*from++;
                    197:                }
                    198:                *to=0;
                    199:                return result;
                    200:        }
1.4     ! misha     201: 
1.1       misha     202:        void query(void *aconnection, 
                    203:                const char *astatement, 
                    204:                size_t placeholders_count, Placeholder* placeholders, 
                    205:                unsigned long offset, unsigned long limit,
                    206:                SQL_Driver_query_event_handlers& handlers) {
                    207: 
                    208:                Connection& connection=*static_cast<Connection*>(aconnection);
                    209:                SQL_Driver_services& services=*connection.services;
                    210:                const char* cstrClientCharset=connection.cstrClientCharset;
                    211: 
                    212:                if(placeholders_count>0)
1.4     ! misha     213:                        _throw(connection, "bind variables not supported yet");
        !           214:    
        !           215:                // transcode from $request:charset to ClientCharset
        !           216:                if(cstrClientCharset) {
        !           217:                        size_t transcoded_statement_size;
        !           218:                        services.transcode(astatement, strlen(astatement),
        !           219:                                astatement, transcoded_statement_size,
        !           220:                                services.request_charset(),
        !           221:                                cstrClientCharset);
        !           222:                }
        !           223:                
1.1       misha     224:                const char *statement;
                    225:                if(offset || limit) {
                    226:                        size_t statement_size=strlen(astatement);
                    227:                        char *statement_limited=(char *)services.malloc_atomic(
                    228:                                statement_size+MAX_NUMBER*2+8/* limit #,#*/+1);
                    229:                        char *cur=statement_limited;
                    230:                        memcpy(cur, astatement, statement_size); cur+=statement_size;
                    231:                        cur+=sprintf(cur, " limit ");
                    232:                        if(offset)
                    233:                                cur+=snprintf(cur, MAX_NUMBER+1, "%u,", offset);
                    234:                        if(limit)
                    235:                                cur+=snprintf(cur, MAX_NUMBER, "%u", limit);
                    236:                        statement=statement_limited;
                    237:                } else
                    238:                        statement=astatement;
                    239: 
                    240: 
                    241:                const char *pzTail;
                    242:                sqlite3_stmt *SQL;
                    243:                int rc;
                    244:                int i;
                    245:                SQL_Error sql_error;
                    246:                bool failed = false;
                    247: 
                    248:                do{ // cycling through SQL commands
                    249: 
                    250:                        rc = sqlite3_prepare(connection.handle, statement, -1, &SQL, &pzTail);
                    251: 
1.4     ! misha     252:                        if(rc!=SQLITE_OK){
        !           253:                                _throw(connection, sqlite3_errmsg(connection.handle));
        !           254:                                sqlite3_free(pzTail); // error? can't free memory after throw
1.1       misha     255:                        }
                    256:                        
                    257: 
                    258:                        #define CHECK(afailed) if(afailed) { failed=true; goto cleanup; }
                    259: 
                    260:                        int column_count = sqlite3_column_count(SQL);
                    261: 
                    262:                        if(!column_count){  // empty result: insert|delete|update|...
                    263:                                rc = sqlite3_step(SQL);
                    264:                        } else {
                    265: 
                    266:                                for(i=0; i<column_count; i++){
                    267:                                        const char *column_name = sqlite3_column_name(SQL, i);
                    268:                                        size_t length = strlen(column_name);
                    269: 
                    270:                                        char* strm=(char*)services.malloc_atomic(length+1);
                    271:                                        memcpy(strm, column_name, length+1);
1.4     ! misha     272:                                        const char* str = strm;
        !           273:                                        // transcode to $request:charset from connect-string?ClientCharset
        !           274:                                        if(cstrClientCharset) {
        !           275:                                                services.transcode(str, length,
        !           276:                                                        str, length,
        !           277:                                                        cstrClientCharset,
        !           278:                                                        services.request_charset());
        !           279:                                        }
        !           280:                                                        
1.1       misha     281:                                        CHECK(handlers.add_column(sql_error, (const char*)strm, length));
                    282:                                }
                    283:                                CHECK(handlers.before_rows(sql_error));
                    284: 
                    285:                                int column_type;
                    286:                                const unsigned char *str;
                    287:                                size_t length = 0;
                    288: 
                    289:                                do{
                    290:                                        rc = sqlite3_step(SQL);
                    291:                                        if( rc == SQLITE_ROW ){   // новая строка!!
                    292: 
                    293:                                                CHECK(handlers.add_row(sql_error));
                    294: 
                    295:                                                for(i=0; i<column_count; i++){
                    296: 
                    297:                                                        column_type = sqlite3_column_type(SQL, i);
                    298:                
                    299:                                                        // SQLite позволяет поле любого типа получить в виде строки через sqlite3_column_text
                    300:                                                        // просто перекодирует если требуется
                    301:                                                        // а парсер только строковые значения получает
                    302:                                                        // но switch я всё-таки сделал - так, на будущее
                    303:                                                        switch(column_type) {
                    304:                                                                case SQLITE_TEXT:
1.4     ! misha     305:                                                                        str=(const unsigned char*)sqlite3_column_text(SQL, i);
        !           306:                                                                        length=strlen(str);
1.1       misha     307:                                                                        break;
                    308:                                                                case SQLITE_INTEGER:
1.4     ! misha     309:                                                                        str=(const unsigned char*)sqlite3_column_text(SQL, i);
        !           310:                                                                        length=strlen(str);
1.1       misha     311:                                                                        break;
1.2       misha     312:                                                                case SQLITE_NULL:
1.4     ! misha     313:                                                                        str=NULL;
        !           314:                                                                        length=0;
1.2       misha     315:                                                                        break;
1.1       misha     316:                                                                default:
1.4     ! misha     317:                                                                        str=(const unsigned char*)sqlite3_column_text(SQL, i);
        !           318:                                                                        length=strlen(str);
1.1       misha     319:                                                                        break;
                    320:                                                        }
                    321: 
1.4     ! misha     322:                                                        if(length){
        !           323:                                                                char* strm=(char*)services.malloc_atomic(length+1);
        !           324:                                                                memcpy(strm, str, length+1);
        !           325:                                                                str = strm;
        !           326: 
        !           327:                                                                // transcode to $request:charset from connect-string?ClientCharset
        !           328:                                                                if(cstrClientCharset) {
        !           329:                                                                        services.transcode(str, length,
        !           330:                                                                                str, length,
        !           331:                                                                                cstrClientCharset,
        !           332:                                                                                services.request_charset());
        !           333:                                                                }
        !           334:                                                        } else
        !           335:                                                                str = 0;
        !           336:                                                        
        !           337:                                                        CHECK(handlers.add_row_cell(sql_error, str, length));
1.1       misha     338: 
                    339:                                                }
                    340:                                        }
                    341:                                } while( rc == SQLITE_BUSY || rc == SQLITE_ROW );
                    342: 
                    343:                        }  // if column
                    344: 
                    345:                        if( rc == SQLITE_ERROR || rc == SQLITE_MISUSE ){
1.4     ! misha     346:                                _throw(connection, sqlite3_errmsg(connection.handle));
1.1       misha     347:                        }
                    348: 
                    349:        cleanup:
                    350:                        sqlite3_finalize(SQL);
                    351:                        statement = pzTail;
                    352:                } while (strlen(pzTail) > 0);
                    353: 
                    354:                if(failed)
1.4     ! misha     355:                        _throw(connection, sql_error);
1.1       misha     356:        }
                    357: 
1.4     ! misha     358: private:
        !           359:         void _throw(Connection& connection, const char* aerr_msg) {
        !           360:                        size_t err_length=strlen(aerr_msg);
        !           361:                        if(err_length && connection.cstrClientCharset) {
        !           362:                                connection.services->transcode(aerr_msg, err_length,
        !           363:                                        aerr_msg, err_length,
        !           364:                                        connection.cstrClientCharset,
        !           365:                                        connection.services->request_charset());
        !           366:                        }
        !           367:                        connection.services->_throw(aerr_msg);
        !           368:         }
        !           369: 
        !           370: 
1.1       misha     371: private: // sqlite client library funcs
                    372: 
                    373:        typedef int (*t_sqlite3_open)(const char *filename, sqlite3 **ppDb); t_sqlite3_open sqlite3_open;
                    374: 
                    375:        typedef int (*t_sqlite3_close)(sqlite3 *); t_sqlite3_close sqlite3_close;
                    376: 
                    377:        typedef int (*t_sqlite3_exec)(sqlite3*, const char *sql, sqlite3_callback, void *, char **errmsg); t_sqlite3_exec sqlite3_exec;
                    378: 
                    379:        typedef void (*t_sqlite3_free)(char *z); t_sqlite3_free sqlite3_free;
                    380: 
                    381:        typedef const char *(* t_sqlite3_errmsg)(sqlite3*); t_sqlite3_errmsg sqlite3_errmsg;
                    382: 
                    383:        typedef int (* t_sqlite3_prepare)(sqlite3 *db, const char *zSql, int nBytes, sqlite3_stmt **ppStmt, const char **pzTail); t_sqlite3_prepare sqlite3_prepare;
                    384: 
                    385:        typedef int (* t_sqlite3_column_count)(sqlite3_stmt *pStmt); t_sqlite3_column_count sqlite3_column_count;
                    386: 
                    387:        typedef int (* t_sqlite3_finalize)(sqlite3_stmt *pStmt); t_sqlite3_finalize sqlite3_finalize;
                    388: 
                    389:        typedef const char *(* t_sqlite3_column_name)(sqlite3_stmt*,int); t_sqlite3_column_name sqlite3_column_name;
                    390: 
                    391:        typedef int (* t_sqlite3_step)(sqlite3_stmt*); t_sqlite3_step sqlite3_step;
                    392: 
                    393:        typedef int (* t_sqlite3_column_type)(sqlite3_stmt*, int iCol); t_sqlite3_column_type sqlite3_column_type;
                    394: 
                    395:        typedef const unsigned char *(* t_sqlite3_column_text)(sqlite3_stmt*, int iCol); t_sqlite3_column_text sqlite3_column_text;
                    396: 
                    397: private: // sqlite client library funcs linking
                    398: 
                    399:        const char *dlink(const char *dlopen_file_spec) {
                    400:                if(lt_dlinit())
                    401:                        return lt_dlerror();
                    402:         lt_dlhandle handle=lt_dlopen(dlopen_file_spec);
                    403:         if (!handle) {
                    404:             if(const char* result=lt_dlerror())
                    405:                return result;
                    406: 
                    407:                        return "can not open the dynamic link module";
                    408:                }
                    409: 
                    410:                #define DSLINK(name, action) \
                    411:                        name=(t_##name)lt_dlsym(handle, #name); \
                    412:                                if(!name) \
                    413:                                        action;
                    414: 
                    415:                #define DLINK(name) DSLINK(name, return "function " #name " was not found")
                    416:                #define SLINK(name) DSLINK(name, name=subst_##name)
                    417:                
                    418:                DLINK(sqlite3_open);
                    419:                DLINK(sqlite3_close);
                    420:                DLINK(sqlite3_exec);
                    421:                DLINK(sqlite3_free);
                    422:                DLINK(sqlite3_errmsg);
                    423:                DLINK(sqlite3_prepare);
                    424:                DLINK(sqlite3_column_count);
                    425:                DLINK(sqlite3_finalize);
                    426:                DLINK(sqlite3_column_name);
                    427:                DLINK(sqlite3_step);
                    428:                DLINK(sqlite3_column_type);
                    429:                DLINK(sqlite3_column_text);
                    430:                return 0;
                    431:        }
                    432: 
                    433: };
                    434: 
                    435: extern "C" SQL_Driver *SQL_DRIVER_CREATE() {
                    436:        return new SQLite_Driver();
                    437: }

E-mail: