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

1.1     ! misha       1: /** @file
        !             2:        Parser SQLite driver.
        !             3: 
        !             4:        (c) Dmitry "Creator" Bobrik, 2004
        !             5: */
        !             6: //static const char *RCSId="$Id: parser3sqlite.C, Exp $"; 
        !             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;
        !           277:                                                                default:
        !           278:                                                                        str = sqlite3_column_text(SQL, i);
        !           279:                                                                        length = strlen((const char*)str);
        !           280:                                                                        break;
        !           281:                                                        }
        !           282: 
        !           283:                                                        //MBox((const char*)str, "query_in_step");
        !           284: 
        !           285:                                                        char* strm=(char*)services.malloc_atomic(length+1);
        !           286:                                                        memcpy(strm, str, length+1);
        !           287: 
        !           288:                                                        CHECK(handlers.add_row_cell(sql_error, (const char*)strm, length));
        !           289: 
        !           290:                                                }
        !           291:                                        }
        !           292:                                } while( rc == SQLITE_BUSY || rc == SQLITE_ROW );
        !           293: 
        !           294:                        }  // if column
        !           295: 
        !           296:                        if( rc == SQLITE_ERROR || rc == SQLITE_MISUSE ){
        !           297:                                services._throw(sqlite3_errmsg(connection.handle));
        !           298:                        }
        !           299: 
        !           300:        cleanup:
        !           301:                        sqlite3_finalize(SQL);
        !           302:                        statement = pzTail;
        !           303:                } while (strlen(pzTail) > 0);
        !           304: 
        !           305:                if(failed)
        !           306:                        services._throw(sql_error);
        !           307:        }
        !           308: 
        !           309: private: // sqlite client library funcs
        !           310: 
        !           311:        typedef int (*t_sqlite3_open)(const char *filename, sqlite3 **ppDb); t_sqlite3_open sqlite3_open;
        !           312: 
        !           313:        typedef int (*t_sqlite3_close)(sqlite3 *); t_sqlite3_close sqlite3_close;
        !           314: 
        !           315:        typedef int (*t_sqlite3_exec)(sqlite3*, const char *sql, sqlite3_callback, void *, char **errmsg); t_sqlite3_exec sqlite3_exec;
        !           316: 
        !           317:        typedef void (*t_sqlite3_free)(char *z); t_sqlite3_free sqlite3_free;
        !           318: 
        !           319:        typedef const char *(* t_sqlite3_errmsg)(sqlite3*); t_sqlite3_errmsg sqlite3_errmsg;
        !           320: 
        !           321:        typedef int (* t_sqlite3_prepare)(sqlite3 *db, const char *zSql, int nBytes, sqlite3_stmt **ppStmt, const char **pzTail); t_sqlite3_prepare sqlite3_prepare;
        !           322: 
        !           323:        typedef int (* t_sqlite3_column_count)(sqlite3_stmt *pStmt); t_sqlite3_column_count sqlite3_column_count;
        !           324: 
        !           325:        typedef int (* t_sqlite3_finalize)(sqlite3_stmt *pStmt); t_sqlite3_finalize sqlite3_finalize;
        !           326: 
        !           327:        typedef const char *(* t_sqlite3_column_name)(sqlite3_stmt*,int); t_sqlite3_column_name sqlite3_column_name;
        !           328: 
        !           329:        typedef int (* t_sqlite3_step)(sqlite3_stmt*); t_sqlite3_step sqlite3_step;
        !           330: 
        !           331:        typedef int (* t_sqlite3_column_type)(sqlite3_stmt*, int iCol); t_sqlite3_column_type sqlite3_column_type;
        !           332: 
        !           333:        typedef const unsigned char *(* t_sqlite3_column_text)(sqlite3_stmt*, int iCol); t_sqlite3_column_text sqlite3_column_text;
        !           334: 
        !           335: private: // sqlite client library funcs linking
        !           336: 
        !           337:        const char *dlink(const char *dlopen_file_spec) {
        !           338:                if(lt_dlinit())
        !           339:                        return lt_dlerror();
        !           340:         lt_dlhandle handle=lt_dlopen(dlopen_file_spec);
        !           341:         if (!handle) {
        !           342:             if(const char* result=lt_dlerror())
        !           343:                return result;
        !           344: 
        !           345:                        return "can not open the dynamic link module";
        !           346:                }
        !           347: 
        !           348:                #define DSLINK(name, action) \
        !           349:                        name=(t_##name)lt_dlsym(handle, #name); \
        !           350:                                if(!name) \
        !           351:                                        action;
        !           352: 
        !           353:                #define DLINK(name) DSLINK(name, return "function " #name " was not found")
        !           354:                #define SLINK(name) DSLINK(name, name=subst_##name)
        !           355:                
        !           356:                DLINK(sqlite3_open);
        !           357:                DLINK(sqlite3_close);
        !           358:                DLINK(sqlite3_exec);
        !           359:                DLINK(sqlite3_free);
        !           360:                DLINK(sqlite3_errmsg);
        !           361:                DLINK(sqlite3_prepare);
        !           362:                DLINK(sqlite3_column_count);
        !           363:                DLINK(sqlite3_finalize);
        !           364:                DLINK(sqlite3_column_name);
        !           365:                DLINK(sqlite3_step);
        !           366:                DLINK(sqlite3_column_type);
        !           367:                DLINK(sqlite3_column_text);
        !           368:                return 0;
        !           369:        }
        !           370: 
        !           371: };
        !           372: 
        !           373: extern "C" SQL_Driver *SQL_DRIVER_CREATE() {
        !           374:        return new SQLite_Driver();
        !           375: }

E-mail: