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

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

E-mail: