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

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

E-mail: