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

1.1       misha       1: /** @file
                      2:        Parser SQLite driver.
                      3: 
                      4:        (c) Dmitry "Creator" Bobrik, 2004
                      5: */
1.2     ! misha       6: //static const char *RCSId="$Id: parser3sqlite.C,v 1.1 2007/02/19 10:54:36 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: 
                     20: #if _MSC_VER
                     21: #      define snprintf _snprintf
                     22: #      define strcasecmp _stricmp
                     23: #endif
                     24: 
                     25: static void MBox(const char *message, const char *title){
                     26: //     MessageBox(0, (LPCSTR)message, (LPCSTR)title, MB_OK);
                     27: }
                     28: 
                     29: static char *lsplit(char *string, char delim) {
                     30:     if(string) {
                     31:                char *v=strchr(string, delim);
                     32:                if(v) {
                     33:                        *v=0;
                     34:                        return v+1;
                     35:                }
                     36:     }
                     37:     return 0;
                     38: }
                     39: 
                     40: static char *lsplit(char **string_ref, char delim) {
                     41:     char *result=*string_ref;
                     42:        char *next=lsplit(*string_ref, delim);
                     43:     *string_ref=next;
                     44:     return result;
                     45: }
                     46: 
                     47: static void toupper_str(char *out, const char *in, size_t size) {
                     48:        while(size--)
                     49:                *out++=(char)toupper(*in++);
                     50: }
                     51: 
                     52: struct Connection {
                     53:        SQL_Driver_services* services;
                     54: 
                     55:        sqlite3* handle;
                     56:        const char* cstrClientCharset;
                     57:        bool autocommit;
                     58: };
                     59: 
                     60: 
                     61: 
                     62: /**
                     63:        SQLite server driver
                     64: */
                     65: class SQLite_Driver : public SQL_Driver {
                     66: public:
                     67: 
                     68:        SQLite_Driver() : SQL_Driver() {
                     69:        }
                     70: 
                     71:        /// get api version
                     72:        int api_version() { return SQL_DRIVER_API_VERSION; }
                     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:        }
                     78:        /**     connect
                     79:                @param url
                     80:                        format: @b database
                     81:                        SQLite options - database file name
                     82:        */
                     83:        void connect(
                     84:                char *url, 
                     85:                SQL_Driver_services& services, 
                     86:                void **connection_ref ///< output: Connection*
                     87:                ) {
                     88: 
                     89:                int rc;
                     90: 
                     91: //             char *cstrBackwardCompAskServerToTranscode=0;
                     92: 
                     93:                Connection& connection=*(Connection  *)services.malloc(sizeof(Connection));
                     94:                connection.services=&services;
                     95: 
                     96:                rc = sqlite3_open(url, &connection.handle);
                     97: 
                     98:                if( SQLITE_OK != rc ){
                     99:                        services._throw(sqlite3_errmsg(connection.handle));
                    100:                        sqlite3_close(connection.handle);
                    101:                }
                    102: 
                    103:                connection.cstrClientCharset=0; 
                    104:                connection.autocommit=true;   // значит что все INSERTы и UPDATEы коммитятся автоматически будучи запущенными отдельным запросом
                    105:                *connection_ref=&connection;
                    106: 
                    107:        }
                    108: 
                    109:        void exec(Connection& connection, const char* statement) {
                    110: 
                    111:                char *zErr;
                    112:                int rc;
                    113: 
                    114:                rc = sqlite3_exec(connection.handle, statement, 0, 0, &zErr);
                    115: 
                    116:                MBox(statement, "exec_stat");
                    117: 
                    118:                if( SQLITE_OK!=rc ){
                    119:                        MBox(zErr, "exec_error");
                    120:                        connection.services->_throw(zErr);
                    121:                        sqlite3_free(zErr);
                    122:                }
                    123: 
                    124:        }
                    125: 
                    126:        void disconnect(void *aconnection) {
                    127:                Connection& connection=*static_cast<Connection*>(aconnection);
                    128: 
                    129:                sqlite3_close(connection.handle);
                    130:                connection.handle=0;
                    131: 
                    132:                MBox("disconnect", "disconnect");
                    133: 
                    134:        }
                    135:        void commit(void *aconnection) {
                    136:                //_asm int 3;
                    137:                Connection& connection=*static_cast<Connection*>(aconnection);
                    138:                MBox("commit", "commit");
                    139: 
                    140:                if(!connection.autocommit)
                    141:                        exec(connection, "commit");
                    142:        }
                    143:        void rollback(void *aconnection) {
                    144:                Connection& connection=*static_cast<Connection*>(aconnection);
                    145: 
                    146:                MBox("rollback", "rollback");
                    147: 
                    148:                if(!connection.autocommit)
                    149:                        exec(connection, "rollback");
                    150:        }
                    151: 
                    152:        bool ping(void *aconnection) {
                    153:                Connection& connection=*static_cast<Connection*>(aconnection);
                    154: 
                    155:                return true;  // пинг не требуется, т.к. сервер не сокетный :)
                    156:        }
                    157: 
                    158:        const char* quote(void *aconnection, const char *from, unsigned int length) {
                    159:                Connection& connection=*static_cast<Connection*>(aconnection);
                    160:                /*
                    161:                        3.23.22b
                    162:                        You must allocate the to buffer to be at least length*2+1 bytes long. 
                    163:                        (In the worse case, each character may need to be encoded as using two bytes, 
                    164:                        and you need room for the terminating null byte.)
                    165:                */
                    166:                char *result=(char*)connection.services->malloc_atomic(length*2+1);
                    167:                MBox(from, "quote");
                    168:                char *to=result;
                    169:                while(length--) {
                    170:                        if(*from=='\'') { // ' -> ''
                    171:                                *to++='\'';
                    172:                        }
                    173:                        *to++=*from++;
                    174:                }
                    175:                *to=0;
                    176: //             mysql_escape_string(result, from, length);
                    177:                return result;
                    178:        }
                    179:        void query(void *aconnection, 
                    180:                const char *astatement, 
                    181:                size_t placeholders_count, Placeholder* placeholders, 
                    182:                unsigned long offset, unsigned long limit,
                    183:                SQL_Driver_query_event_handlers& handlers) {
                    184: 
                    185:                Connection& connection=*static_cast<Connection*>(aconnection);
                    186:                SQL_Driver_services& services=*connection.services;
                    187:                const char* cstrClientCharset=connection.cstrClientCharset;
                    188: 
                    189:                if(placeholders_count>0)
                    190:                        services._throw("bind variables not supported (yet)");
                    191: 
                    192:                const char *statement;
                    193:                // вот этот блок добавляет в запрос LIMIT N, M если задано. SQLite поддерживает эти параметры
                    194:                if(offset || limit) {
                    195:                        size_t statement_size=strlen(astatement);
                    196:                        char *statement_limited=(char *)services.malloc_atomic(
                    197:                                statement_size+MAX_NUMBER*2+8/* limit #,#*/+1);
                    198:                        char *cur=statement_limited;
                    199:                        memcpy(cur, astatement, statement_size); cur+=statement_size;
                    200:                        cur+=sprintf(cur, " limit ");
                    201:                        if(offset)
                    202:                                cur+=snprintf(cur, MAX_NUMBER+1, "%u,", offset);
                    203:                        if(limit)
                    204:                                cur+=snprintf(cur, MAX_NUMBER, "%u", limit);
                    205:                        statement=statement_limited;
                    206:                } else
                    207:                        statement=astatement;
                    208: 
                    209: 
                    210:                char *zErr;
                    211:                const char *pzTail;
                    212:                sqlite3_stmt *SQL;
                    213:                int rc;
                    214:                int i;
                    215:                SQL_Error sql_error;
                    216:                bool failed = false;
                    217: 
                    218:                do{ // cycling through SQL commands
                    219: 
                    220: //                     MBox(statement, "statement");
                    221:                        rc = sqlite3_prepare(connection.handle, statement, -1, &SQL, &pzTail);
                    222:                        MBox(pzTail, "tail");
                    223: 
                    224:                        if( SQLITE_OK!=rc ){
                    225:                                MBox(sqlite3_errmsg(connection.handle), "query_error");
                    226:                                services._throw(sqlite3_errmsg(connection.handle));
                    227:                                sqlite3_free(zErr);
                    228:                        }
                    229:                        
                    230: 
                    231:                        #define CHECK(afailed) if(afailed) { failed=true; goto cleanup; }
                    232: 
                    233:                        int column_count = sqlite3_column_count(SQL);
                    234: 
                    235:                        if(!column_count){  // empty result: insert|delete|update|...
                    236:                                rc = sqlite3_step(SQL);
                    237:                        } else {
                    238: 
                    239:                                for(i=0; i<column_count; i++){
                    240:                                        const char *column_name = sqlite3_column_name(SQL, i);
                    241:                                        size_t length = strlen(column_name);
                    242: 
                    243:                                        char* strm=(char*)services.malloc_atomic(length+1);
                    244:                                        memcpy(strm, column_name, length+1);
                    245: 
                    246:                                        CHECK(handlers.add_column(sql_error, (const char*)strm, length));
                    247:                                }
                    248:                                CHECK(handlers.before_rows(sql_error));
                    249: 
                    250:                                int column_type;
                    251:                                const unsigned char *str;
                    252:                                size_t length = 0;
                    253: 
                    254:                                do{
                    255:                                        rc = sqlite3_step(SQL);
                    256:                                        if( rc == SQLITE_ROW ){   // новая строка!!
                    257: 
                    258:                                                CHECK(handlers.add_row(sql_error));
                    259: 
                    260:                                                for(i=0; i<column_count; i++){
                    261: 
                    262:                                                        column_type = sqlite3_column_type(SQL, i);
                    263:                
                    264:                                                        // SQLite позволяет поле любого типа получить в виде строки через sqlite3_column_text
                    265:                                                        // просто перекодирует если требуется
                    266:                                                        // а парсер только строковые значения получает
                    267:                                                        // но switch я всё-таки сделал - так, на будущее
                    268:                                                        switch(column_type) {
                    269:                                                                case SQLITE_TEXT:
                    270:                                                                        str = sqlite3_column_text(SQL, i);
                    271:                                                                        length = strlen((const char*)str);
                    272:                                                                        break;
                    273:                                                                case SQLITE_INTEGER:
                    274:                                                                        str = sqlite3_column_text(SQL, i);
                    275:                                                                        length = strlen((const char*)str);
                    276:                                                                        break;
1.2     ! misha     277:                                                                case SQLITE_NULL:
        !           278:                                                                        str = NULL;
        !           279:                                                                        length = 0;
        !           280:                                                                        break;
1.1       misha     281:                                                                default:
                    282:                                                                        str = sqlite3_column_text(SQL, i);
                    283:                                                                        length = strlen((const char*)str);
                    284:                                                                        break;
                    285:                                                        }
                    286: 
                    287:                                                        //MBox((const char*)str, "query_in_step");
                    288: 
                    289:                                                        char* strm=(char*)services.malloc_atomic(length+1);
                    290:                                                        memcpy(strm, str, length+1);
                    291: 
                    292:                                                        CHECK(handlers.add_row_cell(sql_error, (const char*)strm, length));
                    293: 
                    294:                                                }
                    295:                                        }
                    296:                                } while( rc == SQLITE_BUSY || rc == SQLITE_ROW );
                    297: 
                    298:                        }  // if column
                    299: 
                    300:                        if( rc == SQLITE_ERROR || rc == SQLITE_MISUSE ){
                    301:                                services._throw(sqlite3_errmsg(connection.handle));
                    302:                        }
                    303: 
                    304:        cleanup:
                    305:                        sqlite3_finalize(SQL);
                    306:                        statement = pzTail;
                    307:                } while (strlen(pzTail) > 0);
                    308: 
                    309:                if(failed)
                    310:                        services._throw(sql_error);
                    311:        }
                    312: 
                    313: private: // sqlite client library funcs
                    314: 
                    315:        typedef int (*t_sqlite3_open)(const char *filename, sqlite3 **ppDb); t_sqlite3_open sqlite3_open;
                    316: 
                    317:        typedef int (*t_sqlite3_close)(sqlite3 *); t_sqlite3_close sqlite3_close;
                    318: 
                    319:        typedef int (*t_sqlite3_exec)(sqlite3*, const char *sql, sqlite3_callback, void *, char **errmsg); t_sqlite3_exec sqlite3_exec;
                    320: 
                    321:        typedef void (*t_sqlite3_free)(char *z); t_sqlite3_free sqlite3_free;
                    322: 
                    323:        typedef const char *(* t_sqlite3_errmsg)(sqlite3*); t_sqlite3_errmsg sqlite3_errmsg;
                    324: 
                    325:        typedef int (* t_sqlite3_prepare)(sqlite3 *db, const char *zSql, int nBytes, sqlite3_stmt **ppStmt, const char **pzTail); t_sqlite3_prepare sqlite3_prepare;
                    326: 
                    327:        typedef int (* t_sqlite3_column_count)(sqlite3_stmt *pStmt); t_sqlite3_column_count sqlite3_column_count;
                    328: 
                    329:        typedef int (* t_sqlite3_finalize)(sqlite3_stmt *pStmt); t_sqlite3_finalize sqlite3_finalize;
                    330: 
                    331:        typedef const char *(* t_sqlite3_column_name)(sqlite3_stmt*,int); t_sqlite3_column_name sqlite3_column_name;
                    332: 
                    333:        typedef int (* t_sqlite3_step)(sqlite3_stmt*); t_sqlite3_step sqlite3_step;
                    334: 
                    335:        typedef int (* t_sqlite3_column_type)(sqlite3_stmt*, int iCol); t_sqlite3_column_type sqlite3_column_type;
                    336: 
                    337:        typedef const unsigned char *(* t_sqlite3_column_text)(sqlite3_stmt*, int iCol); t_sqlite3_column_text sqlite3_column_text;
                    338: 
                    339: private: // sqlite client library funcs linking
                    340: 
                    341:        const char *dlink(const char *dlopen_file_spec) {
                    342:                if(lt_dlinit())
                    343:                        return lt_dlerror();
                    344:         lt_dlhandle handle=lt_dlopen(dlopen_file_spec);
                    345:         if (!handle) {
                    346:             if(const char* result=lt_dlerror())
                    347:                return result;
                    348: 
                    349:                        return "can not open the dynamic link module";
                    350:                }
                    351: 
                    352:                #define DSLINK(name, action) \
                    353:                        name=(t_##name)lt_dlsym(handle, #name); \
                    354:                                if(!name) \
                    355:                                        action;
                    356: 
                    357:                #define DLINK(name) DSLINK(name, return "function " #name " was not found")
                    358:                #define SLINK(name) DSLINK(name, name=subst_##name)
                    359:                
                    360:                DLINK(sqlite3_open);
                    361:                DLINK(sqlite3_close);
                    362:                DLINK(sqlite3_exec);
                    363:                DLINK(sqlite3_free);
                    364:                DLINK(sqlite3_errmsg);
                    365:                DLINK(sqlite3_prepare);
                    366:                DLINK(sqlite3_column_count);
                    367:                DLINK(sqlite3_finalize);
                    368:                DLINK(sqlite3_column_name);
                    369:                DLINK(sqlite3_step);
                    370:                DLINK(sqlite3_column_type);
                    371:                DLINK(sqlite3_column_text);
                    372:                return 0;
                    373:        }
                    374: 
                    375: };
                    376: 
                    377: extern "C" SQL_Driver *SQL_DRIVER_CREATE() {
                    378:        return new SQLite_Driver();
                    379: }

E-mail: