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