Annotation of parser3/src/classes/array.C, revision 1.14

1.1       moko        1: /** @file
                      2:        Parser: @b array parser class.
                      3: 
                      4:        Copyright (c) 2001-2023 Art. Lebedev Studio (http://www.artlebedev.com)
                      5:        Authors: Konstantin Morshnev <moko@design.ru>, Alexandr Petrosian <paf@design.ru>
                      6: */
                      7: 
                      8: #include "classes.h"
                      9: #include "pa_vmethod_frame.h"
                     10: 
                     11: #include "pa_request.h"
                     12: #include "pa_charsets.h"
                     13: #include "pa_varray.h"
                     14: #include "pa_vvoid.h"
                     15: #include "pa_sql_connection.h"
                     16: #include "pa_vtable.h"
                     17: #include "pa_vbool.h"
                     18: #include "pa_vmethod_frame.h"
                     19: 
1.14    ! moko       20: volatile const char * IDENT_ARRAY_C="$Id: array.C,v 1.13 2024/09/30 19:03:53 moko Exp $";
1.1       moko       21: 
                     22: // class
                     23: 
                     24: class MArray: public Methoded {
                     25: public: // VStateless_class
                     26:        Value* create_new_value(Pool&) { return new VArray; }
                     27: 
                     28: public:
                     29:        MArray();
                     30: };
                     31: 
                     32: // global variable
                     33: 
                     34: DECLARE_CLASS_VAR(array, new MArray);
                     35: 
1.5       moko       36: const char* const PARAM_ARRAY_OR_HASH = "param must be array or hash";
1.7       moko       37: const char* const PARAM_INDEX = "index must be integer";
1.5       moko       38: 
1.1       moko       39: // methods
                     40: 
                     41: static void _create_or_add(Request& r, MethodParams& params) {
                     42:        if(params.count()) {
1.5       moko       43:                Value& vsrc=params.as_no_junction(0, PARAM_ARRAY_OR_HASH);
1.1       moko       44:                VArray& self=GET_SELF(r, VArray);
                     45:                ArrayValue& self_array=self.array();
                     46: 
1.3       moko       47:                if(VArray* src=dynamic_cast<VArray*>(&vsrc)) {
1.6       moko       48:                        if(src==&self)
1.14    ! moko       49:                                return;
        !            50:                        if(self_array.count()){
        !            51:                                for(ArrayValue::Iterator i(src->array()); i; i.next()){
        !            52:                                        if(i.value())
        !            53:                                                self_array.put(i.index(), i.value());
        !            54:                                }
        !            55:                        } else {
        !            56:                                self_array.append(src->array());
        !            57:                        }
1.1       moko       58:                } else {
                     59:                        HashStringValue* src_hash=vsrc.get_hash();
1.5       moko       60:                        if(!src_hash)
                     61:                                return;
                     62:                        for(HashStringValue::Iterator i(*src_hash); i; i.next()){
1.7       moko       63:                                self_array.put(VArray::index(i.key()), i.value());
1.5       moko       64:                        }
1.1       moko       65:                }
1.4       moko       66:                self.invalidate();
1.1       moko       67:        }
                     68: }
                     69: 
1.6       moko       70: static ArrayValue::Action_options get_action_options(Request& r, MethodParams& params, size_t options_index) {
                     71:        ArrayValue::Action_options result;
                     72:        if(params.count() <= options_index)
                     73:                return result;
                     74: 
                     75:        HashStringValue* options=params.as_hash(options_index);
                     76:        if(!options)
                     77:                return result;
                     78: 
                     79:        result.defined=true;
                     80:        int valid_options=0;
                     81: 
                     82:        if(Value* voffset=options->get(sql_offset_name)) {
                     83:                valid_options++;
1.8       moko       84:                int offset=r.process(*voffset).as_int();
                     85:                result.offset=offset < 0 ? 0 : offset;
1.6       moko       86:        }
                     87:        if(Value* vlimit=options->get(sql_limit_name)) {
                     88:                valid_options++;
1.8       moko       89:                int limit=r.process(*vlimit).as_int();
                     90:                result.limit=limit < 0 ? 0: limit;
1.6       moko       91:        }
                     92: 
                     93:        if(valid_options!=options->count())
                     94:                throw Exception(PARSER_RUNTIME, 0, CALLED_WITH_INVALID_OPTION);
                     95: 
                     96:        return result;
                     97: }
                     98: 
                     99: static void _join(Request& r, MethodParams& params) {
1.7       moko      100:        Value& vsrc=params.as_no_junction(0, PARAM_ARRAY_OR_HASH);
1.6       moko      101:        ArrayValue::Action_options o=get_action_options(r, params, 1);
                    102: 
                    103:        VArray& self=GET_SELF(r, VArray);
                    104:        ArrayValue& self_array=self.array();
                    105: 
                    106:        if(VArray* src=dynamic_cast<VArray*>(&vsrc)) {
                    107:                if(src==&self)
                    108:                        throw Exception(PARSER_RUNTIME, 0, "source and destination are the same array");
                    109: 
                    110:                if(o.defined){
                    111:                        for(ArrayValue::Iterator i(src->array()); i; i.next()){
                    112:                                if(i.value()){
                    113:                                        if(o.offset > 0){
                    114:                                                o.offset--;
                    115:                                                continue;
                    116:                                        }
                    117:                                        if(o.limit-- == 0)
                    118:                                                break;
                    119:                                        self_array+=i.value();
                    120:                                }
                    121:                        }
                    122:                } else {
                    123:                        for(ArrayValue::Iterator i(src->array()); i; i.next()){
                    124:                                if(i.value())
                    125:                                        self_array+=i.value();
                    126:                        }
                    127:                }
1.7       moko      128:        } else {
                    129:                HashStringValue* src_hash=vsrc.get_hash();
                    130:                if(!src_hash)
                    131:                        return;
                    132:                if(o.defined){
                    133:                        for(HashStringValue::Iterator i(*src_hash); i; i.next()){
                    134:                                if(o.offset > 0){
                    135:                                        o.offset--;
                    136:                                        continue;
                    137:                                }
                    138:                                if(o.limit-- == 0)
                    139:                                        break;
                    140:                                self_array+=i.value();
                    141:                        }
                    142:                } else {
                    143:                        for(HashStringValue::Iterator i(*src_hash); i; i.next()){
                    144:                                self_array+=i.value();
                    145:                        }
                    146:                }
                    147:        }
                    148:        self.invalidate();
1.6       moko      149: }
                    150: 
1.11      moko      151: #ifndef DOXYGEN
                    152: 
                    153: #define STRING(str) ((str) ? *new String(str, String::L_TAINTED /* no length as 0x00 can be inside */) : String::Empty)
                    154: 
                    155: class SparseArray_sql_event_handlers: public SQL_Driver_query_event_handlers {
                    156:        bool distinct;
                    157:        ArrayValue& result;
                    158:        Value* row_value;
                    159:        int column_index;
1.12      moko      160:        ArrayString* columns;
1.11      moko      161:        bool one_bool_column;
                    162:        Table2hash_value_type value_type;
                    163:        int columns_count;
                    164: public:
                    165:        Table* empty;
                    166: public:
                    167:        SparseArray_sql_event_handlers(bool adistinct, ArrayValue& aresult, Table2hash_value_type avalue_type):
                    168:                distinct(adistinct),
                    169:                result(aresult),
                    170:                row_value(0),
                    171:                column_index(0),
1.12      moko      172:                columns(new ArrayString),
1.11      moko      173:                one_bool_column(false),
                    174:                value_type(avalue_type),
                    175:                empty(0) {
                    176:        }
                    177: 
                    178:        bool add_column(SQL_Error& error, const char* str, size_t ) {
                    179:                try {
1.12      moko      180:                        if(columns_count){
                    181:                                // another query in multi_statements mode
                    182:                                columns=new ArrayString;
                    183:                                columns_count=0;
                    184:                        }
                    185:                        *columns+=&STRING(str);
1.11      moko      186:                        return false;
                    187:                } catch(...) {
                    188:                        error=SQL_Error("exception occurred in Hash_sql_event_handlers::add_column");
                    189:                        return true;
                    190:                }
                    191:        }
                    192: 
                    193:        bool before_rows(SQL_Error& error) {
1.12      moko      194:                columns_count=columns->count();
                    195:                if(columns_count<1) {
1.11      moko      196:                        error=SQL_Error("no columns");
                    197:                        return true;
                    198:                }
1.12      moko      199:                if(columns_count==1) {
1.11      moko      200:                        one_bool_column=true;
                    201:                } else {
                    202:                        switch(value_type){
                    203:                                case C_STRING: {
1.12      moko      204:                                        if(columns_count>2){
                    205:                                                error=SQL_Error("only 2 columns allowed for $.type[string] and $.sparse(true)");
1.11      moko      206:                                                return true;
                    207:                                        }
                    208:                                        break;
                    209:                                }
                    210:                                case C_TABLE: {
                    211:                                        // create empty table which we'll copy later
1.12      moko      212:                                        empty=new Table(columns);
1.11      moko      213:                                        break;
                    214:                                }
                    215:                        }
                    216:                }
                    217:                return false;
                    218:        }
                    219: 
                    220:        bool add_row(SQL_Error& /*error*/) {
                    221:                column_index=0;
                    222:                return false;
                    223:        }
                    224: 
                    225:        bool add_row_cell(SQL_Error& error, const char *str, size_t ) {
                    226:                try {
1.12      moko      227:                        if(column_index==columns_count){
                    228:                                // should never happen, buggy driver case
                    229:                                error=SQL_Error("columns index exceed the columns count");
                    230:                                return true;
                    231:                        }
                    232: 
1.11      moko      233:                        bool duplicate=false;
                    234:                        if(one_bool_column) {
                    235:                                size_t index=str ? pa_atoui(str) : 0;
                    236:                                duplicate=result.put_dont_replace(index, &VBool::get(true));  // put. existed?
                    237:                        } else if(column_index==0) {
                    238:                                size_t index=str ? pa_atoui(str) : 0;
                    239:                                switch(value_type){
                    240:                                        case C_HASH: {
                    241:                                                VHash* row_vhash=new VHash;
                    242:                                                row_value=row_vhash;
                    243:                                                duplicate=result.put_dont_replace(index, row_vhash); // put. existed?
                    244:                                                break;
                    245:                                        }
                    246:                                        case C_STRING: {
                    247:                                                VString* row_vstring=new VString();
                    248:                                                row_value=row_vstring;
                    249:                                                duplicate=result.put_dont_replace(index, row_vstring);  // put. existed?
                    250:                                                break;
                    251:                                        }
                    252:                                        case C_TABLE: {
                    253:                                                VTable* vtable=(VTable*)result.get(index);
                    254: 
                    255:                                                if(vtable) { // table with this key exist?
                    256:                                                        if(!distinct) {
                    257:                                                                duplicate=true;
                    258:                                                                break;
                    259:                                                        }
                    260:                                                } else {
                    261:                                                        // no? creating table of same structure as source
                    262:                                                        Table::Action_options table_options(0, 0);
                    263:                                                        vtable=new VTable(new Table(*empty, table_options/*no rows, just structure*/));
                    264:                                                        result.put(index, vtable); // put
                    265:                                                }
                    266:                                                ArrayString* row=new ArrayString(columns_count);
                    267:                                                *row+=&STRING(str);
                    268:                                                *vtable->get_table()+=row;
1.12      moko      269:                                                row_value=(Value*)row;
1.11      moko      270:                                                break;
                    271:                                        }
                    272:                                }
                    273:                        } else {
                    274:                                const String& cell=STRING(str);
                    275:                                switch(value_type) {
                    276:                                        case C_HASH: {
1.12      moko      277:                                                row_value->get_hash()->put(*columns->get(column_index), new VString(cell));
1.11      moko      278:                                                break;
                    279:                                        }
                    280:                                        case C_STRING: {
                    281:                                                VString* row_string=(VString*)row_value;
                    282:                                                row_string->set_string(cell);
                    283:                                                break;
                    284:                                        }
                    285:                                        case C_TABLE: {
                    286:                                                ArrayString* row=(ArrayString*)row_value;
                    287:                                                *row+=&cell;
                    288:                                                break;
                    289:                                        }
                    290:                                }
                    291:                        }
                    292: 
                    293:                        if(duplicate & !distinct) {
                    294:                                error=SQL_Error("duplicate key");
                    295:                                return true;
                    296:                        }
                    297: 
                    298:                        column_index++;
                    299:                        return false;
                    300:                } catch(const Exception& e) {
                    301:                        error=SQL_Error(e.type(), e.comment());
                    302:                        return true;
                    303:                } catch(...) {
                    304:                        error=SQL_Error("exception occurred in Hash_sql_event_handlers::add_row_cell");
                    305:                        return true;
                    306:                }
                    307:        }
                    308: };
                    309: 
                    310: class Array_sql_event_handlers: public SQL_Driver_query_event_handlers {
                    311:        ArrayValue& result;
                    312:        Value* row_value;
                    313:        int column_index;
1.12      moko      314:        ArrayString* columns;
1.11      moko      315:        Table2hash_value_type value_type;
                    316:        int columns_count;
                    317: public:
                    318:        Table* empty;
                    319: public:
                    320:        Array_sql_event_handlers(ArrayValue& aresult, Table2hash_value_type avalue_type):
                    321:                result(aresult),
                    322:                row_value(0),
                    323:                column_index(0),
1.12      moko      324:                columns(new ArrayString),
1.11      moko      325:                value_type(avalue_type),
                    326:                empty(0) {
                    327:        }
                    328: 
                    329:        bool add_column(SQL_Error& error, const char* str, size_t ) {
                    330:                try {
1.12      moko      331:                        if(columns_count){
                    332:                                // another query in multi_statements mode
                    333:                                columns=new ArrayString;
                    334:                                columns_count=0;
                    335:                        }
                    336:                        *columns+=&STRING(str);
1.11      moko      337:                        return false;
                    338:                } catch(...) {
                    339:                        error=SQL_Error("exception occurred in Hash_sql_event_handlers::add_column");
                    340:                        return true;
                    341:                }
                    342:        }
                    343: 
                    344:        bool before_rows(SQL_Error& error) {
1.12      moko      345:                columns_count=columns->count();
                    346:                if(columns_count<1) {
1.11      moko      347:                        error=SQL_Error("no columns");
                    348:                        return true;
                    349:                }
                    350:                switch(value_type){
                    351:                        case C_STRING: {
1.12      moko      352:                                if(columns_count>1){
                    353:                                        error=SQL_Error("only one column allowed for $.type[string]");
1.11      moko      354:                                        return true;
                    355:                                }
                    356:                                break;
                    357:                        }
                    358:                        case C_TABLE: {
                    359:                                // create empty table which we'll copy later
1.12      moko      360:                                empty=new Table(columns);
1.11      moko      361:                                break;
                    362:                        }
                    363:                }
                    364:                return false;
                    365:        }
                    366: 
                    367:        bool add_row(SQL_Error& /*error*/) {
                    368:                column_index=0;
                    369:                return false;
                    370:        }
                    371: 
                    372:        bool add_row_cell(SQL_Error& error, const char *str, size_t ) {
                    373:                try {
1.12      moko      374:                        if(column_index==columns_count){
                    375:                                // should never happen, buggy driver case
                    376:                                error=SQL_Error("columns index exceed the columns count");
                    377:                                return true;
                    378:                        }
                    379: 
1.11      moko      380:                        if(column_index==0) {
                    381:                                switch(value_type){
                    382:                                        case C_HASH: {
                    383:                                                VHash* row_vhash=new VHash;
                    384:                                                row_value=row_vhash;
                    385:                                                result+=row_vhash;
                    386:                                                break;
                    387:                                        }
                    388:                                        case C_STRING: {
                    389:                                                VString* row_vstring=new VString();
                    390:                                                row_value=row_vstring;
                    391:                                                result+=row_vstring;
                    392:                                                break;
                    393:                                        }
                    394:                                        case C_TABLE: {
                    395:                                                // creating table of same structure as source
                    396:                                                Table::Action_options table_options(0, 0);
                    397:                                                VTable* vtable=new VTable(new Table(*empty, table_options/*no rows, just structure*/));
                    398:                                                ArrayString* row=new ArrayString(columns_count);
                    399:                                                *vtable->get_table()+=row;
1.12      moko      400:                                                row_value=(Value*)row;
                    401:                                                result+=vtable;
1.11      moko      402:                                                break;
                    403:                                        }
                    404:                                }
                    405:                        }
                    406: 
                    407:                        const String& cell=STRING(str);
                    408:                        switch(value_type) {
                    409:                                case C_HASH: {
1.12      moko      410:                                        row_value->get_hash()->put(*columns->get(column_index), new VString(cell));
1.11      moko      411:                                        break;
                    412:                                }
                    413:                                case C_STRING: {
                    414:                                        VString* row_string=(VString*)row_value;
                    415:                                        row_string->set_string(cell);
                    416:                                        break;
                    417:                                }
                    418:                                case C_TABLE: {
                    419:                                        ArrayString* row=(ArrayString*)row_value;
                    420:                                        *row+=&cell;
                    421:                                        break;
                    422:                                }
                    423:                        }
                    424: 
                    425:                        column_index++;
                    426:                        return false;
                    427:                } catch(const Exception& e) {
                    428:                        error=SQL_Error(e.type(), e.comment());
                    429:                        return true;
                    430:                } catch(...) {
                    431:                        error=SQL_Error("exception occurred in Hash_sql_event_handlers::add_row_cell");
                    432:                        return true;
                    433:                }
                    434:        }
                    435: };
                    436: 
                    437: #endif
                    438: 
                    439: extern Table2hash_value_type get_value_type(Value& vvalue_type);
                    440: extern int marshal_binds(HashStringValue& hash, SQL_Driver::Placeholder*& placeholders);
                    441: extern void unmarshal_bind_updates(HashStringValue& hash, int placeholder_count, SQL_Driver::Placeholder* placeholders);
                    442: 
                    443: static void _sql(Request& r, MethodParams& params) {
                    444:        Value& statement=params.as_junction(0, "statement must be code");
                    445: 
                    446:        HashStringValue* bind=0;
                    447:        ulong limit=SQL_NO_LIMIT;
                    448:        ulong offset=0;
                    449:        bool distinct=false;
                    450:        bool sparse=false;
                    451:        Table2hash_value_type value_type=C_HASH;
                    452:        if(params.count()>1)
                    453:                if(HashStringValue* options=params.as_hash(1, "sql options")) {
                    454:                        int valid_options=0;
1.13      moko      455:                        bool distinct_specified=false;
1.11      moko      456:                        for(HashStringValue::Iterator i(*options); i; i.next() ){
                    457:                                String::Body key=i.key();
                    458:                                Value* value=i.value();
                    459:                                if(key == sql_bind_name) {
                    460:                                        bind=value->get_hash();
                    461:                                        valid_options++;
                    462:                                } else if(key == sql_limit_name) {
                    463:                                        limit=(ulong)r.process(*value).as_double();
                    464:                                        valid_options++;
                    465:                                } else if(key == sql_offset_name) {
                    466:                                        offset=(ulong)r.process(*value).as_double();
                    467:                                        valid_options++;
                    468:                                } else if (key == sql_distinct_name) {
                    469:                                        distinct=r.process(*value).as_bool();
1.13      moko      470:                                        distinct_specified=true;
1.11      moko      471:                                        valid_options++;
                    472:                                } else if (key == sql_value_type_name) {
1.12      moko      473:                                        value_type=get_value_type(r.process(*value));
1.11      moko      474:                                        valid_options++;
                    475:                                } else if (key == "sparse") {
1.12      moko      476:                                        sparse=r.process(*value).as_bool();
1.11      moko      477:                                        valid_options++;
                    478:                                }
                    479:                        }
                    480:                        if(valid_options!=options->count())
                    481:                                throw Exception(PARSER_RUNTIME, 0, CALLED_WITH_INVALID_OPTION);
1.13      moko      482:                        if(distinct_specified && !sparse)
                    483:                                throw Exception(PARSER_RUNTIME, 0, "'distinct' option can only be used when $.sparse(true) is specified");
1.11      moko      484:                }
                    485: 
                    486:        SQL_Driver::Placeholder* placeholders=0;
                    487:        uint placeholders_count=0;
                    488:        if(bind)
                    489:                placeholders_count=marshal_binds(*bind, placeholders);
                    490: 
                    491:        const String& statement_string=r.process_to_string(statement);
                    492:        const char* statement_cstr=statement_string.untaint_cstr(String::L_SQL, r.connection());
                    493: 
                    494:        VArray& self=GET_SELF(r, VArray);
1.13      moko      495: 
1.11      moko      496:        self.array().clear(); self.invalidate(); // just in case if called as method
                    497: 
                    498:        if(sparse){
                    499:                SparseArray_sql_event_handlers handlers(distinct, self.array(), value_type);
                    500:                r.connection()->query(statement_cstr, placeholders_count, placeholders, offset, limit, handlers, statement_string);
                    501:        } else {
                    502:                Array_sql_event_handlers handlers(self.array(), value_type);
                    503:                r.connection()->query(statement_cstr, placeholders_count, placeholders, offset, limit, handlers, statement_string);
                    504:        }
                    505: 
                    506:        if(bind)
                    507:                unmarshal_bind_updates(*bind, placeholders_count, placeholders);
                    508: }
                    509: 
1.1       moko      510: 
                    511: 
1.10      moko      512: static void mid(Request& r, size_t offset=0, size_t limit=ARRAY_OPTION_LIMIT_ALL) {
1.9       moko      513:        ArrayValue& array=GET_SELF(r, VArray).array();
1.10      moko      514:        if(limit>0){
1.9       moko      515:                VArray *result=new VArray;
                    516:                ArrayValue& result_array=result->array();
                    517:                for(ArrayValue::Iterator i(array); i; i.next()){
                    518:                        if(i.value()){
1.10      moko      519:                                if(offset > 0){
                    520:                                        offset--;
1.9       moko      521:                                        continue;
                    522:                                }
1.10      moko      523:                                if(limit-- == 0)
1.9       moko      524:                                        break;
                    525:                                result_array+=i.value();
                    526:                        }
                    527:                }
                    528:                r.write(*result);
                    529:        } else {
                    530:                r.write(*new VArray);
                    531:        }
                    532: }
1.1       moko      533: 
1.9       moko      534: static void _left(Request& r, MethodParams& params) {
                    535:        int sn=params.as_int(0, "n must be int", r);
1.10      moko      536:        mid(r, 0, sn < 0 ? 0 : sn);
1.9       moko      537: }
                    538: 
                    539: static void _right(Request& r, MethodParams& params) {
                    540:        int sn=params.as_int(0, "n must be int", r);
                    541: 
                    542:        if(sn>0){
                    543:                size_t used=GET_SELF(r, VArray).array().used();
                    544:                if(sn<used){
1.10      moko      545:                        mid(r, used-sn, sn);
1.9       moko      546:                } else {
1.10      moko      547:                        mid(r);
1.9       moko      548:                }
                    549:        } else {
1.10      moko      550:                mid(r, 0, 0);
1.9       moko      551:        }
                    552: }
                    553: 
                    554: static void _mid(Request& r, MethodParams& params) {
                    555:        const String& string=GET_SELF(r, VString).string();
                    556: 
                    557:        int begin=params.as_int(0, "p must be int", r);
                    558:        if(begin<0)
                    559:                throw Exception(PARSER_RUNTIME, 0,  "p(%d) must be >=0", begin);
                    560: 
                    561:        size_t end;
                    562:        size_t length=0;
1.1       moko      563: 
1.9       moko      564:        if(params.count()>1) {
                    565:                int n=params.as_int(1, "n must be int", r);
                    566:                if(n<0)
                    567:                        throw Exception(PARSER_RUNTIME, 0, "n(%d) must be >=0", n);
1.10      moko      568:                mid(r, begin, n);
1.9       moko      569:        } else {
1.10      moko      570:                mid(r, begin);
1.9       moko      571:        }
                    572: }
1.1       moko      573: 
                    574: static void _keys(Request& r, MethodParams& params) {
                    575:        const String* keys_column_name;
                    576:        if(params.count()>0)
                    577:                keys_column_name=&params.as_string(0, COLUMN_NAME_MUST_BE_STRING);
                    578:        else 
                    579:                keys_column_name=new String("key");
                    580: 
                    581:        Table::columns_type columns(new ArrayString(1));
                    582:        *columns+=keys_column_name;
                    583:        Table* table=new Table(columns);
                    584: 
                    585:        ArrayValue& array=GET_SELF(r, VArray).array();
                    586:        for(ArrayValue::Iterator i(array); i; i.next()){
                    587:                if(i.value()){
                    588:                        Table::element_type row(new ArrayString(1));
                    589:                        *row+=new String(i.key(), String::L_TAINTED);
                    590:                        *table+=row;
                    591:                }
                    592:        }
                    593: 
                    594:        r.write(*new VTable(table));
                    595: }
                    596: 
1.5       moko      597: static void _count(Request& r, MethodParams& params) {
                    598:        ArrayValue& array=GET_SELF(r, VArray).array();
                    599:        if(params.count()>0){
                    600:                const String& what=params.as_string(0, PARAMETER_MUST_BE_STRING);
                    601:                if(!what.is_empty()){
                    602:                        if(what != "all")
                    603:                                throw Exception(PARSER_RUNTIME, &what, "param must be empty or 'all'");
                    604:                        return r.write(*new VInt(array.count()));
                    605:                }
                    606:        }
                    607:        r.write(*new VInt(array.used()));
1.1       moko      608: }
                    609: 
1.2       moko      610: static void _append(Request& r, MethodParams& params) {
                    611:        VArray& self=GET_SELF(r, VArray);
                    612:        ArrayValue& array=self.array();
                    613: 
                    614:        int count=params.count();
                    615: 
                    616:        for(int i=0; i<count; i++){
                    617:                array+=&r.process(params[i]);
                    618:        }
1.4       moko      619:        self.invalidate();
1.2       moko      620: }
                    621: 
                    622: static void _insert(Request& r, MethodParams& params) {
                    623:        VArray& self=GET_SELF(r, VArray);
                    624:        ArrayValue& array=self.array();
                    625: 
                    626:        int count=params.count();
1.7       moko      627:        size_t index=VArray::index(params.as_int(0, PARAM_INDEX, r));
1.2       moko      628: 
                    629:        for(int i=1; i<count; i++){
1.8       moko      630:                array.insert(index++, &r.process(params[i]));
1.2       moko      631:        }
1.4       moko      632:        self.invalidate();
1.2       moko      633: }
                    634: 
1.1       moko      635: static void _delete(Request& r, MethodParams& params) {
1.7       moko      636:        VArray& self=GET_SELF(r, VArray);
1.1       moko      637:        if(params.count()>0)
1.7       moko      638:                self.array().clear(VArray::index(params.as_int(0, PARAM_INDEX, r)));
1.1       moko      639:        else
1.7       moko      640:                self.array().clear();
                    641:        self.invalidate();
                    642: }
                    643: 
                    644: static void _remove(Request& r, MethodParams& params) {
                    645:        VArray& self=GET_SELF(r, VArray);
                    646:        self.array().remove(VArray::index(params.as_int(0, PARAM_INDEX, r)));
                    647:        self.invalidate();
1.1       moko      648: }
                    649: 
                    650: static void _contains(Request& r, MethodParams& params) {
                    651:        VArray& self=GET_SELF(r, VArray);
1.7       moko      652:        bool result=self.contains(VArray::index(params.as_int(0, PARAM_INDEX, r)));
1.1       moko      653:        r.write(VBool::get(result));
                    654: }
                    655: 
1.5       moko      656: static void _for(Request& r, MethodParams& params) {
                    657:        InCycle temp(r);
                    658: 
1.7       moko      659:        const String* key_var_name=&params.as_string(0, "key-var name must be string");
                    660:        const String* value_var_name=&params.as_string(1, "value-var name must be string");
                    661:        Value* body_code=&params.as_junction(2, "body must be code");
                    662:        Value* delim_maybe_code=params.count()>3 ? &params[3] : 0;
1.5       moko      663:        Value& caller=*r.get_method_frame()->caller();
                    664: 
1.7       moko      665:        if(key_var_name->is_empty()) key_var_name=0;
1.5       moko      666:        if(value_var_name->is_empty()) value_var_name=0;
                    667: 
                    668:        ArrayValue& array=GET_SELF(r, VArray).array();
                    669: 
                    670:        if(delim_maybe_code){ // delimiter set
                    671:                bool need_delim=false;
                    672:                for(ArrayValue::Iterator i(array); i; i.next()){
1.7       moko      673:                        if(key_var_name){
                    674:                                VString* vkey=new VString(*new String(i.key(), String::L_TAINTED));
                    675:                                r.put_element(caller, *key_var_name, vkey);
                    676:                        }
                    677: 
1.5       moko      678:                        if(value_var_name)
                    679:                                r.put_element(caller, *value_var_name, i.value() ? i.value() : VVoid::get());
                    680: 
                    681:                        Value& sv_processed=r.process(*body_code);
                    682:                        TempSkip4Delimiter skip(r);
                    683: 
                    684:                        const String* s_processed=sv_processed.get_string();
                    685:                        if(s_processed && !s_processed->is_empty()) { // we have body
                    686:                                if(need_delim) // need delim & iteration produced string?
                    687:                                        r.write(r.process(*delim_maybe_code));
                    688:                                else
                    689:                                        need_delim=true;
                    690:                        }
                    691: 
                    692:                        r.write(sv_processed);
                    693: 
                    694:                        if(skip.check_break())
                    695:                                break;
                    696:                }
                    697:        } else {
                    698:                for(ArrayValue::Iterator i(array); i; i.next()){
1.7       moko      699:                        if(key_var_name){
                    700:                                VString* vkey=new VString(*new String(i.key(), String::L_TAINTED));
                    701:                                r.put_element(caller, *key_var_name, vkey);
                    702:                        }
                    703: 
1.5       moko      704:                        if(value_var_name)
                    705:                                r.put_element(caller, *value_var_name, i.value() ? i.value() : VVoid::get());
                    706: 
                    707:                        r.process_write(*body_code);
                    708: 
                    709:                        if(r.check_skip_break())
                    710:                                break;
                    711:                }
                    712:        }
                    713: }
                    714: 
1.1       moko      715: static void _foreach(Request& r, MethodParams& params) {
                    716:        InCycle temp(r);
                    717: 
                    718:        const String* key_var_name=&params.as_string(0, "key-var name must be string");
                    719:        const String* value_var_name=&params.as_string(1, "value-var name must be string");
                    720:        Value* body_code=&params.as_junction(2, "body must be code");
1.7       moko      721:        Value* delim_maybe_code=params.count()>3 ? &params[3] : 0;
1.1       moko      722:        Value& caller=*r.get_method_frame()->caller();
                    723: 
                    724:        if(key_var_name->is_empty()) key_var_name=0;
                    725:        if(value_var_name->is_empty()) value_var_name=0;
                    726: 
                    727:        ArrayValue& array=GET_SELF(r, VArray).array();
                    728: 
                    729:        if(delim_maybe_code){ // delimiter set
                    730:                bool need_delim=false;
                    731:                for(ArrayValue::Iterator i(array); i; i.next()){
                    732:                        if(i.value()){
                    733:                                if(key_var_name){
                    734:                                        VString* vkey=new VString(*new String(i.key(), String::L_TAINTED));
                    735:                                        r.put_element(caller, *key_var_name, vkey);
                    736:                                }
                    737: 
                    738:                                if(value_var_name)
                    739:                                        r.put_element(caller, *value_var_name, i.value());
                    740: 
                    741:                                Value& sv_processed=r.process(*body_code);
                    742:                                TempSkip4Delimiter skip(r);
                    743: 
                    744:                                const String* s_processed=sv_processed.get_string();
                    745:                                if(s_processed && !s_processed->is_empty()) { // we have body
                    746:                                        if(need_delim) // need delim & iteration produced string?
                    747:                                                r.write(r.process(*delim_maybe_code));
                    748:                                        else
                    749:                                                need_delim=true;
                    750:                                }
                    751: 
                    752:                                r.write(sv_processed);
                    753: 
                    754:                                if(skip.check_break())
                    755:                                        break;
                    756:                        }
                    757:                }
                    758:        } else {
                    759:                for(ArrayValue::Iterator i(array); i; i.next()){
                    760:                        if(i.value()){
                    761:                                if(key_var_name){
                    762:                                        VString* vkey=new VString(*new String(i.key(), String::L_TAINTED));
                    763:                                        r.put_element(caller, *key_var_name, vkey);
                    764:                                }
                    765: 
                    766:                                if(value_var_name)
                    767:                                        r.put_element(caller, *value_var_name, i.value());
                    768: 
                    769:                                r.process_write(*body_code);
                    770: 
                    771:                                if(r.check_skip_break())
                    772:                                        break;
                    773:                        }
                    774:                }
                    775:        }
                    776: }
                    777: 
                    778: #ifndef DOXYGEN
                    779: struct Array_seq_item : public PA_Allocated {
                    780:        Value *array_data;
                    781:        union {
                    782:                const char *c_str;
                    783:                double d;
                    784:        } value;
                    785: };
                    786: #endif
                    787: 
                    788: static int sort_cmp_string(const void *a, const void *b) {
                    789:        return strcmp(
                    790:                static_cast<const Array_seq_item *>(a)->value.c_str,
                    791:                static_cast<const Array_seq_item *>(b)->value.c_str
                    792:        );
                    793: }
                    794: static int sort_cmp_double(const void *a, const void *b) {
                    795:        double va=static_cast<const Array_seq_item *>(a)->value.d;
                    796:        double vb=static_cast<const Array_seq_item *>(b)->value.d;
                    797:        if(va<vb)
                    798:                return -1;
                    799:        else if(va>vb)
                    800:                return +1;
                    801:        else 
                    802:                return 0;
                    803: }
                    804: 
                    805: static void _sort(Request& r, MethodParams& params){
                    806:        const String& key_var_name=params.as_string(0, "key-var name must be string");
                    807:        const String& value_var_name=params.as_string(1, "value-var name must be string");
                    808:        Value& key_maker=params.as_junction(2, "key-maker must be code");
                    809:        bool reverse=params.count()>3 && params.as_no_junction(3, "order must not be code").as_string()=="desc"; // default=asc
                    810: 
                    811:        const String* key_var=key_var_name.is_empty()? 0 : &key_var_name;
                    812:        const String* value_var=value_var_name.is_empty()? 0 : &value_var_name;
                    813:        VMethodFrame* context=r.get_method_frame()->caller();
                    814: 
                    815:        VArray& self=GET_SELF(r, VArray);
                    816:        ArrayValue& array=self.array();
1.4       moko      817:        int count=array.used(); // not array.count()
1.1       moko      818: 
                    819:        Array_seq_item* seq=new Array_seq_item[count];
                    820:        int pos=0;
                    821:        bool key_values_are_strings=true;
                    822: 
                    823:        for(ArrayValue::Iterator i(array); i; i.next() ){
                    824:                if(i.value()){
                    825:                        if(key_var)
                    826:                                r.put_element(*context, *key_var, new VString(*new String(i.key(), String::L_TAINTED)));
                    827:                        if(value_var)
                    828:                                r.put_element(*context, *value_var, i.value());
                    829: 
                    830:                        Value& value=r.process(key_maker);
                    831:                        if(pos==0) // determining key values type by first one
                    832:                                key_values_are_strings=value.is_string();
                    833: 
                    834:                        seq[pos].array_data=i.value();
                    835:                        if(key_values_are_strings)
                    836:                                seq[pos++].value.c_str=value.as_string().cstr();
                    837:                        else
                    838:                                seq[pos++].value.d=value.as_expr_result().as_double();
                    839:                }
                    840:        }
                    841: 
                    842:        // @todo: handle this elsewhere
                    843:        if(r.charsets.source().NAME()=="KOI8-R" && key_values_are_strings)
                    844:                for(pos=0; pos<count; pos++)
                    845:                        if(*seq[pos].value.c_str)
                    846:                                seq[pos].value.c_str=Charset::transcode(seq[pos].value.c_str, r.charsets.source(), pa_UTF8_charset).cstr();
                    847: 
                    848:        // sort keys
                    849:        qsort(seq, count, sizeof(Array_seq_item), key_values_are_strings ? sort_cmp_string : sort_cmp_double);
                    850: 
                    851:        // reorder array as required in 'seq'
                    852:        array.clear();
                    853:        if(reverse)
                    854:                for(pos=count-1; pos>=0; pos--)
                    855:                        array+=seq[pos].array_data;
                    856:        else
                    857:                for(pos=0; pos<count; pos++)
                    858:                        array+=seq[pos].array_data;
                    859: 
                    860:        delete[] seq;
                    861: }
                    862: 
1.5       moko      863: enum AtResultType {
                    864:        AtResultTypeValue = 0,
                    865:        AtResultTypeKey = 1,
                    866:        AtResultTypeHash = 2
                    867: };
                    868: 
                    869: inline Value& SingleElementHash(String::Body akey, Value* avalue) {
                    870:        Value& result=*new VHash;
                    871:        result.put_element(*new String(akey, String::L_TAINTED), avalue);
                    872:        return result;
                    873: }
                    874: 
1.1       moko      875: static void _at(Request& r, MethodParams& params) {
                    876:        VArray& self=GET_SELF(r, VArray);
                    877:        ArrayValue& array=self.array();
1.5       moko      878:        size_t count=array.used(); // not array.count()
1.1       moko      879: 
                    880:        int pos=0;
                    881: 
                    882:        AtResultType result_type=AtResultTypeValue;
                    883:        if(params.count() > 1) {
                    884:                const String& stype=params.as_string(1, "type must be string");
                    885:                if(stype == "key")
                    886:                        result_type=AtResultTypeKey;
                    887:                else if(stype == "hash")
                    888:                        result_type=AtResultTypeHash;
                    889:                else if(stype != "value")
                    890:                        throw Exception(PARSER_RUNTIME, &stype, "type must be 'key', 'value' or 'hash'");
                    891:        }
                    892: 
                    893:        Value& vwhence=params[0];
                    894:        if(vwhence.is_string()) {
                    895:                const String& swhence=*vwhence.get_string();
                    896:                if(swhence == "last")
                    897:                        pos=count-1;
                    898:                else if(swhence != "first")
                    899:                        throw Exception(PARSER_RUNTIME, &swhence, "whence must be 'first', 'last' or expression");
                    900:        } else {
                    901:                pos=r.process(vwhence).as_int();
                    902:                if(pos < 0)
                    903:                        pos+=count;
                    904:        }
                    905: 
                    906:        if(count && pos >= 0 && (size_t)pos < count){
                    907:                switch(result_type) {
                    908:                        case AtResultTypeKey:
                    909:                                {
                    910:                                        for(ArrayValue::Iterator i(array); i; i.next() ){
                    911:                                                if(i.value() && !(pos--)){
                    912:                                                        r.write(*new VString(*new String(i.key(), String::L_TAINTED)));
                    913:                                                        break;
                    914:                                                }
                    915:                                        }
                    916:                                        break;
                    917:                                }
                    918:                        case AtResultTypeValue:
                    919:                                {
                    920:                                        for(ArrayValue::Iterator i(array); i; i.next() )
                    921:                                                if(i.value() &&!(pos--)){
                    922:                                                        r.write(*i.value());
                    923:                                                        break;
                    924:                                                }
                    925:                                        break;
                    926:                                }
                    927:                        case AtResultTypeHash:
                    928:                                {
                    929:                                        for(ArrayValue::Iterator i(array); i; i.next() )
                    930:                                                if(i.value() &&!(pos--)){
                    931:                                                        r.write(SingleElementHash(i.key(), i.value()));
                    932:                                                        break;
                    933:                                                }
                    934:                                        break;
                    935:                                }
                    936:                }
                    937:        }
                    938: }
                    939: 
                    940: 
                    941: extern String table_reverse_name;
                    942: 
                    943: static void _select(Request& r, MethodParams& params) {
                    944:        InCycle temp(r);
                    945:        const String* key_var_name=&params.as_string(0, "key-var name must be string");
                    946:        const String* value_var_name=&params.as_string(1, "value-var name must be string");
                    947:        Value& vcondition=params.as_expression(2, "condition must be number, bool or expression");
                    948: 
                    949:        if(key_var_name->is_empty()) key_var_name=0;
                    950:        if(value_var_name->is_empty()) value_var_name=0;
                    951: 
                    952:        ArrayValue& source_array=GET_SELF(r, VArray).array();
                    953:        Value& caller=*r.get_method_frame()->caller();
                    954: 
                    955:        int limit=source_array.count();
                    956:        bool reverse=false;
                    957: 
                    958:        if(params.count()>3)
                    959:                if(HashStringValue* options=params.as_hash(3)) {
                    960:                        int valid_options=0;
                    961:                        if(Value* vlimit=options->get(sql_limit_name)) {
                    962:                                valid_options++;
                    963:                                limit=r.process(*vlimit).as_int();
                    964:                        }
                    965:                        if(Value* vreverse=options->get(table_reverse_name)) {
                    966:                                valid_options++;
                    967:                                reverse=r.process(*vreverse).as_bool();
                    968:                        }
                    969:                        if(valid_options!=options->count())
                    970:                                throw Exception(PARSER_RUNTIME, 0, CALLED_WITH_INVALID_OPTION);
                    971:                }
                    972: 
                    973:        VArray *result=new VArray;
                    974:        ArrayValue& result_array=result->array();
                    975: 
                    976:        if(limit>0){
                    977:                if(reverse){
                    978:                        for(ArrayValue::ReverseIterator i(source_array); i; ){
1.5       moko      979:                                if(Value *value=i.prev()){ // here for correct i.key()
                    980:                                        if(key_var_name)
                    981:                                                r.put_element(caller, *key_var_name, new VString(*new String(i.key(), String::L_TAINTED)));
                    982:                                        if(value_var_name)
                    983:                                                r.put_element(caller, *value_var_name, value);
1.1       moko      984: 
1.5       moko      985:                                        bool condition=r.process(vcondition).as_bool();
1.1       moko      986: 
1.5       moko      987:                                        if(r.check_skip_break())
                    988:                                                break;
1.1       moko      989: 
1.5       moko      990:                                        if(condition){
                    991:                                                result_array+=value;
                    992:                                                if(!--limit)
                    993:                                                        break;
                    994:                                        }
1.1       moko      995:                                }
                    996:                        }
                    997:                } else {
                    998:                        for(ArrayValue::Iterator i(source_array); i; i.next() ){
1.5       moko      999:                                if(Value *value=i.value()){
1.1       moko     1000:                                        if(key_var_name)
                   1001:                                                r.put_element(caller, *key_var_name, new VString(*new String(i.key(), String::L_TAINTED)));
                   1002:                                        if(value_var_name)
                   1003:                                                r.put_element(caller, *value_var_name, value);
                   1004: 
                   1005:                                        bool condition=r.process(vcondition).as_bool();
                   1006: 
                   1007:                                        if(r.check_skip_break())
                   1008:                                                break;
                   1009: 
                   1010:                                        if(condition){
                   1011:                                                result_array+=value;
                   1012:                                                if(!--limit)
                   1013:                                                        break;
                   1014:                                        }
                   1015:                                }
                   1016:                        }
                   1017:                }
                   1018:        }
                   1019: 
                   1020:        r.write(*result);
                   1021: }
                   1022: 
                   1023: static void _reverse(Request& r, MethodParams& params) {
1.5       moko     1024:        ArrayValue& source_array=GET_SELF(r, VArray).array();
1.1       moko     1025: 
1.5       moko     1026:        VArray& result=*new VArray(source_array.count());
1.1       moko     1027:        ArrayValue& result_array=result.array();
                   1028: 
1.4       moko     1029:        for(ArrayValue::ReverseIterator i(source_array); i; ){
                   1030:                result_array+=i.prev();
1.1       moko     1031:        }
                   1032: 
                   1033:        r.write(result);
                   1034: }
                   1035: 
                   1036: 
                   1037: // constructor
                   1038: 
                   1039: MArray::MArray(): Methoded(VARRAY_TYPE) {
                   1040: 
                   1041:        // ^array::create[[copy_from]]
                   1042:        add_native_method("create", Method::CT_DYNAMIC, _create_or_add, 0, 1);
                   1043:        // ^array.add[add_from]
                   1044:        add_native_method("add", Method::CT_DYNAMIC, _create_or_add, 1, 1);
1.6       moko     1045:        // ^array.join[join_from[;options]]
                   1046:        add_native_method("join", Method::CT_DYNAMIC, _join, 1, 2);
1.1       moko     1047: 
1.9       moko     1048:        // ^array.left(n)
                   1049:        add_native_method("left", Method::CT_DYNAMIC, _left, 1, 1);
                   1050:        // ^array.right(n)
                   1051:        add_native_method("right", Method::CT_DYNAMIC, _right, 1, 1);
                   1052:        // ^array.mid(p)
                   1053:        // ^array.mid(p;n)
                   1054:        add_native_method("mid", Method::CT_DYNAMIC, _mid, 1, 2);
1.1       moko     1055: 
1.8       moko     1056:        // ^array::new[value;value]
                   1057:        add_native_method("new", Method::CT_DYNAMIC, _append, 0, 10000);
1.2       moko     1058:        // ^array.append[value;value]
                   1059:        add_native_method("append", Method::CT_DYNAMIC, _append, 1, 10000);
                   1060:        // ^array.insert[index;value...]
                   1061:        add_native_method("insert", Method::CT_DYNAMIC, _insert, 2, 10000);
                   1062: 
                   1063:        // ^array.delete[index]
1.1       moko     1064:        add_native_method("delete", Method::CT_DYNAMIC, _delete, 0, 1);
1.7       moko     1065:        // ^array.remove[index]
                   1066:        add_native_method("remove", Method::CT_DYNAMIC, _remove, 1, 1);
1.1       moko     1067: 
1.2       moko     1068:        // ^array.contains[index]
1.1       moko     1069:        add_native_method("contains", Method::CT_DYNAMIC, _contains, 1, 1);
                   1070: 
                   1071:        // ^array::sql[query][options array]
                   1072:        add_native_method("sql", Method::CT_DYNAMIC, _sql, 1, 2);
                   1073: 
                   1074:        // ^array._keys[[column name]]
                   1075:        add_native_method("_keys", Method::CT_DYNAMIC, _keys, 0, 1);
                   1076: 
1.5       moko     1077:        // ^array._count[[all]]
                   1078:        add_native_method("_count", Method::CT_DYNAMIC, _count, 0, 1);
1.1       moko     1079: 
1.7       moko     1080:        // ^array.for[index;value]{code}[delim]
                   1081:        add_native_method("for", Method::CT_DYNAMIC, _for, 3, 3+1);
1.2       moko     1082:        // ^array.foreach[index;value]{code}[delim]
1.7       moko     1083:        add_native_method("foreach", Method::CT_DYNAMIC, _foreach, 3, 3+1);
1.1       moko     1084: 
1.2       moko     1085:        // ^array.sort[index;value]{string-key-maker}[[asc|desc]]
                   1086:        // ^array.sort[index;value](numeric-key-maker)[[asc|desc]]
1.1       moko     1087:        add_native_method("sort", Method::CT_DYNAMIC, _sort, 3, 4);
                   1088: 
1.2       moko     1089:        // ^array.select[index;value](bool-condition)[options hash]
1.1       moko     1090:        add_native_method("select", Method::CT_DYNAMIC, _select, 3, 4);
                   1091: 
                   1092:        // ^array.reverse[]
                   1093:        add_native_method("reverse", Method::CT_DYNAMIC, _reverse, 0, 0);
                   1094: 
1.2       moko     1095:        // ^array._at[first|last[;'key'|'value'|'hash']]
                   1096:        // ^array._at([-+]offset)[['key'|'value'|'hash']]
1.1       moko     1097:        add_native_method("_at", Method::CT_DYNAMIC, _at, 1, 2);
                   1098: 
                   1099: #ifdef FEATURE_GET_ELEMENT4CALL
                   1100:        // aliases without "_"
                   1101:        add_native_method("keys", Method::CT_DYNAMIC, _keys, 0, 1);
1.14    ! moko     1102:        add_native_method("count", Method::CT_DYNAMIC, _count, 0, 1);
1.1       moko     1103:        add_native_method("at", Method::CT_DYNAMIC, _at, 1, 2);
                   1104: #endif
                   1105: 
                   1106: }

E-mail: