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

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

E-mail: