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

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

E-mail: