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

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

E-mail: