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

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

E-mail: