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

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

E-mail: