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

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

E-mail: