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

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

E-mail: