Annotation of parser3/src/classes/hash.C, revision 1.161

1.1       paf         1: /** @file
                      2:        Parser: @b hash parser class.
                      3: 
1.157     moko        4:        Copyright (c) 2001-2023 Art. Lebedev Studio (http://www.artlebedev.com)
                      5:        Authors: Konstantin Morshnev <moko@design.ru>, Alexandr Petrosian <paf@design.ru>
1.41      paf         6: */
1.1       paf         7: 
                      8: #include "classes.h"
1.57      paf         9: #include "pa_vmethod_frame.h"
                     10: 
1.1       paf        11: #include "pa_request.h"
1.122     moko       12: #include "pa_charsets.h"
1.1       paf        13: #include "pa_vhash.h"
1.6       parser     14: #include "pa_vvoid.h"
1.2       parser     15: #include "pa_sql_connection.h"
1.9       parser     16: #include "pa_vtable.h"
1.22      parser     17: #include "pa_vbool.h"
1.26      paf        18: #include "pa_vmethod_frame.h"
1.2       parser     19: 
1.161   ! moko       20: volatile const char * IDENT_HASH_C="$Id: hash.C,v 1.160 2024/09/27 20:49:10 moko Exp $";
1.113     moko       21: 
1.1       paf        22: // class
                     23: 
1.57      paf        24: class MHash: public Methoded {
1.2       parser     25: public: // VStateless_class
1.103     misha      26:        Value* create_new_value(Pool&) { return new VHash(); }
1.2       parser     27: 
1.1       paf        28: public:
1.57      paf        29:        MHash();
1.1       paf        30: };
                     31: 
1.57      paf        32: // global variable
                     33: 
1.126     moko       34: DECLARE_CLASS_VAR(hash, new MHash);
1.57      paf        35: 
1.1       paf        36: // methods
                     37: 
1.11      parser     38: #ifndef DOXYGEN
1.52      paf        39: class Hash_sql_event_handlers: public SQL_Driver_query_event_handlers {
1.57      paf        40:        bool distinct;
1.159     moko       41:        HashStringValue& result;
1.86      misha      42:        Value* row_value;
1.57      paf        43:        int column_index;
1.86      misha      44:        ArrayString& columns;
                     45:        bool one_bool_column;
                     46:        Table2hash_value_type value_type;
                     47:        int columns_count;
                     48: public:
                     49:        Table* empty;
1.11      parser     50: public:
1.159     moko       51:        Hash_sql_event_handlers(bool adistinct, HashStringValue& aresult, Table2hash_value_type avalue_type):
1.49      paf        52:                distinct(adistinct),
1.159     moko       53:                result(aresult),
1.86      misha      54:                row_value(0),
1.67      paf        55:                column_index(0),
1.139     moko       56:                columns(*new ArrayString),
1.86      misha      57:                one_bool_column(false),
1.139     moko       58:                value_type(avalue_type),
1.86      misha      59:                empty(0) {
1.11      parser     60:        }
1.86      misha      61: 
1.109     misha      62:        bool add_column(SQL_Error& error, const char* str, size_t ) {
1.53      paf        63:                try {
1.107     moko       64:                        columns+=new String(str, String::L_TAINTED /* no length as 0x00 can be inside */);
1.53      paf        65:                        return false;
                     66:                } catch(...) {
1.142     moko       67:                        error=SQL_Error("exception occurred in Hash_sql_event_handlers::add_column");
1.53      paf        68:                        return true;
                     69:                }
1.11      parser     70:        }
1.86      misha      71: 
1.53      paf        72:        bool before_rows(SQL_Error& error) { 
1.67      paf        73:                if(columns.count()<1) {
1.145     moko       74:                        error=SQL_Error("no columns");
1.53      paf        75:                        return true;
                     76:                }
1.86      misha      77:                switch(value_type){
                     78:                        case C_STRING: {
                     79:                                if(columns.count()>2){
1.145     moko       80:                                        error=SQL_Error("only 2 columns allowed for $.type[string].");
1.86      misha      81:                                        return true;
                     82:                                }
                     83:                        }
                     84:                        case C_TABLE: {
                     85:                                // create empty table which we'll copy later
                     86:                                empty=new Table(&columns);
                     87:                                columns_count=columns.count();
                     88:                        }
                     89:                        case C_HASH: {
                     90:                                one_bool_column=columns.count()==1;
                     91:                        }
                     92:                }
1.53      paf        93:                return false;
1.11      parser     94:        }
1.86      misha      95: 
1.53      paf        96:        bool add_row(SQL_Error& /*error*/) {
1.11      parser     97:                column_index=0;
1.53      paf        98:                return false;
1.11      parser     99:        }
1.86      misha     100: 
1.116     misha     101:        bool add_row_cell(SQL_Error& error, const char *str, size_t ) {
1.53      paf       102:                try {
1.145     moko      103:                        const String& cell=str ? *new String(str, String::L_TAINTED /* no length as 0x00 can be inside */) : String::Empty;
1.86      misha     104: 
1.69      paf       105:                        bool duplicate=false;
1.86      misha     106:                        if(one_bool_column) {
1.159     moko      107:                                duplicate=result.put_dont_replace(cell, &VBool::get(true));  // put. existed?
1.69      paf       108:                        } else if(column_index==0) {
1.86      misha     109:                                switch(value_type){
                    110:                                        case C_HASH: {
                    111:                                                VHash* row_vhash=new VHash;
                    112:                                                row_value=row_vhash;
1.159     moko      113:                                                duplicate=result.put_dont_replace(cell, row_vhash); // put. existed?
1.86      misha     114:                                                break;
                    115:                                        }
                    116:                                        case C_STRING: {
                    117:                                                VString* row_vstring=new VString();
                    118:                                                row_value=row_vstring;
1.159     moko      119:                                                duplicate=result.put_dont_replace(cell, row_vstring);  // put. existed?
1.86      misha     120:                                                break;
                    121:                                        }
                    122:                                        case C_TABLE: {
1.159     moko      123:                                                VTable* vtable=(VTable*)result.get(cell);
1.86      misha     124: 
                    125:                                                if(vtable) { // table with this key exist?
                    126:                                                        if(!distinct) {
                    127:                                                                duplicate=true;
                    128:                                                                break;
                    129:                                                        }
                    130:                                                } else {
                    131:                                                        // no? creating table of same structure as source
                    132:                                                        Table::Action_options table_options(0, 0);
1.160     moko      133:                                                        vtable=new VTable(new Table(*empty, table_options/*no rows, just structure*/));
1.159     moko      134:                                                        result.put(cell, vtable); // put
1.86      misha     135:                                                }
                    136:                                                ArrayString* row=new ArrayString(columns_count);
                    137:                                                row_value=(Value*)row;
                    138:                                                *row+=&cell;
1.160     moko      139:                                                *vtable->get_table()+=row;
1.86      misha     140:                                                break;
                    141:                                        }
                    142:                                }
                    143:                        } else {
                    144:                                switch(value_type) {
                    145:                                        case C_HASH: {
                    146:                                                row_value->get_hash()->put(*columns[column_index], new VString(cell));
                    147:                                                break;
                    148:                                        }
                    149:                                        case C_STRING: {
                    150:                                                VString* row_string=(VString*)row_value;
                    151:                                                row_string->set_string(cell);
                    152:                                                break;
                    153:                                        }
                    154:                                        case C_TABLE: {
                    155:                                                ArrayString* row=(ArrayString*)row_value;
                    156:                                                *row+=&cell;
                    157:                                                break;
                    158:                                        }
                    159:                                }
                    160:                        }
1.69      paf       161: 
                    162:                        if(duplicate & !distinct) {
1.145     moko      163:                                error=SQL_Error("duplicate key");
1.69      paf       164:                                return true;
                    165:                        }
                    166: 
1.53      paf       167:                        column_index++;
                    168:                        return false;
                    169:                } catch(...) {
1.142     moko      170:                        error=SQL_Error("exception occurred in Hash_sql_event_handlers::add_row_cell");
1.53      paf       171:                        return true;
                    172:                }
1.11      parser    173:        }
                    174: 
                    175: };
1.67      paf       176: 
1.11      parser    177: #endif
                    178: 
1.57      paf       179: static void _create_or_add(Request& r, MethodParams& params) {
                    180:        if(params.count()) {
1.111     misha     181:                Value& vsrc=params.as_no_junction(0, PARAM_MUST_BE_HASH);
1.130     moko      182:                VHashBase& self=GET_SELF(r, VHashBase);
                    183:                HashStringValue* self_hash=&(self.hash());
1.115     moko      184:                HashStringValue* src_hash;
                    185: 
1.158     moko      186:                if(VHashBase* src=dynamic_cast<VHashBase*>(&vsrc)) {
1.127     moko      187:                        src_hash=&(src->hash());
1.115     moko      188: 
                    189:                        if(src_hash==self_hash) // same: doing nothing
1.66      paf       190:                                return;
1.72      paf       191: 
1.115     moko      192:                        if(Value* vdefault=src->get_default())
1.129     moko      193:                                self.set_default(vdefault);
1.115     moko      194:                } else {
                    195:                        src_hash=vsrc.get_hash();
1.66      paf       196:                }
1.115     moko      197: 
                    198:                if(src_hash)
1.138     moko      199:                        for(HashStringValue::Iterator i(*src_hash); i; i.next())
                    200:                                self_hash->put(i.key(), i.value());
1.20      parser    201:        }
                    202: }
1.22      parser    203: 
1.57      paf       204: static void _sub(Request& r, MethodParams& params) {
1.114     misha     205:        if(HashStringValue* src=params.as_hash(0, "param")) {
1.130     moko      206:                HashStringValue* self=&(GET_SELF(r, VHashBase).hash());
1.66      paf       207:                if(src==self) { // same: clearing
                    208:                        self->clear();
                    209:                        return;
                    210:                }
1.138     moko      211:                for(HashStringValue::Iterator i(*src); i; i.next())
                    212:                        self->remove(i.key());
1.66      paf       213:        }
1.57      paf       214: }
                    215: 
1.130     moko      216: static void copy_all_dontoverwrite_to(HashStringValue::key_type key, HashStringValue::value_type value, HashStringValue* dest) {
1.57      paf       217:        dest->put_dont_replace(key, value);
1.22      parser    218: }
1.57      paf       219: static void _union(Request& r, MethodParams& params) {
1.22      parser    220:        // dest = copy of self
1.130     moko      221:        Value& result=*new VHash(GET_SELF(r, VHashBase).hash());
1.22      parser    222:        // dest += b
1.114     misha     223:        if(HashStringValue* src=params.as_hash(0, "param"))
1.77      paf       224:                src->for_each<HashStringValue*>(copy_all_dontoverwrite_to, result.get_hash());
1.22      parser    225: 
                    226:        // return result
1.137     moko      227:        r.write(result);
1.22      parser    228: }
                    229: 
                    230: #ifndef DOXYGEN
                    231: struct Copy_intersection_to_info {
1.57      paf       232:        HashStringValue* b;
                    233:        HashStringValue* dest;
1.22      parser    234: };
                    235: #endif
1.155     moko      236: 
                    237: static void copy_intersection_by_arg(HashStringValue::key_type key, HashStringValue::value_type, Copy_intersection_to_info *info) {
                    238:        if(HashStringValue::value_type value=info->b->get(key))
                    239:                info->dest->put_dont_replace(key, value);
                    240: }
                    241: 
                    242: static void copy_intersection_by_self(HashStringValue::key_type key, HashStringValue::value_type value, Copy_intersection_to_info *info) {
1.57      paf       243:        if(info->b->get(key))
                    244:                info->dest->put_dont_replace(key, value);
1.22      parser    245: }
1.155     moko      246: 
1.57      paf       247: static void _intersection(Request& r, MethodParams& params) {
                    248:        Value& result=*new VHash;
1.155     moko      249: 
1.156     moko      250:        bool order_by_arg=false;
1.155     moko      251:        if(params.count()>1)
                    252:                if(HashStringValue* options=params.as_hash(1, "options")) {
                    253:                        int valid_options=0;
                    254:                        if(Value* vorder=options->get("order")) {
                    255:                                const String &sorder=r.process(*vorder).as_string();
1.156     moko      256:                                if(sorder == "arg")
                    257:                                        order_by_arg=true;
                    258:                                else if(sorder != "self")
1.155     moko      259:                                        throw Exception(PARSER_RUNTIME, &sorder, "'order' must be 'self' or 'arg'");
                    260:                                valid_options++;
                    261:                        }
                    262:                        if(valid_options!=options->count())
                    263:                                throw Exception(PARSER_RUNTIME, 0, CALLED_WITH_INVALID_OPTION);
                    264:                }
                    265: 
1.114     misha     266:        if(HashStringValue* b=params.as_hash(0, "param")) {
1.155     moko      267:                if(order_by_arg){
                    268:                        Copy_intersection_to_info info={&GET_SELF(r, VHashBase).hash(), result.get_hash()};
                    269:                        b->for_each<Copy_intersection_to_info*>(copy_intersection_by_arg, &info);
                    270:                } else {
                    271:                        Copy_intersection_to_info info={b, result.get_hash()};
                    272:                        GET_SELF(r, VHashBase).hash().for_each<Copy_intersection_to_info*>(copy_intersection_by_self, &info);
                    273:                }
1.22      parser    274:        }
                    275: 
1.137     moko      276:        r.write(result);
1.22      parser    277: }
                    278: 
1.130     moko      279: static bool intersects(        HashStringValue::key_type key, HashStringValue::value_type /*value*/, HashStringValue* b) {
1.57      paf       280:        return b->get(key)!=0;
1.22      parser    281: }
                    282: 
1.57      paf       283: static void _intersects(Request& r, MethodParams& params) {
                    284:        bool result=false;
                    285: 
1.119     misha     286:        if(HashStringValue* b=params.as_hash(0, "param")) {
1.130     moko      287:                HashStringValue* self=&(GET_SELF(r, VHashBase).hash());
1.120     misha     288:                if(b==self) {
1.137     moko      289:                        r.write(VBool::get(true));
1.120     misha     290:                        return;
                    291:                }
1.119     misha     292:                result=self->first_that<HashStringValue*>(intersects, b)!=0;
                    293:        }
1.22      parser    294: 
                    295:        // return result
1.137     moko      296:        r.write(VBool::get(result));
1.22      parser    297: }
                    298: 
                    299: 
1.81      misha     300: extern Table2hash_value_type get_value_type(Value& vvalue_type);
1.71      paf       301: extern int marshal_binds(HashStringValue& hash, SQL_Driver::Placeholder*& placeholders);
                    302: extern void unmarshal_bind_updates(HashStringValue& hash, int placeholder_count, SQL_Driver::Placeholder* placeholders);
                    303: 
1.57      paf       304: static void _sql(Request& r, MethodParams& params) {
                    305:        Value& statement=params.as_junction(0, "statement must be code");
1.2       parser    306: 
1.71      paf       307:        HashStringValue* bind=0;
1.87      misha     308:        ulong limit=SQL_NO_LIMIT;
1.33      paf       309:        ulong offset=0;
1.49      paf       310:        bool distinct=false;
1.81      misha     311:        Table2hash_value_type value_type=C_HASH;
1.110     misha     312:        if(params.count()>1)
1.114     misha     313:                if(HashStringValue* options=params.as_hash(1, "sql options")) {
1.110     misha     314:                        int valid_options=0;
1.161   ! moko      315:                        for(HashStringValue::Iterator i(*options); i; i.next() ){
        !           316:                                String::Body key=i.key();
        !           317:                                Value* value=i.value();
        !           318:                                if(key == sql_bind_name) {
        !           319:                                        bind=value->get_hash();
        !           320:                                        valid_options++;
        !           321:                                } else if(key == sql_limit_name) {
        !           322:                                        limit=(ulong)r.process(*value).as_double();
        !           323:                                        valid_options++;
        !           324:                                } else if(key == sql_offset_name) {
        !           325:                                        offset=(ulong)r.process(*value).as_double();
        !           326:                                        valid_options++;
        !           327:                                } else if (key == sql_distinct_name) {
        !           328:                                        distinct=r.process(*value).as_bool();
        !           329:                                        valid_options++;
        !           330:                                } else if (key == sql_value_type_name) {
        !           331:                                        value_type=get_value_type(r.process(*value));
        !           332:                                        valid_options++;
        !           333:                                }
1.110     misha     334:                        }
                    335:                        if(valid_options!=options->count())
                    336:                                throw Exception(PARSER_RUNTIME, 0, CALLED_WITH_INVALID_OPTION);
                    337:                }
1.2       parser    338: 
1.71      paf       339:        SQL_Driver::Placeholder* placeholders=0;
                    340:        uint placeholders_count=0;
                    341:        if(bind)
                    342:                placeholders_count=marshal_binds(*bind, placeholders);
                    343: 
1.37      paf       344:        const String& statement_string=r.process_to_string(statement);
1.136     moko      345:        const char* statement_cstr=statement_string.untaint_cstr(String::L_SQL, r.connection());
1.97      misha     346: 
1.130     moko      347:        HashStringValue& hash=GET_SELF(r, VHashBase).hash();
1.145     moko      348:        hash.clear();
                    349:        Hash_sql_event_handlers handlers(distinct, hash, value_type);
                    350: 
                    351:        r.connection()->query(statement_cstr, placeholders_count, placeholders, offset, limit, handlers, statement_string);
1.71      paf       352: 
                    353:        if(bind)
                    354:                unmarshal_bind_updates(*bind, placeholders_count, placeholders);
1.2       parser    355: }
                    356: 
1.130     moko      357: static void keys_collector(HashStringValue::key_type key, HashStringValue::value_type, Table *table) {
1.100     misha     358:        Table::element_type row(new ArrayString(1));
1.57      paf       359:        *row+=new String(key, String::L_TAINTED);
                    360:        *table+=row;
1.9       parser    361: }
1.68      paf       362: static void _keys(Request& r, MethodParams& params) {
                    363:        const String* keys_column_name;
                    364:        if(params.count()>0)
1.81      misha     365:                keys_column_name=&params.as_string(0, COLUMN_NAME_MUST_BE_STRING);
1.68      paf       366:        else 
                    367:                keys_column_name=new String("key");
                    368: 
1.101     misha     369:        Table::columns_type columns(new ArrayString(1));
1.68      paf       370:        *columns+=keys_column_name;
1.57      paf       371:        Table* table=new Table(columns);
1.9       parser    372: 
1.130     moko      373:        GET_SELF(r, VHashBase).hash().for_each<Table*>(keys_collector, table);
1.9       parser    374: 
1.137     moko      375:        r.write(*new VTable(table));
1.9       parser    376: }
                    377: 
1.57      paf       378: static void _count(Request& r, MethodParams&) {
1.137     moko      379:        r.write(*new VInt(GET_SELF(r, VHashBase).hash().count()));
1.16      parser    380: }
                    381: 
1.57      paf       382: static void _delete(Request& r, MethodParams& params) {
1.119     misha     383:        if(params.count()>0)
1.130     moko      384:                GET_SELF(r, VHashBase).hash().remove(params.as_string(0, "key must be string"));
1.119     misha     385:        else
1.130     moko      386:                GET_SELF(r, VHashBase).hash().clear();
1.25      paf       387: }
                    388: 
1.82      misha     389: static void _contains(Request& r, MethodParams& params) {
1.130     moko      390:        VHashBase& self=GET_SELF(r, VHashBase);
1.129     moko      391:        const String& key_name=params.as_string(0, "key must be string");
                    392:        bool result=SYMBOLS_EQ(key_name,_DEFAULT_SYMBOL) ? (self.get_default() != 0) : self.hash().contains(key_name);
1.137     moko      393:        r.write(VBool::get(result));
1.80      misha     394: }
                    395: 
1.57      paf       396: static void _foreach(Request& r, MethodParams& params) {
1.102     misha     397:        InCycle temp(r);
1.77      paf       398: 
1.128     moko      399:        const String* key_var_name=&params.as_string(0, "key-var name must be string");
                    400:        const String* value_var_name=&params.as_string(1, "value-var name must be string");
                    401:        Value* body_code=&params.as_junction(2, "body must be code");
1.134     moko      402:        Value* delim_maybe_code=params.count()>3?&params[3]:0;
1.128     moko      403:        Value& caller=*r.get_method_frame()->caller();
1.85      misha     404: 
1.128     moko      405:        if(key_var_name->is_empty()) key_var_name=0;
                    406:        if(value_var_name->is_empty()) value_var_name=0;
1.57      paf       407: 
1.130     moko      408:        HashStringValue& hash=GET_SELF(r, VHashBase).hash();
1.128     moko      409: 
                    410:        if(delim_maybe_code){ // delimiter set
                    411:                bool need_delim=false;;
                    412:                for(HashStringValue::Iterator i(hash); i; i.next()){
                    413:                        if(key_var_name){
                    414:                                VString* vkey=new VString(*new String(i.key(), String::L_TAINTED));
                    415:                                r.put_element(caller, *key_var_name, vkey);
                    416:                        }
                    417: 
                    418:                        if(value_var_name)
                    419:                                r.put_element(caller, *value_var_name, i.value());
                    420: 
1.132     moko      421:                        Value& sv_processed=r.process(*body_code);
1.140     moko      422:                        TempSkip4Delimiter skip(r);
1.128     moko      423: 
                    424:                        const String* s_processed=sv_processed.get_string();
                    425:                        if(s_processed && !s_processed->is_empty()) { // we have body
                    426:                                if(need_delim) // need delim & iteration produced string?
1.137     moko      427:                                        r.write(r.process(*delim_maybe_code));
1.128     moko      428:                                else
                    429:                                        need_delim=true;
                    430:                        }
                    431: 
1.137     moko      432:                        r.write(sv_processed);
1.128     moko      433: 
1.140     moko      434:                        if(skip.check_break())
1.128     moko      435:                                break;
                    436:                }
                    437:        } else {
                    438:                for(HashStringValue::Iterator i(hash); i; i.next()){
                    439:                        if(key_var_name){
                    440:                                VString* vkey=new VString(*new String(i.key(), String::L_TAINTED));
                    441:                                r.put_element(caller, *key_var_name, vkey);
                    442:                        }
                    443: 
                    444:                        if(value_var_name)
                    445:                                r.put_element(caller, *value_var_name, i.value());
                    446: 
                    447:                        r.process_write(*body_code);
                    448: 
1.140     moko      449:                        if(r.check_skip_break())
1.128     moko      450:                                break;
                    451:                }
                    452:        }
1.26      paf       453: }
                    454: 
1.121     misha     455: enum AtResultType {
                    456:        AtResultTypeValue = 0,
                    457:        AtResultTypeKey = 1,
                    458:        AtResultTypeHash = 2
                    459: };
                    460: 
                    461: inline Value& SingleElementHash(String::Body akey, Value* avalue) {
                    462:        Value& result=*new VHash;
                    463:        result.put_element(*new String(akey, String::L_TAINTED), avalue);
                    464:        return result;
                    465: }
                    466: 
1.122     moko      467: #ifndef DOXYGEN
1.143     moko      468: struct Hash_seq_item : public PA_Allocated {
1.122     moko      469:        HashStringValue::Pair *hash_pair;
                    470:        union {
                    471:                const char *c_str;
                    472:                double d;
                    473:        } value;
                    474: };
                    475: #endif
                    476: static int sort_cmp_string(const void *a, const void *b) {
                    477:        return strcmp(
                    478:                static_cast<const Hash_seq_item *>(a)->value.c_str,
                    479:                static_cast<const Hash_seq_item *>(b)->value.c_str
                    480:        );
                    481: }
                    482: static int sort_cmp_double(const void *a, const void *b) {
                    483:        double va=static_cast<const Hash_seq_item *>(a)->value.d;
                    484:        double vb=static_cast<const Hash_seq_item *>(b)->value.d;
                    485:        if(va<vb)
                    486:                return -1;
                    487:        else if(va>vb)
                    488:                return +1;
                    489:        else 
                    490:                return 0;
                    491: }
                    492: static void _sort(Request& r, MethodParams& params){
1.123     moko      493: #ifdef HASH_ORDER
1.122     moko      494:        const String& key_var_name=params.as_string(0, "key-var name must be string");
                    495:        const String& value_var_name=params.as_string(1, "value-var name must be string");
                    496:        Value& key_maker=params.as_junction(2, "key-maker must be code");
1.139     moko      497:        bool reverse=params.count()>3 /*..[desc|asc|]*/ && params.as_no_junction(3, "order must not be code").as_string()=="desc"; // default=asc
1.122     moko      498: 
                    499:        const String* key_var=key_var_name.is_empty()? 0 : &key_var_name;
                    500:        const String* value_var=value_var_name.is_empty()? 0 : &value_var_name;
                    501:        VMethodFrame* context=r.get_method_frame()->caller();
                    502: 
1.130     moko      503:        HashStringValue& hash=GET_SELF(r, VHashBase).hash();
1.122     moko      504:        int count=hash.count();
                    505: 
1.143     moko      506:        Hash_seq_item* seq=new Hash_seq_item[count];
1.122     moko      507:        int pos=0;
                    508:        bool key_values_are_strings=true;
                    509: 
                    510:        for(HashStringValue::Iterator i(hash); i; i.next(), pos++ ){
                    511:                if(key_var)
                    512:                        r.put_element(*context, *key_var, new VString(*new String(i.key(), String::L_TAINTED)));
                    513:                if(value_var)
                    514:                        r.put_element(*context, *value_var, i.value());
                    515:        
1.133     moko      516:                Value& value=r.process(key_maker);
1.122     moko      517:                if(pos==0) // determining key values type by first one
                    518:                        key_values_are_strings=value.is_string();
                    519: 
                    520:                seq[pos].hash_pair=i.pair();
                    521:                if(key_values_are_strings)
                    522:                        seq[pos].value.c_str=value.as_string().cstr();
                    523:                else
                    524:                        seq[pos].value.d=value.as_expr_result().as_double();
                    525:        }
                    526: 
                    527:        // @todo: handle this elsewhere
                    528:        if(r.charsets.source().NAME()=="KOI8-R" && key_values_are_strings)
                    529:                for(pos=0; pos<count; pos++)
                    530:                        if(*seq[pos].value.c_str)
1.131     moko      531:                                seq[pos].value.c_str=Charset::transcode(seq[pos].value.c_str, r.charsets.source(), pa_UTF8_charset).cstr();
1.122     moko      532: 
                    533:        // sort keys
                    534:        qsort(seq, count, sizeof(Hash_seq_item), key_values_are_strings?sort_cmp_string:sort_cmp_double);
                    535: 
                    536:        // reorder hash as required in 'seq'
                    537:        hash.order_clear();
                    538:        if(reverse)
                    539:                for(pos=count-1; pos>=0; pos--)
                    540:                        hash.order_next(seq[pos].hash_pair);
                    541:        else
                    542:                for(pos=0; pos<count; pos++)
                    543:                        hash.order_next(seq[pos].hash_pair);
                    544: 
                    545:        delete[] seq;
1.123     moko      546: #endif
1.122     moko      547: }
                    548: 
1.105     misha     549: static void _at(Request& r, MethodParams& params) {
1.130     moko      550:        HashStringValue& hash=GET_SELF(r, VHashBase).hash();
1.105     misha     551:        size_t count=hash.count();
                    552: 
                    553:        int pos=0;
                    554: 
1.121     misha     555:        // misha@
                    556:        // I do not like that type is checked before whence.
1.133     moko      557:        // But I do not like the idea to move it after whence (where process can be called) even more.
1.121     misha     558:        AtResultType result_type=AtResultTypeValue;
                    559:        if(params.count() > 1) {
                    560:                const String& stype=params.as_string(1, "type must be string");
                    561:                if(stype == "key")
                    562:                        result_type=AtResultTypeKey;
                    563:                else if(stype == "hash")
                    564:                        result_type=AtResultTypeHash;
                    565:                else if(stype != "value")
                    566:                        throw Exception(PARSER_RUNTIME, &stype, "type must be 'key', 'value' or 'hash'");
                    567:        }
                    568: 
1.134     moko      569:        Value& vwhence=params[0];
1.121     misha     570:        if(vwhence.is_string()) {
1.105     misha     571:                const String& swhence=*vwhence.get_string();
                    572:                if(swhence == "last")
                    573:                        pos=count-1;
                    574:                else if(swhence != "first")
                    575:                        throw Exception(PARSER_RUNTIME,
                    576:                                &swhence,
                    577:                                "whence must be 'first', 'last' or expression");
                    578:        } else {
1.133     moko      579:                pos=r.process(vwhence).as_int();
1.105     misha     580:                if(pos < 0)
                    581:                        pos+=count;
                    582:        }
                    583: 
1.106     misha     584:        if(count && pos >= 0 && (size_t)pos < count){
1.121     misha     585:                switch(result_type) {
                    586:                        case AtResultTypeKey:
                    587:                                {
1.123     moko      588: #ifdef HASH_ORDER
1.121     misha     589:                                        if(pos == 0) {
1.137     moko      590:                                                r.write(*new VString(*new String(hash.first_key(), String::L_TAINTED)));
1.121     misha     591:                                        } else if((size_t)pos == count-1) {
1.137     moko      592:                                                r.write(*new VString(*new String(hash.last_key(), String::L_TAINTED)));
1.123     moko      593:                                        } else
                    594: #endif
                    595:                                        {
1.121     misha     596:                                                for(HashStringValue::Iterator i(hash); i; i.next(), pos-- )
                    597:                                                        if(!pos){
1.137     moko      598:                                                                r.write(*new VString(*new String(i.key(), String::L_TAINTED)));
1.121     misha     599:                                                                break;
                    600:                                                        }
                    601:                                        }
1.105     misha     602:                                        break;
                    603:                                }
1.121     misha     604:                        case AtResultTypeValue:
                    605:                                {
1.123     moko      606: #ifdef HASH_ORDER
1.121     misha     607:                                        if(pos == 0) {
1.137     moko      608:                                                r.write(*hash.first_value());
1.121     misha     609:                                        } else if((size_t)pos == count-1) {
1.137     moko      610:                                                r.write(*hash.last_value());
1.123     moko      611:                                        } else
                    612: #endif
                    613:                                        {
1.121     misha     614:                                                for(HashStringValue::Iterator i(hash); i; i.next(), pos-- )
                    615:                                                        if(!pos){
1.137     moko      616:                                                                r.write(*i.value());
1.121     misha     617:                                                                break;
                    618:                                                        }
                    619:                                        }
                    620:                                        break;
                    621:                                }
                    622:                        case AtResultTypeHash:
                    623:                                {
1.123     moko      624: #ifdef HASH_ORDER
1.121     misha     625:                                        if(pos == 0) {
1.137     moko      626:                                                r.write(SingleElementHash(hash.first_key(), hash.first_value()));
1.121     misha     627:                                        } else if((size_t)pos == count-1) {
1.137     moko      628:                                                r.write(SingleElementHash(hash.last_key(), hash.last_value()));
1.123     moko      629:                                        } else
                    630: #endif
                    631:                                        {
1.121     misha     632:                                                for(HashStringValue::Iterator i(hash); i; i.next(), pos-- )
                    633:                                                        if(!pos){
1.137     moko      634:                                                                r.write(SingleElementHash(i.key(), i.value()));
1.121     misha     635:                                                                break;
                    636:                                                        }
                    637:                                        }
                    638:                                        break;
                    639:                                }
                    640:                }
1.105     misha     641:        }
                    642: }
                    643: 
1.147     moko      644: extern String table_reverse_name;
                    645: 
                    646: static void _select(Request& r, MethodParams& params) {
1.154     moko      647:        InCycle temp(r);
1.147     moko      648:        const String* key_var_name=&params.as_string(0, "key-var name must be string");
                    649:        const String* value_var_name=&params.as_string(1, "value-var name must be string");
                    650:        Value& vcondition=params.as_expression(2, "condition must be number, bool or expression");
                    651: 
                    652:        if(key_var_name->is_empty()) key_var_name=0;
                    653:        if(value_var_name->is_empty()) value_var_name=0;
                    654: 
                    655:        HashStringValue& source_hash=GET_SELF(r, VHashBase).hash();
                    656:        Value& caller=*r.get_method_frame()->caller();
                    657: 
                    658:        int limit=source_hash.count();
                    659:        bool reverse=false;
1.149     moko      660:        bool copy_default=false;
1.147     moko      661: 
                    662:        if(params.count()>3)
                    663:                if(HashStringValue* options=params.as_hash(3)) {
                    664:                        int valid_options=0;
                    665:                        if(Value* vlimit=options->get(sql_limit_name)) {
                    666:                                valid_options++;
                    667:                                limit=r.process(*vlimit).as_int();
                    668:                        }
                    669:                        if(Value* vreverse=options->get(table_reverse_name)) {
                    670:                                valid_options++;
                    671:                                reverse=r.process(*vreverse).as_bool();
                    672:                        }
1.149     moko      673:                        if(Value* vcopy_default=options->get(sql_default_name)) {
                    674:                                valid_options++;
                    675:                                copy_default=r.process(*vcopy_default).as_bool();
                    676:                        }
1.147     moko      677:                        if(valid_options!=options->count())
                    678:                                throw Exception(PARSER_RUNTIME, 0, CALLED_WITH_INVALID_OPTION);
                    679:                }
                    680: 
                    681:        HashStringValue& result_hash=*new HashStringValue();
                    682: 
                    683:        if(limit>0){
1.154     moko      684: 
1.147     moko      685: #ifdef HASH_ORDER
                    686:                if(reverse){
                    687:                        for(HashStringValue::ReverseIterator i(source_hash); i; i.prev()){
                    688:                                if(key_var_name)
                    689:                                        r.put_element(caller, *key_var_name, new VString(*new String(i.key(), String::L_TAINTED)));
                    690:                                if(value_var_name)
                    691:                                        r.put_element(caller, *value_var_name, i.value());
                    692: 
1.154     moko      693:                                bool condition=r.process(vcondition).as_bool();
                    694: 
                    695:                                if(r.check_skip_break())
                    696:                                        break;
                    697: 
                    698:                                if(condition){
1.147     moko      699:                                        result_hash.put(i.key(), i.value());
                    700:                                        if(!--limit)
                    701:                                                break;
                    702:                                }
                    703:                        }
                    704:                } else {
                    705: #else
                    706:                {
                    707: #endif
                    708:                        for(HashStringValue::Iterator i(source_hash); i; i.next() ){
                    709:                                if(key_var_name)
                    710:                                        r.put_element(caller, *key_var_name, new VString(*new String(i.key(), String::L_TAINTED)));
                    711:                                if(value_var_name)
                    712:                                        r.put_element(caller, *value_var_name, i.value());
                    713: 
1.154     moko      714:                                bool condition=r.process(vcondition).as_bool();
                    715: 
                    716:                                if(r.check_skip_break())
                    717:                                        break;
                    718: 
                    719:                                if(condition){
1.147     moko      720:                                        result_hash.put(i.key(), i.value());
                    721:                                        if(!--limit)
                    722:                                                break;
                    723:                                }
                    724:                        }
                    725:                }
                    726:        }
                    727: 
1.149     moko      728:        VHash *result=new VHash(result_hash);
                    729:        if(copy_default){
                    730:                result->set_default(GET_SELF(r, VHashBase).get_default());
                    731:        }
                    732: 
                    733:        r.write(*result);
1.147     moko      734: }
                    735: 
                    736: static void _reverse(Request& r, MethodParams& params) {
1.148     moko      737:        VHashBase& self=GET_SELF(r, VHashBase);
                    738:        HashStringValue& source_hash=self.hash();
1.147     moko      739:        HashStringValue& result_hash=*new HashStringValue();
                    740: 
                    741: #ifdef HASH_ORDER
                    742:        for(HashStringValue::ReverseIterator i(source_hash); i; i.prev())
                    743:                result_hash.put(i.key(), i.value());
                    744: #else
                    745:        for(HashStringValue::Iterator i(source_hash); i; i.next() )
                    746:                result_hash.put(i.key(), i.value());
                    747: #endif
1.148     moko      748: 
                    749:        VHashBase& result=*new VHash(result_hash);
                    750:        if(Value* vdefault=self.get_default())
                    751:                result.set_default(vdefault);
                    752: 
                    753:        r.write(result);
1.147     moko      754: }
                    755: 
1.150     moko      756: 
                    757: static void _rename(Request& r, MethodParams& params) {
1.151     moko      758:        HashStringValue& hash=GET_SELF(r, VHashBase).hash();
                    759: 
                    760:        if(params.count()>1){
                    761:                const String& key_from=params.as_string(0, "from key must be string");
                    762:                const String& key_to=params.as_string(1, "to key must be string");
                    763: 
                    764:                hash.rename(key_from, key_to);
1.152     moko      765:        } else {
1.153     moko      766:                HashStringValue* names=params.as_hash(0,"single parameter");
1.150     moko      767: 
1.151     moko      768:                for(HashStringValue::Iterator i(*names); i; i.next())
                    769:                        hash.rename(i.key(), i.value()->as_string());
                    770:        }
1.150     moko      771: }
                    772: 
                    773: 
1.1       paf       774: // constructor
                    775: 
1.57      paf       776: MHash::MHash(): Methoded("hash") 
1.39      paf       777: {
1.21      parser    778:        // ^hash::create[[copy_from]]
1.57      paf       779:        add_native_method("create", Method::CT_DYNAMIC, _create_or_add, 0, 1);
1.22      parser    780:        // ^hash.add[add_from]
1.57      paf       781:        add_native_method("add", Method::CT_DYNAMIC, _create_or_add, 1, 1);
1.22      parser    782:        // ^hash.sub[sub_from]
                    783:        add_native_method("sub", Method::CT_DYNAMIC, _sub, 1, 1);
                    784:        // ^a.union[b] = hash
                    785:        add_native_method("union", Method::CT_DYNAMIC, _union, 1, 1);
1.155     moko      786:        // ^a.intersection[b][options hash] = hash
                    787:        add_native_method("intersection", Method::CT_DYNAMIC, _intersection, 1, 2);
1.22      parser    788:        // ^a.intersects[b] = bool
                    789:        add_native_method("intersects", Method::CT_DYNAMIC, _intersects, 1, 1);
1.25      paf       790: 
                    791:        // ^a.delete[key]
1.119     misha     792:        add_native_method("delete", Method::CT_DYNAMIC, _delete, 0, 1);
1.2       parser    793: 
1.82      misha     794:        // ^a.contains[key]
                    795:        add_native_method("contains", Method::CT_DYNAMIC, _contains, 1, 1);
                    796:        // backward
                    797:        add_native_method("contain", Method::CT_DYNAMIC, _contains, 1, 1);
1.80      misha     798: 
                    799:        // ^hash::sql[query][options hash]
1.33      paf       800:        add_native_method("sql", Method::CT_DYNAMIC, _sql, 1, 2);
1.2       parser    801: 
1.68      paf       802:        // ^hash._keys[[column name]]
1.124     moko      803:        add_native_method("_keys", Method::CT_DYNAMIC, _keys, 0, 1);
1.16      parser    804: 
                    805:        // ^hash._count[]
1.124     moko      806:        add_native_method("_count", Method::CT_DYNAMIC, _count, 0, 0);
1.26      paf       807: 
                    808:        // ^hash.foreach[key;value]{code}[delim]
                    809:        add_native_method("foreach", Method::CT_DYNAMIC, _foreach, 2+1, 2+1+1);
1.105     misha     810: 
1.122     moko      811:        // ^hash.sort[key;value]{string-key-maker}[[asc|desc]]
                    812:        // ^hash.sort[key;value](numeric-key-maker)[[asc|desc]]
1.147     moko      813:        add_native_method("sort", Method::CT_DYNAMIC, _sort, 3, 4);
                    814: 
                    815:        // ^hash.select[key;value](bool-condition)[options hash]
                    816:        add_native_method("select", Method::CT_DYNAMIC, _select, 3, 4);
                    817: 
                    818:        // ^hash.reverse[]
                    819:        add_native_method("reverse", Method::CT_DYNAMIC, _reverse, 0, 0);
1.122     moko      820: 
1.121     misha     821:        // ^hash._at[first|last[;'key'|'value'|'hash']]
                    822:        // ^hash._at([-+]offset)[['key'|'value'|'hash']]
                    823:        add_native_method("_at", Method::CT_DYNAMIC, _at, 1, 2);
1.124     moko      824: 
1.150     moko      825:        // ^hash.rename[from;to]
1.151     moko      826:        // ^hash.rename[ $.from[to] ... ]
                    827:        add_native_method("rename", Method::CT_DYNAMIC, _rename, 1, 2);
1.150     moko      828: 
1.124     moko      829: #ifdef FEATURE_GET_ELEMENT4CALL
                    830:        // aliases without "_"
                    831:        add_native_method("keys", Method::CT_DYNAMIC, _keys, 0, 1);
                    832:        add_native_method("count", Method::CT_DYNAMIC, _count, 0, 0);
                    833:        add_native_method("at", Method::CT_DYNAMIC, _at, 1, 2);
                    834: #endif
                    835: 
1.1       paf       836: }

E-mail: