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

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

E-mail: