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

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

E-mail: