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