Annotation of parser3/src/classes/table.C, revision 1.318
1.20 paf 1: /** @file
1.47 paf 2: Parser: @b table parser class.
1.20 paf 3:
1.312 moko 4: Copyright (c) 2001-2015 Art. Lebedev Studio (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.105 parser 8: #include "classes.h"
1.182 paf 9: #include "pa_vmethod_frame.h"
10:
1.16 paf 11: #include "pa_common.h"
1.1 paf 12: #include "pa_request.h"
1.265 misha 13: #include "pa_charsets.h"
1.1 paf 14: #include "pa_vtable.h"
1.6 paf 15: #include "pa_vint.h"
1.51 paf 16: #include "pa_sql_connection.h"
1.72 paf 17: #include "pa_vbool.h"
1.277 moko 18: #include "pa_array.h"
1.1 paf 19:
1.305 moko 20: #if (!defined(NO_STRINGSTREAM) && !defined(FREEBSD4))
21: #include <sstream>
22: #define USE_STRINGSTREAM
23: #endif
24:
1.318 ! moko 25: volatile const char * IDENT_TABLE_C="$Id: table.C,v 1.317 2016/07/29 22:40:58 moko Exp $";
1.286 moko 26:
1.66 paf 27: // class
28:
1.182 paf 29: class MTable: public Methoded {
1.66 paf 30: public: // VStateless_class
1.264 misha 31: Value* create_new_value(Pool&) { return new VTable(); }
1.66 paf 32: public:
1.182 paf 33: MTable();
1.66 paf 34: };
1.1 paf 35:
1.182 paf 36: // global variable
37:
1.313 moko 38: DECLARE_CLASS_VAR(table, new MTable);
1.182 paf 39:
40: #define TABLE_REVERSE_NAME "reverse"
41:
42: // globals
43:
1.203 paf 44: String sql_bind_name(SQL_BIND_NAME);
1.214 paf 45: String sql_limit_name(PA_SQL_LIMIT_NAME);
46: String sql_offset_name(PA_SQL_OFFSET_NAME);
1.182 paf 47: String sql_default_name(SQL_DEFAULT_NAME);
48: String sql_distinct_name(SQL_DISTINCT_NAME);
1.227 misha 49: String sql_value_type_name(SQL_VALUE_TYPE_NAME);
1.182 paf 50: String table_reverse_name(TABLE_REVERSE_NAME);
51:
1.1 paf 52: // methods
1.66 paf 53:
1.182 paf 54: static Table::Action_options get_action_options(Request& r, MethodParams& params,
1.268 misha 55: size_t options_index, const Table& source) {
1.176 paf 56: Table::Action_options result;
1.268 misha 57: if(params.count() <= options_index)
1.182 paf 58: return result;
59:
1.288 misha 60: HashStringValue* options=params.as_hash(options_index);
1.176 paf 61: if(!options)
62: return result;
63:
64: result.defined=true;
65: bool defined_offset=false;
66:
67: int valid_options=0;
1.182 paf 68: if(Value* voffset=options->get(sql_offset_name)) {
1.176 paf 69: valid_options++;
70: defined_offset=true;
71: if(voffset->is_string()) {
1.182 paf 72: const String& soffset=*voffset->get_string();
1.176 paf 73: if(soffset == "cur")
74: result.offset=source.current();
75: else
1.318 ! moko 76: throw Exception(PARSER_RUNTIME, &soffset, "must be 'cur' string or expression");
1.176 paf 77: } else
78: result.offset=r.process_to_value(*voffset).as_int();
79: }
1.182 paf 80: if(Value* vlimit=options->get(sql_limit_name)) {
1.176 paf 81: valid_options++;
82: result.limit=r.process_to_value(*vlimit).as_int();
83: }
1.182 paf 84: if(Value *vreverse=(Value *)options->get(table_reverse_name)) {
85: valid_options++;
86: result.reverse=r.process_to_value(*vreverse).as_bool();
87: if(result.reverse && !defined_offset)
88: result.offset=source.count()-1;
89: }
90:
91: if(valid_options!=options->count())
1.272 misha 92: throw Exception(PARSER_RUNTIME, 0, CALLED_WITH_INVALID_OPTION);
1.176 paf 93:
94: return result;
95: }
1.157 paf 96:
1.236 misha 97: struct TableSeparators {
98: char column; const String* scolumn;
99: char encloser; const String* sencloser;
100:
101: TableSeparators():
1.254 misha 102: column('\t'), scolumn(new String("\t")),
1.236 misha 103: encloser(0), sencloser(0)
104: {}
105: int load( HashStringValue& options ) {
106: int result=0;
107: if(Value* vseparator=options.get(PA_COLUMN_SEPARATOR_NAME)) {
108: scolumn=&vseparator->as_string();
109: if(scolumn->length()!=1)
1.318 ! moko 110: throw Exception(PARSER_RUNTIME, scolumn, "separator must be one character long");
1.236 misha 111: column=scolumn->first_char();
112: result++;
113: }
114: if(Value* vencloser=options.get(PA_COLUMN_ENCLOSER_NAME)) {
115: sencloser=&vencloser->as_string();
1.297 moko 116: if(sencloser->is_empty()){
117: encloser=0;
118: } else {
1.236 misha 119: if(sencloser->length()!=1)
1.318 ! moko 120: throw Exception(PARSER_RUNTIME, sencloser, "encloser must be one character long");
1.236 misha 121: encloser=sencloser->first_char();
1.297 moko 122: }
1.236 misha 123: result++;
124: }
125: return result;
126: }
127: };
128:
1.182 paf 129: static void _create(Request& r, MethodParams& params) {
1.157 paf 130: // clone/copy part?
1.182 paf 131: if(Table *source=params[0].get_table()) {
1.268 misha 132: Table::Action_options o=get_action_options(r, params, 1, *source);
1.303 moko 133: if(params.count()>2)
134: throw Exception(PARSER_RUNTIME, 0, "too many parameters");
1.182 paf 135: GET_SELF(r, VTable).set_table(*new Table(*source, o));
1.157 paf 136: return;
137: }
1.142 paf 138:
1.236 misha 139: size_t data_param_index=0;
140: bool nameless=false;
141:
142: if(params.count()>1) {
143: if(params[0].is_string()){ // can be nameless only
144: const String& snameless=params.as_string(0, "called with more then 1 param, first param may be only string 'nameless' or junction");
145: if(snameless!="nameless")
1.318 ! moko 146: throw Exception(PARSER_RUNTIME, &snameless, "table::create called with more then 1 param, first param may be only 'nameless'");
1.236 misha 147: nameless=true;
148: data_param_index++;
149: }
150: }
151:
152: HashStringValue *options=0;
153: TableSeparators separators;
154:
155: size_t options_param_index=data_param_index+1;
156: if(
157: options_param_index<params.count()
1.288 misha 158: && (options=params.as_hash(options_param_index))
1.236 misha 159: ) {
160: // cloning, so that we could change
161: options=new HashStringValue(*options);
162: separators.load(*options);
163: if(separators.encloser){
1.318 ! moko 164: throw Exception(PARSER_RUNTIME, 0, "encloser not supported for table::create yet");
1.236 misha 165: }
166: }
167:
168: // data
1.182 paf 169: Temp_lang temp_lang(r, String::L_PASS_APPENDED);
170: const String& data=
1.301 misha 171: r.process_to_string(params.as_junction(data_param_index, "body must be table or code"));
1.44 paf 172:
173: // parse columns
1.182 paf 174: size_t raw_pos_after=0;
175: Table::columns_type columns;
1.236 misha 176:
177: if(nameless){
1.182 paf 178: columns=Table::columns_type(0); // nameless
1.21 paf 179: } else {
1.182 paf 180: columns=Table::columns_type(new ArrayString);
1.44 paf 181:
1.182 paf 182: ArrayString head;
183: data.split(head, raw_pos_after, "\n", String::L_AS_IS, 1);
184: if(head.count()) {
185: size_t col_pos_after=0;
1.285 misha 186: if(head[0]->is_empty())
187: *columns += new String();
188: else
189: head[0]->split(*columns, col_pos_after, *separators.scolumn, String::L_AS_IS);
1.182 paf 190: }
1.44 paf 191: }
192:
1.182 paf 193: Table& table=*new Table(columns);
1.44 paf 194: // parse cells
1.182 paf 195:
196: ArrayString rows;
197: data.split(rows, raw_pos_after, "\n", String::L_AS_IS);
198: Array_iterator<const String*> i(rows);
1.98 parser 199: while(i.has_next()) {
1.182 paf 200: Table::element_type row(new ArrayString);
1.252 misha 201: const String& string=*i.next();
1.118 parser 202: // remove comment lines
1.252 misha 203: if(string.is_empty())
1.44 paf 204: continue;
205:
1.182 paf 206: size_t col_pos_after=0;
1.236 misha 207: string.split(*row, col_pos_after, *separators.scolumn, String::L_AS_IS);
1.182 paf 208: table+=row;
1.17 paf 209: }
1.1 paf 210:
1.44 paf 211: // replace any previous table value
1.182 paf 212: GET_SELF(r, VTable).set_table(table);
1.44 paf 213: }
214:
1.187 paf 215: struct lsplit_result {
216: char* piece;
217: char delim;
218:
219: operator bool() { return piece!=0; }
220: };
221:
222: inline lsplit_result lsplit(char* string, char delim1, char delim2) {
223: lsplit_result result;
1.273 misha 224: if(string) {
1.187 paf 225: char delims[]={delim1, delim2, 0};
226: if(char* v=strpbrk(string, delims)) {
227: result.delim=*v;
228: *v=0;
229: result.piece=v+1;
230: return result;
231: }
1.273 misha 232: }
1.187 paf 233: result.piece=0;
234: result.delim=0;
1.273 misha 235: return result;
1.187 paf 236: }
237:
238: inline lsplit_result lsplit(char* *string_ref, char delim1, char delim2) {
1.273 misha 239: lsplit_result result;
1.187 paf 240: result.piece=*string_ref;
241: lsplit_result next=lsplit(*string_ref, delim1, delim2);
242: result.delim=next.delim;
243: *string_ref=next.piece;
1.273 misha 244: return result;
1.187 paf 245: }
246:
247: static lsplit_result lsplit(char** string_ref, char delim1, char delim2, char encloser) {
248: lsplit_result result;
249:
1.273 misha 250: if(char* string=*string_ref) {
1.187 paf 251: if(encloser && *string==encloser) {
1.273 misha 252: string++;
1.187 paf 253:
254: char *read;
255: char *write;
256: write=read=string;
257: char c;
1.290 moko 258: // we are enclosed, searching for second encloser
259: while(c=*read++) {
1.187 paf 260: if(c==encloser) {
1.290 moko 261: if(*read==encloser) // double-encloser stands for encloser
1.187 paf 262: read++;
1.290 moko 263: else
264: break; // note: skipping encloser
1.187 paf 265: }
266: *write++=c;
267: }
1.290 moko 268: // we are no longer enclosed, searching for delimiter, skipping extra enclosers
269: while(c=*read++) {
270: if(c==delim1 || c==delim2) {
271: result.delim=c;
272: break;
273: } else if(c!=encloser)
274: *write++=c;
275: }
1.187 paf 276: *write=0; // terminate
277: *string_ref=c? read: 0;
278: result.piece=string;
279: return result;
280: } else
281: return lsplit(string_ref, delim1, delim2);
1.273 misha 282: }
1.187 paf 283: result.piece=0;
1.273 misha 284: return result;
1.187 paf 285: }
286:
287: static void skip_empty_and_comment_lines( char** data_ref ) {
288: if(char *data=*data_ref) {
289: while( char c=*data ) {
290: if( c== '\n' || c == '#' ) {
291: /*nowhere=*/getrow(&data); // remove empty&comment lines
1.199 paf 292: if(!(*data_ref=data))
293: break;
1.187 paf 294: continue;
295: }
296: break;
297: }
298: }
299: }
300:
1.273 misha 301: static void skip_empty_lines( char** data_ref ) {
302: if(char *data=*data_ref) {
303: while( char c=*data ) {
304: if( c== '\n' ) {
305: /*nowhere=*/getrow(&data); // remove empty lines
306: if(!(*data_ref=data))
307: break;
308: continue;
309: }
310: break;
311: }
312: }
313: }
314:
315: typedef void (*Skip_lines_action)(char** data_ref);
316:
1.182 paf 317: static void _load(Request& r, MethodParams& params) {
1.232 misha 318: const String& first_param=params.as_string(0, FILE_NAME_MUST_BE_STRING);
1.168 paf 319: int filename_param_index=0;
320: bool nameless=first_param=="nameless";
321: if(nameless)
322: filename_param_index++;
1.182 paf 323: size_t options_param_index=filename_param_index+1;
1.186 paf 324:
325: HashStringValue *options=0;
1.187 paf 326: TableSeparators separators;
1.186 paf 327: if(options_param_index<params.count()
1.288 misha 328: && (options=params.as_hash(options_param_index))) {
1.186 paf 329: // cloning, so that we could change [to simplify checks on params inside file_read_text
330: options=new HashStringValue(*options);
1.187 paf 331: separators.load(*options);
1.186 paf 332: }
333:
1.44 paf 334: // loading text
1.247 misha 335: char *data=file_load_text(r,
1.232 misha 336: r.absolute(params.as_string(filename_param_index, FILE_NAME_MUST_BE_STRING)),
1.168 paf 337: true,
1.186 paf 338: options
1.168 paf 339: );
1.44 paf 340:
1.273 misha 341: Skip_lines_action skip_lines_action = (separators.column=='#' || separators.encloser=='#') ? skip_empty_lines : skip_empty_and_comment_lines;
342:
1.1 paf 343: // parse columns
1.182 paf 344: Table::columns_type columns;
1.168 paf 345: if(nameless) {
1.182 paf 346: columns=Table::columns_type(0); // nameless
1.1 paf 347: } else {
1.182 paf 348: columns=Table::columns_type(new ArrayString);
1.1 paf 349:
1.273 misha 350: skip_lines_action(&data);
1.187 paf 351: while( lsplit_result sr=lsplit(&data, separators.column, '\n', separators.encloser) ) {
1.256 misha 352: *columns+=new String(sr.piece, String::L_TAINTED);
1.187 paf 353: if(sr.delim=='\n')
354: break;
1.139 paf 355: }
1.1 paf 356: }
1.187 paf 357:
358: Table& table=*new Table(columns);
1.219 paf 359: int columns_count=columns? columns->count(): 0;
1.1 paf 360:
361: // parse cells
1.218 paf 362: Table::element_type row(new ArrayString(columns_count));
1.273 misha 363: skip_lines_action(&data);
1.187 paf 364: while( lsplit_result sr=lsplit(&data, separators.column, '\n', separators.encloser) ) {
1.201 paf 365: if(!*sr.piece && !sr.delim && !row->count()) // append last empty column [if without \n]
366: break;
1.256 misha 367: *row+=new String(sr.piece, String::L_TAINTED);
1.187 paf 368: if(sr.delim=='\n') {
369: table+=row;
1.218 paf 370: row=new ArrayString(columns_count);
1.273 misha 371: skip_lines_action(&data);
1.1 paf 372: }
1.187 paf 373: }
374: // last line [if without \n]
375: if(row->count())
1.1 paf 376: table+=row;
1.187 paf 377:
1.1 paf 378: // replace any previous table value
1.182 paf 379: GET_SELF(r, VTable).set_table(table);
1.1 paf 380: }
1.2 paf 381:
1.297 moko 382: #ifdef USE_STRINGSTREAM
1.269 misha 383: #include "gc_allocator.h"
384:
385: typedef std::basic_stringstream<char, std::char_traits<char>, gc_allocator<char> > pa_stringstream;
386: typedef std::basic_string<char, std::char_traits<char>, gc_allocator<char> > pa_string;
387:
1.298 moko 388: static void enclose( pa_stringstream& to, const String* from, char encloser ) {
1.297 moko 389: if(from){
1.257 misha 390: to<<encloser;
1.188 paf 391: // while we have 'encloser'...
1.189 paf 392: size_t pos_after=0;
1.297 moko 393: for( size_t pos_before; (pos_before=from->pos( encloser, pos_after ))!=STRING_NOT_FOUND; pos_after=pos_before) {
1.220 paf 394: pos_before++; // including first encloser (and skipping it for next pos)
1.297 moko 395: to<<from->mid(pos_after, pos_before).cstr();
1.257 misha 396: to<<encloser; // doubling encloser
1.188 paf 397: }
398: // last piece
1.297 moko 399: size_t from_length=from->length();
1.188 paf 400: if(pos_after<from_length)
1.297 moko 401: to<<from->mid(pos_after, from_length).cstr();
402: to<<encloser;
403: } else {
404: to<<encloser<<encloser;
405: }
406: }
407:
408: static void table_to_csv(pa_stringstream& result, Table& table, TableSeparators& separators, bool output_column_names) {
409: if(output_column_names) {
410: if(table.columns()) { // named table
411: if(separators.encloser){
412: for(Array_iterator<const String*> i(*table.columns()); i.has_next(); ) {
1.298 moko 413: enclose( result, i.next(), separators.encloser );
1.297 moko 414: if(i.has_next())
415: result<<separators.column;
416: }
417: } else {
418: for(Array_iterator<const String*> i(*table.columns()); i.has_next(); ) {
419: result<<i.next()->cstr();
420: if(i.has_next())
421: result<<separators.column;
422: }
423: }
424: } else { // nameless table [we were asked to output column names]
425: if(int lsize=table.count()?table[0]->count():0)
426: for(int column=0; column<lsize; column++) {
427: if(separators.encloser) {
428: result<<separators.encloser<<column<<separators.encloser;
429: } else {
430: result<<column;
431: }
432: if(column<lsize-1){
433: result<<separators.column;
434: }
435: }
436: else
437: result<<"empty nameless table";
438: }
439: result<<'\n';
440: }
1.188 paf 441:
1.297 moko 442: // process data lines
443: Array_iterator<ArrayString*> i(table);
444: if(separators.encloser){
445: while(i.has_next()) {
446: for(Array_iterator<const String*> c(*i.next()); c.has_next(); ) {
1.298 moko 447: enclose( result, c.next(), separators.encloser );
1.297 moko 448: if(c.has_next())
449: result<<separators.column;
450: }
451: result<<'\n';
452: }
453: } else {
454: while(i.has_next()) {
455: for(Array_iterator<const String*> c(*i.next()); c.has_next(); ) {
456: result<<c.next()->cstr();
457: if(c.has_next())
458: result<<separators.column;
459: }
460: result<<'\n';
461: }
462: }
1.188 paf 463: }
464:
1.241 misha 465: #else
466:
1.298 moko 467: void enclose( String& to, const String* from, char encloser, const String* sencloser ) {
1.297 moko 468: if(from){
1.257 misha 469: to<<*sencloser;
1.224 misha 470: // while we have 'encloser'...
471: size_t pos_after=0;
1.297 moko 472: for( size_t pos_before; (pos_before=from->pos( encloser, pos_after ))!=STRING_NOT_FOUND; pos_after=pos_before) {
1.224 misha 473: pos_before++; // including first encloser (and skipping it for next pos)
1.297 moko 474: to<<from->mid(pos_after, pos_before);
1.257 misha 475: to<<*sencloser; // doubling encloser
1.224 misha 476: }
477: // last piece
1.297 moko 478: size_t from_length=from->length();
1.224 misha 479: if(pos_after<from_length)
1.297 moko 480: to<<from->mid(pos_after, from_length);
1.257 misha 481: to<<*sencloser;
1.297 moko 482: } else {
483: to<<*sencloser<<*sencloser;
484: }
1.224 misha 485: }
486:
1.297 moko 487: static void table_to_csv(String& result, Table& table, TableSeparators& separators, bool output_column_names) {
488: if(output_column_names) {
489: if(table.columns()) { // named table
490: if(separators.encloser) {
491: for(Array_iterator<const String*> i(*table.columns()); i.has_next(); ) {
1.298 moko 492: enclose( result, i.next(), separators.encloser, separators.sencloser );
1.297 moko 493: if(i.has_next())
494: result<<*separators.scolumn;
495: }
496: } else {
497: for(Array_iterator<const String*> i(*table.columns()); i.has_next(); ) {
498: result<<*i.next();
499: if(i.has_next())
500: result<<*separators.scolumn;
501: }
502: }
503: } else { // nameless table [we were asked to output column names]
504: if(int lsize=table.count()?table[0]->count():0)
505: for(int column=0; column<lsize; column++) {
1.298 moko 506: if(separators.encloser) {
507: result<<*separators.sencloser<<String::Body::Format(column)<<*separators.sencloser;
508: } else {
509: result<<String::Body::Format(column);
510: }
511: if(column<lsize-1){
512: result<<*separators.scolumn;
513: }
1.297 moko 514: }
515: else
516: result.append_help_length("empty nameless table", 0, String::L_CLEAN);
517: }
518: result.append_know_length("\n", 1, String::L_CLEAN);
519: }
520:
521: // data lines
522: Array_iterator<ArrayString*> i(table);
523: if(separators.encloser){
524: while(i.has_next()) {
525: for(Array_iterator<const String*> c(*i.next()); c.has_next(); ) {
1.298 moko 526: enclose( result, c.next(), separators.encloser, separators.sencloser );
1.297 moko 527: if(c.has_next())
528: result<<*separators.scolumn;
529: }
530: result.append_know_length("\n", 1, String::L_CLEAN);
531: }
532: } else {
533: while(i.has_next()) {
534: for(Array_iterator<const String*> c(*i.next()); c.has_next(); ) {
535: result<<*c.next();
536: if(c.has_next())
537: result<<*separators.scolumn;
538: }
539: result.append_know_length("\n", 1, String::L_CLEAN);
540: }
541: }
542: }
1.257 misha 543: #endif // don't use stringstream
1.241 misha 544:
1.297 moko 545:
1.241 misha 546: static void _save(Request& r, MethodParams& params) {
1.237 misha 547: const String& first_arg=params.as_string(0, FIRST_ARG_MUST_NOT_BE_CODE);
1.188 paf 548: size_t param_index=1;
549:
550: bool do_append=false;
551: bool output_column_names=true;
552:
553: // mode?
554: if(first_arg=="append")
555: do_append=true;
556: else if(first_arg=="nameless")
557: output_column_names=false;
558: else
559: --param_index;
560:
1.232 misha 561: const String& file_name=params.as_string(param_index++, FILE_NAME_MUST_NOT_BE_CODE);
1.246 misha 562: String file_spec=r.absolute(file_name);
563:
564: if(do_append && file_exist(file_spec))
565: output_column_names=false;
1.188 paf 566:
567: TableSeparators separators;
1.281 misha 568: if(param_index<params.count())
1.288 misha 569: if(HashStringValue* options=params.as_hash(param_index++)) {
1.281 misha 570: int valid_options=separators.load(*options);
571: if(valid_options!=options->count())
572: throw Exception(PARSER_RUNTIME, 0, CALLED_WITH_INVALID_OPTION);
1.222 paf 573: }
1.281 misha 574:
1.188 paf 575: if(param_index<params.count())
1.318 ! moko 576: throw Exception(PARSER_RUNTIME, 0, "bad mode (must be nameless or append)");
1.22 paf 577:
1.182 paf 578: Table& table=GET_SELF(r, VTable).table();
1.31 paf 579:
1.297 moko 580: #ifdef USE_STRINGSTREAM
1.269 misha 581: pa_stringstream ost(std::stringstream::out);
1.257 misha 582:
1.297 moko 583: table_to_csv(ost, table, separators, output_column_names);
1.31 paf 584:
585: // write
1.269 misha 586: pa_string data=ost.str();
1.257 misha 587: const char* data_cstr=data.c_str();
1.267 misha 588: file_write(r.charsets, file_spec, data_cstr, data.length(), true /* as text */, do_append);
1.241 misha 589: #else
1.257 misha 590: String sdata;
1.224 misha 591:
1.297 moko 592: table_to_csv(sdata, table, separators, output_column_names);
1.224 misha 593:
594: // write
1.257 misha 595: const char* data_cstr=sdata.cstr();
1.297 moko 596: file_write(r.charsets, file_spec, data_cstr, sdata.length(), true /* as text */, do_append);
1.257 misha 597: if(*data_cstr) // not empty (when empty it's not heap memory)
598: pa_free((void*)data_cstr); // not needed anymore
1.297 moko 599: #endif
600: }
601:
602: static void _csv_string(Request& r, MethodParams& params) {
603: bool output_column_names=true;
604: size_t param_index=0;
605: if(params.count()>0 && params[0].is_string()) {
606: if(params.as_string(0, FIRST_ARG_MUST_NOT_BE_CODE)=="nameless") {
607: output_column_names=false;
608: param_index++;
609: } else {
1.318 ! moko 610: throw Exception(PARSER_RUNTIME, 0, "bad mode (must be nameless)");
1.297 moko 611: }
1.224 misha 612: }
1.240 misha 613:
1.297 moko 614: TableSeparators separators;
615: if(param_index<params.count())
616: if(HashStringValue* options=params.as_hash(param_index++)) {
617: int valid_options=separators.load(*options);
618: if(valid_options!=options->count())
619: throw Exception(PARSER_RUNTIME, 0, CALLED_WITH_INVALID_OPTION);
620: }
621:
622: Table& table=GET_SELF(r, VTable).table();
623:
624: #ifdef USE_STRINGSTREAM
625: pa_stringstream ost(std::stringstream::out);
626:
627: table_to_csv(ost, table, separators, output_column_names);
628:
629: r.write_no_lang(*new VString(*new String(pa_strdup(ost.str().c_str()), String::L_CLEAN)));
630: #else
631: String sdata;
632:
633: table_to_csv(sdata, table, separators, output_column_names);
634:
635: r.write_no_lang(*new VString(*new String(sdata.cstr(), String::L_CLEAN)));
636: #endif
1.224 misha 637: }
638:
1.280 misha 639: static void _count(Request& r, MethodParams& params) {
640: Table& table=GET_SELF(r, VTable).table();
641: size_t result=0;
642: if(params.count()) {
643: const String& param=params.as_string(0, PARAMETER_MUST_BE_STRING);
644: if(param == "columns")
1.310 moko 645: result = table.columns() ? table.columns()->count() : table.max_cells();
1.280 misha 646: else if(param == "cells")
647: result = table.count() ? table[table.current()]->count() : 0;
648: else if(param == "rows") // synonim for ^table.count[]
649: result = table.count();
650: else
651: throw Exception(PARSER_RUNTIME, ¶m, "parameter must be 'columns', 'cells' and 'rows' only");
652: } else
653: result = table.count();
654:
1.182 paf 655: r.write_no_lang(*new VInt(result));
1.6 paf 656: }
657:
1.182 paf 658: static void _line(Request& r, MethodParams&) {
659: int result=1+GET_SELF(r, VTable).table().current();
660: r.write_no_lang(*new VInt(result));
1.6 paf 661: }
662:
1.182 paf 663: static void _offset(Request& r, MethodParams& params) {
664: Table& table=GET_SELF(r, VTable).table();
665: if(params.count()) {
1.133 paf 666: bool absolute=false;
1.182 paf 667: if(params.count()>1) {
668: const String& whence=params.as_string(0, "whence must be string");
1.133 paf 669: if(whence=="cur")
1.134 paf 670: absolute=false;
1.133 paf 671: else if(whence=="set")
1.134 paf 672: absolute=true;
1.133 paf 673: else
1.318 ! moko 674: throw Exception(PARSER_RUNTIME, &whence, "is invalid whence, valid are 'cur' or 'set'");
1.157 paf 675: }
1.133 paf 676:
1.211 paf 677: int offset=params.as_int(params.count()-1, "offset must be expression", r);
678: table.offset(absolute, offset);
1.151 paf 679: } else
1.182 paf 680: r.write_no_lang(*new VInt(table.current()));
1.6 paf 681: }
682:
1.182 paf 683: static void _menu(Request& r, MethodParams& params) {
1.263 misha 684: InCycle temp(r);
1.221 paf 685:
1.182 paf 686: Value& body_code=params.as_junction(0, "body must be code");
1.7 paf 687:
1.182 paf 688: Value* delim_maybe_code=params.count()>1?¶ms[1]:0;
1.7 paf 689:
1.182 paf 690: Table& table=GET_SELF(r, VTable).table();
1.293 misha 691: size_t saved_current=table.current();
1.7 paf 692:
1.251 misha 693: if(delim_maybe_code) { // delimiter set
1.250 misha 694: bool need_delim=false;
1.316 moko 695: for(size_t row=0; row<table.count(); row++) {
1.250 misha 696: table.set_current(row);
697:
698: StringOrValue sv_processed=r.process(body_code);
699: Request::Skip lskip=r.get_skip(); r.set_skip(Request::SKIP_NOTHING);
700:
701: const String* s_processed=sv_processed.get_string();
1.251 misha 702: if(s_processed && !s_processed->is_empty()) { // we have body
1.250 misha 703: if(need_delim) // need delim & iteration produced string?
704: r.write_pass_lang(r.process(*delim_maybe_code));
705: else
706: need_delim=true;
707: }
708:
709: r.write_pass_lang(sv_processed);
1.242 misha 710:
1.250 misha 711: if(lskip==Request::SKIP_BREAK)
712: break;
713: }
714: } else {
1.316 moko 715: for(size_t row=0; row<table.count(); row++) {
1.250 misha 716: table.set_current(row);
717:
718: r.process_write(body_code);
719: Request::Skip lskip=r.get_skip(); r.set_skip(Request::SKIP_NOTHING);
720:
721: if(lskip==Request::SKIP_BREAK)
722: break;
1.7 paf 723: }
724: }
1.99 parser 725: table.set_current(saved_current);
1.7 paf 726: }
727:
1.110 parser 728: #ifndef DOXYGEN
1.74 paf 729: struct Row_info {
1.166 paf 730: Request *r;
1.74 paf 731: Table *table;
1.182 paf 732: Value* key_code;
733: size_t key_field;
734: Array<int>* value_fields;
1.315 moko 735: Value* value_code;
1.182 paf 736: HashStringValue* hash;
1.174 paf 737: Table2hash_distint distinct;
1.182 paf 738: size_t row;
1.227 misha 739: Table2hash_value_type value_type;
1.74 paf 740: };
1.110 parser 741: #endif
1.182 paf 742: static void table_row_to_hash(Table::element_type row, Row_info *info) {
743: const String* key;
744: if(info->key_code) {
745: info->table->set_current(info->row++); // change context row
746: StringOrValue sv_processed=info->r->process(*info->key_code);
1.166 paf 747: key=&sv_processed.as_string();
1.227 misha 748: } else {
1.182 paf 749: key=info->key_field<row->count()?row->get(info->key_field):0;
1.227 misha 750: }
1.166 paf 751:
752: if(!key)
753: return; // ignore rows without key [too-short-record_array if-indexed]
1.74 paf 754:
1.243 misha 755: bool exist=false;
756: switch(info->value_type) {
757: case C_STRING: {
1.317 moko 758: if(info->value_fields->count()){
759: size_t index=info->value_fields->get(0);
760: exist=info->hash->put_dont_replace(*key, (index < row->count()) ? new VString(*row->get(index)) : VString::empty());
761: } else {
762: exist=info->hash->put_dont_replace(*key, VString::empty());
763: }
1.243 misha 764: break;
1.227 misha 765: }
1.243 misha 766: case C_HASH: {
1.182 paf 767: VHash* vhash=new VHash;
768: HashStringValue& hash=vhash->hash();
769: for(Array_iterator<int> i(*info->value_fields); i.has_next(); ) {
770: size_t value_field=i.next();
771: if(value_field<row->count())
1.314 moko 772: hash.put(*info->table->columns()->get(value_field), new VString(*row->get(value_field)));
1.174 paf 773: }
774:
1.227 misha 775: exist=info->hash->put_dont_replace(*key, vhash);
1.243 misha 776: break;
1.174 paf 777: }
1.243 misha 778: case C_TABLE: {
779: VTable* vtable=(VTable*)info->hash->get(*key); // table exist?
1.174 paf 780: Table* table;
1.227 misha 781: if(vtable) {
1.243 misha 782: if(info->distinct==D_ILLEGAL) {
783: exist=true;
784: break;
785: }
1.174 paf 786: table=vtable->get_table();
1.227 misha 787: } else {
1.174 paf 788: // no? creating table of same structure as source
1.179 paf 789: Table::Action_options table_options(0, 0);
1.182 paf 790: table=new Table(*info->table, table_options/*no rows, just structure*/);
791: info->hash->put(*key, new VTable(table));
1.174 paf 792: }
1.308 moko 793: Table::element_type row_copy(new ArrayString(row->count()));
794: row_copy->append(*row);
795: *table+=row_copy;
1.243 misha 796: break;
1.174 paf 797: }
1.315 moko 798: case C_CODE: {
799: if(!info->key_code)
800: info->table->set_current(info->row++); // change context row
801: exist=info->hash->put_dont_replace(*key, &info->r->process(*info->value_code).as_value());
802: break;
803: }
1.74 paf 804: }
1.227 misha 805: if(exist && info->distinct==D_ILLEGAL)
1.314 moko 806: throw Exception(PARSER_RUNTIME, key, "duplicate key");
1.74 paf 807: }
1.235 misha 808:
809: Table2hash_value_type get_value_type(Value& vvalue_type){
810: if(vvalue_type.is_string()) {
811: const String& svalue_type=*vvalue_type.get_string();
812: if(svalue_type == "table"){
813: return C_TABLE;
814: } else if (svalue_type == "string") {
815: return C_STRING;
816: } else if (svalue_type == "hash") {
817: return C_HASH;
818: } else {
1.314 moko 819: throw Exception(PARSER_RUNTIME, &svalue_type, "must be 'hash', 'table' or 'string'");
1.235 misha 820: }
821: } else {
1.314 moko 822: throw Exception(PARSER_RUNTIME, 0, "'type' must be string");
1.235 misha 823: }
824: }
825:
1.315 moko 826: static Table2hash_distint get_distinct(Value& vdistinct, Table2hash_value_type& value_type){
827: if(vdistinct.is_string()) {
828: const String& sdistinct=*vdistinct.get_string();
829: if(sdistinct!="tables")
830: throw Exception(PARSER_RUNTIME, &sdistinct, "must be 'tables' or true/false");
831: value_type=C_TABLE;
832: return D_FIRST;
833: }
834: return vdistinct.as_bool() ? D_FIRST : D_ILLEGAL;
835: }
836:
1.182 paf 837: static void _hash(Request& r, MethodParams& params) {
838: Table& self_table=GET_SELF(r, VTable).table();
839: VHash& result=*new VHash;
1.238 misha 840: if(Table::columns_type columns=self_table.columns()){
1.182 paf 841: if(columns->count()>0) {
1.174 paf 842: Table2hash_distint distinct=D_ILLEGAL;
1.227 misha 843: Table2hash_value_type value_type=C_HASH;
1.182 paf 844: int param_index=params.count()-1;
1.166 paf 845: if(param_index>0) {
1.315 moko 846:
847: if(params[1].get_junction())
848: value_type=C_CODE;
849:
850: if(HashStringValue* options=params[param_index].get_hash()){ // can't use .as_hash because the 2nd param could be table so .as_hash throws an error
1.166 paf 851: --param_index;
852: int valid_options=0;
1.238 misha 853: if(Value* vdistinct_code=options->get(sql_distinct_name)) { // $.distinct ?
1.166 paf 854: valid_options++;
1.315 moko 855: distinct=get_distinct(r.process_to_value(*vdistinct_code), value_type);
1.166 paf 856: }
1.238 misha 857: if(Value* vvalue_type_code=options->get(sql_value_type_name)) { // $.type ?
858: if(value_type==C_TABLE) // $.distinct[tables] already was specified
1.314 moko 859: throw Exception(PARSER_RUNTIME, 0, "you can't specify $.distinct[tables] and $.type[] together");
1.315 moko 860: if(value_type==C_CODE)
861: throw Exception(PARSER_RUNTIME, 0, "you can't specify $.type[] if value is code");
1.238 misha 862: valid_options++;
863: value_type=get_value_type(r.process_to_value(*vvalue_type_code));
864: }
1.226 misha 865:
1.182 paf 866: if(valid_options!=options->count())
1.272 misha 867: throw Exception(PARSER_RUNTIME, 0, CALLED_WITH_INVALID_OPTION);
1.163 paf 868: }
869: }
1.238 misha 870:
1.315 moko 871: if(param_index==2) // options were specified but not as hash
1.289 misha 872: throw Exception(PARSER_RUNTIME, 0, "options must be hash");
873:
1.182 paf 874: Array<int> value_fields;
1.315 moko 875: Value* value_code=0;
876:
1.238 misha 877: if(param_index==0){ // list of columns wasn't specified
878: if(value_type==C_STRING) // $.type[string]
1.314 moko 879: throw Exception(PARSER_RUNTIME, 0, "you must specify one value field with option $.type[string]");
1.238 misha 880:
881: for(size_t i=0; i<columns->count(); i++) // by all columns, including key
882: value_fields+=i;
883:
1.315 moko 884: } else { // list of columns or code was specified
1.227 misha 885: if(value_type==C_TABLE)
1.314 moko 886: throw Exception(PARSER_RUNTIME, 0, "you can't specify value field(s) with option $.distinct[tables] or $.type[tables]");
1.238 misha 887:
1.315 moko 888: Value& value_fields_param=params[1];
1.317 moko 889: if(value_fields_param.get_junction()){ // code specified
1.315 moko 890: value_code=&value_fields_param;
891: } else if(value_fields_param.is_string()) { // one column as string was specified
1.317 moko 892: const String &field_name=*value_fields_param.get_string();
893: if(!field_name.is_empty())
894: value_fields+=self_table.column_name2index(field_name, true);
1.238 misha 895: } else if(Table* value_fields_table=value_fields_param.get_table()) { // list of columns were specified in table
896: for(Array_iterator<Table::element_type> i(*value_fields_table); i.has_next(); ) {
897: const String& value_field_name =*i.next()->get(0);
898: value_fields +=self_table.column_name2index(value_field_name, true);
1.123 parser 899: }
900: } else
1.315 moko 901: throw Exception(PARSER_RUNTIME, 0, "value field(s) must be string or table or code");
1.239 misha 902: }
1.74 paf 903:
1.227 misha 904: if(value_type==C_STRING && value_fields.count()!=1)
1.314 moko 905: throw Exception(PARSER_RUNTIME, 0, "you can specify only one value field with option $.type[string]");
1.182 paf 906:
907: {
908: Value* key_param=¶ms[0];
1.193 paf 909: Row_info info={
910: &r,
911: &self_table,
1.315 moko 912: /*key_code=*/key_param->get_junction() ? key_param : 0,
1.197 paf 913: /*key_field=*/0/*filled below*/,
1.193 paf 914: &value_fields,
1.315 moko 915: value_code,
1.193 paf 916: &result.hash(),
917: distinct,
1.227 misha 918: /*row=*/0,
919: value_type
1.193 paf 920: };
1.314 moko 921: info.key_field=(info.key_code ? -1 : self_table.column_name2index(key_param->as_string(), true));
1.182 paf 922:
923: int saved_current=self_table.current();
924: self_table.for_each(table_row_to_hash, &info);
925: self_table.set_current(saved_current);
1.207 paf 926:
927: result.extract_default();
1.182 paf 928: }
1.74 paf 929: }
1.238 misha 930: }
1.97 parser 931: r.write_no_lang(result);
1.74 paf 932: }
933:
1.110 parser 934: #ifndef DOXYGEN
1.78 paf 935: struct Table_seq_item {
1.182 paf 936: ArrayString* row;
1.34 paf 937: union {
1.182 paf 938: const char *c_str;
1.34 paf 939: double d;
940: } value;
1.32 paf 941: };
1.110 parser 942: #endif
1.34 paf 943: static int sort_cmp_string(const void *a, const void *b) {
944: return strcmp(
1.78 paf 945: static_cast<const Table_seq_item *>(a)->value.c_str,
946: static_cast<const Table_seq_item *>(b)->value.c_str
1.34 paf 947: );
948: }
949: static int sort_cmp_double(const void *a, const void *b) {
1.78 paf 950: double va=static_cast<const Table_seq_item *>(a)->value.d;
951: double vb=static_cast<const Table_seq_item *>(b)->value.d;
1.34 paf 952: if(va<vb)
953: return -1;
954: else if(va>vb)
955: return +1;
956: else
957: return 0;
958: }
1.182 paf 959: static void _sort(Request& r, MethodParams& params) {
960: Value& key_maker=params.as_junction(0, "key-maker must be code");
1.61 paf 961:
1.182 paf 962: bool reverse=params.count()>1/*..[desc|asc|]*/?
963: reverse=params.as_no_junction(1, "order must not be code").as_string()=="desc":
1.104 parser 964: false; // default=asc
1.32 paf 965:
1.182 paf 966: Table& old_table=GET_SELF(r, VTable).table();
967: Table& new_table=*new Table(old_table.columns());
1.34 paf 968:
1.182 paf 969: Table_seq_item* seq=new(PointerFreeGC) Table_seq_item[old_table.count()];
1.34 paf 970: int i;
971:
972: // calculate key values
973: bool key_values_are_strings=true;
1.182 paf 974: int old_count=old_table.count();
975: for(i=0; i<old_count; i++) {
1.101 parser 976: old_table.set_current(i);
1.32 paf 977: // calculate key value
1.182 paf 978: seq[i].row=old_table[i];
1.287 moko 979: Value& value=r.process_to_value(key_maker);
1.34 paf 980: if(i==0) // determining key values type by first one
981: key_values_are_strings=value.is_string();
982:
983: if(key_values_are_strings)
984: seq[i].value.c_str=value.as_string().cstr();
985: else
1.287 moko 986: seq[i].value.d=value.as_expr_result().as_double();
1.32 paf 987: }
1.265 misha 988:
989: // @todo: handle this elsewhere
990: if(r.charsets.source().NAME()=="KOI8-R" && key_values_are_strings) {
991: for(i=0; i<old_count; i++)
992: if(*seq[i].value.c_str)
993: seq[i].value.c_str=Charset::transcode(seq[i].value.c_str, r.charsets.source(), UTF8_charset).cstr();
994: }
995:
1.266 misha 996: // sort keys
1.295 moko 997: qsort(seq, old_count, sizeof(Table_seq_item), key_values_are_strings?sort_cmp_string:sort_cmp_double);
1.32 paf 998:
1.34 paf 999: // reorder table as they require in 'seq'
1.182 paf 1000: for(i=0; i<old_count; i++)
1001: new_table+=Table::element_type(seq[reverse?old_count-1-i:i].row);
1002:
1003: delete[] seq;
1.32 paf 1004:
1.116 parser 1005: // replace any previous table value
1.182 paf 1006: GET_SELF(r, VTable).set_table(new_table);
1.32 paf 1007: }
1008:
1.176 paf 1009: #ifndef DOXYGEN
1.182 paf 1010: struct Expression_is_true_info {
1.176 paf 1011: Request* r;
1012: Value* expression_code;
1013: };
1014: #endif
1.275 misha 1015:
1.191 paf 1016: static bool expression_is_true(Table&, Expression_is_true_info* info) {
1017: return info->r->process_to_value(*info->expression_code).as_bool();
1.176 paf 1018: }
1.275 misha 1019:
1020: static bool _locate_expression(Table& table, Request& r, MethodParams& params) {
1.182 paf 1021: Value& expression_code=params.as_junction(0, "must be expression");
1.303 moko 1022: Table::Action_options o=get_action_options(r, params, 1, table);
1023: if(params.count()>2)
1024: throw Exception(PARSER_RUNTIME, 0, "locate by expression only has parameters: expression and, maybe, options");
1.182 paf 1025: Expression_is_true_info info={&r, &expression_code};
1026: return table.table_first_that(expression_is_true, &info, o);
1.145 paf 1027: }
1.275 misha 1028:
1029: static bool _locate_name_value(Table& table, Request& r, MethodParams& params) {
1.182 paf 1030: const String& name=params.as_string(0, "column name must be string");
1.232 misha 1031: const String& value=params.as_string(1, VALUE_MUST_BE_STRING);
1.303 moko 1032: Table::Action_options o=get_action_options(r, params, 2, table);
1.182 paf 1033: return table.locate(name, value, o);
1034: }
1.275 misha 1035:
1.182 paf 1036: static void _locate(Request& r, MethodParams& params) {
1037: Table& table=GET_SELF(r, VTable).table();
1.72 paf 1038:
1.291 moko 1039: bool result=params[0].get_junction() || (params.count() == 1) ?
1.275 misha 1040: _locate_expression(table, r, params) :
1041: _locate_name_value(table, r, params);
1.249 misha 1042: r.write_no_lang(VBool::get(result));
1.145 paf 1043: }
1.182 paf 1044:
1045:
1.191 paf 1046: static void _flip(Request& r, MethodParams&) {
1.182 paf 1047: Table& old_table=GET_SELF(r, VTable).table();
1.184 paf 1048: Table& new_table=*new Table(0);
1.182 paf 1049: if(size_t old_count=old_table.count())
1.310 moko 1050: if(size_t old_cols=old_table.columns()?old_table.columns()->count():old_table.max_cells())
1.182 paf 1051: for(size_t column=0; column<old_cols; column++) {
1052: Table::element_type new_row(new ArrayString(old_count));
1053: for(size_t i=0; i<old_count; i++) {
1054: Table::element_type old_row=old_table[i];
1055: *new_row+=column<old_row->count()?old_row->get(column):new String;
1.39 paf 1056: }
1.182 paf 1057: new_table+=new_row;
1.39 paf 1058: }
1059:
1.182 paf 1060: r.write_no_lang(*new VTable(&new_table));
1.39 paf 1061: }
1062:
1.293 misha 1063: static void _foreach(Request& r, MethodParams& params) {
1064: InCycle temp(r);
1065:
1066: const String& rownum_name=params.as_string(0, "rownum-var name must be string");
1067: const String& value_name=params.as_string(1, "value-var name must be string");
1068:
1069: Value& body_code=params.as_junction(2, "body must be code");
1070:
1071: Value* delim_maybe_code=params.count()>3?¶ms[3]:0;
1072:
1073: Table& table=GET_SELF(r, VTable).table();
1074: size_t saved_current=table.current();
1075:
1076: const String* rownum_var_name=rownum_name.is_empty()? 0 : &rownum_name;
1077: const String* value_var_name=value_name.is_empty()? 0 : &value_name;
1078:
1079: Value* var_context=r.get_method_frame()->caller();
1080:
1081: if(delim_maybe_code) { // delimiter set
1082: bool need_delim=false;
1.316 moko 1083: for(size_t row=0; row<table.count(); row++) {
1.293 misha 1084: table.set_current(row);
1085:
1086: if(rownum_var_name)
1.299 moko 1087: r.put_element(*var_context, *rownum_var_name, new VString(*new String(String::Body::Format(row), String::L_CLEAN)));
1.293 misha 1088: if(value_var_name)
1.299 moko 1089: r.put_element(*var_context, *value_var_name, new VTable(&table));
1.293 misha 1090:
1091: StringOrValue sv_processed=r.process(body_code);
1092: Request::Skip lskip=r.get_skip(); r.set_skip(Request::SKIP_NOTHING);
1093:
1094: const String* s_processed=sv_processed.get_string();
1095: if(s_processed && !s_processed->is_empty()) { // we have body
1096: if(need_delim) // need delim & iteration produced string?
1097: r.write_pass_lang(r.process(*delim_maybe_code));
1098: else
1099: need_delim=true;
1100: }
1101:
1102: r.write_pass_lang(sv_processed);
1103:
1104: if(lskip==Request::SKIP_BREAK)
1105: break;
1106: }
1107: } else {
1.316 moko 1108: for(size_t row=0; row<table.count(); row++) {
1.293 misha 1109: table.set_current(row);
1110:
1111: if(rownum_var_name)
1.300 moko 1112: r.put_element(*var_context, *rownum_var_name, new VString(*new String(String::Body::Format(row), String::L_CLEAN)));
1.293 misha 1113: if(value_var_name)
1.300 moko 1114: r.put_element(*var_context, *value_var_name, new VTable(&table));
1.293 misha 1115:
1116: r.process_write(body_code);
1117: Request::Skip lskip=r.get_skip(); r.set_skip(Request::SKIP_NOTHING);
1118:
1119: if(lskip==Request::SKIP_BREAK)
1120: break;
1121: }
1122: }
1123: table.set_current(saved_current);
1124: }
1125:
1.309 moko 1126: static void update_cell(HashStringValue::key_type aname, HashStringValue::value_type avalue, VTable *dest) {
1127: dest->put_element(String(aname, String::L_CLEAN), avalue); // new not required
1128: }
1129:
1130: inline Table::element_type row_from_string(Request& r, Value ¶m){
1131: if(!param.is_string() && !param.get_junction())
1132: throw Exception(PARSER_RUNTIME, 0, "row must be string, code or hash");
1133:
1.182 paf 1134: Temp_lang temp_lang(r, String::L_PASS_APPENDED);
1.309 moko 1135: const String& string=r.process_to_string(param);
1.41 paf 1136:
1137: // parse cells
1.182 paf 1138: Table::element_type row=new ArrayString;
1139: size_t pos_after=0;
1140: string.split(*row, pos_after, "\t", String::L_AS_IS);
1.41 paf 1141:
1.309 moko 1142: return row;
1.41 paf 1143: }
1144:
1.309 moko 1145: static void _append(Request& r, MethodParams& params) {
1146: VTable vtable=GET_SELF(r, VTable);
1147: Table& table=vtable.table();
1.306 moko 1148:
1.309 moko 1149: HashStringValue* hash=params[0].get_hash();
1150: if(hash){
1151: table+=new ArrayString();
1152: size_t saved_current=table.current();
1153: table.set_current(table.count()-1);
1154: hash->for_each<VTable*>(update_cell, &vtable);
1155: table.set_current(saved_current);
1156: } else {
1157: table+=row_from_string(r, params[0]);
1158: }
1159: }
1.306 moko 1160:
1.309 moko 1161: static void _insert(Request& r, MethodParams& params) {
1162: VTable vtable=GET_SELF(r, VTable);
1163: Table& table=vtable.table();
1164: HashStringValue* hash=params[0].get_hash();
1165: if(hash){
1166: table.insert(table.current(), new ArrayString());
1167: hash->for_each<VTable*>(update_cell, &vtable);
1168: } else {
1169: table.insert(table.current(), row_from_string(r, params[0]));
1170: }
1.306 moko 1171: }
1172:
1.311 moko 1173: static void _delete(Request& r, MethodParams&) {
1.307 moko 1174: Table& table=GET_SELF(r, VTable).table();
1175: table.remove_current();
1176: }
1177:
1.182 paf 1178: static void join_named_row(Table& src, Table* dest) {
1179: Table::columns_type dest_columns=dest->columns();
1180: size_t dest_columns_count=dest_columns->count();
1181: Table::element_type dest_row(new ArrayString(dest_columns_count));
1182: for(size_t dest_column=0; dest_column<dest_columns_count; dest_column++) {
1183: const String* src_item=src.item(*dest_columns->get(dest_column));
1184: *dest_row+=src_item?src_item:new String;
1185: }
1186: *dest+=dest_row;
1187: }
1188: static void join_nameless_row(Table& src, Table* dest) {
1189: *dest+=src[src.current()];
1190: }
1191: static void _join(Request& r, MethodParams& params) {
1.288 misha 1192: Table& src=*params.as_table(0, "source");
1.176 paf 1193:
1.268 misha 1194: Table::Action_options o=get_action_options(r, params, 1, src);
1.42 paf 1195:
1.182 paf 1196: Table& dest=GET_SELF(r, VTable).table();
1.42 paf 1197: if(&src == &dest)
1.318 ! moko 1198: throw Exception(PARSER_RUNTIME, 0, "source and destination are same table");
1.42 paf 1199:
1.193 paf 1200: if(dest.columns()) // dest is named
1.182 paf 1201: src.table_for_each(join_named_row, &dest, o);
1202: else // dest is nameless
1203: src.table_for_each(join_nameless_row, &dest, o);
1.42 paf 1204: }
1205:
1.94 parser 1206: #ifndef DOXYGEN
1.169 paf 1207: class Table_sql_event_handlers: public SQL_Driver_query_event_handlers {
1.182 paf 1208: ArrayString& columns;
1.218 paf 1209: int columns_count;
1.182 paf 1210: ArrayString* row;
1.94 parser 1211: public:
1.182 paf 1212: Table* table;
1213: public:
1214: Table_sql_event_handlers() :
1215: columns(*new ArrayString), row(0), table(0) {
1.94 parser 1216: }
1217:
1.279 misha 1218: bool add_column(SQL_Error& error, const char *str, size_t ) {
1.170 paf 1219: try {
1.274 moko 1220: columns+=new String(str, String::L_TAINTED /* no length as 0x00 can be inside */);
1.170 paf 1221: return false;
1222: } catch(...) {
1223: error=SQL_Error("exception occured in Table_sql_event_handlers::add_column");
1224: return true;
1225: }
1226: }
1227: bool before_rows(SQL_Error& error) {
1228: try {
1.182 paf 1229: table=new Table(&columns);
1.218 paf 1230: columns_count=columns.count();
1.170 paf 1231: return false;
1232: } catch(...) {
1233: error=SQL_Error("exception occured in Table_sql_event_handlers::before_rows");
1234: return true;
1235: }
1236: }
1237: bool add_row(SQL_Error& error) {
1238: try {
1.218 paf 1239: *table+=row=new ArrayString(columns_count);
1.170 paf 1240: return false;
1241: } catch(...) {
1242: error=SQL_Error("exception occured in Table_sql_event_handlers::add_row");
1243: return true;
1244: }
1245: }
1.279 misha 1246: bool add_row_cell(SQL_Error& error, const char* str, size_t ) {
1.170 paf 1247: try {
1.292 misha 1248: *row+=str?new String(str, String::L_TAINTED /* no length as 0x00 can be inside */):&String::Empty;
1.170 paf 1249: return false;
1250: } catch(...) {
1251: error=SQL_Error("exception occured in Table_sql_event_handlers::add_row_cell");
1252: return true;
1253: }
1.94 parser 1254: }
1255: };
1256: #endif
1.204 paf 1257:
1258: static void marshal_bind(
1259: HashStringValue::key_type aname,
1260: HashStringValue::value_type avalue,
1261: SQL_Driver::Placeholder** pptr)
1262: {
1263: SQL_Driver::Placeholder& ph=**pptr;
1264: ph.name=aname.cstr();
1.261 misha 1265: ph.value=avalue->as_string().untaint_cstr(String::L_AS_IS);
1.204 paf 1266: ph.is_null=avalue->get_class()==void_class;
1267: ph.were_updated=false;
1268:
1269: (*pptr)++;
1270: }
1271:
1272: // not static, used elsewhere
1273: int marshal_binds(HashStringValue& hash, SQL_Driver::Placeholder*& placeholders) {
1274: int hash_count=hash.count();
1.302 moko 1275: placeholders=new SQL_Driver::Placeholder[hash_count];
1.204 paf 1276: SQL_Driver::Placeholder* ptr=placeholders;
1.221 paf 1277: hash.for_each<SQL_Driver::Placeholder**>(marshal_bind, &ptr);
1.204 paf 1278: return hash_count;
1279: }
1280:
1281: // not static, used elsewhere
1282: void unmarshal_bind_updates(HashStringValue& hash, int placeholder_count, SQL_Driver::Placeholder* placeholders) {
1283: SQL_Driver::Placeholder* ph=placeholders;
1284: for(int i=0; i<placeholder_count; i++, ph++)
1285: if(ph->were_updated) {
1286: Value* value;
1287: if(ph->is_null)
1.248 misha 1288: value=VVoid::get();
1.204 paf 1289: else
1.256 misha 1290: value=new VString(*new String(ph->value, String::L_TAINTED));
1.204 paf 1291: hash.put(ph->name, value);
1292: }
1293: }
1294:
1.182 paf 1295: static void _sql(Request& r, MethodParams& params) {
1296: Value& statement=params.as_junction(0, "statement must be code");
1.49 paf 1297:
1.204 paf 1298: HashStringValue* bind=0;
1.244 misha 1299: ulong limit=SQL_NO_LIMIT;
1.100 parser 1300: ulong offset=0;
1.281 misha 1301: if(params.count()>1)
1.288 misha 1302: if(HashStringValue* options=params.as_hash(1, "sql options")) {
1.281 misha 1303: int valid_options=0;
1304: if(Value* vbind=options->get(sql_bind_name)) {
1305: valid_options++;
1306: bind=vbind->get_hash();
1307: }
1308: if(Value* vlimit=options->get(sql_limit_name)) {
1309: valid_options++;
1310: limit=(ulong)r.process_to_value(*vlimit).as_double();
1311: }
1312: if(Value* voffset=options->get(sql_offset_name)) {
1313: valid_options++;
1314: offset=(ulong)r.process_to_value(*voffset).as_double();
1315: }
1316: if(valid_options!=options->count())
1317: throw Exception(PARSER_RUNTIME, 0, CALLED_WITH_INVALID_OPTION);
1318: }
1.49 paf 1319:
1.204 paf 1320: SQL_Driver::Placeholder* placeholders=0;
1321: uint placeholders_count=0;
1322: if(bind)
1323: placeholders_count=marshal_binds(*bind, placeholders);
1324:
1.182 paf 1325: Temp_lang temp_lang(r, String::L_SQL);
1326: const String& statement_string=r.process_to_string(statement);
1.262 misha 1327: const char* statement_cstr=statement_string.untaint_cstr(r.flang, r.connection());
1.260 misha 1328:
1.182 paf 1329: Table_sql_event_handlers handlers;
1.294 moko 1330:
1.182 paf 1331: r.connection()->query(
1.203 paf 1332: statement_cstr,
1.208 paf 1333: placeholders_count, placeholders,
1.203 paf 1334: offset, limit,
1.160 paf 1335: handlers,
1336: statement_string);
1.135 paf 1337:
1.204 paf 1338: if(bind)
1339: unmarshal_bind_updates(*bind, placeholders_count, placeholders);
1.96 parser 1340:
1.182 paf 1341: Table& result=
1342: handlers.table?*handlers.table: // query resulted in table? return it
1343: *new Table(Table::columns_type(0)); // query returned no table, fake it
1.49 paf 1344:
1345: // replace any previous table value
1.182 paf 1346: GET_SELF(r, VTable).set_table(result);
1.49 paf 1347: }
1348:
1.233 misha 1349: static void _columns(Request& r, MethodParams& params) {
1350: const String* column_column_name;
1351: if(params.count()>0)
1352: column_column_name=¶ms.as_string(0, COLUMN_NAME_MUST_BE_STRING);
1353: else
1354: column_column_name=new String("column");
1.88 parser 1355:
1.182 paf 1356: Table::columns_type result_columns(new ArrayString);
1.233 misha 1357: *result_columns+=column_column_name;
1.182 paf 1358: Table& result_table=*new Table(result_columns);
1.88 parser 1359:
1.182 paf 1360: Table& source_table=GET_SELF(r, VTable).table();
1361: if(Table::columns_type source_columns=source_table.columns()) {
1362: for(Array_iterator<const String*> i(*source_columns); i.has_next(); ) {
1363: Table::element_type result_row(new ArrayString);
1364: *result_row+=i.next();
1365: result_table+=result_row;
1.88 parser 1366: }
1367: }
1368:
1.182 paf 1369: r.write_no_lang(*new VTable(&result_table));
1.88 parser 1370: }
1371:
1.182 paf 1372: static void _select(Request& r, MethodParams& params) {
1.231 misha 1373: Value& vcondition=params.as_expression(0, "condition must be number, bool or expression");
1.148 paf 1374:
1.182 paf 1375: Table& source_table=GET_SELF(r, VTable).table();
1.148 paf 1376:
1.277 moko 1377: int limit=source_table.count();
1.282 misha 1378: int offset=0;
1379: bool reverse=false;
1.278 moko 1380:
1.281 misha 1381: if(params.count()>1)
1382: if(HashStringValue* options=params.as_hash(1)) {
1383: int valid_options=0;
1384: if(Value* vlimit=options->get(sql_limit_name)) {
1385: valid_options++;
1386: limit=r.process_to_value(*vlimit).as_int();
1387: }
1388: if(Value* voffset=options->get(sql_offset_name)) {
1389: valid_options++;
1390: offset=r.process_to_value(*voffset).as_int();
1391: }
1392: if(Value* vreverse=options->get(table_reverse_name)) {
1393: valid_options++;
1394: reverse=r.process_to_value(*vreverse).as_bool();
1395: }
1396: if(valid_options!=options->count())
1.288 misha 1397: throw Exception(PARSER_RUNTIME, 0, CALLED_WITH_INVALID_OPTION);
1.281 misha 1398: }
1399:
1400: Table& result_table=*new Table(source_table.columns());
1.277 moko 1401:
1.283 misha 1402: size_t size=source_table.count();
1403: if(offset<0)
1404: offset+=size;
1.284 misha 1405: if(size && limit>0 && offset>=0 && (size_t)offset<size){
1.282 misha 1406: size_t saved_current=source_table.current();
1407: size_t appended=0;
1408:
1409: if(reverse){
1410: for(size_t row=size-1; result_table.count() < (size_t)limit; row--) {
1411: source_table.set_current(row);
1412:
1413: bool condition=r.process_to_value(vcondition, false/*don't intercept string*/).as_bool();
1414:
1415: if(condition && ++appended > (size_t)offset) // ...condition is true, adding to the result
1416: result_table+=source_table[row];
1417: if(row==0) break;
1418: }
1419: } else {
1420: for(size_t row=0; row < size && result_table.count() < (size_t)limit; row++) {
1421: source_table.set_current(row);
1.148 paf 1422:
1.282 misha 1423: bool condition=r.process_to_value(vcondition, false/*don't intercept string*/).as_bool();
1.277 moko 1424:
1.282 misha 1425: if(condition && ++appended > (size_t)offset) // ...condition is true, adding to the result
1426: result_table+=source_table[row];
1427: }
1.277 moko 1428: }
1.282 misha 1429: source_table.set_current(saved_current);
1.148 paf 1430: }
1431:
1.182 paf 1432: r.write_no_lang(*new VTable(&result_table));
1.148 paf 1433: }
1434:
1.66 paf 1435: // constructor
1436:
1.182 paf 1437: MTable::MTable(): Methoded("table") {
1.142 paf 1438: // ^table::create{data}
1439: // ^table::create[nameless]{data}
1440: // ^table::create[table]
1.236 misha 1441: add_native_method("create", Method::CT_DYNAMIC, _create, 1, 3);
1.142 paf 1442: // old name for compatibility with <= v 1.141 2002/01/25 11:33:45 paf
1.236 misha 1443: add_native_method("set", Method::CT_DYNAMIC, _create, 1, 3);
1.2 paf 1444:
1.142 paf 1445: // ^table::load[file]
1446: // ^table::load[nameless;file]
1.168 paf 1447: add_native_method("load", Method::CT_DYNAMIC, _load, 1, 3);
1.22 paf 1448:
1449: // ^table.save[file]
1450: // ^table.save[nameless;file]
1.188 paf 1451: add_native_method("save", Method::CT_DYNAMIC, _save, 1, 3);
1.6 paf 1452:
1.224 misha 1453: // add_native_method("save_old", Method::CT_DYNAMIC, _save_old, 1, 3);
1454:
1.297 moko 1455: // ^table.csv-string[]
1456: // ^table.csv-string[nameless]
1457: // ^table.csv-string[nameless;$.encloser["] $.separator[,]]
1458: add_native_method("csv-string", Method::CT_DYNAMIC, _csv_string, 0, 2);
1459:
1.6 paf 1460: // ^table.count[]
1.280 misha 1461: // ^table.count[rows]
1462: // ^table.count[columns]
1463: // ^table.count[cells]
1464: add_native_method("count", Method::CT_DYNAMIC, _count, 0, 1);
1.6 paf 1465:
1466: // ^table.line[]
1.66 paf 1467: add_native_method("line", Method::CT_DYNAMIC, _line, 0, 0);
1.6 paf 1468:
1.10 paf 1469: // ^table.offset[]
1.133 paf 1470: // ^table.offset(offset)
1471: // ^table.offset[cur|set](offset)
1472: add_native_method("offset", Method::CT_DYNAMIC, _offset, 0, 2);
1.7 paf 1473:
1.10 paf 1474: // ^table.menu{code}
1475: // ^table.menu{code}[delim]
1.66 paf 1476: add_native_method("menu", Method::CT_DYNAMIC, _menu, 1, 2);
1.74 paf 1477:
1.239 misha 1478: // ^table.hash[key field name]
1479: // ^table.hash[key field name][value field name(s) string/table]
1.163 paf 1480: add_native_method("hash", Method::CT_DYNAMIC, _hash, 1, 3);
1.32 paf 1481:
1.102 parser 1482: // ^table.sort{string-key-maker} ^table.sort{string-key-maker}[desc|asc]
1483: // ^table.sort(numeric-key-maker) ^table.sort(numeric-key-maker)[desc|asc]
1.66 paf 1484: add_native_method("sort", Method::CT_DYNAMIC, _sort, 1, 2);
1.8 paf 1485:
1.36 paf 1486: // ^table.locate[field;value]
1.176 paf 1487: add_native_method("locate", Method::CT_DYNAMIC, _locate, 1, 3);
1.39 paf 1488:
1489: // ^table.flip[]
1.66 paf 1490: add_native_method("flip", Method::CT_DYNAMIC, _flip, 0, 0);
1.41 paf 1491:
1.293 misha 1492: // ^table.foreach[row-num;value]{code}
1493: // ^table.foreach[row-num;value]{code}[delim]
1494: add_native_method("foreach", Method::CT_DYNAMIC, _foreach, 3, 4);
1495:
1.306 moko 1496: // ^table.append{row{tab}data}
1.66 paf 1497: add_native_method("append", Method::CT_DYNAMIC, _append, 1, 1);
1.42 paf 1498:
1.306 moko 1499: // ^table.insert{row{tab}data} before current row
1500: add_native_method("insert", Method::CT_DYNAMIC, _insert, 1, 1);
1501:
1.307 moko 1502: // ^table.delete[] current row
1503: add_native_method("delete", Method::CT_DYNAMIC, _delete, 0, 0);
1504:
1.157 paf 1505: // ^table.join[table][$.limit(10) $.offset(1) $.offset[cur] ]
1506: add_native_method("join", Method::CT_DYNAMIC, _join, 1, 2);
1.49 paf 1507:
1508:
1.239 misha 1509: // ^table::sql[query]
1510: // ^table::sql[query][$.limit(1) $.offset(2)]
1.100 parser 1511: add_native_method("sql", Method::CT_DYNAMIC, _sql, 1, 2);
1.88 parser 1512:
1.239 misha 1513: // ^table.columns[[column name]]
1.233 misha 1514: add_native_method("columns", Method::CT_DYNAMIC, _columns, 0, 1);
1.148 paf 1515:
1516: // ^table.select(expression) = table
1.277 moko 1517: add_native_method("select", Method::CT_DYNAMIC, _select, 1, 2);
1.40 paf 1518: }
E-mail: