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

1.20      paf         1: /** @file
1.47      paf         2:        Parser: @b table parser class.
1.20      paf         3: 
1.172.2.2  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.172.2.14.2.  (paf        8:): static const char* IDENT_TABLE_C="$Date: 2003/03/24 09:39:54 $";
1.1       paf         9: 
1.105     parser     10: #include "classes.h"
1.172.2.4  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.172.2.9  paf        22: class MTable: public Methoded {
1.66      paf        23: public: // VStateless_class
1.172.2.14.2.  (paf       24:):      Value* create_new_value() { return new VTable(); }
1.66      paf        25: 
                     26: public:
1.172.2.6  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.172.2.6  paf        33: // global variable
                     34: 
1.172.2.11  paf        35: DECLARE_CLASS_VAR(table, new MTable, 0);
1.172.2.7  paf        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: 
                     44: // globals
                     45: 
1.172.2.14.2.  (paf       46:): const String& sql_limit_name(new String(SQL_LIMIT_NAME));
                     47:): const String& sql_offset_name(new String(SQL_OFFSET_NAME));
                     48:): const String& sql_default_name(new String(SQL_DEFAULT_NAME));
                     49:): const String& sql_distinct_name(new String(SQL_DISTINCT_NAME));
1.172.2.6  paf        50: 
1.1       paf        51: // methods
1.66      paf        52: 
1.172.2.14.2.  (paf       53:): static void get_copy_options(Request& r, MethodParams* params, int param_index,
1.157     paf        54:                                                         const Table& source,
                     55:                                                         int& offset,
                     56:                                                         int& limit) {
1.172.2.6  paf        57: 
1.157     paf        58:        offset=0;
                     59:        limit=0;
1.172.2.10  paf        60:        if(params->count()<=param_index)
1.157     paf        61:                return;
                     62: 
1.172.2.14.2.  (paf       63:):      Value* voptions=params->as_no_junction(param_index, "options must be hash, not code");
1.172.2.6  paf        64:        if(!voptions->is_string()) {
1.172.2.14.2.  (paf       65:):              if(HashStringValue* options=voptions->get_hash()) {
1.164     paf        66:                        int valid_options=0;
1.172.2.14.2.  (paf       67:):                      if(Value* voffset=options->get(sql_offset_name)) {
1.164     paf        68:                                valid_options++;
1.157     paf        69:                                if(voffset->is_string()) {
1.172.2.14.2.  (paf       70:):                                      const String&  soffset=voffset->get_string();
1.172.2.6  paf        71:                                        if(*soffset == "cur")
1.157     paf        72:                                                offset=source.current();
                     73:                                        else
                     74:                                                throw Exception("parser.runtime",
1.172.2.6  paf        75:                                                        soffset,
1.157     paf        76:                                                        "must be 'cur' string or expression");
                     77:                                } else 
1.172.2.6  paf        78:                                        offset=r.process_to_value(voffset)->as_int();
1.164     paf        79:                        }
1.172.2.14.2.  (paf       80:):                      if(Value* vlimit=options->get(sql_limit_name)) {
1.164     paf        81:                                valid_options++;
1.172.2.6  paf        82:                                limit=r.process_to_value(vlimit)->as_int();
1.172.2.12  paf        83:                                if(!limit) // zero limit = should be 'nothing to copy', for methods zero means 'all'
                     84:                                        limit=-1; // thus fixing
1.164     paf        85:                        }
1.172.2.6  paf        86:                        if(valid_options!=options->count())
1.164     paf        87:                                throw Exception("parser.runtime",
1.172.2.5  paf        88:                                        method_name,
1.164     paf        89:                                        "called with invalid option");
1.157     paf        90:                } else
                     91:                        throw Exception("parser.runtime",
1.172.2.5  paf        92:                                method_name,
1.157     paf        93:                                "options must be hash");
1.158     paf        94:        }
1.157     paf        95: }
                     96: 
1.172.2.14.2.  (paf       97:): static void _create(Request& r, MethodParams* params) {
1.157     paf        98:        // clone/copy part?
1.172.2.10  paf        99:        if(const Table *source=(*params)[0]->get_table()) {
1.157     paf       100:                int offset, limit;
                    101:                get_copy_options(r, method_name, params, 1, *source, 
                    102:                        offset, limit);
1.172.2.14.2.  (paf      103:):              GET_SELF(r, VTable).set_table(Table*(new Table(*source, offset, limit)));
1.157     paf       104:                return;
                    105:        }
1.142     paf       106: 
1.1       paf       107:        // data is last parameter
1.172.2.14.2.  (paf      108:):      Temp_lang temp_lang(r, String::L_PASS_APPENDED);
                    109:):      const String&  data=
1.172.2.10  paf       110:                r.process_to_string(params->as_junction(params->count()-1, "body must be code"));
1.44      paf       111: 
                    112:        size_t pos_after=0;
                    113:        // parse columns
1.172.2.6  paf       114:        Table::columns_type columns;
1.172.2.10  paf       115:        if(params->count()==2) {
1.172.2.6  paf       116:                columns=Table::columns_type(0); // nameless
1.21      paf       117:        } else {
1.172.2.6  paf       118:                columns=Table::columns_type(new ArrayString);
1.44      paf       119: 
1.172.2.6  paf       120:                ArrayString head;
1.172.2.14.2.  (paf      121:):              data->split(head, &pos_after, "\n", 1, String::L_AS_IS, 1);
1.172.2.6  paf       122:                if(head.count())
1.172.2.14.2.  (paf      123:):                      head[0]->split(*columns, 0, "\t", 1, String::L_AS_IS);
1.44      paf       124:        }
                    125: 
1.172.2.14.2.  (paf      126:):      Table* table(new Table(method_name, columns));
1.44      paf       127:        // parse cells
1.172.2.6  paf       128: 
                    129:        ArrayString rows;
1.172.2.14.2.  (paf      130:):      data->split(rows, &pos_after, "\n", 1, String::L_AS_IS);
                    131:):      Array_iterator<String*> i(rows);
1.98      parser    132:        while(i.has_next()) {
1.172.2.6  paf       133:                Table::element_type row(new ArrayString);
1.172.2.14.2.  (paf      134:):              const String&  string=i.next();
1.118     parser    135:                // remove comment lines
1.172.2.14.2.  (paf      136:):              if(!string->length())
1.44      paf       137:                        continue;
                    138: 
1.172.2.14.2.  (paf      139:):              string->split(*row, 0, "\t", 1, String::L_AS_IS);
1.172.2.6  paf       140:                *table+=row;
1.17      paf       141:        }
1.1       paf       142: 
1.44      paf       143:        // replace any previous table value
1.172.2.6  paf       144:        GET_SELF(r, VTable).set_table(table);
1.44      paf       145: }
                    146: 
1.172.2.14.2.  (paf      147:): static void _load(Request& r, MethodParams* params) {
                    148:):      const String&  first_param=params->as_string(0, "file name must be string");
1.168     paf       149:        int filename_param_index=0;
1.172.2.6  paf       150:        bool nameless=*first_param=="nameless";
1.168     paf       151:        if(nameless)
                    152:                filename_param_index++;
                    153:        int options_param_index=filename_param_index+1;
                    154:        
1.44      paf       155:        // loading text
1.172.2.14.2.  (paf      156:):      char *data=file_read_text(r.charsets.source(),
1.172.2.10  paf       157:                r.absolute(params->as_string(filename_param_index, "file name must be string")),
1.168     paf       158:                true,
1.172.2.14.2.  (paf      159:):              options_param_index<params->count()?params->as_no_junction(options_param_index, "additional params must be hash")->get_hash():0
1.168     paf       160:        );
1.44      paf       161: 
1.1       paf       162:        // parse columns
1.172.2.6  paf       163:        Table::columns_type columns;
1.1       paf       164: #ifndef NO_STRING_ORIGIN
1.172.2.6  paf       165:        const String_fragment::Origin& origin=method_name->origin();
1.172.2.2  paf       166:        const char* file=origin.file;
1.1       paf       167:        uint line=origin.line;
                    168: #endif
1.168     paf       169:        if(nameless) {
1.172.2.6  paf       170:                columns=Table::columns_type(0); // nameless
1.1       paf       171:        } else {
1.172.2.6  paf       172:                columns=Table::columns_type(new ArrayString);
1.1       paf       173: 
1.139     paf       174:                while(char *row_chars=getrow(&data)) {
                    175:                        // remove empty&comment lines
                    176:                        if(!*row_chars || *row_chars == '#')
                    177:                                continue;
1.1       paf       178:                        do {
1.172.2.14.2.  (paf      179:):                              const String& name(new String);
1.45      paf       180:                                name->APPEND_TAINTED(lsplit(&row_chars, '\t'), 0, file, line++);
1.1       paf       181:                                *columns+=name;
                    182:                        } while(row_chars);
1.139     paf       183: 
                    184:                        break;
                    185:                }
1.1       paf       186:        }
                    187: 
                    188:        // parse cells
1.172.2.14.2.  (paf      189:):      Table* table(new Table(method_name, columns));
1.1       paf       190:        char *row_chars;
                    191:        while(row_chars=getrow(&data)) {
1.118     parser    192:                // remove empty&comment lines
                    193:                if(!*row_chars || *row_chars == '#')
1.28      paf       194:                        continue;
1.172.2.6  paf       195:                Table::element_type row(new ArrayString);
1.1       paf       196:                while(char *cell_chars=lsplit(&row_chars, '\t')) {
1.172.2.14.2.  (paf      197:):                      const String& cell(new String);
1.44      paf       198:                        cell->APPEND_TAINTED(cell_chars, 0, file, line);
1.1       paf       199:                        *row+=cell;
                    200:                }
1.107     parser    201: #ifndef NO_STRING_ORIGIN
1.1       paf       202:                line++;
1.107     parser    203: #endif
1.172.2.6  paf       204:                *table+=row;
1.1       paf       205:        };
                    206: 
                    207:        // replace any previous table value
1.172.2.6  paf       208:        GET_SELF(r, VTable).set_table(table);
1.1       paf       209: }
1.2       paf       210: 
1.146     paf       211: /// @todo "x\nx" "xxx""xx"
1.172.2.14.2.  (paf      212:): static void _save(Request& r, MethodParams* params) {
                    213:):      Value& vfile_name=params->as_no_junction(params->count()-1, "file name must not be code");
1.22      paf       214: 
1.172.2.14.2.  (paf      215:):      Table& table=GET_SELF(r, VTable).table();
1.31      paf       216: 
1.129     paf       217:        bool do_append=false;
1.172.2.6  paf       218:        String sdata;
1.172.2.10  paf       219:        if(params->count()==1) { // named output
1.31      paf       220:                // write out names line
                    221:                if(table.columns()) { // named table
1.172.2.14.2.  (paf      222:):                      Array_iterator<String*> i(*table.columns());
1.98      parser    223:                        while(i.has_next()) {
1.172.2.14.2.  (paf      224:):                              sdata.append(*i.next(), String::L_TABLE);
1.98      parser    225:                                if(i.has_next())
1.31      paf       226:                                        sdata.APPEND_CONST("\t");
                    227:                        }
                    228:                } else { // nameless table
1.172.2.6  paf       229:                        if(int lsize=table.count()?table[0]->count():0)
1.31      paf       230:                                for(int column=0; column<lsize; column++) {
1.172.2.14.2.  (paf      231:):                                      char *cindex_tab=new char[MAX_NUMBER];
                    232:):                                      sdata.append(cindex_tab, 
                    233:):                                              snprintf(cindex_tab, MAX_NUMBER, "%d\t", column),
                    234:):                                              String::L_CLEAN);
1.31      paf       235:                                }
                    236:                        else
                    237:                                sdata.APPEND_CONST("empty nameless table");
                    238:                }
                    239:                sdata.APPEND_CONST("\n");
1.129     paf       240:        } else { // mode specified
1.172.2.14.2.  (paf      241:):              const String&  mode=params->as_string(0, "mode must be string");
1.172.2.6  paf       242:                if(*mode=="append")
1.129     paf       243:                        do_append=true;
1.172.2.6  paf       244:                else if(*mode=="nameless")
1.129     paf       245:                        /*ok, already skipped names output*/;
                    246:                else
1.146     paf       247:                        throw Exception("parser.runtime",
1.172.2.6  paf       248:                                mode,
1.129     paf       249:                                "unknown mode, must be 'append'");
                    250: 
1.31      paf       251:        }
                    252:        // data lines
1.172.2.14.2.  (paf      253:):      Array_iterator<ArrayString*> i(table);
1.98      parser    254:        while(i.has_next()) {
1.172.2.14.2.  (paf      255:):              Array_iterator<String*> c(*i.next());
1.98      parser    256:                while(c.has_next()) {
1.172.2.14.2.  (paf      257:):                      if(const String* s=c.next())
                    258:):                              sdata.append(*s, String::L_TABLE);
1.98      parser    259:                        if(c.has_next())
1.172.2.14.2.  (paf      260:):                              sdata.append("\t", 1, String::L_CLEAN);
1.31      paf       261:                }
1.172.2.14.2.  (paf      262:):              sdata.append("\n", 1, String::L_CLEAN);
1.31      paf       263:        }
                    264: 
                    265:        // write
1.172.2.14.2.  (paf      266:):      file_write(r.absolute(vfile_name.as_string()), 
                    267:):              sdata.cstr(), sdata.length(), true, do_append);
1.22      paf       268: }
                    269: 
1.172.2.14.2.  (paf      270:): static void _count(Request& r, MethodParams* ) {
                    271:):      int result=GET_SELF(r, VTable).table().count();
                    272:):      r.write_no_lang(Value*(new VInt(result)));
1.6       paf       273: }
                    274: 
1.172.2.14.2.  (paf      275:): static void _line(Request& r, MethodParams* ) {
                    276:):      int result=1+GET_SELF(r, VTable).table().current();
                    277:):      r.write_no_lang(Value*(new VInt(result)));
1.6       paf       278: }
                    279: 
1.172.2.14.2.  (paf      280:): static void _offset(Request& r, MethodParams* params) {
                    281:):      Table& table=GET_SELF(r, VTable).table();
1.172.2.10  paf       282:        if(params->count()) {
1.133     paf       283:                bool absolute=false;
1.172.2.10  paf       284:                if(params->count()>1) {
1.172.2.14.2.  (paf      285:):                  const String&  whence=params->as_string(0, "whence must be string");
1.172.2.6  paf       286:                    if(*whence=="cur")
1.134     paf       287:                                absolute=false;
1.172.2.6  paf       288:                    else if(*whence=="set")
1.134     paf       289:                                absolute=true;
1.133     paf       290:                    else
1.146     paf       291:                                throw Exception("parser.runtime",
1.172.2.6  paf       292:                                        whence,
1.134     paf       293:                                        "is invalid whence, valid are 'cur' or 'set'");
1.157     paf       294:                }
1.133     paf       295:                
1.172.2.14.2.  (paf      296:):              Value* offset_expr=params->as_junction(params->count()-1, "offset must be expression");
1.172.2.6  paf       297:                table.offset(absolute, r.process_to_value(offset_expr)->as_int());
1.151     paf       298:        } else
1.172.2.14.2.  (paf      299:):              r.write_no_lang(Value*(new VInt(table.current())));
1.6       paf       300: }
                    301: 
1.172.2.14.2.  (paf      302:): static void _menu(Request& r, MethodParams* params) {
                    303:):      Value* body_code=params->as_junction(0, "body must be code");
1.7       paf       304:        
1.172.2.14.2.  (paf      305:):      Value* delim_maybe_code=params->count()>1?(*params)[1]:0;
1.7       paf       306: 
1.172.2.14.2.  (paf      307:):      Table& table=GET_SELF(r, VTable).table();
1.7       paf       308:        bool need_delim=false;
1.99      parser    309:        int saved_current=table.current();
1.172.2.6  paf       310:        int size=table.count();
1.99      parser    311:        for(int row=0; row<size; row++) {
1.22      paf       312:                table.set_current(row);
1.7       paf       313: 
1.161     paf       314:                StringOrValue sv_processed=r.process(body_code);
1.172.2.14.2.  (paf      315:):              const String& s_processed=sv_processed.get_string();
                    316:):              if(delim_maybe_code && s_processed && s_processed->length()) { // delimiter set and we have body
1.161     paf       317:                        if(need_delim) // need delim & iteration produced string?
1.172.2.6  paf       318:                                r.write_pass_lang(r.process(delim_maybe_code));
1.7       paf       319:                        need_delim=true;
                    320:                }
1.161     paf       321:                r.write_pass_lang(sv_processed);
1.7       paf       322:        }
1.99      parser    323:        table.set_current(saved_current);
1.7       paf       324: }
                    325: 
1.110     parser    326: #ifndef DOXYGEN
1.74      paf       327: struct Row_info {
1.166     paf       328:        Request *r;
1.74      paf       329:        Table *table;
1.172.2.14.2.  (paf      330:):      Value* key_code;
1.74      paf       331:        int key_field;
1.172.2.6  paf       332:        Array<int>* value_fields;
                    333:        HashStringValue* hash;
1.163     paf       334:        bool distinct;
1.167     paf       335:        int row;
1.74      paf       336: };
1.110     parser    337: #endif
1.172.2.6  paf       338: static void table_row_to_hash(Table::element_type row, Row_info *info) {
1.172.2.14.2.  (paf      339:):      const String& key;
1.172.2.6  paf       340:        if(info->key_code) {
                    341:                info->table->set_current(info->row++); // change context row
                    342:                StringOrValue sv_processed=info->r->process(info->key_code);
1.172.2.14.2.  (paf      343:):              key=sv_processed.as_string();
1.166     paf       344:        } else
1.172.2.14.2.  (paf      345:):              key=info->key_field<row->count()?row->get(info->key_field):0;
1.166     paf       346: 
                    347:        if(!key)
                    348:                return; // ignore rows without key [too-short-record_array if-indexed]
1.74      paf       349:                
1.172.2.14.2.  (paf      350:):      VHash* vhash=new VHash;
1.172.2.6  paf       351:        HashStringValue& hash=vhash->hash();
                    352:        for(int i=0; i<info->value_fields->count(); i++) {
                    353:                int value_field=info->value_fields->get(i);
                    354:                if(value_field<row->count())
1.166     paf       355:                        hash.put(
1.172.2.6  paf       356:                                info->table->columns()->get(value_field), 
1.172.2.14.2.  (paf      357:):                              Value*(new VString(row->get(value_field))));
1.74      paf       358:        }
1.166     paf       359: 
1.172.2.6  paf       360:        if(info->hash->put_dont_replace(key, vhash)) // put. existed?
                    361:                if(!info->distinct)
1.166     paf       362:                        throw Exception("parser.runtime",
1.172.2.14.2.  (paf      363:):                              &key,
1.166     paf       364:                                "duplicate key");
1.74      paf       365: }
1.172.2.14.2.  (paf      366:): static void _hash(Request& r, MethodParams* params) {
                    367:):      Table& self_table=GET_SELF(r, VTable).table();
                    368:):      VHash* result(new VHash);
1.172.2.6  paf       369:        if(Table::columns_type columns=self_table.columns())
                    370:                if(columns->count()>0) {
1.163     paf       371:                        bool distinct=false;
1.172.2.10  paf       372:                        int param_index=params->count()-1;
1.166     paf       373:                        if(param_index>0) {
1.172.2.6  paf       374:                                if(HashStringValue* options=
1.172.2.14.2.  (paf      375:):                                      params->as_no_junction(param_index, "param must not be code")->get_hash()) {
1.166     paf       376:                                        --param_index;
                    377:                                        int valid_options=0;
1.172.2.14.2.  (paf      378:):                                      if(Value* vdistinct=options->get(sql_distinct_name)) {
1.166     paf       379:                                                valid_options++;
1.172.2.6  paf       380:                                                distinct=r.process_to_value(vdistinct)->as_bool();
1.166     paf       381:                                        }
1.172.2.6  paf       382:                                        if(valid_options!=options->count())
1.166     paf       383:                                                throw Exception("parser.runtime",
1.172.2.5  paf       384:                                                        method_name,
1.166     paf       385:                                                        "called with invalid option");
1.163     paf       386:                                }
                    387:                        }
                    388:                        if(param_index==2) // bad options param type
                    389:                                throw Exception("parser.runtime",
1.172.2.5  paf       390:                                        method_name,
1.163     paf       391:                                        "options must be hash");
                    392: 
1.172.2.6  paf       393:                        Array<int> value_fields;
1.163     paf       394:                        if(param_index>0) {
1.172.2.14.2.  (paf      395:):                              Value* value_fields_param=params->as_no_junction(param_index, "value field(s) must not be code");
1.172.2.6  paf       396:                                if(value_fields_param->is_string()) {
                    397:                                        value_fields+=self_table.column_name2index(
1.172.2.14.2.  (paf      398:):                                              value_fields_param->as_string(), true);
1.172.2.6  paf       399:                                } else if(Table* value_fields_table=value_fields_param->get_table()) {
                    400:                                        for(int i=0; i<value_fields_table->count(); i++) {
1.172.2.14.2.  (paf      401:):                                              const String&  value_field_name=
1.172.2.6  paf       402:                                                        value_fields_table->get(i)->get(0);
1.123     parser    403:                                                value_fields+=self_table.column_name2index(value_field_name, true);
                    404:                                        }
                    405:                                } else
1.146     paf       406:                                        throw Exception("parser.runtime",
1.172.2.5  paf       407:                                                method_name,
1.123     parser    408:                                                "value field(s) must be string or self_table"
                    409:                                        );
                    410:                        } else { // by all columns, including key
1.172.2.6  paf       411:                                for(int i=0; i<columns->count(); i++)
1.123     parser    412:                                        value_fields+=i;
1.74      paf       413:                        }
                    414: 
1.172.2.6  paf       415: 
                    416:                        {
                    417:                                Row_info info;
                    418:                                info.r=&r;
                    419:                                info.table=&self_table;
1.172.2.14.2.  (paf      420:):                              Value* key_param=(*params)[0];
                    421:):                              info.key_code=key_param->get_junction()?key_param:0;
1.172.2.6  paf       422:                                info.key_field=info.key_code?-1
1.172.2.14.2.  (paf      423:):                                      :self_table.column_name2index(key_param->as_string(), true);
1.172.2.6  paf       424:                                info.value_fields=&value_fields;
                    425:                                info.hash=&result->hash();
                    426:                                info.distinct=distinct;
1.172.2.12  paf       427:                                info.row=0;
1.172.2.6  paf       428: 
                    429:                                int saved_current=self_table.current();
                    430:                                self_table.for_each(table_row_to_hash, &info);
                    431:                                self_table.set_current(saved_current);
                    432:                        }
1.74      paf       433:                }
1.97      parser    434:        r.write_no_lang(result);
1.74      paf       435: }
                    436: 
1.110     parser    437: #ifndef DOXYGEN
1.78      paf       438: struct Table_seq_item {
1.172.2.13  paf       439:        ArrayString* row;
1.34      paf       440:        union {
                    441:                char *c_str;
                    442:                double d;
                    443:        } value;
1.32      paf       444: };
1.110     parser    445: #endif
1.34      paf       446: static int sort_cmp_string(const void *a, const void *b) {
                    447:        return strcmp(
1.78      paf       448:                static_cast<const Table_seq_item *>(a)->value.c_str, 
                    449:                static_cast<const Table_seq_item *>(b)->value.c_str
1.34      paf       450:        );
                    451: }
                    452: static int sort_cmp_double(const void *a, const void *b) {
1.78      paf       453:        double va=static_cast<const Table_seq_item *>(a)->value.d;
                    454:        double vb=static_cast<const Table_seq_item *>(b)->value.d;
1.34      paf       455:        if(va<vb)
                    456:                return -1;
                    457:        else if(va>vb)
                    458:                return +1;
                    459:        else 
                    460:                return 0;
                    461: }
1.172.2.14.2.  (paf      462:): static void _sort(Request& r, MethodParams* params) {
1.172.2.6  paf       463:        Pool local_pool;
1.172.2.14.2.  (paf      464:):      Value* key_maker=params->as_junction(0, "key-maker must be code");
1.61      paf       465: 
1.172.2.10  paf       466:        bool reverse=params->count()>1/*..[desc|asc|]*/?
                    467:                reverse=*params->as_no_junction(1, "order must not be code")->as_string(&local_pool)=="desc":
1.104     parser    468:                false; // default=asc
1.32      paf       469: 
1.172.2.14.2.  (paf      470:):      Table& old_table=GET_SELF(r, VTable).table();
                    471:):      Table* new_table(new Table(method_name, old_table.columns()));
1.34      paf       472: 
1.172.2.6  paf       473:        smart_ptr<Table_seq_item> seq(new Table_seq_item[old_table.count()]);
1.34      paf       474:        int i;
                    475: 
                    476:        // calculate key values
                    477:        bool key_values_are_strings=true;
1.172.2.6  paf       478:        for(i=0; i<old_table.count(); i++) {
1.101     parser    479:                old_table.set_current(i);
1.32      paf       480:                // calculate key value
1.172.2.14.2.  (paf      481:):              seq[i].row=old_table[i];
                    482:):              Value* value=r.process_to_value(key_maker)->as_expr_result(true/*return string as-is*/);
1.34      paf       483:                if(i==0) // determining key values type by first one
1.172.2.6  paf       484:                        key_values_are_strings=value->is_string();
1.34      paf       485: 
                    486:                if(key_values_are_strings)
1.172.2.6  paf       487:                        seq[i].value.c_str=value->as_string(&local_pool)->cstr(local_pool);
1.34      paf       488:                else
1.172.2.6  paf       489:                        seq[i].value.d=value->as_double();
1.32      paf       490:        }
                    491:        // sort keys
1.172.2.6  paf       492:        _qsort(seq, old_table.count(), sizeof(Table_seq_item), 
1.34      paf       493:                key_values_are_strings?sort_cmp_string:sort_cmp_double);
1.32      paf       494: 
1.34      paf       495:        // reorder table as they require in 'seq'
1.172.2.6  paf       496:        for(i=0; i<old_table.count(); i++)
1.172.2.13  paf       497:                *new_table+=Table::element_type(seq[reverse?old_table.count()-1-i:i].row);
1.32      paf       498: 
1.116     parser    499:        // replace any previous table value
1.172.2.6  paf       500:        GET_SELF(r, VTable).set_table(new_table);
1.32      paf       501: }
                    502: 
1.172.2.14.2.  (paf      503:): static bool _locate_expression(Request& r, MethodParams* params) {
1.172.2.10  paf       504:        if(params->count()>1)
1.146     paf       505:                throw Exception("parser.runtime", 
1.172.2.5  paf       506:                        method_name,
1.145     paf       507:                        "locate by expression has only one parameter - expression");
                    508: 
1.172.2.14.2.  (paf      509:):      Value* expression_code=params->as_junction(0, "must be expression");
1.145     paf       510: 
1.172.2.14.2.  (paf      511:):      Table& table=GET_SELF(r, VTable).table();
1.145     paf       512:        int saved_current=table.current();
1.172.2.6  paf       513:        int size=table.count();
1.145     paf       514:        for(int row=0; row<size; row++) {
                    515:                table.set_current(row);
                    516: 
1.172.2.6  paf       517:                if(r.process_to_value(expression_code)->as_bool())
1.145     paf       518:                        return true;
                    519:        }
                    520:        table.set_current(saved_current);
                    521:        return false;
                    522: }
1.172.2.14.2.  (paf      523:): static bool _locate_name_value(Request& r, MethodParams* params) {
1.172.2.10  paf       524:        if(params->count()>2)
1.146     paf       525:                throw Exception("parser.runtime", 
1.172.2.5  paf       526:                        method_name,
1.145     paf       527:                        "locate by name and value has only two parameters - name and value");
1.72      paf       528: 
1.172.2.14.2.  (paf      529:):      Table& table=GET_SELF(r, VTable).table();
1.145     paf       530:        return table.locate(
1.172.2.10  paf       531:                params->as_string(0, "column name must be string"),
                    532:                params->as_string(1, "value must be string")
1.145     paf       533:        );
                    534: }
1.172.2.14.2.  (paf      535:): static void _locate(Request& r, MethodParams* params) {
1.172.2.10  paf       536:        bool result=(*params)[0]->get_junction()?
1.145     paf       537:                _locate_expression(r, method_name, params) :
1.151     paf       538:                _locate_name_value(r, method_name, params);
1.172.2.14.2.  (paf      539:):      r.write_no_lang(Value*(new VBool(result)));
1.37      paf       540: }
                    541: 
1.172.2.14.2.  (paf      542:): static void _flip(Request& r, MethodParams* params) {
                    543:):      Table& old_table=GET_SELF(r, VTable).table();
                    544:):      Table* new_table(new Table(method_name, old_table.columns()));
1.172.2.6  paf       545:        if(old_table.count())
                    546:                if(int old_cols=old_table[0]->count()) 
1.39      paf       547:                        for(int column=0; column<old_cols; column++) {
1.172.2.6  paf       548:                                Table::element_type new_row(new ArrayString(old_table.count()));
                    549:                                for(int i=0; i<old_table.count(); i++) {
                    550:                                        Table::element_type old_row=old_table[i];
1.172.2.14.2.  (paf      551:):                                      *new_row+=column<old_row->count()?old_row->get(column):String* (new String);
1.39      paf       552:                                }
1.172.2.6  paf       553:                                *new_table+=new_row;
1.39      paf       554:                        }
                    555: 
1.172.2.14.2.  (paf      556:):      r.write_no_lang(Value*(new VTable(new_table)));
1.39      paf       557: }
                    558: 
1.172.2.14.2.  (paf      559:): static void _append(Request& r, MethodParams* params) {
1.134     paf       560:        // data
1.172.2.14.2.  (paf      561:):      Temp_lang temp_lang(r, String::L_PASS_APPENDED);
                    562:):      const String& string=r.process_to_string(params->as_junction(0, "body must be code"));
1.41      paf       563: 
                    564:        // parse cells
1.172.2.14.2.  (paf      565:):      ArrayString& row(new ArrayString);
                    566:):      string->split(*row, 0, "\t", 1, String::L_AS_IS);
1.41      paf       567: 
1.172.2.14.2.  (paf      568:):      GET_SELF(r, VTable).table()+=row;
1.41      paf       569: }
                    570: 
1.172.2.14.2.  (paf      571:): static void _join(Request& r, MethodParams* params) {
1.42      paf       572: 
1.172.2.10  paf       573:        Table* maybe_src=params->as_no_junction(0, "table ref must not be code")->get_table();
1.42      paf       574:        if(!maybe_src)
1.146     paf       575:                throw Exception("parser.runtime", 
1.172.2.5  paf       576:                        method_name, 
1.42      paf       577:                        "source is not a table");
                    578: 
                    579:        Table& src=*maybe_src;
1.172.2.14.2.  (paf      580:):      Table& dest=GET_SELF(r, VTable).table();
1.42      paf       581:        if(&src == &dest)
1.146     paf       582:                throw Exception("parser.runtime", 
1.172.2.5  paf       583:                        method_name, 
1.42      paf       584:                        "source and destination are same table");
                    585: 
1.157     paf       586:        int offset, limit;
                    587:        get_copy_options(r, method_name, params, 1, src, 
                    588:                offset, limit);
                    589: 
1.172.2.6  paf       590:        if(Table::columns_type dest_columns=dest.columns()) { // dest is named
1.42      paf       591:                int saved_src_current=src.current();
1.172.2.6  paf       592:                int m=src.count()-offset;
1.157     paf       593:                if(!limit || limit>m)
                    594:                        limit=m;
                    595:                int end=offset+limit;
                    596:                for(int src_row=offset; src_row<end; src_row++) {
1.42      paf       597:                        src.set_current(src_row);
1.172.2.6  paf       598:                        Table::element_type dest_row(new ArrayString(src.count()));
                    599:                        for(int dest_column=0; dest_column<dest_columns->count(); dest_column++) {
1.172.2.14.2.  (paf      600:):                              const String& src_item=src.item(dest_columns->get(dest_column));
                    601:):                              *dest_row+=src_item?src_item:String* (new String);
1.140     paf       602:                        }
1.172.2.6  paf       603:                        dest+=dest_row;
1.42      paf       604:                }
                    605:                src.set_current(saved_src_current);
                    606:        } else { // dest is nameless
1.172.2.6  paf       607:                for(int src_row=0; src_row<src.count(); src_row++)
                    608:                        dest+=src[src_row];
1.42      paf       609:        }
                    610: }
                    611: 
1.94      parser    612: #ifndef DOXYGEN
1.169     paf       613: class Table_sql_event_handlers: public SQL_Driver_query_event_handlers {
1.172.2.14.2.  (paf      614:):      const String&  method_name;
                    615:):      const String&  statement_string; const char* statement_cstr;
                    616:):      ArrayString& columns;
1.172.2.6  paf       617:        ArrayString* row;
                    618: public:
1.172.2.14.2.  (paf      619:):      Table* table;
1.94      parser    620: public:
1.172.2.14.2.  (paf      621:):      Table_sql_event_handlers(const String& amethod_name,
                    622:):              const String& astatement_string, const char* astatement_cstr) :
1.94      parser    623:                method_name(amethod_name),
1.172.2.14  paf       624:                statement_string(astatement_string), statement_cstr(astatement_cstr),
                    625:                columns(new ArrayString), row(0) {
                    626:        }
1.94      parser    627: 
1.170     paf       628:        bool add_column(SQL_Error& error, void *ptr, size_t size) {
                    629:                try {
1.172.2.14.2.  (paf      630:):                      const String& column(new String);
1.170     paf       631:                        column->APPEND_TAINTED(
1.172.2.2  paf       632:                                (const char* )ptr, size, 
1.170     paf       633:                                statement_cstr, 0);
1.172.2.6  paf       634:                        *columns+=column;
1.170     paf       635:                        return false;
                    636:                } catch(...) {
                    637:                        error=SQL_Error("exception occured in Table_sql_event_handlers::add_column");
                    638:                        return true;
                    639:                }
                    640:        }
                    641:        bool before_rows(SQL_Error& error) { 
                    642:                try {
1.172.2.14.2.  (paf      643:):                      table=Table*(new Table( method_name, columns));
1.170     paf       644:                        return false;
                    645:                } catch(...) {
                    646:                        error=SQL_Error("exception occured in Table_sql_event_handlers::before_rows");
                    647:                        return true;
                    648:                }
                    649:        }
                    650:        bool add_row(SQL_Error& error) {
                    651:                try {
1.172.2.14.2.  (paf      652:):                      *table+=(ArrayString* (row=new ArrayString));
1.170     paf       653:                        return false;
                    654:                } catch(...) {
                    655:                        error=SQL_Error("exception occured in Table_sql_event_handlers::add_row");
                    656:                        return true;
                    657:                }
                    658:        }
                    659:        bool add_row_cell(SQL_Error& error, void *ptr, size_t size) {
                    660:                try {
1.172.2.14.2.  (paf      661:):                      const String& cell(new String);
1.170     paf       662:                        if(size)
                    663:                                cell->APPEND_TAINTED(
1.172.2.2  paf       664:                                        (const char* )ptr, size, 
1.172.2.6  paf       665:                                        statement_cstr, table->count()-1);
                    666:                        *row+=cell;
1.170     paf       667:                        return false;
                    668:                } catch(...) {
                    669:                        error=SQL_Error("exception occured in Table_sql_event_handlers::add_row_cell");
                    670:                        return true;
                    671:                }
1.94      parser    672:        }
                    673: };
                    674: #endif
1.172.2.14.2.  (paf      675:): static void _sql(Request& r, MethodParams* params) {
1.49      paf       676: 
1.172.2.14.2.  (paf      677:):      Value* statement=params->as_junction(0, "statement must be code");
1.49      paf       678: 
1.53      paf       679:        ulong limit=0;
1.100     parser    680:        ulong offset=0;
1.172.2.10  paf       681:        if(params->count()>1) {
1.172.2.14.2.  (paf      682:):              Value* voptions=params->as_no_junction(1, "options must be hash, not code");
1.172.2.6  paf       683:                if(!voptions->is_string())
1.172.2.14.2.  (paf      684:):                      if(HashStringValue* options=voptions->get_hash()) {
1.164     paf       685:                                int valid_options=0;
1.172.2.14.2.  (paf      686:):                              if(Value* vlimit=options->get(sql_limit_name)) {
1.164     paf       687:                                        valid_options++;
1.172.2.6  paf       688:                                        limit=(ulong)r.process_to_value(vlimit)->as_double();
1.164     paf       689:                                }
1.172.2.14.2.  (paf      690:):                              if(Value* voffset=options->get(sql_offset_name)) {
1.164     paf       691:                                        valid_options++;
1.172.2.6  paf       692:                                        offset=(ulong)r.process_to_value(voffset)->as_double();
1.164     paf       693:                                }
1.172.2.6  paf       694:                                if(valid_options!=options->count())
1.164     paf       695:                                        throw Exception("parser.runtime",
1.172.2.5  paf       696:                                                method_name,
1.164     paf       697:                                                "called with invalid option");
1.109     parser    698:                        } else
1.146     paf       699:                                throw Exception("parser.runtime",
1.172.2.5  paf       700:                                        method_name,
1.109     parser    701:                                        "options must be hash");
1.49      paf       702:        }
                    703: 
1.172.2.14.2.  (paf      704:):      Temp_lang temp_lang(r, String::L_SQL);
                    705:):      const String&  statement_string=r.process_to_string(statement);
1.172.2.2  paf       706:        const char* statement_cstr=
1.172.2.14.2.  (paf      707:):              statement_string->cstr(String::L_UNSPECIFIED, r.connection());
1.172.2.14  paf       708:        Table_sql_event_handlers handlers(method_name, 
1.94      parser    709:                statement_string, statement_cstr);
1.135     paf       710: #ifdef RESOURCES_DEBUG
                    711:        struct timeval mt[2];
                    712:        //measure:before
                    713:        gettimeofday(&mt[0],NULL);
                    714: #endif 
1.172.2.14.2.  (paf      715:):      r.connection()->query(
1.160     paf       716:                statement_cstr, offset, limit, 
                    717:                handlers,
                    718:                statement_string);
1.135     paf       719:        
                    720: #ifdef RESOURCES_DEBUG
                    721:                //measure:after connect
                    722:        gettimeofday(&mt[1],NULL);
                    723:        
                    724:        double t[2];
                    725:        for(int i=0;i<2;i++)
                    726:            t[i]=mt[i].tv_sec+mt[i].tv_usec/1000000.0;
                    727:            
                    728:        r.sql_request_time+=t[1]-t[0];
                    729: #endif                         
1.96      parser    730: 
1.172.2.14.2.  (paf      731:):      Table* result=
1.96      parser    732:                handlers.table?handlers.table: // query resulted in table? return it
1.172.2.14.2.  (paf      733:):              Table*(new Table(method_name, Table::columns_type(0))); // query returned no table, fake it
1.49      paf       734: 
                    735:        // replace any previous table value
1.172.2.6  paf       736:        GET_SELF(r, VTable).set_table(result);
1.49      paf       737: }
                    738: 
1.172.2.14.2.  (paf      739:): static void _columns(Request& r, MethodParams* ) {
1.88      parser    740: 
1.172.2.6  paf       741:        Table::columns_type result_columns(new ArrayString);
1.172.2.14.2.  (paf      742:):      *result_columns+=String* (new String("column"));
                    743:):      Table* result_table(new Table(method_name, result_columns));
1.172.2.6  paf       744: 
1.172.2.14.2.  (paf      745:):      Table& source_table=GET_SELF(r, VTable).table();
1.172.2.6  paf       746:        if(Table::columns_type source_columns=source_table.columns()) {
1.172.2.14.2.  (paf      747:):              Array_iterator<String*> i(*source_columns);
1.98      parser    748:                while(i.has_next()) {
1.172.2.6  paf       749:                        Table::element_type result_row(new ArrayString);
                    750:                        *result_row+=i.next();
                    751:                        *result_table+=result_row;
1.88      parser    752:                }
                    753:        }
                    754: 
1.172.2.14.2.  (paf      755:):      r.write_no_lang(Value*(new VTable(result_table)));
1.88      parser    756: }
                    757: 
1.172.2.14.2.  (paf      758:): static void _select(Request& r, MethodParams* params) {
1.148     paf       759: 
1.172.2.14.2.  (paf      760:):      Value* vcondition=params->as_junction(0, "condition must be expression");
1.148     paf       761: 
1.172.2.14.2.  (paf      762:):      Table& source_table=GET_SELF(r, VTable).table();
                    763:):      Table* result_table(new Table(
1.148     paf       764:                source_table.origin_string(), 
                    765:                source_table.columns()
1.172.2.6  paf       766:        ));
1.148     paf       767: 
                    768:        int saved_current=source_table.current();
1.172.2.6  paf       769:        int size=source_table.count();
1.148     paf       770:        for(int row=0; row<size; row++) {
                    771:                source_table.set_current(row);
                    772: 
1.150     paf       773:                bool condition=r.process_to_value(vcondition, 
1.149     paf       774:                                /*0/*no name* /,*/
1.172.2.6  paf       775:                                false/*don't intercept string*/)->as_bool();
1.148     paf       776: 
                    777:                if(condition) // ...condition is true=
1.172.2.6  paf       778:                        *result_table+=source_table[row]; // =green light to go to result
1.148     paf       779:        }
                    780:        source_table.set_current(saved_current);
                    781: 
1.172.2.14.2.  (paf      782:):      r.write_no_lang(Value*(new VTable(result_table)));
1.148     paf       783: }
                    784: 
1.66      paf       785: // constructor
                    786: 
1.172.2.6  paf       787: MTable::MTable(): Methoded("table") {
1.142     paf       788:        // ^table::create{data}
                    789:        // ^table::create[nameless]{data}
                    790:        // ^table::create[table]
                    791:        add_native_method("create", Method::CT_DYNAMIC, _create, 1, 2);
                    792:        // old name for compatibility with <= v 1.141 2002/01/25 11:33:45 paf
                    793:        add_native_method("set", Method::CT_DYNAMIC, _create, 1, 2); 
1.2       paf       794: 
1.142     paf       795:        // ^table::load[file]  
                    796:        // ^table::load[nameless;file]
1.168     paf       797:        add_native_method("load", Method::CT_DYNAMIC, _load, 1, 3);
1.22      paf       798: 
                    799:        // ^table.save[file]  
                    800:        // ^table.save[nameless;file]
1.66      paf       801:        add_native_method("save", Method::CT_DYNAMIC, _save, 1, 2);
1.6       paf       802: 
                    803:        // ^table.count[]
1.66      paf       804:        add_native_method("count", Method::CT_DYNAMIC, _count, 0, 0);
1.6       paf       805: 
                    806:        // ^table.line[]
1.66      paf       807:        add_native_method("line", Method::CT_DYNAMIC, _line, 0, 0);
1.6       paf       808: 
1.10      paf       809:        // ^table.offset[]  
1.133     paf       810:        // ^table.offset(offset)
                    811:        // ^table.offset[cur|set](offset)
                    812:        add_native_method("offset", Method::CT_DYNAMIC, _offset, 0, 2);
1.7       paf       813: 
1.10      paf       814:        // ^table.menu{code}  
                    815:        // ^table.menu{code}[delim]
1.66      paf       816:        add_native_method("menu", Method::CT_DYNAMIC, _menu, 1, 2);
1.74      paf       817: 
1.79      paf       818:        // ^table:hash[key field name]
1.123     parser    819:        // ^table:hash[key field name][value field name(s) string/table]
1.163     paf       820:        add_native_method("hash", Method::CT_DYNAMIC, _hash, 1, 3);
1.32      paf       821: 
1.102     parser    822:        // ^table.sort{string-key-maker} ^table.sort{string-key-maker}[desc|asc]
                    823:        // ^table.sort(numeric-key-maker) ^table.sort(numeric-key-maker)[desc|asc]
1.66      paf       824:        add_native_method("sort", Method::CT_DYNAMIC, _sort, 1, 2);
1.8       paf       825: 
1.36      paf       826:        // ^table.locate[field;value]
1.145     paf       827:        add_native_method("locate", Method::CT_DYNAMIC, _locate, 1, 2);
1.39      paf       828: 
                    829:        // ^table.flip[]
1.66      paf       830:        add_native_method("flip", Method::CT_DYNAMIC, _flip, 0, 0);
1.41      paf       831: 
                    832:        // ^table.append{r{tab}e{tab}c{tab}o{tab}r{tab}d}
1.66      paf       833:        add_native_method("append", Method::CT_DYNAMIC, _append, 1, 1);
1.42      paf       834: 
1.157     paf       835:        // ^table.join[table][$.limit(10) $.offset(1) $.offset[cur] ]
                    836:        add_native_method("join", Method::CT_DYNAMIC, _join, 1, 2);
1.49      paf       837: 
                    838: 
1.100     parser    839:        // ^table:sql[query]
                    840:        // ^table:sql[query][$.limit(1) $.offset(2)]
                    841:        add_native_method("sql", Method::CT_DYNAMIC, _sql, 1, 2);
1.88      parser    842: 
                    843:        // ^table:columns[]
                    844:        add_native_method("columns", Method::CT_DYNAMIC, _columns, 0, 0);
1.148     paf       845: 
                    846:        // ^table.select(expression) = table
                    847:        add_native_method("select", Method::CT_DYNAMIC, _select, 1, 1);
1.40      paf       848: }

E-mail: