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

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

E-mail: