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

1.20      paf         1: /** @file
1.47      paf         2:        Parser: @b table parser class.
1.20      paf         3: 
1.182     paf         4:        Copyright (c) 2001-2003 ArtLebedev Group (http://www.artlebedev.com)
1.144     paf         5:        Author: Alexandr Petrosian <paf@design.ru> (http://paf.design.ru)
1.154     paf         6: */
1.20      paf         7: 
1.187   ! paf         8: static const char* IDENT_TABLE_C="$Date: 2003/11/03 13:20:30 $";
1.1       paf         9: 
1.105     parser     10: #include "classes.h"
1.182     paf        11: #include "pa_vmethod_frame.h"
                     12: 
1.16      paf        13: #include "pa_common.h"
1.1       paf        14: #include "pa_request.h"
                     15: #include "pa_vtable.h"
1.6       paf        16: #include "pa_vint.h"
1.51      paf        17: #include "pa_sql_connection.h"
1.72      paf        18: #include "pa_vbool.h"
1.1       paf        19: 
1.66      paf        20: // class
                     21: 
1.182     paf        22: class MTable: public Methoded {
1.66      paf        23: public: // VStateless_class
1.182     paf        24:        Value* create_new_value() { return new VTable(); }
1.66      paf        25: 
                     26: public:
1.182     paf        27:        MTable();
1.70      paf        28: 
                     29: public: // Methoded
1.66      paf        30:        bool used_directly() { return true; }
                     31: };
1.1       paf        32: 
1.182     paf        33: // global variable
                     34: 
                     35: DECLARE_CLASS_VAR(table, new MTable, 0);
                     36: 
                     37: // defines for globals
                     38: 
                     39: #define SQL_LIMIT_NAME "limit"
                     40: #define SQL_OFFSET_NAME "offset"
                     41: #define SQL_DEFAULT_NAME "default"
                     42: #define SQL_DISTINCT_NAME "distinct"
                     43: #define TABLE_REVERSE_NAME "reverse"
                     44: 
                     45: // globals
                     46: 
                     47: String sql_limit_name(SQL_LIMIT_NAME);
                     48: String sql_offset_name(SQL_OFFSET_NAME);
                     49: String sql_default_name(SQL_DEFAULT_NAME);
                     50: String sql_distinct_name(SQL_DISTINCT_NAME);
                     51: String table_reverse_name(TABLE_REVERSE_NAME);
                     52: 
1.186     paf        53: // local defines
                     54: 
1.187   ! paf        55: #define COLUMN_SEPARATOR_NAME "separator"
        !            56: #define COLUMN_ENCLOSER_NAME "encloser"
1.186     paf        57: 
                     58: 
1.1       paf        59: // methods
1.66      paf        60: 
1.182     paf        61: static Table::Action_options get_action_options(Request& r, MethodParams& params, 
                     62:                                                const Table& source) {
1.176     paf        63:        Table::Action_options result;
1.182     paf        64:        if(!params.count())
                     65:                return result;
                     66: 
                     67:        Value& maybe_options=params.last();
                     68: /* can not do it: 
                     69:        want to enable ^table::create[$source;
                     70: #              $.option[]
                     71:        ]
                     72:        but there is ^table.locate[name;value]
1.176     paf        73: 
1.182     paf        74:        if(maybe_options.is_string()) { // allow empty options
                     75:                result.defined=true;
1.176     paf        76:                return result;
1.182     paf        77:        }
                     78: */
                     79:        HashStringValue* options=maybe_options.get_hash();
1.176     paf        80:        if(!options)
                     81:                return result;
                     82: 
                     83:        result.defined=true;
                     84:        bool defined_offset=false;
                     85: 
                     86:        int valid_options=0;
1.182     paf        87:        if(Value* voffset=options->get(sql_offset_name)) {
1.176     paf        88:                valid_options++;
                     89:                defined_offset=true;
                     90:                if(voffset->is_string()) {
1.182     paf        91:                        const String&  soffset=*voffset->get_string();
1.176     paf        92:                        if(soffset == "cur")
                     93:                                result.offset=source.current();
                     94:                        else
1.164     paf        95:                                throw Exception("parser.runtime",
1.176     paf        96:                                        &soffset,
                     97:                                        "must be 'cur' string or expression");
                     98:                } else 
                     99:                        result.offset=r.process_to_value(*voffset).as_int();
                    100:        }
1.182     paf       101:        if(Value* vlimit=options->get(sql_limit_name)) {
1.176     paf       102:                valid_options++;
                    103:                result.limit=r.process_to_value(*vlimit).as_int();
                    104:        }
1.182     paf       105:        if(Value *vreverse=(Value *)options->get(table_reverse_name)) { 
                    106:                valid_options++; 
                    107:                result.reverse=r.process_to_value(*vreverse).as_bool(); 
                    108:                if(result.reverse && !defined_offset) 
                    109:                        result.offset=source.count()-1; 
                    110:        } 
                    111: 
                    112:        if(valid_options!=options->count())
1.176     paf       113:                throw Exception("parser.runtime",
1.182     paf       114:                        0,
1.176     paf       115:                        "called with invalid option");
                    116: 
                    117:        return result;
                    118: }
1.180     paf       119: static void check_option_param(bool options_defined, 
1.182     paf       120:                          MethodParams& params, size_t next_param_index,
1.176     paf       121:                          const char *msg) {
1.182     paf       122:        if(next_param_index+(options_defined?1:0) != params.count())
1.176     paf       123:                throw Exception("parser.runtime",
1.182     paf       124:                        0,
1.176     paf       125:                        "%s", msg);
1.157     paf       126: }
                    127: 
1.182     paf       128: static void _create(Request& r, MethodParams& params) {
1.157     paf       129:        // clone/copy part?
1.182     paf       130:        if(Table *source=params[0].get_table()) {
                    131:                Table::Action_options o=get_action_options(r, params, *source);
                    132:                check_option_param(o.defined, params, 1, 
1.176     paf       133:                        "too many parameters");
1.182     paf       134:                GET_SELF(r, VTable).set_table(*new Table(*source, o));
1.157     paf       135:                return;
                    136:        }
1.142     paf       137: 
1.1       paf       138:        // data is last parameter
1.182     paf       139:        Temp_lang temp_lang(r, String::L_PASS_APPENDED);
                    140:        const String&  data=
                    141:                r.process_to_string(params.as_junction(params.count()-1, "body must be code"));
1.44      paf       142: 
                    143:        // parse columns
1.182     paf       144:        size_t raw_pos_after=0;
                    145:        Table::columns_type columns;
                    146:        if(params.count()==2) {
                    147:                columns=Table::columns_type(0); // nameless
1.21      paf       148:        } else {
1.182     paf       149:                columns=Table::columns_type(new ArrayString);
1.44      paf       150: 
1.182     paf       151:                ArrayString head;
                    152:                data.split(head, raw_pos_after, "\n", String::L_AS_IS, 1);
                    153:                if(head.count()) {
                    154:                        size_t col_pos_after=0;
                    155:                        head[0]->split(*columns, col_pos_after, "\t", String::L_AS_IS);
                    156:                }
1.44      paf       157:        }
                    158: 
1.182     paf       159:        Table& table=*new Table(columns);
1.44      paf       160:        // parse cells
1.182     paf       161: 
                    162:        ArrayString rows;
                    163:        data.split(rows, raw_pos_after, "\n", String::L_AS_IS);
                    164:        Array_iterator<const String*> i(rows);
1.98      parser    165:        while(i.has_next()) {
1.182     paf       166:                Table::element_type row(new ArrayString);
                    167:                const String&  string=*i.next();
1.118     parser    168:                // remove comment lines
1.182     paf       169:                if(!string.length())
1.44      paf       170:                        continue;
                    171: 
1.182     paf       172:                size_t col_pos_after=0;
                    173:                string.split(*row, col_pos_after, "\t", String::L_AS_IS);
                    174:                table+=row;
1.17      paf       175:        }
1.1       paf       176: 
1.44      paf       177:        // replace any previous table value
1.182     paf       178:        GET_SELF(r, VTable).set_table(table);
1.44      paf       179: }
                    180: 
1.187   ! paf       181: static char* remove_encloser(char* cstr, char encloser) {
1.186     paf       182:        if(cstr[0]!=encloser)
                    183:                return cstr;
                    184: 
                    185:        size_t length=strlen(cstr);
                    186:        if(length<2 || cstr[length-1]!=encloser)
                    187:                return cstr;
                    188: 
                    189:        // 'string'
                    190: 
                    191:        cstr[length-1]=0;
                    192:        cstr++;
                    193: 
                    194:        // double-encloser stands for encloser
                    195:        char *read;
                    196:        char *write;
                    197:        write=read=cstr;
                    198:        while(char c=*read++) {
                    199:                if(c==encloser && *read==encloser)
                    200:                        read++;
                    201: 
                    202:                *write++=c;
                    203:        }
                    204:        *write=0; // terminate
                    205: 
                    206:        return cstr;
                    207: }
                    208: 
1.187   ! paf       209: struct lsplit_result {
        !           210:        char* piece;
        !           211:        char delim;
        !           212: 
        !           213:        operator bool() { return piece!=0; }
        !           214: };
        !           215: 
        !           216: inline lsplit_result lsplit(char* string, char delim1, char delim2) {
        !           217:        lsplit_result result;
        !           218:     if(string) {
        !           219:                char delims[]={delim1, delim2, 0};
        !           220:                if(char* v=strpbrk(string, delims)) {
        !           221:                        result.delim=*v;
        !           222:                        *v=0;
        !           223:                        result.piece=v+1;
        !           224:                        return result;
        !           225:                }
        !           226:     }
        !           227:        result.piece=0;
        !           228:        result.delim=0;
        !           229:     return result;
        !           230: }
        !           231: 
        !           232: inline lsplit_result lsplit(char* *string_ref, char delim1, char delim2) {
        !           233:     lsplit_result result;
        !           234:        result.piece=*string_ref;
        !           235:        lsplit_result next=lsplit(*string_ref, delim1, delim2);
        !           236:        result.delim=next.delim;
        !           237:        *string_ref=next.piece;
        !           238:     return result;
        !           239: }
        !           240: 
        !           241: static lsplit_result lsplit(char** string_ref, char delim1, char delim2, char encloser) {
        !           242:        lsplit_result result;
        !           243: 
        !           244:     if(char* string=*string_ref) {
        !           245:                if(encloser && *string==encloser) {
        !           246:             string++;
        !           247:                        
        !           248:                        char *read;
        !           249:                        char *write;
        !           250:                        write=read=string;
        !           251:                        char c;
        !           252:                        while(c=*read++) {
        !           253:                                if(c==encloser) {
        !           254:                                        char n=*read;
        !           255:                                        if(n==encloser) // double-encloser stands for encloser
        !           256:                                                read++;
        !           257:                                        else if(n==delim1 || n==delim2) {
        !           258:                                                result.delim=n;
        !           259:                                                read++;
        !           260:                                                break;
        !           261:                                        }
        !           262:                                }
        !           263: 
        !           264:                                *write++=c;
        !           265:                        }
        !           266:                        *write=0; // terminate
        !           267:                        *string_ref=c? read: 0;
        !           268:                        result.piece=string;
        !           269:                        return result;
        !           270:                } else
        !           271:                        return lsplit(string_ref, delim1, delim2);
        !           272:     }
        !           273:        result.piece=0;
        !           274:     return result;
        !           275: }
        !           276: 
        !           277: static void skip_empty_and_comment_lines( char** data_ref ) {
        !           278:        if(char *data=*data_ref) {
        !           279:                while( char c=*data ) {
        !           280:                        if( c== '\n' || c == '#' ) {
        !           281:                                /*nowhere=*/getrow(&data); // remove empty&comment lines
        !           282:                                *data_ref=data;
        !           283:                                continue;
        !           284:                        }
        !           285:                        break;
        !           286:                }
        !           287:        }
        !           288: }
        !           289: 
        !           290: struct TableSeparators {
        !           291:        char column;
        !           292:        char encloser;
        !           293: 
        !           294:        TableSeparators() {
        !           295:                column='\t';
        !           296:                encloser=0;
        !           297:        }
        !           298:        void load( HashStringValue& options ) {
        !           299:                if(Value* vseparator=options.get(COLUMN_SEPARATOR_NAME)) {
        !           300:                        options.remove(COLUMN_SEPARATOR_NAME);
        !           301:                        const String& sseparator=vseparator->as_string();
        !           302:                        if(sseparator.length()!=1)
        !           303:                                throw Exception("parser.runtime",
        !           304:                                        &sseparator,
        !           305:                                        "separator must be one character long");
        !           306:                        column=sseparator.first_char();
        !           307:                }
        !           308:                if(Value* vencloser=options.get(COLUMN_ENCLOSER_NAME)) {
        !           309:                        options.remove(COLUMN_ENCLOSER_NAME);
        !           310:                        const String& sencloser=vencloser->as_string();
        !           311:                        if(sencloser.length()!=1)
        !           312:                                throw Exception("parser.runtime",
        !           313:                                        &sencloser,
        !           314:                                        "encloser must be one character long");
        !           315:                        encloser=sencloser.first_char();
        !           316:                }
        !           317:        }
        !           318: };
        !           319: 
1.182     paf       320: static void _load(Request& r, MethodParams& params) {
                    321:        const String&  first_param=params.as_string(0, "file name must be string");
1.168     paf       322:        int filename_param_index=0;
                    323:        bool nameless=first_param=="nameless";
                    324:        if(nameless)
                    325:                filename_param_index++;
1.182     paf       326:        size_t options_param_index=filename_param_index+1;
1.186     paf       327: 
                    328:        HashStringValue *options=0;
1.187   ! paf       329:        TableSeparators separators;
1.186     paf       330:        if(options_param_index<params.count()
                    331:                && (options=params.as_no_junction(options_param_index, "additional params must be hash").get_hash())) {
                    332:                // cloning, so that we could change [to simplify checks on params inside file_read_text
                    333:                options=new HashStringValue(*options);
1.187   ! paf       334:                separators.load(*options);
1.186     paf       335:        }
                    336: 
1.44      paf       337:        // loading text
1.182     paf       338:        char *data=file_read_text(r.charsets,
                    339:                r.absolute(params.as_string(filename_param_index, "file name must be string")),
1.168     paf       340:                true,
1.186     paf       341:                options
1.168     paf       342:        );
1.44      paf       343: 
1.1       paf       344:        // parse columns
1.182     paf       345:        Table::columns_type columns;
1.168     paf       346:        if(nameless) {
1.182     paf       347:                columns=Table::columns_type(0); // nameless
1.1       paf       348:        } else {
1.182     paf       349:                columns=Table::columns_type(new ArrayString);
1.1       paf       350: 
1.187   ! paf       351:                skip_empty_and_comment_lines(&data);
        !           352:                while( lsplit_result sr=lsplit(&data, separators.column, '\n', separators.encloser) ) {
        !           353:                        *columns+=new String(sr.piece, 0, true);
        !           354:                        if(sr.delim=='\n') 
        !           355:                                break;
1.139     paf       356:                }
1.1       paf       357:        }
1.187   ! paf       358:        
        !           359:        Table& table=*new Table(columns);
1.1       paf       360: 
                    361:        // parse cells
1.187   ! paf       362:        Table::element_type row(new ArrayString);
        !           363:        skip_empty_and_comment_lines(&data);
        !           364:        while( lsplit_result sr=lsplit(&data, separators.column, '\n', separators.encloser) ) {
        !           365:                if(!sr.delim && !row->count()) // append last empty column [if without \n]
        !           366:                        break;
        !           367:                *row+=new String(sr.piece, 0, true);
        !           368:                if(sr.delim=='\n') {
        !           369:                        table+=row;
        !           370:                        row=new ArrayString;
        !           371:                        skip_empty_and_comment_lines(&data);
1.1       paf       372:                }
1.187   ! paf       373:        }
        !           374:        // last line [if without \n]
        !           375:        if(row->count())
1.1       paf       376:                table+=row;
1.187   ! paf       377:        
1.1       paf       378:        // replace any previous table value
1.182     paf       379:        GET_SELF(r, VTable).set_table(table);
1.1       paf       380: }
1.2       paf       381: 
1.146     paf       382: /// @todo "x\nx" "xxx""xx"
1.182     paf       383: static void _save(Request& r, MethodParams& params) {
                    384:        Value& vfile_name=params.as_no_junction(params.count()-1, "file name must not be code");
1.22      paf       385: 
1.182     paf       386:        Table& table=GET_SELF(r, VTable).table();
1.31      paf       387: 
1.129     paf       388:        bool do_append=false;
1.182     paf       389:        String sdata;
                    390:        if(params.count()==1) { // named output
1.31      paf       391:                // write out names line
                    392:                if(table.columns()) { // named table
1.182     paf       393:                        for(Array_iterator<const String*> i(*table.columns()); i.has_next(); ) {
                    394:                                sdata.append(*i.next(), String::L_TABLE);
1.98      parser    395:                                if(i.has_next())
1.182     paf       396:                                        sdata.append_know_length("\t", 1, String::L_CLEAN);
1.31      paf       397:                        }
                    398:                } else { // nameless table
1.182     paf       399:                        if(int lsize=table.count()?table[0]->count():0)
1.31      paf       400:                                for(int column=0; column<lsize; column++) {
1.182     paf       401:                                        char *cindex_tab=new(PointerFreeGC) char[MAX_NUMBER];
                    402:                                        sdata.append_know_length(cindex_tab, 
1.185     paf       403:                                                snprintf(cindex_tab, MAX_NUMBER, 
                    404:                                                        column<lsize-1?"%d\t":"%d", column),
                    405:                                                        String::L_CLEAN);
1.31      paf       406:                                }
                    407:                        else
1.182     paf       408:                                sdata.append_help_length("empty nameless table", 0, String::L_CLEAN);
1.31      paf       409:                }
1.182     paf       410:                sdata.append_know_length("\n", 1, String::L_CLEAN);
1.129     paf       411:        } else { // mode specified
1.182     paf       412:                const String&  mode=params.as_string(0, "mode must be string");
1.129     paf       413:                if(mode=="append")
                    414:                        do_append=true;
                    415:                else if(mode=="nameless")
                    416:                        /*ok, already skipped names output*/;
                    417:                else
1.146     paf       418:                        throw Exception("parser.runtime",
1.129     paf       419:                                &mode,
                    420:                                "unknown mode, must be 'append'");
                    421: 
1.31      paf       422:        }
                    423:        // data lines
1.182     paf       424:        Array_iterator<ArrayString*> i(table);
1.98      parser    425:        while(i.has_next()) {
1.182     paf       426:                for(Array_iterator<const String*> c(*i.next()); c.has_next(); ) {
                    427:                        sdata.append(*c.next(), String::L_TABLE);
1.98      parser    428:                        if(c.has_next())
1.182     paf       429:                                sdata.append_know_length("\t", 1, String::L_CLEAN);
1.31      paf       430:                }
1.182     paf       431:                sdata.append_know_length("\n", 1, String::L_CLEAN);
1.31      paf       432:        }
                    433: 
                    434:        // write
1.141     paf       435:        file_write(r.absolute(vfile_name.as_string()), 
1.182     paf       436:                sdata.cstr(), sdata.length(), true, do_append);
1.22      paf       437: }
                    438: 
1.182     paf       439: static void _count(Request& r, MethodParams&) {
                    440:        int result=GET_SELF(r, VTable).table().count();
                    441:        r.write_no_lang(*new VInt(result));
1.6       paf       442: }
                    443: 
1.182     paf       444: static void _line(Request& r, MethodParams&) {
                    445:        int result=1+GET_SELF(r, VTable).table().current();
                    446:        r.write_no_lang(*new VInt(result));
1.6       paf       447: }
                    448: 
1.182     paf       449: static void _offset(Request& r, MethodParams& params) {
                    450:        Table& table=GET_SELF(r, VTable).table();
                    451:        if(params.count()) {
1.133     paf       452:                bool absolute=false;
1.182     paf       453:                if(params.count()>1) {
                    454:                    const String&  whence=params.as_string(0, "whence must be string");
1.133     paf       455:                    if(whence=="cur")
1.134     paf       456:                                absolute=false;
1.133     paf       457:                    else if(whence=="set")
1.134     paf       458:                                absolute=true;
1.133     paf       459:                    else
1.146     paf       460:                                throw Exception("parser.runtime",
1.134     paf       461:                                        &whence,
                    462:                                        "is invalid whence, valid are 'cur' or 'set'");
1.157     paf       463:                }
1.133     paf       464:                
1.182     paf       465:                Value& offset_expr=params.as_junction(params.count()-1, "offset must be expression");
1.147     paf       466:                table.offset(absolute, r.process_to_value(offset_expr).as_int());
1.151     paf       467:        } else
1.182     paf       468:                r.write_no_lang(*new VInt(table.current()));
1.6       paf       469: }
                    470: 
1.182     paf       471: static void _menu(Request& r, MethodParams& params) {
                    472:        Value& body_code=params.as_junction(0, "body must be code");
1.7       paf       473:        
1.182     paf       474:        Value* delim_maybe_code=params.count()>1?&params[1]:0;
1.7       paf       475: 
1.182     paf       476:        Table& table=GET_SELF(r, VTable).table();
1.7       paf       477:        bool need_delim=false;
1.99      parser    478:        int saved_current=table.current();
1.182     paf       479:        int size=table.count();
1.99      parser    480:        for(int row=0; row<size; row++) {
1.22      paf       481:                table.set_current(row);
1.7       paf       482: 
1.161     paf       483:                StringOrValue sv_processed=r.process(body_code);
1.182     paf       484:                const String* s_processed=sv_processed.get_string();
                    485:                if(delim_maybe_code && s_processed && s_processed->length()) { // delimiter set and we have body
1.161     paf       486:                        if(need_delim) // need delim & iteration produced string?
1.150     paf       487:                                r.write_pass_lang(r.process(*delim_maybe_code));
1.7       paf       488:                        need_delim=true;
                    489:                }
1.161     paf       490:                r.write_pass_lang(sv_processed);
1.7       paf       491:        }
1.99      parser    492:        table.set_current(saved_current);
1.7       paf       493: }
                    494: 
1.110     parser    495: #ifndef DOXYGEN
1.174     paf       496: enum Table2hash_distint { D_ILLEGAL, D_FIRST, D_TABLES };
1.74      paf       497: struct Row_info {
1.166     paf       498:        Request *r;
1.74      paf       499:        Table *table;
1.182     paf       500:        Value* key_code;
                    501:        size_t key_field;
                    502:        Array<int>* value_fields;
                    503:        HashStringValue* hash;
1.174     paf       504:        Table2hash_distint distinct;
1.182     paf       505:        size_t row;
1.74      paf       506: };
1.110     parser    507: #endif
1.182     paf       508: static void table_row_to_hash(Table::element_type row, Row_info *info) {
                    509:        const String* key;
                    510:        if(info->key_code) {
                    511:                info->table->set_current(info->row++); // change context row
                    512:                StringOrValue sv_processed=info->r->process(*info->key_code);
1.166     paf       513:                key=&sv_processed.as_string();
                    514:        } else
1.182     paf       515:                key=info->key_field<row->count()?row->get(info->key_field):0;
1.166     paf       516: 
                    517:        if(!key)
                    518:                return; // ignore rows without key [too-short-record_array if-indexed]
1.74      paf       519:                
1.182     paf       520:        switch(info->distinct) {
1.174     paf       521:        case D_ILLEGAL: case D_FIRST:
                    522:                {
1.182     paf       523:                        VHash* vhash=new VHash;
                    524:                        HashStringValue& hash=vhash->hash();
                    525:                        for(Array_iterator<int> i(*info->value_fields); i.has_next(); ) {
                    526:                                size_t value_field=i.next();
                    527:                                if(value_field<row->count())
1.174     paf       528:                                        hash.put(
1.182     paf       529:                                                *info->table->columns()->get(value_field), 
                    530:                                                new VString(*row->get(value_field)));
1.174     paf       531:                        }
                    532: 
1.182     paf       533:                        if(info->hash->put_dont_replace(*key, vhash)) // put. existed?
                    534:                                if(info->distinct==D_ILLEGAL)
1.174     paf       535:                                        throw Exception("parser.runtime",
                    536:                                                key,
                    537:                                                "duplicate key");
                    538:                }
                    539:                break;
                    540:        case D_TABLES:
                    541:                {
1.182     paf       542:                        VTable* vtable=(VTable*)info->hash->get(*key); // put. table existed?
1.174     paf       543:                        Table* table;
                    544:                        if(vtable) 
                    545:                                table=vtable->get_table();
                    546:                        else {
                    547:                                // no? creating table of same structure as source
1.179     paf       548:                                Table::Action_options table_options(0, 0);
1.182     paf       549:                                table=new Table(*info->table, table_options/*no rows, just structure*/);
                    550:                                info->hash->put(*key, new VTable(table));
1.174     paf       551:                        }
1.182     paf       552:                        *table+=row;
1.174     paf       553:                }
                    554:                break;
                    555:        default:
                    556:                throw Exception(0,
                    557:                        0,
1.182     paf       558:                        "invalid distinct code (#%d)", info->distinct);
1.74      paf       559:        }
                    560: }
1.182     paf       561: static void _hash(Request& r, MethodParams& params) {
                    562:        Table& self_table=GET_SELF(r, VTable).table();
                    563:        VHash& result=*new VHash;
                    564:        if(Table::columns_type columns=self_table.columns())
                    565:                if(columns->count()>0) {
1.174     paf       566:                        Table2hash_distint distinct=D_ILLEGAL;
1.182     paf       567:                        int param_index=params.count()-1;
1.166     paf       568:                        if(param_index>0) {
1.182     paf       569:                                if(HashStringValue* options=
                    570:                                        params.as_no_junction(param_index, "param must not be code").get_hash()) {
1.166     paf       571:                                        --param_index;
                    572:                                        int valid_options=0;
1.182     paf       573:                                        if(Value* vdistinct_code=options->get(sql_distinct_name)) {
1.166     paf       574:                                                valid_options++;
1.174     paf       575:                                                Value& vdistinct_value=r.process_to_value(*vdistinct_code);
                    576:                                                if(vdistinct_value.is_string()) {
                    577:                                                        const String& sdistinct=*vdistinct_value.get_string();
                    578:                                                        if(sdistinct=="tables")
                    579:                                                                distinct=D_TABLES;
                    580:                                                        else
                    581:                                                                throw Exception("parser.runtime",
                    582:                                                                        &sdistinct,
                    583:                                                                        "must be 'tables' or true/false");
                    584:                                                } else
                    585:                                                        distinct=vdistinct_value.as_bool()?D_FIRST:D_ILLEGAL;
1.166     paf       586:                                        }
1.182     paf       587:                                        if(valid_options!=options->count())
1.166     paf       588:                                                throw Exception("parser.runtime",
1.182     paf       589:                                                        0,
1.166     paf       590:                                                        "called with invalid option");
1.163     paf       591:                                }
                    592:                        }
                    593:                        if(param_index==2) // bad options param type
                    594:                                throw Exception("parser.runtime",
1.182     paf       595:                                        0,
1.163     paf       596:                                        "options must be hash");
                    597: 
1.182     paf       598:                        Array<int> value_fields;
1.163     paf       599:                        if(param_index>0) {
1.174     paf       600:                                if(distinct!=D_ILLEGAL && distinct!=D_FIRST)
                    601:                                        throw Exception("parser.runtime",
                    602:                                                0,
                    603:                                                "in distinct[tables] mode you may not specify value field(s)");
1.182     paf       604:                                Value& value_fields_param=params.as_no_junction(param_index, "value field(s) must not be code");
1.123     parser    605:                                if(value_fields_param.is_string()) {
1.182     paf       606:                                        value_fields+=self_table.column_name2index(
                    607:                                                *value_fields_param.get_string(), true);
                    608:                                } else if(Table* value_fields_table=value_fields_param.get_table()) {
                    609:                                        for(Array_iterator<Table::element_type> i(*value_fields_table); 
                    610:                                                i.has_next(); ) {
                    611:                                                const String& value_field_name
                    612:                                                        =*i.next()->get(0);
                    613:                                                value_fields
                    614:                                                        +=self_table.column_name2index(value_field_name, true);
1.123     parser    615:                                        }
                    616:                                } else
1.146     paf       617:                                        throw Exception("parser.runtime",
1.182     paf       618:                                                0,
1.123     parser    619:                                                "value field(s) must be string or self_table"
                    620:                                        );
                    621:                        } else { // by all columns, including key
1.174     paf       622:                                if(!(distinct!=D_ILLEGAL && distinct!=D_FIRST))
1.182     paf       623:                                        for(size_t i=0; i<columns->count(); i++)
1.174     paf       624:                                                value_fields+=i;
1.74      paf       625:                        }
                    626: 
1.182     paf       627: 
                    628:                        {
                    629:                                Row_info info={0};
                    630:                                info.r=&r;
                    631:                                info.table=&self_table;
                    632:                                Value* key_param=&params[0];
                    633:                                info.key_code=key_param->get_junction()?key_param:0;
                    634:                                info.key_field=info.key_code?-1
                    635:                                        :self_table.column_name2index(key_param->as_string(), true);
                    636:                                info.value_fields=&value_fields;
                    637:                                info.hash=&result.hash();
                    638:                                info.distinct=distinct;
                    639:                                info.row=0;
                    640: 
                    641:                                int saved_current=self_table.current();
                    642:                                self_table.for_each(table_row_to_hash, &info);
                    643:                                self_table.set_current(saved_current);
                    644:                        }
1.74      paf       645:                }
1.97      parser    646:        r.write_no_lang(result);
1.74      paf       647: }
                    648: 
1.110     parser    649: #ifndef DOXYGEN
1.78      paf       650: struct Table_seq_item {
1.182     paf       651:        ArrayString* row;
1.34      paf       652:        union {
1.182     paf       653:                const char *c_str;
1.34      paf       654:                double d;
                    655:        } value;
1.32      paf       656: };
1.110     parser    657: #endif
1.34      paf       658: static int sort_cmp_string(const void *a, const void *b) {
                    659:        return strcmp(
1.78      paf       660:                static_cast<const Table_seq_item *>(a)->value.c_str, 
                    661:                static_cast<const Table_seq_item *>(b)->value.c_str
1.34      paf       662:        );
                    663: }
                    664: static int sort_cmp_double(const void *a, const void *b) {
1.78      paf       665:        double va=static_cast<const Table_seq_item *>(a)->value.d;
                    666:        double vb=static_cast<const Table_seq_item *>(b)->value.d;
1.34      paf       667:        if(va<vb)
                    668:                return -1;
                    669:        else if(va>vb)
                    670:                return +1;
                    671:        else 
                    672:                return 0;
                    673: }
1.182     paf       674: static void _sort(Request& r, MethodParams& params) {
                    675:        Value& key_maker=params.as_junction(0, "key-maker must be code");
1.61      paf       676: 
1.182     paf       677:        bool reverse=params.count()>1/*..[desc|asc|]*/?
                    678:                reverse=params.as_no_junction(1, "order must not be code").as_string()=="desc":
1.104     parser    679:                false; // default=asc
1.32      paf       680: 
1.182     paf       681:        Table& old_table=GET_SELF(r, VTable).table();
                    682:        Table& new_table=*new Table(old_table.columns());
1.34      paf       683: 
1.182     paf       684:        Table_seq_item* seq=new(PointerFreeGC) Table_seq_item[old_table.count()];
1.34      paf       685:        int i;
                    686: 
                    687:        // calculate key values
                    688:        bool key_values_are_strings=true;
1.182     paf       689:        int old_count=old_table.count();
                    690:        for(i=0; i<old_count; i++) {
1.101     parser    691:                old_table.set_current(i);
1.32      paf       692:                // calculate key value
1.182     paf       693:                seq[i].row=old_table[i];
                    694:                Value& value=r.process_to_value(key_maker).as_expr_result(true/*return string as-is*/);
1.34      paf       695:                if(i==0) // determining key values type by first one
                    696:                        key_values_are_strings=value.is_string();
                    697: 
                    698:                if(key_values_are_strings)
                    699:                        seq[i].value.c_str=value.as_string().cstr();
                    700:                else
                    701:                        seq[i].value.d=value.as_double();
1.32      paf       702:        }
                    703:        // sort keys
1.182     paf       704:        _qsort(seq, old_count, sizeof(Table_seq_item), 
1.34      paf       705:                key_values_are_strings?sort_cmp_string:sort_cmp_double);
1.32      paf       706: 
1.34      paf       707:        // reorder table as they require in 'seq'
1.182     paf       708:        for(i=0; i<old_count; i++)
                    709:                new_table+=Table::element_type(seq[reverse?old_count-1-i:i].row);
                    710: 
                    711:        delete[] seq;
1.32      paf       712: 
1.116     parser    713:        // replace any previous table value
1.182     paf       714:        GET_SELF(r, VTable).set_table(new_table);
1.32      paf       715: }
                    716: 
1.176     paf       717: #ifndef DOXYGEN
1.182     paf       718: struct Expression_is_true_info {
1.176     paf       719:        Request* r;
                    720:        Value* expression_code;
                    721: };
                    722: #endif
1.182     paf       723: static bool expression_is_true(Table& self, void* ainfo) {
                    724:        Expression_is_true_info& info=*static_cast<Expression_is_true_info*>(ainfo);
1.176     paf       725:        return info.r->process_to_value(*info.expression_code).as_bool();
                    726: }
                    727: static bool _locate_expression(Table& table, Table::Action_options o,
1.182     paf       728:                               Request& r, MethodParams& params) {
                    729:        check_option_param(o.defined, params, 1,
1.176     paf       730:                "locate by expression only has parameters: expression and, maybe, options");
1.182     paf       731:        Value& expression_code=params.as_junction(0, "must be expression");
1.145     paf       732: 
1.182     paf       733:        Expression_is_true_info info={&r, &expression_code};
                    734:        return table.table_first_that(expression_is_true, &info, o);
1.145     paf       735: }
1.176     paf       736: static bool _locate_name_value(Table& table, Table::Action_options o,
1.182     paf       737:                               Request& r, MethodParams& params) {
                    738:        check_option_param(o.defined, params, 2,
1.176     paf       739:                "locate by locate by name has parameters: name, value and, maybe, options");
1.182     paf       740:        const String& name=params.as_string(0, "column name must be string");
                    741:        const String& value=params.as_string(1, "value must be string");
                    742:        return table.locate(name, value, o);
                    743: }
                    744: static void _locate(Request& r, MethodParams& params) {
                    745:        Table& table=GET_SELF(r, VTable).table();
1.72      paf       746: 
1.182     paf       747:        Table::Action_options o=get_action_options(r, params, table);
                    748: 
                    749:        bool result=params[0].get_junction()?
                    750:                _locate_expression(table, o, r, params) :
                    751:                _locate_name_value(table, o, r, params);
                    752:        r.write_no_lang(*new VBool(result));
1.145     paf       753: }
1.182     paf       754: 
                    755: 
                    756: static void _flip(Request& r, MethodParams& params) {
                    757:        Table& old_table=GET_SELF(r, VTable).table();
1.184     paf       758:        Table& new_table=*new Table(0);
1.182     paf       759:        if(size_t old_count=old_table.count())
                    760:                if(size_t old_cols=old_table[0]->count()) 
                    761:                        for(size_t column=0; column<old_cols; column++) {
                    762:                                Table::element_type new_row(new ArrayString(old_count));
                    763:                                for(size_t i=0; i<old_count; i++) {
                    764:                                        Table::element_type old_row=old_table[i];
                    765:                                        *new_row+=column<old_row->count()?old_row->get(column):new String;
1.39      paf       766:                                }
1.182     paf       767:                                new_table+=new_row;
1.39      paf       768:                        }
                    769: 
1.182     paf       770:        r.write_no_lang(*new VTable(&new_table));
1.39      paf       771: }
                    772: 
1.182     paf       773: static void _append(Request& r, MethodParams& params) {
1.134     paf       774:        // data
1.182     paf       775:        Temp_lang temp_lang(r, String::L_PASS_APPENDED);
                    776:        const String& string=r.process_to_string(params.as_junction(0, "body must be code"));
1.41      paf       777: 
                    778:        // parse cells
1.182     paf       779:        Table::element_type row=new ArrayString;
                    780:        size_t pos_after=0;
                    781:        string.split(*row, pos_after, "\t", String::L_AS_IS);
1.41      paf       782: 
1.182     paf       783:        GET_SELF(r, VTable).table()+=row;
1.41      paf       784: }
                    785: 
1.182     paf       786: static void join_named_row(Table& src, Table* dest) {
                    787:        Table::columns_type dest_columns=dest->columns();
                    788:        size_t dest_columns_count=dest_columns->count();
                    789:        Table::element_type dest_row(new ArrayString(dest_columns_count));
                    790:        for(size_t dest_column=0; dest_column<dest_columns_count; dest_column++) {
                    791:                const String* src_item=src.item(*dest_columns->get(dest_column));
                    792:                *dest_row+=src_item?src_item:new String;
                    793:        }
                    794:        *dest+=dest_row;
                    795: }
                    796: static void join_nameless_row(Table& src, Table* dest) {
                    797:        *dest+=src[src.current()];
                    798: }
                    799: static void _join(Request& r, MethodParams& params) {
                    800:        Table* maybe_src=params.as_no_junction(0, "table ref must not be code").get_table();
1.42      paf       801:        if(!maybe_src)
1.146     paf       802:                throw Exception("parser.runtime", 
1.182     paf       803:                        0, 
1.42      paf       804:                        "source is not a table");
1.176     paf       805:        Table& src=*maybe_src;
                    806: 
1.182     paf       807:        Table::Action_options o=get_action_options(r, params, src);
                    808:        check_option_param(o.defined, params, 1,
1.176     paf       809:                "invalid extra parameter");
1.42      paf       810: 
1.182     paf       811:        Table& dest=GET_SELF(r, VTable).table();
1.42      paf       812:        if(&src == &dest)
1.146     paf       813:                throw Exception("parser.runtime", 
1.182     paf       814:                        0, 
1.42      paf       815:                        "source and destination are same table");
                    816: 
1.182     paf       817:        if(Table::columns_type dest_columns=dest.columns()) // dest is named
                    818:                src.table_for_each(join_named_row, &dest, o);
                    819:        else // dest is nameless
                    820:                src.table_for_each(join_nameless_row, &dest, o);
1.42      paf       821: }
                    822: 
1.94      parser    823: #ifndef DOXYGEN
1.169     paf       824: class Table_sql_event_handlers: public SQL_Driver_query_event_handlers {
1.182     paf       825:        ArrayString& columns;
                    826:        ArrayString* row;
1.94      parser    827: public:
1.182     paf       828:        Table* table;
                    829: public:
                    830:        Table_sql_event_handlers() :
                    831:                columns(*new ArrayString), row(0), table(0) {
1.94      parser    832:        }
                    833: 
1.182     paf       834:        bool add_column(SQL_Error& error, const char *str, size_t length) {
1.170     paf       835:                try {
1.182     paf       836:                        columns+=new String(str, length, true);
1.170     paf       837:                        return false;
                    838:                } catch(...) {
                    839:                        error=SQL_Error("exception occured in Table_sql_event_handlers::add_column");
                    840:                        return true;
                    841:                }
                    842:        }
                    843:        bool before_rows(SQL_Error& error) { 
                    844:                try {
1.182     paf       845:                        table=new Table(&columns);
1.170     paf       846:                        return false;
                    847:                } catch(...) {
                    848:                        error=SQL_Error("exception occured in Table_sql_event_handlers::before_rows");
                    849:                        return true;
                    850:                }
                    851:        }
                    852:        bool add_row(SQL_Error& error) {
                    853:                try {
1.182     paf       854:                        *table+=row=new ArrayString;
1.170     paf       855:                        return false;
                    856:                } catch(...) {
                    857:                        error=SQL_Error("exception occured in Table_sql_event_handlers::add_row");
                    858:                        return true;
                    859:                }
                    860:        }
1.182     paf       861:        bool add_row_cell(SQL_Error& error, const char* str, size_t length) {
1.170     paf       862:                try {
1.182     paf       863:                        String& cell=*new String;
                    864:                        if(length)
                    865:                                cell.append_know_length(str, length, String::L_TAINTED);
                    866:                        *row+=&cell;
1.170     paf       867:                        return false;
                    868:                } catch(...) {
                    869:                        error=SQL_Error("exception occured in Table_sql_event_handlers::add_row_cell");
                    870:                        return true;
                    871:                }
1.94      parser    872:        }
                    873: };
                    874: #endif
1.182     paf       875: static void _sql(Request& r, MethodParams& params) {
                    876:        Value& statement=params.as_junction(0, "statement must be code");
1.49      paf       877: 
1.53      paf       878:        ulong limit=0;
1.100     parser    879:        ulong offset=0;
1.182     paf       880:        if(params.count()>1) {
                    881:                Value& voptions=params.as_no_junction(1, "options must be hash, not code");
1.156     paf       882:                if(!voptions.is_string())
1.182     paf       883:                        if(HashStringValue* options=voptions.get_hash()) {
1.164     paf       884:                                int valid_options=0;
1.182     paf       885:                                if(Value* vlimit=options->get(sql_limit_name)) {
1.164     paf       886:                                        valid_options++;
1.147     paf       887:                                        limit=(ulong)r.process_to_value(*vlimit).as_double();
1.164     paf       888:                                }
1.182     paf       889:                                if(Value* voffset=options->get(sql_offset_name)) {
1.164     paf       890:                                        valid_options++;
1.147     paf       891:                                        offset=(ulong)r.process_to_value(*voffset).as_double();
1.164     paf       892:                                }
1.182     paf       893:                                if(valid_options!=options->count())
1.164     paf       894:                                        throw Exception("parser.runtime",
1.182     paf       895:                                                0,
1.164     paf       896:                                                "called with invalid option");
1.109     parser    897:                        } else
1.146     paf       898:                                throw Exception("parser.runtime",
1.182     paf       899:                                        0,
1.109     parser    900:                                        "options must be hash");
1.49      paf       901:        }
                    902: 
1.182     paf       903:        Temp_lang temp_lang(r, String::L_SQL);
                    904:        const String&  statement_string=r.process_to_string(statement);
                    905:        const char* statement_cstr=
                    906:                statement_string.cstr(String::L_UNSPECIFIED, r.connection());
                    907:        Table_sql_event_handlers handlers;
1.135     paf       908: #ifdef RESOURCES_DEBUG
                    909:        struct timeval mt[2];
                    910:        //measure:before
                    911:        gettimeofday(&mt[0],NULL);
                    912: #endif 
1.182     paf       913:        r.connection()->query(
1.160     paf       914:                statement_cstr, offset, limit, 
                    915:                handlers,
                    916:                statement_string);
1.135     paf       917:        
                    918: #ifdef RESOURCES_DEBUG
                    919:                //measure:after connect
                    920:        gettimeofday(&mt[1],NULL);
                    921:        
                    922:        double t[2];
                    923:        for(int i=0;i<2;i++)
                    924:            t[i]=mt[i].tv_sec+mt[i].tv_usec/1000000.0;
                    925:            
                    926:        r.sql_request_time+=t[1]-t[0];
                    927: #endif                         
1.96      parser    928: 
1.182     paf       929:        Table& result=
                    930:                handlers.table?*handlers.table: // query resulted in table? return it
                    931:                *new Table(Table::columns_type(0)); // query returned no table, fake it
1.49      paf       932: 
                    933:        // replace any previous table value
1.182     paf       934:        GET_SELF(r, VTable).set_table(result);
1.49      paf       935: }
                    936: 
1.182     paf       937: static void _columns(Request& r, MethodParams&) {
1.88      parser    938: 
1.182     paf       939:        Table::columns_type result_columns(new ArrayString);
                    940:        *result_columns+=new String("column");
                    941:        Table& result_table=*new Table(result_columns);
1.88      parser    942: 
1.182     paf       943:        Table& source_table=GET_SELF(r, VTable).table();
                    944:        if(Table::columns_type source_columns=source_table.columns()) {
                    945:                for(Array_iterator<const String*> i(*source_columns); i.has_next(); ) {
                    946:                        Table::element_type result_row(new ArrayString);
                    947:                        *result_row+=i.next();
                    948:                        result_table+=result_row;
1.88      parser    949:                }
                    950:        }
                    951: 
1.182     paf       952:        r.write_no_lang(*new VTable(&result_table));
1.88      parser    953: }
                    954: 
1.182     paf       955: static void _select(Request& r, MethodParams& params) {
                    956:        Value& vcondition=params.as_junction(0, "condition must be expression");
1.148     paf       957: 
1.182     paf       958:        Table& source_table=GET_SELF(r, VTable).table();
                    959:        Table& result_table=*new Table(source_table.columns());
1.148     paf       960: 
                    961:        int saved_current=source_table.current();
1.182     paf       962:        int size=source_table.count();
1.148     paf       963:        for(int row=0; row<size; row++) {
                    964:                source_table.set_current(row);
                    965: 
1.150     paf       966:                bool condition=r.process_to_value(vcondition, 
1.149     paf       967:                                /*0/*no name* /,*/
1.148     paf       968:                                false/*don't intercept string*/).as_bool();
                    969: 
                    970:                if(condition) // ...condition is true=
1.182     paf       971:                        result_table+=source_table[row]; // =green light to go to result
1.148     paf       972:        }
                    973:        source_table.set_current(saved_current);
                    974: 
1.182     paf       975:        r.write_no_lang(*new VTable(&result_table));
1.148     paf       976: }
                    977: 
1.66      paf       978: // constructor
                    979: 
1.182     paf       980: MTable::MTable(): Methoded("table") {
1.142     paf       981:        // ^table::create{data}
                    982:        // ^table::create[nameless]{data}
                    983:        // ^table::create[table]
                    984:        add_native_method("create", Method::CT_DYNAMIC, _create, 1, 2);
                    985:        // old name for compatibility with <= v 1.141 2002/01/25 11:33:45 paf
                    986:        add_native_method("set", Method::CT_DYNAMIC, _create, 1, 2); 
1.2       paf       987: 
1.142     paf       988:        // ^table::load[file]  
                    989:        // ^table::load[nameless;file]
1.168     paf       990:        add_native_method("load", Method::CT_DYNAMIC, _load, 1, 3);
1.22      paf       991: 
                    992:        // ^table.save[file]  
                    993:        // ^table.save[nameless;file]
1.66      paf       994:        add_native_method("save", Method::CT_DYNAMIC, _save, 1, 2);
1.6       paf       995: 
                    996:        // ^table.count[]
1.66      paf       997:        add_native_method("count", Method::CT_DYNAMIC, _count, 0, 0);
1.6       paf       998: 
                    999:        // ^table.line[]
1.66      paf      1000:        add_native_method("line", Method::CT_DYNAMIC, _line, 0, 0);
1.6       paf      1001: 
1.10      paf      1002:        // ^table.offset[]  
1.133     paf      1003:        // ^table.offset(offset)
                   1004:        // ^table.offset[cur|set](offset)
                   1005:        add_native_method("offset", Method::CT_DYNAMIC, _offset, 0, 2);
1.7       paf      1006: 
1.10      paf      1007:        // ^table.menu{code}  
                   1008:        // ^table.menu{code}[delim]
1.66      paf      1009:        add_native_method("menu", Method::CT_DYNAMIC, _menu, 1, 2);
1.74      paf      1010: 
1.79      paf      1011:        // ^table:hash[key field name]
1.123     parser   1012:        // ^table:hash[key field name][value field name(s) string/table]
1.163     paf      1013:        add_native_method("hash", Method::CT_DYNAMIC, _hash, 1, 3);
1.32      paf      1014: 
1.102     parser   1015:        // ^table.sort{string-key-maker} ^table.sort{string-key-maker}[desc|asc]
                   1016:        // ^table.sort(numeric-key-maker) ^table.sort(numeric-key-maker)[desc|asc]
1.66      paf      1017:        add_native_method("sort", Method::CT_DYNAMIC, _sort, 1, 2);
1.8       paf      1018: 
1.36      paf      1019:        // ^table.locate[field;value]
1.176     paf      1020:        add_native_method("locate", Method::CT_DYNAMIC, _locate, 1, 3);
1.39      paf      1021: 
                   1022:        // ^table.flip[]
1.66      paf      1023:        add_native_method("flip", Method::CT_DYNAMIC, _flip, 0, 0);
1.41      paf      1024: 
                   1025:        // ^table.append{r{tab}e{tab}c{tab}o{tab}r{tab}d}
1.66      paf      1026:        add_native_method("append", Method::CT_DYNAMIC, _append, 1, 1);
1.42      paf      1027: 
1.157     paf      1028:        // ^table.join[table][$.limit(10) $.offset(1) $.offset[cur] ]
                   1029:        add_native_method("join", Method::CT_DYNAMIC, _join, 1, 2);
1.49      paf      1030: 
                   1031: 
1.100     parser   1032:        // ^table:sql[query]
                   1033:        // ^table:sql[query][$.limit(1) $.offset(2)]
                   1034:        add_native_method("sql", Method::CT_DYNAMIC, _sql, 1, 2);
1.88      parser   1035: 
                   1036:        // ^table:columns[]
                   1037:        add_native_method("columns", Method::CT_DYNAMIC, _columns, 0, 0);
1.148     paf      1038: 
                   1039:        // ^table.select(expression) = table
                   1040:        add_native_method("select", Method::CT_DYNAMIC, _select, 1, 1);
1.40      paf      1041: }

E-mail: