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