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

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.225   ! misha       8: static const char * const IDENT_TABLE_C="$Date: 2007/03/14 10:57:52 $";
1.224     misha       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++) {
1.225   ! misha     546:                                        if(separators.encloser) {
        !           547:                                                ost<<separators.encloser<<column<<separators.encloser;
        !           548:                                        } else {
1.224     misha     549:                                        ost<<column;
1.225   ! misha     550:                                        }
1.224     misha     551:                                        if(column<lsize-1){
                    552:                                                ost<<separators.column;
                    553:                                        }
                    554:                                }
                    555:                        else
                    556:                                ost<<"empty nameless table";
                    557:                }
                    558:                ost<<'\n';
                    559:        }
                    560: 
                    561:        // process data lines
                    562:        Array_iterator<ArrayString*> i(table);
                    563:        while(i.has_next()) {
                    564:                for(Array_iterator<const String*> c(*i.next()); c.has_next(); ) {
                    565:                        maybe_enclose( ost, *c.next(), separators.encloser );
                    566:                        if(c.has_next())
                    567:                                ost<<separators.column;
                    568:                }
                    569:                ost<<'\n';
                    570:        }
                    571: 
                    572:        // write
                    573:        {
                    574:                string data=ost.str();
                    575:                const char* data_cstr = data.c_str();
                    576: 
                    577:                file_write(r.absolute(file_name), data_cstr, data.length(), true /* as text */, do_append);
                    578:        }
                    579: }
                    580: 
1.182     paf       581: static void _count(Request& r, MethodParams&) {
                    582:        int result=GET_SELF(r, VTable).table().count();
                    583:        r.write_no_lang(*new VInt(result));
1.6       paf       584: }
                    585: 
1.182     paf       586: static void _line(Request& r, MethodParams&) {
                    587:        int result=1+GET_SELF(r, VTable).table().current();
                    588:        r.write_no_lang(*new VInt(result));
1.6       paf       589: }
                    590: 
1.182     paf       591: static void _offset(Request& r, MethodParams& params) {
                    592:        Table& table=GET_SELF(r, VTable).table();
                    593:        if(params.count()) {
1.133     paf       594:                bool absolute=false;
1.182     paf       595:                if(params.count()>1) {
                    596:                    const String&  whence=params.as_string(0, "whence must be string");
1.133     paf       597:                    if(whence=="cur")
1.134     paf       598:                                absolute=false;
1.133     paf       599:                    else if(whence=="set")
1.134     paf       600:                                absolute=true;
1.133     paf       601:                    else
1.146     paf       602:                                throw Exception("parser.runtime",
1.134     paf       603:                                        &whence,
                    604:                                        "is invalid whence, valid are 'cur' or 'set'");
1.157     paf       605:                }
1.133     paf       606:                
1.211     paf       607:                int offset=params.as_int(params.count()-1, "offset must be expression", r);
                    608:                table.offset(absolute, offset);
1.151     paf       609:        } else
1.182     paf       610:                r.write_no_lang(*new VInt(table.current()));
1.6       paf       611: }
                    612: 
1.182     paf       613: static void _menu(Request& r, MethodParams& params) {
1.221     paf       614:        Temp_hash_value<const String::Body, void*> 
                    615:                cycle_data_setter(r.classes_conf, cycle_data_name, /*any not null flag*/&r);
                    616: 
1.182     paf       617:        Value& body_code=params.as_junction(0, "body must be code");
1.7       paf       618:        
1.182     paf       619:        Value* delim_maybe_code=params.count()>1?&params[1]:0;
1.7       paf       620: 
1.182     paf       621:        Table& table=GET_SELF(r, VTable).table();
1.7       paf       622:        bool need_delim=false;
1.99      parser    623:        int saved_current=table.current();
1.182     paf       624:        int size=table.count();
1.99      parser    625:        for(int row=0; row<size; row++) {
1.22      paf       626:                table.set_current(row);
1.7       paf       627: 
1.161     paf       628:                StringOrValue sv_processed=r.process(body_code);
1.221     paf       629:                Request::Skip lskip=r.get_skip(); r.set_skip(Request::SKIP_NOTHING);
1.182     paf       630:                const String* s_processed=sv_processed.get_string();
                    631:                if(delim_maybe_code && s_processed && s_processed->length()) { // delimiter set and we have body
1.161     paf       632:                        if(need_delim) // need delim & iteration produced string?
1.150     paf       633:                                r.write_pass_lang(r.process(*delim_maybe_code));
1.7       paf       634:                        need_delim=true;
                    635:                }
1.161     paf       636:                r.write_pass_lang(sv_processed);
1.221     paf       637: 
                    638:                if(lskip==Request::SKIP_BREAK)
                    639:                        break;
1.7       paf       640:        }
1.99      parser    641:        table.set_current(saved_current);
1.7       paf       642: }
                    643: 
1.110     parser    644: #ifndef DOXYGEN
1.174     paf       645: enum Table2hash_distint { D_ILLEGAL, D_FIRST, D_TABLES };
1.74      paf       646: struct Row_info {
1.166     paf       647:        Request *r;
1.74      paf       648:        Table *table;
1.182     paf       649:        Value* key_code;
                    650:        size_t key_field;
                    651:        Array<int>* value_fields;
                    652:        HashStringValue* hash;
1.174     paf       653:        Table2hash_distint distinct;
1.182     paf       654:        size_t row;
1.74      paf       655: };
1.110     parser    656: #endif
1.182     paf       657: static void table_row_to_hash(Table::element_type row, Row_info *info) {
                    658:        const String* key;
                    659:        if(info->key_code) {
                    660:                info->table->set_current(info->row++); // change context row
                    661:                StringOrValue sv_processed=info->r->process(*info->key_code);
1.166     paf       662:                key=&sv_processed.as_string();
                    663:        } else
1.182     paf       664:                key=info->key_field<row->count()?row->get(info->key_field):0;
1.166     paf       665: 
                    666:        if(!key)
                    667:                return; // ignore rows without key [too-short-record_array if-indexed]
1.74      paf       668:                
1.182     paf       669:        switch(info->distinct) {
1.174     paf       670:        case D_ILLEGAL: case D_FIRST:
                    671:                {
1.182     paf       672:                        VHash* vhash=new VHash;
                    673:                        HashStringValue& hash=vhash->hash();
                    674:                        for(Array_iterator<int> i(*info->value_fields); i.has_next(); ) {
                    675:                                size_t value_field=i.next();
                    676:                                if(value_field<row->count())
1.174     paf       677:                                        hash.put(
1.182     paf       678:                                                *info->table->columns()->get(value_field), 
                    679:                                                new VString(*row->get(value_field)));
1.174     paf       680:                        }
                    681: 
1.182     paf       682:                        if(info->hash->put_dont_replace(*key, vhash)) // put. existed?
                    683:                                if(info->distinct==D_ILLEGAL)
1.174     paf       684:                                        throw Exception("parser.runtime",
                    685:                                                key,
                    686:                                                "duplicate key");
                    687:                }
                    688:                break;
                    689:        case D_TABLES:
                    690:                {
1.182     paf       691:                        VTable* vtable=(VTable*)info->hash->get(*key); // put. table existed?
1.174     paf       692:                        Table* table;
                    693:                        if(vtable) 
                    694:                                table=vtable->get_table();
                    695:                        else {
                    696:                                // no? creating table of same structure as source
1.179     paf       697:                                Table::Action_options table_options(0, 0);
1.182     paf       698:                                table=new Table(*info->table, table_options/*no rows, just structure*/);
                    699:                                info->hash->put(*key, new VTable(table));
1.174     paf       700:                        }
1.182     paf       701:                        *table+=row;
1.174     paf       702:                }
                    703:                break;
                    704:        default:
                    705:                throw Exception(0,
                    706:                        0,
1.182     paf       707:                        "invalid distinct code (#%d)", info->distinct);
1.74      paf       708:        }
                    709: }
1.182     paf       710: static void _hash(Request& r, MethodParams& params) {
                    711:        Table& self_table=GET_SELF(r, VTable).table();
                    712:        VHash& result=*new VHash;
                    713:        if(Table::columns_type columns=self_table.columns())
                    714:                if(columns->count()>0) {
1.174     paf       715:                        Table2hash_distint distinct=D_ILLEGAL;
1.182     paf       716:                        int param_index=params.count()-1;
1.166     paf       717:                        if(param_index>0) {
1.182     paf       718:                                if(HashStringValue* options=
                    719:                                        params.as_no_junction(param_index, "param must not be code").get_hash()) {
1.166     paf       720:                                        --param_index;
                    721:                                        int valid_options=0;
1.182     paf       722:                                        if(Value* vdistinct_code=options->get(sql_distinct_name)) {
1.166     paf       723:                                                valid_options++;
1.174     paf       724:                                                Value& vdistinct_value=r.process_to_value(*vdistinct_code);
                    725:                                                if(vdistinct_value.is_string()) {
                    726:                                                        const String& sdistinct=*vdistinct_value.get_string();
                    727:                                                        if(sdistinct=="tables")
                    728:                                                                distinct=D_TABLES;
                    729:                                                        else
                    730:                                                                throw Exception("parser.runtime",
                    731:                                                                        &sdistinct,
                    732:                                                                        "must be 'tables' or true/false");
                    733:                                                } else
                    734:                                                        distinct=vdistinct_value.as_bool()?D_FIRST:D_ILLEGAL;
1.166     paf       735:                                        }
1.182     paf       736:                                        if(valid_options!=options->count())
1.166     paf       737:                                                throw Exception("parser.runtime",
1.182     paf       738:                                                        0,
1.166     paf       739:                                                        "called with invalid option");
1.163     paf       740:                                }
                    741:                        }
                    742:                        if(param_index==2) // bad options param type
                    743:                                throw Exception("parser.runtime",
1.182     paf       744:                                        0,
1.163     paf       745:                                        "options must be hash");
                    746: 
1.182     paf       747:                        Array<int> value_fields;
1.163     paf       748:                        if(param_index>0) {
1.174     paf       749:                                if(distinct!=D_ILLEGAL && distinct!=D_FIRST)
                    750:                                        throw Exception("parser.runtime",
                    751:                                                0,
                    752:                                                "in distinct[tables] mode you may not specify value field(s)");
1.182     paf       753:                                Value& value_fields_param=params.as_no_junction(param_index, "value field(s) must not be code");
1.123     parser    754:                                if(value_fields_param.is_string()) {
1.182     paf       755:                                        value_fields+=self_table.column_name2index(
                    756:                                                *value_fields_param.get_string(), true);
                    757:                                } else if(Table* value_fields_table=value_fields_param.get_table()) {
                    758:                                        for(Array_iterator<Table::element_type> i(*value_fields_table); 
                    759:                                                i.has_next(); ) {
                    760:                                                const String& value_field_name
                    761:                                                        =*i.next()->get(0);
                    762:                                                value_fields
                    763:                                                        +=self_table.column_name2index(value_field_name, true);
1.123     parser    764:                                        }
                    765:                                } else
1.146     paf       766:                                        throw Exception("parser.runtime",
1.182     paf       767:                                                0,
1.197     paf       768:                                                "value field(s) must be string or table"
1.123     parser    769:                                        );
                    770:                        } else { // by all columns, including key
1.174     paf       771:                                if(!(distinct!=D_ILLEGAL && distinct!=D_FIRST))
1.182     paf       772:                                        for(size_t i=0; i<columns->count(); i++)
1.174     paf       773:                                                value_fields+=i;
1.74      paf       774:                        }
                    775: 
1.182     paf       776: 
                    777:                        {
                    778:                                Value* key_param=&params[0];
1.193     paf       779:                                Row_info info={
                    780:                                        &r,
                    781:                                        &self_table,
                    782:                                        /*key_code=*/key_param->get_junction()?key_param:0,
1.197     paf       783:                                        /*key_field=*/0/*filled below*/,
1.193     paf       784:                                        &value_fields,
                    785:                                        &result.hash(),
                    786:                                        distinct,
                    787:                                        /*row=*/0
                    788:                                };
1.195     paf       789:                                info.key_field=(info.key_code?-1
                    790:                                                :self_table.column_name2index(key_param->as_string(), true));
1.182     paf       791: 
                    792:                                int saved_current=self_table.current();
                    793:                                self_table.for_each(table_row_to_hash, &info);
                    794:                                self_table.set_current(saved_current);
1.207     paf       795: 
                    796:                                result.extract_default();
1.182     paf       797:                        }
1.74      paf       798:                }
1.97      parser    799:        r.write_no_lang(result);
1.74      paf       800: }
                    801: 
1.110     parser    802: #ifndef DOXYGEN
1.78      paf       803: struct Table_seq_item {
1.182     paf       804:        ArrayString* row;
1.34      paf       805:        union {
1.182     paf       806:                const char *c_str;
1.34      paf       807:                double d;
                    808:        } value;
1.32      paf       809: };
1.110     parser    810: #endif
1.34      paf       811: static int sort_cmp_string(const void *a, const void *b) {
                    812:        return strcmp(
1.78      paf       813:                static_cast<const Table_seq_item *>(a)->value.c_str, 
                    814:                static_cast<const Table_seq_item *>(b)->value.c_str
1.34      paf       815:        );
                    816: }
                    817: static int sort_cmp_double(const void *a, const void *b) {
1.78      paf       818:        double va=static_cast<const Table_seq_item *>(a)->value.d;
                    819:        double vb=static_cast<const Table_seq_item *>(b)->value.d;
1.34      paf       820:        if(va<vb)
                    821:                return -1;
                    822:        else if(va>vb)
                    823:                return +1;
                    824:        else 
                    825:                return 0;
                    826: }
1.182     paf       827: static void _sort(Request& r, MethodParams& params) {
                    828:        Value& key_maker=params.as_junction(0, "key-maker must be code");
1.61      paf       829: 
1.182     paf       830:        bool reverse=params.count()>1/*..[desc|asc|]*/?
                    831:                reverse=params.as_no_junction(1, "order must not be code").as_string()=="desc":
1.104     parser    832:                false; // default=asc
1.32      paf       833: 
1.182     paf       834:        Table& old_table=GET_SELF(r, VTable).table();
                    835:        Table& new_table=*new Table(old_table.columns());
1.34      paf       836: 
1.182     paf       837:        Table_seq_item* seq=new(PointerFreeGC) Table_seq_item[old_table.count()];
1.34      paf       838:        int i;
                    839: 
                    840:        // calculate key values
                    841:        bool key_values_are_strings=true;
1.182     paf       842:        int old_count=old_table.count();
                    843:        for(i=0; i<old_count; i++) {
1.101     parser    844:                old_table.set_current(i);
1.32      paf       845:                // calculate key value
1.182     paf       846:                seq[i].row=old_table[i];
                    847:                Value& value=r.process_to_value(key_maker).as_expr_result(true/*return string as-is*/);
1.34      paf       848:                if(i==0) // determining key values type by first one
                    849:                        key_values_are_strings=value.is_string();
                    850: 
                    851:                if(key_values_are_strings)
                    852:                        seq[i].value.c_str=value.as_string().cstr();
                    853:                else
                    854:                        seq[i].value.d=value.as_double();
1.32      paf       855:        }
                    856:        // sort keys
1.182     paf       857:        _qsort(seq, old_count, sizeof(Table_seq_item), 
1.34      paf       858:                key_values_are_strings?sort_cmp_string:sort_cmp_double);
1.32      paf       859: 
1.34      paf       860:        // reorder table as they require in 'seq'
1.182     paf       861:        for(i=0; i<old_count; i++)
                    862:                new_table+=Table::element_type(seq[reverse?old_count-1-i:i].row);
                    863: 
                    864:        delete[] seq;
1.32      paf       865: 
1.116     parser    866:        // replace any previous table value
1.182     paf       867:        GET_SELF(r, VTable).set_table(new_table);
1.32      paf       868: }
                    869: 
1.176     paf       870: #ifndef DOXYGEN
1.182     paf       871: struct Expression_is_true_info {
1.176     paf       872:        Request* r;
                    873:        Value* expression_code;
                    874: };
                    875: #endif
1.191     paf       876: static bool expression_is_true(Table&, Expression_is_true_info* info) {
                    877:        return info->r->process_to_value(*info->expression_code).as_bool();
1.176     paf       878: }
                    879: static bool _locate_expression(Table& table, Table::Action_options o,
1.182     paf       880:                               Request& r, MethodParams& params) {
                    881:        check_option_param(o.defined, params, 1,
1.176     paf       882:                "locate by expression only has parameters: expression and, maybe, options");
1.182     paf       883:        Value& expression_code=params.as_junction(0, "must be expression");
1.145     paf       884: 
1.182     paf       885:        Expression_is_true_info info={&r, &expression_code};
                    886:        return table.table_first_that(expression_is_true, &info, o);
1.145     paf       887: }
1.176     paf       888: static bool _locate_name_value(Table& table, Table::Action_options o,
1.191     paf       889:                               Request&, MethodParams& params) {
1.182     paf       890:        check_option_param(o.defined, params, 2,
1.176     paf       891:                "locate by locate by name has parameters: name, value and, maybe, options");
1.182     paf       892:        const String& name=params.as_string(0, "column name must be string");
                    893:        const String& value=params.as_string(1, "value must be string");
                    894:        return table.locate(name, value, o);
                    895: }
                    896: static void _locate(Request& r, MethodParams& params) {
                    897:        Table& table=GET_SELF(r, VTable).table();
1.72      paf       898: 
1.182     paf       899:        Table::Action_options o=get_action_options(r, params, table);
                    900: 
                    901:        bool result=params[0].get_junction()?
                    902:                _locate_expression(table, o, r, params) :
                    903:                _locate_name_value(table, o, r, params);
                    904:        r.write_no_lang(*new VBool(result));
1.145     paf       905: }
1.182     paf       906: 
                    907: 
1.191     paf       908: static void _flip(Request& r, MethodParams&) {
1.182     paf       909:        Table& old_table=GET_SELF(r, VTable).table();
1.184     paf       910:        Table& new_table=*new Table(0);
1.182     paf       911:        if(size_t old_count=old_table.count())
                    912:                if(size_t old_cols=old_table[0]->count()) 
                    913:                        for(size_t column=0; column<old_cols; column++) {
                    914:                                Table::element_type new_row(new ArrayString(old_count));
                    915:                                for(size_t i=0; i<old_count; i++) {
                    916:                                        Table::element_type old_row=old_table[i];
                    917:                                        *new_row+=column<old_row->count()?old_row->get(column):new String;
1.39      paf       918:                                }
1.182     paf       919:                                new_table+=new_row;
1.39      paf       920:                        }
                    921: 
1.182     paf       922:        r.write_no_lang(*new VTable(&new_table));
1.39      paf       923: }
                    924: 
1.182     paf       925: static void _append(Request& r, MethodParams& params) {
1.134     paf       926:        // data
1.182     paf       927:        Temp_lang temp_lang(r, String::L_PASS_APPENDED);
                    928:        const String& string=r.process_to_string(params.as_junction(0, "body must be code"));
1.41      paf       929: 
                    930:        // parse cells
1.182     paf       931:        Table::element_type row=new ArrayString;
                    932:        size_t pos_after=0;
                    933:        string.split(*row, pos_after, "\t", String::L_AS_IS);
1.41      paf       934: 
1.182     paf       935:        GET_SELF(r, VTable).table()+=row;
1.41      paf       936: }
                    937: 
1.182     paf       938: static void join_named_row(Table& src, Table* dest) {
                    939:        Table::columns_type dest_columns=dest->columns();
                    940:        size_t dest_columns_count=dest_columns->count();
                    941:        Table::element_type dest_row(new ArrayString(dest_columns_count));
                    942:        for(size_t dest_column=0; dest_column<dest_columns_count; dest_column++) {
                    943:                const String* src_item=src.item(*dest_columns->get(dest_column));
                    944:                *dest_row+=src_item?src_item:new String;
                    945:        }
                    946:        *dest+=dest_row;
                    947: }
                    948: static void join_nameless_row(Table& src, Table* dest) {
                    949:        *dest+=src[src.current()];
                    950: }
                    951: static void _join(Request& r, MethodParams& params) {
                    952:        Table* maybe_src=params.as_no_junction(0, "table ref must not be code").get_table();
1.42      paf       953:        if(!maybe_src)
1.146     paf       954:                throw Exception("parser.runtime", 
1.182     paf       955:                        0, 
1.42      paf       956:                        "source is not a table");
1.176     paf       957:        Table& src=*maybe_src;
                    958: 
1.182     paf       959:        Table::Action_options o=get_action_options(r, params, src);
                    960:        check_option_param(o.defined, params, 1,
1.176     paf       961:                "invalid extra parameter");
1.42      paf       962: 
1.182     paf       963:        Table& dest=GET_SELF(r, VTable).table();
1.42      paf       964:        if(&src == &dest)
1.146     paf       965:                throw Exception("parser.runtime", 
1.182     paf       966:                        0, 
1.42      paf       967:                        "source and destination are same table");
                    968: 
1.193     paf       969:        if(dest.columns()) // dest is named
1.182     paf       970:                src.table_for_each(join_named_row, &dest, o);
                    971:        else // dest is nameless
                    972:                src.table_for_each(join_nameless_row, &dest, o);
1.42      paf       973: }
                    974: 
1.94      parser    975: #ifndef DOXYGEN
1.169     paf       976: class Table_sql_event_handlers: public SQL_Driver_query_event_handlers {
1.182     paf       977:        ArrayString& columns;
1.218     paf       978:        int columns_count;
1.182     paf       979:        ArrayString* row;
1.94      parser    980: public:
1.182     paf       981:        Table* table;
                    982: public:
                    983:        Table_sql_event_handlers() :
                    984:                columns(*new ArrayString), row(0), table(0) {
1.94      parser    985:        }
                    986: 
1.182     paf       987:        bool add_column(SQL_Error& error, const char *str, size_t length) {
1.170     paf       988:                try {
1.182     paf       989:                        columns+=new String(str, length, true);
1.170     paf       990:                        return false;
                    991:                } catch(...) {
                    992:                        error=SQL_Error("exception occured in Table_sql_event_handlers::add_column");
                    993:                        return true;
                    994:                }
                    995:        }
                    996:        bool before_rows(SQL_Error& error) { 
                    997:                try {
1.182     paf       998:                        table=new Table(&columns);
1.218     paf       999:                        columns_count=columns.count();
1.170     paf      1000:                        return false;
                   1001:                } catch(...) {
                   1002:                        error=SQL_Error("exception occured in Table_sql_event_handlers::before_rows");
                   1003:                        return true;
                   1004:                }
                   1005:        }
                   1006:        bool add_row(SQL_Error& error) {
                   1007:                try {
1.218     paf      1008:                        *table+=row=new ArrayString(columns_count);
1.170     paf      1009:                        return false;
                   1010:                } catch(...) {
                   1011:                        error=SQL_Error("exception occured in Table_sql_event_handlers::add_row");
                   1012:                        return true;
                   1013:                }
                   1014:        }
1.182     paf      1015:        bool add_row_cell(SQL_Error& error, const char* str, size_t length) {
1.170     paf      1016:                try {
1.182     paf      1017:                        String& cell=*new String;
                   1018:                        if(length)
                   1019:                                cell.append_know_length(str, length, String::L_TAINTED);
                   1020:                        *row+=&cell;
1.170     paf      1021:                        return false;
                   1022:                } catch(...) {
                   1023:                        error=SQL_Error("exception occured in Table_sql_event_handlers::add_row_cell");
                   1024:                        return true;
                   1025:                }
1.94      parser   1026:        }
                   1027: };
                   1028: #endif
1.204     paf      1029: 
                   1030: static void marshal_bind(
                   1031:                                                 HashStringValue::key_type aname, 
                   1032:                                                 HashStringValue::value_type avalue,
                   1033:                                                 SQL_Driver::Placeholder** pptr) 
                   1034: {
                   1035:        SQL_Driver::Placeholder& ph=**pptr;
                   1036:        ph.name=aname.cstr();
1.205     paf      1037:        ph.value=avalue->as_string().cstr(String::L_UNSPECIFIED);
1.204     paf      1038:        ph.is_null=avalue->get_class()==void_class;
                   1039:        ph.were_updated=false;
                   1040: 
                   1041:        (*pptr)++;
                   1042: }
                   1043: 
                   1044: // not static, used elsewhere
                   1045: int marshal_binds(HashStringValue& hash, SQL_Driver::Placeholder*& placeholders) {
                   1046:        int hash_count=hash.count();
                   1047:        placeholders=new(UseGC) SQL_Driver::Placeholder[hash_count];
                   1048:        SQL_Driver::Placeholder* ptr=placeholders;
1.221     paf      1049:        hash.for_each<SQL_Driver::Placeholder**>(marshal_bind, &ptr);
1.204     paf      1050:        return hash_count;
                   1051: }
                   1052: 
                   1053: // not static, used elsewhere
                   1054: void unmarshal_bind_updates(HashStringValue& hash, int placeholder_count, SQL_Driver::Placeholder* placeholders) {
                   1055:        SQL_Driver::Placeholder* ph=placeholders;
                   1056:        for(int i=0; i<placeholder_count; i++, ph++)
                   1057:                if(ph->were_updated) {
                   1058:                        Value* value;
                   1059:                        if(ph->is_null)
                   1060:                                value=new VVoid();
                   1061:                        else
                   1062:                                if(ph->value)
                   1063:                                        value=new VString(*new String(ph->value, 0, true/*tainted*/));
                   1064:                                else
                   1065:                                        value=new VString(*new String());                                       
                   1066:                        hash.put(ph->name, value);
                   1067:                }
                   1068: }
                   1069: 
1.182     paf      1070: static void _sql(Request& r, MethodParams& params) {
                   1071:        Value& statement=params.as_junction(0, "statement must be code");
1.49      paf      1072: 
1.204     paf      1073:        HashStringValue* bind=0;
1.53      paf      1074:        ulong limit=0;
1.100     parser   1075:        ulong offset=0;
1.182     paf      1076:        if(params.count()>1) {
                   1077:                Value& voptions=params.as_no_junction(1, "options must be hash, not code");
1.212     paf      1078:                if(voptions.is_defined() && !voptions.is_string())
1.182     paf      1079:                        if(HashStringValue* options=voptions.get_hash()) {
1.164     paf      1080:                                int valid_options=0;
1.204     paf      1081:                                if(Value* vbind=options->get(sql_bind_name)) {
                   1082:                                        valid_options++;
                   1083:                                        bind=vbind->get_hash();
                   1084:                                }
1.182     paf      1085:                                if(Value* vlimit=options->get(sql_limit_name)) {
1.164     paf      1086:                                        valid_options++;
1.147     paf      1087:                                        limit=(ulong)r.process_to_value(*vlimit).as_double();
1.164     paf      1088:                                }
1.182     paf      1089:                                if(Value* voffset=options->get(sql_offset_name)) {
1.164     paf      1090:                                        valid_options++;
1.147     paf      1091:                                        offset=(ulong)r.process_to_value(*voffset).as_double();
1.164     paf      1092:                                }
1.182     paf      1093:                                if(valid_options!=options->count())
1.164     paf      1094:                                        throw Exception("parser.runtime",
1.182     paf      1095:                                                0,
1.164     paf      1096:                                                "called with invalid option");
1.109     parser   1097:                        } else
1.146     paf      1098:                                throw Exception("parser.runtime",
1.182     paf      1099:                                        0,
1.109     parser   1100:                                        "options must be hash");
1.49      paf      1101:        }
                   1102: 
1.204     paf      1103:        SQL_Driver::Placeholder* placeholders=0;
                   1104:        uint placeholders_count=0;
                   1105:        if(bind)
                   1106:                placeholders_count=marshal_binds(*bind, placeholders);
                   1107: 
1.182     paf      1108:        Temp_lang temp_lang(r, String::L_SQL);
                   1109:        const String&  statement_string=r.process_to_string(statement);
                   1110:        const char* statement_cstr=
                   1111:                statement_string.cstr(String::L_UNSPECIFIED, r.connection());
                   1112:        Table_sql_event_handlers handlers;
1.135     paf      1113: #ifdef RESOURCES_DEBUG
                   1114:        struct timeval mt[2];
                   1115:        //measure:before
                   1116:        gettimeofday(&mt[0],NULL);
                   1117: #endif 
1.182     paf      1118:        r.connection()->query(
1.203     paf      1119:                statement_cstr, 
1.208     paf      1120:                placeholders_count, placeholders,
1.203     paf      1121:                offset, limit, 
1.160     paf      1122:                handlers,
                   1123:                statement_string);
1.135     paf      1124:        
                   1125: #ifdef RESOURCES_DEBUG
                   1126:                //measure:after connect
                   1127:        gettimeofday(&mt[1],NULL);
                   1128:        
                   1129:        double t[2];
                   1130:        for(int i=0;i<2;i++)
                   1131:            t[i]=mt[i].tv_sec+mt[i].tv_usec/1000000.0;
                   1132:            
                   1133:        r.sql_request_time+=t[1]-t[0];
                   1134: #endif                         
1.204     paf      1135: 
                   1136:        if(bind)
                   1137:                unmarshal_bind_updates(*bind, placeholders_count, placeholders);
1.96      parser   1138: 
1.182     paf      1139:        Table& result=
                   1140:                handlers.table?*handlers.table: // query resulted in table? return it
                   1141:                *new Table(Table::columns_type(0)); // query returned no table, fake it
1.49      paf      1142: 
                   1143:        // replace any previous table value
1.182     paf      1144:        GET_SELF(r, VTable).set_table(result);
1.49      paf      1145: }
                   1146: 
1.182     paf      1147: static void _columns(Request& r, MethodParams&) {
1.88      parser   1148: 
1.182     paf      1149:        Table::columns_type result_columns(new ArrayString);
                   1150:        *result_columns+=new String("column");
                   1151:        Table& result_table=*new Table(result_columns);
1.88      parser   1152: 
1.182     paf      1153:        Table& source_table=GET_SELF(r, VTable).table();
                   1154:        if(Table::columns_type source_columns=source_table.columns()) {
                   1155:                for(Array_iterator<const String*> i(*source_columns); i.has_next(); ) {
                   1156:                        Table::element_type result_row(new ArrayString);
                   1157:                        *result_row+=i.next();
                   1158:                        result_table+=result_row;
1.88      parser   1159:                }
                   1160:        }
                   1161: 
1.182     paf      1162:        r.write_no_lang(*new VTable(&result_table));
1.88      parser   1163: }
                   1164: 
1.182     paf      1165: static void _select(Request& r, MethodParams& params) {
                   1166:        Value& vcondition=params.as_junction(0, "condition must be expression");
1.148     paf      1167: 
1.182     paf      1168:        Table& source_table=GET_SELF(r, VTable).table();
                   1169:        Table& result_table=*new Table(source_table.columns());
1.148     paf      1170: 
                   1171:        int saved_current=source_table.current();
1.182     paf      1172:        int size=source_table.count();
1.148     paf      1173:        for(int row=0; row<size; row++) {
                   1174:                source_table.set_current(row);
                   1175: 
1.150     paf      1176:                bool condition=r.process_to_value(vcondition, 
1.148     paf      1177:                                false/*don't intercept string*/).as_bool();
                   1178: 
                   1179:                if(condition) // ...condition is true=
1.182     paf      1180:                        result_table+=source_table[row]; // =green light to go to result
1.148     paf      1181:        }
                   1182:        source_table.set_current(saved_current);
                   1183: 
1.182     paf      1184:        r.write_no_lang(*new VTable(&result_table));
1.148     paf      1185: }
                   1186: 
1.66      paf      1187: // constructor
                   1188: 
1.182     paf      1189: MTable::MTable(): Methoded("table") {
1.142     paf      1190:        // ^table::create{data}
                   1191:        // ^table::create[nameless]{data}
                   1192:        // ^table::create[table]
                   1193:        add_native_method("create", Method::CT_DYNAMIC, _create, 1, 2);
                   1194:        // old name for compatibility with <= v 1.141 2002/01/25 11:33:45 paf
                   1195:        add_native_method("set", Method::CT_DYNAMIC, _create, 1, 2); 
1.2       paf      1196: 
1.142     paf      1197:        // ^table::load[file]  
                   1198:        // ^table::load[nameless;file]
1.168     paf      1199:        add_native_method("load", Method::CT_DYNAMIC, _load, 1, 3);
1.22      paf      1200: 
                   1201:        // ^table.save[file]  
                   1202:        // ^table.save[nameless;file]
1.188     paf      1203:        add_native_method("save", Method::CT_DYNAMIC, _save, 1, 3);
1.6       paf      1204: 
1.224     misha    1205:        // add_native_method("save_old", Method::CT_DYNAMIC, _save_old, 1, 3);
                   1206: 
1.6       paf      1207:        // ^table.count[]
1.66      paf      1208:        add_native_method("count", Method::CT_DYNAMIC, _count, 0, 0);
1.6       paf      1209: 
                   1210:        // ^table.line[]
1.66      paf      1211:        add_native_method("line", Method::CT_DYNAMIC, _line, 0, 0);
1.6       paf      1212: 
1.10      paf      1213:        // ^table.offset[]  
1.133     paf      1214:        // ^table.offset(offset)
                   1215:        // ^table.offset[cur|set](offset)
                   1216:        add_native_method("offset", Method::CT_DYNAMIC, _offset, 0, 2);
1.7       paf      1217: 
1.10      paf      1218:        // ^table.menu{code}  
                   1219:        // ^table.menu{code}[delim]
1.66      paf      1220:        add_native_method("menu", Method::CT_DYNAMIC, _menu, 1, 2);
1.74      paf      1221: 
1.79      paf      1222:        // ^table:hash[key field name]
1.123     parser   1223:        // ^table:hash[key field name][value field name(s) string/table]
1.163     paf      1224:        add_native_method("hash", Method::CT_DYNAMIC, _hash, 1, 3);
1.32      paf      1225: 
1.102     parser   1226:        // ^table.sort{string-key-maker} ^table.sort{string-key-maker}[desc|asc]
                   1227:        // ^table.sort(numeric-key-maker) ^table.sort(numeric-key-maker)[desc|asc]
1.66      paf      1228:        add_native_method("sort", Method::CT_DYNAMIC, _sort, 1, 2);
1.8       paf      1229: 
1.36      paf      1230:        // ^table.locate[field;value]
1.176     paf      1231:        add_native_method("locate", Method::CT_DYNAMIC, _locate, 1, 3);
1.39      paf      1232: 
                   1233:        // ^table.flip[]
1.66      paf      1234:        add_native_method("flip", Method::CT_DYNAMIC, _flip, 0, 0);
1.41      paf      1235: 
                   1236:        // ^table.append{r{tab}e{tab}c{tab}o{tab}r{tab}d}
1.66      paf      1237:        add_native_method("append", Method::CT_DYNAMIC, _append, 1, 1);
1.42      paf      1238: 
1.157     paf      1239:        // ^table.join[table][$.limit(10) $.offset(1) $.offset[cur] ]
                   1240:        add_native_method("join", Method::CT_DYNAMIC, _join, 1, 2);
1.49      paf      1241: 
                   1242: 
1.100     parser   1243:        // ^table:sql[query]
                   1244:        // ^table:sql[query][$.limit(1) $.offset(2)]
                   1245:        add_native_method("sql", Method::CT_DYNAMIC, _sql, 1, 2);
1.88      parser   1246: 
                   1247:        // ^table:columns[]
                   1248:        add_native_method("columns", Method::CT_DYNAMIC, _columns, 0, 0);
1.148     paf      1249: 
                   1250:        // ^table.select(expression) = table
                   1251:        add_native_method("select", Method::CT_DYNAMIC, _select, 1, 1);
1.40      paf      1252: }

E-mail: