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