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

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

E-mail: