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