Annotation of parser3/src/classes/table.C, revision 1.224

1.20      paf         1: /** @file
1.47      paf         2:        Parser: @b table parser class.
1.20      paf         3: 
1.210     paf         4:        Copyright (c) 2001-2005 ArtLebedev Group (http://www.artlebedev.com)
1.144     paf         5:        Author: Alexandr Petrosian <paf@design.ru> (http://paf.design.ru)
1.154     paf         6: */
1.221     paf         7: 
1.224   ! misha       8: static const char * const IDENT_TABLE_C="$Date: 2006/06/09 19:09:19 $";
        !             9: 
        !            10: #include <sstream>
        !            11: using namespace std;
1.1       paf        12: 
1.105     parser     13: #include "classes.h"
1.182     paf        14: #include "pa_vmethod_frame.h"
                     15: 
1.16      paf        16: #include "pa_common.h"
1.1       paf        17: #include "pa_request.h"
                     18: #include "pa_vtable.h"
1.6       paf        19: #include "pa_vint.h"
1.51      paf        20: #include "pa_sql_connection.h"
1.72      paf        21: #include "pa_vbool.h"
1.1       paf        22: 
1.66      paf        23: // class
                     24: 
1.182     paf        25: class MTable: public Methoded {
1.66      paf        26: public: // VStateless_class
1.209     paf        27:        Value* create_new_value(Pool&, HashStringValue&) { return new VTable(); }
1.66      paf        28: 
                     29: public:
1.182     paf        30:        MTable();
1.70      paf        31: 
                     32: public: // Methoded
1.66      paf        33:        bool used_directly() { return true; }
                     34: };
1.1       paf        35: 
1.182     paf        36: // global variable
                     37: 
                     38: DECLARE_CLASS_VAR(table, new MTable, 0);
                     39: 
1.221     paf        40: // externs
                     41: 
                     42: extern String cycle_data_name;
                     43: 
1.182     paf        44: // defines for globals
                     45: 
1.203     paf        46: #define SQL_BIND_NAME "bind"
1.182     paf        47: #define SQL_DEFAULT_NAME "default"
                     48: #define SQL_DISTINCT_NAME "distinct"
                     49: #define TABLE_REVERSE_NAME "reverse"
                     50: 
                     51: // globals
                     52: 
1.203     paf        53: String sql_bind_name(SQL_BIND_NAME);
1.214     paf        54: String sql_limit_name(PA_SQL_LIMIT_NAME);
                     55: String sql_offset_name(PA_SQL_OFFSET_NAME);
1.182     paf        56: String sql_default_name(SQL_DEFAULT_NAME);
                     57: String sql_distinct_name(SQL_DISTINCT_NAME);
                     58: String table_reverse_name(TABLE_REVERSE_NAME);
                     59: 
1.1       paf        60: // methods
1.66      paf        61: 
1.182     paf        62: static Table::Action_options get_action_options(Request& r, MethodParams& params, 
                     63:                                                const Table& source) {
1.176     paf        64:        Table::Action_options result;
1.182     paf        65:        if(!params.count())
                     66:                return result;
                     67: 
                     68:        Value& maybe_options=params.last();
                     69: /* can not do it: 
                     70:        want to enable ^table::create[$source;
                     71: #              $.option[]
                     72:        ]
                     73:        but there is ^table.locate[name;value]
1.176     paf        74: 
1.212     paf        75:        ...if(voptions.is_defined() && !voptions.is_string()))
1.182     paf        76:        if(maybe_options.is_string()) { // allow empty options
                     77:                result.defined=true;
1.176     paf        78:                return result;
1.182     paf        79:        }
                     80: */
                     81:        HashStringValue* options=maybe_options.get_hash();
1.176     paf        82:        if(!options)
                     83:                return result;
                     84: 
                     85:        result.defined=true;
                     86:        bool defined_offset=false;
                     87: 
                     88:        int valid_options=0;
1.182     paf        89:        if(Value* voffset=options->get(sql_offset_name)) {
1.176     paf        90:                valid_options++;
                     91:                defined_offset=true;
                     92:                if(voffset->is_string()) {
1.182     paf        93:                        const String&  soffset=*voffset->get_string();
1.176     paf        94:                        if(soffset == "cur")
                     95:                                result.offset=source.current();
                     96:                        else
1.164     paf        97:                                throw Exception("parser.runtime",
1.176     paf        98:                                        &soffset,
                     99:                                        "must be 'cur' string or expression");
                    100:                } else 
                    101:                        result.offset=r.process_to_value(*voffset).as_int();
                    102:        }
1.182     paf       103:        if(Value* vlimit=options->get(sql_limit_name)) {
1.176     paf       104:                valid_options++;
                    105:                result.limit=r.process_to_value(*vlimit).as_int();
                    106:        }
1.182     paf       107:        if(Value *vreverse=(Value *)options->get(table_reverse_name)) { 
                    108:                valid_options++; 
                    109:                result.reverse=r.process_to_value(*vreverse).as_bool(); 
                    110:                if(result.reverse && !defined_offset) 
                    111:                        result.offset=source.count()-1; 
                    112:        } 
                    113: 
                    114:        if(valid_options!=options->count())
1.176     paf       115:                throw Exception("parser.runtime",
1.182     paf       116:                        0,
1.176     paf       117:                        "called with invalid option");
                    118: 
                    119:        return result;
                    120: }
1.180     paf       121: static void check_option_param(bool options_defined, 
1.182     paf       122:                          MethodParams& params, size_t next_param_index,
1.176     paf       123:                          const char *msg) {
1.182     paf       124:        if(next_param_index+(options_defined?1:0) != params.count())
1.176     paf       125:                throw Exception("parser.runtime",
1.182     paf       126:                        0,
1.176     paf       127:                        "%s", msg);
1.157     paf       128: }
                    129: 
1.182     paf       130: static void _create(Request& r, MethodParams& params) {
1.157     paf       131:        // clone/copy part?
1.182     paf       132:        if(Table *source=params[0].get_table()) {
                    133:                Table::Action_options o=get_action_options(r, params, *source);
                    134:                check_option_param(o.defined, params, 1, 
1.176     paf       135:                        "too many parameters");
1.182     paf       136:                GET_SELF(r, VTable).set_table(*new Table(*source, o));
1.157     paf       137:                return;
                    138:        }
1.142     paf       139: 
1.1       paf       140:        // data is last parameter
1.182     paf       141:        Temp_lang temp_lang(r, String::L_PASS_APPENDED);
                    142:        const String&  data=
                    143:                r.process_to_string(params.as_junction(params.count()-1, "body must be code"));
1.44      paf       144: 
                    145:        // parse columns
1.182     paf       146:        size_t raw_pos_after=0;
                    147:        Table::columns_type columns;
                    148:        if(params.count()==2) {
1.216     paf       149:                const String& snameless=params.as_string(0, "called with two params, first param may only be string 'nameless'");
1.213     paf       150:                if(snameless!="nameless")
                    151:                        throw Exception("parser.runtime",
                    152:                                &snameless,
                    153:                                "table::create called with two params, first param may only be 'nameless'");
1.182     paf       154:                columns=Table::columns_type(0); // nameless
1.21      paf       155:        } else {
1.182     paf       156:                columns=Table::columns_type(new ArrayString);
1.44      paf       157: 
1.182     paf       158:                ArrayString head;
                    159:                data.split(head, raw_pos_after, "\n", String::L_AS_IS, 1);
                    160:                if(head.count()) {
                    161:                        size_t col_pos_after=0;
                    162:                        head[0]->split(*columns, col_pos_after, "\t", String::L_AS_IS);
                    163:                }
1.44      paf       164:        }
                    165: 
1.182     paf       166:        Table& table=*new Table(columns);
1.44      paf       167:        // parse cells
1.182     paf       168: 
                    169:        ArrayString rows;
                    170:        data.split(rows, raw_pos_after, "\n", String::L_AS_IS);
                    171:        Array_iterator<const String*> i(rows);
1.98      parser    172:        while(i.has_next()) {
1.182     paf       173:                Table::element_type row(new ArrayString);
                    174:                const String&  string=*i.next();
1.118     parser    175:                // remove comment lines
1.182     paf       176:                if(!string.length())
1.44      paf       177:                        continue;
                    178: 
1.182     paf       179:                size_t col_pos_after=0;
                    180:                string.split(*row, col_pos_after, "\t", String::L_AS_IS);
                    181:                table+=row;
1.17      paf       182:        }
1.1       paf       183: 
1.44      paf       184:        // replace any previous table value
1.182     paf       185:        GET_SELF(r, VTable).set_table(table);
1.44      paf       186: }
                    187: 
1.187     paf       188: struct lsplit_result {
                    189:        char* piece;
                    190:        char delim;
                    191: 
                    192:        operator bool() { return piece!=0; }
                    193: };
                    194: 
                    195: inline lsplit_result lsplit(char* string, char delim1, char delim2) {
                    196:        lsplit_result result;
                    197:     if(string) {
                    198:                char delims[]={delim1, delim2, 0};
                    199:                if(char* v=strpbrk(string, delims)) {
                    200:                        result.delim=*v;
                    201:                        *v=0;
                    202:                        result.piece=v+1;
                    203:                        return result;
                    204:                }
                    205:     }
                    206:        result.piece=0;
                    207:        result.delim=0;
                    208:     return result;
                    209: }
                    210: 
                    211: inline lsplit_result lsplit(char* *string_ref, char delim1, char delim2) {
                    212:     lsplit_result result;
                    213:        result.piece=*string_ref;
                    214:        lsplit_result next=lsplit(*string_ref, delim1, delim2);
                    215:        result.delim=next.delim;
                    216:        *string_ref=next.piece;
                    217:     return result;
                    218: }
                    219: 
                    220: static lsplit_result lsplit(char** string_ref, char delim1, char delim2, char encloser) {
                    221:        lsplit_result result;
                    222: 
                    223:     if(char* string=*string_ref) {
                    224:                if(encloser && *string==encloser) {
                    225:             string++;
                    226:                        
                    227:                        char *read;
                    228:                        char *write;
                    229:                        write=read=string;
                    230:                        char c;
1.193     paf       231:                        while((c=*read++)) {
1.187     paf       232:                                if(c==encloser) {
                    233:                                        char n=*read;
                    234:                                        if(n==encloser) // double-encloser stands for encloser
                    235:                                                read++;
                    236:                                        else if(n==delim1 || n==delim2) {
                    237:                                                result.delim=n;
                    238:                                                read++;
                    239:                                                break;
                    240:                                        }
                    241:                                }
                    242: 
                    243:                                *write++=c;
                    244:                        }
                    245:                        *write=0; // terminate
                    246:                        *string_ref=c? read: 0;
                    247:                        result.piece=string;
                    248:                        return result;
                    249:                } else
                    250:                        return lsplit(string_ref, delim1, delim2);
                    251:     }
                    252:        result.piece=0;
                    253:     return result;
                    254: }
                    255: 
                    256: static void skip_empty_and_comment_lines( char** data_ref ) {
                    257:        if(char *data=*data_ref) {
                    258:                while( char c=*data ) {
                    259:                        if( c== '\n' || c == '#' ) {
                    260:                                /*nowhere=*/getrow(&data); // remove empty&comment lines
1.199     paf       261:                                if(!(*data_ref=data))
                    262:                                        break;
1.187     paf       263:                                continue;
                    264:                        }
                    265:                        break;
                    266:                }
                    267:        }
                    268: }
                    269: 
                    270: struct TableSeparators {
1.206     paf       271:        char column;  const String* scolumn;
                    272:        char encloser; const String* sencloser;
                    273: 
                    274:        TableSeparators():
                    275:                column('\t'), scolumn(new String("\t", false)),
                    276:                encloser(0), sencloser(0)
                    277:        {}
1.214     paf       278:        int load( HashStringValue& options ) {
                    279:                int result=0;
                    280:                if(Value* vseparator=options.get(PA_COLUMN_SEPARATOR_NAME)) {
1.206     paf       281:                        scolumn=&vseparator->as_string();
                    282:                        if(scolumn->length()!=1)
1.187     paf       283:                                throw Exception("parser.runtime",
1.206     paf       284:                                        scolumn,
1.187     paf       285:                                        "separator must be one character long");
1.206     paf       286:                        column=scolumn->first_char();
1.214     paf       287:                        result++;
1.187     paf       288:                }
1.214     paf       289:                if(Value* vencloser=options.get(PA_COLUMN_ENCLOSER_NAME)) {
1.188     paf       290:                        sencloser=&vencloser->as_string();
                    291:                        if(sencloser->length()!=1)
1.187     paf       292:                                throw Exception("parser.runtime",
1.188     paf       293:                                        sencloser,
1.187     paf       294:                                        "encloser must be one character long");
1.188     paf       295:                        encloser=sencloser->first_char();
1.214     paf       296:                        result++;
1.187     paf       297:                }
1.214     paf       298:                return result;
1.187     paf       299:        }
                    300: };
                    301: 
1.182     paf       302: static void _load(Request& r, MethodParams& params) {
                    303:        const String&  first_param=params.as_string(0, "file name must be string");
1.168     paf       304:        int filename_param_index=0;
                    305:        bool nameless=first_param=="nameless";
                    306:        if(nameless)
                    307:                filename_param_index++;
1.182     paf       308:        size_t options_param_index=filename_param_index+1;
1.186     paf       309: 
                    310:        HashStringValue *options=0;
1.187     paf       311:        TableSeparators separators;
1.186     paf       312:        if(options_param_index<params.count()
                    313:                && (options=params.as_no_junction(options_param_index, "additional params must be hash").get_hash())) {
                    314:                // cloning, so that we could change [to simplify checks on params inside file_read_text
                    315:                options=new HashStringValue(*options);
1.187     paf       316:                separators.load(*options);
1.186     paf       317:        }
                    318: 
1.44      paf       319:        // loading text
1.182     paf       320:        char *data=file_read_text(r.charsets,
                    321:                r.absolute(params.as_string(filename_param_index, "file name must be string")),
1.168     paf       322:                true,
1.186     paf       323:                options
1.168     paf       324:        );
1.44      paf       325: 
1.1       paf       326:        // parse columns
1.182     paf       327:        Table::columns_type columns;
1.168     paf       328:        if(nameless) {
1.182     paf       329:                columns=Table::columns_type(0); // nameless
1.1       paf       330:        } else {
1.182     paf       331:                columns=Table::columns_type(new ArrayString);
1.1       paf       332: 
1.187     paf       333:                skip_empty_and_comment_lines(&data);
                    334:                while( lsplit_result sr=lsplit(&data, separators.column, '\n', separators.encloser) ) {
                    335:                        *columns+=new String(sr.piece, 0, true);
                    336:                        if(sr.delim=='\n') 
                    337:                                break;
1.139     paf       338:                }
1.1       paf       339:        }
1.187     paf       340:        
                    341:        Table& table=*new Table(columns);
1.219     paf       342:        int columns_count=columns? columns->count(): 0;
1.1       paf       343: 
                    344:        // parse cells
1.218     paf       345:        Table::element_type row(new ArrayString(columns_count));
1.187     paf       346:        skip_empty_and_comment_lines(&data);
                    347:        while( lsplit_result sr=lsplit(&data, separators.column, '\n', separators.encloser) ) {
1.201     paf       348:                if(!*sr.piece && !sr.delim && !row->count()) // append last empty column [if without \n]
                    349:                        break;
1.187     paf       350:                *row+=new String(sr.piece, 0, true);
                    351:                if(sr.delim=='\n') {
                    352:                        table+=row;
1.218     paf       353:                        row=new ArrayString(columns_count);
1.187     paf       354:                        skip_empty_and_comment_lines(&data);
1.1       paf       355:                }
1.187     paf       356:        }
                    357:        // last line [if without \n]
                    358:        if(row->count())
1.1       paf       359:                table+=row;
1.187     paf       360:        
1.1       paf       361:        // replace any previous table value
1.182     paf       362:        GET_SELF(r, VTable).set_table(table);
1.1       paf       363: }
1.2       paf       364: 
1.224   ! misha     365: void maybe_enclose( String& to, const String& from, char encloser, const String* sencloser ) {
1.188     paf       366:        if(encloser) {
                    367:                to<<*sencloser;
                    368:                // while we have 'encloser'...
1.189     paf       369:                size_t pos_after=0;
1.220     paf       370:                for( size_t pos_before; (pos_before=from.pos( encloser, pos_after ))!=STRING_NOT_FOUND; pos_after=pos_before) {
                    371:                        pos_before++; // including first encloser (and skipping it for next pos)
                    372:             to<<from.mid(pos_after, pos_before);
                    373:                        to<<*sencloser; // doubling encloser
1.188     paf       374:                }
                    375:                // last piece
                    376:                size_t from_length=from.length();
                    377:                if(pos_after<from_length)
                    378:                        to<<from.mid(pos_after, from_length);
                    379: 
                    380:                to<<*sencloser;
                    381:        } else
1.202     paf       382:                to<<from;
1.188     paf       383: }
                    384: 
1.224   ! misha     385: void maybe_enclose( ostringstream& to, const String& from, char encloser ) {
        !           386:        if(encloser) {
        !           387:                to<<encloser;
        !           388:                // while we have 'encloser'...
        !           389:                size_t pos_after=0;
        !           390:                for( size_t pos_before; (pos_before=from.pos( encloser, pos_after ))!=STRING_NOT_FOUND; pos_after=pos_before) {
        !           391:                        pos_before++; // including first encloser (and skipping it for next pos)
        !           392:             to<<from.mid(pos_after, pos_before).cstr();
        !           393:                        to<<encloser; // doubling encloser
        !           394:                }
        !           395:                // last piece
        !           396:                size_t from_length=from.length();
        !           397:                if(pos_after<from_length)
        !           398:                        to<<from.mid(pos_after, from_length).cstr();
        !           399: 
        !           400:                to<<encloser;
        !           401:        } else
        !           402:                to<<from.cstr();
        !           403: }
        !           404: 
1.188     paf       405: 
1.224   ! misha     406: static void _save_old(Request& r, MethodParams& params) {
1.188     paf       407:        const String& first_arg=params.as_string(0, "first argument must not be code");
                    408:        size_t param_index=1;
                    409: 
                    410:        bool do_append=false;
                    411:        bool output_column_names=true;
                    412: 
                    413:        // mode?
                    414:        if(first_arg=="append")
                    415:                do_append=true;
                    416:        else if(first_arg=="nameless")
                    417:                output_column_names=false;
                    418:        else
                    419:                --param_index;
                    420: 
                    421:        const String& file_name=params.as_string(param_index++, "file name must not be code");
                    422: 
                    423:        TableSeparators separators;
                    424:        if(param_index<params.count()) {
1.222     paf       425:                Value& voptions=params.as_no_junction(param_index++, "additional params must be hash");
                    426:                if( voptions.is_defined() && !voptions.is_string() ) {
                    427:                        if(HashStringValue* options=voptions.get_hash()) {
1.223     paf       428:                                int valid_options=separators.load(*options);
                    429:                                if(valid_options!=options->count())
                    430:                                        throw Exception("parser.runtime",
                    431:                                                0,
                    432:                                                "invalid option passed");
                    433:                        } else {
1.188     paf       434:                                throw Exception("parser.runtime",
                    435:                                        0,
1.223     paf       436:                                        "additional params must be hash (did you spell mode parameter correctly?)");
                    437:                        }
1.222     paf       438:                }
1.188     paf       439:        }
                    440:        if(param_index<params.count())
                    441:                throw Exception("parser.runtime",
                    442:                        0,
                    443:                        "bad mode (must be nameless or append)");
1.22      paf       444: 
1.182     paf       445:        Table& table=GET_SELF(r, VTable).table();
1.31      paf       446: 
1.182     paf       447:        String sdata;
1.188     paf       448:        if(output_column_names) {
1.31      paf       449:                if(table.columns()) { // named table
1.182     paf       450:                        for(Array_iterator<const String*> i(*table.columns()); i.has_next(); ) {
1.188     paf       451:                                maybe_enclose( sdata, *i.next(), separators.encloser, separators.sencloser );
1.98      parser    452:                                if(i.has_next())
1.206     paf       453:                                        sdata<<*separators.scolumn;
1.31      paf       454:                        }
1.188     paf       455:                } else { // nameless table [we were asked to output column names]
1.182     paf       456:                        if(int lsize=table.count()?table[0]->count():0)
1.31      paf       457:                                for(int column=0; column<lsize; column++) {
1.182     paf       458:                                        char *cindex_tab=new(PointerFreeGC) char[MAX_NUMBER];
                    459:                                        sdata.append_know_length(cindex_tab, 
1.185     paf       460:                                                snprintf(cindex_tab, MAX_NUMBER, 
1.206     paf       461:                                                        column<lsize-1?"%d%c":"%d", column, separators.column),
1.185     paf       462:                                                        String::L_CLEAN);
1.31      paf       463:                                }
                    464:                        else
1.182     paf       465:                                sdata.append_help_length("empty nameless table", 0, String::L_CLEAN);
1.31      paf       466:                }
1.182     paf       467:                sdata.append_know_length("\n", 1, String::L_CLEAN);
1.188     paf       468:        }
1.129     paf       469: 
1.31      paf       470:        // data lines
1.182     paf       471:        Array_iterator<ArrayString*> i(table);
1.98      parser    472:        while(i.has_next()) {
1.182     paf       473:                for(Array_iterator<const String*> c(*i.next()); c.has_next(); ) {
1.188     paf       474:                        maybe_enclose( sdata, *c.next(), separators.encloser, separators.sencloser );
1.98      parser    475:                        if(c.has_next())
1.206     paf       476:                                sdata<<*separators.scolumn;
1.31      paf       477:                }
1.182     paf       478:                sdata.append_know_length("\n", 1, String::L_CLEAN);
1.31      paf       479:        }
                    480: 
                    481:        // write
1.217     paf       482:        {
                    483:                const char* data_cstr=sdata.cstr();
                    484:                file_write(r.absolute(file_name), 
                    485:                        data_cstr, sdata.length(), true, do_append);
                    486:                if(*data_cstr) // not empty (when empty it's not heap memory)
                    487:                        pa_free((void*)data_cstr); // not needed anymore
                    488:        }
1.22      paf       489: }
                    490: 
1.224   ! misha     491: static void _save(Request& r, MethodParams& params) {
        !           492:        const String& first_arg=params.as_string(0, "first argument must not be code");
        !           493:        size_t param_index=1;
        !           494: 
        !           495:        bool do_append=false;
        !           496:        bool output_column_names=true;
        !           497: 
        !           498:        // mode?
        !           499:        if(first_arg=="append")
        !           500:                do_append=true;
        !           501:        else if(first_arg=="nameless")
        !           502:                output_column_names=false;
        !           503:        else
        !           504:                --param_index;
        !           505: 
        !           506:        const String& file_name=params.as_string(param_index++, "file name must not be code");
        !           507: 
        !           508:        TableSeparators separators;
        !           509:        if(param_index<params.count()) {
        !           510:                Value& voptions=params.as_no_junction(param_index++, "additional params must be hash");
        !           511:                if( voptions.is_defined() && !voptions.is_string() ) {
        !           512:                        if(HashStringValue* options=voptions.get_hash()) {
        !           513:                                int valid_options=separators.load(*options);
        !           514:                                if(valid_options!=options->count())
        !           515:                                        throw Exception("parser.runtime",
        !           516:                                                0,
        !           517:                                                "invalid option passed");
        !           518:                        } else {
        !           519:                                throw Exception("parser.runtime",
        !           520:                                        0,
        !           521:                                        "additional params must be hash (did you spell mode parameter correctly?)");
        !           522:                        }
        !           523:                }
        !           524:        }
        !           525:        if(param_index<params.count())
        !           526:                throw Exception("parser.runtime",
        !           527:                        0,
        !           528:                        "bad mode (must be nameless or append)");
        !           529: 
        !           530:        Table& table=GET_SELF(r, VTable).table();
        !           531: 
        !           532:        ostringstream ost(stringstream::out);
        !           533: 
        !           534:        // process header
        !           535:        if(output_column_names) {
        !           536:                if(table.columns()) { // named table
        !           537:                        for(Array_iterator<const String*> i(*table.columns()); i.has_next(); ) {
        !           538:                                maybe_enclose( ost, *i.next(), separators.encloser );
        !           539:                                if(i.has_next()){
        !           540:                                        ost<<separators.column;
        !           541:                                }
        !           542:                        }
        !           543:                } else { // nameless table [we were asked to output column names]
        !           544:                        if(int lsize=table.count()?table[0]->count():0)
        !           545:                                for(int column=0; column<lsize; column++) {
        !           546:                                        ost<<column;
        !           547:                                        if(column<lsize-1){
        !           548:                                                ost<<separators.column;
        !           549:                                        }
        !           550:                                }
        !           551:                        else
        !           552:                                ost<<"empty nameless table";
        !           553:                }
        !           554:                ost<<'\n';
        !           555:        }
        !           556: 
        !           557:        // process data lines
        !           558:        Array_iterator<ArrayString*> i(table);
        !           559:        while(i.has_next()) {
        !           560:                for(Array_iterator<const String*> c(*i.next()); c.has_next(); ) {
        !           561:                        maybe_enclose( ost, *c.next(), separators.encloser );
        !           562:                        if(c.has_next())
        !           563:                                ost<<separators.column;
        !           564:                }
        !           565:                ost<<'\n';
        !           566:        }
        !           567: 
        !           568:        // write
        !           569:        {
        !           570:                string data=ost.str();
        !           571:                const char* data_cstr = data.c_str();
        !           572: 
        !           573:                file_write(r.absolute(file_name), data_cstr, data.length(), true /* as text */, do_append);
        !           574:        }
        !           575: }
        !           576: 
1.182     paf       577: static void _count(Request& r, MethodParams&) {
                    578:        int result=GET_SELF(r, VTable).table().count();
                    579:        r.write_no_lang(*new VInt(result));
1.6       paf       580: }
                    581: 
1.182     paf       582: static void _line(Request& r, MethodParams&) {
                    583:        int result=1+GET_SELF(r, VTable).table().current();
                    584:        r.write_no_lang(*new VInt(result));
1.6       paf       585: }
                    586: 
1.182     paf       587: static void _offset(Request& r, MethodParams& params) {
                    588:        Table& table=GET_SELF(r, VTable).table();
                    589:        if(params.count()) {
1.133     paf       590:                bool absolute=false;
1.182     paf       591:                if(params.count()>1) {
                    592:                    const String&  whence=params.as_string(0, "whence must be string");
1.133     paf       593:                    if(whence=="cur")
1.134     paf       594:                                absolute=false;
1.133     paf       595:                    else if(whence=="set")
1.134     paf       596:                                absolute=true;
1.133     paf       597:                    else
1.146     paf       598:                                throw Exception("parser.runtime",
1.134     paf       599:                                        &whence,
                    600:                                        "is invalid whence, valid are 'cur' or 'set'");
1.157     paf       601:                }
1.133     paf       602:                
1.211     paf       603:                int offset=params.as_int(params.count()-1, "offset must be expression", r);
                    604:                table.offset(absolute, offset);
1.151     paf       605:        } else
1.182     paf       606:                r.write_no_lang(*new VInt(table.current()));
1.6       paf       607: }
                    608: 
1.182     paf       609: static void _menu(Request& r, MethodParams& params) {
1.221     paf       610:        Temp_hash_value<const String::Body, void*> 
                    611:                cycle_data_setter(r.classes_conf, cycle_data_name, /*any not null flag*/&r);
                    612: 
1.182     paf       613:        Value& body_code=params.as_junction(0, "body must be code");
1.7       paf       614:        
1.182     paf       615:        Value* delim_maybe_code=params.count()>1?&params[1]:0;
1.7       paf       616: 
1.182     paf       617:        Table& table=GET_SELF(r, VTable).table();
1.7       paf       618:        bool need_delim=false;
1.99      parser    619:        int saved_current=table.current();
1.182     paf       620:        int size=table.count();
1.99      parser    621:        for(int row=0; row<size; row++) {
1.22      paf       622:                table.set_current(row);
1.7       paf       623: 
1.161     paf       624:                StringOrValue sv_processed=r.process(body_code);
1.221     paf       625:                Request::Skip lskip=r.get_skip(); r.set_skip(Request::SKIP_NOTHING);
1.182     paf       626:                const String* s_processed=sv_processed.get_string();
                    627:                if(delim_maybe_code && s_processed && s_processed->length()) { // delimiter set and we have body
1.161     paf       628:                        if(need_delim) // need delim & iteration produced string?
1.150     paf       629:                                r.write_pass_lang(r.process(*delim_maybe_code));
1.7       paf       630:                        need_delim=true;
                    631:                }
1.161     paf       632:                r.write_pass_lang(sv_processed);
1.221     paf       633: 
                    634:                if(lskip==Request::SKIP_BREAK)
                    635:                        break;
1.7       paf       636:        }
1.99      parser    637:        table.set_current(saved_current);
1.7       paf       638: }
                    639: 
1.110     parser    640: #ifndef DOXYGEN
1.174     paf       641: enum Table2hash_distint { D_ILLEGAL, D_FIRST, D_TABLES };
1.74      paf       642: struct Row_info {
1.166     paf       643:        Request *r;
1.74      paf       644:        Table *table;
1.182     paf       645:        Value* key_code;
                    646:        size_t key_field;
                    647:        Array<int>* value_fields;
                    648:        HashStringValue* hash;
1.174     paf       649:        Table2hash_distint distinct;
1.182     paf       650:        size_t row;
1.74      paf       651: };
1.110     parser    652: #endif
1.182     paf       653: static void table_row_to_hash(Table::element_type row, Row_info *info) {
                    654:        const String* key;
                    655:        if(info->key_code) {
                    656:                info->table->set_current(info->row++); // change context row
                    657:                StringOrValue sv_processed=info->r->process(*info->key_code);
1.166     paf       658:                key=&sv_processed.as_string();
                    659:        } else
1.182     paf       660:                key=info->key_field<row->count()?row->get(info->key_field):0;
1.166     paf       661: 
                    662:        if(!key)
                    663:                return; // ignore rows without key [too-short-record_array if-indexed]
1.74      paf       664:                
1.182     paf       665:        switch(info->distinct) {
1.174     paf       666:        case D_ILLEGAL: case D_FIRST:
                    667:                {
1.182     paf       668:                        VHash* vhash=new VHash;
                    669:                        HashStringValue& hash=vhash->hash();
                    670:                        for(Array_iterator<int> i(*info->value_fields); i.has_next(); ) {
                    671:                                size_t value_field=i.next();
                    672:                                if(value_field<row->count())
1.174     paf       673:                                        hash.put(
1.182     paf       674:                                                *info->table->columns()->get(value_field), 
                    675:                                                new VString(*row->get(value_field)));
1.174     paf       676:                        }
                    677: 
1.182     paf       678:                        if(info->hash->put_dont_replace(*key, vhash)) // put. existed?
                    679:                                if(info->distinct==D_ILLEGAL)
1.174     paf       680:                                        throw Exception("parser.runtime",
                    681:                                                key,
                    682:                                                "duplicate key");
                    683:                }
                    684:                break;
                    685:        case D_TABLES:
                    686:                {
1.182     paf       687:                        VTable* vtable=(VTable*)info->hash->get(*key); // put. table existed?
1.174     paf       688:                        Table* table;
                    689:                        if(vtable) 
                    690:                                table=vtable->get_table();
                    691:                        else {
                    692:                                // no? creating table of same structure as source
1.179     paf       693:                                Table::Action_options table_options(0, 0);
1.182     paf       694:                                table=new Table(*info->table, table_options/*no rows, just structure*/);
                    695:                                info->hash->put(*key, new VTable(table));
1.174     paf       696:                        }
1.182     paf       697:                        *table+=row;
1.174     paf       698:                }
                    699:                break;
                    700:        default:
                    701:                throw Exception(0,
                    702:                        0,
1.182     paf       703:                        "invalid distinct code (#%d)", info->distinct);
1.74      paf       704:        }
                    705: }
1.182     paf       706: static void _hash(Request& r, MethodParams& params) {
                    707:        Table& self_table=GET_SELF(r, VTable).table();
                    708:        VHash& result=*new VHash;
                    709:        if(Table::columns_type columns=self_table.columns())
                    710:                if(columns->count()>0) {
1.174     paf       711:                        Table2hash_distint distinct=D_ILLEGAL;
1.182     paf       712:                        int param_index=params.count()-1;
1.166     paf       713:                        if(param_index>0) {
1.182     paf       714:                                if(HashStringValue* options=
                    715:                                        params.as_no_junction(param_index, "param must not be code").get_hash()) {
1.166     paf       716:                                        --param_index;
                    717:                                        int valid_options=0;
1.182     paf       718:                                        if(Value* vdistinct_code=options->get(sql_distinct_name)) {
1.166     paf       719:                                                valid_options++;
1.174     paf       720:                                                Value& vdistinct_value=r.process_to_value(*vdistinct_code);
                    721:                                                if(vdistinct_value.is_string()) {
                    722:                                                        const String& sdistinct=*vdistinct_value.get_string();
                    723:                                                        if(sdistinct=="tables")
                    724:                                                                distinct=D_TABLES;
                    725:                                                        else
                    726:                                                                throw Exception("parser.runtime",
                    727:                                                                        &sdistinct,
                    728:                                                                        "must be 'tables' or true/false");
                    729:                                                } else
                    730:                                                        distinct=vdistinct_value.as_bool()?D_FIRST:D_ILLEGAL;
1.166     paf       731:                                        }
1.182     paf       732:                                        if(valid_options!=options->count())
1.166     paf       733:                                                throw Exception("parser.runtime",
1.182     paf       734:                                                        0,
1.166     paf       735:                                                        "called with invalid option");
1.163     paf       736:                                }
                    737:                        }
                    738:                        if(param_index==2) // bad options param type
                    739:                                throw Exception("parser.runtime",
1.182     paf       740:                                        0,
1.163     paf       741:                                        "options must be hash");
                    742: 
1.182     paf       743:                        Array<int> value_fields;
1.163     paf       744:                        if(param_index>0) {
1.174     paf       745:                                if(distinct!=D_ILLEGAL && distinct!=D_FIRST)
                    746:                                        throw Exception("parser.runtime",
                    747:                                                0,
                    748:                                                "in distinct[tables] mode you may not specify value field(s)");
1.182     paf       749:                                Value& value_fields_param=params.as_no_junction(param_index, "value field(s) must not be code");
1.123     parser    750:                                if(value_fields_param.is_string()) {
1.182     paf       751:                                        value_fields+=self_table.column_name2index(
                    752:                                                *value_fields_param.get_string(), true);
                    753:                                } else if(Table* value_fields_table=value_fields_param.get_table()) {
                    754:                                        for(Array_iterator<Table::element_type> i(*value_fields_table); 
                    755:                                                i.has_next(); ) {
                    756:                                                const String& value_field_name
                    757:                                                        =*i.next()->get(0);
                    758:                                                value_fields
                    759:                                                        +=self_table.column_name2index(value_field_name, true);
1.123     parser    760:                                        }
                    761:                                } else
1.146     paf       762:                                        throw Exception("parser.runtime",
1.182     paf       763:                                                0,
1.197     paf       764:                                                "value field(s) must be string or table"
1.123     parser    765:                                        );
                    766:                        } else { // by all columns, including key
1.174     paf       767:                                if(!(distinct!=D_ILLEGAL && distinct!=D_FIRST))
1.182     paf       768:                                        for(size_t i=0; i<columns->count(); i++)
1.174     paf       769:                                                value_fields+=i;
1.74      paf       770:                        }
                    771: 
1.182     paf       772: 
                    773:                        {
                    774:                                Value* key_param=&params[0];
1.193     paf       775:                                Row_info info={
                    776:                                        &r,
                    777:                                        &self_table,
                    778:                                        /*key_code=*/key_param->get_junction()?key_param:0,
1.197     paf       779:                                        /*key_field=*/0/*filled below*/,
1.193     paf       780:                                        &value_fields,
                    781:                                        &result.hash(),
                    782:                                        distinct,
                    783:                                        /*row=*/0
                    784:                                };
1.195     paf       785:                                info.key_field=(info.key_code?-1
                    786:                                                :self_table.column_name2index(key_param->as_string(), true));
1.182     paf       787: 
                    788:                                int saved_current=self_table.current();
                    789:                                self_table.for_each(table_row_to_hash, &info);
                    790:                                self_table.set_current(saved_current);
1.207     paf       791: 
                    792:                                result.extract_default();
1.182     paf       793:                        }
1.74      paf       794:                }
1.97      parser    795:        r.write_no_lang(result);
1.74      paf       796: }
                    797: 
1.110     parser    798: #ifndef DOXYGEN
1.78      paf       799: struct Table_seq_item {
1.182     paf       800:        ArrayString* row;
1.34      paf       801:        union {
1.182     paf       802:                const char *c_str;
1.34      paf       803:                double d;
                    804:        } value;
1.32      paf       805: };
1.110     parser    806: #endif
1.34      paf       807: static int sort_cmp_string(const void *a, const void *b) {
                    808:        return strcmp(
1.78      paf       809:                static_cast<const Table_seq_item *>(a)->value.c_str, 
                    810:                static_cast<const Table_seq_item *>(b)->value.c_str
1.34      paf       811:        );
                    812: }
                    813: static int sort_cmp_double(const void *a, const void *b) {
1.78      paf       814:        double va=static_cast<const Table_seq_item *>(a)->value.d;
                    815:        double vb=static_cast<const Table_seq_item *>(b)->value.d;
1.34      paf       816:        if(va<vb)
                    817:                return -1;
                    818:        else if(va>vb)
                    819:                return +1;
                    820:        else 
                    821:                return 0;
                    822: }
1.182     paf       823: static void _sort(Request& r, MethodParams& params) {
                    824:        Value& key_maker=params.as_junction(0, "key-maker must be code");
1.61      paf       825: 
1.182     paf       826:        bool reverse=params.count()>1/*..[desc|asc|]*/?
                    827:                reverse=params.as_no_junction(1, "order must not be code").as_string()=="desc":
1.104     parser    828:                false; // default=asc
1.32      paf       829: 
1.182     paf       830:        Table& old_table=GET_SELF(r, VTable).table();
                    831:        Table& new_table=*new Table(old_table.columns());
1.34      paf       832: 
1.182     paf       833:        Table_seq_item* seq=new(PointerFreeGC) Table_seq_item[old_table.count()];
1.34      paf       834:        int i;
                    835: 
                    836:        // calculate key values
                    837:        bool key_values_are_strings=true;
1.182     paf       838:        int old_count=old_table.count();
                    839:        for(i=0; i<old_count; i++) {
1.101     parser    840:                old_table.set_current(i);
1.32      paf       841:                // calculate key value
1.182     paf       842:                seq[i].row=old_table[i];
                    843:                Value& value=r.process_to_value(key_maker).as_expr_result(true/*return string as-is*/);
1.34      paf       844:                if(i==0) // determining key values type by first one
                    845:                        key_values_are_strings=value.is_string();
                    846: 
                    847:                if(key_values_are_strings)
                    848:                        seq[i].value.c_str=value.as_string().cstr();
                    849:                else
                    850:                        seq[i].value.d=value.as_double();
1.32      paf       851:        }
                    852:        // sort keys
1.182     paf       853:        _qsort(seq, old_count, sizeof(Table_seq_item), 
1.34      paf       854:                key_values_are_strings?sort_cmp_string:sort_cmp_double);
1.32      paf       855: 
1.34      paf       856:        // reorder table as they require in 'seq'
1.182     paf       857:        for(i=0; i<old_count; i++)
                    858:                new_table+=Table::element_type(seq[reverse?old_count-1-i:i].row);
                    859: 
                    860:        delete[] seq;
1.32      paf       861: 
1.116     parser    862:        // replace any previous table value
1.182     paf       863:        GET_SELF(r, VTable).set_table(new_table);
1.32      paf       864: }
                    865: 
1.176     paf       866: #ifndef DOXYGEN
1.182     paf       867: struct Expression_is_true_info {
1.176     paf       868:        Request* r;
                    869:        Value* expression_code;
                    870: };
                    871: #endif
1.191     paf       872: static bool expression_is_true(Table&, Expression_is_true_info* info) {
                    873:        return info->r->process_to_value(*info->expression_code).as_bool();
1.176     paf       874: }
                    875: static bool _locate_expression(Table& table, Table::Action_options o,
1.182     paf       876:                               Request& r, MethodParams& params) {
                    877:        check_option_param(o.defined, params, 1,
1.176     paf       878:                "locate by expression only has parameters: expression and, maybe, options");
1.182     paf       879:        Value& expression_code=params.as_junction(0, "must be expression");
1.145     paf       880: 
1.182     paf       881:        Expression_is_true_info info={&r, &expression_code};
                    882:        return table.table_first_that(expression_is_true, &info, o);
1.145     paf       883: }
1.176     paf       884: static bool _locate_name_value(Table& table, Table::Action_options o,
1.191     paf       885:                               Request&, MethodParams& params) {
1.182     paf       886:        check_option_param(o.defined, params, 2,
1.176     paf       887:                "locate by locate by name has parameters: name, value and, maybe, options");
1.182     paf       888:        const String& name=params.as_string(0, "column name must be string");
                    889:        const String& value=params.as_string(1, "value must be string");
                    890:        return table.locate(name, value, o);
                    891: }
                    892: static void _locate(Request& r, MethodParams& params) {
                    893:        Table& table=GET_SELF(r, VTable).table();
1.72      paf       894: 
1.182     paf       895:        Table::Action_options o=get_action_options(r, params, table);
                    896: 
                    897:        bool result=params[0].get_junction()?
                    898:                _locate_expression(table, o, r, params) :
                    899:                _locate_name_value(table, o, r, params);
                    900:        r.write_no_lang(*new VBool(result));
1.145     paf       901: }
1.182     paf       902: 
                    903: 
1.191     paf       904: static void _flip(Request& r, MethodParams&) {
1.182     paf       905:        Table& old_table=GET_SELF(r, VTable).table();
1.184     paf       906:        Table& new_table=*new Table(0);
1.182     paf       907:        if(size_t old_count=old_table.count())
                    908:                if(size_t old_cols=old_table[0]->count()) 
                    909:                        for(size_t column=0; column<old_cols; column++) {
                    910:                                Table::element_type new_row(new ArrayString(old_count));
                    911:                                for(size_t i=0; i<old_count; i++) {
                    912:                                        Table::element_type old_row=old_table[i];
                    913:                                        *new_row+=column<old_row->count()?old_row->get(column):new String;
1.39      paf       914:                                }
1.182     paf       915:                                new_table+=new_row;
1.39      paf       916:                        }
                    917: 
1.182     paf       918:        r.write_no_lang(*new VTable(&new_table));
1.39      paf       919: }
                    920: 
1.182     paf       921: static void _append(Request& r, MethodParams& params) {
1.134     paf       922:        // data
1.182     paf       923:        Temp_lang temp_lang(r, String::L_PASS_APPENDED);
                    924:        const String& string=r.process_to_string(params.as_junction(0, "body must be code"));
1.41      paf       925: 
                    926:        // parse cells
1.182     paf       927:        Table::element_type row=new ArrayString;
                    928:        size_t pos_after=0;
                    929:        string.split(*row, pos_after, "\t", String::L_AS_IS);
1.41      paf       930: 
1.182     paf       931:        GET_SELF(r, VTable).table()+=row;
1.41      paf       932: }
                    933: 
1.182     paf       934: static void join_named_row(Table& src, Table* dest) {
                    935:        Table::columns_type dest_columns=dest->columns();
                    936:        size_t dest_columns_count=dest_columns->count();
                    937:        Table::element_type dest_row(new ArrayString(dest_columns_count));
                    938:        for(size_t dest_column=0; dest_column<dest_columns_count; dest_column++) {
                    939:                const String* src_item=src.item(*dest_columns->get(dest_column));
                    940:                *dest_row+=src_item?src_item:new String;
                    941:        }
                    942:        *dest+=dest_row;
                    943: }
                    944: static void join_nameless_row(Table& src, Table* dest) {
                    945:        *dest+=src[src.current()];
                    946: }
                    947: static void _join(Request& r, MethodParams& params) {
                    948:        Table* maybe_src=params.as_no_junction(0, "table ref must not be code").get_table();
1.42      paf       949:        if(!maybe_src)
1.146     paf       950:                throw Exception("parser.runtime", 
1.182     paf       951:                        0, 
1.42      paf       952:                        "source is not a table");
1.176     paf       953:        Table& src=*maybe_src;
                    954: 
1.182     paf       955:        Table::Action_options o=get_action_options(r, params, src);
                    956:        check_option_param(o.defined, params, 1,
1.176     paf       957:                "invalid extra parameter");
1.42      paf       958: 
1.182     paf       959:        Table& dest=GET_SELF(r, VTable).table();
1.42      paf       960:        if(&src == &dest)
1.146     paf       961:                throw Exception("parser.runtime", 
1.182     paf       962:                        0, 
1.42      paf       963:                        "source and destination are same table");
                    964: 
1.193     paf       965:        if(dest.columns()) // dest is named
1.182     paf       966:                src.table_for_each(join_named_row, &dest, o);
                    967:        else // dest is nameless
                    968:                src.table_for_each(join_nameless_row, &dest, o);
1.42      paf       969: }
                    970: 
1.94      parser    971: #ifndef DOXYGEN
1.169     paf       972: class Table_sql_event_handlers: public SQL_Driver_query_event_handlers {
1.182     paf       973:        ArrayString& columns;
1.218     paf       974:        int columns_count;
1.182     paf       975:        ArrayString* row;
1.94      parser    976: public:
1.182     paf       977:        Table* table;
                    978: public:
                    979:        Table_sql_event_handlers() :
                    980:                columns(*new ArrayString), row(0), table(0) {
1.94      parser    981:        }
                    982: 
1.182     paf       983:        bool add_column(SQL_Error& error, const char *str, size_t length) {
1.170     paf       984:                try {
1.182     paf       985:                        columns+=new String(str, length, true);
1.170     paf       986:                        return false;
                    987:                } catch(...) {
                    988:                        error=SQL_Error("exception occured in Table_sql_event_handlers::add_column");
                    989:                        return true;
                    990:                }
                    991:        }
                    992:        bool before_rows(SQL_Error& error) { 
                    993:                try {
1.182     paf       994:                        table=new Table(&columns);
1.218     paf       995:                        columns_count=columns.count();
1.170     paf       996:                        return false;
                    997:                } catch(...) {
                    998:                        error=SQL_Error("exception occured in Table_sql_event_handlers::before_rows");
                    999:                        return true;
                   1000:                }
                   1001:        }
                   1002:        bool add_row(SQL_Error& error) {
                   1003:                try {
1.218     paf      1004:                        *table+=row=new ArrayString(columns_count);
1.170     paf      1005:                        return false;
                   1006:                } catch(...) {
                   1007:                        error=SQL_Error("exception occured in Table_sql_event_handlers::add_row");
                   1008:                        return true;
                   1009:                }
                   1010:        }
1.182     paf      1011:        bool add_row_cell(SQL_Error& error, const char* str, size_t length) {
1.170     paf      1012:                try {
1.182     paf      1013:                        String& cell=*new String;
                   1014:                        if(length)
                   1015:                                cell.append_know_length(str, length, String::L_TAINTED);
                   1016:                        *row+=&cell;
1.170     paf      1017:                        return false;
                   1018:                } catch(...) {
                   1019:                        error=SQL_Error("exception occured in Table_sql_event_handlers::add_row_cell");
                   1020:                        return true;
                   1021:                }
1.94      parser   1022:        }
                   1023: };
                   1024: #endif
1.204     paf      1025: 
                   1026: static void marshal_bind(
                   1027:                                                 HashStringValue::key_type aname, 
                   1028:                                                 HashStringValue::value_type avalue,
                   1029:                                                 SQL_Driver::Placeholder** pptr) 
                   1030: {
                   1031:        SQL_Driver::Placeholder& ph=**pptr;
                   1032:        ph.name=aname.cstr();
1.205     paf      1033:        ph.value=avalue->as_string().cstr(String::L_UNSPECIFIED);
1.204     paf      1034:        ph.is_null=avalue->get_class()==void_class;
                   1035:        ph.were_updated=false;
                   1036: 
                   1037:        (*pptr)++;
                   1038: }
                   1039: 
                   1040: // not static, used elsewhere
                   1041: int marshal_binds(HashStringValue& hash, SQL_Driver::Placeholder*& placeholders) {
                   1042:        int hash_count=hash.count();
                   1043:        placeholders=new(UseGC) SQL_Driver::Placeholder[hash_count];
                   1044:        SQL_Driver::Placeholder* ptr=placeholders;
1.221     paf      1045:        hash.for_each<SQL_Driver::Placeholder**>(marshal_bind, &ptr);
1.204     paf      1046:        return hash_count;
                   1047: }
                   1048: 
                   1049: // not static, used elsewhere
                   1050: void unmarshal_bind_updates(HashStringValue& hash, int placeholder_count, SQL_Driver::Placeholder* placeholders) {
                   1051:        SQL_Driver::Placeholder* ph=placeholders;
                   1052:        for(int i=0; i<placeholder_count; i++, ph++)
                   1053:                if(ph->were_updated) {
                   1054:                        Value* value;
                   1055:                        if(ph->is_null)
                   1056:                                value=new VVoid();
                   1057:                        else
                   1058:                                if(ph->value)
                   1059:                                        value=new VString(*new String(ph->value, 0, true/*tainted*/));
                   1060:                                else
                   1061:                                        value=new VString(*new String());                                       
                   1062:                        hash.put(ph->name, value);
                   1063:                }
                   1064: }
                   1065: 
1.182     paf      1066: static void _sql(Request& r, MethodParams& params) {
                   1067:        Value& statement=params.as_junction(0, "statement must be code");
1.49      paf      1068: 
1.204     paf      1069:        HashStringValue* bind=0;
1.53      paf      1070:        ulong limit=0;
1.100     parser   1071:        ulong offset=0;
1.182     paf      1072:        if(params.count()>1) {
                   1073:                Value& voptions=params.as_no_junction(1, "options must be hash, not code");
1.212     paf      1074:                if(voptions.is_defined() && !voptions.is_string())
1.182     paf      1075:                        if(HashStringValue* options=voptions.get_hash()) {
1.164     paf      1076:                                int valid_options=0;
1.204     paf      1077:                                if(Value* vbind=options->get(sql_bind_name)) {
                   1078:                                        valid_options++;
                   1079:                                        bind=vbind->get_hash();
                   1080:                                }
1.182     paf      1081:                                if(Value* vlimit=options->get(sql_limit_name)) {
1.164     paf      1082:                                        valid_options++;
1.147     paf      1083:                                        limit=(ulong)r.process_to_value(*vlimit).as_double();
1.164     paf      1084:                                }
1.182     paf      1085:                                if(Value* voffset=options->get(sql_offset_name)) {
1.164     paf      1086:                                        valid_options++;
1.147     paf      1087:                                        offset=(ulong)r.process_to_value(*voffset).as_double();
1.164     paf      1088:                                }
1.182     paf      1089:                                if(valid_options!=options->count())
1.164     paf      1090:                                        throw Exception("parser.runtime",
1.182     paf      1091:                                                0,
1.164     paf      1092:                                                "called with invalid option");
1.109     parser   1093:                        } else
1.146     paf      1094:                                throw Exception("parser.runtime",
1.182     paf      1095:                                        0,
1.109     parser   1096:                                        "options must be hash");
1.49      paf      1097:        }
                   1098: 
1.204     paf      1099:        SQL_Driver::Placeholder* placeholders=0;
                   1100:        uint placeholders_count=0;
                   1101:        if(bind)
                   1102:                placeholders_count=marshal_binds(*bind, placeholders);
                   1103: 
1.182     paf      1104:        Temp_lang temp_lang(r, String::L_SQL);
                   1105:        const String&  statement_string=r.process_to_string(statement);
                   1106:        const char* statement_cstr=
                   1107:                statement_string.cstr(String::L_UNSPECIFIED, r.connection());
                   1108:        Table_sql_event_handlers handlers;
1.135     paf      1109: #ifdef RESOURCES_DEBUG
                   1110:        struct timeval mt[2];
                   1111:        //measure:before
                   1112:        gettimeofday(&mt[0],NULL);
                   1113: #endif 
1.182     paf      1114:        r.connection()->query(
1.203     paf      1115:                statement_cstr, 
1.208     paf      1116:                placeholders_count, placeholders,
1.203     paf      1117:                offset, limit, 
1.160     paf      1118:                handlers,
                   1119:                statement_string);
1.135     paf      1120:        
                   1121: #ifdef RESOURCES_DEBUG
                   1122:                //measure:after connect
                   1123:        gettimeofday(&mt[1],NULL);
                   1124:        
                   1125:        double t[2];
                   1126:        for(int i=0;i<2;i++)
                   1127:            t[i]=mt[i].tv_sec+mt[i].tv_usec/1000000.0;
                   1128:            
                   1129:        r.sql_request_time+=t[1]-t[0];
                   1130: #endif                         
1.204     paf      1131: 
                   1132:        if(bind)
                   1133:                unmarshal_bind_updates(*bind, placeholders_count, placeholders);
1.96      parser   1134: 
1.182     paf      1135:        Table& result=
                   1136:                handlers.table?*handlers.table: // query resulted in table? return it
                   1137:                *new Table(Table::columns_type(0)); // query returned no table, fake it
1.49      paf      1138: 
                   1139:        // replace any previous table value
1.182     paf      1140:        GET_SELF(r, VTable).set_table(result);
1.49      paf      1141: }
                   1142: 
1.182     paf      1143: static void _columns(Request& r, MethodParams&) {
1.88      parser   1144: 
1.182     paf      1145:        Table::columns_type result_columns(new ArrayString);
                   1146:        *result_columns+=new String("column");
                   1147:        Table& result_table=*new Table(result_columns);
1.88      parser   1148: 
1.182     paf      1149:        Table& source_table=GET_SELF(r, VTable).table();
                   1150:        if(Table::columns_type source_columns=source_table.columns()) {
                   1151:                for(Array_iterator<const String*> i(*source_columns); i.has_next(); ) {
                   1152:                        Table::element_type result_row(new ArrayString);
                   1153:                        *result_row+=i.next();
                   1154:                        result_table+=result_row;
1.88      parser   1155:                }
                   1156:        }
                   1157: 
1.182     paf      1158:        r.write_no_lang(*new VTable(&result_table));
1.88      parser   1159: }
                   1160: 
1.182     paf      1161: static void _select(Request& r, MethodParams& params) {
                   1162:        Value& vcondition=params.as_junction(0, "condition must be expression");
1.148     paf      1163: 
1.182     paf      1164:        Table& source_table=GET_SELF(r, VTable).table();
                   1165:        Table& result_table=*new Table(source_table.columns());
1.148     paf      1166: 
                   1167:        int saved_current=source_table.current();
1.182     paf      1168:        int size=source_table.count();
1.148     paf      1169:        for(int row=0; row<size; row++) {
                   1170:                source_table.set_current(row);
                   1171: 
1.150     paf      1172:                bool condition=r.process_to_value(vcondition, 
1.148     paf      1173:                                false/*don't intercept string*/).as_bool();
                   1174: 
                   1175:                if(condition) // ...condition is true=
1.182     paf      1176:                        result_table+=source_table[row]; // =green light to go to result
1.148     paf      1177:        }
                   1178:        source_table.set_current(saved_current);
                   1179: 
1.182     paf      1180:        r.write_no_lang(*new VTable(&result_table));
1.148     paf      1181: }
                   1182: 
1.66      paf      1183: // constructor
                   1184: 
1.182     paf      1185: MTable::MTable(): Methoded("table") {
1.142     paf      1186:        // ^table::create{data}
                   1187:        // ^table::create[nameless]{data}
                   1188:        // ^table::create[table]
                   1189:        add_native_method("create", Method::CT_DYNAMIC, _create, 1, 2);
                   1190:        // old name for compatibility with <= v 1.141 2002/01/25 11:33:45 paf
                   1191:        add_native_method("set", Method::CT_DYNAMIC, _create, 1, 2); 
1.2       paf      1192: 
1.142     paf      1193:        // ^table::load[file]  
                   1194:        // ^table::load[nameless;file]
1.168     paf      1195:        add_native_method("load", Method::CT_DYNAMIC, _load, 1, 3);
1.22      paf      1196: 
                   1197:        // ^table.save[file]  
                   1198:        // ^table.save[nameless;file]
1.188     paf      1199:        add_native_method("save", Method::CT_DYNAMIC, _save, 1, 3);
1.6       paf      1200: 
1.224   ! misha    1201:        // add_native_method("save_old", Method::CT_DYNAMIC, _save_old, 1, 3);
        !          1202: 
1.6       paf      1203:        // ^table.count[]
1.66      paf      1204:        add_native_method("count", Method::CT_DYNAMIC, _count, 0, 0);
1.6       paf      1205: 
                   1206:        // ^table.line[]
1.66      paf      1207:        add_native_method("line", Method::CT_DYNAMIC, _line, 0, 0);
1.6       paf      1208: 
1.10      paf      1209:        // ^table.offset[]  
1.133     paf      1210:        // ^table.offset(offset)
                   1211:        // ^table.offset[cur|set](offset)
                   1212:        add_native_method("offset", Method::CT_DYNAMIC, _offset, 0, 2);
1.7       paf      1213: 
1.10      paf      1214:        // ^table.menu{code}  
                   1215:        // ^table.menu{code}[delim]
1.66      paf      1216:        add_native_method("menu", Method::CT_DYNAMIC, _menu, 1, 2);
1.74      paf      1217: 
1.79      paf      1218:        // ^table:hash[key field name]
1.123     parser   1219:        // ^table:hash[key field name][value field name(s) string/table]
1.163     paf      1220:        add_native_method("hash", Method::CT_DYNAMIC, _hash, 1, 3);
1.32      paf      1221: 
1.102     parser   1222:        // ^table.sort{string-key-maker} ^table.sort{string-key-maker}[desc|asc]
                   1223:        // ^table.sort(numeric-key-maker) ^table.sort(numeric-key-maker)[desc|asc]
1.66      paf      1224:        add_native_method("sort", Method::CT_DYNAMIC, _sort, 1, 2);
1.8       paf      1225: 
1.36      paf      1226:        // ^table.locate[field;value]
1.176     paf      1227:        add_native_method("locate", Method::CT_DYNAMIC, _locate, 1, 3);
1.39      paf      1228: 
                   1229:        // ^table.flip[]
1.66      paf      1230:        add_native_method("flip", Method::CT_DYNAMIC, _flip, 0, 0);
1.41      paf      1231: 
                   1232:        // ^table.append{r{tab}e{tab}c{tab}o{tab}r{tab}d}
1.66      paf      1233:        add_native_method("append", Method::CT_DYNAMIC, _append, 1, 1);
1.42      paf      1234: 
1.157     paf      1235:        // ^table.join[table][$.limit(10) $.offset(1) $.offset[cur] ]
                   1236:        add_native_method("join", Method::CT_DYNAMIC, _join, 1, 2);
1.49      paf      1237: 
                   1238: 
1.100     parser   1239:        // ^table:sql[query]
                   1240:        // ^table:sql[query][$.limit(1) $.offset(2)]
                   1241:        add_native_method("sql", Method::CT_DYNAMIC, _sql, 1, 2);
1.88      parser   1242: 
                   1243:        // ^table:columns[]
                   1244:        add_native_method("columns", Method::CT_DYNAMIC, _columns, 0, 0);
1.148     paf      1245: 
                   1246:        // ^table.select(expression) = table
                   1247:        add_native_method("select", Method::CT_DYNAMIC, _select, 1, 1);
1.40      paf      1248: }

E-mail: