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

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

E-mail: