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

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

E-mail: