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