Annotation of parser3/src/classes/table.C, revision 1.186
1.20 paf 1: /** @file
1.47 paf 2: Parser: @b table parser class.
1.20 paf 3:
1.182 paf 4: Copyright (c) 2001-2003 ArtLebedev Group (http://www.artlebedev.com)
1.144 paf 5: Author: Alexandr Petrosian <paf@design.ru> (http://paf.design.ru)
1.154 paf 6: */
1.20 paf 7:
1.186 ! paf 8: static const char* IDENT_TABLE_C="$Date: 2003/09/29 11:03:21 $";
1.1 paf 9:
1.105 parser 10: #include "classes.h"
1.182 paf 11: #include "pa_vmethod_frame.h"
12:
1.16 paf 13: #include "pa_common.h"
1.1 paf 14: #include "pa_request.h"
15: #include "pa_vtable.h"
1.6 paf 16: #include "pa_vint.h"
1.51 paf 17: #include "pa_sql_connection.h"
1.72 paf 18: #include "pa_vbool.h"
1.1 paf 19:
1.66 paf 20: // class
21:
1.182 paf 22: class MTable: public Methoded {
1.66 paf 23: public: // VStateless_class
1.182 paf 24: Value* create_new_value() { return new VTable(); }
1.66 paf 25:
26: public:
1.182 paf 27: MTable();
1.70 paf 28:
29: public: // Methoded
1.66 paf 30: bool used_directly() { return true; }
31: };
1.1 paf 32:
1.182 paf 33: // global variable
34:
35: DECLARE_CLASS_VAR(table, new MTable, 0);
36:
37: // defines for globals
38:
39: #define SQL_LIMIT_NAME "limit"
40: #define SQL_OFFSET_NAME "offset"
41: #define SQL_DEFAULT_NAME "default"
42: #define SQL_DISTINCT_NAME "distinct"
43: #define TABLE_REVERSE_NAME "reverse"
44:
45: // globals
46:
47: String sql_limit_name(SQL_LIMIT_NAME);
48: String sql_offset_name(SQL_OFFSET_NAME);
49: String sql_default_name(SQL_DEFAULT_NAME);
50: String sql_distinct_name(SQL_DISTINCT_NAME);
51: String table_reverse_name(TABLE_REVERSE_NAME);
52:
1.186 ! paf 53: // local defines
! 54:
! 55: #define COLUMN_SEPARATOR_NAME "column-separator"
! 56: #define COLUMN_ENCLOSER_NAME "column-encloser"
! 57:
! 58:
1.1 paf 59: // methods
1.66 paf 60:
1.182 paf 61: static Table::Action_options get_action_options(Request& r, MethodParams& params,
62: const Table& source) {
1.176 paf 63: Table::Action_options result;
1.182 paf 64: if(!params.count())
65: return result;
66:
67: Value& maybe_options=params.last();
68: /* can not do it:
69: want to enable ^table::create[$source;
70: # $.option[]
71: ]
72: but there is ^table.locate[name;value]
1.176 paf 73:
1.182 paf 74: if(maybe_options.is_string()) { // allow empty options
75: result.defined=true;
1.176 paf 76: return result;
1.182 paf 77: }
78: */
79: HashStringValue* options=maybe_options.get_hash();
1.176 paf 80: if(!options)
81: return result;
82:
83: result.defined=true;
84: bool defined_offset=false;
85:
86: int valid_options=0;
1.182 paf 87: if(Value* voffset=options->get(sql_offset_name)) {
1.176 paf 88: valid_options++;
89: defined_offset=true;
90: if(voffset->is_string()) {
1.182 paf 91: const String& soffset=*voffset->get_string();
1.176 paf 92: if(soffset == "cur")
93: result.offset=source.current();
94: else
1.164 paf 95: throw Exception("parser.runtime",
1.176 paf 96: &soffset,
97: "must be 'cur' string or expression");
98: } else
99: result.offset=r.process_to_value(*voffset).as_int();
100: }
1.182 paf 101: if(Value* vlimit=options->get(sql_limit_name)) {
1.176 paf 102: valid_options++;
103: result.limit=r.process_to_value(*vlimit).as_int();
104: }
1.182 paf 105: if(Value *vreverse=(Value *)options->get(table_reverse_name)) {
106: valid_options++;
107: result.reverse=r.process_to_value(*vreverse).as_bool();
108: if(result.reverse && !defined_offset)
109: result.offset=source.count()-1;
110: }
111:
112: if(valid_options!=options->count())
1.176 paf 113: throw Exception("parser.runtime",
1.182 paf 114: 0,
1.176 paf 115: "called with invalid option");
116:
117: return result;
118: }
1.180 paf 119: static void check_option_param(bool options_defined,
1.182 paf 120: MethodParams& params, size_t next_param_index,
1.176 paf 121: const char *msg) {
1.182 paf 122: if(next_param_index+(options_defined?1:0) != params.count())
1.176 paf 123: throw Exception("parser.runtime",
1.182 paf 124: 0,
1.176 paf 125: "%s", msg);
1.157 paf 126: }
127:
1.182 paf 128: static void _create(Request& r, MethodParams& params) {
1.157 paf 129: // clone/copy part?
1.182 paf 130: if(Table *source=params[0].get_table()) {
131: Table::Action_options o=get_action_options(r, params, *source);
132: check_option_param(o.defined, params, 1,
1.176 paf 133: "too many parameters");
1.182 paf 134: GET_SELF(r, VTable).set_table(*new Table(*source, o));
1.157 paf 135: return;
136: }
1.142 paf 137:
1.1 paf 138: // data is last parameter
1.182 paf 139: Temp_lang temp_lang(r, String::L_PASS_APPENDED);
140: const String& data=
141: r.process_to_string(params.as_junction(params.count()-1, "body must be code"));
1.44 paf 142:
143: // parse columns
1.182 paf 144: size_t raw_pos_after=0;
145: Table::columns_type columns;
146: if(params.count()==2) {
147: columns=Table::columns_type(0); // nameless
1.21 paf 148: } else {
1.182 paf 149: columns=Table::columns_type(new ArrayString);
1.44 paf 150:
1.182 paf 151: ArrayString head;
152: data.split(head, raw_pos_after, "\n", String::L_AS_IS, 1);
153: if(head.count()) {
154: size_t col_pos_after=0;
155: head[0]->split(*columns, col_pos_after, "\t", String::L_AS_IS);
156: }
1.44 paf 157: }
158:
1.182 paf 159: Table& table=*new Table(columns);
1.44 paf 160: // parse cells
1.182 paf 161:
162: ArrayString rows;
163: data.split(rows, raw_pos_after, "\n", String::L_AS_IS);
164: Array_iterator<const String*> i(rows);
1.98 parser 165: while(i.has_next()) {
1.182 paf 166: Table::element_type row(new ArrayString);
167: const String& string=*i.next();
1.118 parser 168: // remove comment lines
1.182 paf 169: if(!string.length())
1.44 paf 170: continue;
171:
1.182 paf 172: size_t col_pos_after=0;
173: string.split(*row, col_pos_after, "\t", String::L_AS_IS);
174: table+=row;
1.17 paf 175: }
1.1 paf 176:
1.44 paf 177: // replace any previous table value
1.182 paf 178: GET_SELF(r, VTable).set_table(table);
1.44 paf 179: }
180:
1.186 ! paf 181: inline char* remove_encloser(char* cstr, char encloser) {
! 182: if(cstr[0]!=encloser)
! 183: return cstr;
! 184:
! 185: size_t length=strlen(cstr);
! 186: if(length<2 || cstr[length-1]!=encloser)
! 187: return cstr;
! 188:
! 189: // 'string'
! 190:
! 191: cstr[length-1]=0;
! 192: cstr++;
! 193:
! 194: // double-encloser stands for encloser
! 195: char *read;
! 196: char *write;
! 197: write=read=cstr;
! 198: while(char c=*read++) {
! 199: if(c==encloser && *read==encloser)
! 200: read++;
! 201:
! 202: *write++=c;
! 203: }
! 204: *write=0; // terminate
! 205:
! 206: return cstr;
! 207: }
! 208:
1.182 paf 209: static void _load(Request& r, MethodParams& params) {
210: const String& first_param=params.as_string(0, "file name must be string");
1.168 paf 211: int filename_param_index=0;
212: bool nameless=first_param=="nameless";
213: if(nameless)
214: filename_param_index++;
1.182 paf 215: size_t options_param_index=filename_param_index+1;
1.186 ! paf 216:
! 217: HashStringValue *options=0;
! 218: char column_separator='\t';
! 219: char column_encloser=0;
! 220: if(options_param_index<params.count()
! 221: && (options=params.as_no_junction(options_param_index, "additional params must be hash").get_hash())) {
! 222: // cloning, so that we could change [to simplify checks on params inside file_read_text
! 223: options=new HashStringValue(*options);
! 224: if(Value* vseparator=options->get(COLUMN_SEPARATOR_NAME)) {
! 225: options->remove(COLUMN_SEPARATOR_NAME);
! 226: const String& sseparator=vseparator->as_string();
! 227: if(sseparator.length()!=1)
! 228: throw Exception("parser.runtime",
! 229: &sseparator,
! 230: "separator must be one character long");
! 231: column_separator=sseparator.first_char();
! 232: }
! 233: if(Value* vencloser=options->get(COLUMN_ENCLOSER_NAME)) {
! 234: options->remove(COLUMN_ENCLOSER_NAME);
! 235: const String& sencloser=vencloser->as_string();
! 236: if(sencloser.length()!=1)
! 237: throw Exception("parser.runtime",
! 238: &sencloser,
! 239: "encloser must be one character long");
! 240: column_encloser=sencloser.first_char();
! 241: }
! 242: }
! 243:
1.44 paf 244: // loading text
1.182 paf 245: char *data=file_read_text(r.charsets,
246: r.absolute(params.as_string(filename_param_index, "file name must be string")),
1.168 paf 247: true,
1.186 ! paf 248: options
1.168 paf 249: );
1.44 paf 250:
1.1 paf 251: // parse columns
1.182 paf 252: Table::columns_type columns;
1.168 paf 253: if(nameless) {
1.182 paf 254: columns=Table::columns_type(0); // nameless
1.1 paf 255: } else {
1.182 paf 256: columns=Table::columns_type(new ArrayString);
1.1 paf 257:
1.139 paf 258: while(char *row_chars=getrow(&data)) {
259: // remove empty&comment lines
260: if(!*row_chars || *row_chars == '#')
261: continue;
1.1 paf 262: do {
1.186 ! paf 263: char *column_chars=lsplit(&row_chars, column_separator);
! 264: if(column_encloser)
! 265: column_chars=remove_encloser(column_chars, column_encloser);
! 266: *columns+=new String(column_chars, 0, true);
1.1 paf 267: } while(row_chars);
1.139 paf 268:
269: break;
270: }
1.1 paf 271: }
272:
273: // parse cells
1.183 paf 274: Table& table=*new Table(columns);//что-то очень плохое с realloc'ом: 1000 сильно помогает
1.1 paf 275: char *row_chars;
1.183 paf 276: int cells=0;
1.1 paf 277: while(row_chars=getrow(&data)) {
1.118 parser 278: // remove empty&comment lines
279: if(!*row_chars || *row_chars == '#')
1.28 paf 280: continue;
1.182 paf 281: Table::element_type row(new ArrayString);
1.1 paf 282: while(char *cell_chars=lsplit(&row_chars, '\t')) {
1.186 ! paf 283: if(column_encloser)
! 284: cell_chars=remove_encloser(cell_chars, column_encloser);
1.182 paf 285: *row+=new String(cell_chars, 0, true);
1.183 paf 286: cells++;
1.1 paf 287: }
288: table+=row;
289: };
290:
291: // replace any previous table value
1.182 paf 292: GET_SELF(r, VTable).set_table(table);
1.1 paf 293: }
1.2 paf 294:
1.146 paf 295: /// @todo "x\nx" "xxx""xx"
1.182 paf 296: static void _save(Request& r, MethodParams& params) {
297: Value& vfile_name=params.as_no_junction(params.count()-1, "file name must not be code");
1.22 paf 298:
1.182 paf 299: Table& table=GET_SELF(r, VTable).table();
1.31 paf 300:
1.129 paf 301: bool do_append=false;
1.182 paf 302: String sdata;
303: if(params.count()==1) { // named output
1.31 paf 304: // write out names line
305: if(table.columns()) { // named table
1.182 paf 306: for(Array_iterator<const String*> i(*table.columns()); i.has_next(); ) {
307: sdata.append(*i.next(), String::L_TABLE);
1.98 parser 308: if(i.has_next())
1.182 paf 309: sdata.append_know_length("\t", 1, String::L_CLEAN);
1.31 paf 310: }
311: } else { // nameless table
1.182 paf 312: if(int lsize=table.count()?table[0]->count():0)
1.31 paf 313: for(int column=0; column<lsize; column++) {
1.182 paf 314: char *cindex_tab=new(PointerFreeGC) char[MAX_NUMBER];
315: sdata.append_know_length(cindex_tab,
1.185 paf 316: snprintf(cindex_tab, MAX_NUMBER,
317: column<lsize-1?"%d\t":"%d", column),
318: String::L_CLEAN);
1.31 paf 319: }
320: else
1.182 paf 321: sdata.append_help_length("empty nameless table", 0, String::L_CLEAN);
1.31 paf 322: }
1.182 paf 323: sdata.append_know_length("\n", 1, String::L_CLEAN);
1.129 paf 324: } else { // mode specified
1.182 paf 325: const String& mode=params.as_string(0, "mode must be string");
1.129 paf 326: if(mode=="append")
327: do_append=true;
328: else if(mode=="nameless")
329: /*ok, already skipped names output*/;
330: else
1.146 paf 331: throw Exception("parser.runtime",
1.129 paf 332: &mode,
333: "unknown mode, must be 'append'");
334:
1.31 paf 335: }
336: // data lines
1.182 paf 337: Array_iterator<ArrayString*> i(table);
1.98 parser 338: while(i.has_next()) {
1.182 paf 339: for(Array_iterator<const String*> c(*i.next()); c.has_next(); ) {
340: sdata.append(*c.next(), String::L_TABLE);
1.98 parser 341: if(c.has_next())
1.182 paf 342: sdata.append_know_length("\t", 1, String::L_CLEAN);
1.31 paf 343: }
1.182 paf 344: sdata.append_know_length("\n", 1, String::L_CLEAN);
1.31 paf 345: }
346:
347: // write
1.141 paf 348: file_write(r.absolute(vfile_name.as_string()),
1.182 paf 349: sdata.cstr(), sdata.length(), true, do_append);
1.22 paf 350: }
351:
1.182 paf 352: static void _count(Request& r, MethodParams&) {
353: int result=GET_SELF(r, VTable).table().count();
354: r.write_no_lang(*new VInt(result));
1.6 paf 355: }
356:
1.182 paf 357: static void _line(Request& r, MethodParams&) {
358: int result=1+GET_SELF(r, VTable).table().current();
359: r.write_no_lang(*new VInt(result));
1.6 paf 360: }
361:
1.182 paf 362: static void _offset(Request& r, MethodParams& params) {
363: Table& table=GET_SELF(r, VTable).table();
364: if(params.count()) {
1.133 paf 365: bool absolute=false;
1.182 paf 366: if(params.count()>1) {
367: const String& whence=params.as_string(0, "whence must be string");
1.133 paf 368: if(whence=="cur")
1.134 paf 369: absolute=false;
1.133 paf 370: else if(whence=="set")
1.134 paf 371: absolute=true;
1.133 paf 372: else
1.146 paf 373: throw Exception("parser.runtime",
1.134 paf 374: &whence,
375: "is invalid whence, valid are 'cur' or 'set'");
1.157 paf 376: }
1.133 paf 377:
1.182 paf 378: Value& offset_expr=params.as_junction(params.count()-1, "offset must be expression");
1.147 paf 379: table.offset(absolute, r.process_to_value(offset_expr).as_int());
1.151 paf 380: } else
1.182 paf 381: r.write_no_lang(*new VInt(table.current()));
1.6 paf 382: }
383:
1.182 paf 384: static void _menu(Request& r, MethodParams& params) {
385: Value& body_code=params.as_junction(0, "body must be code");
1.7 paf 386:
1.182 paf 387: Value* delim_maybe_code=params.count()>1?¶ms[1]:0;
1.7 paf 388:
1.182 paf 389: Table& table=GET_SELF(r, VTable).table();
1.7 paf 390: bool need_delim=false;
1.99 parser 391: int saved_current=table.current();
1.182 paf 392: int size=table.count();
1.99 parser 393: for(int row=0; row<size; row++) {
1.22 paf 394: table.set_current(row);
1.7 paf 395:
1.161 paf 396: StringOrValue sv_processed=r.process(body_code);
1.182 paf 397: const String* s_processed=sv_processed.get_string();
398: if(delim_maybe_code && s_processed && s_processed->length()) { // delimiter set and we have body
1.161 paf 399: if(need_delim) // need delim & iteration produced string?
1.150 paf 400: r.write_pass_lang(r.process(*delim_maybe_code));
1.7 paf 401: need_delim=true;
402: }
1.161 paf 403: r.write_pass_lang(sv_processed);
1.7 paf 404: }
1.99 parser 405: table.set_current(saved_current);
1.7 paf 406: }
407:
1.110 parser 408: #ifndef DOXYGEN
1.174 paf 409: enum Table2hash_distint { D_ILLEGAL, D_FIRST, D_TABLES };
1.74 paf 410: struct Row_info {
1.166 paf 411: Request *r;
1.74 paf 412: Table *table;
1.182 paf 413: Value* key_code;
414: size_t key_field;
415: Array<int>* value_fields;
416: HashStringValue* hash;
1.174 paf 417: Table2hash_distint distinct;
1.182 paf 418: size_t row;
1.74 paf 419: };
1.110 parser 420: #endif
1.182 paf 421: static void table_row_to_hash(Table::element_type row, Row_info *info) {
422: const String* key;
423: if(info->key_code) {
424: info->table->set_current(info->row++); // change context row
425: StringOrValue sv_processed=info->r->process(*info->key_code);
1.166 paf 426: key=&sv_processed.as_string();
427: } else
1.182 paf 428: key=info->key_field<row->count()?row->get(info->key_field):0;
1.166 paf 429:
430: if(!key)
431: return; // ignore rows without key [too-short-record_array if-indexed]
1.74 paf 432:
1.182 paf 433: switch(info->distinct) {
1.174 paf 434: case D_ILLEGAL: case D_FIRST:
435: {
1.182 paf 436: VHash* vhash=new VHash;
437: HashStringValue& hash=vhash->hash();
438: for(Array_iterator<int> i(*info->value_fields); i.has_next(); ) {
439: size_t value_field=i.next();
440: if(value_field<row->count())
1.174 paf 441: hash.put(
1.182 paf 442: *info->table->columns()->get(value_field),
443: new VString(*row->get(value_field)));
1.174 paf 444: }
445:
1.182 paf 446: if(info->hash->put_dont_replace(*key, vhash)) // put. existed?
447: if(info->distinct==D_ILLEGAL)
1.174 paf 448: throw Exception("parser.runtime",
449: key,
450: "duplicate key");
451: }
452: break;
453: case D_TABLES:
454: {
1.182 paf 455: VTable* vtable=(VTable*)info->hash->get(*key); // put. table existed?
1.174 paf 456: Table* table;
457: if(vtable)
458: table=vtable->get_table();
459: else {
460: // no? creating table of same structure as source
1.179 paf 461: Table::Action_options table_options(0, 0);
1.182 paf 462: table=new Table(*info->table, table_options/*no rows, just structure*/);
463: info->hash->put(*key, new VTable(table));
1.174 paf 464: }
1.182 paf 465: *table+=row;
1.174 paf 466: }
467: break;
468: default:
469: throw Exception(0,
470: 0,
1.182 paf 471: "invalid distinct code (#%d)", info->distinct);
1.74 paf 472: }
473: }
1.182 paf 474: static void _hash(Request& r, MethodParams& params) {
475: Table& self_table=GET_SELF(r, VTable).table();
476: VHash& result=*new VHash;
477: if(Table::columns_type columns=self_table.columns())
478: if(columns->count()>0) {
1.174 paf 479: Table2hash_distint distinct=D_ILLEGAL;
1.182 paf 480: int param_index=params.count()-1;
1.166 paf 481: if(param_index>0) {
1.182 paf 482: if(HashStringValue* options=
483: params.as_no_junction(param_index, "param must not be code").get_hash()) {
1.166 paf 484: --param_index;
485: int valid_options=0;
1.182 paf 486: if(Value* vdistinct_code=options->get(sql_distinct_name)) {
1.166 paf 487: valid_options++;
1.174 paf 488: Value& vdistinct_value=r.process_to_value(*vdistinct_code);
489: if(vdistinct_value.is_string()) {
490: const String& sdistinct=*vdistinct_value.get_string();
491: if(sdistinct=="tables")
492: distinct=D_TABLES;
493: else
494: throw Exception("parser.runtime",
495: &sdistinct,
496: "must be 'tables' or true/false");
497: } else
498: distinct=vdistinct_value.as_bool()?D_FIRST:D_ILLEGAL;
1.166 paf 499: }
1.182 paf 500: if(valid_options!=options->count())
1.166 paf 501: throw Exception("parser.runtime",
1.182 paf 502: 0,
1.166 paf 503: "called with invalid option");
1.163 paf 504: }
505: }
506: if(param_index==2) // bad options param type
507: throw Exception("parser.runtime",
1.182 paf 508: 0,
1.163 paf 509: "options must be hash");
510:
1.182 paf 511: Array<int> value_fields;
1.163 paf 512: if(param_index>0) {
1.174 paf 513: if(distinct!=D_ILLEGAL && distinct!=D_FIRST)
514: throw Exception("parser.runtime",
515: 0,
516: "in distinct[tables] mode you may not specify value field(s)");
1.182 paf 517: Value& value_fields_param=params.as_no_junction(param_index, "value field(s) must not be code");
1.123 parser 518: if(value_fields_param.is_string()) {
1.182 paf 519: value_fields+=self_table.column_name2index(
520: *value_fields_param.get_string(), true);
521: } else if(Table* value_fields_table=value_fields_param.get_table()) {
522: for(Array_iterator<Table::element_type> i(*value_fields_table);
523: i.has_next(); ) {
524: const String& value_field_name
525: =*i.next()->get(0);
526: value_fields
527: +=self_table.column_name2index(value_field_name, true);
1.123 parser 528: }
529: } else
1.146 paf 530: throw Exception("parser.runtime",
1.182 paf 531: 0,
1.123 parser 532: "value field(s) must be string or self_table"
533: );
534: } else { // by all columns, including key
1.174 paf 535: if(!(distinct!=D_ILLEGAL && distinct!=D_FIRST))
1.182 paf 536: for(size_t i=0; i<columns->count(); i++)
1.174 paf 537: value_fields+=i;
1.74 paf 538: }
539:
1.182 paf 540:
541: {
542: Row_info info={0};
543: info.r=&r;
544: info.table=&self_table;
545: Value* key_param=¶ms[0];
546: info.key_code=key_param->get_junction()?key_param:0;
547: info.key_field=info.key_code?-1
548: :self_table.column_name2index(key_param->as_string(), true);
549: info.value_fields=&value_fields;
550: info.hash=&result.hash();
551: info.distinct=distinct;
552: info.row=0;
553:
554: int saved_current=self_table.current();
555: self_table.for_each(table_row_to_hash, &info);
556: self_table.set_current(saved_current);
557: }
1.74 paf 558: }
1.97 parser 559: r.write_no_lang(result);
1.74 paf 560: }
561:
1.110 parser 562: #ifndef DOXYGEN
1.78 paf 563: struct Table_seq_item {
1.182 paf 564: ArrayString* row;
1.34 paf 565: union {
1.182 paf 566: const char *c_str;
1.34 paf 567: double d;
568: } value;
1.32 paf 569: };
1.110 parser 570: #endif
1.34 paf 571: static int sort_cmp_string(const void *a, const void *b) {
572: return strcmp(
1.78 paf 573: static_cast<const Table_seq_item *>(a)->value.c_str,
574: static_cast<const Table_seq_item *>(b)->value.c_str
1.34 paf 575: );
576: }
577: static int sort_cmp_double(const void *a, const void *b) {
1.78 paf 578: double va=static_cast<const Table_seq_item *>(a)->value.d;
579: double vb=static_cast<const Table_seq_item *>(b)->value.d;
1.34 paf 580: if(va<vb)
581: return -1;
582: else if(va>vb)
583: return +1;
584: else
585: return 0;
586: }
1.182 paf 587: static void _sort(Request& r, MethodParams& params) {
588: Value& key_maker=params.as_junction(0, "key-maker must be code");
1.61 paf 589:
1.182 paf 590: bool reverse=params.count()>1/*..[desc|asc|]*/?
591: reverse=params.as_no_junction(1, "order must not be code").as_string()=="desc":
1.104 parser 592: false; // default=asc
1.32 paf 593:
1.182 paf 594: Table& old_table=GET_SELF(r, VTable).table();
595: Table& new_table=*new Table(old_table.columns());
1.34 paf 596:
1.182 paf 597: Table_seq_item* seq=new(PointerFreeGC) Table_seq_item[old_table.count()];
1.34 paf 598: int i;
599:
600: // calculate key values
601: bool key_values_are_strings=true;
1.182 paf 602: int old_count=old_table.count();
603: for(i=0; i<old_count; i++) {
1.101 parser 604: old_table.set_current(i);
1.32 paf 605: // calculate key value
1.182 paf 606: seq[i].row=old_table[i];
607: Value& value=r.process_to_value(key_maker).as_expr_result(true/*return string as-is*/);
1.34 paf 608: if(i==0) // determining key values type by first one
609: key_values_are_strings=value.is_string();
610:
611: if(key_values_are_strings)
612: seq[i].value.c_str=value.as_string().cstr();
613: else
614: seq[i].value.d=value.as_double();
1.32 paf 615: }
616: // sort keys
1.182 paf 617: _qsort(seq, old_count, sizeof(Table_seq_item),
1.34 paf 618: key_values_are_strings?sort_cmp_string:sort_cmp_double);
1.32 paf 619:
1.34 paf 620: // reorder table as they require in 'seq'
1.182 paf 621: for(i=0; i<old_count; i++)
622: new_table+=Table::element_type(seq[reverse?old_count-1-i:i].row);
623:
624: delete[] seq;
1.32 paf 625:
1.116 parser 626: // replace any previous table value
1.182 paf 627: GET_SELF(r, VTable).set_table(new_table);
1.32 paf 628: }
629:
1.176 paf 630: #ifndef DOXYGEN
1.182 paf 631: struct Expression_is_true_info {
1.176 paf 632: Request* r;
633: Value* expression_code;
634: };
635: #endif
1.182 paf 636: static bool expression_is_true(Table& self, void* ainfo) {
637: Expression_is_true_info& info=*static_cast<Expression_is_true_info*>(ainfo);
1.176 paf 638: return info.r->process_to_value(*info.expression_code).as_bool();
639: }
640: static bool _locate_expression(Table& table, Table::Action_options o,
1.182 paf 641: Request& r, MethodParams& params) {
642: check_option_param(o.defined, params, 1,
1.176 paf 643: "locate by expression only has parameters: expression and, maybe, options");
1.182 paf 644: Value& expression_code=params.as_junction(0, "must be expression");
1.145 paf 645:
1.182 paf 646: Expression_is_true_info info={&r, &expression_code};
647: return table.table_first_that(expression_is_true, &info, o);
1.145 paf 648: }
1.176 paf 649: static bool _locate_name_value(Table& table, Table::Action_options o,
1.182 paf 650: Request& r, MethodParams& params) {
651: check_option_param(o.defined, params, 2,
1.176 paf 652: "locate by locate by name has parameters: name, value and, maybe, options");
1.182 paf 653: const String& name=params.as_string(0, "column name must be string");
654: const String& value=params.as_string(1, "value must be string");
655: return table.locate(name, value, o);
656: }
657: static void _locate(Request& r, MethodParams& params) {
658: Table& table=GET_SELF(r, VTable).table();
1.72 paf 659:
1.182 paf 660: Table::Action_options o=get_action_options(r, params, table);
661:
662: bool result=params[0].get_junction()?
663: _locate_expression(table, o, r, params) :
664: _locate_name_value(table, o, r, params);
665: r.write_no_lang(*new VBool(result));
1.145 paf 666: }
1.182 paf 667:
668:
669: static void _flip(Request& r, MethodParams& params) {
670: Table& old_table=GET_SELF(r, VTable).table();
1.184 paf 671: Table& new_table=*new Table(0);
1.182 paf 672: if(size_t old_count=old_table.count())
673: if(size_t old_cols=old_table[0]->count())
674: for(size_t column=0; column<old_cols; column++) {
675: Table::element_type new_row(new ArrayString(old_count));
676: for(size_t i=0; i<old_count; i++) {
677: Table::element_type old_row=old_table[i];
678: *new_row+=column<old_row->count()?old_row->get(column):new String;
1.39 paf 679: }
1.182 paf 680: new_table+=new_row;
1.39 paf 681: }
682:
1.182 paf 683: r.write_no_lang(*new VTable(&new_table));
1.39 paf 684: }
685:
1.182 paf 686: static void _append(Request& r, MethodParams& params) {
1.134 paf 687: // data
1.182 paf 688: Temp_lang temp_lang(r, String::L_PASS_APPENDED);
689: const String& string=r.process_to_string(params.as_junction(0, "body must be code"));
1.41 paf 690:
691: // parse cells
1.182 paf 692: Table::element_type row=new ArrayString;
693: size_t pos_after=0;
694: string.split(*row, pos_after, "\t", String::L_AS_IS);
1.41 paf 695:
1.182 paf 696: GET_SELF(r, VTable).table()+=row;
1.41 paf 697: }
698:
1.182 paf 699: static void join_named_row(Table& src, Table* dest) {
700: Table::columns_type dest_columns=dest->columns();
701: size_t dest_columns_count=dest_columns->count();
702: Table::element_type dest_row(new ArrayString(dest_columns_count));
703: for(size_t dest_column=0; dest_column<dest_columns_count; dest_column++) {
704: const String* src_item=src.item(*dest_columns->get(dest_column));
705: *dest_row+=src_item?src_item:new String;
706: }
707: *dest+=dest_row;
708: }
709: static void join_nameless_row(Table& src, Table* dest) {
710: *dest+=src[src.current()];
711: }
712: static void _join(Request& r, MethodParams& params) {
713: Table* maybe_src=params.as_no_junction(0, "table ref must not be code").get_table();
1.42 paf 714: if(!maybe_src)
1.146 paf 715: throw Exception("parser.runtime",
1.182 paf 716: 0,
1.42 paf 717: "source is not a table");
1.176 paf 718: Table& src=*maybe_src;
719:
1.182 paf 720: Table::Action_options o=get_action_options(r, params, src);
721: check_option_param(o.defined, params, 1,
1.176 paf 722: "invalid extra parameter");
1.42 paf 723:
1.182 paf 724: Table& dest=GET_SELF(r, VTable).table();
1.42 paf 725: if(&src == &dest)
1.146 paf 726: throw Exception("parser.runtime",
1.182 paf 727: 0,
1.42 paf 728: "source and destination are same table");
729:
1.182 paf 730: if(Table::columns_type dest_columns=dest.columns()) // dest is named
731: src.table_for_each(join_named_row, &dest, o);
732: else // dest is nameless
733: src.table_for_each(join_nameless_row, &dest, o);
1.42 paf 734: }
735:
1.94 parser 736: #ifndef DOXYGEN
1.169 paf 737: class Table_sql_event_handlers: public SQL_Driver_query_event_handlers {
1.182 paf 738: ArrayString& columns;
739: ArrayString* row;
1.94 parser 740: public:
1.182 paf 741: Table* table;
742: public:
743: Table_sql_event_handlers() :
744: columns(*new ArrayString), row(0), table(0) {
1.94 parser 745: }
746:
1.182 paf 747: bool add_column(SQL_Error& error, const char *str, size_t length) {
1.170 paf 748: try {
1.182 paf 749: columns+=new String(str, length, true);
1.170 paf 750: return false;
751: } catch(...) {
752: error=SQL_Error("exception occured in Table_sql_event_handlers::add_column");
753: return true;
754: }
755: }
756: bool before_rows(SQL_Error& error) {
757: try {
1.182 paf 758: table=new Table(&columns);
1.170 paf 759: return false;
760: } catch(...) {
761: error=SQL_Error("exception occured in Table_sql_event_handlers::before_rows");
762: return true;
763: }
764: }
765: bool add_row(SQL_Error& error) {
766: try {
1.182 paf 767: *table+=row=new ArrayString;
1.170 paf 768: return false;
769: } catch(...) {
770: error=SQL_Error("exception occured in Table_sql_event_handlers::add_row");
771: return true;
772: }
773: }
1.182 paf 774: bool add_row_cell(SQL_Error& error, const char* str, size_t length) {
1.170 paf 775: try {
1.182 paf 776: String& cell=*new String;
777: if(length)
778: cell.append_know_length(str, length, String::L_TAINTED);
779: *row+=&cell;
1.170 paf 780: return false;
781: } catch(...) {
782: error=SQL_Error("exception occured in Table_sql_event_handlers::add_row_cell");
783: return true;
784: }
1.94 parser 785: }
786: };
787: #endif
1.182 paf 788: static void _sql(Request& r, MethodParams& params) {
789: Value& statement=params.as_junction(0, "statement must be code");
1.49 paf 790:
1.53 paf 791: ulong limit=0;
1.100 parser 792: ulong offset=0;
1.182 paf 793: if(params.count()>1) {
794: Value& voptions=params.as_no_junction(1, "options must be hash, not code");
1.156 paf 795: if(!voptions.is_string())
1.182 paf 796: if(HashStringValue* options=voptions.get_hash()) {
1.164 paf 797: int valid_options=0;
1.182 paf 798: if(Value* vlimit=options->get(sql_limit_name)) {
1.164 paf 799: valid_options++;
1.147 paf 800: limit=(ulong)r.process_to_value(*vlimit).as_double();
1.164 paf 801: }
1.182 paf 802: if(Value* voffset=options->get(sql_offset_name)) {
1.164 paf 803: valid_options++;
1.147 paf 804: offset=(ulong)r.process_to_value(*voffset).as_double();
1.164 paf 805: }
1.182 paf 806: if(valid_options!=options->count())
1.164 paf 807: throw Exception("parser.runtime",
1.182 paf 808: 0,
1.164 paf 809: "called with invalid option");
1.109 parser 810: } else
1.146 paf 811: throw Exception("parser.runtime",
1.182 paf 812: 0,
1.109 parser 813: "options must be hash");
1.49 paf 814: }
815:
1.182 paf 816: Temp_lang temp_lang(r, String::L_SQL);
817: const String& statement_string=r.process_to_string(statement);
818: const char* statement_cstr=
819: statement_string.cstr(String::L_UNSPECIFIED, r.connection());
820: Table_sql_event_handlers handlers;
1.135 paf 821: #ifdef RESOURCES_DEBUG
822: struct timeval mt[2];
823: //measure:before
824: gettimeofday(&mt[0],NULL);
825: #endif
1.182 paf 826: r.connection()->query(
1.160 paf 827: statement_cstr, offset, limit,
828: handlers,
829: statement_string);
1.135 paf 830:
831: #ifdef RESOURCES_DEBUG
832: //measure:after connect
833: gettimeofday(&mt[1],NULL);
834:
835: double t[2];
836: for(int i=0;i<2;i++)
837: t[i]=mt[i].tv_sec+mt[i].tv_usec/1000000.0;
838:
839: r.sql_request_time+=t[1]-t[0];
840: #endif
1.96 parser 841:
1.182 paf 842: Table& result=
843: handlers.table?*handlers.table: // query resulted in table? return it
844: *new Table(Table::columns_type(0)); // query returned no table, fake it
1.49 paf 845:
846: // replace any previous table value
1.182 paf 847: GET_SELF(r, VTable).set_table(result);
1.49 paf 848: }
849:
1.182 paf 850: static void _columns(Request& r, MethodParams&) {
1.88 parser 851:
1.182 paf 852: Table::columns_type result_columns(new ArrayString);
853: *result_columns+=new String("column");
854: Table& result_table=*new Table(result_columns);
1.88 parser 855:
1.182 paf 856: Table& source_table=GET_SELF(r, VTable).table();
857: if(Table::columns_type source_columns=source_table.columns()) {
858: for(Array_iterator<const String*> i(*source_columns); i.has_next(); ) {
859: Table::element_type result_row(new ArrayString);
860: *result_row+=i.next();
861: result_table+=result_row;
1.88 parser 862: }
863: }
864:
1.182 paf 865: r.write_no_lang(*new VTable(&result_table));
1.88 parser 866: }
867:
1.182 paf 868: static void _select(Request& r, MethodParams& params) {
869: Value& vcondition=params.as_junction(0, "condition must be expression");
1.148 paf 870:
1.182 paf 871: Table& source_table=GET_SELF(r, VTable).table();
872: Table& result_table=*new Table(source_table.columns());
1.148 paf 873:
874: int saved_current=source_table.current();
1.182 paf 875: int size=source_table.count();
1.148 paf 876: for(int row=0; row<size; row++) {
877: source_table.set_current(row);
878:
1.150 paf 879: bool condition=r.process_to_value(vcondition,
1.149 paf 880: /*0/*no name* /,*/
1.148 paf 881: false/*don't intercept string*/).as_bool();
882:
883: if(condition) // ...condition is true=
1.182 paf 884: result_table+=source_table[row]; // =green light to go to result
1.148 paf 885: }
886: source_table.set_current(saved_current);
887:
1.182 paf 888: r.write_no_lang(*new VTable(&result_table));
1.148 paf 889: }
890:
1.66 paf 891: // constructor
892:
1.182 paf 893: MTable::MTable(): Methoded("table") {
1.142 paf 894: // ^table::create{data}
895: // ^table::create[nameless]{data}
896: // ^table::create[table]
897: add_native_method("create", Method::CT_DYNAMIC, _create, 1, 2);
898: // old name for compatibility with <= v 1.141 2002/01/25 11:33:45 paf
899: add_native_method("set", Method::CT_DYNAMIC, _create, 1, 2);
1.2 paf 900:
1.142 paf 901: // ^table::load[file]
902: // ^table::load[nameless;file]
1.168 paf 903: add_native_method("load", Method::CT_DYNAMIC, _load, 1, 3);
1.22 paf 904:
905: // ^table.save[file]
906: // ^table.save[nameless;file]
1.66 paf 907: add_native_method("save", Method::CT_DYNAMIC, _save, 1, 2);
1.6 paf 908:
909: // ^table.count[]
1.66 paf 910: add_native_method("count", Method::CT_DYNAMIC, _count, 0, 0);
1.6 paf 911:
912: // ^table.line[]
1.66 paf 913: add_native_method("line", Method::CT_DYNAMIC, _line, 0, 0);
1.6 paf 914:
1.10 paf 915: // ^table.offset[]
1.133 paf 916: // ^table.offset(offset)
917: // ^table.offset[cur|set](offset)
918: add_native_method("offset", Method::CT_DYNAMIC, _offset, 0, 2);
1.7 paf 919:
1.10 paf 920: // ^table.menu{code}
921: // ^table.menu{code}[delim]
1.66 paf 922: add_native_method("menu", Method::CT_DYNAMIC, _menu, 1, 2);
1.74 paf 923:
1.79 paf 924: // ^table:hash[key field name]
1.123 parser 925: // ^table:hash[key field name][value field name(s) string/table]
1.163 paf 926: add_native_method("hash", Method::CT_DYNAMIC, _hash, 1, 3);
1.32 paf 927:
1.102 parser 928: // ^table.sort{string-key-maker} ^table.sort{string-key-maker}[desc|asc]
929: // ^table.sort(numeric-key-maker) ^table.sort(numeric-key-maker)[desc|asc]
1.66 paf 930: add_native_method("sort", Method::CT_DYNAMIC, _sort, 1, 2);
1.8 paf 931:
1.36 paf 932: // ^table.locate[field;value]
1.176 paf 933: add_native_method("locate", Method::CT_DYNAMIC, _locate, 1, 3);
1.39 paf 934:
935: // ^table.flip[]
1.66 paf 936: add_native_method("flip", Method::CT_DYNAMIC, _flip, 0, 0);
1.41 paf 937:
938: // ^table.append{r{tab}e{tab}c{tab}o{tab}r{tab}d}
1.66 paf 939: add_native_method("append", Method::CT_DYNAMIC, _append, 1, 1);
1.42 paf 940:
1.157 paf 941: // ^table.join[table][$.limit(10) $.offset(1) $.offset[cur] ]
942: add_native_method("join", Method::CT_DYNAMIC, _join, 1, 2);
1.49 paf 943:
944:
1.100 parser 945: // ^table:sql[query]
946: // ^table:sql[query][$.limit(1) $.offset(2)]
947: add_native_method("sql", Method::CT_DYNAMIC, _sql, 1, 2);
1.88 parser 948:
949: // ^table:columns[]
950: add_native_method("columns", Method::CT_DYNAMIC, _columns, 0, 0);
1.148 paf 951:
952: // ^table.select(expression) = table
953: add_native_method("select", Method::CT_DYNAMIC, _select, 1, 1);
1.40 paf 954: }
E-mail: