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

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

E-mail: