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

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.280   ! misha       8: static const char * const IDENT_TABLE_C="$Date: 2010-11-26 06:40:01 $";
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;
                    474:        if(param_index<params.count()) {
1.222     paf       475:                Value& voptions=params.as_no_junction(param_index++, "additional params must be hash");
                    476:                if( voptions.is_defined() && !voptions.is_string() ) {
                    477:                        if(HashStringValue* options=voptions.get_hash()) {
1.223     paf       478:                                int valid_options=separators.load(*options);
                    479:                                if(valid_options!=options->count())
1.272     misha     480:                                        throw Exception(PARSER_RUNTIME, 0, CALLED_WITH_INVALID_OPTION);
1.223     paf       481:                        } else {
1.226     misha     482:                                throw Exception(PARSER_RUNTIME,
1.188     paf       483:                                        0,
1.223     paf       484:                                        "additional params must be hash (did you spell mode parameter correctly?)");
                    485:                        }
1.222     paf       486:                }
1.188     paf       487:        }
                    488:        if(param_index<params.count())
1.226     misha     489:                throw Exception(PARSER_RUNTIME,
1.188     paf       490:                        0,
                    491:                        "bad mode (must be nameless or append)");
1.22      paf       492: 
1.182     paf       493:        Table& table=GET_SELF(r, VTable).table();
1.31      paf       494: 
1.257     misha     495: #if (!defined(NO_STRINGSTREAM) && !defined(FREEBSD4))
1.241     misha     496: 
1.269     misha     497:        pa_stringstream ost(std::stringstream::out);
1.257     misha     498: 
                    499:        // process header
1.188     paf       500:        if(output_column_names) {
1.31      paf       501:                if(table.columns()) { // named table
1.182     paf       502:                        for(Array_iterator<const String*> i(*table.columns()); i.has_next(); ) {
1.257     misha     503:                                maybe_enclose( ost, *i.next(), separators.encloser );
                    504:                                if(i.has_next()){
                    505:                                        ost<<separators.column;
                    506:                                }
1.31      paf       507:                        }
1.188     paf       508:                } else { // nameless table [we were asked to output column names]
1.182     paf       509:                        if(int lsize=table.count()?table[0]->count():0)
1.31      paf       510:                                for(int column=0; column<lsize; column++) {
1.257     misha     511:                                        if(separators.encloser) {
                    512:                                                ost<<separators.encloser<<column<<separators.encloser;
                    513:                                        } else {
                    514:                                                ost<<column;
                    515:                                        }
                    516:                                        if(column<lsize-1){
                    517:                                                ost<<separators.column;
                    518:                                        }
1.31      paf       519:                                }
                    520:                        else
1.257     misha     521:                                ost<<"empty nameless table";
1.31      paf       522:                }
1.257     misha     523:                ost<<'\n';
1.188     paf       524:        }
1.129     paf       525: 
1.257     misha     526:        // process data lines
1.182     paf       527:        Array_iterator<ArrayString*> i(table);
1.98      parser    528:        while(i.has_next()) {
1.182     paf       529:                for(Array_iterator<const String*> c(*i.next()); c.has_next(); ) {
1.257     misha     530:                        maybe_enclose( ost, *c.next(), separators.encloser );
1.98      parser    531:                        if(c.has_next())
1.257     misha     532:                                ost<<separators.column;
1.31      paf       533:                }
1.257     misha     534:                ost<<'\n';
1.31      paf       535:        }
                    536: 
                    537:        // write
1.217     paf       538:        {
1.269     misha     539:                pa_string data=ost.str();
1.257     misha     540:                const char* data_cstr=data.c_str();
                    541: 
1.267     misha     542:                file_write(r.charsets, file_spec, data_cstr, data.length(), true /* as text */, do_append);
1.217     paf       543:        }
1.22      paf       544: 
1.241     misha     545: #else
1.240     misha     546: 
1.257     misha     547:        String sdata;
1.224     misha     548:        if(output_column_names) {
                    549:                if(table.columns()) { // named table
                    550:                        for(Array_iterator<const String*> i(*table.columns()); i.has_next(); ) {
1.257     misha     551:                                maybe_enclose( sdata, *i.next(), separators.encloser, separators.sencloser );
                    552:                                if(i.has_next())
                    553:                                        sdata<<*separators.scolumn;
1.224     misha     554:                        }
                    555:                } else { // nameless table [we were asked to output column names]
                    556:                        if(int lsize=table.count()?table[0]->count():0)
                    557:                                for(int column=0; column<lsize; column++) {
1.257     misha     558:                                        char *cindex_tab=new(PointerFreeGC) char[MAX_NUMBER];
                    559:                                        sdata.append_know_length(cindex_tab, 
                    560:                                                snprintf(cindex_tab, MAX_NUMBER, 
                    561:                                                        column<lsize-1?"%d%c":"%d", column, separators.column),
                    562:                                                        String::L_CLEAN);
1.224     misha     563:                                }
                    564:                        else
1.257     misha     565:                                sdata.append_help_length("empty nameless table", 0, String::L_CLEAN);
1.224     misha     566:                }
1.257     misha     567:                sdata.append_know_length("\n", 1, String::L_CLEAN);
1.224     misha     568:        }
                    569: 
1.257     misha     570:        // data lines
1.224     misha     571:        Array_iterator<ArrayString*> i(table);
                    572:        while(i.has_next()) {
                    573:                for(Array_iterator<const String*> c(*i.next()); c.has_next(); ) {
1.257     misha     574:                        maybe_enclose( sdata, *c.next(), separators.encloser, separators.sencloser );
1.224     misha     575:                        if(c.has_next())
1.257     misha     576:                                sdata<<*separators.scolumn;
1.224     misha     577:                }
1.257     misha     578:                sdata.append_know_length("\n", 1, String::L_CLEAN);
1.224     misha     579:        }
                    580: 
                    581:        // write
                    582:        {
1.257     misha     583:                const char* data_cstr=sdata.cstr();
1.267     misha     584:                file_write(r.charsets, file_spec, data_cstr, sdata.length(), true, do_append);
1.257     misha     585:                if(*data_cstr) // not empty (when empty it's not heap memory)
                    586:                        pa_free((void*)data_cstr); // not needed anymore
1.224     misha     587:        }
1.240     misha     588: 
1.257     misha     589: #endif // don't use stringstream
1.224     misha     590: }
                    591: 
1.280   ! misha     592: static void _count(Request& r, MethodParams& params) {
        !           593:        Table& table=GET_SELF(r, VTable).table();
        !           594:        size_t result=0;
        !           595:        if(params.count()) {
        !           596:                const String& param=params.as_string(0, PARAMETER_MUST_BE_STRING);
        !           597:                if(param == "columns")
        !           598:                        result = table.columns() ? table.columns()->count() : 0;
        !           599:                else if(param == "cells")
        !           600:                        result = table.count() ? table[table.current()]->count() : 0;
        !           601:                else if(param == "rows") // synonim for ^table.count[]
        !           602:                        result = table.count();
        !           603:                else
        !           604:                        throw Exception(PARSER_RUNTIME, &param, "parameter must be 'columns', 'cells' and 'rows' only");
        !           605:        } else
        !           606:                result = table.count();
        !           607: 
1.182     paf       608:        r.write_no_lang(*new VInt(result));
1.6       paf       609: }
                    610: 
1.182     paf       611: static void _line(Request& r, MethodParams&) {
                    612:        int result=1+GET_SELF(r, VTable).table().current();
                    613:        r.write_no_lang(*new VInt(result));
1.6       paf       614: }
                    615: 
1.182     paf       616: static void _offset(Request& r, MethodParams& params) {
                    617:        Table& table=GET_SELF(r, VTable).table();
                    618:        if(params.count()) {
1.133     paf       619:                bool absolute=false;
1.182     paf       620:                if(params.count()>1) {
                    621:                    const String&  whence=params.as_string(0, "whence must be string");
1.133     paf       622:                    if(whence=="cur")
1.134     paf       623:                                absolute=false;
1.133     paf       624:                    else if(whence=="set")
1.134     paf       625:                                absolute=true;
1.133     paf       626:                    else
1.226     misha     627:                                throw Exception(PARSER_RUNTIME,
1.134     paf       628:                                        &whence,
                    629:                                        "is invalid whence, valid are 'cur' or 'set'");
1.157     paf       630:                }
1.133     paf       631:                
1.211     paf       632:                int offset=params.as_int(params.count()-1, "offset must be expression", r);
                    633:                table.offset(absolute, offset);
1.151     paf       634:        } else
1.182     paf       635:                r.write_no_lang(*new VInt(table.current()));
1.6       paf       636: }
                    637: 
1.182     paf       638: static void _menu(Request& r, MethodParams& params) {
1.263     misha     639:        InCycle temp(r);
1.221     paf       640: 
1.182     paf       641:        Value& body_code=params.as_junction(0, "body must be code");
1.7       paf       642:        
1.182     paf       643:        Value* delim_maybe_code=params.count()>1?&params[1]:0;
1.7       paf       644: 
1.182     paf       645:        Table& table=GET_SELF(r, VTable).table();
1.99      parser    646:        int saved_current=table.current();
1.182     paf       647:        int size=table.count();
1.7       paf       648: 
1.251     misha     649:        if(delim_maybe_code) { // delimiter set
1.250     misha     650:                bool need_delim=false;
                    651:                for(int row=0; row<size; row++) {
                    652:                        table.set_current(row);
                    653: 
                    654:                        StringOrValue sv_processed=r.process(body_code);
                    655:                        Request::Skip lskip=r.get_skip(); r.set_skip(Request::SKIP_NOTHING);
                    656: 
                    657:                        const String* s_processed=sv_processed.get_string();
1.251     misha     658:                        if(s_processed && !s_processed->is_empty()) { // we have body
1.250     misha     659:                                if(need_delim) // need delim & iteration produced string?
                    660:                                        r.write_pass_lang(r.process(*delim_maybe_code));
                    661:                                else
                    662:                                        need_delim=true;
                    663:                        }
                    664: 
                    665:                        r.write_pass_lang(sv_processed);
1.242     misha     666: 
1.250     misha     667:                        if(lskip==Request::SKIP_BREAK)
                    668:                                break;
                    669:                }
                    670:        } else {
                    671:                for(int row=0; row<size; row++) {
                    672:                        table.set_current(row);
                    673:  
                    674:                        r.process_write(body_code);
                    675:                        Request::Skip lskip=r.get_skip(); r.set_skip(Request::SKIP_NOTHING);
                    676:  
                    677:                        if(lskip==Request::SKIP_BREAK)
                    678:                                break;
1.7       paf       679:                }
                    680:        }
1.99      parser    681:        table.set_current(saved_current);
1.7       paf       682: }
                    683: 
1.110     parser    684: #ifndef DOXYGEN
1.74      paf       685: struct Row_info {
1.166     paf       686:        Request *r;
1.74      paf       687:        Table *table;
1.182     paf       688:        Value* key_code;
                    689:        size_t key_field;
                    690:        Array<int>* value_fields;
                    691:        HashStringValue* hash;
1.174     paf       692:        Table2hash_distint distinct;
1.182     paf       693:        size_t row;
1.227     misha     694:        Table2hash_value_type value_type;
1.74      paf       695: };
1.110     parser    696: #endif
1.182     paf       697: static void table_row_to_hash(Table::element_type row, Row_info *info) {
                    698:        const String* key;
                    699:        if(info->key_code) {
                    700:                info->table->set_current(info->row++); // change context row
                    701:                StringOrValue sv_processed=info->r->process(*info->key_code);
1.166     paf       702:                key=&sv_processed.as_string();
1.227     misha     703:        } else {
1.182     paf       704:                key=info->key_field<row->count()?row->get(info->key_field):0;
1.227     misha     705:        }
1.166     paf       706: 
                    707:        if(!key)
                    708:                return; // ignore rows without key [too-short-record_array if-indexed]
1.74      paf       709:                
1.243     misha     710:        bool exist=false;
                    711:        switch(info->value_type) {
                    712:                case C_STRING: {
1.271     misha     713:                        size_t index=info->value_fields->get(0);
                    714:                        exist=info->hash->put_dont_replace(*key, (index < row->count()) ? new VString(*row->get(index)) : new VString());
1.243     misha     715:                        break;
1.227     misha     716:                }
1.243     misha     717:                case C_HASH: {
1.182     paf       718:                        VHash* vhash=new VHash;
                    719:                        HashStringValue& hash=vhash->hash();
                    720:                        for(Array_iterator<int> i(*info->value_fields); i.has_next(); ) {
                    721:                                size_t value_field=i.next();
                    722:                                if(value_field<row->count())
1.174     paf       723:                                        hash.put(
1.182     paf       724:                                                *info->table->columns()->get(value_field), 
                    725:                                                new VString(*row->get(value_field)));
1.174     paf       726:                        }
                    727: 
1.227     misha     728:                        exist=info->hash->put_dont_replace(*key, vhash);
1.243     misha     729:                        break;
1.174     paf       730:                }
1.243     misha     731:                case C_TABLE: {
                    732:                        VTable* vtable=(VTable*)info->hash->get(*key); // table exist?
1.174     paf       733:                        Table* table;
1.227     misha     734:                        if(vtable) {
1.243     misha     735:                                if(info->distinct==D_ILLEGAL) {
                    736:                                        exist=true;
                    737:                                        break;
                    738:                                }
1.174     paf       739:                                table=vtable->get_table();
1.227     misha     740:                        } else {
1.174     paf       741:                                // no? creating table of same structure as source
1.179     paf       742:                                Table::Action_options table_options(0, 0);
1.182     paf       743:                                table=new Table(*info->table, table_options/*no rows, just structure*/);
                    744:                                info->hash->put(*key, new VTable(table));
1.174     paf       745:                        }
1.182     paf       746:                        *table+=row;
1.243     misha     747:                        break;
1.174     paf       748:                }
1.74      paf       749:        }
1.227     misha     750:        if(exist && info->distinct==D_ILLEGAL)
                    751:                throw Exception(PARSER_RUNTIME,
                    752:                        key,
                    753:                        "duplicate key");
1.74      paf       754: }
1.235     misha     755: 
                    756: Table2hash_value_type get_value_type(Value& vvalue_type){
                    757:        if(vvalue_type.is_string()) {
                    758:                const String& svalue_type=*vvalue_type.get_string();
                    759:                if(svalue_type == "table"){
                    760:                        return C_TABLE;
                    761:                } else if (svalue_type == "string") {
                    762:                        return C_STRING;
                    763:                } else if (svalue_type == "hash") {
                    764:                        return C_HASH;
                    765:                } else {
                    766:                        throw Exception(PARSER_RUNTIME,
                    767:                                &svalue_type,
                    768:                                "must be 'hash', 'table' or 'string'");
                    769:                }
                    770:        } else {
                    771:                throw Exception(PARSER_RUNTIME,
                    772:                        0,
                    773:                        "'type' must be hash");
                    774:        }
                    775: }
                    776: 
1.182     paf       777: static void _hash(Request& r, MethodParams& params) {
                    778:        Table& self_table=GET_SELF(r, VTable).table();
                    779:        VHash& result=*new VHash;
1.238     misha     780:        if(Table::columns_type columns=self_table.columns()){
1.182     paf       781:                if(columns->count()>0) {
1.174     paf       782:                        Table2hash_distint distinct=D_ILLEGAL;
1.227     misha     783:                        Table2hash_value_type value_type=C_HASH;
1.182     paf       784:                        int param_index=params.count()-1;
1.166     paf       785:                        if(param_index>0) {
1.238     misha     786:                                if(HashStringValue* options=params.as_no_junction(param_index, PARAM_MUST_NOT_BE_CODE).get_hash()){ // options where specified
1.166     paf       787:                                        --param_index;
                    788:                                        int valid_options=0;
1.238     misha     789:                                        if(Value* vdistinct_code=options->get(sql_distinct_name)) { // $.distinct ?
1.166     paf       790:                                                valid_options++;
1.174     paf       791:                                                Value& vdistinct_value=r.process_to_value(*vdistinct_code);
                    792:                                                if(vdistinct_value.is_string()) {
                    793:                                                        const String& sdistinct=*vdistinct_value.get_string();
1.227     misha     794:                                                        if(sdistinct=="tables") {
                    795:                                                                value_type=C_TABLE;
                    796:                                                                distinct=D_FIRST;
1.238     misha     797:                                                        } else {
1.226     misha     798:                                                                throw Exception(PARSER_RUNTIME,
1.174     paf       799:                                                                        &sdistinct,
                    800:                                                                        "must be 'tables' or true/false");
1.238     misha     801:                                                        }
                    802:                                                } else {
1.174     paf       803:                                                        distinct=vdistinct_value.as_bool()?D_FIRST:D_ILLEGAL;
1.238     misha     804:                                                }
1.166     paf       805:                                        }
1.238     misha     806:                                        if(Value* vvalue_type_code=options->get(sql_value_type_name)) { // $.type ?
                    807:                                                if(value_type==C_TABLE) // $.distinct[tables] already was specified
1.227     misha     808:                                                        throw Exception(PARSER_RUNTIME,
                    809:                                                                0,
1.238     misha     810:                                                                "you can't specify $.distinct[tables] and $.type[] together");
                    811: 
                    812:                                                valid_options++;
                    813:                                                value_type=get_value_type(r.process_to_value(*vvalue_type_code));
                    814:                                        }
1.226     misha     815: 
1.182     paf       816:                                        if(valid_options!=options->count())
1.272     misha     817:                                                throw Exception(PARSER_RUNTIME, 0, CALLED_WITH_INVALID_OPTION);
1.163     paf       818:                                }
                    819:                        }
1.238     misha     820: 
                    821:                        if(param_index==2) // options was specified but not as hash
1.272     misha     822:                                throw Exception(PARSER_RUNTIME, 0, OPTIONS_MUST_BE_HASH);
1.163     paf       823: 
1.182     paf       824:                        Array<int> value_fields;
1.238     misha     825:                        if(param_index==0){ // list of columns wasn't specified
                    826:                                if(value_type==C_STRING) // $.type[string]
                    827:                                        throw Exception(PARSER_RUNTIME,
                    828:                                                0,
                    829:                                                "you must specify one value field with option $.type[string]");
                    830:                                
                    831:                                for(size_t i=0; i<columns->count(); i++) // by all columns, including key
                    832:                                        value_fields+=i;
                    833: 
                    834:                        } else { // list of columns was specified
1.227     misha     835:                                if(value_type==C_TABLE)
                    836:                                        throw Exception(PARSER_RUNTIME,
1.174     paf       837:                                                0,
1.238     misha     838:                                                "you can't specify value field(s) with option $.distinct[tables] or $.type[tables]");
                    839: 
1.182     paf       840:                                Value& value_fields_param=params.as_no_junction(param_index, "value field(s) must not be code");
1.238     misha     841:                                if(value_fields_param.is_string()) { // one column as string was specified
                    842:                                        value_fields+=self_table.column_name2index(*value_fields_param.get_string(), true);
                    843:                                } else if(Table* value_fields_table=value_fields_param.get_table()) { // list of columns were specified in table
                    844:                                        for(Array_iterator<Table::element_type> i(*value_fields_table); i.has_next(); ) {
                    845:                                                const String& value_field_name =*i.next()->get(0);
                    846:                                                value_fields +=self_table.column_name2index(value_field_name, true);
1.123     parser    847:                                        }
                    848:                                } else
1.226     misha     849:                                        throw Exception(PARSER_RUNTIME,
1.182     paf       850:                                                0,
1.226     misha     851:                                                "value field(s) must be string or table");
1.239     misha     852:                        }
1.74      paf       853: 
1.227     misha     854:                        if(value_type==C_STRING && value_fields.count()!=1)
                    855:                                throw Exception(PARSER_RUNTIME,
                    856:                                        0,
1.238     misha     857:                                        "you can specify only one value field with option $.type[string]");
1.182     paf       858: 
                    859:                        {
                    860:                                Value* key_param=&params[0];
1.193     paf       861:                                Row_info info={
                    862:                                        &r,
                    863:                                        &self_table,
                    864:                                        /*key_code=*/key_param->get_junction()?key_param:0,
1.197     paf       865:                                        /*key_field=*/0/*filled below*/,
1.193     paf       866:                                        &value_fields,
                    867:                                        &result.hash(),
                    868:                                        distinct,
1.227     misha     869:                                        /*row=*/0,
                    870:                                        value_type
1.193     paf       871:                                };
1.195     paf       872:                                info.key_field=(info.key_code?-1
                    873:                                                :self_table.column_name2index(key_param->as_string(), true));
1.182     paf       874: 
                    875:                                int saved_current=self_table.current();
                    876:                                self_table.for_each(table_row_to_hash, &info);
                    877:                                self_table.set_current(saved_current);
1.207     paf       878: 
                    879:                                result.extract_default();
1.182     paf       880:                        }
1.74      paf       881:                }
1.238     misha     882:        }
1.97      parser    883:        r.write_no_lang(result);
1.74      paf       884: }
                    885: 
1.110     parser    886: #ifndef DOXYGEN
1.78      paf       887: struct Table_seq_item {
1.182     paf       888:        ArrayString* row;
1.34      paf       889:        union {
1.182     paf       890:                const char *c_str;
1.34      paf       891:                double d;
                    892:        } value;
1.32      paf       893: };
1.110     parser    894: #endif
1.34      paf       895: static int sort_cmp_string(const void *a, const void *b) {
                    896:        return strcmp(
1.78      paf       897:                static_cast<const Table_seq_item *>(a)->value.c_str, 
                    898:                static_cast<const Table_seq_item *>(b)->value.c_str
1.34      paf       899:        );
                    900: }
                    901: static int sort_cmp_double(const void *a, const void *b) {
1.78      paf       902:        double va=static_cast<const Table_seq_item *>(a)->value.d;
                    903:        double vb=static_cast<const Table_seq_item *>(b)->value.d;
1.34      paf       904:        if(va<vb)
                    905:                return -1;
                    906:        else if(va>vb)
                    907:                return +1;
                    908:        else 
                    909:                return 0;
                    910: }
1.182     paf       911: static void _sort(Request& r, MethodParams& params) {
                    912:        Value& key_maker=params.as_junction(0, "key-maker must be code");
1.61      paf       913: 
1.182     paf       914:        bool reverse=params.count()>1/*..[desc|asc|]*/?
                    915:                reverse=params.as_no_junction(1, "order must not be code").as_string()=="desc":
1.104     parser    916:                false; // default=asc
1.32      paf       917: 
1.182     paf       918:        Table& old_table=GET_SELF(r, VTable).table();
                    919:        Table& new_table=*new Table(old_table.columns());
1.34      paf       920: 
1.182     paf       921:        Table_seq_item* seq=new(PointerFreeGC) Table_seq_item[old_table.count()];
1.34      paf       922:        int i;
                    923: 
                    924:        // calculate key values
                    925:        bool key_values_are_strings=true;
1.182     paf       926:        int old_count=old_table.count();
                    927:        for(i=0; i<old_count; i++) {
1.101     parser    928:                old_table.set_current(i);
1.32      paf       929:                // calculate key value
1.182     paf       930:                seq[i].row=old_table[i];
                    931:                Value& value=r.process_to_value(key_maker).as_expr_result(true/*return string as-is*/);
1.34      paf       932:                if(i==0) // determining key values type by first one
                    933:                        key_values_are_strings=value.is_string();
                    934: 
                    935:                if(key_values_are_strings)
                    936:                        seq[i].value.c_str=value.as_string().cstr();
                    937:                else
                    938:                        seq[i].value.d=value.as_double();
1.32      paf       939:        }
1.265     misha     940: 
                    941:        // @todo: handle this elsewhere
                    942:        if(r.charsets.source().NAME()=="KOI8-R" && key_values_are_strings) {
                    943:                for(i=0; i<old_count; i++)
                    944:                        if(*seq[i].value.c_str)
                    945:                                seq[i].value.c_str=Charset::transcode(seq[i].value.c_str, r.charsets.source(), UTF8_charset).cstr();
                    946:        }
                    947: 
1.266     misha     948:        // sort keys
1.182     paf       949:        _qsort(seq, old_count, sizeof(Table_seq_item), 
1.34      paf       950:                key_values_are_strings?sort_cmp_string:sort_cmp_double);
1.32      paf       951: 
1.34      paf       952:        // reorder table as they require in 'seq'
1.182     paf       953:        for(i=0; i<old_count; i++)
                    954:                new_table+=Table::element_type(seq[reverse?old_count-1-i:i].row);
                    955: 
                    956:        delete[] seq;
1.32      paf       957: 
1.116     parser    958:        // replace any previous table value
1.182     paf       959:        GET_SELF(r, VTable).set_table(new_table);
1.32      paf       960: }
                    961: 
1.176     paf       962: #ifndef DOXYGEN
1.182     paf       963: struct Expression_is_true_info {
1.176     paf       964:        Request* r;
                    965:        Value* expression_code;
                    966: };
                    967: #endif
1.275     misha     968: 
1.191     paf       969: static bool expression_is_true(Table&, Expression_is_true_info* info) {
                    970:        return info->r->process_to_value(*info->expression_code).as_bool();
1.176     paf       971: }
1.275     misha     972: 
                    973: static bool _locate_expression(Table& table, Request& r, MethodParams& params) {
1.182     paf       974:        Value& expression_code=params.as_junction(0, "must be expression");
1.275     misha     975:        const size_t options_index=1;
                    976:        Table::Action_options o=get_action_options(r, params, options_index, table);
                    977:        check_option_param(o.defined, params, options_index, "locate by expression only has parameters: expression and, maybe, options");
1.145     paf       978: 
1.182     paf       979:        Expression_is_true_info info={&r, &expression_code};
                    980:        return table.table_first_that(expression_is_true, &info, o);
1.145     paf       981: }
1.275     misha     982: 
                    983: static bool _locate_name_value(Table& table, Request& r, MethodParams& params) {
1.182     paf       984:        const String& name=params.as_string(0, "column name must be string");
1.232     misha     985:        const String& value=params.as_string(1, VALUE_MUST_BE_STRING);
1.275     misha     986:        const size_t options_index=2;
                    987:        Table::Action_options o=get_action_options(r, params, options_index, table);
                    988:        check_option_param(o.defined, params, options_index, "locate by name has parameters: name, value and, maybe, options");
                    989: 
1.182     paf       990:        return table.locate(name, value, o);
                    991: }
1.275     misha     992: 
1.182     paf       993: static void _locate(Request& r, MethodParams& params) {
                    994:        Table& table=GET_SELF(r, VTable).table();
1.72      paf       995: 
1.182     paf       996:        bool result=params[0].get_junction()?
1.275     misha     997:                _locate_expression(table, r, params) :
                    998:                _locate_name_value(table, r, params);
1.249     misha     999:        r.write_no_lang(VBool::get(result));
1.145     paf      1000: }
1.182     paf      1001: 
                   1002: 
1.191     paf      1003: static void _flip(Request& r, MethodParams&) {
1.182     paf      1004:        Table& old_table=GET_SELF(r, VTable).table();
1.184     paf      1005:        Table& new_table=*new Table(0);
1.182     paf      1006:        if(size_t old_count=old_table.count())
1.270     misha    1007:                if(size_t old_cols=old_table.columns()?old_table.columns()->count():old_table[0]->count()) 
1.182     paf      1008:                        for(size_t column=0; column<old_cols; column++) {
                   1009:                                Table::element_type new_row(new ArrayString(old_count));
                   1010:                                for(size_t i=0; i<old_count; i++) {
                   1011:                                        Table::element_type old_row=old_table[i];
                   1012:                                        *new_row+=column<old_row->count()?old_row->get(column):new String;
1.39      paf      1013:                                }
1.182     paf      1014:                                new_table+=new_row;
1.39      paf      1015:                        }
                   1016: 
1.182     paf      1017:        r.write_no_lang(*new VTable(&new_table));
1.39      paf      1018: }
                   1019: 
1.182     paf      1020: static void _append(Request& r, MethodParams& params) {
                   1021:        Temp_lang temp_lang(r, String::L_PASS_APPENDED);
1.266     misha    1022:        const String& string=r.process_to_string(params[0]);
1.41      paf      1023: 
                   1024:        // parse cells
1.182     paf      1025:        Table::element_type row=new ArrayString;
                   1026:        size_t pos_after=0;
                   1027:        string.split(*row, pos_after, "\t", String::L_AS_IS);
1.41      paf      1028: 
1.182     paf      1029:        GET_SELF(r, VTable).table()+=row;
1.41      paf      1030: }
                   1031: 
1.182     paf      1032: static void join_named_row(Table& src, Table* dest) {
                   1033:        Table::columns_type dest_columns=dest->columns();
                   1034:        size_t dest_columns_count=dest_columns->count();
                   1035:        Table::element_type dest_row(new ArrayString(dest_columns_count));
                   1036:        for(size_t dest_column=0; dest_column<dest_columns_count; dest_column++) {
                   1037:                const String* src_item=src.item(*dest_columns->get(dest_column));
                   1038:                *dest_row+=src_item?src_item:new String;
                   1039:        }
                   1040:        *dest+=dest_row;
                   1041: }
                   1042: static void join_nameless_row(Table& src, Table* dest) {
                   1043:        *dest+=src[src.current()];
                   1044: }
                   1045: static void _join(Request& r, MethodParams& params) {
                   1046:        Table* maybe_src=params.as_no_junction(0, "table ref must not be code").get_table();
1.42      paf      1047:        if(!maybe_src)
1.226     misha    1048:                throw Exception(PARSER_RUNTIME, 
1.182     paf      1049:                        0, 
1.42      paf      1050:                        "source is not a table");
1.176     paf      1051:        Table& src=*maybe_src;
                   1052: 
1.268     misha    1053:        Table::Action_options o=get_action_options(r, params, 1, src);
1.182     paf      1054:        check_option_param(o.defined, params, 1,
1.176     paf      1055:                "invalid extra parameter");
1.42      paf      1056: 
1.182     paf      1057:        Table& dest=GET_SELF(r, VTable).table();
1.42      paf      1058:        if(&src == &dest)
1.226     misha    1059:                throw Exception(PARSER_RUNTIME, 
1.182     paf      1060:                        0, 
1.42      paf      1061:                        "source and destination are same table");
                   1062: 
1.193     paf      1063:        if(dest.columns()) // dest is named
1.182     paf      1064:                src.table_for_each(join_named_row, &dest, o);
                   1065:        else // dest is nameless
                   1066:                src.table_for_each(join_nameless_row, &dest, o);
1.42      paf      1067: }
                   1068: 
1.94      parser   1069: #ifndef DOXYGEN
1.169     paf      1070: class Table_sql_event_handlers: public SQL_Driver_query_event_handlers {
1.182     paf      1071:        ArrayString& columns;
1.218     paf      1072:        int columns_count;
1.182     paf      1073:        ArrayString* row;
1.94      parser   1074: public:
1.182     paf      1075:        Table* table;
                   1076: public:
                   1077:        Table_sql_event_handlers() :
                   1078:                columns(*new ArrayString), row(0), table(0) {
1.94      parser   1079:        }
                   1080: 
1.279     misha    1081:        bool add_column(SQL_Error& error, const char *str, size_t ) {
1.170     paf      1082:                try {
1.274     moko     1083:                        columns+=new String(str, String::L_TAINTED /* no length as 0x00 can be inside */);
1.170     paf      1084:                        return false;
                   1085:                } catch(...) {
                   1086:                        error=SQL_Error("exception occured in Table_sql_event_handlers::add_column");
                   1087:                        return true;
                   1088:                }
                   1089:        }
                   1090:        bool before_rows(SQL_Error& error) { 
                   1091:                try {
1.182     paf      1092:                        table=new Table(&columns);
1.218     paf      1093:                        columns_count=columns.count();
1.170     paf      1094:                        return false;
                   1095:                } catch(...) {
                   1096:                        error=SQL_Error("exception occured in Table_sql_event_handlers::before_rows");
                   1097:                        return true;
                   1098:                }
                   1099:        }
                   1100:        bool add_row(SQL_Error& error) {
                   1101:                try {
1.218     paf      1102:                        *table+=row=new ArrayString(columns_count);
1.170     paf      1103:                        return false;
                   1104:                } catch(...) {
                   1105:                        error=SQL_Error("exception occured in Table_sql_event_handlers::add_row");
                   1106:                        return true;
                   1107:                }
                   1108:        }
1.279     misha    1109:        bool add_row_cell(SQL_Error& error, const char* str, size_t ) {
1.170     paf      1110:                try {
1.274     moko     1111:                        *row+=new String(str, String::L_TAINTED /* no length as 0x00 can be inside */);
1.170     paf      1112:                        return false;
                   1113:                } catch(...) {
                   1114:                        error=SQL_Error("exception occured in Table_sql_event_handlers::add_row_cell");
                   1115:                        return true;
                   1116:                }
1.94      parser   1117:        }
                   1118: };
                   1119: #endif
1.204     paf      1120: 
                   1121: static void marshal_bind(
                   1122:                                                 HashStringValue::key_type aname, 
                   1123:                                                 HashStringValue::value_type avalue,
                   1124:                                                 SQL_Driver::Placeholder** pptr) 
                   1125: {
                   1126:        SQL_Driver::Placeholder& ph=**pptr;
                   1127:        ph.name=aname.cstr();
1.261     misha    1128:        ph.value=avalue->as_string().untaint_cstr(String::L_AS_IS);
1.204     paf      1129:        ph.is_null=avalue->get_class()==void_class;
                   1130:        ph.were_updated=false;
                   1131: 
                   1132:        (*pptr)++;
                   1133: }
                   1134: 
                   1135: // not static, used elsewhere
                   1136: int marshal_binds(HashStringValue& hash, SQL_Driver::Placeholder*& placeholders) {
                   1137:        int hash_count=hash.count();
                   1138:        placeholders=new(UseGC) SQL_Driver::Placeholder[hash_count];
                   1139:        SQL_Driver::Placeholder* ptr=placeholders;
1.221     paf      1140:        hash.for_each<SQL_Driver::Placeholder**>(marshal_bind, &ptr);
1.204     paf      1141:        return hash_count;
                   1142: }
                   1143: 
                   1144: // not static, used elsewhere
                   1145: void unmarshal_bind_updates(HashStringValue& hash, int placeholder_count, SQL_Driver::Placeholder* placeholders) {
                   1146:        SQL_Driver::Placeholder* ph=placeholders;
                   1147:        for(int i=0; i<placeholder_count; i++, ph++)
                   1148:                if(ph->were_updated) {
                   1149:                        Value* value;
                   1150:                        if(ph->is_null)
1.248     misha    1151:                                value=VVoid::get();
1.204     paf      1152:                        else
1.256     misha    1153:                                value=new VString(*new String(ph->value, String::L_TAINTED));
1.204     paf      1154:                        hash.put(ph->name, value);
                   1155:                }
                   1156: }
                   1157: 
1.182     paf      1158: static void _sql(Request& r, MethodParams& params) {
                   1159:        Value& statement=params.as_junction(0, "statement must be code");
1.49      paf      1160: 
1.204     paf      1161:        HashStringValue* bind=0;
1.244     misha    1162:        ulong limit=SQL_NO_LIMIT;
1.100     parser   1163:        ulong offset=0;
1.182     paf      1164:        if(params.count()>1) {
                   1165:                Value& voptions=params.as_no_junction(1, "options must be hash, not code");
1.212     paf      1166:                if(voptions.is_defined() && !voptions.is_string())
1.182     paf      1167:                        if(HashStringValue* options=voptions.get_hash()) {
1.164     paf      1168:                                int valid_options=0;
1.204     paf      1169:                                if(Value* vbind=options->get(sql_bind_name)) {
                   1170:                                        valid_options++;
                   1171:                                        bind=vbind->get_hash();
                   1172:                                }
1.182     paf      1173:                                if(Value* vlimit=options->get(sql_limit_name)) {
1.245     misha    1174:                                        valid_options++;
                   1175:                                        limit=(ulong)r.process_to_value(*vlimit).as_double();
1.164     paf      1176:                                }
1.182     paf      1177:                                if(Value* voffset=options->get(sql_offset_name)) {
1.164     paf      1178:                                        valid_options++;
1.147     paf      1179:                                        offset=(ulong)r.process_to_value(*voffset).as_double();
1.164     paf      1180:                                }
1.182     paf      1181:                                if(valid_options!=options->count())
1.272     misha    1182:                                        throw Exception(PARSER_RUNTIME, 0, CALLED_WITH_INVALID_OPTION);
1.109     parser   1183:                        } else
1.272     misha    1184:                                throw Exception(PARSER_RUNTIME, 0, OPTIONS_MUST_BE_HASH);
1.49      paf      1185:        }
                   1186: 
1.204     paf      1187:        SQL_Driver::Placeholder* placeholders=0;
                   1188:        uint placeholders_count=0;
                   1189:        if(bind)
                   1190:                placeholders_count=marshal_binds(*bind, placeholders);
                   1191: 
1.182     paf      1192:        Temp_lang temp_lang(r, String::L_SQL);
                   1193:        const String&  statement_string=r.process_to_string(statement);
1.262     misha    1194:        const char* statement_cstr=statement_string.untaint_cstr(r.flang, r.connection());
1.260     misha    1195: 
1.182     paf      1196:        Table_sql_event_handlers handlers;
1.135     paf      1197: #ifdef RESOURCES_DEBUG
                   1198:        struct timeval mt[2];
                   1199:        //measure:before
                   1200:        gettimeofday(&mt[0],NULL);
                   1201: #endif 
1.182     paf      1202:        r.connection()->query(
1.203     paf      1203:                statement_cstr, 
1.208     paf      1204:                placeholders_count, placeholders,
1.203     paf      1205:                offset, limit, 
1.160     paf      1206:                handlers,
                   1207:                statement_string);
1.135     paf      1208:        
                   1209: #ifdef RESOURCES_DEBUG
                   1210:                //measure:after connect
                   1211:        gettimeofday(&mt[1],NULL);
                   1212:        
                   1213:        double t[2];
                   1214:        for(int i=0;i<2;i++)
                   1215:            t[i]=mt[i].tv_sec+mt[i].tv_usec/1000000.0;
                   1216:            
                   1217:        r.sql_request_time+=t[1]-t[0];
                   1218: #endif                         
1.204     paf      1219: 
                   1220:        if(bind)
                   1221:                unmarshal_bind_updates(*bind, placeholders_count, placeholders);
1.96      parser   1222: 
1.182     paf      1223:        Table& result=
                   1224:                handlers.table?*handlers.table: // query resulted in table? return it
                   1225:                *new Table(Table::columns_type(0)); // query returned no table, fake it
1.49      paf      1226: 
                   1227:        // replace any previous table value
1.182     paf      1228:        GET_SELF(r, VTable).set_table(result);
1.49      paf      1229: }
                   1230: 
1.233     misha    1231: static void _columns(Request& r, MethodParams& params) {
                   1232:        const String* column_column_name;
                   1233:        if(params.count()>0)
                   1234:                column_column_name=&params.as_string(0, COLUMN_NAME_MUST_BE_STRING);
                   1235:        else 
                   1236:                column_column_name=new String("column");
1.88      parser   1237: 
1.182     paf      1238:        Table::columns_type result_columns(new ArrayString);
1.233     misha    1239:        *result_columns+=column_column_name;
1.182     paf      1240:        Table& result_table=*new Table(result_columns);
1.88      parser   1241: 
1.182     paf      1242:        Table& source_table=GET_SELF(r, VTable).table();
                   1243:        if(Table::columns_type source_columns=source_table.columns()) {
                   1244:                for(Array_iterator<const String*> i(*source_columns); i.has_next(); ) {
                   1245:                        Table::element_type result_row(new ArrayString);
                   1246:                        *result_row+=i.next();
                   1247:                        result_table+=result_row;
1.88      parser   1248:                }
                   1249:        }
                   1250: 
1.182     paf      1251:        r.write_no_lang(*new VTable(&result_table));
1.88      parser   1252: }
                   1253: 
1.182     paf      1254: static void _select(Request& r, MethodParams& params) {
1.231     misha    1255:        Value& vcondition=params.as_expression(0, "condition must be number, bool or expression");
1.148     paf      1256: 
1.182     paf      1257:        Table& source_table=GET_SELF(r, VTable).table();
                   1258:        Table& result_table=*new Table(source_table.columns());
1.148     paf      1259: 
1.277     moko     1260:        int limit=source_table.count();
                   1261:        int offset = 0;
                   1262:        bool reverse = false;
1.278     moko     1263:        
1.277     moko     1264:        if(params.count()>1) {
                   1265:                Value& voptions=params.as_no_junction(1, "options must be hash, not code");
                   1266:                if(voptions.is_defined() && !voptions.is_string())
                   1267:                        if(HashStringValue* options=voptions.get_hash()) {
                   1268:                                int valid_options=0;
                   1269:                                if(Value* vlimit=options->get(sql_limit_name)) {
                   1270:                                        valid_options++;
                   1271:                                        limit=r.process_to_value(*vlimit).as_int();
                   1272:                                }
                   1273:                                if(Value* voffset=options->get(sql_offset_name)) {
                   1274:                                        valid_options++;
                   1275:                                        offset=r.process_to_value(*voffset).as_int();
                   1276:                                }
                   1277:                                if(Value* vreverse=options->get(table_reverse_name)) {
                   1278:                                        valid_options++;
                   1279:                                        reverse=r.process_to_value(*vreverse).as_bool();
                   1280:                                }
                   1281:                                if(valid_options!=options->count())
                   1282:                                        throw Exception(PARSER_RUNTIME,
                   1283:                                                0,
                   1284:                                                "called with invalid option");
                   1285:                        } else
                   1286:                                throw Exception(PARSER_RUNTIME,
                   1287:                                        0,
                   1288:                                        "options must be hash");
                   1289:        }
                   1290: 
1.148     paf      1291:        int saved_current=source_table.current();
1.182     paf      1292:        int size=source_table.count();
1.277     moko     1293:        int appended = 0;
                   1294: 
                   1295:        if(reverse){
                   1296:                for(int row=size-1; row >=0 && result_table.count() < limit; row--) {
1.278     moko     1297:                        source_table.set_current(row);
1.148     paf      1298: 
1.277     moko     1299:                        bool condition=r.process_to_value(vcondition, false/*don't intercept string*/).as_bool();
                   1300: 
                   1301:                        if(condition && ++appended > offset) // ...condition is true, adding to the result
1.278     moko     1302:                                result_table+=source_table[row];
                   1303:                }
1.277     moko     1304:        } else {
                   1305:                for(int row=0; row < size && result_table.count() < limit; row++) {
                   1306:                        source_table.set_current(row);
                   1307: 
                   1308:                        bool condition=r.process_to_value(vcondition, false/*don't intercept string*/).as_bool();
1.148     paf      1309: 
1.277     moko     1310:                        if(condition && ++appended > offset) // ...condition is true, adding to the result
1.278     moko     1311:                                result_table+=source_table[row];
1.277     moko     1312:                }
1.148     paf      1313:        }
                   1314:        source_table.set_current(saved_current);
                   1315: 
1.182     paf      1316:        r.write_no_lang(*new VTable(&result_table));
1.148     paf      1317: }
                   1318: 
1.66      paf      1319: // constructor
                   1320: 
1.182     paf      1321: MTable::MTable(): Methoded("table") {
1.142     paf      1322:        // ^table::create{data}
                   1323:        // ^table::create[nameless]{data}
                   1324:        // ^table::create[table]
1.236     misha    1325:        add_native_method("create", Method::CT_DYNAMIC, _create, 1, 3);
1.142     paf      1326:        // old name for compatibility with <= v 1.141 2002/01/25 11:33:45 paf
1.236     misha    1327:        add_native_method("set", Method::CT_DYNAMIC, _create, 1, 3); 
1.2       paf      1328: 
1.142     paf      1329:        // ^table::load[file]  
                   1330:        // ^table::load[nameless;file]
1.168     paf      1331:        add_native_method("load", Method::CT_DYNAMIC, _load, 1, 3);
1.22      paf      1332: 
                   1333:        // ^table.save[file]  
                   1334:        // ^table.save[nameless;file]
1.188     paf      1335:        add_native_method("save", Method::CT_DYNAMIC, _save, 1, 3);
1.6       paf      1336: 
1.224     misha    1337:        // add_native_method("save_old", Method::CT_DYNAMIC, _save_old, 1, 3);
                   1338: 
1.6       paf      1339:        // ^table.count[]
1.280   ! misha    1340:        // ^table.count[rows]
        !          1341:        // ^table.count[columns]
        !          1342:        // ^table.count[cells]
        !          1343:        add_native_method("count", Method::CT_DYNAMIC, _count, 0, 1);
1.6       paf      1344: 
                   1345:        // ^table.line[]
1.66      paf      1346:        add_native_method("line", Method::CT_DYNAMIC, _line, 0, 0);
1.6       paf      1347: 
1.10      paf      1348:        // ^table.offset[]  
1.133     paf      1349:        // ^table.offset(offset)
                   1350:        // ^table.offset[cur|set](offset)
                   1351:        add_native_method("offset", Method::CT_DYNAMIC, _offset, 0, 2);
1.7       paf      1352: 
1.10      paf      1353:        // ^table.menu{code}  
                   1354:        // ^table.menu{code}[delim]
1.66      paf      1355:        add_native_method("menu", Method::CT_DYNAMIC, _menu, 1, 2);
1.74      paf      1356: 
1.239     misha    1357:        // ^table.hash[key field name]
                   1358:        // ^table.hash[key field name][value field name(s) string/table]
1.163     paf      1359:        add_native_method("hash", Method::CT_DYNAMIC, _hash, 1, 3);
1.32      paf      1360: 
1.102     parser   1361:        // ^table.sort{string-key-maker} ^table.sort{string-key-maker}[desc|asc]
                   1362:        // ^table.sort(numeric-key-maker) ^table.sort(numeric-key-maker)[desc|asc]
1.66      paf      1363:        add_native_method("sort", Method::CT_DYNAMIC, _sort, 1, 2);
1.8       paf      1364: 
1.36      paf      1365:        // ^table.locate[field;value]
1.176     paf      1366:        add_native_method("locate", Method::CT_DYNAMIC, _locate, 1, 3);
1.39      paf      1367: 
                   1368:        // ^table.flip[]
1.66      paf      1369:        add_native_method("flip", Method::CT_DYNAMIC, _flip, 0, 0);
1.41      paf      1370: 
                   1371:        // ^table.append{r{tab}e{tab}c{tab}o{tab}r{tab}d}
1.66      paf      1372:        add_native_method("append", Method::CT_DYNAMIC, _append, 1, 1);
1.42      paf      1373: 
1.157     paf      1374:        // ^table.join[table][$.limit(10) $.offset(1) $.offset[cur] ]
                   1375:        add_native_method("join", Method::CT_DYNAMIC, _join, 1, 2);
1.49      paf      1376: 
                   1377: 
1.239     misha    1378:        // ^table::sql[query]
                   1379:        // ^table::sql[query][$.limit(1) $.offset(2)]
1.100     parser   1380:        add_native_method("sql", Method::CT_DYNAMIC, _sql, 1, 2);
1.88      parser   1381: 
1.239     misha    1382:        // ^table.columns[[column name]]
1.233     misha    1383:        add_native_method("columns", Method::CT_DYNAMIC, _columns, 0, 1);
1.148     paf      1384: 
                   1385:        // ^table.select(expression) = table
1.277     moko     1386:        add_native_method("select", Method::CT_DYNAMIC, _select, 1, 2);
1.40      paf      1387: }

E-mail: