Annotation of parser3/src/classes/table.C, revision 1.222
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:
1.222 ! paf 8: static const char * const IDENT_TABLE_C="$Date: 2006/04/09 13:38:47 $";
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()) {
1.222 ! paf 402: Value& voptions=params.as_no_junction(param_index++, "additional params must be hash");
! 403: if( voptions.is_defined() && !voptions.is_string() ) {
! 404: if(HashStringValue* options=voptions.get_hash()) {
1.214 paf 405: int valid_options=separators.load(*options);
406: if(valid_options!=options->count())
1.188 paf 407: throw Exception("parser.runtime",
408: 0,
409: "invalid option passed");
410: } else
411: throw Exception("parser.runtime",
412: 0,
413: "additional params must be hash (did you spell mode parameter correctly?)");
1.222 ! paf 414: }
1.188 paf 415: }
416: if(param_index<params.count())
417: throw Exception("parser.runtime",
418: 0,
419: "bad mode (must be nameless or append)");
1.22 paf 420:
1.182 paf 421: Table& table=GET_SELF(r, VTable).table();
1.31 paf 422:
1.182 paf 423: String sdata;
1.188 paf 424: if(output_column_names) {
1.31 paf 425: if(table.columns()) { // named table
1.182 paf 426: for(Array_iterator<const String*> i(*table.columns()); i.has_next(); ) {
1.188 paf 427: maybe_enclose( sdata, *i.next(), separators.encloser, separators.sencloser );
1.98 parser 428: if(i.has_next())
1.206 paf 429: sdata<<*separators.scolumn;
1.31 paf 430: }
1.188 paf 431: } else { // nameless table [we were asked to output column names]
1.182 paf 432: if(int lsize=table.count()?table[0]->count():0)
1.31 paf 433: for(int column=0; column<lsize; column++) {
1.182 paf 434: char *cindex_tab=new(PointerFreeGC) char[MAX_NUMBER];
435: sdata.append_know_length(cindex_tab,
1.185 paf 436: snprintf(cindex_tab, MAX_NUMBER,
1.206 paf 437: column<lsize-1?"%d%c":"%d", column, separators.column),
1.185 paf 438: String::L_CLEAN);
1.31 paf 439: }
440: else
1.182 paf 441: sdata.append_help_length("empty nameless table", 0, String::L_CLEAN);
1.31 paf 442: }
1.182 paf 443: sdata.append_know_length("\n", 1, String::L_CLEAN);
1.188 paf 444: }
1.129 paf 445:
1.31 paf 446: // data lines
1.182 paf 447: Array_iterator<ArrayString*> i(table);
1.98 parser 448: while(i.has_next()) {
1.182 paf 449: for(Array_iterator<const String*> c(*i.next()); c.has_next(); ) {
1.188 paf 450: maybe_enclose( sdata, *c.next(), separators.encloser, separators.sencloser );
1.98 parser 451: if(c.has_next())
1.206 paf 452: sdata<<*separators.scolumn;
1.31 paf 453: }
1.182 paf 454: sdata.append_know_length("\n", 1, String::L_CLEAN);
1.31 paf 455: }
456:
457: // write
1.217 paf 458: {
459: const char* data_cstr=sdata.cstr();
460: file_write(r.absolute(file_name),
461: data_cstr, sdata.length(), true, do_append);
462: if(*data_cstr) // not empty (when empty it's not heap memory)
463: pa_free((void*)data_cstr); // not needed anymore
464: }
1.22 paf 465: }
466:
1.182 paf 467: static void _count(Request& r, MethodParams&) {
468: int result=GET_SELF(r, VTable).table().count();
469: r.write_no_lang(*new VInt(result));
1.6 paf 470: }
471:
1.182 paf 472: static void _line(Request& r, MethodParams&) {
473: int result=1+GET_SELF(r, VTable).table().current();
474: r.write_no_lang(*new VInt(result));
1.6 paf 475: }
476:
1.182 paf 477: static void _offset(Request& r, MethodParams& params) {
478: Table& table=GET_SELF(r, VTable).table();
479: if(params.count()) {
1.133 paf 480: bool absolute=false;
1.182 paf 481: if(params.count()>1) {
482: const String& whence=params.as_string(0, "whence must be string");
1.133 paf 483: if(whence=="cur")
1.134 paf 484: absolute=false;
1.133 paf 485: else if(whence=="set")
1.134 paf 486: absolute=true;
1.133 paf 487: else
1.146 paf 488: throw Exception("parser.runtime",
1.134 paf 489: &whence,
490: "is invalid whence, valid are 'cur' or 'set'");
1.157 paf 491: }
1.133 paf 492:
1.211 paf 493: int offset=params.as_int(params.count()-1, "offset must be expression", r);
494: table.offset(absolute, offset);
1.151 paf 495: } else
1.182 paf 496: r.write_no_lang(*new VInt(table.current()));
1.6 paf 497: }
498:
1.182 paf 499: static void _menu(Request& r, MethodParams& params) {
1.221 paf 500: Temp_hash_value<const String::Body, void*>
501: cycle_data_setter(r.classes_conf, cycle_data_name, /*any not null flag*/&r);
502:
1.182 paf 503: Value& body_code=params.as_junction(0, "body must be code");
1.7 paf 504:
1.182 paf 505: Value* delim_maybe_code=params.count()>1?¶ms[1]:0;
1.7 paf 506:
1.182 paf 507: Table& table=GET_SELF(r, VTable).table();
1.7 paf 508: bool need_delim=false;
1.99 parser 509: int saved_current=table.current();
1.182 paf 510: int size=table.count();
1.99 parser 511: for(int row=0; row<size; row++) {
1.22 paf 512: table.set_current(row);
1.7 paf 513:
1.161 paf 514: StringOrValue sv_processed=r.process(body_code);
1.221 paf 515: Request::Skip lskip=r.get_skip(); r.set_skip(Request::SKIP_NOTHING);
1.182 paf 516: const String* s_processed=sv_processed.get_string();
517: if(delim_maybe_code && s_processed && s_processed->length()) { // delimiter set and we have body
1.161 paf 518: if(need_delim) // need delim & iteration produced string?
1.150 paf 519: r.write_pass_lang(r.process(*delim_maybe_code));
1.7 paf 520: need_delim=true;
521: }
1.161 paf 522: r.write_pass_lang(sv_processed);
1.221 paf 523:
524: if(lskip==Request::SKIP_BREAK)
525: break;
1.7 paf 526: }
1.99 parser 527: table.set_current(saved_current);
1.7 paf 528: }
529:
1.110 parser 530: #ifndef DOXYGEN
1.174 paf 531: enum Table2hash_distint { D_ILLEGAL, D_FIRST, D_TABLES };
1.74 paf 532: struct Row_info {
1.166 paf 533: Request *r;
1.74 paf 534: Table *table;
1.182 paf 535: Value* key_code;
536: size_t key_field;
537: Array<int>* value_fields;
538: HashStringValue* hash;
1.174 paf 539: Table2hash_distint distinct;
1.182 paf 540: size_t row;
1.74 paf 541: };
1.110 parser 542: #endif
1.182 paf 543: static void table_row_to_hash(Table::element_type row, Row_info *info) {
544: const String* key;
545: if(info->key_code) {
546: info->table->set_current(info->row++); // change context row
547: StringOrValue sv_processed=info->r->process(*info->key_code);
1.166 paf 548: key=&sv_processed.as_string();
549: } else
1.182 paf 550: key=info->key_field<row->count()?row->get(info->key_field):0;
1.166 paf 551:
552: if(!key)
553: return; // ignore rows without key [too-short-record_array if-indexed]
1.74 paf 554:
1.182 paf 555: switch(info->distinct) {
1.174 paf 556: case D_ILLEGAL: case D_FIRST:
557: {
1.182 paf 558: VHash* vhash=new VHash;
559: HashStringValue& hash=vhash->hash();
560: for(Array_iterator<int> i(*info->value_fields); i.has_next(); ) {
561: size_t value_field=i.next();
562: if(value_field<row->count())
1.174 paf 563: hash.put(
1.182 paf 564: *info->table->columns()->get(value_field),
565: new VString(*row->get(value_field)));
1.174 paf 566: }
567:
1.182 paf 568: if(info->hash->put_dont_replace(*key, vhash)) // put. existed?
569: if(info->distinct==D_ILLEGAL)
1.174 paf 570: throw Exception("parser.runtime",
571: key,
572: "duplicate key");
573: }
574: break;
575: case D_TABLES:
576: {
1.182 paf 577: VTable* vtable=(VTable*)info->hash->get(*key); // put. table existed?
1.174 paf 578: Table* table;
579: if(vtable)
580: table=vtable->get_table();
581: else {
582: // no? creating table of same structure as source
1.179 paf 583: Table::Action_options table_options(0, 0);
1.182 paf 584: table=new Table(*info->table, table_options/*no rows, just structure*/);
585: info->hash->put(*key, new VTable(table));
1.174 paf 586: }
1.182 paf 587: *table+=row;
1.174 paf 588: }
589: break;
590: default:
591: throw Exception(0,
592: 0,
1.182 paf 593: "invalid distinct code (#%d)", info->distinct);
1.74 paf 594: }
595: }
1.182 paf 596: static void _hash(Request& r, MethodParams& params) {
597: Table& self_table=GET_SELF(r, VTable).table();
598: VHash& result=*new VHash;
599: if(Table::columns_type columns=self_table.columns())
600: if(columns->count()>0) {
1.174 paf 601: Table2hash_distint distinct=D_ILLEGAL;
1.182 paf 602: int param_index=params.count()-1;
1.166 paf 603: if(param_index>0) {
1.182 paf 604: if(HashStringValue* options=
605: params.as_no_junction(param_index, "param must not be code").get_hash()) {
1.166 paf 606: --param_index;
607: int valid_options=0;
1.182 paf 608: if(Value* vdistinct_code=options->get(sql_distinct_name)) {
1.166 paf 609: valid_options++;
1.174 paf 610: Value& vdistinct_value=r.process_to_value(*vdistinct_code);
611: if(vdistinct_value.is_string()) {
612: const String& sdistinct=*vdistinct_value.get_string();
613: if(sdistinct=="tables")
614: distinct=D_TABLES;
615: else
616: throw Exception("parser.runtime",
617: &sdistinct,
618: "must be 'tables' or true/false");
619: } else
620: distinct=vdistinct_value.as_bool()?D_FIRST:D_ILLEGAL;
1.166 paf 621: }
1.182 paf 622: if(valid_options!=options->count())
1.166 paf 623: throw Exception("parser.runtime",
1.182 paf 624: 0,
1.166 paf 625: "called with invalid option");
1.163 paf 626: }
627: }
628: if(param_index==2) // bad options param type
629: throw Exception("parser.runtime",
1.182 paf 630: 0,
1.163 paf 631: "options must be hash");
632:
1.182 paf 633: Array<int> value_fields;
1.163 paf 634: if(param_index>0) {
1.174 paf 635: if(distinct!=D_ILLEGAL && distinct!=D_FIRST)
636: throw Exception("parser.runtime",
637: 0,
638: "in distinct[tables] mode you may not specify value field(s)");
1.182 paf 639: Value& value_fields_param=params.as_no_junction(param_index, "value field(s) must not be code");
1.123 parser 640: if(value_fields_param.is_string()) {
1.182 paf 641: value_fields+=self_table.column_name2index(
642: *value_fields_param.get_string(), true);
643: } else if(Table* value_fields_table=value_fields_param.get_table()) {
644: for(Array_iterator<Table::element_type> i(*value_fields_table);
645: i.has_next(); ) {
646: const String& value_field_name
647: =*i.next()->get(0);
648: value_fields
649: +=self_table.column_name2index(value_field_name, true);
1.123 parser 650: }
651: } else
1.146 paf 652: throw Exception("parser.runtime",
1.182 paf 653: 0,
1.197 paf 654: "value field(s) must be string or table"
1.123 parser 655: );
656: } else { // by all columns, including key
1.174 paf 657: if(!(distinct!=D_ILLEGAL && distinct!=D_FIRST))
1.182 paf 658: for(size_t i=0; i<columns->count(); i++)
1.174 paf 659: value_fields+=i;
1.74 paf 660: }
661:
1.182 paf 662:
663: {
664: Value* key_param=¶ms[0];
1.193 paf 665: Row_info info={
666: &r,
667: &self_table,
668: /*key_code=*/key_param->get_junction()?key_param:0,
1.197 paf 669: /*key_field=*/0/*filled below*/,
1.193 paf 670: &value_fields,
671: &result.hash(),
672: distinct,
673: /*row=*/0
674: };
1.195 paf 675: info.key_field=(info.key_code?-1
676: :self_table.column_name2index(key_param->as_string(), true));
1.182 paf 677:
678: int saved_current=self_table.current();
679: self_table.for_each(table_row_to_hash, &info);
680: self_table.set_current(saved_current);
1.207 paf 681:
682: result.extract_default();
1.182 paf 683: }
1.74 paf 684: }
1.97 parser 685: r.write_no_lang(result);
1.74 paf 686: }
687:
1.110 parser 688: #ifndef DOXYGEN
1.78 paf 689: struct Table_seq_item {
1.182 paf 690: ArrayString* row;
1.34 paf 691: union {
1.182 paf 692: const char *c_str;
1.34 paf 693: double d;
694: } value;
1.32 paf 695: };
1.110 parser 696: #endif
1.34 paf 697: static int sort_cmp_string(const void *a, const void *b) {
698: return strcmp(
1.78 paf 699: static_cast<const Table_seq_item *>(a)->value.c_str,
700: static_cast<const Table_seq_item *>(b)->value.c_str
1.34 paf 701: );
702: }
703: static int sort_cmp_double(const void *a, const void *b) {
1.78 paf 704: double va=static_cast<const Table_seq_item *>(a)->value.d;
705: double vb=static_cast<const Table_seq_item *>(b)->value.d;
1.34 paf 706: if(va<vb)
707: return -1;
708: else if(va>vb)
709: return +1;
710: else
711: return 0;
712: }
1.182 paf 713: static void _sort(Request& r, MethodParams& params) {
714: Value& key_maker=params.as_junction(0, "key-maker must be code");
1.61 paf 715:
1.182 paf 716: bool reverse=params.count()>1/*..[desc|asc|]*/?
717: reverse=params.as_no_junction(1, "order must not be code").as_string()=="desc":
1.104 parser 718: false; // default=asc
1.32 paf 719:
1.182 paf 720: Table& old_table=GET_SELF(r, VTable).table();
721: Table& new_table=*new Table(old_table.columns());
1.34 paf 722:
1.182 paf 723: Table_seq_item* seq=new(PointerFreeGC) Table_seq_item[old_table.count()];
1.34 paf 724: int i;
725:
726: // calculate key values
727: bool key_values_are_strings=true;
1.182 paf 728: int old_count=old_table.count();
729: for(i=0; i<old_count; i++) {
1.101 parser 730: old_table.set_current(i);
1.32 paf 731: // calculate key value
1.182 paf 732: seq[i].row=old_table[i];
733: Value& value=r.process_to_value(key_maker).as_expr_result(true/*return string as-is*/);
1.34 paf 734: if(i==0) // determining key values type by first one
735: key_values_are_strings=value.is_string();
736:
737: if(key_values_are_strings)
738: seq[i].value.c_str=value.as_string().cstr();
739: else
740: seq[i].value.d=value.as_double();
1.32 paf 741: }
742: // sort keys
1.182 paf 743: _qsort(seq, old_count, sizeof(Table_seq_item),
1.34 paf 744: key_values_are_strings?sort_cmp_string:sort_cmp_double);
1.32 paf 745:
1.34 paf 746: // reorder table as they require in 'seq'
1.182 paf 747: for(i=0; i<old_count; i++)
748: new_table+=Table::element_type(seq[reverse?old_count-1-i:i].row);
749:
750: delete[] seq;
1.32 paf 751:
1.116 parser 752: // replace any previous table value
1.182 paf 753: GET_SELF(r, VTable).set_table(new_table);
1.32 paf 754: }
755:
1.176 paf 756: #ifndef DOXYGEN
1.182 paf 757: struct Expression_is_true_info {
1.176 paf 758: Request* r;
759: Value* expression_code;
760: };
761: #endif
1.191 paf 762: static bool expression_is_true(Table&, Expression_is_true_info* info) {
763: return info->r->process_to_value(*info->expression_code).as_bool();
1.176 paf 764: }
765: static bool _locate_expression(Table& table, Table::Action_options o,
1.182 paf 766: Request& r, MethodParams& params) {
767: check_option_param(o.defined, params, 1,
1.176 paf 768: "locate by expression only has parameters: expression and, maybe, options");
1.182 paf 769: Value& expression_code=params.as_junction(0, "must be expression");
1.145 paf 770:
1.182 paf 771: Expression_is_true_info info={&r, &expression_code};
772: return table.table_first_that(expression_is_true, &info, o);
1.145 paf 773: }
1.176 paf 774: static bool _locate_name_value(Table& table, Table::Action_options o,
1.191 paf 775: Request&, MethodParams& params) {
1.182 paf 776: check_option_param(o.defined, params, 2,
1.176 paf 777: "locate by locate by name has parameters: name, value and, maybe, options");
1.182 paf 778: const String& name=params.as_string(0, "column name must be string");
779: const String& value=params.as_string(1, "value must be string");
780: return table.locate(name, value, o);
781: }
782: static void _locate(Request& r, MethodParams& params) {
783: Table& table=GET_SELF(r, VTable).table();
1.72 paf 784:
1.182 paf 785: Table::Action_options o=get_action_options(r, params, table);
786:
787: bool result=params[0].get_junction()?
788: _locate_expression(table, o, r, params) :
789: _locate_name_value(table, o, r, params);
790: r.write_no_lang(*new VBool(result));
1.145 paf 791: }
1.182 paf 792:
793:
1.191 paf 794: static void _flip(Request& r, MethodParams&) {
1.182 paf 795: Table& old_table=GET_SELF(r, VTable).table();
1.184 paf 796: Table& new_table=*new Table(0);
1.182 paf 797: if(size_t old_count=old_table.count())
798: if(size_t old_cols=old_table[0]->count())
799: for(size_t column=0; column<old_cols; column++) {
800: Table::element_type new_row(new ArrayString(old_count));
801: for(size_t i=0; i<old_count; i++) {
802: Table::element_type old_row=old_table[i];
803: *new_row+=column<old_row->count()?old_row->get(column):new String;
1.39 paf 804: }
1.182 paf 805: new_table+=new_row;
1.39 paf 806: }
807:
1.182 paf 808: r.write_no_lang(*new VTable(&new_table));
1.39 paf 809: }
810:
1.182 paf 811: static void _append(Request& r, MethodParams& params) {
1.134 paf 812: // data
1.182 paf 813: Temp_lang temp_lang(r, String::L_PASS_APPENDED);
814: const String& string=r.process_to_string(params.as_junction(0, "body must be code"));
1.41 paf 815:
816: // parse cells
1.182 paf 817: Table::element_type row=new ArrayString;
818: size_t pos_after=0;
819: string.split(*row, pos_after, "\t", String::L_AS_IS);
1.41 paf 820:
1.182 paf 821: GET_SELF(r, VTable).table()+=row;
1.41 paf 822: }
823:
1.182 paf 824: static void join_named_row(Table& src, Table* dest) {
825: Table::columns_type dest_columns=dest->columns();
826: size_t dest_columns_count=dest_columns->count();
827: Table::element_type dest_row(new ArrayString(dest_columns_count));
828: for(size_t dest_column=0; dest_column<dest_columns_count; dest_column++) {
829: const String* src_item=src.item(*dest_columns->get(dest_column));
830: *dest_row+=src_item?src_item:new String;
831: }
832: *dest+=dest_row;
833: }
834: static void join_nameless_row(Table& src, Table* dest) {
835: *dest+=src[src.current()];
836: }
837: static void _join(Request& r, MethodParams& params) {
838: Table* maybe_src=params.as_no_junction(0, "table ref must not be code").get_table();
1.42 paf 839: if(!maybe_src)
1.146 paf 840: throw Exception("parser.runtime",
1.182 paf 841: 0,
1.42 paf 842: "source is not a table");
1.176 paf 843: Table& src=*maybe_src;
844:
1.182 paf 845: Table::Action_options o=get_action_options(r, params, src);
846: check_option_param(o.defined, params, 1,
1.176 paf 847: "invalid extra parameter");
1.42 paf 848:
1.182 paf 849: Table& dest=GET_SELF(r, VTable).table();
1.42 paf 850: if(&src == &dest)
1.146 paf 851: throw Exception("parser.runtime",
1.182 paf 852: 0,
1.42 paf 853: "source and destination are same table");
854:
1.193 paf 855: if(dest.columns()) // dest is named
1.182 paf 856: src.table_for_each(join_named_row, &dest, o);
857: else // dest is nameless
858: src.table_for_each(join_nameless_row, &dest, o);
1.42 paf 859: }
860:
1.94 parser 861: #ifndef DOXYGEN
1.169 paf 862: class Table_sql_event_handlers: public SQL_Driver_query_event_handlers {
1.182 paf 863: ArrayString& columns;
1.218 paf 864: int columns_count;
1.182 paf 865: ArrayString* row;
1.94 parser 866: public:
1.182 paf 867: Table* table;
868: public:
869: Table_sql_event_handlers() :
870: columns(*new ArrayString), row(0), table(0) {
1.94 parser 871: }
872:
1.182 paf 873: bool add_column(SQL_Error& error, const char *str, size_t length) {
1.170 paf 874: try {
1.182 paf 875: columns+=new String(str, length, true);
1.170 paf 876: return false;
877: } catch(...) {
878: error=SQL_Error("exception occured in Table_sql_event_handlers::add_column");
879: return true;
880: }
881: }
882: bool before_rows(SQL_Error& error) {
883: try {
1.182 paf 884: table=new Table(&columns);
1.218 paf 885: columns_count=columns.count();
1.170 paf 886: return false;
887: } catch(...) {
888: error=SQL_Error("exception occured in Table_sql_event_handlers::before_rows");
889: return true;
890: }
891: }
892: bool add_row(SQL_Error& error) {
893: try {
1.218 paf 894: *table+=row=new ArrayString(columns_count);
1.170 paf 895: return false;
896: } catch(...) {
897: error=SQL_Error("exception occured in Table_sql_event_handlers::add_row");
898: return true;
899: }
900: }
1.182 paf 901: bool add_row_cell(SQL_Error& error, const char* str, size_t length) {
1.170 paf 902: try {
1.182 paf 903: String& cell=*new String;
904: if(length)
905: cell.append_know_length(str, length, String::L_TAINTED);
906: *row+=&cell;
1.170 paf 907: return false;
908: } catch(...) {
909: error=SQL_Error("exception occured in Table_sql_event_handlers::add_row_cell");
910: return true;
911: }
1.94 parser 912: }
913: };
914: #endif
1.204 paf 915:
916: static void marshal_bind(
917: HashStringValue::key_type aname,
918: HashStringValue::value_type avalue,
919: SQL_Driver::Placeholder** pptr)
920: {
921: SQL_Driver::Placeholder& ph=**pptr;
922: ph.name=aname.cstr();
1.205 paf 923: ph.value=avalue->as_string().cstr(String::L_UNSPECIFIED);
1.204 paf 924: ph.is_null=avalue->get_class()==void_class;
925: ph.were_updated=false;
926:
927: (*pptr)++;
928: }
929:
930: // not static, used elsewhere
931: int marshal_binds(HashStringValue& hash, SQL_Driver::Placeholder*& placeholders) {
932: int hash_count=hash.count();
933: placeholders=new(UseGC) SQL_Driver::Placeholder[hash_count];
934: SQL_Driver::Placeholder* ptr=placeholders;
1.221 paf 935: hash.for_each<SQL_Driver::Placeholder**>(marshal_bind, &ptr);
1.204 paf 936: return hash_count;
937: }
938:
939: // not static, used elsewhere
940: void unmarshal_bind_updates(HashStringValue& hash, int placeholder_count, SQL_Driver::Placeholder* placeholders) {
941: SQL_Driver::Placeholder* ph=placeholders;
942: for(int i=0; i<placeholder_count; i++, ph++)
943: if(ph->were_updated) {
944: Value* value;
945: if(ph->is_null)
946: value=new VVoid();
947: else
948: if(ph->value)
949: value=new VString(*new String(ph->value, 0, true/*tainted*/));
950: else
951: value=new VString(*new String());
952: hash.put(ph->name, value);
953: }
954: }
955:
1.182 paf 956: static void _sql(Request& r, MethodParams& params) {
957: Value& statement=params.as_junction(0, "statement must be code");
1.49 paf 958:
1.204 paf 959: HashStringValue* bind=0;
1.53 paf 960: ulong limit=0;
1.100 parser 961: ulong offset=0;
1.182 paf 962: if(params.count()>1) {
963: Value& voptions=params.as_no_junction(1, "options must be hash, not code");
1.212 paf 964: if(voptions.is_defined() && !voptions.is_string())
1.182 paf 965: if(HashStringValue* options=voptions.get_hash()) {
1.164 paf 966: int valid_options=0;
1.204 paf 967: if(Value* vbind=options->get(sql_bind_name)) {
968: valid_options++;
969: bind=vbind->get_hash();
970: }
1.182 paf 971: if(Value* vlimit=options->get(sql_limit_name)) {
1.164 paf 972: valid_options++;
1.147 paf 973: limit=(ulong)r.process_to_value(*vlimit).as_double();
1.164 paf 974: }
1.182 paf 975: if(Value* voffset=options->get(sql_offset_name)) {
1.164 paf 976: valid_options++;
1.147 paf 977: offset=(ulong)r.process_to_value(*voffset).as_double();
1.164 paf 978: }
1.182 paf 979: if(valid_options!=options->count())
1.164 paf 980: throw Exception("parser.runtime",
1.182 paf 981: 0,
1.164 paf 982: "called with invalid option");
1.109 parser 983: } else
1.146 paf 984: throw Exception("parser.runtime",
1.182 paf 985: 0,
1.109 parser 986: "options must be hash");
1.49 paf 987: }
988:
1.204 paf 989: SQL_Driver::Placeholder* placeholders=0;
990: uint placeholders_count=0;
991: if(bind)
992: placeholders_count=marshal_binds(*bind, placeholders);
993:
1.182 paf 994: Temp_lang temp_lang(r, String::L_SQL);
995: const String& statement_string=r.process_to_string(statement);
996: const char* statement_cstr=
997: statement_string.cstr(String::L_UNSPECIFIED, r.connection());
998: Table_sql_event_handlers handlers;
1.135 paf 999: #ifdef RESOURCES_DEBUG
1000: struct timeval mt[2];
1001: //measure:before
1002: gettimeofday(&mt[0],NULL);
1003: #endif
1.182 paf 1004: r.connection()->query(
1.203 paf 1005: statement_cstr,
1.208 paf 1006: placeholders_count, placeholders,
1.203 paf 1007: offset, limit,
1.160 paf 1008: handlers,
1009: statement_string);
1.135 paf 1010:
1011: #ifdef RESOURCES_DEBUG
1012: //measure:after connect
1013: gettimeofday(&mt[1],NULL);
1014:
1015: double t[2];
1016: for(int i=0;i<2;i++)
1017: t[i]=mt[i].tv_sec+mt[i].tv_usec/1000000.0;
1018:
1019: r.sql_request_time+=t[1]-t[0];
1020: #endif
1.204 paf 1021:
1022: if(bind)
1023: unmarshal_bind_updates(*bind, placeholders_count, placeholders);
1.96 parser 1024:
1.182 paf 1025: Table& result=
1026: handlers.table?*handlers.table: // query resulted in table? return it
1027: *new Table(Table::columns_type(0)); // query returned no table, fake it
1.49 paf 1028:
1029: // replace any previous table value
1.182 paf 1030: GET_SELF(r, VTable).set_table(result);
1.49 paf 1031: }
1032:
1.182 paf 1033: static void _columns(Request& r, MethodParams&) {
1.88 parser 1034:
1.182 paf 1035: Table::columns_type result_columns(new ArrayString);
1036: *result_columns+=new String("column");
1037: Table& result_table=*new Table(result_columns);
1.88 parser 1038:
1.182 paf 1039: Table& source_table=GET_SELF(r, VTable).table();
1040: if(Table::columns_type source_columns=source_table.columns()) {
1041: for(Array_iterator<const String*> i(*source_columns); i.has_next(); ) {
1042: Table::element_type result_row(new ArrayString);
1043: *result_row+=i.next();
1044: result_table+=result_row;
1.88 parser 1045: }
1046: }
1047:
1.182 paf 1048: r.write_no_lang(*new VTable(&result_table));
1.88 parser 1049: }
1050:
1.182 paf 1051: static void _select(Request& r, MethodParams& params) {
1052: Value& vcondition=params.as_junction(0, "condition must be expression");
1.148 paf 1053:
1.182 paf 1054: Table& source_table=GET_SELF(r, VTable).table();
1055: Table& result_table=*new Table(source_table.columns());
1.148 paf 1056:
1057: int saved_current=source_table.current();
1.182 paf 1058: int size=source_table.count();
1.148 paf 1059: for(int row=0; row<size; row++) {
1060: source_table.set_current(row);
1061:
1.150 paf 1062: bool condition=r.process_to_value(vcondition,
1.148 paf 1063: false/*don't intercept string*/).as_bool();
1064:
1065: if(condition) // ...condition is true=
1.182 paf 1066: result_table+=source_table[row]; // =green light to go to result
1.148 paf 1067: }
1068: source_table.set_current(saved_current);
1069:
1.182 paf 1070: r.write_no_lang(*new VTable(&result_table));
1.148 paf 1071: }
1072:
1.66 paf 1073: // constructor
1074:
1.182 paf 1075: MTable::MTable(): Methoded("table") {
1.142 paf 1076: // ^table::create{data}
1077: // ^table::create[nameless]{data}
1078: // ^table::create[table]
1079: add_native_method("create", Method::CT_DYNAMIC, _create, 1, 2);
1080: // old name for compatibility with <= v 1.141 2002/01/25 11:33:45 paf
1081: add_native_method("set", Method::CT_DYNAMIC, _create, 1, 2);
1.2 paf 1082:
1.142 paf 1083: // ^table::load[file]
1084: // ^table::load[nameless;file]
1.168 paf 1085: add_native_method("load", Method::CT_DYNAMIC, _load, 1, 3);
1.22 paf 1086:
1087: // ^table.save[file]
1088: // ^table.save[nameless;file]
1.188 paf 1089: add_native_method("save", Method::CT_DYNAMIC, _save, 1, 3);
1.6 paf 1090:
1091: // ^table.count[]
1.66 paf 1092: add_native_method("count", Method::CT_DYNAMIC, _count, 0, 0);
1.6 paf 1093:
1094: // ^table.line[]
1.66 paf 1095: add_native_method("line", Method::CT_DYNAMIC, _line, 0, 0);
1.6 paf 1096:
1.10 paf 1097: // ^table.offset[]
1.133 paf 1098: // ^table.offset(offset)
1099: // ^table.offset[cur|set](offset)
1100: add_native_method("offset", Method::CT_DYNAMIC, _offset, 0, 2);
1.7 paf 1101:
1.10 paf 1102: // ^table.menu{code}
1103: // ^table.menu{code}[delim]
1.66 paf 1104: add_native_method("menu", Method::CT_DYNAMIC, _menu, 1, 2);
1.74 paf 1105:
1.79 paf 1106: // ^table:hash[key field name]
1.123 parser 1107: // ^table:hash[key field name][value field name(s) string/table]
1.163 paf 1108: add_native_method("hash", Method::CT_DYNAMIC, _hash, 1, 3);
1.32 paf 1109:
1.102 parser 1110: // ^table.sort{string-key-maker} ^table.sort{string-key-maker}[desc|asc]
1111: // ^table.sort(numeric-key-maker) ^table.sort(numeric-key-maker)[desc|asc]
1.66 paf 1112: add_native_method("sort", Method::CT_DYNAMIC, _sort, 1, 2);
1.8 paf 1113:
1.36 paf 1114: // ^table.locate[field;value]
1.176 paf 1115: add_native_method("locate", Method::CT_DYNAMIC, _locate, 1, 3);
1.39 paf 1116:
1117: // ^table.flip[]
1.66 paf 1118: add_native_method("flip", Method::CT_DYNAMIC, _flip, 0, 0);
1.41 paf 1119:
1120: // ^table.append{r{tab}e{tab}c{tab}o{tab}r{tab}d}
1.66 paf 1121: add_native_method("append", Method::CT_DYNAMIC, _append, 1, 1);
1.42 paf 1122:
1.157 paf 1123: // ^table.join[table][$.limit(10) $.offset(1) $.offset[cur] ]
1124: add_native_method("join", Method::CT_DYNAMIC, _join, 1, 2);
1.49 paf 1125:
1126:
1.100 parser 1127: // ^table:sql[query]
1128: // ^table:sql[query][$.limit(1) $.offset(2)]
1129: add_native_method("sql", Method::CT_DYNAMIC, _sql, 1, 2);
1.88 parser 1130:
1131: // ^table:columns[]
1132: add_native_method("columns", Method::CT_DYNAMIC, _columns, 0, 0);
1.148 paf 1133:
1134: // ^table.select(expression) = table
1135: add_native_method("select", Method::CT_DYNAMIC, _select, 1, 1);
1.40 paf 1136: }
E-mail: