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

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

E-mail: