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