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

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

E-mail: