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

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

E-mail: