Annotation of parser3/src/classes/table.C, revision 1.334

1.20      paf         1: /** @file
1.47      paf         2:        Parser: @b table parser class.
1.20      paf         3: 
1.312     moko        4:        Copyright (c) 2001-2015 Art. Lebedev Studio (http://www.artlebedev.com)
1.144     paf         5:        Author: Alexandr Petrosian <paf@design.ru> (http://paf.design.ru)
1.154     paf         6: */
1.221     paf         7: 
1.105     parser      8: #include "classes.h"
1.182     paf         9: #include "pa_vmethod_frame.h"
                     10: 
1.16      paf        11: #include "pa_common.h"
1.1       paf        12: #include "pa_request.h"
1.265     misha      13: #include "pa_charsets.h"
1.1       paf        14: #include "pa_vtable.h"
1.6       paf        15: #include "pa_vint.h"
1.51      paf        16: #include "pa_sql_connection.h"
1.72      paf        17: #include "pa_vbool.h"
1.277     moko       18: #include "pa_array.h"
1.1       paf        19: 
1.305     moko       20: #if (!defined(NO_STRINGSTREAM) && !defined(FREEBSD4))
                     21: #include <sstream>
                     22: #define USE_STRINGSTREAM
                     23: #endif
                     24: 
1.334   ! moko       25: volatile const char * IDENT_TABLE_C="$Id: table.C,v 1.333 2016/09/21 21:48:37 moko Exp $";
1.286     moko       26: 
1.66      paf        27: // class
                     28: 
1.182     paf        29: class MTable: public Methoded {
1.66      paf        30: public: // VStateless_class
1.264     misha      31:        Value* create_new_value(Pool&) { return new VTable(); }
1.66      paf        32: public:
1.182     paf        33:        MTable();
1.66      paf        34: };
1.1       paf        35: 
1.182     paf        36: // global variable
                     37: 
1.313     moko       38: DECLARE_CLASS_VAR(table, new MTable);
1.182     paf        39: 
                     40: #define TABLE_REVERSE_NAME "reverse"
                     41: 
                     42: // globals
                     43: 
1.203     paf        44: String sql_bind_name(SQL_BIND_NAME);
1.214     paf        45: String sql_limit_name(PA_SQL_LIMIT_NAME);
                     46: String sql_offset_name(PA_SQL_OFFSET_NAME);
1.182     paf        47: String sql_default_name(SQL_DEFAULT_NAME);
                     48: String sql_distinct_name(SQL_DISTINCT_NAME);
1.227     misha      49: String sql_value_type_name(SQL_VALUE_TYPE_NAME);
1.182     paf        50: String table_reverse_name(TABLE_REVERSE_NAME);
                     51: 
1.1       paf        52: // methods
1.66      paf        53: 
1.319     moko       54: static Table::Action_options get_action_options(Request& r, MethodParams& params, size_t options_index, const Table& source) {
1.176     paf        55:        Table::Action_options result;
1.268     misha      56:        if(params.count() <= options_index)
1.182     paf        57:                return result;
                     58: 
1.288     misha      59:        HashStringValue* options=params.as_hash(options_index);
1.176     paf        60:        if(!options)
                     61:                return result;
                     62: 
                     63:        result.defined=true;
                     64:        bool defined_offset=false;
                     65: 
                     66:        int valid_options=0;
1.182     paf        67:        if(Value* voffset=options->get(sql_offset_name)) {
1.176     paf        68:                valid_options++;
                     69:                defined_offset=true;
                     70:                if(voffset->is_string()) {
1.182     paf        71:                        const String&  soffset=*voffset->get_string();
1.176     paf        72:                        if(soffset == "cur")
                     73:                                result.offset=source.current();
                     74:                        else
1.318     moko       75:                                throw Exception(PARSER_RUNTIME, &soffset, "must be 'cur' string or expression");
1.176     paf        76:                } else 
                     77:                        result.offset=r.process_to_value(*voffset).as_int();
                     78:        }
1.182     paf        79:        if(Value* vlimit=options->get(sql_limit_name)) {
1.176     paf        80:                valid_options++;
                     81:                result.limit=r.process_to_value(*vlimit).as_int();
                     82:        }
1.182     paf        83:        if(Value *vreverse=(Value *)options->get(table_reverse_name)) { 
                     84:                valid_options++; 
                     85:                result.reverse=r.process_to_value(*vreverse).as_bool(); 
                     86:                if(result.reverse && !defined_offset) 
                     87:                        result.offset=source.count()-1; 
                     88:        } 
                     89: 
                     90:        if(valid_options!=options->count())
1.272     misha      91:                throw Exception(PARSER_RUNTIME, 0, CALLED_WITH_INVALID_OPTION);
1.176     paf        92: 
                     93:        return result;
                     94: }
1.157     paf        95: 
1.319     moko       96: struct TableControlChars {
                     97:        char separator;  const String* sseparator;
1.236     misha      98:        char encloser; const String* sencloser;
                     99: 
1.320     moko      100:        char separators[3];
                    101: 
1.319     moko      102:        TableControlChars():
                    103:                separator('\t'), sseparator(new String("\t")),
1.236     misha     104:                encloser(0), sencloser(0)
1.320     moko      105:        {
                    106:                strcpy(separators,"\t\n");
                    107:        }
                    108: 
1.236     misha     109:        int load( HashStringValue& options ) {
                    110:                int result=0;
                    111:                if(Value* vseparator=options.get(PA_COLUMN_SEPARATOR_NAME)) {
1.319     moko      112:                        sseparator=&vseparator->as_string();
                    113:                        if(sseparator->length()!=1)
1.323     moko      114:                                throw Exception(PARSER_RUNTIME, sseparator, "separator must be one byte character");
1.319     moko      115:                        separator=sseparator->first_char();
1.320     moko      116:                        separators[0]=separator;
1.236     misha     117:                        result++;
                    118:                }
                    119:                if(Value* vencloser=options.get(PA_COLUMN_ENCLOSER_NAME)) {
                    120:                        sencloser=&vencloser->as_string();
1.297     moko      121:                        if(sencloser->is_empty()){
                    122:                                encloser=0;
                    123:                        } else {
1.325     moko      124:                                if(sencloser->length()!=1)
                    125:                                        throw Exception(PARSER_RUNTIME, sencloser, "encloser must be empty or one byte character");
                    126:                                encloser=sencloser->first_char();
1.297     moko      127:                        }
1.236     misha     128:                        result++;
                    129:                }
                    130:                return result;
                    131:        }
                    132: };
                    133: 
1.319     moko      134: 
1.322     moko      135: struct lsplit_sresult {
                    136:        String* piece;
                    137:        char delim;
                    138: 
                    139:        lsplit_sresult() : piece(0), delim(0){}
                    140: 
                    141:        operator bool() { return piece!=0; }
                    142: 
                    143:        void append(String *str){
                    144:                if(piece)
                    145:                        *piece << *str;
                    146:                else
                    147:                        piece = str;
                    148:        }
                    149: };
                    150: 
                    151: class StringSplitHelper : public String {
                    152: public:
                    153:        char* base;
                    154: 
                    155:        StringSplitHelper(String astring) : String(astring), base(cstrm()) {}
                    156: 
                    157:        bool check_lang(const char *pos){
                    158:                return langs.check_lang(L_AS_IS, pos-base, 1);
                    159:        }
                    160: 
                    161:        String *extract(char *pos){
                    162:                String *result=new String;
1.330     moko      163:                if(size_t len=strlen(pos)){
                    164:                        // first: their langs
                    165:                        result->langs.append(result->body, langs, pos-base, len);
                    166:                        // next: letters themselves
                    167:                        result->body=Body(pos);
                    168:                }
1.322     moko      169:                return result;
                    170:        }
                    171: };
                    172: 
                    173: inline lsplit_sresult lsplit(char* *string_ref, const char* delims, StringSplitHelper& helper) {
                    174:        lsplit_sresult result;
                    175:        if(char *pos=*string_ref) {
1.327     moko      176:                while(pos=strpbrk(pos, delims)) {
                    177:                        if(helper.check_lang(pos)){
                    178:                                result.delim=*pos;
                    179:                                *pos=0;
1.322     moko      180:                                result.piece=helper.extract(*string_ref);
1.327     moko      181:                                *string_ref=pos+1;
1.322     moko      182:                                return result;
                    183:                        }
1.327     moko      184:                        pos++;
1.322     moko      185:                }
                    186:                result.piece=helper.extract(*string_ref);
                    187:                *string_ref=0;
                    188:        }
                    189:        return result;
                    190: }
                    191: 
                    192: static lsplit_sresult lsplit(char** string_ref, const char* delims, char encloser, StringSplitHelper& helper) {
                    193:        lsplit_sresult result;
                    194: 
                    195:        if(char *pos=*string_ref) {
                    196:                if(encloser && *pos==encloser && helper.check_lang(pos)) {
                    197:                        *string_ref=++pos;
                    198: 
                    199:                        // we are enclosed, searching for second encloser
                    200:                        while(1) {
1.328     moko      201:                                if(pos=strchr(pos, encloser)){
                    202:                                        if(helper.check_lang(pos)){
                    203:                                                *(pos++)=0;
1.322     moko      204:                                                result.append(helper.extract(*string_ref));
1.328     moko      205:                                                if(*pos==encloser && helper.check_lang(pos)){ // double-encloser stands for encloser
1.333     moko      206:                                                        *string_ref=pos;
1.322     moko      207:                                                } else {
1.328     moko      208:                                                        *string_ref=pos;
1.322     moko      209:                                                        break;
                    210:                                                }
                    211:                                        }
1.333     moko      212:                                        pos++;
1.327     moko      213:                                } else {
1.322     moko      214:                                        result.append(helper.extract(*string_ref));
                    215:                                        *string_ref=0;
                    216:                                        return result;
                    217:                                }
                    218:                        }
                    219: 
                    220:                        // we are no longer enclosed, searching for delimiter
1.328     moko      221:                        while(pos=strpbrk(pos, delims)) {
                    222:                                if(helper.check_lang(pos)){
                    223:                                        result.delim=*pos;
                    224:                                        if(pos>*string_ref){
                    225:                                                *pos=0;
1.322     moko      226:                                                result.append(helper.extract(*string_ref));
                    227:                                        }
1.328     moko      228:                                        *string_ref=pos+1;
1.322     moko      229:                                        return result;
                    230:                                }
1.328     moko      231:                                pos++;
1.322     moko      232:                        }
                    233:                        result.append(helper.extract(*string_ref));
                    234:                        *string_ref=0;
                    235:                } else
                    236:                        return lsplit(string_ref, delims, helper);
                    237:        }
                    238:        return result;
                    239: }
                    240: 
                    241: static void skip_clean_empty_lines(char** data_ref, StringSplitHelper& helper) {
                    242:        if(*data_ref) {
                    243:                while(**data_ref == '\n' && helper.check_lang(*data_ref))
                    244:                        (*data_ref)++;
                    245:        }
                    246: }
                    247: 
1.182     paf       248: static void _create(Request& r, MethodParams& params) {
1.157     paf       249:        // clone/copy part?
1.182     paf       250:        if(Table *source=params[0].get_table()) {
1.268     misha     251:                Table::Action_options o=get_action_options(r, params, 1, *source);
1.303     moko      252:                if(params.count()>2)
                    253:                        throw Exception(PARSER_RUNTIME, 0, "too many parameters");
1.182     paf       254:                GET_SELF(r, VTable).set_table(*new Table(*source, o));
1.157     paf       255:                return;
                    256:        }
1.142     paf       257: 
1.236     misha     258:        size_t data_param_index=0;
                    259:        bool nameless=false;
                    260: 
                    261:        if(params.count()>1) {
                    262:                if(params[0].is_string()){ // can be nameless only
                    263:                        const String& snameless=params.as_string(0, "called with more then 1 param, first param may be only string 'nameless' or junction");
                    264:                        if(snameless!="nameless")
1.318     moko      265:                                throw Exception(PARSER_RUNTIME, &snameless, "table::create called with more then 1 param, first param may be only 'nameless'");
1.236     misha     266:                        nameless=true;
                    267:                        data_param_index++;
                    268:                }
                    269:        }
                    270: 
                    271:        HashStringValue *options=0;
1.319     moko      272:        TableControlChars control_chars;
1.236     misha     273: 
                    274:        size_t options_param_index=data_param_index+1;
1.322     moko      275:        if( options_param_index<params.count() && (options=params.as_hash(options_param_index)) ) {
1.324     moko      276:                if(control_chars.load(*options)!=options->count())
                    277:                        throw Exception(PARSER_RUNTIME, 0, CALLED_WITH_INVALID_OPTION);
1.236     misha     278:        }
                    279: 
                    280:        // data
1.182     paf       281:        Temp_lang temp_lang(r, String::L_PASS_APPENDED);
1.322     moko      282:        StringSplitHelper sdata(r.process_to_string(params.as_junction(data_param_index, "body must be table or code")));
                    283:        char *data=sdata.base;
1.44      paf       284: 
                    285:        // parse columns
1.182     paf       286:        Table::columns_type columns;
1.322     moko      287:        if(nameless) {
                    288:                columns=0; // nameless
1.21      paf       289:        } else {
1.322     moko      290:                columns=new ArrayString;
                    291:                while( lsplit_sresult sr=lsplit(&data, control_chars.separators, control_chars.encloser, sdata) ) {
                    292:                        *columns+=sr.piece;
                    293:                        if(sr.delim=='\n') 
                    294:                                break;
1.182     paf       295:                }
1.44      paf       296:        }
1.322     moko      297:        
                    298:        Table& table=*new Table(columns);
                    299:        int columns_count=columns ? columns->count(): 0;
1.44      paf       300: 
                    301:        // parse cells
1.322     moko      302:        Table::element_type row(new ArrayString(columns_count));
                    303:        skip_clean_empty_lines(&data, sdata);
                    304:        while( lsplit_sresult sr=lsplit(&data, control_chars.separators, control_chars.encloser, sdata) ) {
                    305:                if(sr.piece->is_empty() && !sr.delim && !row->count()) // append last empty column [if without \n]
                    306:                        break;
                    307:                *row+=sr.piece;
                    308:                if(sr.delim=='\n') {
                    309:                        table+=row;
                    310:                        row=new ArrayString(columns_count);
                    311:                        skip_clean_empty_lines(&data, sdata);
                    312:                }
                    313:        }
                    314:        // last line [if without \n]
                    315:        if(row->count())
1.182     paf       316:                table+=row;
1.322     moko      317:        
1.44      paf       318:        // replace any previous table value
1.182     paf       319:        GET_SELF(r, VTable).set_table(table);
1.44      paf       320: }
                    321: 
1.187     paf       322: struct lsplit_result {
                    323:        char* piece;
                    324:        char delim;
                    325: 
1.321     moko      326:        lsplit_result(char *apiece=0) : piece(apiece), delim(0){}
1.187     paf       327:        operator bool() { return piece!=0; }
                    328: };
                    329: 
1.321     moko      330: inline lsplit_result lsplit(char* *string_ref, const char* delims) {
                    331:        lsplit_result result(*string_ref);
                    332:        if(result.piece) {
                    333:                if(char* v=strpbrk(result.piece, delims)) {
1.187     paf       334:                        result.delim=*v;
                    335:                        *v=0;
1.321     moko      336:                        *string_ref=v+1;
1.187     paf       337:                        return result;
                    338:                }
1.322     moko      339:                *string_ref=0;
1.273     misha     340:        }
                    341:        return result;
1.187     paf       342: }
                    343: 
1.320     moko      344: static lsplit_result lsplit(char** string_ref, const char* delims, char encloser) {
1.321     moko      345:        lsplit_result result(*string_ref);
1.187     paf       346: 
1.321     moko      347:        if(result.piece) {
                    348:                if(encloser && *result.piece==encloser) {
                    349:                        result.piece++;
1.187     paf       350:                        
1.321     moko      351:                        char c;
1.187     paf       352:                        char *read;
                    353:                        char *write;
1.321     moko      354:                        write=read=result.piece;
                    355: 
1.290     moko      356:                        // we are enclosed, searching for second encloser
                    357:                        while(c=*read++) {
1.187     paf       358:                                if(c==encloser) {
1.290     moko      359:                                        if(*read==encloser) // double-encloser stands for encloser
1.187     paf       360:                                                read++;
1.290     moko      361:                                        else
                    362:                                                break; // note: skipping encloser
1.187     paf       363:                                }
                    364:                                *write++=c;
                    365:                        }
1.321     moko      366: 
1.329     moko      367:                        // we are no longer enclosed, searching for delimiter
1.290     moko      368:                        while(c=*read++) {
1.320     moko      369:                                if(c==delims[0] || c==delims[1]) {
1.290     moko      370:                                        result.delim=c;
                    371:                                        break;
1.329     moko      372:                                } else 
1.290     moko      373:                                        *write++=c;
                    374:                        }
1.321     moko      375: 
1.187     paf       376:                        *write=0; // terminate
1.321     moko      377:                        *string_ref=c ? read : 0;
1.187     paf       378:                        return result;
                    379:                } else
1.320     moko      380:                        return lsplit(string_ref, delims);
1.273     misha     381:        }
                    382:        return result;
1.187     paf       383: }
                    384: 
                    385: static void skip_empty_and_comment_lines( char** data_ref ) {
1.322     moko      386:        while(*data_ref) {
                    387:                if(**data_ref == '\n'){
                    388:                        (*data_ref)++;
                    389:                } else {
                    390:                        if(**data_ref == '#' )
                    391:                                /*nowhere=*/getrow(data_ref);
                    392:                        else
                    393:                                break;
1.187     paf       394:                }
                    395:        }
                    396: }
                    397: 
1.273     misha     398: static void skip_empty_lines( char** data_ref ) {
1.322     moko      399:        if(*data_ref) {
                    400:                while(**data_ref == '\n')
                    401:                        (*data_ref)++;
1.273     misha     402:        }
                    403: }
                    404: 
                    405: typedef void (*Skip_lines_action)(char** data_ref);
                    406: 
1.182     paf       407: static void _load(Request& r, MethodParams& params) {
1.232     misha     408:        const String&  first_param=params.as_string(0, FILE_NAME_MUST_BE_STRING);
1.168     paf       409:        int filename_param_index=0;
                    410:        bool nameless=first_param=="nameless";
                    411:        if(nameless)
                    412:                filename_param_index++;
1.182     paf       413:        size_t options_param_index=filename_param_index+1;
1.186     paf       414: 
                    415:        HashStringValue *options=0;
1.319     moko      416:        TableControlChars control_chars;
1.186     paf       417:        if(options_param_index<params.count()
1.288     misha     418:                && (options=params.as_hash(options_param_index))) {
1.186     paf       419:                // cloning, so that we could change [to simplify checks on params inside file_read_text
                    420:                options=new HashStringValue(*options);
1.319     moko      421:                control_chars.load(*options);
1.186     paf       422:        }
                    423: 
1.44      paf       424:        // loading text
1.321     moko      425:        char *data=file_load_text(r, r.absolute(params.as_string(filename_param_index, FILE_NAME_MUST_BE_STRING)), true, options);
1.44      paf       426: 
1.319     moko      427:        Skip_lines_action skip_lines_action = (control_chars.separator=='#' || control_chars.encloser=='#') ? skip_empty_lines : skip_empty_and_comment_lines;
1.273     misha     428: 
1.1       paf       429:        // parse columns
1.182     paf       430:        Table::columns_type columns;
1.168     paf       431:        if(nameless) {
1.322     moko      432:                columns=0; // nameless
1.1       paf       433:        } else {
1.322     moko      434:                columns=new ArrayString;
1.1       paf       435: 
1.273     misha     436:                skip_lines_action(&data);
1.320     moko      437:                while( lsplit_result sr=lsplit(&data, control_chars.separators, control_chars.encloser) ) {
1.256     misha     438:                        *columns+=new String(sr.piece, String::L_TAINTED);
1.187     paf       439:                        if(sr.delim=='\n') 
                    440:                                break;
1.139     paf       441:                }
1.1       paf       442:        }
1.187     paf       443:        
                    444:        Table& table=*new Table(columns);
1.322     moko      445:        int columns_count=columns ? columns->count(): 0;
1.1       paf       446: 
                    447:        // parse cells
1.218     paf       448:        Table::element_type row(new ArrayString(columns_count));
1.273     misha     449:        skip_lines_action(&data);
1.320     moko      450:        while( lsplit_result sr=lsplit(&data, control_chars.separators, control_chars.encloser) ) {
1.201     paf       451:                if(!*sr.piece && !sr.delim && !row->count()) // append last empty column [if without \n]
                    452:                        break;
1.256     misha     453:                *row+=new String(sr.piece, String::L_TAINTED);
1.187     paf       454:                if(sr.delim=='\n') {
                    455:                        table+=row;
1.218     paf       456:                        row=new ArrayString(columns_count);
1.273     misha     457:                        skip_lines_action(&data);
1.1       paf       458:                }
1.187     paf       459:        }
                    460:        // last line [if without \n]
                    461:        if(row->count())
1.1       paf       462:                table+=row;
1.187     paf       463:        
1.1       paf       464:        // replace any previous table value
1.182     paf       465:        GET_SELF(r, VTable).set_table(table);
1.1       paf       466: }
1.2       paf       467: 
1.297     moko      468: #ifdef USE_STRINGSTREAM
1.269     misha     469: #include "gc_allocator.h"
                    470: 
                    471: typedef std::basic_stringstream<char, std::char_traits<char>, gc_allocator<char> > pa_stringstream;
                    472: typedef std::basic_string<char, std::char_traits<char>, gc_allocator<char> > pa_string;
                    473: 
1.298     moko      474: static void enclose( pa_stringstream& to, const String* from, char encloser ) {
1.297     moko      475:        if(from){
1.257     misha     476:                to<<encloser;
1.188     paf       477:                // while we have 'encloser'...
1.189     paf       478:                size_t pos_after=0;
1.297     moko      479:                for( size_t pos_before; (pos_before=from->pos( encloser, pos_after ))!=STRING_NOT_FOUND; pos_after=pos_before) {
1.220     paf       480:                        pos_before++; // including first encloser (and skipping it for next pos)
1.297     moko      481:                        to<<from->mid(pos_after, pos_before).cstr();
1.257     misha     482:                        to<<encloser; // doubling encloser
1.188     paf       483:                }
                    484:                // last piece
1.297     moko      485:                size_t from_length=from->length();
1.188     paf       486:                if(pos_after<from_length)
1.297     moko      487:                        to<<from->mid(pos_after, from_length).cstr();
                    488:                to<<encloser;
                    489:        } else {
                    490:                to<<encloser<<encloser;
                    491:        }
                    492: }
                    493: 
1.319     moko      494: static void table_to_csv(pa_stringstream& result, Table& table, TableControlChars& control_chars, bool output_column_names) {
1.297     moko      495:        if(output_column_names) {
                    496:                if(table.columns()) { // named table
1.319     moko      497:                        if(control_chars.encloser){
1.297     moko      498:                                for(Array_iterator<const String*> i(*table.columns()); i.has_next(); ) {
1.319     moko      499:                                        enclose( result, i.next(), control_chars.encloser );
1.297     moko      500:                                        if(i.has_next())
1.319     moko      501:                                                result<<control_chars.separator;
1.297     moko      502:                                }
                    503:                        } else {
                    504:                                for(Array_iterator<const String*> i(*table.columns()); i.has_next(); ) {
                    505:                                        result<<i.next()->cstr();
                    506:                                        if(i.has_next())
1.319     moko      507:                                                result<<control_chars.separator;
1.297     moko      508:                                }
                    509:                        }
                    510:                } else { // nameless table [we were asked to output column names]
                    511:                        if(int lsize=table.count()?table[0]->count():0)
                    512:                                for(int column=0; column<lsize; column++) {
1.319     moko      513:                                        if(control_chars.encloser) {
                    514:                                                result<<control_chars.encloser<<column<<control_chars.encloser;
1.297     moko      515:                                        } else {
                    516:                                                result<<column;
                    517:                                        }
                    518:                                        if(column<lsize-1){
1.319     moko      519:                                                result<<control_chars.separator;
1.297     moko      520:                                        }
                    521:                                }
                    522:                        else
                    523:                                result<<"empty nameless table";
                    524:                }
                    525:                result<<'\n';
                    526:        }
1.188     paf       527: 
1.297     moko      528:        // process data lines
                    529:        Array_iterator<ArrayString*> i(table);
1.319     moko      530:        if(control_chars.encloser){
1.297     moko      531:                while(i.has_next()) {
                    532:                        for(Array_iterator<const String*> c(*i.next()); c.has_next(); ) {
1.319     moko      533:                                enclose( result, c.next(), control_chars.encloser );
1.297     moko      534:                                if(c.has_next())
1.319     moko      535:                                        result<<control_chars.separator;
1.297     moko      536:                        }
                    537:                        result<<'\n';
                    538:                }
                    539:        } else {
                    540:                while(i.has_next()) {
                    541:                        for(Array_iterator<const String*> c(*i.next()); c.has_next(); ) {
                    542:                                result<<c.next()->cstr();
                    543:                                if(c.has_next())
1.319     moko      544:                                        result<<control_chars.separator;
1.297     moko      545:                        }
                    546:                        result<<'\n';
                    547:                }
                    548:        }
1.188     paf       549: }
                    550: 
1.241     misha     551: #else
                    552: 
1.298     moko      553: void enclose( String& to, const String* from, char encloser, const String* sencloser ) {
1.297     moko      554:        if(from){
1.257     misha     555:                to<<*sencloser;
1.224     misha     556:                // while we have 'encloser'...
                    557:                size_t pos_after=0;
1.297     moko      558:                for( size_t pos_before; (pos_before=from->pos( encloser, pos_after ))!=STRING_NOT_FOUND; pos_after=pos_before) {
1.224     misha     559:                        pos_before++; // including first encloser (and skipping it for next pos)
1.297     moko      560:                        to<<from->mid(pos_after, pos_before);
1.257     misha     561:                        to<<*sencloser; // doubling encloser
1.224     misha     562:                }
                    563:                // last piece
1.297     moko      564:                size_t from_length=from->length();
1.224     misha     565:                if(pos_after<from_length)
1.297     moko      566:                        to<<from->mid(pos_after, from_length);
1.257     misha     567:                to<<*sencloser;
1.297     moko      568:        } else {
                    569:                to<<*sencloser<<*sencloser;
                    570:        }
1.224     misha     571: }
                    572: 
1.319     moko      573: static void table_to_csv(String& result, Table& table, TableControlChars& control_chars, bool output_column_names) {
1.297     moko      574:        if(output_column_names) {
                    575:                if(table.columns()) { // named table
1.319     moko      576:                        if(control_chars.encloser) {
1.297     moko      577:                                for(Array_iterator<const String*> i(*table.columns()); i.has_next(); ) {
1.319     moko      578:                                        enclose( result, i.next(), control_chars.encloser, control_chars.sencloser );
1.297     moko      579:                                        if(i.has_next())
1.319     moko      580:                                                result<<*control_chars.sseparator;
1.297     moko      581:                                }
                    582:                        } else {
                    583:                                for(Array_iterator<const String*> i(*table.columns()); i.has_next(); ) {
                    584:                                        result<<*i.next();
                    585:                                        if(i.has_next())
1.319     moko      586:                                                result<<*control_chars.sseparator;
1.297     moko      587:                                }
                    588:                        }
                    589:                } else { // nameless table [we were asked to output column names]
                    590:                        if(int lsize=table.count()?table[0]->count():0)
                    591:                                for(int column=0; column<lsize; column++) {
1.319     moko      592:                                        if(control_chars.encloser) {
                    593:                                                result<<*control_chars.sencloser<<String::Body::Format(column)<<*control_chars.sencloser;
1.298     moko      594:                                        } else {
                    595:                                                result<<String::Body::Format(column);
                    596:                                        }
                    597:                                        if(column<lsize-1){
1.319     moko      598:                                                result<<*control_chars.sseparator;
1.298     moko      599:                                        }
1.297     moko      600:                                }
                    601:                        else
                    602:                                result.append_help_length("empty nameless table", 0, String::L_CLEAN);
                    603:                }
                    604:                result.append_know_length("\n", 1, String::L_CLEAN);
                    605:        }
                    606: 
                    607:        // data lines
                    608:        Array_iterator<ArrayString*> i(table);
1.319     moko      609:        if(control_chars.encloser){
1.297     moko      610:                while(i.has_next()) {
                    611:                        for(Array_iterator<const String*> c(*i.next()); c.has_next(); ) {
1.319     moko      612:                                enclose( result, c.next(), control_chars.encloser, control_chars.sencloser );
1.297     moko      613:                                if(c.has_next())
1.319     moko      614:                                        result<<*control_chars.sseparator;
1.297     moko      615:                        }
                    616:                        result.append_know_length("\n", 1, String::L_CLEAN);
                    617:                }
                    618:        } else {
                    619:                while(i.has_next()) {
                    620:                        for(Array_iterator<const String*> c(*i.next()); c.has_next(); ) {
                    621:                                result<<*c.next();
                    622:                                if(c.has_next())
1.319     moko      623:                                        result<<*control_chars.sseparator;
1.297     moko      624:                        }
                    625:                        result.append_know_length("\n", 1, String::L_CLEAN);
                    626:                }
                    627:        }
                    628: }
1.257     misha     629: #endif // don't use stringstream
1.241     misha     630: 
1.297     moko      631: 
1.241     misha     632: static void _save(Request& r, MethodParams& params) {
1.237     misha     633:        const String& first_arg=params.as_string(0, FIRST_ARG_MUST_NOT_BE_CODE);
1.188     paf       634:        size_t param_index=1;
                    635: 
                    636:        bool do_append=false;
                    637:        bool output_column_names=true;
                    638: 
                    639:        // mode?
                    640:        if(first_arg=="append")
                    641:                do_append=true;
                    642:        else if(first_arg=="nameless")
                    643:                output_column_names=false;
                    644:        else
                    645:                --param_index;
                    646: 
1.232     misha     647:        const String& file_name=params.as_string(param_index++, FILE_NAME_MUST_NOT_BE_CODE);
1.246     misha     648:        String file_spec=r.absolute(file_name);
                    649: 
                    650:        if(do_append && file_exist(file_spec))
                    651:                output_column_names=false;
1.188     paf       652: 
1.319     moko      653:        TableControlChars control_chars;
1.281     misha     654:        if(param_index<params.count())
1.288     misha     655:                if(HashStringValue* options=params.as_hash(param_index++)) {
1.319     moko      656:                        int valid_options=control_chars.load(*options);
1.281     misha     657:                        if(valid_options!=options->count())
                    658:                                throw Exception(PARSER_RUNTIME, 0, CALLED_WITH_INVALID_OPTION);
1.222     paf       659:                }
1.281     misha     660: 
1.188     paf       661:        if(param_index<params.count())
1.318     moko      662:                throw Exception(PARSER_RUNTIME, 0, "bad mode (must be nameless or append)");
1.22      paf       663: 
1.182     paf       664:        Table& table=GET_SELF(r, VTable).table();
1.31      paf       665: 
1.297     moko      666: #ifdef USE_STRINGSTREAM
1.269     misha     667:        pa_stringstream ost(std::stringstream::out);
1.257     misha     668: 
1.319     moko      669:        table_to_csv(ost, table, control_chars, output_column_names);
1.31      paf       670: 
                    671:        // write
1.269     misha     672:                pa_string data=ost.str();
1.257     misha     673:                const char* data_cstr=data.c_str();
1.267     misha     674:                file_write(r.charsets, file_spec, data_cstr, data.length(), true /* as text */, do_append);
1.241     misha     675: #else
1.257     misha     676:        String sdata;
1.224     misha     677: 
1.319     moko      678:        table_to_csv(sdata, table, control_chars, output_column_names);
1.224     misha     679: 
                    680:        // write
1.257     misha     681:                const char* data_cstr=sdata.cstr();
1.297     moko      682:        file_write(r.charsets, file_spec, data_cstr, sdata.length(), true /* as text */, do_append);
1.257     misha     683:                if(*data_cstr) // not empty (when empty it's not heap memory)
                    684:                        pa_free((void*)data_cstr); // not needed anymore
1.297     moko      685: #endif
                    686: }
                    687: 
                    688: static void _csv_string(Request& r, MethodParams& params) {
                    689:        bool output_column_names=true;
                    690:        size_t param_index=0;
                    691:        if(params.count()>0 && params[0].is_string()) {
                    692:                if(params.as_string(0, FIRST_ARG_MUST_NOT_BE_CODE)=="nameless") {
                    693:                        output_column_names=false;
                    694:                        param_index++;
                    695:                } else {
1.318     moko      696:                        throw Exception(PARSER_RUNTIME, 0, "bad mode (must be nameless)");
1.297     moko      697:                }
1.224     misha     698:        }
1.240     misha     699: 
1.319     moko      700:        TableControlChars control_chars;
1.297     moko      701:        if(param_index<params.count())
                    702:                if(HashStringValue* options=params.as_hash(param_index++)) {
1.319     moko      703:                        int valid_options=control_chars.load(*options);
1.297     moko      704:                        if(valid_options!=options->count())
                    705:                                throw Exception(PARSER_RUNTIME, 0, CALLED_WITH_INVALID_OPTION);
                    706:                }
                    707: 
                    708:        Table& table=GET_SELF(r, VTable).table();
                    709: 
                    710: #ifdef USE_STRINGSTREAM
                    711:        pa_stringstream ost(std::stringstream::out);
                    712: 
1.319     moko      713:        table_to_csv(ost, table, control_chars, output_column_names);
1.297     moko      714: 
                    715:        r.write_no_lang(*new VString(*new String(pa_strdup(ost.str().c_str()), String::L_CLEAN)));
                    716: #else
                    717:        String sdata;
                    718: 
1.319     moko      719:        table_to_csv(sdata, table, control_chars, output_column_names);
1.297     moko      720: 
                    721:        r.write_no_lang(*new VString(*new String(sdata.cstr(), String::L_CLEAN)));
                    722: #endif
1.224     misha     723: }
                    724: 
1.280     misha     725: static void _count(Request& r, MethodParams& params) {
                    726:        Table& table=GET_SELF(r, VTable).table();
                    727:        size_t result=0;
                    728:        if(params.count()) {
                    729:                const String& param=params.as_string(0, PARAMETER_MUST_BE_STRING);
                    730:                if(param == "columns")
1.310     moko      731:                        result = table.columns() ? table.columns()->count() : table.max_cells();
1.280     misha     732:                else if(param == "cells")
                    733:                        result = table.count() ? table[table.current()]->count() : 0;
                    734:                else if(param == "rows") // synonim for ^table.count[]
                    735:                        result = table.count();
                    736:                else
                    737:                        throw Exception(PARSER_RUNTIME, &param, "parameter must be 'columns', 'cells' and 'rows' only");
                    738:        } else
                    739:                result = table.count();
                    740: 
1.182     paf       741:        r.write_no_lang(*new VInt(result));
1.6       paf       742: }
                    743: 
1.182     paf       744: static void _line(Request& r, MethodParams&) {
                    745:        int result=1+GET_SELF(r, VTable).table().current();
                    746:        r.write_no_lang(*new VInt(result));
1.6       paf       747: }
                    748: 
1.182     paf       749: static void _offset(Request& r, MethodParams& params) {
                    750:        Table& table=GET_SELF(r, VTable).table();
                    751:        if(params.count()) {
1.133     paf       752:                bool absolute=false;
1.182     paf       753:                if(params.count()>1) {
                    754:                    const String&  whence=params.as_string(0, "whence must be string");
1.133     paf       755:                    if(whence=="cur")
1.134     paf       756:                                absolute=false;
1.133     paf       757:                    else if(whence=="set")
1.134     paf       758:                                absolute=true;
1.133     paf       759:                    else
1.318     moko      760:                                throw Exception(PARSER_RUNTIME, &whence, "is invalid whence, valid are 'cur' or 'set'");
1.157     paf       761:                }
1.133     paf       762:                
1.211     paf       763:                int offset=params.as_int(params.count()-1, "offset must be expression", r);
                    764:                table.offset(absolute, offset);
1.151     paf       765:        } else
1.182     paf       766:                r.write_no_lang(*new VInt(table.current()));
1.6       paf       767: }
                    768: 
1.182     paf       769: static void _menu(Request& r, MethodParams& params) {
1.263     misha     770:        InCycle temp(r);
1.221     paf       771: 
1.182     paf       772:        Value& body_code=params.as_junction(0, "body must be code");
1.7       paf       773:        
1.182     paf       774:        Value* delim_maybe_code=params.count()>1?&params[1]:0;
1.7       paf       775: 
1.182     paf       776:        Table& table=GET_SELF(r, VTable).table();
1.293     misha     777:        size_t saved_current=table.current();
1.7       paf       778: 
1.251     misha     779:        if(delim_maybe_code) { // delimiter set
1.250     misha     780:                bool need_delim=false;
1.316     moko      781:                for(size_t row=0; row<table.count(); row++) {
1.250     misha     782:                        table.set_current(row);
                    783: 
1.334   ! moko      784:                        Value& sv_processed=r.process(body_code);
1.250     misha     785:                        Request::Skip lskip=r.get_skip(); r.set_skip(Request::SKIP_NOTHING);
                    786: 
                    787:                        const String* s_processed=sv_processed.get_string();
1.251     misha     788:                        if(s_processed && !s_processed->is_empty()) { // we have body
1.250     misha     789:                                if(need_delim) // need delim & iteration produced string?
                    790:                                        r.write_pass_lang(r.process(*delim_maybe_code));
                    791:                                else
                    792:                                        need_delim=true;
                    793:                        }
                    794: 
                    795:                        r.write_pass_lang(sv_processed);
1.242     misha     796: 
1.250     misha     797:                        if(lskip==Request::SKIP_BREAK)
                    798:                                break;
                    799:                }
                    800:        } else {
1.316     moko      801:                for(size_t row=0; row<table.count(); row++) {
1.250     misha     802:                        table.set_current(row);
                    803:  
                    804:                        r.process_write(body_code);
                    805:                        Request::Skip lskip=r.get_skip(); r.set_skip(Request::SKIP_NOTHING);
                    806:  
                    807:                        if(lskip==Request::SKIP_BREAK)
                    808:                                break;
1.7       paf       809:                }
                    810:        }
1.99      parser    811:        table.set_current(saved_current);
1.7       paf       812: }
                    813: 
1.110     parser    814: #ifndef DOXYGEN
1.74      paf       815: struct Row_info {
1.166     paf       816:        Request *r;
1.74      paf       817:        Table *table;
1.182     paf       818:        Value* key_code;
                    819:        size_t key_field;
                    820:        Array<int>* value_fields;
1.315     moko      821:        Value* value_code;
1.182     paf       822:        HashStringValue* hash;
1.174     paf       823:        Table2hash_distint distinct;
1.182     paf       824:        size_t row;
1.227     misha     825:        Table2hash_value_type value_type;
1.74      paf       826: };
1.110     parser    827: #endif
1.182     paf       828: static void table_row_to_hash(Table::element_type row, Row_info *info) {
                    829:        const String* key;
                    830:        if(info->key_code) {
                    831:                info->table->set_current(info->row++); // change context row
1.334   ! moko      832:                Value& sv_processed=info->r->process(*info->key_code);
1.166     paf       833:                key=&sv_processed.as_string();
1.227     misha     834:        } else {
1.182     paf       835:                key=info->key_field<row->count()?row->get(info->key_field):0;
1.227     misha     836:        }
1.166     paf       837: 
                    838:        if(!key)
                    839:                return; // ignore rows without key [too-short-record_array if-indexed]
1.74      paf       840:                
1.243     misha     841:        bool exist=false;
                    842:        switch(info->value_type) {
                    843:                case C_STRING: {
1.317     moko      844:                        if(info->value_fields->count()){
                    845:                                size_t index=info->value_fields->get(0);
                    846:                                exist=info->hash->put_dont_replace(*key, (index < row->count()) ? new VString(*row->get(index)) : VString::empty());
                    847:                        } else {
                    848:                                exist=info->hash->put_dont_replace(*key, VString::empty());
                    849:                        }
1.243     misha     850:                        break;
1.227     misha     851:                }
1.243     misha     852:                case C_HASH: {
1.182     paf       853:                        VHash* vhash=new VHash;
                    854:                        HashStringValue& hash=vhash->hash();
                    855:                        for(Array_iterator<int> i(*info->value_fields); i.has_next(); ) {
                    856:                                size_t value_field=i.next();
                    857:                                if(value_field<row->count())
1.314     moko      858:                                        hash.put(*info->table->columns()->get(value_field), new VString(*row->get(value_field)));
1.174     paf       859:                        }
                    860: 
1.227     misha     861:                        exist=info->hash->put_dont_replace(*key, vhash);
1.243     misha     862:                        break;
1.174     paf       863:                }
1.243     misha     864:                case C_TABLE: {
                    865:                        VTable* vtable=(VTable*)info->hash->get(*key); // table exist?
1.174     paf       866:                        Table* table;
1.227     misha     867:                        if(vtable) {
1.243     misha     868:                                if(info->distinct==D_ILLEGAL) {
                    869:                                        exist=true;
                    870:                                        break;
                    871:                                }
1.174     paf       872:                                table=vtable->get_table();
1.227     misha     873:                        } else {
1.174     paf       874:                                // no? creating table of same structure as source
1.179     paf       875:                                Table::Action_options table_options(0, 0);
1.182     paf       876:                                table=new Table(*info->table, table_options/*no rows, just structure*/);
                    877:                                info->hash->put(*key, new VTable(table));
1.174     paf       878:                        }
1.308     moko      879:                        Table::element_type row_copy(new ArrayString(row->count()));
                    880:                        row_copy->append(*row);
                    881:                        *table+=row_copy;
1.243     misha     882:                        break;
1.174     paf       883:                }
1.315     moko      884:                case C_CODE: {
                    885:                        if(!info->key_code)
                    886:                                info->table->set_current(info->row++); // change context row
1.334   ! moko      887:                        exist=info->hash->put_dont_replace(*key, &info->r->process(*info->value_code));
1.315     moko      888:                        break;
                    889:                }
1.74      paf       890:        }
1.227     misha     891:        if(exist && info->distinct==D_ILLEGAL)
1.314     moko      892:                throw Exception(PARSER_RUNTIME, key, "duplicate key");
1.74      paf       893: }
1.235     misha     894: 
                    895: Table2hash_value_type get_value_type(Value& vvalue_type){
                    896:        if(vvalue_type.is_string()) {
                    897:                const String& svalue_type=*vvalue_type.get_string();
                    898:                if(svalue_type == "table"){
                    899:                        return C_TABLE;
                    900:                } else if (svalue_type == "string") {
                    901:                        return C_STRING;
                    902:                } else if (svalue_type == "hash") {
                    903:                        return C_HASH;
                    904:                } else {
1.314     moko      905:                        throw Exception(PARSER_RUNTIME, &svalue_type, "must be 'hash', 'table' or 'string'");
1.235     misha     906:                }
                    907:        } else {
1.314     moko      908:                throw Exception(PARSER_RUNTIME, 0, "'type' must be string");
1.235     misha     909:        }
                    910: }
                    911: 
1.315     moko      912: static Table2hash_distint get_distinct(Value& vdistinct, Table2hash_value_type& value_type){
                    913:        if(vdistinct.is_string()) {
                    914:                const String& sdistinct=*vdistinct.get_string();
                    915:                if(sdistinct!="tables")
                    916:                        throw Exception(PARSER_RUNTIME, &sdistinct, "must be 'tables' or true/false");
                    917:                value_type=C_TABLE;
                    918:                return D_FIRST;
                    919:        }
                    920:        return vdistinct.as_bool() ? D_FIRST : D_ILLEGAL;
                    921: }
                    922: 
1.182     paf       923: static void _hash(Request& r, MethodParams& params) {
                    924:        Table& self_table=GET_SELF(r, VTable).table();
                    925:        VHash& result=*new VHash;
1.238     misha     926:        if(Table::columns_type columns=self_table.columns()){
1.182     paf       927:                if(columns->count()>0) {
1.174     paf       928:                        Table2hash_distint distinct=D_ILLEGAL;
1.227     misha     929:                        Table2hash_value_type value_type=C_HASH;
1.182     paf       930:                        int param_index=params.count()-1;
1.166     paf       931:                        if(param_index>0) {
1.315     moko      932: 
                    933:                                if(params[1].get_junction())
                    934:                                        value_type=C_CODE;
                    935: 
                    936:                                if(HashStringValue* options=params[param_index].get_hash()){ // can't use .as_hash because the 2nd param could be table so .as_hash throws an error
1.166     paf       937:                                        --param_index;
                    938:                                        int valid_options=0;
1.238     misha     939:                                        if(Value* vdistinct_code=options->get(sql_distinct_name)) { // $.distinct ?
1.166     paf       940:                                                valid_options++;
1.315     moko      941:                                                distinct=get_distinct(r.process_to_value(*vdistinct_code), value_type);
1.166     paf       942:                                        }
1.238     misha     943:                                        if(Value* vvalue_type_code=options->get(sql_value_type_name)) { // $.type ?
                    944:                                                if(value_type==C_TABLE) // $.distinct[tables] already was specified
1.314     moko      945:                                                        throw Exception(PARSER_RUNTIME, 0, "you can't specify $.distinct[tables] and $.type[] together");
1.315     moko      946:                                                if(value_type==C_CODE)
                    947:                                                        throw Exception(PARSER_RUNTIME, 0, "you can't specify $.type[] if value is code");
1.238     misha     948:                                                valid_options++;
                    949:                                                value_type=get_value_type(r.process_to_value(*vvalue_type_code));
                    950:                                        }
1.226     misha     951: 
1.182     paf       952:                                        if(valid_options!=options->count())
1.272     misha     953:                                                throw Exception(PARSER_RUNTIME, 0, CALLED_WITH_INVALID_OPTION);
1.163     paf       954:                                }
                    955:                        }
1.238     misha     956: 
1.315     moko      957:                        if(param_index==2) // options were specified but not as hash
1.289     misha     958:                                throw Exception(PARSER_RUNTIME, 0, "options must be hash");
                    959: 
1.182     paf       960:                        Array<int> value_fields;
1.315     moko      961:                        Value* value_code=0;
                    962: 
1.238     misha     963:                        if(param_index==0){ // list of columns wasn't specified
                    964:                                if(value_type==C_STRING) // $.type[string]
1.314     moko      965:                                        throw Exception(PARSER_RUNTIME, 0, "you must specify one value field with option $.type[string]");
1.238     misha     966:                                
                    967:                                for(size_t i=0; i<columns->count(); i++) // by all columns, including key
                    968:                                        value_fields+=i;
                    969: 
1.315     moko      970:                        } else { // list of columns or code was specified
1.227     misha     971:                                if(value_type==C_TABLE)
1.314     moko      972:                                        throw Exception(PARSER_RUNTIME, 0, "you can't specify value field(s) with option $.distinct[tables] or $.type[tables]");
1.238     misha     973: 
1.315     moko      974:                                Value& value_fields_param=params[1];
1.317     moko      975:                                if(value_fields_param.get_junction()){ // code specified
1.315     moko      976:                                        value_code=&value_fields_param;
                    977:                                } else if(value_fields_param.is_string()) { // one column as string was specified
1.317     moko      978:                                        const String &field_name=*value_fields_param.get_string();
                    979:                                        if(!field_name.is_empty())
                    980:                                                value_fields+=self_table.column_name2index(field_name, true);
1.238     misha     981:                                } else if(Table* value_fields_table=value_fields_param.get_table()) { // list of columns were specified in table
                    982:                                        for(Array_iterator<Table::element_type> i(*value_fields_table); i.has_next(); ) {
                    983:                                                const String& value_field_name =*i.next()->get(0);
                    984:                                                value_fields +=self_table.column_name2index(value_field_name, true);
1.123     parser    985:                                        }
                    986:                                } else
1.315     moko      987:                                        throw Exception(PARSER_RUNTIME, 0, "value field(s) must be string or table or code");
1.239     misha     988:                        }
1.74      paf       989: 
1.227     misha     990:                        if(value_type==C_STRING && value_fields.count()!=1)
1.314     moko      991:                                throw Exception(PARSER_RUNTIME, 0, "you can specify only one value field with option $.type[string]");
1.182     paf       992: 
                    993:                        {
                    994:                                Value* key_param=&params[0];
1.193     paf       995:                                Row_info info={
                    996:                                        &r,
                    997:                                        &self_table,
1.315     moko      998:                                        /*key_code=*/key_param->get_junction() ? key_param : 0,
1.197     paf       999:                                        /*key_field=*/0/*filled below*/,
1.193     paf      1000:                                        &value_fields,
1.315     moko     1001:                                        value_code,
1.193     paf      1002:                                        &result.hash(),
                   1003:                                        distinct,
1.227     misha    1004:                                        /*row=*/0,
                   1005:                                        value_type
1.193     paf      1006:                                };
1.314     moko     1007:                                info.key_field=(info.key_code ? -1 : self_table.column_name2index(key_param->as_string(), true));
1.182     paf      1008: 
                   1009:                                int saved_current=self_table.current();
                   1010:                                self_table.for_each(table_row_to_hash, &info);
                   1011:                                self_table.set_current(saved_current);
1.207     paf      1012: 
                   1013:                                result.extract_default();
1.182     paf      1014:                        }
1.74      paf      1015:                }
1.238     misha    1016:        }
1.97      parser   1017:        r.write_no_lang(result);
1.74      paf      1018: }
                   1019: 
1.110     parser   1020: #ifndef DOXYGEN
1.78      paf      1021: struct Table_seq_item {
1.182     paf      1022:        ArrayString* row;
1.34      paf      1023:        union {
1.182     paf      1024:                const char *c_str;
1.34      paf      1025:                double d;
                   1026:        } value;
1.32      paf      1027: };
1.110     parser   1028: #endif
1.34      paf      1029: static int sort_cmp_string(const void *a, const void *b) {
                   1030:        return strcmp(
1.78      paf      1031:                static_cast<const Table_seq_item *>(a)->value.c_str, 
                   1032:                static_cast<const Table_seq_item *>(b)->value.c_str
1.34      paf      1033:        );
                   1034: }
                   1035: static int sort_cmp_double(const void *a, const void *b) {
1.78      paf      1036:        double va=static_cast<const Table_seq_item *>(a)->value.d;
                   1037:        double vb=static_cast<const Table_seq_item *>(b)->value.d;
1.34      paf      1038:        if(va<vb)
                   1039:                return -1;
                   1040:        else if(va>vb)
                   1041:                return +1;
                   1042:        else 
                   1043:                return 0;
                   1044: }
1.182     paf      1045: static void _sort(Request& r, MethodParams& params) {
                   1046:        Value& key_maker=params.as_junction(0, "key-maker must be code");
1.61      paf      1047: 
1.182     paf      1048:        bool reverse=params.count()>1/*..[desc|asc|]*/?
                   1049:                reverse=params.as_no_junction(1, "order must not be code").as_string()=="desc":
1.104     parser   1050:                false; // default=asc
1.32      paf      1051: 
1.182     paf      1052:        Table& old_table=GET_SELF(r, VTable).table();
                   1053:        Table& new_table=*new Table(old_table.columns());
1.34      paf      1054: 
1.182     paf      1055:        Table_seq_item* seq=new(PointerFreeGC) Table_seq_item[old_table.count()];
1.34      paf      1056:        int i;
                   1057: 
                   1058:        // calculate key values
                   1059:        bool key_values_are_strings=true;
1.182     paf      1060:        int old_count=old_table.count();
                   1061:        for(i=0; i<old_count; i++) {
1.101     parser   1062:                old_table.set_current(i);
1.32      paf      1063:                // calculate key value
1.182     paf      1064:                seq[i].row=old_table[i];
1.287     moko     1065:                Value& value=r.process_to_value(key_maker);
1.34      paf      1066:                if(i==0) // determining key values type by first one
                   1067:                        key_values_are_strings=value.is_string();
                   1068: 
                   1069:                if(key_values_are_strings)
                   1070:                        seq[i].value.c_str=value.as_string().cstr();
                   1071:                else
1.287     moko     1072:                        seq[i].value.d=value.as_expr_result().as_double();
1.32      paf      1073:        }
1.265     misha    1074: 
                   1075:        // @todo: handle this elsewhere
                   1076:        if(r.charsets.source().NAME()=="KOI8-R" && key_values_are_strings) {
                   1077:                for(i=0; i<old_count; i++)
                   1078:                        if(*seq[i].value.c_str)
1.332     moko     1079:                                seq[i].value.c_str=Charset::transcode(seq[i].value.c_str, r.charsets.source(), pa_UTF8_charset).cstr();
1.265     misha    1080:        }
                   1081: 
1.266     misha    1082:        // sort keys
1.295     moko     1083:        qsort(seq, old_count, sizeof(Table_seq_item), key_values_are_strings?sort_cmp_string:sort_cmp_double);
1.32      paf      1084: 
1.34      paf      1085:        // reorder table as they require in 'seq'
1.182     paf      1086:        for(i=0; i<old_count; i++)
                   1087:                new_table+=Table::element_type(seq[reverse?old_count-1-i:i].row);
                   1088: 
                   1089:        delete[] seq;
1.32      paf      1090: 
1.116     parser   1091:        // replace any previous table value
1.182     paf      1092:        GET_SELF(r, VTable).set_table(new_table);
1.32      paf      1093: }
                   1094: 
1.176     paf      1095: #ifndef DOXYGEN
1.182     paf      1096: struct Expression_is_true_info {
1.176     paf      1097:        Request* r;
                   1098:        Value* expression_code;
                   1099: };
                   1100: #endif
1.275     misha    1101: 
1.191     paf      1102: static bool expression_is_true(Table&, Expression_is_true_info* info) {
                   1103:        return info->r->process_to_value(*info->expression_code).as_bool();
1.176     paf      1104: }
1.275     misha    1105: 
                   1106: static bool _locate_expression(Table& table, Request& r, MethodParams& params) {
1.182     paf      1107:        Value& expression_code=params.as_junction(0, "must be expression");
1.303     moko     1108:        Table::Action_options o=get_action_options(r, params, 1, table);
                   1109:        if(params.count()>2)
                   1110:                throw Exception(PARSER_RUNTIME, 0, "locate by expression only has parameters: expression and, maybe, options");
1.182     paf      1111:        Expression_is_true_info info={&r, &expression_code};
                   1112:        return table.table_first_that(expression_is_true, &info, o);
1.145     paf      1113: }
1.275     misha    1114: 
                   1115: static bool _locate_name_value(Table& table, Request& r, MethodParams& params) {
1.182     paf      1116:        const String& name=params.as_string(0, "column name must be string");
1.232     misha    1117:        const String& value=params.as_string(1, VALUE_MUST_BE_STRING);
1.303     moko     1118:        Table::Action_options o=get_action_options(r, params, 2, table);
1.182     paf      1119:        return table.locate(name, value, o);
                   1120: }
1.275     misha    1121: 
1.182     paf      1122: static void _locate(Request& r, MethodParams& params) {
                   1123:        Table& table=GET_SELF(r, VTable).table();
1.72      paf      1124: 
1.291     moko     1125:        bool result=params[0].get_junction() || (params.count() == 1) ?
1.275     misha    1126:                _locate_expression(table, r, params) :
                   1127:                _locate_name_value(table, r, params);
1.249     misha    1128:        r.write_no_lang(VBool::get(result));
1.145     paf      1129: }
1.182     paf      1130: 
                   1131: 
1.191     paf      1132: static void _flip(Request& r, MethodParams&) {
1.182     paf      1133:        Table& old_table=GET_SELF(r, VTable).table();
1.184     paf      1134:        Table& new_table=*new Table(0);
1.182     paf      1135:        if(size_t old_count=old_table.count())
1.310     moko     1136:                if(size_t old_cols=old_table.columns()?old_table.columns()->count():old_table.max_cells())
1.182     paf      1137:                        for(size_t column=0; column<old_cols; column++) {
                   1138:                                Table::element_type new_row(new ArrayString(old_count));
                   1139:                                for(size_t i=0; i<old_count; i++) {
                   1140:                                        Table::element_type old_row=old_table[i];
                   1141:                                        *new_row+=column<old_row->count()?old_row->get(column):new String;
1.39      paf      1142:                                }
1.182     paf      1143:                                new_table+=new_row;
1.39      paf      1144:                        }
                   1145: 
1.182     paf      1146:        r.write_no_lang(*new VTable(&new_table));
1.39      paf      1147: }
                   1148: 
1.293     misha    1149: static void _foreach(Request& r, MethodParams& params) {
                   1150:        InCycle temp(r);
                   1151: 
1.331     moko     1152:        const String* rownum_var_name=&params.as_string(0, "rownum-var name must be string");
                   1153:        const String* value_var_name=&params.as_string(1, "value-var name must be string");
1.293     misha    1154: 
                   1155:        Value& body_code=params.as_junction(2, "body must be code");
                   1156:        
                   1157:        Value* delim_maybe_code=params.count()>3?&params[3]:0;
                   1158: 
                   1159:        Table& table=GET_SELF(r, VTable).table();
                   1160:        size_t saved_current=table.current();
                   1161: 
1.331     moko     1162:        rownum_var_name=rownum_var_name->is_empty()? 0 : rownum_var_name;
                   1163:        value_var_name=value_var_name->is_empty()? 0 : value_var_name;
1.293     misha    1164: 
                   1165:        Value* var_context=r.get_method_frame()->caller();
                   1166: 
                   1167:        if(delim_maybe_code) { // delimiter set
                   1168:                bool need_delim=false;
1.316     moko     1169:                for(size_t row=0; row<table.count(); row++) {
1.293     misha    1170:                        table.set_current(row);
                   1171: 
                   1172:                        if(rownum_var_name)
1.299     moko     1173:                                r.put_element(*var_context, *rownum_var_name, new VString(*new String(String::Body::Format(row), String::L_CLEAN)));
1.293     misha    1174:                        if(value_var_name)
1.299     moko     1175:                                r.put_element(*var_context, *value_var_name, new VTable(&table));
1.293     misha    1176: 
1.334   ! moko     1177:                        Value& sv_processed=r.process(body_code);
1.293     misha    1178:                        Request::Skip lskip=r.get_skip(); r.set_skip(Request::SKIP_NOTHING);
                   1179: 
                   1180:                        const String* s_processed=sv_processed.get_string();
                   1181:                        if(s_processed && !s_processed->is_empty()) { // we have body
                   1182:                                if(need_delim) // need delim & iteration produced string?
                   1183:                                        r.write_pass_lang(r.process(*delim_maybe_code));
                   1184:                                else
                   1185:                                        need_delim=true;
                   1186:                        }
                   1187: 
                   1188:                        r.write_pass_lang(sv_processed);
                   1189: 
                   1190:                        if(lskip==Request::SKIP_BREAK)
                   1191:                                break;
                   1192:                }
                   1193:        } else {
1.316     moko     1194:                for(size_t row=0; row<table.count(); row++) {
1.293     misha    1195:                        table.set_current(row);
                   1196:  
                   1197:                        if(rownum_var_name)
1.300     moko     1198:                                r.put_element(*var_context, *rownum_var_name, new VString(*new String(String::Body::Format(row), String::L_CLEAN)));
1.293     misha    1199:                        if(value_var_name)
1.300     moko     1200:                                r.put_element(*var_context, *value_var_name, new VTable(&table));
1.293     misha    1201: 
                   1202:                        r.process_write(body_code);
                   1203:                        Request::Skip lskip=r.get_skip(); r.set_skip(Request::SKIP_NOTHING);
                   1204:  
                   1205:                        if(lskip==Request::SKIP_BREAK)
                   1206:                                break;
                   1207:                }
                   1208:        }
                   1209:        table.set_current(saved_current);
                   1210: }
                   1211: 
1.309     moko     1212: static void update_cell(HashStringValue::key_type aname, HashStringValue::value_type avalue, VTable *dest) {
                   1213:        dest->put_element(String(aname, String::L_CLEAN), avalue); // new not required
                   1214: }
                   1215: 
                   1216: inline Table::element_type row_from_string(Request& r, Value &param){
                   1217:        if(!param.is_string() && !param.get_junction())
                   1218:                throw Exception(PARSER_RUNTIME, 0, "row must be string, code or hash");
                   1219: 
1.182     paf      1220:        Temp_lang temp_lang(r, String::L_PASS_APPENDED);
1.309     moko     1221:        const String& string=r.process_to_string(param);
1.41      paf      1222: 
                   1223:        // parse cells
1.182     paf      1224:        Table::element_type row=new ArrayString;
1.326     moko     1225:        string.split(*row, 0, "\t", String::L_AS_IS);
1.41      paf      1226: 
1.309     moko     1227:        return row;
1.41      paf      1228: }
                   1229: 
1.309     moko     1230: static void _append(Request& r, MethodParams& params) {
                   1231:        VTable vtable=GET_SELF(r, VTable);
                   1232:        Table& table=vtable.table();
1.306     moko     1233: 
1.309     moko     1234:        HashStringValue* hash=params[0].get_hash();
                   1235:        if(hash){
                   1236:                table+=new ArrayString();
                   1237:                size_t saved_current=table.current();
                   1238:                table.set_current(table.count()-1);
                   1239:                hash->for_each<VTable*>(update_cell, &vtable);
                   1240:                table.set_current(saved_current);
                   1241:        } else {
                   1242:                table+=row_from_string(r, params[0]);
                   1243:        }
                   1244: }
1.306     moko     1245: 
1.309     moko     1246: static void _insert(Request& r, MethodParams& params) {
                   1247:        VTable vtable=GET_SELF(r, VTable);
                   1248:        Table& table=vtable.table();
                   1249:        HashStringValue* hash=params[0].get_hash();
                   1250:        if(hash){
                   1251:                table.insert(table.current(), new ArrayString());
                   1252:                hash->for_each<VTable*>(update_cell, &vtable);
                   1253:        } else {
                   1254:                table.insert(table.current(), row_from_string(r, params[0]));
                   1255:        }
1.306     moko     1256: }
                   1257: 
1.311     moko     1258: static void _delete(Request& r, MethodParams&) {
1.307     moko     1259:        Table& table=GET_SELF(r, VTable).table();
                   1260:        table.remove_current();
                   1261: }
                   1262: 
1.182     paf      1263: static void join_named_row(Table& src, Table* dest) {
                   1264:        Table::columns_type dest_columns=dest->columns();
                   1265:        size_t dest_columns_count=dest_columns->count();
                   1266:        Table::element_type dest_row(new ArrayString(dest_columns_count));
                   1267:        for(size_t dest_column=0; dest_column<dest_columns_count; dest_column++) {
                   1268:                const String* src_item=src.item(*dest_columns->get(dest_column));
                   1269:                *dest_row+=src_item?src_item:new String;
                   1270:        }
                   1271:        *dest+=dest_row;
                   1272: }
                   1273: static void join_nameless_row(Table& src, Table* dest) {
                   1274:        *dest+=src[src.current()];
                   1275: }
                   1276: static void _join(Request& r, MethodParams& params) {
1.288     misha    1277:        Table& src=*params.as_table(0, "source");
1.176     paf      1278: 
1.268     misha    1279:        Table::Action_options o=get_action_options(r, params, 1, src);
1.42      paf      1280: 
1.182     paf      1281:        Table& dest=GET_SELF(r, VTable).table();
1.42      paf      1282:        if(&src == &dest)
1.318     moko     1283:                throw Exception(PARSER_RUNTIME, 0, "source and destination are same table");
1.42      paf      1284: 
1.193     paf      1285:        if(dest.columns()) // dest is named
1.182     paf      1286:                src.table_for_each(join_named_row, &dest, o);
                   1287:        else // dest is nameless
                   1288:                src.table_for_each(join_nameless_row, &dest, o);
1.42      paf      1289: }
                   1290: 
1.94      parser   1291: #ifndef DOXYGEN
1.169     paf      1292: class Table_sql_event_handlers: public SQL_Driver_query_event_handlers {
1.182     paf      1293:        ArrayString& columns;
1.218     paf      1294:        int columns_count;
1.182     paf      1295:        ArrayString* row;
1.94      parser   1296: public:
1.182     paf      1297:        Table* table;
                   1298: public:
                   1299:        Table_sql_event_handlers() :
                   1300:                columns(*new ArrayString), row(0), table(0) {
1.94      parser   1301:        }
                   1302: 
1.279     misha    1303:        bool add_column(SQL_Error& error, const char *str, size_t ) {
1.170     paf      1304:                try {
1.274     moko     1305:                        columns+=new String(str, String::L_TAINTED /* no length as 0x00 can be inside */);
1.170     paf      1306:                        return false;
                   1307:                } catch(...) {
                   1308:                        error=SQL_Error("exception occured in Table_sql_event_handlers::add_column");
                   1309:                        return true;
                   1310:                }
                   1311:        }
                   1312:        bool before_rows(SQL_Error& error) { 
                   1313:                try {
1.182     paf      1314:                        table=new Table(&columns);
1.218     paf      1315:                        columns_count=columns.count();
1.170     paf      1316:                        return false;
                   1317:                } catch(...) {
                   1318:                        error=SQL_Error("exception occured in Table_sql_event_handlers::before_rows");
                   1319:                        return true;
                   1320:                }
                   1321:        }
                   1322:        bool add_row(SQL_Error& error) {
                   1323:                try {
1.218     paf      1324:                        *table+=row=new ArrayString(columns_count);
1.170     paf      1325:                        return false;
                   1326:                } catch(...) {
                   1327:                        error=SQL_Error("exception occured in Table_sql_event_handlers::add_row");
                   1328:                        return true;
                   1329:                }
                   1330:        }
1.279     misha    1331:        bool add_row_cell(SQL_Error& error, const char* str, size_t ) {
1.170     paf      1332:                try {
1.292     misha    1333:                        *row+=str?new String(str, String::L_TAINTED /* no length as 0x00 can be inside */):&String::Empty;
1.170     paf      1334:                        return false;
                   1335:                } catch(...) {
                   1336:                        error=SQL_Error("exception occured in Table_sql_event_handlers::add_row_cell");
                   1337:                        return true;
                   1338:                }
1.94      parser   1339:        }
                   1340: };
                   1341: #endif
1.204     paf      1342: 
                   1343: static void marshal_bind(
                   1344:                                                 HashStringValue::key_type aname, 
                   1345:                                                 HashStringValue::value_type avalue,
                   1346:                                                 SQL_Driver::Placeholder** pptr) 
                   1347: {
                   1348:        SQL_Driver::Placeholder& ph=**pptr;
                   1349:        ph.name=aname.cstr();
1.261     misha    1350:        ph.value=avalue->as_string().untaint_cstr(String::L_AS_IS);
1.204     paf      1351:        ph.is_null=avalue->get_class()==void_class;
                   1352:        ph.were_updated=false;
                   1353: 
                   1354:        (*pptr)++;
                   1355: }
                   1356: 
                   1357: // not static, used elsewhere
                   1358: int marshal_binds(HashStringValue& hash, SQL_Driver::Placeholder*& placeholders) {
                   1359:        int hash_count=hash.count();
1.302     moko     1360:        placeholders=new SQL_Driver::Placeholder[hash_count];
1.204     paf      1361:        SQL_Driver::Placeholder* ptr=placeholders;
1.221     paf      1362:        hash.for_each<SQL_Driver::Placeholder**>(marshal_bind, &ptr);
1.204     paf      1363:        return hash_count;
                   1364: }
                   1365: 
                   1366: // not static, used elsewhere
                   1367: void unmarshal_bind_updates(HashStringValue& hash, int placeholder_count, SQL_Driver::Placeholder* placeholders) {
                   1368:        SQL_Driver::Placeholder* ph=placeholders;
                   1369:        for(int i=0; i<placeholder_count; i++, ph++)
                   1370:                if(ph->were_updated) {
                   1371:                        Value* value;
                   1372:                        if(ph->is_null)
1.248     misha    1373:                                value=VVoid::get();
1.204     paf      1374:                        else
1.256     misha    1375:                                value=new VString(*new String(ph->value, String::L_TAINTED));
1.204     paf      1376:                        hash.put(ph->name, value);
                   1377:                }
                   1378: }
                   1379: 
1.182     paf      1380: static void _sql(Request& r, MethodParams& params) {
                   1381:        Value& statement=params.as_junction(0, "statement must be code");
1.49      paf      1382: 
1.204     paf      1383:        HashStringValue* bind=0;
1.244     misha    1384:        ulong limit=SQL_NO_LIMIT;
1.100     parser   1385:        ulong offset=0;
1.281     misha    1386:        if(params.count()>1)
1.288     misha    1387:                if(HashStringValue* options=params.as_hash(1, "sql options")) {
1.281     misha    1388:                        int valid_options=0;
                   1389:                        if(Value* vbind=options->get(sql_bind_name)) {
                   1390:                                valid_options++;
                   1391:                                bind=vbind->get_hash();
                   1392:                        }
                   1393:                        if(Value* vlimit=options->get(sql_limit_name)) {
                   1394:                                valid_options++;
                   1395:                                limit=(ulong)r.process_to_value(*vlimit).as_double();
                   1396:                        }
                   1397:                        if(Value* voffset=options->get(sql_offset_name)) {
                   1398:                                valid_options++;
                   1399:                                offset=(ulong)r.process_to_value(*voffset).as_double();
                   1400:                        }
                   1401:                        if(valid_options!=options->count())
                   1402:                                throw Exception(PARSER_RUNTIME, 0, CALLED_WITH_INVALID_OPTION);
                   1403:                }
1.49      paf      1404: 
1.204     paf      1405:        SQL_Driver::Placeholder* placeholders=0;
                   1406:        uint placeholders_count=0;
                   1407:        if(bind)
                   1408:                placeholders_count=marshal_binds(*bind, placeholders);
                   1409: 
1.182     paf      1410:        Temp_lang temp_lang(r, String::L_SQL);
                   1411:        const String&  statement_string=r.process_to_string(statement);
1.262     misha    1412:        const char* statement_cstr=statement_string.untaint_cstr(r.flang, r.connection());
1.260     misha    1413: 
1.182     paf      1414:        Table_sql_event_handlers handlers;
1.294     moko     1415: 
1.182     paf      1416:        r.connection()->query(
1.203     paf      1417:                statement_cstr, 
1.208     paf      1418:                placeholders_count, placeholders,
1.203     paf      1419:                offset, limit, 
1.160     paf      1420:                handlers,
                   1421:                statement_string);
1.135     paf      1422:        
1.204     paf      1423:        if(bind)
                   1424:                unmarshal_bind_updates(*bind, placeholders_count, placeholders);
1.96      parser   1425: 
1.182     paf      1426:        Table& result=
                   1427:                handlers.table?*handlers.table: // query resulted in table? return it
                   1428:                *new Table(Table::columns_type(0)); // query returned no table, fake it
1.49      paf      1429: 
                   1430:        // replace any previous table value
1.182     paf      1431:        GET_SELF(r, VTable).set_table(result);
1.49      paf      1432: }
                   1433: 
1.233     misha    1434: static void _columns(Request& r, MethodParams& params) {
                   1435:        const String* column_column_name;
                   1436:        if(params.count()>0)
                   1437:                column_column_name=&params.as_string(0, COLUMN_NAME_MUST_BE_STRING);
                   1438:        else 
                   1439:                column_column_name=new String("column");
1.88      parser   1440: 
1.182     paf      1441:        Table::columns_type result_columns(new ArrayString);
1.233     misha    1442:        *result_columns+=column_column_name;
1.182     paf      1443:        Table& result_table=*new Table(result_columns);
1.88      parser   1444: 
1.182     paf      1445:        Table& source_table=GET_SELF(r, VTable).table();
                   1446:        if(Table::columns_type source_columns=source_table.columns()) {
                   1447:                for(Array_iterator<const String*> i(*source_columns); i.has_next(); ) {
                   1448:                        Table::element_type result_row(new ArrayString);
                   1449:                        *result_row+=i.next();
                   1450:                        result_table+=result_row;
1.88      parser   1451:                }
                   1452:        }
                   1453: 
1.182     paf      1454:        r.write_no_lang(*new VTable(&result_table));
1.88      parser   1455: }
                   1456: 
1.182     paf      1457: static void _select(Request& r, MethodParams& params) {
1.231     misha    1458:        Value& vcondition=params.as_expression(0, "condition must be number, bool or expression");
1.148     paf      1459: 
1.182     paf      1460:        Table& source_table=GET_SELF(r, VTable).table();
1.148     paf      1461: 
1.277     moko     1462:        int limit=source_table.count();
1.282     misha    1463:        int offset=0;
                   1464:        bool reverse=false;
1.278     moko     1465:        
1.281     misha    1466:        if(params.count()>1)
                   1467:                if(HashStringValue* options=params.as_hash(1)) {
                   1468:                        int valid_options=0;
                   1469:                        if(Value* vlimit=options->get(sql_limit_name)) {
                   1470:                                valid_options++;
                   1471:                                limit=r.process_to_value(*vlimit).as_int();
                   1472:                        }
                   1473:                        if(Value* voffset=options->get(sql_offset_name)) {
                   1474:                                valid_options++;
                   1475:                                offset=r.process_to_value(*voffset).as_int();
                   1476:                        }
                   1477:                        if(Value* vreverse=options->get(table_reverse_name)) {
                   1478:                                valid_options++;
                   1479:                                reverse=r.process_to_value(*vreverse).as_bool();
                   1480:                        }
                   1481:                        if(valid_options!=options->count())
1.288     misha    1482:                                throw Exception(PARSER_RUNTIME, 0, CALLED_WITH_INVALID_OPTION);
1.281     misha    1483:                }
                   1484: 
                   1485:        Table& result_table=*new Table(source_table.columns());
1.277     moko     1486: 
1.283     misha    1487:        size_t size=source_table.count();
                   1488:        if(offset<0)
                   1489:                offset+=size;
1.284     misha    1490:        if(size && limit>0 && offset>=0 && (size_t)offset<size){
1.282     misha    1491:                size_t saved_current=source_table.current();
                   1492:                size_t appended=0;
                   1493: 
                   1494:                if(reverse){
                   1495:                        for(size_t row=size-1; result_table.count() < (size_t)limit; row--) {
                   1496:                                source_table.set_current(row);
                   1497: 
                   1498:                                bool condition=r.process_to_value(vcondition, false/*don't intercept string*/).as_bool();
                   1499: 
                   1500:                                if(condition && ++appended > (size_t)offset) // ...condition is true, adding to the result
                   1501:                                        result_table+=source_table[row];
                   1502:                                if(row==0) break;
                   1503:                        }
                   1504:                } else {
                   1505:                        for(size_t row=0; row < size && result_table.count() < (size_t)limit; row++) {
                   1506:                                source_table.set_current(row);
1.148     paf      1507: 
1.282     misha    1508:                                bool condition=r.process_to_value(vcondition, false/*don't intercept string*/).as_bool();
1.277     moko     1509: 
1.282     misha    1510:                                if(condition && ++appended > (size_t)offset) // ...condition is true, adding to the result
                   1511:                                        result_table+=source_table[row];
                   1512:                        }
1.277     moko     1513:                }
1.282     misha    1514:                source_table.set_current(saved_current);
1.148     paf      1515:        }
                   1516: 
1.182     paf      1517:        r.write_no_lang(*new VTable(&result_table));
1.148     paf      1518: }
                   1519: 
1.66      paf      1520: // constructor
                   1521: 
1.182     paf      1522: MTable::MTable(): Methoded("table") {
1.142     paf      1523:        // ^table::create{data}
                   1524:        // ^table::create[nameless]{data}
                   1525:        // ^table::create[table]
1.236     misha    1526:        add_native_method("create", Method::CT_DYNAMIC, _create, 1, 3);
1.142     paf      1527:        // old name for compatibility with <= v 1.141 2002/01/25 11:33:45 paf
1.236     misha    1528:        add_native_method("set", Method::CT_DYNAMIC, _create, 1, 3); 
1.2       paf      1529: 
1.142     paf      1530:        // ^table::load[file]  
                   1531:        // ^table::load[nameless;file]
1.168     paf      1532:        add_native_method("load", Method::CT_DYNAMIC, _load, 1, 3);
1.22      paf      1533: 
                   1534:        // ^table.save[file]  
                   1535:        // ^table.save[nameless;file]
1.188     paf      1536:        add_native_method("save", Method::CT_DYNAMIC, _save, 1, 3);
1.6       paf      1537: 
1.224     misha    1538:        // add_native_method("save_old", Method::CT_DYNAMIC, _save_old, 1, 3);
                   1539: 
1.297     moko     1540:        // ^table.csv-string[]
                   1541:        // ^table.csv-string[nameless]
                   1542:        // ^table.csv-string[nameless;$.encloser["] $.separator[,]]
                   1543:        add_native_method("csv-string", Method::CT_DYNAMIC, _csv_string, 0, 2);
                   1544: 
1.6       paf      1545:        // ^table.count[]
1.280     misha    1546:        // ^table.count[rows]
                   1547:        // ^table.count[columns]
                   1548:        // ^table.count[cells]
                   1549:        add_native_method("count", Method::CT_DYNAMIC, _count, 0, 1);
1.6       paf      1550: 
                   1551:        // ^table.line[]
1.66      paf      1552:        add_native_method("line", Method::CT_DYNAMIC, _line, 0, 0);
1.6       paf      1553: 
1.10      paf      1554:        // ^table.offset[]  
1.133     paf      1555:        // ^table.offset(offset)
                   1556:        // ^table.offset[cur|set](offset)
                   1557:        add_native_method("offset", Method::CT_DYNAMIC, _offset, 0, 2);
1.7       paf      1558: 
1.10      paf      1559:        // ^table.menu{code}  
                   1560:        // ^table.menu{code}[delim]
1.66      paf      1561:        add_native_method("menu", Method::CT_DYNAMIC, _menu, 1, 2);
1.74      paf      1562: 
1.239     misha    1563:        // ^table.hash[key field name]
                   1564:        // ^table.hash[key field name][value field name(s) string/table]
1.163     paf      1565:        add_native_method("hash", Method::CT_DYNAMIC, _hash, 1, 3);
1.32      paf      1566: 
1.102     parser   1567:        // ^table.sort{string-key-maker} ^table.sort{string-key-maker}[desc|asc]
                   1568:        // ^table.sort(numeric-key-maker) ^table.sort(numeric-key-maker)[desc|asc]
1.66      paf      1569:        add_native_method("sort", Method::CT_DYNAMIC, _sort, 1, 2);
1.8       paf      1570: 
1.36      paf      1571:        // ^table.locate[field;value]
1.176     paf      1572:        add_native_method("locate", Method::CT_DYNAMIC, _locate, 1, 3);
1.39      paf      1573: 
                   1574:        // ^table.flip[]
1.66      paf      1575:        add_native_method("flip", Method::CT_DYNAMIC, _flip, 0, 0);
1.41      paf      1576: 
1.293     misha    1577:        // ^table.foreach[row-num;value]{code}
                   1578:        // ^table.foreach[row-num;value]{code}[delim]
                   1579:        add_native_method("foreach", Method::CT_DYNAMIC, _foreach, 3, 4);
                   1580: 
1.306     moko     1581:        // ^table.append{row{tab}data}
1.66      paf      1582:        add_native_method("append", Method::CT_DYNAMIC, _append, 1, 1);
1.42      paf      1583: 
1.306     moko     1584:        // ^table.insert{row{tab}data} before current row
                   1585:        add_native_method("insert", Method::CT_DYNAMIC, _insert, 1, 1);
                   1586: 
1.307     moko     1587:        // ^table.delete[] current row
                   1588:        add_native_method("delete", Method::CT_DYNAMIC, _delete, 0, 0);
                   1589: 
1.157     paf      1590:        // ^table.join[table][$.limit(10) $.offset(1) $.offset[cur] ]
                   1591:        add_native_method("join", Method::CT_DYNAMIC, _join, 1, 2);
1.49      paf      1592: 
                   1593: 
1.239     misha    1594:        // ^table::sql[query]
                   1595:        // ^table::sql[query][$.limit(1) $.offset(2)]
1.100     parser   1596:        add_native_method("sql", Method::CT_DYNAMIC, _sql, 1, 2);
1.88      parser   1597: 
1.239     misha    1598:        // ^table.columns[[column name]]
1.233     misha    1599:        add_native_method("columns", Method::CT_DYNAMIC, _columns, 0, 1);
1.148     paf      1600: 
                   1601:        // ^table.select(expression) = table
1.277     moko     1602:        add_native_method("select", Method::CT_DYNAMIC, _select, 1, 2);
1.40      paf      1603: }

E-mail: