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

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

E-mail: