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