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

1.20      paf         1: /** @file
1.47      paf         2:        Parser: @b table parser class.
1.20      paf         3: 
1.1       paf         4:        Copyright (c) 2001 ArtLebedev Group (http://www.artlebedev.com)
1.20      paf         5: 
1.1       paf         6:        Author: Alexander Petrosyan <paf@design.ru> (http://design.ru/paf)
                      7: */
1.103   ! parser      8: static const char *RCSId="$Id: table.C,v 1.102 2001/08/10 07:10:17 parser Exp $"; 
1.1       paf         9: 
1.24      paf        10: #include "pa_config_includes.h"
1.59      paf        11: 
                     12: #include "pcre.h"
                     13: 
1.68      paf        14: #include "classes.h"
1.16      paf        15: #include "pa_common.h"
1.1       paf        16: #include "pa_request.h"
                     17: #include "pa_vtable.h"
1.6       paf        18: #include "pa_vint.h"
1.51      paf        19: #include "pa_sql_connection.h"
1.58      paf        20: #include "pa_dir.h"
1.72      paf        21: #include "pa_vbool.h"
1.1       paf        22: 
1.66      paf        23: // defines
1.1       paf        24: 
1.66      paf        25: #define TABLE_CLASS_NAME "table"
                     26: 
                     27: // class
                     28: 
                     29: class MTable : public Methoded {
                     30: public: // VStateless_class
                     31:        Value *create_new_value(Pool& pool) { return new(pool) VTable(pool); }
                     32: 
                     33: public:
                     34:        MTable(Pool& pool);
1.70      paf        35: 
                     36: public: // Methoded
1.66      paf        37:        bool used_directly() { return true; }
                     38: };
1.1       paf        39: 
                     40: // methods
1.66      paf        41: 
1.61      paf        42: static void _set(Request& r, const String& method_name, MethodParams *params) {
1.1       paf        43:        Pool& pool=r.pool();
                     44:        // data is last parameter
1.90      parser     45:        Value& vdata=params->as_junction(params->size()-1, "body must be code");
1.44      paf        46: 
1.45      paf        47:        Temp_lang temp_lang(r, String::UL_PASS_APPENDED);
1.61      paf        48:        const String& data=r.process(vdata).as_string();
1.44      paf        49: 
                     50:        size_t pos_after=0;
                     51:        // parse columns
                     52:        Array *columns;
                     53:        if(params->size()==2) {
                     54:                columns=0;
1.21      paf        55:        } else {
1.44      paf        56:                columns=new(pool) Array(pool);
                     57: 
                     58:                Array head(pool);
                     59:                data.split(head, &pos_after, "\n", 1, String::UL_CLEAN, 1);
                     60:                if(head.size())
                     61:                        head.get_string(0)->split(*columns, 0, "\t", 1, String::UL_CLEAN);
                     62:        }
                     63: 
                     64:        Table& table=*new(pool) Table(pool, &method_name, columns);
                     65:        // parse cells
                     66:        Array rows(pool);
                     67:        data.split(rows, &pos_after, "\n", 1, String::UL_CLEAN);
1.98      parser     68:        Array_iter i(rows);
                     69:        while(i.has_next()) {
1.44      paf        70:                Array& row=*new(pool) Array(pool);
1.98      parser     71:                const String& string=*i.next_string();
1.44      paf        72:                // remove empty lines
                     73:                if(!string.size())
                     74:                        continue;
                     75: 
                     76:                string.split(row, 0, "\t", 1, String::UL_CLEAN);
                     77:                table+=&row;
1.17      paf        78:        }
1.1       paf        79: 
1.44      paf        80:        // replace any previous table value
                     81:        static_cast<VTable *>(r.self)->set_table(table);
                     82: }
                     83: 
1.61      paf        84: static void _load(Request& r, const String& method_name, MethodParams *params) {
1.44      paf        85:        Pool& pool=r.pool();
                     86:        // filename is last parameter
1.90      parser     87:        Value& vfilename=params->as_no_junction(params->size()-1, 
1.61      paf        88:                "file name must not be code");
1.44      paf        89: 
                     90:        // loading text
1.61      paf        91:        char *data=file_read_text(pool, r.absolute(vfilename.as_string()));
1.44      paf        92: 
1.1       paf        93:        // parse columns
                     94:        Array *columns;
                     95: #ifndef NO_STRING_ORIGIN
                     96:        const Origin& origin=method_name.origin();
1.2       paf        97:        const char *file=origin.file;
1.1       paf        98:        uint line=origin.line;
                     99: #endif
                    100:        if(params->size()==2) {
                    101:                columns=0;
                    102:        } else {
                    103:                columns=new(pool) Array(pool);
                    104: 
                    105:                if(char *row_chars=getrow(&data)) 
                    106:                        do {
                    107:                                String *name=new(pool) String(pool);
1.45      paf       108:                                name->APPEND_TAINTED(lsplit(&row_chars, '\t'), 0, file, line++);
1.1       paf       109:                                *columns+=name;
                    110:                        } while(row_chars);
                    111:        }
                    112: 
                    113:        // parse cells
1.27      paf       114:        Table& table=*new(pool) Table(pool, &method_name, columns);
1.1       paf       115:        char *row_chars;
                    116:        while(row_chars=getrow(&data)) {
1.28      paf       117:                if(!*row_chars) // remove empty lines
                    118:                        continue;
1.1       paf       119:                Array *row=new(pool) Array(pool);
                    120:                while(char *cell_chars=lsplit(&row_chars, '\t')) {
                    121:                        String *cell=new(pool) String(pool);
1.44      paf       122:                        cell->APPEND_TAINTED(cell_chars, 0, file, line);
1.1       paf       123:                        *row+=cell;
                    124:                }
                    125:                line++;
                    126:                table+=row;
                    127:        };
                    128: 
                    129:        // replace any previous table value
1.18      paf       130:        static_cast<VTable *>(r.self)->set_table(table);
1.1       paf       131: }
1.2       paf       132: 
1.91      parser    133: static Table *fill_month_days(Request& r, 
                    134:                                                          const String& method_name, MethodParams *params, bool rus){
                    135:        Pool& pool=r.pool();
                    136:        Table *result=new(pool) Table(pool, &method_name, 0/*&columns*/);
                    137: 
                    138:     int year=params->as_int(1, r);
                    139:     int month=max(1, min(params->as_int(2, r), 12)) -1;
                    140: 
                    141:     tm tmIn={0, 0, 0, 1, month, year-1900};
                    142:     time_t t=mktime(&tmIn);
                    143:        if(t<0)
                    144:                PTHROW(0, 0, 
                    145:                        &method_name, 
                    146:                        "invalid date");
                    147:     tm *tmOut=localtime(&t);
                    148: 
                    149:     int weekDay1=tmOut->tm_wday;
                    150:        if(rus) 
                    151:                weekDay1=weekDay1?weekDay1-1:6; //sunday last
                    152:     int monthDays=getMonthDays(year, month);
                    153:     
                    154:     for(int _day=1-weekDay1; _day<=monthDays;) {
                    155:                Array& row=*new(pool) Array(pool, 7);
                    156:        for(int wday=0; wday<7; wday++, _day++) {
1.93      parser    157:                String *cell=new(pool) String(pool);
1.91      parser    158:                        if(_day>=1 && _day<=monthDays) {
                    159:                                char *buf=(char *)malloc(2+1); 
1.93      parser    160:                                cell->APPEND_CLEAN(buf, sprintf(buf, "%02d", _day), 
                    161:                                        method_name.origin().file, method_name.origin().line);
                    162:             }
1.91      parser    163:                        row+=cell;            
                    164:         }
                    165:        *result+=&row;
                    166:     }
                    167:     
                    168:     return result;
                    169: }
                    170: 
                    171: static Table *fill_week_days(Request& r, 
                    172:                                                         const String& method_name, MethodParams *params, bool rus){
                    173:        Pool& pool=r.pool();
                    174:        Array& columns=*new(pool) Array(pool, 4);
                    175:        columns+=new(pool) String(pool, "year");
                    176:        columns+=new(pool) String(pool, "month");
                    177:        columns+=new(pool) String(pool, "day");
                    178:        columns+=new(pool) String(pool, "weekday");
                    179:        Table *result=new(pool) Table(pool, &method_name, &columns);
                    180: 
                    181:     int year=params->as_int(1, r);
                    182:     int month=max(1, min(params->as_int(2, r), 12)) -1;
                    183:     int day=params->as_int(3, r);
                    184:     
                    185:     tm tmIn={0, 0, 18, day, month, year-1900};
                    186:     time_t t=mktime(&tmIn);
                    187:        if(t<0)
                    188:                PTHROW(0, 0, 
                    189:                        &method_name, 
                    190:                        "invalid date");
                    191:     tm *tmOut=localtime(&t);
                    192:     
                    193:     int baseWeekDay=tmOut->tm_wday;
                    194:        if(rus) 
                    195:                baseWeekDay=baseWeekDay?baseWeekDay-1:6; //sunday last
                    196: 
                    197:     t-=baseWeekDay*SECS_PER_DAY;
                    198: 
                    199:     for(int curWeekDay=0; curWeekDay<7; curWeekDay++, t+=SECS_PER_DAY) {
                    200:         tm *tmOut=localtime(&t);
                    201:                Array& row=*new(pool) Array(pool, 4);
1.93      parser    202: #define WDFILL(size, value) { \
                    203:                char *buf=(char *)malloc(size+1); \
                    204:                String *cell=new(pool) String(pool); \
                    205:                cell->APPEND_CLEAN(buf, sprintf(buf, "%0"#size"d", value), \
                    206:                        method_name.origin().file, \
                    207:                        method_name.origin().line); \
                    208:                row+=cell; \
                    209:                }
                    210:                WDFILL(4, 1900+tmOut->tm_year);
                    211:                WDFILL(2, 1+tmOut->tm_mon);
                    212:                WDFILL(2, tmOut->tm_mday);
                    213:                WDFILL(2, tmOut->tm_wday);
1.91      parser    214:         *result+=&row;
                    215:     }
                    216:     
                    217:     return result;
                    218: }
                    219: 
                    220: static void _calendar(Request& r, const String& method_name, MethodParams *params) {
                    221:        Pool& pool=r.pool();
                    222: 
1.92      parser    223:        const String& what=params->as_string(0, "format must be strig");
1.91      parser    224:        bool rus=false;
1.92      parser    225:        if(what=="rus")
1.91      parser    226:                rus=true;
1.92      parser    227:        else if(what=="eng")
1.91      parser    228:                rus=false;
                    229:        else
                    230:                PTHROW(0, 0, 
                    231:                        &what, 
                    232:                        "must be rus|eng");
                    233: 
                    234:        Table *result=0;
                    235:        if(params->size()==1+2) 
                    236:                result=fill_month_days(r, method_name, params, rus);
                    237:        else // 1+3
                    238:                result=fill_week_days(r, method_name, params, rus);
                    239: 
                    240:        // replace any previous table value
                    241:        static_cast<VTable *>(r.self)->set_table(*result);
                    242: }
                    243: 
                    244: 
                    245: 
                    246: 
1.61      paf       247: static void _save(Request& r, const String& method_name, MethodParams *params) {
1.22      paf       248:        Pool& pool=r.pool();
1.90      parser    249:        Value& vtable_name=params->as_no_junction(params->size()-1, 
1.61      paf       250:                "file name must not be code");
1.22      paf       251: 
1.31      paf       252:        Table& table=static_cast<VTable *>(r.self)->table();
                    253: 
                    254:        String sdata(pool);
                    255:        if(params->size()==1) { // not nameless=named output
                    256:                // write out names line
                    257:                if(table.columns()) { // named table
1.98      parser    258:                        Array_iter i(*table.columns());
                    259:                        while(i.has_next()) {
                    260:                                sdata.append(*i.next_string(), //*static_cast<String *>(table.columns()->quick_get(column)), 
                    261:                                        String::UL_TABLE);
                    262:                                if(i.has_next())
1.31      paf       263:                                        sdata.APPEND_CONST("\t");
                    264:                        }
                    265:                } else { // nameless table
1.98      parser    266:                        if(int lsize=table.size()?static_cast<Array *>(table.get(0))->size():0)
1.31      paf       267:                                for(int column=0; column<lsize; column++) {
                    268:                                        char *cindex_tab=(char *)malloc(MAX_NUMBER);
                    269:                                        snprintf(cindex_tab, MAX_NUMBER, "%d\t", column);
                    270:                                        sdata.APPEND_CONST(cindex_tab);
                    271:                                }
                    272:                        else
                    273:                                sdata.APPEND_CONST("empty nameless table");
                    274:                }
                    275:                sdata.APPEND_CONST("\n");
                    276:        }
                    277:        // data lines
1.98      parser    278:        Array_iter i(table);
                    279:        while(i.has_next()) {
                    280:                Array_iter c(*static_cast<Array *>(i.next()));
                    281:                while(c.has_next()) {
                    282:                        sdata.append(*c.next_string(), //*static_cast<String *>(row->quick_get(column)), 
                    283:                                String::UL_TABLE);
                    284:                        if(c.has_next())
1.31      paf       285:                                sdata.APPEND_CONST("\t");
                    286:                }
                    287:                sdata.APPEND_CONST("\n");
                    288:        }
                    289: 
                    290:        // write
1.61      paf       291:        file_write(pool, r.absolute(vtable_name.as_string()), 
1.48      paf       292:                sdata.cstr(), sdata.size(), true);
1.22      paf       293: }
                    294: 
1.93      parser    295: static void _count(Request& r, const String& method_name, MethodParams *) {
1.6       paf       296:        Pool& pool=r.pool();
1.18      paf       297:        Value& value=*new(pool) VInt(pool, static_cast<VTable *>(r.self)->table().size());
1.93      parser    298:        value.set_name(method_name);
1.15      paf       299:        r.write_no_lang(value);
1.6       paf       300: }
                    301: 
1.61      paf       302: static void _line(Request& r, const String& method_name, MethodParams *) {
1.6       paf       303:        Pool& pool=r.pool();
1.37      paf       304:        Value& value=*new(pool) VInt(pool, 1+static_cast<VTable *>(r.self)->table().current());
1.93      parser    305:        value.set_name(method_name);
1.15      paf       306:        r.write_no_lang(value);
1.6       paf       307: }
                    308: 
1.61      paf       309: static void _offset(Request& r, const String& method_name, MethodParams *params) {
1.6       paf       310:        Pool& pool=r.pool();
1.18      paf       311:        Table& table=static_cast<VTable *>(r.self)->table();
1.74      paf       312:        if(params->size()) {
1.90      parser    313:                Value& offset_expr=params->as_junction(0, "offset must be expression");
1.80      parser    314:                table.shift(r.process(offset_expr).as_int());
1.74      paf       315:        } else {
1.37      paf       316:                Value& value=*new(pool) VInt(pool, table.current());
1.93      parser    317:                value.set_name(method_name);
1.15      paf       318:                r.write_no_lang(value);
1.6       paf       319:        }
                    320: }
                    321: 
1.61      paf       322: static void _menu(Request& r, const String& method_name, MethodParams *params) {
1.90      parser    323:        Value& body_code=params->as_junction(0, "body must be code");
1.7       paf       324:        
1.61      paf       325:        Value *delim_code=params->size()==2?&params->get(1):0;
1.7       paf       326: 
1.64      paf       327:        VTable& vtable=*static_cast<VTable *>(r.self);
                    328:        Table& table=vtable.table();
1.7       paf       329:        bool need_delim=false;
1.99      parser    330:        int saved_current=table.current();
                    331:        int size=table.size();
                    332:        for(int row=0; row<size; row++) {
1.22      paf       333:                table.set_current(row);
1.7       paf       334: 
1.12      paf       335:                Value& processed_body=r.process(body_code);
1.7       paf       336:                if(delim_code) { // delimiter set?
                    337:                        const String *string=processed_body.get_string();
                    338:                        if(need_delim && string && string->size()) // need delim & iteration produced string?
                    339:                                r.write_pass_lang(r.process(*delim_code));
                    340:                        need_delim=true;
                    341:                }
                    342:                r.write_pass_lang(processed_body);
                    343:        }
1.99      parser    344:        table.set_current(saved_current);
1.7       paf       345: }
                    346: 
1.61      paf       347: static void _empty(Request& r, const String& method_name, MethodParams *params) {
1.75      paf       348:        Pool& pool=r.pool();
1.18      paf       349:        Table& table=static_cast<VTable *>(r.self)->table();
1.75      paf       350:        
                    351:        r.write_no_lang(*new(pool) VBool(pool, table.size()==0));
1.8       paf       352: }
1.15      paf       353: 
1.74      paf       354: /// used by table: _hash / table_row_to_hash
                    355: struct Row_info {
                    356:        Table *table;
                    357:        int key_field;
                    358:        Array *value_fields;
                    359:        Hash *hash;
                    360: };
                    361: static void table_row_to_hash(Array::Item *value, void *info) {
                    362:        Array& row=*static_cast<Array *>(value);
                    363:        Row_info& ri=*static_cast<Row_info *>(info);
                    364:        Pool& pool=ri.table->pool();
                    365: 
1.76      paf       366:        if(ri.key_field<row.size()) {
                    367:                VHash& result=*new(pool) VHash(pool);
                    368:                Hash& hash=*result.get_hash();
1.74      paf       369:                for(int i=0; i<ri.value_fields->size(); i++) {
                    370:                        int value_field=ri.value_fields->get_int(i);
                    371:                        if(value_field<row.size())
                    372:                                hash.put(
1.91      parser    373:                                        *ri.table->columns()->get_string(value_field), 
1.74      paf       374:                                        new(pool) VString(*row.get_string(value_field)));
                    375:                }
                    376:                
1.77      paf       377:                ri.hash->put(*row.get_string(ri.key_field), &result);
1.74      paf       378:        }
                    379: }
                    380: static void _hash(Request& r, const String& method_name, MethodParams *params) {
1.97      parser    381:        Pool& pool=r.pool();
1.74      paf       382:        Table& table=static_cast<VTable *>(r.self)->table();
1.97      parser    383:        Value& result=*new(pool) VHash(pool);
1.74      paf       384:        if(const Array *columns=table.columns()) 
                    385:                if(columns->size()>1) {
                    386: 
1.90      parser    387:                        const String& key_field_name=params->as_no_junction(0, 
1.74      paf       388:                                "key field name must not be code").as_string();
                    389:                        int key_field=table.column_name2index(key_field_name, true);
                    390:                        int value_fields_count=params->size()-1;
                    391:                        bool value_fields_by_params=value_fields_count!=0;
                    392:                        if(!value_fields_by_params)
                    393:                                value_fields_count=columns->size()-1; // all columns except key
                    394:                        Array value_fields(pool, value_fields_count);
                    395:                        if(value_fields_by_params) {
                    396:                                for(int i=1; i<params->size(); i++) {
1.91      parser    397:                                        const String& value_field_name=params->as_no_junction(i, 
1.74      paf       398:                                                "value field name must not be code").as_string();
                    399:                                        value_fields+=table.column_name2index(value_field_name, true);
                    400:                                }
                    401:                        } else { // by all columns except key
                    402:                                for(int i=0; i<columns->size(); i++)
                    403:                                        if(i!=key_field)
                    404:                                                value_fields+=i;
                    405:                        }
                    406: 
                    407:                        // integers: key_field & value_fields
                    408:                        Row_info row_info={&table, key_field, &value_fields, result.get_hash()};
                    409:                        table.for_each(table_row_to_hash, &row_info);
                    410:                }
1.97      parser    411:        result.set_name(method_name);
                    412:        r.write_no_lang(result);
1.74      paf       413: }
                    414: 
                    415: /// used by table: _sort / sort_cmp_string|sort_cmp_double
1.78      paf       416: struct Table_seq_item {
1.34      paf       417:        Array *row;
                    418:        union {
                    419:                char *c_str;
                    420:                double d;
                    421:        } value;
1.32      paf       422: };
1.34      paf       423: static int sort_cmp_string(const void *a, const void *b) {
                    424:        return strcmp(
1.78      paf       425:                static_cast<const Table_seq_item *>(a)->value.c_str, 
                    426:                static_cast<const Table_seq_item *>(b)->value.c_str
1.34      paf       427:        );
                    428: }
                    429: static int sort_cmp_double(const void *a, const void *b) {
1.78      paf       430:        double va=static_cast<const Table_seq_item *>(a)->value.d;
                    431:        double vb=static_cast<const Table_seq_item *>(b)->value.d;
1.34      paf       432:        if(va<vb)
                    433:                return -1;
                    434:        else if(va>vb)
                    435:                return +1;
                    436:        else 
                    437:                return 0;
                    438: }
1.61      paf       439: static void _sort(Request& r, const String& method_name, MethodParams *params) {
1.101     parser    440:        Pool& pool=r.pool();
1.90      parser    441:        Value& key_maker=params->as_junction(0, "key-maker must be code");
1.61      paf       442: 
1.102     parser    443:        bool reverse=params->size()==2/*..[desc|asc|]*/?
1.103   ! parser    444:                reverse=params->as_no_junction(1, "order must not be code").as_string()=="desc":
        !           445:                true;
1.32      paf       446: 
1.101     parser    447:        Table& old_table=static_cast<VTable *>(r.self)->table();
                    448:        Table& new_table=*new(pool) Table(pool, &method_name, old_table.columns());
1.34      paf       449: 
1.101     parser    450:        Table_seq_item *seq=(Table_seq_item *)pool.malloc(sizeof(Table_seq_item)*old_table.size());
1.34      paf       451:        int i;
                    452: 
                    453:        // calculate key values
                    454:        bool key_values_are_strings=true;
1.101     parser    455:        // save 'current'
                    456:        int saved_current=old_table.current();
                    457:        for(i=0; i<old_table.size(); i++) {
                    458:                old_table.set_current(i);
1.32      paf       459:                // calculate key value
1.101     parser    460:                seq[i].row=(MethodParams *)old_table.get(i);
1.34      paf       461:                Value& value=*r.process(key_maker).as_expr_result(true/*return string as-is*/);
                    462:                if(i==0) // determining key values type by first one
                    463:                        key_values_are_strings=value.is_string();
                    464: 
                    465:                if(key_values_are_strings)
                    466:                        seq[i].value.c_str=value.as_string().cstr();
                    467:                else
                    468:                        seq[i].value.d=value.as_double();
1.32      paf       469:        }
1.101     parser    470:        // restore 'current'
                    471:        old_table.set_current(saved_current);
1.32      paf       472:        // sort keys
1.101     parser    473:        _qsort(seq, old_table.size(), sizeof(Table_seq_item), 
1.34      paf       474:                key_values_are_strings?sort_cmp_string:sort_cmp_double);
1.32      paf       475: 
1.34      paf       476:        // reorder table as they require in 'seq'
1.101     parser    477:        for(i=0; i<old_table.size(); i++)
                    478:                new_table+=seq[reverse?old_table.size()-1-i:i].row;
1.32      paf       479: 
1.101     parser    480:        r.write_no_lang(*new(pool) VTable(pool, &new_table));
1.32      paf       481: }
                    482: 
1.61      paf       483: static void _locate(Request& r, const String& method_name, MethodParams *params) {
1.72      paf       484:        Pool& pool=r.pool();
                    485: 
1.36      paf       486:        VTable& vtable=*static_cast<VTable *>(r.self);
                    487:        Table& table=vtable.table();
1.72      paf       488:        Value& result=*new(pool) VBool(pool, table.locate(
1.91      parser    489:                params->get(0).as_string(), 
1.72      paf       490:                params->get(1).as_string()));
                    491:        result.set_name(method_name);
                    492:        r.write_no_lang(result);
1.37      paf       493: }
                    494: 
1.61      paf       495: static void _flip(Request& r, const String& method_name, MethodParams *params) {
1.39      paf       496:        Pool& pool=r.pool();
                    497:        VTable& vtable=*static_cast<VTable *>(r.self);
                    498: 
                    499:        Table& old_table=*vtable.get_table();
                    500:        Table& new_table=*new(pool) Table(pool, &method_name, 0/*nameless*/);
                    501:        if(old_table.size())
                    502:                if(int old_cols=old_table.at(0).size()) 
                    503:                        for(int column=0; column<old_cols; column++) {
                    504:                                Array& new_row=*new(pool) Array(pool, old_table.size());
                    505:                                for(int i=0; i<old_table.size(); i++) {
                    506:                                        const Array& old_row=old_table.at(i);
                    507:                                        new_row+=column<old_row.size()?old_row.get(column):empty_string;
                    508:                                }
                    509:                                new_table+=&new_row;
                    510:                        }
                    511: 
1.99      parser    512:        r.write_no_lang(*new(pool) VTable(pool, &new_table));
1.39      paf       513: }
                    514: 
1.61      paf       515: static void _append(Request& r, const String& method_name, MethodParams *params) {
1.41      paf       516:        Pool& pool=r.pool();
                    517:        // data is last parameter
1.61      paf       518:        const String& string=
1.90      parser    519:                r.process(params->as_junction(0, "body must be code")).as_string();
1.41      paf       520: 
                    521:        // parse cells
                    522:        Array& row=*new(pool) Array(pool);
1.46      paf       523:        string.split(row, 0, "\t", 1, String::UL_CLEAN);
1.41      paf       524: 
1.66      paf       525:        VTable& vtable=*static_cast<VTable *>(r.self);
                    526:        vtable.table()+=&row;
1.41      paf       527: }
                    528: 
1.61      paf       529: static void _join(Request& r, const String& method_name, MethodParams *params) {
1.42      paf       530:        Pool& pool=r.pool();
                    531: 
1.90      parser    532:        Table *maybe_src=params->as_no_junction(0, "table ref must not be code").get_table();
1.42      paf       533:        if(!maybe_src)
1.91      parser    534:                PTHROW(0, 0, 
                    535:                        &method_name, 
1.42      paf       536:                        "source is not a table");
                    537: 
                    538:        Table& src=*maybe_src;
                    539:        Table& dest=static_cast<VTable *>(r.self)->table();
                    540:        if(&src == &dest)
1.91      parser    541:                PTHROW(0, 0, 
                    542:                        &method_name, 
1.42      paf       543:                        "source and destination are same table");
                    544: 
                    545:        if(const Array *dest_columns=dest.columns()) { // dest is named
                    546:                int saved_src_current=src.current();
                    547:                for(int src_row=0; src_row<src.size(); src_row++) {
                    548:                        src.set_current(src_row);
                    549:                        Array& dest_row=*new(pool) Array(pool);
                    550:                        for(int dest_column=0; dest_column<dest_columns->size(); dest_column++) 
                    551:                                dest_row+=src.item(*dest_columns->get_string(dest_column));
                    552:                        dest+=&dest_row;
                    553:                }
                    554:                src.set_current(saved_src_current);
                    555:        } else { // dest is nameless
                    556:                for(int src_row=0; src_row<src.size(); src_row++)
                    557:                        dest+=&src.at(src_row);
                    558:        }
                    559: }
                    560: 
1.94      parser    561: #ifndef DOXYGEN
                    562: class Table_sql_event_handlers : public SQL_Driver_query_event_handlers {
                    563: public:
                    564:        Table_sql_event_handlers(Pool& apool, const String& amethod_name,
                    565:                const String& astatement_string, const char *astatement_cstr) :
                    566:                pool(apool), 
                    567:                method_name(amethod_name),
                    568:                statement_string(astatement_string),
                    569:                statement_cstr(astatement_cstr),
                    570:                columns(*new(pool) Array(pool)),
                    571:                row(0), row_index(0),
                    572:                table(0)
                    573:        {
                    574:        }
                    575: 
                    576:        void add_column(void *ptr, size_t size) {
                    577:                String *column=new(pool) String(pool);
                    578:                column->APPEND_TAINTED(
                    579:                        (const char *)ptr, size, 
                    580:                        statement_cstr, 0);
                    581:                columns+=column;
                    582:        }
                    583:        void before_rows() { 
                    584:                table=new(pool) Table(pool, &method_name, &columns);
                    585:        }
                    586:        void add_row() {
                    587:                (*table)+=(row=new(pool) Array(pool));
                    588:        }
                    589:        void add_row_cell(void *ptr, size_t size) {
                    590:                String *cell=new(pool) String(pool);
                    591:                if(size)
                    592:                        cell->APPEND_TAINTED(
                    593:                                (const char *)ptr, size, 
                    594:                                statement_cstr, row_index++);
                    595:                (*row)+=cell;
                    596:        }
                    597: 
                    598: private:
                    599:        Pool& pool;
                    600:        const String& method_name;
                    601:        const String& statement_string; const char *statement_cstr;
                    602:        Array& columns;
                    603:        Array *row;
                    604:        uint row_index;
                    605: public:
                    606:        Table *table;
                    607: };
                    608: #endif
1.61      paf       609: static void _sql(Request& r, const String& method_name, MethodParams *params) {
1.49      paf       610:        Pool& pool=r.pool();
                    611: 
                    612:        if(!r.connection)
1.91      parser    613:                PTHROW(0, 0, 
                    614:                        &method_name, 
1.49      paf       615:                        "without connect");
                    616: 
1.90      parser    617:        Value& statement=params->as_junction(0, "statement must be code");
1.49      paf       618: 
1.53      paf       619:        ulong limit=0;
1.100     parser    620:        ulong offset=0;
1.49      paf       621:        if(params->size()>1) {
1.100     parser    622:                Value& options_param=params->as_no_junction(1, "options must be hash, not code");
                    623:                if(Hash *options=options_param.get_hash()) {
                    624:                        if(Value *vlimit=(Value *)options->get(*sql_limit_name))
                    625:                                limit=(ulong)r.process(*vlimit).as_double();
                    626:                        if(Value *voffset=(Value *)options->get(*sql_offset_name))
                    627:                                offset=(ulong)r.process(*voffset).as_double();
                    628:                } else
                    629:                        PTHROW(0, 0,
                    630:                                &method_name,
                    631:                                "options must be hash");
1.49      paf       632:        }
                    633: 
1.54      paf       634:        Temp_lang temp_lang(r, String::UL_SQL);
                    635:        const String& statement_string=r.process(statement).as_string();
1.55      paf       636:        const char *statement_cstr=
                    637:                statement_string.cstr(String::UL_UNSPECIFIED, r.connection);
1.94      parser    638:        Table_sql_event_handlers handlers(pool, method_name,
                    639:                statement_string, statement_cstr);
1.52      paf       640:        bool need_rethrow=false; Exception rethrow_me;
                    641:        PTRY {
                    642:                r.connection->query(
1.91      parser    643:                        statement_cstr, offset, limit, 
1.94      parser    644:                        handlers);
1.52      paf       645:        }
1.82      parser    646:        PCATCH(e) { // query problem
1.52      paf       647:                rethrow_me=e;  need_rethrow=true;
                    648:        }
                    649:        PEND_CATCH
                    650:        if(need_rethrow)
1.91      parser    651:                PTHROW(rethrow_me.type(), rethrow_me.code(), 
1.53      paf       652:                        &statement_string, // setting more specific source [were url]
1.52      paf       653:                        rethrow_me.comment());
1.96      parser    654: 
                    655:        Table *result=
                    656:                handlers.table?handlers.table: // query resulted in table? return it
                    657:                new(pool) Table(pool, &method_name, 0); // query returned no table, fake it
1.49      paf       658: 
                    659:        // replace any previous table value
1.96      parser    660:        static_cast<VTable *>(r.self)->set_table(*result);
1.49      paf       661: }
                    662: 
1.61      paf       663: static void _dir(Request& r, const String& method_name, MethodParams *params) {
1.58      paf       664:        Pool& pool=r.pool();
                    665: 
1.90      parser    666:        Value& relative_path=params->as_no_junction(0, "path must not be code");
1.58      paf       667: 
1.59      paf       668:        const String *regexp;
                    669:        pcre *regexp_code;
                    670:        int ovecsize;
                    671:        int *ovector;
                    672:        if(params->size()>1) {
1.90      parser    673:                regexp=&params->as_no_junction(1, "regexp must not be code").as_string();
1.59      paf       674: 
                    675:                const char *pattern=regexp->cstr(String::UL_AS_IS);
                    676:                const char *errptr;
                    677:                int erroffset;
                    678:                regexp_code=pcre_compile(pattern, PCRE_EXTRA | PCRE_DOTALL, 
1.91      parser    679:                        &errptr, &erroffset, 
1.63      paf       680:                        r.pcre_tables);
1.59      paf       681: 
                    682:                if(!regexp_code)
1.91      parser    683:                        PTHROW(0, 0, 
                    684:                                &regexp->mid(erroffset, regexp->size()), 
1.59      paf       685:                                "regular expression syntax error - %s", errptr);
                    686: 
                    687:                ovector=(int *)malloc(sizeof(int)*(ovecsize=(1/*match*/)*3));
                    688:        } else 
                    689:                regexp_code=0;
                    690: 
                    691: 
1.58      paf       692:        const char* absolute_path_cstr=r.absolute(relative_path.as_string())
                    693:                .cstr(String::UL_FILE_NAME);
                    694: 
                    695:        Array& columns=*new(pool) Array(pool);
                    696:        columns+=new(pool) String(pool, "name");        
                    697:        Table& table=*new(pool) Table(pool, &method_name, &columns);
                    698: 
                    699:        LOAD_DIR(absolute_path_cstr, 
                    700:                size_t file_name_size=strlen(ffblk.ff_name);
1.59      paf       701:                bool suits=true;
                    702:                if(regexp_code) {
1.91      parser    703:                        int exec_result=pcre_exec(regexp_code, 0, 
                    704:                                ffblk.ff_name, file_name_size, 0, 
1.59      paf       705:                                0, ovector, ovecsize);
                    706:                        
                    707:                        if(exec_result==PCRE_ERROR_NOMATCH)
                    708:                                suits=false;
                    709:                        else if(exec_result<0) {
                    710:                                (*pcre_free)(regexp_code);
1.91      parser    711:                                PTHROW(0, 0, 
                    712:                                        regexp, 
1.60      paf       713:                                        "regular expression execute (%d)", 
1.59      paf       714:                                                exec_result);
                    715:                        }
                    716:                }
                    717: 
                    718:                if(suits) {
                    719:                        char *file_name_cstr=(char *)r.malloc(file_name_size);
                    720:                        memcpy(file_name_cstr, ffblk.ff_name, file_name_size);
                    721:                        String &file_name=*new(pool) String(pool);
1.91      parser    722:                        file_name.APPEND(file_name_cstr, file_name_size, String::UL_FILE_NAME, 
1.59      paf       723:                                method_name.origin().file, method_name.origin().line);
                    724:                
                    725:                        Array& row=*new(pool) Array(pool);
                    726:                        row+=&file_name;
                    727:                        table+=&row;
                    728:                }
1.58      paf       729:        );
1.59      paf       730: 
                    731:        if(regexp_code)
                    732:                (*pcre_free)(regexp_code);
1.58      paf       733: 
                    734:        // replace any previous table value
                    735:        static_cast<VTable *>(r.self)->set_table(table);
                    736: }
                    737: 
1.88      parser    738: static void _columns(Request& r, const String& method_name, MethodParams *) {
                    739:        Pool& pool=r.pool();
                    740: 
                    741:        Array& result_columns=*new(pool) Array(pool);
1.89      parser    742:        result_columns+=new(pool) String(pool, "column");
1.88      parser    743:        Table& result_table=*new(pool) Table(pool, &method_name, &result_columns);
                    744: 
                    745:        Table& source_table=static_cast<VTable *>(r.self)->table();
                    746:        if(const Array *source_columns=source_table.columns()) {
1.98      parser    747:                Array_iter i(*source_columns);
                    748:                while(i.has_next()) {
1.88      parser    749:                        Array& result_row=*new(pool) Array(pool);
1.98      parser    750:                        result_row+=i.next();
1.88      parser    751:                        result_table+=&result_row;
                    752:                }
                    753:        }
                    754: 
                    755:        VTable& result=*new(pool) VTable(pool, &result_table);
                    756:        result.set_name(method_name);
                    757:        r.write_no_lang(result);
                    758: }
                    759: 
1.66      paf       760: // constructor
                    761: 
                    762: MTable::MTable(Pool& apool) : Methoded(apool) {
                    763:        set_name(*NEW String(pool(), TABLE_CLASS_NAME));
                    764: 
1.49      paf       765:        // ^table:set{data}
                    766:        // ^table:set[nameless]{data}
1.66      paf       767:        add_native_method("set", Method::CT_DYNAMIC, _set, 1, 2);
1.2       paf       768: 
1.49      paf       769:        // ^table:load[file]  
                    770:        // ^table:load[nameless;file]
1.66      paf       771:        add_native_method("load", Method::CT_DYNAMIC, _load, 1, 2);
1.91      parser    772: 
                    773:        // ^table:calendar[month|montheng;year;month]  
                    774:        // ^table:calendar[week|weekeng;year;month;day]
                    775:        add_native_method("calendar", Method::CT_DYNAMIC, _calendar, 3, 4);
1.22      paf       776: 
                    777:        // ^table.save[file]  
                    778:        // ^table.save[nameless;file]
1.66      paf       779:        add_native_method("save", Method::CT_DYNAMIC, _save, 1, 2);
1.6       paf       780: 
                    781:        // ^table.count[]
1.66      paf       782:        add_native_method("count", Method::CT_DYNAMIC, _count, 0, 0);
1.6       paf       783: 
                    784:        // ^table.line[]
1.66      paf       785:        add_native_method("line", Method::CT_DYNAMIC, _line, 0, 0);
1.6       paf       786: 
1.10      paf       787:        // ^table.offset[]  
                    788:        // ^table.offset[offset]
1.66      paf       789:        add_native_method("offset", Method::CT_DYNAMIC, _offset, 0, 1);
1.7       paf       790: 
1.10      paf       791:        // ^table.menu{code}  
                    792:        // ^table.menu{code}[delim]
1.66      paf       793:        add_native_method("menu", Method::CT_DYNAMIC, _menu, 1, 2);
1.8       paf       794: 
1.75      paf       795:        // ^table.empty[]
                    796:        add_native_method("empty", Method::CT_DYNAMIC, _empty, 0, 0);
1.74      paf       797: 
1.79      paf       798:        // ^table:hash[key field name]
                    799:        // ^table:hash[key field name][value field name;...]
1.74      paf       800:        add_native_method("hash", Method::CT_DYNAMIC, _hash, 1, 1000);
1.32      paf       801: 
1.102     parser    802:        // ^table.sort{string-key-maker} ^table.sort{string-key-maker}[desc|asc]
                    803:        // ^table.sort(numeric-key-maker) ^table.sort(numeric-key-maker)[desc|asc]
1.66      paf       804:        add_native_method("sort", Method::CT_DYNAMIC, _sort, 1, 2);
1.8       paf       805: 
1.36      paf       806:        // ^table.locate[field;value]
1.66      paf       807:        add_native_method("locate", Method::CT_DYNAMIC, _locate, 2, 2);
1.39      paf       808: 
                    809:        // ^table.flip[]
1.66      paf       810:        add_native_method("flip", Method::CT_DYNAMIC, _flip, 0, 0);
1.41      paf       811: 
                    812:        // ^table.append{r{tab}e{tab}c{tab}o{tab}r{tab}d}
1.66      paf       813:        add_native_method("append", Method::CT_DYNAMIC, _append, 1, 1);
1.42      paf       814: 
                    815:        // ^table.join[table]
1.66      paf       816:        add_native_method("join", Method::CT_DYNAMIC, _join, 1, 1);
1.49      paf       817: 
                    818: 
1.100     parser    819:        // ^table:sql[query]
                    820:        // ^table:sql[query][$.limit(1) $.offset(2)]
                    821:        add_native_method("sql", Method::CT_DYNAMIC, _sql, 1, 2);
1.58      paf       822: 
                    823:        // ^table:dir[path]
                    824:        // ^table:dir[path][regexp]
1.66      paf       825:        add_native_method("dir", Method::CT_DYNAMIC, _dir, 1, 2);
1.88      parser    826: 
                    827:        // ^table:columns[]
                    828:        add_native_method("columns", Method::CT_DYNAMIC, _columns, 0, 0);
1.66      paf       829: }
                    830: 
                    831: // global variable
                    832: 
                    833: Methoded *table_class;
                    834: 
                    835: // creator
                    836: 
                    837: Methoded *MTable_create(Pool& pool) {
                    838:        return table_class=new(pool) MTable(pool);
1.40      paf       839: }

E-mail: