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