Annotation of parser3/src/classes/table.C, revision 1.190
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.190 ! paf 8: static const char* IDENT_TABLE_C="$Date: 2003/11/04 12:50:22 $";
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.190 ! paf 24: Value* create_new_value(Pool& apool) { 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:
1.187 paf 55: #define COLUMN_SEPARATOR_NAME "separator"
56: #define COLUMN_ENCLOSER_NAME "encloser"
1.186 paf 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.187 paf 181: static char* remove_encloser(char* cstr, char encloser) {
1.186 paf 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.187 paf 209: struct lsplit_result {
210: char* piece;
211: char delim;
212:
213: operator bool() { return piece!=0; }
214: };
215:
216: inline lsplit_result lsplit(char* string, char delim1, char delim2) {
217: lsplit_result result;
218: if(string) {
219: char delims[]={delim1, delim2, 0};
220: if(char* v=strpbrk(string, delims)) {
221: result.delim=*v;
222: *v=0;
223: result.piece=v+1;
224: return result;
225: }
226: }
227: result.piece=0;
228: result.delim=0;
229: return result;
230: }
231:
232: inline lsplit_result lsplit(char* *string_ref, char delim1, char delim2) {
233: lsplit_result result;
234: result.piece=*string_ref;
235: lsplit_result next=lsplit(*string_ref, delim1, delim2);
236: result.delim=next.delim;
237: *string_ref=next.piece;
238: return result;
239: }
240:
241: static lsplit_result lsplit(char** string_ref, char delim1, char delim2, char encloser) {
242: lsplit_result result;
243:
244: if(char* string=*string_ref) {
245: if(encloser && *string==encloser) {
246: string++;
247:
248: char *read;
249: char *write;
250: write=read=string;
251: char c;
252: while(c=*read++) {
253: if(c==encloser) {
254: char n=*read;
255: if(n==encloser) // double-encloser stands for encloser
256: read++;
257: else if(n==delim1 || n==delim2) {
258: result.delim=n;
259: read++;
260: break;
261: }
262: }
263:
264: *write++=c;
265: }
266: *write=0; // terminate
267: *string_ref=c? read: 0;
268: result.piece=string;
269: return result;
270: } else
271: return lsplit(string_ref, delim1, delim2);
272: }
273: result.piece=0;
274: return result;
275: }
276:
277: static void skip_empty_and_comment_lines( char** data_ref ) {
278: if(char *data=*data_ref) {
279: while( char c=*data ) {
280: if( c== '\n' || c == '#' ) {
281: /*nowhere=*/getrow(&data); // remove empty&comment lines
282: *data_ref=data;
283: continue;
284: }
285: break;
286: }
287: }
288: }
289:
290: struct TableSeparators {
291: char column;
292: char encloser;
1.188 paf 293: const String* sencloser;
1.187 paf 294:
295: TableSeparators() {
296: column='\t';
297: encloser=0;
298: }
299: void load( HashStringValue& options ) {
300: if(Value* vseparator=options.get(COLUMN_SEPARATOR_NAME)) {
301: options.remove(COLUMN_SEPARATOR_NAME);
302: const String& sseparator=vseparator->as_string();
303: if(sseparator.length()!=1)
304: throw Exception("parser.runtime",
305: &sseparator,
306: "separator must be one character long");
307: column=sseparator.first_char();
308: }
309: if(Value* vencloser=options.get(COLUMN_ENCLOSER_NAME)) {
310: options.remove(COLUMN_ENCLOSER_NAME);
1.188 paf 311: sencloser=&vencloser->as_string();
312: if(sencloser->length()!=1)
1.187 paf 313: throw Exception("parser.runtime",
1.188 paf 314: sencloser,
1.187 paf 315: "encloser must be one character long");
1.188 paf 316: encloser=sencloser->first_char();
1.187 paf 317: }
318: }
319: };
320:
1.182 paf 321: static void _load(Request& r, MethodParams& params) {
322: const String& first_param=params.as_string(0, "file name must be string");
1.168 paf 323: int filename_param_index=0;
324: bool nameless=first_param=="nameless";
325: if(nameless)
326: filename_param_index++;
1.182 paf 327: size_t options_param_index=filename_param_index+1;
1.186 paf 328:
329: HashStringValue *options=0;
1.187 paf 330: TableSeparators separators;
1.186 paf 331: if(options_param_index<params.count()
332: && (options=params.as_no_junction(options_param_index, "additional params must be hash").get_hash())) {
333: // cloning, so that we could change [to simplify checks on params inside file_read_text
334: options=new HashStringValue(*options);
1.187 paf 335: separators.load(*options);
1.186 paf 336: }
337:
1.44 paf 338: // loading text
1.182 paf 339: char *data=file_read_text(r.charsets,
340: r.absolute(params.as_string(filename_param_index, "file name must be string")),
1.168 paf 341: true,
1.186 paf 342: options
1.168 paf 343: );
1.44 paf 344:
1.1 paf 345: // parse columns
1.182 paf 346: Table::columns_type columns;
1.168 paf 347: if(nameless) {
1.182 paf 348: columns=Table::columns_type(0); // nameless
1.1 paf 349: } else {
1.182 paf 350: columns=Table::columns_type(new ArrayString);
1.1 paf 351:
1.187 paf 352: skip_empty_and_comment_lines(&data);
353: while( lsplit_result sr=lsplit(&data, separators.column, '\n', separators.encloser) ) {
354: *columns+=new String(sr.piece, 0, true);
355: if(sr.delim=='\n')
356: break;
1.139 paf 357: }
1.1 paf 358: }
1.187 paf 359:
360: Table& table=*new Table(columns);
1.1 paf 361:
362: // parse cells
1.187 paf 363: Table::element_type row(new ArrayString);
364: skip_empty_and_comment_lines(&data);
365: while( lsplit_result sr=lsplit(&data, separators.column, '\n', separators.encloser) ) {
366: if(!sr.delim && !row->count()) // append last empty column [if without \n]
367: break;
368: *row+=new String(sr.piece, 0, true);
369: if(sr.delim=='\n') {
370: table+=row;
371: row=new ArrayString;
372: skip_empty_and_comment_lines(&data);
1.1 paf 373: }
1.187 paf 374: }
375: // last line [if without \n]
376: if(row->count())
1.1 paf 377: table+=row;
1.187 paf 378:
1.1 paf 379: // replace any previous table value
1.182 paf 380: GET_SELF(r, VTable).set_table(table);
1.1 paf 381: }
1.2 paf 382:
1.188 paf 383: static void maybe_enclose( String& to, const String& from, char encloser, const String* sencloser ) {
384: if(encloser) {
385: to<<*sencloser;
386: // while we have 'encloser'...
1.189 paf 387: size_t pos_after=0;
388: for( size_t pos_before; (pos_before=from.pos( encloser, pos_after ))!=STRING_NOT_FOUND; pos_after=pos_before+1) {
1.188 paf 389: to<<from.mid(pos_before+1/*+found encloser*/, pos_after-pos_before);
390: to<<*sencloser; // doubling encloser
391: }
392: // last piece
393: size_t from_length=from.length();
394: if(pos_after<from_length)
395: to<<from.mid(pos_after, from_length);
396:
397: to<<*sencloser;
398: } else
399: to.append(from, String::L_TABLE);
400: }
401:
402:
1.182 paf 403: static void _save(Request& r, MethodParams& params) {
1.188 paf 404: const String& first_arg=params.as_string(0, "first argument must not be code");
405: size_t param_index=1;
406:
407: bool do_append=false;
408: bool output_column_names=true;
409:
410: // mode?
411: if(first_arg=="append")
412: do_append=true;
413: else if(first_arg=="nameless")
414: output_column_names=false;
415: else
416: --param_index;
417:
418: const String& file_name=params.as_string(param_index++, "file name must not be code");
419:
420: TableSeparators separators;
421: if(param_index<params.count()) {
422: if(HashStringValue *options=params.as_no_junction(param_index++, "additional params must be hash").get_hash()) {
423: separators.load(*options);
424: if(options->count())
425: throw Exception("parser.runtime",
426: 0,
427: "invalid option passed");
428: } else
429: throw Exception("parser.runtime",
430: 0,
431: "additional params must be hash (did you spell mode parameter correctly?)");
432:
433: }
434: if(param_index<params.count())
435: throw Exception("parser.runtime",
436: 0,
437: "bad mode (must be nameless or append)");
1.22 paf 438:
1.182 paf 439: Table& table=GET_SELF(r, VTable).table();
1.31 paf 440:
1.182 paf 441: String sdata;
1.188 paf 442: if(output_column_names) {
1.31 paf 443: if(table.columns()) { // named table
1.182 paf 444: for(Array_iterator<const String*> i(*table.columns()); i.has_next(); ) {
1.188 paf 445: maybe_enclose( sdata, *i.next(), separators.encloser, separators.sencloser );
1.98 parser 446: if(i.has_next())
1.182 paf 447: sdata.append_know_length("\t", 1, String::L_CLEAN);
1.31 paf 448: }
1.188 paf 449: } else { // nameless table [we were asked to output column names]
1.182 paf 450: if(int lsize=table.count()?table[0]->count():0)
1.31 paf 451: for(int column=0; column<lsize; column++) {
1.182 paf 452: char *cindex_tab=new(PointerFreeGC) char[MAX_NUMBER];
453: sdata.append_know_length(cindex_tab,
1.185 paf 454: snprintf(cindex_tab, MAX_NUMBER,
455: column<lsize-1?"%d\t":"%d", column),
456: String::L_CLEAN);
1.31 paf 457: }
458: else
1.182 paf 459: sdata.append_help_length("empty nameless table", 0, String::L_CLEAN);
1.31 paf 460: }
1.182 paf 461: sdata.append_know_length("\n", 1, String::L_CLEAN);
1.188 paf 462: }
1.129 paf 463:
1.31 paf 464: // data lines
1.182 paf 465: Array_iterator<ArrayString*> i(table);
1.98 parser 466: while(i.has_next()) {
1.182 paf 467: for(Array_iterator<const String*> c(*i.next()); c.has_next(); ) {
1.188 paf 468: maybe_enclose( sdata, *c.next(), separators.encloser, separators.sencloser );
1.98 parser 469: if(c.has_next())
1.182 paf 470: sdata.append_know_length("\t", 1, String::L_CLEAN);
1.31 paf 471: }
1.182 paf 472: sdata.append_know_length("\n", 1, String::L_CLEAN);
1.31 paf 473: }
474:
475: // write
1.188 paf 476: file_write(r.absolute(file_name),
1.182 paf 477: sdata.cstr(), sdata.length(), true, do_append);
1.22 paf 478: }
479:
1.182 paf 480: static void _count(Request& r, MethodParams&) {
481: int result=GET_SELF(r, VTable).table().count();
482: r.write_no_lang(*new VInt(result));
1.6 paf 483: }
484:
1.182 paf 485: static void _line(Request& r, MethodParams&) {
486: int result=1+GET_SELF(r, VTable).table().current();
487: r.write_no_lang(*new VInt(result));
1.6 paf 488: }
489:
1.182 paf 490: static void _offset(Request& r, MethodParams& params) {
491: Table& table=GET_SELF(r, VTable).table();
492: if(params.count()) {
1.133 paf 493: bool absolute=false;
1.182 paf 494: if(params.count()>1) {
495: const String& whence=params.as_string(0, "whence must be string");
1.133 paf 496: if(whence=="cur")
1.134 paf 497: absolute=false;
1.133 paf 498: else if(whence=="set")
1.134 paf 499: absolute=true;
1.133 paf 500: else
1.146 paf 501: throw Exception("parser.runtime",
1.134 paf 502: &whence,
503: "is invalid whence, valid are 'cur' or 'set'");
1.157 paf 504: }
1.133 paf 505:
1.182 paf 506: Value& offset_expr=params.as_junction(params.count()-1, "offset must be expression");
1.147 paf 507: table.offset(absolute, r.process_to_value(offset_expr).as_int());
1.151 paf 508: } else
1.182 paf 509: r.write_no_lang(*new VInt(table.current()));
1.6 paf 510: }
511:
1.182 paf 512: static void _menu(Request& r, MethodParams& params) {
513: Value& body_code=params.as_junction(0, "body must be code");
1.7 paf 514:
1.182 paf 515: Value* delim_maybe_code=params.count()>1?¶ms[1]:0;
1.7 paf 516:
1.182 paf 517: Table& table=GET_SELF(r, VTable).table();
1.7 paf 518: bool need_delim=false;
1.99 parser 519: int saved_current=table.current();
1.182 paf 520: int size=table.count();
1.99 parser 521: for(int row=0; row<size; row++) {
1.22 paf 522: table.set_current(row);
1.7 paf 523:
1.161 paf 524: StringOrValue sv_processed=r.process(body_code);
1.182 paf 525: const String* s_processed=sv_processed.get_string();
526: if(delim_maybe_code && s_processed && s_processed->length()) { // delimiter set and we have body
1.161 paf 527: if(need_delim) // need delim & iteration produced string?
1.150 paf 528: r.write_pass_lang(r.process(*delim_maybe_code));
1.7 paf 529: need_delim=true;
530: }
1.161 paf 531: r.write_pass_lang(sv_processed);
1.7 paf 532: }
1.99 parser 533: table.set_current(saved_current);
1.7 paf 534: }
535:
1.110 parser 536: #ifndef DOXYGEN
1.174 paf 537: enum Table2hash_distint { D_ILLEGAL, D_FIRST, D_TABLES };
1.74 paf 538: struct Row_info {
1.166 paf 539: Request *r;
1.74 paf 540: Table *table;
1.182 paf 541: Value* key_code;
542: size_t key_field;
543: Array<int>* value_fields;
544: HashStringValue* hash;
1.174 paf 545: Table2hash_distint distinct;
1.182 paf 546: size_t row;
1.74 paf 547: };
1.110 parser 548: #endif
1.182 paf 549: static void table_row_to_hash(Table::element_type row, Row_info *info) {
550: const String* key;
551: if(info->key_code) {
552: info->table->set_current(info->row++); // change context row
553: StringOrValue sv_processed=info->r->process(*info->key_code);
1.166 paf 554: key=&sv_processed.as_string();
555: } else
1.182 paf 556: key=info->key_field<row->count()?row->get(info->key_field):0;
1.166 paf 557:
558: if(!key)
559: return; // ignore rows without key [too-short-record_array if-indexed]
1.74 paf 560:
1.182 paf 561: switch(info->distinct) {
1.174 paf 562: case D_ILLEGAL: case D_FIRST:
563: {
1.182 paf 564: VHash* vhash=new VHash;
565: HashStringValue& hash=vhash->hash();
566: for(Array_iterator<int> i(*info->value_fields); i.has_next(); ) {
567: size_t value_field=i.next();
568: if(value_field<row->count())
1.174 paf 569: hash.put(
1.182 paf 570: *info->table->columns()->get(value_field),
571: new VString(*row->get(value_field)));
1.174 paf 572: }
573:
1.182 paf 574: if(info->hash->put_dont_replace(*key, vhash)) // put. existed?
575: if(info->distinct==D_ILLEGAL)
1.174 paf 576: throw Exception("parser.runtime",
577: key,
578: "duplicate key");
579: }
580: break;
581: case D_TABLES:
582: {
1.182 paf 583: VTable* vtable=(VTable*)info->hash->get(*key); // put. table existed?
1.174 paf 584: Table* table;
585: if(vtable)
586: table=vtable->get_table();
587: else {
588: // no? creating table of same structure as source
1.179 paf 589: Table::Action_options table_options(0, 0);
1.182 paf 590: table=new Table(*info->table, table_options/*no rows, just structure*/);
591: info->hash->put(*key, new VTable(table));
1.174 paf 592: }
1.182 paf 593: *table+=row;
1.174 paf 594: }
595: break;
596: default:
597: throw Exception(0,
598: 0,
1.182 paf 599: "invalid distinct code (#%d)", info->distinct);
1.74 paf 600: }
601: }
1.182 paf 602: static void _hash(Request& r, MethodParams& params) {
603: Table& self_table=GET_SELF(r, VTable).table();
604: VHash& result=*new VHash;
605: if(Table::columns_type columns=self_table.columns())
606: if(columns->count()>0) {
1.174 paf 607: Table2hash_distint distinct=D_ILLEGAL;
1.182 paf 608: int param_index=params.count()-1;
1.166 paf 609: if(param_index>0) {
1.182 paf 610: if(HashStringValue* options=
611: params.as_no_junction(param_index, "param must not be code").get_hash()) {
1.166 paf 612: --param_index;
613: int valid_options=0;
1.182 paf 614: if(Value* vdistinct_code=options->get(sql_distinct_name)) {
1.166 paf 615: valid_options++;
1.174 paf 616: Value& vdistinct_value=r.process_to_value(*vdistinct_code);
617: if(vdistinct_value.is_string()) {
618: const String& sdistinct=*vdistinct_value.get_string();
619: if(sdistinct=="tables")
620: distinct=D_TABLES;
621: else
622: throw Exception("parser.runtime",
623: &sdistinct,
624: "must be 'tables' or true/false");
625: } else
626: distinct=vdistinct_value.as_bool()?D_FIRST:D_ILLEGAL;
1.166 paf 627: }
1.182 paf 628: if(valid_options!=options->count())
1.166 paf 629: throw Exception("parser.runtime",
1.182 paf 630: 0,
1.166 paf 631: "called with invalid option");
1.163 paf 632: }
633: }
634: if(param_index==2) // bad options param type
635: throw Exception("parser.runtime",
1.182 paf 636: 0,
1.163 paf 637: "options must be hash");
638:
1.182 paf 639: Array<int> value_fields;
1.163 paf 640: if(param_index>0) {
1.174 paf 641: if(distinct!=D_ILLEGAL && distinct!=D_FIRST)
642: throw Exception("parser.runtime",
643: 0,
644: "in distinct[tables] mode you may not specify value field(s)");
1.182 paf 645: Value& value_fields_param=params.as_no_junction(param_index, "value field(s) must not be code");
1.123 parser 646: if(value_fields_param.is_string()) {
1.182 paf 647: value_fields+=self_table.column_name2index(
648: *value_fields_param.get_string(), true);
649: } else if(Table* value_fields_table=value_fields_param.get_table()) {
650: for(Array_iterator<Table::element_type> i(*value_fields_table);
651: i.has_next(); ) {
652: const String& value_field_name
653: =*i.next()->get(0);
654: value_fields
655: +=self_table.column_name2index(value_field_name, true);
1.123 parser 656: }
657: } else
1.146 paf 658: throw Exception("parser.runtime",
1.182 paf 659: 0,
1.123 parser 660: "value field(s) must be string or self_table"
661: );
662: } else { // by all columns, including key
1.174 paf 663: if(!(distinct!=D_ILLEGAL && distinct!=D_FIRST))
1.182 paf 664: for(size_t i=0; i<columns->count(); i++)
1.174 paf 665: value_fields+=i;
1.74 paf 666: }
667:
1.182 paf 668:
669: {
670: Row_info info={0};
671: info.r=&r;
672: info.table=&self_table;
673: Value* key_param=¶ms[0];
674: info.key_code=key_param->get_junction()?key_param:0;
675: info.key_field=info.key_code?-1
676: :self_table.column_name2index(key_param->as_string(), true);
677: info.value_fields=&value_fields;
678: info.hash=&result.hash();
679: info.distinct=distinct;
680: info.row=0;
681:
682: int saved_current=self_table.current();
683: self_table.for_each(table_row_to_hash, &info);
684: self_table.set_current(saved_current);
685: }
1.74 paf 686: }
1.97 parser 687: r.write_no_lang(result);
1.74 paf 688: }
689:
1.110 parser 690: #ifndef DOXYGEN
1.78 paf 691: struct Table_seq_item {
1.182 paf 692: ArrayString* row;
1.34 paf 693: union {
1.182 paf 694: const char *c_str;
1.34 paf 695: double d;
696: } value;
1.32 paf 697: };
1.110 parser 698: #endif
1.34 paf 699: static int sort_cmp_string(const void *a, const void *b) {
700: return strcmp(
1.78 paf 701: static_cast<const Table_seq_item *>(a)->value.c_str,
702: static_cast<const Table_seq_item *>(b)->value.c_str
1.34 paf 703: );
704: }
705: static int sort_cmp_double(const void *a, const void *b) {
1.78 paf 706: double va=static_cast<const Table_seq_item *>(a)->value.d;
707: double vb=static_cast<const Table_seq_item *>(b)->value.d;
1.34 paf 708: if(va<vb)
709: return -1;
710: else if(va>vb)
711: return +1;
712: else
713: return 0;
714: }
1.182 paf 715: static void _sort(Request& r, MethodParams& params) {
716: Value& key_maker=params.as_junction(0, "key-maker must be code");
1.61 paf 717:
1.182 paf 718: bool reverse=params.count()>1/*..[desc|asc|]*/?
719: reverse=params.as_no_junction(1, "order must not be code").as_string()=="desc":
1.104 parser 720: false; // default=asc
1.32 paf 721:
1.182 paf 722: Table& old_table=GET_SELF(r, VTable).table();
723: Table& new_table=*new Table(old_table.columns());
1.34 paf 724:
1.182 paf 725: Table_seq_item* seq=new(PointerFreeGC) Table_seq_item[old_table.count()];
1.34 paf 726: int i;
727:
728: // calculate key values
729: bool key_values_are_strings=true;
1.182 paf 730: int old_count=old_table.count();
731: for(i=0; i<old_count; i++) {
1.101 parser 732: old_table.set_current(i);
1.32 paf 733: // calculate key value
1.182 paf 734: seq[i].row=old_table[i];
735: Value& value=r.process_to_value(key_maker).as_expr_result(true/*return string as-is*/);
1.34 paf 736: if(i==0) // determining key values type by first one
737: key_values_are_strings=value.is_string();
738:
739: if(key_values_are_strings)
740: seq[i].value.c_str=value.as_string().cstr();
741: else
742: seq[i].value.d=value.as_double();
1.32 paf 743: }
744: // sort keys
1.182 paf 745: _qsort(seq, old_count, sizeof(Table_seq_item),
1.34 paf 746: key_values_are_strings?sort_cmp_string:sort_cmp_double);
1.32 paf 747:
1.34 paf 748: // reorder table as they require in 'seq'
1.182 paf 749: for(i=0; i<old_count; i++)
750: new_table+=Table::element_type(seq[reverse?old_count-1-i:i].row);
751:
752: delete[] seq;
1.32 paf 753:
1.116 parser 754: // replace any previous table value
1.182 paf 755: GET_SELF(r, VTable).set_table(new_table);
1.32 paf 756: }
757:
1.176 paf 758: #ifndef DOXYGEN
1.182 paf 759: struct Expression_is_true_info {
1.176 paf 760: Request* r;
761: Value* expression_code;
762: };
763: #endif
1.182 paf 764: static bool expression_is_true(Table& self, void* ainfo) {
765: Expression_is_true_info& info=*static_cast<Expression_is_true_info*>(ainfo);
1.176 paf 766: return info.r->process_to_value(*info.expression_code).as_bool();
767: }
768: static bool _locate_expression(Table& table, Table::Action_options o,
1.182 paf 769: Request& r, MethodParams& params) {
770: check_option_param(o.defined, params, 1,
1.176 paf 771: "locate by expression only has parameters: expression and, maybe, options");
1.182 paf 772: Value& expression_code=params.as_junction(0, "must be expression");
1.145 paf 773:
1.182 paf 774: Expression_is_true_info info={&r, &expression_code};
775: return table.table_first_that(expression_is_true, &info, o);
1.145 paf 776: }
1.176 paf 777: static bool _locate_name_value(Table& table, Table::Action_options o,
1.182 paf 778: Request& r, MethodParams& params) {
779: check_option_param(o.defined, params, 2,
1.176 paf 780: "locate by locate by name has parameters: name, value and, maybe, options");
1.182 paf 781: const String& name=params.as_string(0, "column name must be string");
782: const String& value=params.as_string(1, "value must be string");
783: return table.locate(name, value, o);
784: }
785: static void _locate(Request& r, MethodParams& params) {
786: Table& table=GET_SELF(r, VTable).table();
1.72 paf 787:
1.182 paf 788: Table::Action_options o=get_action_options(r, params, table);
789:
790: bool result=params[0].get_junction()?
791: _locate_expression(table, o, r, params) :
792: _locate_name_value(table, o, r, params);
793: r.write_no_lang(*new VBool(result));
1.145 paf 794: }
1.182 paf 795:
796:
797: static void _flip(Request& r, MethodParams& params) {
798: Table& old_table=GET_SELF(r, VTable).table();
1.184 paf 799: Table& new_table=*new Table(0);
1.182 paf 800: if(size_t old_count=old_table.count())
801: if(size_t old_cols=old_table[0]->count())
802: for(size_t column=0; column<old_cols; column++) {
803: Table::element_type new_row(new ArrayString(old_count));
804: for(size_t i=0; i<old_count; i++) {
805: Table::element_type old_row=old_table[i];
806: *new_row+=column<old_row->count()?old_row->get(column):new String;
1.39 paf 807: }
1.182 paf 808: new_table+=new_row;
1.39 paf 809: }
810:
1.182 paf 811: r.write_no_lang(*new VTable(&new_table));
1.39 paf 812: }
813:
1.182 paf 814: static void _append(Request& r, MethodParams& params) {
1.134 paf 815: // data
1.182 paf 816: Temp_lang temp_lang(r, String::L_PASS_APPENDED);
817: const String& string=r.process_to_string(params.as_junction(0, "body must be code"));
1.41 paf 818:
819: // parse cells
1.182 paf 820: Table::element_type row=new ArrayString;
821: size_t pos_after=0;
822: string.split(*row, pos_after, "\t", String::L_AS_IS);
1.41 paf 823:
1.182 paf 824: GET_SELF(r, VTable).table()+=row;
1.41 paf 825: }
826:
1.182 paf 827: static void join_named_row(Table& src, Table* dest) {
828: Table::columns_type dest_columns=dest->columns();
829: size_t dest_columns_count=dest_columns->count();
830: Table::element_type dest_row(new ArrayString(dest_columns_count));
831: for(size_t dest_column=0; dest_column<dest_columns_count; dest_column++) {
832: const String* src_item=src.item(*dest_columns->get(dest_column));
833: *dest_row+=src_item?src_item:new String;
834: }
835: *dest+=dest_row;
836: }
837: static void join_nameless_row(Table& src, Table* dest) {
838: *dest+=src[src.current()];
839: }
840: static void _join(Request& r, MethodParams& params) {
841: Table* maybe_src=params.as_no_junction(0, "table ref must not be code").get_table();
1.42 paf 842: if(!maybe_src)
1.146 paf 843: throw Exception("parser.runtime",
1.182 paf 844: 0,
1.42 paf 845: "source is not a table");
1.176 paf 846: Table& src=*maybe_src;
847:
1.182 paf 848: Table::Action_options o=get_action_options(r, params, src);
849: check_option_param(o.defined, params, 1,
1.176 paf 850: "invalid extra parameter");
1.42 paf 851:
1.182 paf 852: Table& dest=GET_SELF(r, VTable).table();
1.42 paf 853: if(&src == &dest)
1.146 paf 854: throw Exception("parser.runtime",
1.182 paf 855: 0,
1.42 paf 856: "source and destination are same table");
857:
1.182 paf 858: if(Table::columns_type dest_columns=dest.columns()) // dest is named
859: src.table_for_each(join_named_row, &dest, o);
860: else // dest is nameless
861: src.table_for_each(join_nameless_row, &dest, o);
1.42 paf 862: }
863:
1.94 parser 864: #ifndef DOXYGEN
1.169 paf 865: class Table_sql_event_handlers: public SQL_Driver_query_event_handlers {
1.182 paf 866: ArrayString& columns;
867: ArrayString* row;
1.94 parser 868: public:
1.182 paf 869: Table* table;
870: public:
871: Table_sql_event_handlers() :
872: columns(*new ArrayString), row(0), table(0) {
1.94 parser 873: }
874:
1.182 paf 875: bool add_column(SQL_Error& error, const char *str, size_t length) {
1.170 paf 876: try {
1.182 paf 877: columns+=new String(str, length, true);
1.170 paf 878: return false;
879: } catch(...) {
880: error=SQL_Error("exception occured in Table_sql_event_handlers::add_column");
881: return true;
882: }
883: }
884: bool before_rows(SQL_Error& error) {
885: try {
1.182 paf 886: table=new Table(&columns);
1.170 paf 887: return false;
888: } catch(...) {
889: error=SQL_Error("exception occured in Table_sql_event_handlers::before_rows");
890: return true;
891: }
892: }
893: bool add_row(SQL_Error& error) {
894: try {
1.182 paf 895: *table+=row=new ArrayString;
1.170 paf 896: return false;
897: } catch(...) {
898: error=SQL_Error("exception occured in Table_sql_event_handlers::add_row");
899: return true;
900: }
901: }
1.182 paf 902: bool add_row_cell(SQL_Error& error, const char* str, size_t length) {
1.170 paf 903: try {
1.182 paf 904: String& cell=*new String;
905: if(length)
906: cell.append_know_length(str, length, String::L_TAINTED);
907: *row+=&cell;
1.170 paf 908: return false;
909: } catch(...) {
910: error=SQL_Error("exception occured in Table_sql_event_handlers::add_row_cell");
911: return true;
912: }
1.94 parser 913: }
914: };
915: #endif
1.182 paf 916: static void _sql(Request& r, MethodParams& params) {
917: Value& statement=params.as_junction(0, "statement must be code");
1.49 paf 918:
1.53 paf 919: ulong limit=0;
1.100 parser 920: ulong offset=0;
1.182 paf 921: if(params.count()>1) {
922: Value& voptions=params.as_no_junction(1, "options must be hash, not code");
1.156 paf 923: if(!voptions.is_string())
1.182 paf 924: if(HashStringValue* options=voptions.get_hash()) {
1.164 paf 925: int valid_options=0;
1.182 paf 926: if(Value* vlimit=options->get(sql_limit_name)) {
1.164 paf 927: valid_options++;
1.147 paf 928: limit=(ulong)r.process_to_value(*vlimit).as_double();
1.164 paf 929: }
1.182 paf 930: if(Value* voffset=options->get(sql_offset_name)) {
1.164 paf 931: valid_options++;
1.147 paf 932: offset=(ulong)r.process_to_value(*voffset).as_double();
1.164 paf 933: }
1.182 paf 934: if(valid_options!=options->count())
1.164 paf 935: throw Exception("parser.runtime",
1.182 paf 936: 0,
1.164 paf 937: "called with invalid option");
1.109 parser 938: } else
1.146 paf 939: throw Exception("parser.runtime",
1.182 paf 940: 0,
1.109 parser 941: "options must be hash");
1.49 paf 942: }
943:
1.182 paf 944: Temp_lang temp_lang(r, String::L_SQL);
945: const String& statement_string=r.process_to_string(statement);
946: const char* statement_cstr=
947: statement_string.cstr(String::L_UNSPECIFIED, r.connection());
948: Table_sql_event_handlers handlers;
1.135 paf 949: #ifdef RESOURCES_DEBUG
950: struct timeval mt[2];
951: //measure:before
952: gettimeofday(&mt[0],NULL);
953: #endif
1.182 paf 954: r.connection()->query(
1.160 paf 955: statement_cstr, offset, limit,
956: handlers,
957: statement_string);
1.135 paf 958:
959: #ifdef RESOURCES_DEBUG
960: //measure:after connect
961: gettimeofday(&mt[1],NULL);
962:
963: double t[2];
964: for(int i=0;i<2;i++)
965: t[i]=mt[i].tv_sec+mt[i].tv_usec/1000000.0;
966:
967: r.sql_request_time+=t[1]-t[0];
968: #endif
1.96 parser 969:
1.182 paf 970: Table& result=
971: handlers.table?*handlers.table: // query resulted in table? return it
972: *new Table(Table::columns_type(0)); // query returned no table, fake it
1.49 paf 973:
974: // replace any previous table value
1.182 paf 975: GET_SELF(r, VTable).set_table(result);
1.49 paf 976: }
977:
1.182 paf 978: static void _columns(Request& r, MethodParams&) {
1.88 parser 979:
1.182 paf 980: Table::columns_type result_columns(new ArrayString);
981: *result_columns+=new String("column");
982: Table& result_table=*new Table(result_columns);
1.88 parser 983:
1.182 paf 984: Table& source_table=GET_SELF(r, VTable).table();
985: if(Table::columns_type source_columns=source_table.columns()) {
986: for(Array_iterator<const String*> i(*source_columns); i.has_next(); ) {
987: Table::element_type result_row(new ArrayString);
988: *result_row+=i.next();
989: result_table+=result_row;
1.88 parser 990: }
991: }
992:
1.182 paf 993: r.write_no_lang(*new VTable(&result_table));
1.88 parser 994: }
995:
1.182 paf 996: static void _select(Request& r, MethodParams& params) {
997: Value& vcondition=params.as_junction(0, "condition must be expression");
1.148 paf 998:
1.182 paf 999: Table& source_table=GET_SELF(r, VTable).table();
1000: Table& result_table=*new Table(source_table.columns());
1.148 paf 1001:
1002: int saved_current=source_table.current();
1.182 paf 1003: int size=source_table.count();
1.148 paf 1004: for(int row=0; row<size; row++) {
1005: source_table.set_current(row);
1006:
1.150 paf 1007: bool condition=r.process_to_value(vcondition,
1.149 paf 1008: /*0/*no name* /,*/
1.148 paf 1009: false/*don't intercept string*/).as_bool();
1010:
1011: if(condition) // ...condition is true=
1.182 paf 1012: result_table+=source_table[row]; // =green light to go to result
1.148 paf 1013: }
1014: source_table.set_current(saved_current);
1015:
1.182 paf 1016: r.write_no_lang(*new VTable(&result_table));
1.148 paf 1017: }
1018:
1.66 paf 1019: // constructor
1020:
1.182 paf 1021: MTable::MTable(): Methoded("table") {
1.142 paf 1022: // ^table::create{data}
1023: // ^table::create[nameless]{data}
1024: // ^table::create[table]
1025: add_native_method("create", Method::CT_DYNAMIC, _create, 1, 2);
1026: // old name for compatibility with <= v 1.141 2002/01/25 11:33:45 paf
1027: add_native_method("set", Method::CT_DYNAMIC, _create, 1, 2);
1.2 paf 1028:
1.142 paf 1029: // ^table::load[file]
1030: // ^table::load[nameless;file]
1.168 paf 1031: add_native_method("load", Method::CT_DYNAMIC, _load, 1, 3);
1.22 paf 1032:
1033: // ^table.save[file]
1034: // ^table.save[nameless;file]
1.188 paf 1035: add_native_method("save", Method::CT_DYNAMIC, _save, 1, 3);
1.6 paf 1036:
1037: // ^table.count[]
1.66 paf 1038: add_native_method("count", Method::CT_DYNAMIC, _count, 0, 0);
1.6 paf 1039:
1040: // ^table.line[]
1.66 paf 1041: add_native_method("line", Method::CT_DYNAMIC, _line, 0, 0);
1.6 paf 1042:
1.10 paf 1043: // ^table.offset[]
1.133 paf 1044: // ^table.offset(offset)
1045: // ^table.offset[cur|set](offset)
1046: add_native_method("offset", Method::CT_DYNAMIC, _offset, 0, 2);
1.7 paf 1047:
1.10 paf 1048: // ^table.menu{code}
1049: // ^table.menu{code}[delim]
1.66 paf 1050: add_native_method("menu", Method::CT_DYNAMIC, _menu, 1, 2);
1.74 paf 1051:
1.79 paf 1052: // ^table:hash[key field name]
1.123 parser 1053: // ^table:hash[key field name][value field name(s) string/table]
1.163 paf 1054: add_native_method("hash", Method::CT_DYNAMIC, _hash, 1, 3);
1.32 paf 1055:
1.102 parser 1056: // ^table.sort{string-key-maker} ^table.sort{string-key-maker}[desc|asc]
1057: // ^table.sort(numeric-key-maker) ^table.sort(numeric-key-maker)[desc|asc]
1.66 paf 1058: add_native_method("sort", Method::CT_DYNAMIC, _sort, 1, 2);
1.8 paf 1059:
1.36 paf 1060: // ^table.locate[field;value]
1.176 paf 1061: add_native_method("locate", Method::CT_DYNAMIC, _locate, 1, 3);
1.39 paf 1062:
1063: // ^table.flip[]
1.66 paf 1064: add_native_method("flip", Method::CT_DYNAMIC, _flip, 0, 0);
1.41 paf 1065:
1066: // ^table.append{r{tab}e{tab}c{tab}o{tab}r{tab}d}
1.66 paf 1067: add_native_method("append", Method::CT_DYNAMIC, _append, 1, 1);
1.42 paf 1068:
1.157 paf 1069: // ^table.join[table][$.limit(10) $.offset(1) $.offset[cur] ]
1070: add_native_method("join", Method::CT_DYNAMIC, _join, 1, 2);
1.49 paf 1071:
1072:
1.100 parser 1073: // ^table:sql[query]
1074: // ^table:sql[query][$.limit(1) $.offset(2)]
1075: add_native_method("sql", Method::CT_DYNAMIC, _sql, 1, 2);
1.88 parser 1076:
1077: // ^table:columns[]
1078: add_native_method("columns", Method::CT_DYNAMIC, _columns, 0, 0);
1.148 paf 1079:
1080: // ^table.select(expression) = table
1081: add_native_method("select", Method::CT_DYNAMIC, _select, 1, 1);
1.40 paf 1082: }
E-mail: