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

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

E-mail: