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

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

E-mail: