--- parser3/src/classes/table.C 2011/11/23 12:17:23 1.284 +++ parser3/src/classes/table.C 2016/09/06 22:38:44 1.320 @@ -1,16 +1,10 @@ /** @file Parser: @b table parser class. - Copyright (c) 2001-2009 ArtLebedev Group (http://www.artlebedev.com) + Copyright (c) 2001-2015 Art. Lebedev Studio (http://www.artlebedev.com) Author: Alexandr Petrosian (http://paf.design.ru) */ -static const char * const IDENT_TABLE_C="$Date: 2011/11/23 12:17:23 $"; - -#if (!defined(NO_STRINGSTREAM) && !defined(FREEBSD4)) -#include -#endif - #include "classes.h" #include "pa_vmethod_frame.h" @@ -23,6 +17,13 @@ static const char * const IDENT_TABLE_C= #include "pa_vbool.h" #include "pa_array.h" +#if (!defined(NO_STRINGSTREAM) && !defined(FREEBSD4)) +#include +#define USE_STRINGSTREAM +#endif + +volatile const char * IDENT_TABLE_C="$Id: table.C,v 1.320 2016/09/06 22:38:44 moko Exp $"; + // class class MTable: public Methoded { @@ -34,7 +35,7 @@ public: // global variable -DECLARE_CLASS_VAR(table, new MTable, 0); +DECLARE_CLASS_VAR(table, new MTable); #define TABLE_REVERSE_NAME "reverse" @@ -50,26 +51,12 @@ String table_reverse_name(TABLE_REVERSE_ // methods -static Table::Action_options get_action_options(Request& r, MethodParams& params, - size_t options_index, const Table& source) { +static Table::Action_options get_action_options(Request& r, MethodParams& params, size_t options_index, const Table& source) { Table::Action_options result; if(params.count() <= options_index) return result; - Value& maybe_options=params[options_index]; -/* can not do it: - want to enable ^table::create[$source; -# $.option[] - ] - but there is ^table.locate[name;value] - - ...if(voptions.is_defined() && !voptions.is_string())) - if(maybe_options.is_string()) { // allow empty options - result.defined=true; - return result; - } -*/ - HashStringValue* options=maybe_options.get_hash(); + HashStringValue* options=params.as_hash(options_index); if(!options) return result; @@ -85,9 +72,7 @@ static Table::Action_options get_action_ if(soffset == "cur") result.offset=source.current(); else - throw Exception(PARSER_RUNTIME, - &soffset, - "must be 'cur' string or expression"); + throw Exception(PARSER_RUNTIME, &soffset, "must be 'cur' string or expression"); } else result.offset=r.process_to_value(*voffset).as_int(); } @@ -107,53 +92,52 @@ static Table::Action_options get_action_ return result; } -static void check_option_param(bool options_defined, - MethodParams& params, size_t next_param_index, - const char *msg) { - if(next_param_index+(options_defined?1:0) != params.count()) - throw Exception(PARSER_RUNTIME, - 0, - "%s", msg); -} -struct TableSeparators { - char column; const String* scolumn; +struct TableControlChars { + char separator; const String* sseparator; char encloser; const String* sencloser; - TableSeparators(): - column('\t'), scolumn(new String("\t")), + char separators[3]; + + TableControlChars(): + separator('\t'), sseparator(new String("\t")), encloser(0), sencloser(0) - {} + { + strcpy(separators,"\t\n"); + } + int load( HashStringValue& options ) { int result=0; if(Value* vseparator=options.get(PA_COLUMN_SEPARATOR_NAME)) { - scolumn=&vseparator->as_string(); - if(scolumn->length()!=1) - throw Exception(PARSER_RUNTIME, - scolumn, - "separator must be one character long"); - column=scolumn->first_char(); + sseparator=&vseparator->as_string(); + if(sseparator->length()!=1) + throw Exception(PARSER_RUNTIME, sseparator, "separator must be one character long"); + separator=sseparator->first_char(); + separators[0]=separator; result++; } if(Value* vencloser=options.get(PA_COLUMN_ENCLOSER_NAME)) { sencloser=&vencloser->as_string(); + if(sencloser->is_empty()){ + encloser=0; + } else { if(sencloser->length()!=1) - throw Exception(PARSER_RUNTIME, - sencloser, - "encloser must be one character long"); + throw Exception(PARSER_RUNTIME, sencloser, "encloser must be one character long"); encloser=sencloser->first_char(); + } result++; } return result; } }; + static void _create(Request& r, MethodParams& params) { // clone/copy part? if(Table *source=params[0].get_table()) { Table::Action_options o=get_action_options(r, params, 1, *source); - check_option_param(o.defined, params, 1, - "too many parameters"); + if(params.count()>2) + throw Exception(PARSER_RUNTIME, 0, "too many parameters"); GET_SELF(r, VTable).set_table(*new Table(*source, o)); return; } @@ -165,36 +149,32 @@ static void _create(Request& r, MethodPa if(params[0].is_string()){ // can be nameless only const String& snameless=params.as_string(0, "called with more then 1 param, first param may be only string 'nameless' or junction"); if(snameless!="nameless") - throw Exception(PARSER_RUNTIME, - &snameless, - "table::create called with more then 1 param, first param may be only 'nameless'"); + throw Exception(PARSER_RUNTIME, &snameless, "table::create called with more then 1 param, first param may be only 'nameless'"); nameless=true; data_param_index++; } } HashStringValue *options=0; - TableSeparators separators; + TableControlChars control_chars; size_t options_param_index=data_param_index+1; if( options_param_indexsplit(*columns, col_pos_after, *separators.scolumn, String::L_AS_IS); + if(head[0]->is_empty()) + *columns += new String(); + else + head[0]->split(*columns, col_pos_after, *control_chars.sseparator, String::L_AS_IS); } } @@ -227,7 +210,7 @@ static void _create(Request& r, MethodPa continue; size_t col_pos_after=0; - string.split(*row, col_pos_after, *separators.scolumn, String::L_AS_IS); + string.split(*row, col_pos_after, *control_chars.sseparator, String::L_AS_IS); table+=row; } @@ -242,10 +225,9 @@ struct lsplit_result { operator bool() { return piece!=0; } }; -inline lsplit_result lsplit(char* string, char delim1, char delim2) { +inline lsplit_result lsplit(char* string, const char* delims) { lsplit_result result; if(string) { - char delims[]={delim1, delim2, 0}; if(char* v=strpbrk(string, delims)) { result.delim=*v; *v=0; @@ -258,16 +240,16 @@ inline lsplit_result lsplit(char* string return result; } -inline lsplit_result lsplit(char* *string_ref, char delim1, char delim2) { +inline lsplit_result lsplit(char* *string_ref, const char* delims) { lsplit_result result; result.piece=*string_ref; - lsplit_result next=lsplit(*string_ref, delim1, delim2); + lsplit_result next=lsplit(*string_ref, delims); result.delim=next.delim; *string_ref=next.piece; return result; } -static lsplit_result lsplit(char** string_ref, char delim1, char delim2, char encloser) { +static lsplit_result lsplit(char** string_ref, const char* delims, char encloser) { lsplit_result result; if(char* string=*string_ref) { @@ -278,26 +260,30 @@ static lsplit_result lsplit(char** strin char *write; write=read=string; char c; - while((c=*read++)) { + // we are enclosed, searching for second encloser + while(c=*read++) { if(c==encloser) { - char n=*read; - if(n==encloser) // double-encloser stands for encloser + if(*read==encloser) // double-encloser stands for encloser read++; - else if(n==delim1 || n==delim2) { - result.delim=n; - read++; - break; - } + else + break; // note: skipping encloser } - *write++=c; } + // we are no longer enclosed, searching for delimiter, skipping extra enclosers + while(c=*read++) { + if(c==delims[0] || c==delims[1]) { + result.delim=c; + break; + } else if(c!=encloser) + *write++=c; + } *write=0; // terminate *string_ref=c? read: 0; result.piece=string; return result; } else - return lsplit(string_ref, delim1, delim2); + return lsplit(string_ref, delims); } result.piece=0; return result; @@ -342,12 +328,12 @@ static void _load(Request& r, MethodPara size_t options_param_index=filename_param_index+1; HashStringValue *options=0; - TableSeparators separators; + TableControlChars control_chars; if(options_param_indexcount()) // append last empty column [if without \n] break; *row+=new String(sr.piece, String::L_TAINTED); @@ -398,57 +384,170 @@ static void _load(Request& r, MethodPara GET_SELF(r, VTable).set_table(table); } -#if (!defined(NO_STRINGSTREAM) && !defined(FREEBSD4)) - +#ifdef USE_STRINGSTREAM #include "gc_allocator.h" typedef std::basic_stringstream, gc_allocator > pa_stringstream; typedef std::basic_string, gc_allocator > pa_string; -void maybe_enclose( pa_stringstream& to, const String& from, char encloser ) { - if(encloser) { +static void enclose( pa_stringstream& to, const String* from, char encloser ) { + if(from){ to<pos( encloser, pos_after ))!=STRING_NOT_FOUND; pos_after=pos_before) { pos_before++; // including first encloser (and skipping it for next pos) - to<mid(pos_after, pos_before).cstr(); to<length(); if(pos_aftermid(pos_after, from_length).cstr(); to< i(*table.columns()); i.has_next(); ) { + enclose( result, i.next(), control_chars.encloser ); + if(i.has_next()) + result< i(*table.columns()); i.has_next(); ) { + result<cstr(); + if(i.has_next()) + result<count():0) + for(int column=0; column i(table); + if(control_chars.encloser){ + while(i.has_next()) { + for(Array_iterator c(*i.next()); c.has_next(); ) { + enclose( result, c.next(), control_chars.encloser ); + if(c.has_next()) + result< c(*i.next()); c.has_next(); ) { + result<cstr(); + if(c.has_next()) + result<pos( encloser, pos_after ))!=STRING_NOT_FOUND; pos_after=pos_before) { pos_before++; // including first encloser (and skipping it for next pos) - to<mid(pos_after, pos_before); to<<*sencloser; // doubling encloser } // last piece - size_t from_length=from.length(); + size_t from_length=from->length(); if(pos_aftermid(pos_after, from_length); to<<*sencloser; - } else - to< i(*table.columns()); i.has_next(); ) { + enclose( result, i.next(), control_chars.encloser, control_chars.sencloser ); + if(i.has_next()) + result<<*control_chars.sseparator; + } + } else { + for(Array_iterator i(*table.columns()); i.has_next(); ) { + result<<*i.next(); + if(i.has_next()) + result<<*control_chars.sseparator; + } + } + } else { // nameless table [we were asked to output column names] + if(int lsize=table.count()?table[0]->count():0) + for(int column=0; column i(table); + if(control_chars.encloser){ + while(i.has_next()) { + for(Array_iterator c(*i.next()); c.has_next(); ) { + enclose( result, c.next(), control_chars.encloser, control_chars.sencloser ); + if(c.has_next()) + result<<*control_chars.sseparator; + } + result.append_know_length("\n", 1, String::L_CLEAN); + } + } else { + while(i.has_next()) { + for(Array_iterator c(*i.next()); c.has_next(); ) { + result<<*c.next(); + if(c.has_next()) + result<<*control_chars.sseparator; + } + result.append_know_length("\n", 1, String::L_CLEAN); + } + } +} #endif // don't use stringstream + static void _save(Request& r, MethodParams& params) { const String& first_arg=params.as_string(0, FIRST_ARG_MUST_NOT_BE_CODE); size_t param_index=1; @@ -470,119 +569,76 @@ static void _save(Request& r, MethodPara if(do_append && file_exist(file_spec)) output_column_names=false; - TableSeparators separators; + TableControlChars control_chars; if(param_indexcount()) throw Exception(PARSER_RUNTIME, 0, CALLED_WITH_INVALID_OPTION); } if(param_index i(*table.columns()); i.has_next(); ) { - maybe_enclose( ost, *i.next(), separators.encloser ); - if(i.has_next()){ - ost<count():0) - for(int column=0; column i(table); - while(i.has_next()) { - for(Array_iterator c(*i.next()); c.has_next(); ) { - maybe_enclose( ost, *c.next(), separators.encloser ); - if(c.has_next()) - ost< i(*table.columns()); i.has_next(); ) { - maybe_enclose( sdata, *i.next(), separators.encloser, separators.sencloser ); - if(i.has_next()) - sdata<<*separators.scolumn; - } - } else { // nameless table [we were asked to output column names] - if(int lsize=table.count()?table[0]->count():0) - for(int column=0; column i(table); - while(i.has_next()) { - for(Array_iterator c(*i.next()); c.has_next(); ) { - maybe_enclose( sdata, *c.next(), separators.encloser, separators.sencloser ); - if(c.has_next()) - sdata<<*separators.scolumn; - } - sdata.append_know_length("\n", 1, String::L_CLEAN); - } + table_to_csv(sdata, table, control_chars, output_column_names); // write - { const char* data_cstr=sdata.cstr(); - file_write(r.charsets, file_spec, data_cstr, sdata.length(), true, do_append); + file_write(r.charsets, file_spec, data_cstr, sdata.length(), true /* as text */, do_append); if(*data_cstr) // not empty (when empty it's not heap memory) pa_free((void*)data_cstr); // not needed anymore +#endif +} + +static void _csv_string(Request& r, MethodParams& params) { + bool output_column_names=true; + size_t param_index=0; + if(params.count()>0 && params[0].is_string()) { + if(params.as_string(0, FIRST_ARG_MUST_NOT_BE_CODE)=="nameless") { + output_column_names=false; + param_index++; + } else { + throw Exception(PARSER_RUNTIME, 0, "bad mode (must be nameless)"); + } } -#endif // don't use stringstream + TableControlChars control_chars; + if(param_indexcount()) + throw Exception(PARSER_RUNTIME, 0, CALLED_WITH_INVALID_OPTION); + } + + Table& table=GET_SELF(r, VTable).table(); + +#ifdef USE_STRINGSTREAM + pa_stringstream ost(std::stringstream::out); + + table_to_csv(ost, table, control_chars, output_column_names); + + r.write_no_lang(*new VString(*new String(pa_strdup(ost.str().c_str()), String::L_CLEAN))); +#else + String sdata; + + table_to_csv(sdata, table, control_chars, output_column_names); + + r.write_no_lang(*new VString(*new String(sdata.cstr(), String::L_CLEAN))); +#endif } static void _count(Request& r, MethodParams& params) { @@ -591,7 +647,7 @@ static void _count(Request& r, MethodPar if(params.count()) { const String& param=params.as_string(0, PARAMETER_MUST_BE_STRING); if(param == "columns") - result = table.columns() ? table.columns()->count() : 0; + result = table.columns() ? table.columns()->count() : table.max_cells(); else if(param == "cells") result = table.count() ? table[table.current()]->count() : 0; else if(param == "rows") // synonim for ^table.count[] @@ -620,9 +676,7 @@ static void _offset(Request& r, MethodPa else if(whence=="set") absolute=true; else - throw Exception(PARSER_RUNTIME, - &whence, - "is invalid whence, valid are 'cur' or 'set'"); + throw Exception(PARSER_RUNTIME, &whence, "is invalid whence, valid are 'cur' or 'set'"); } int offset=params.as_int(params.count()-1, "offset must be expression", r); @@ -639,12 +693,11 @@ static void _menu(Request& r, MethodPara Value* delim_maybe_code=params.count()>1?¶ms[1]:0; Table& table=GET_SELF(r, VTable).table(); - int saved_current=table.current(); - int size=table.count(); + size_t saved_current=table.current(); if(delim_maybe_code) { // delimiter set bool need_delim=false; - for(int row=0; row* value_fields; + Value* value_code; HashStringValue* hash; Table2hash_distint distinct; size_t row; @@ -706,8 +760,12 @@ static void table_row_to_hash(Table::ele bool exist=false; switch(info->value_type) { case C_STRING: { - size_t index=info->value_fields->get(0); - exist=info->hash->put_dont_replace(*key, (index < row->count()) ? new VString(*row->get(index)) : new VString()); + if(info->value_fields->count()){ + size_t index=info->value_fields->get(0); + exist=info->hash->put_dont_replace(*key, (index < row->count()) ? new VString(*row->get(index)) : VString::empty()); + } else { + exist=info->hash->put_dont_replace(*key, VString::empty()); + } break; } case C_HASH: { @@ -716,9 +774,7 @@ static void table_row_to_hash(Table::ele for(Array_iterator i(*info->value_fields); i.has_next(); ) { size_t value_field=i.next(); if(value_fieldcount()) - hash.put( - *info->table->columns()->get(value_field), - new VString(*row->get(value_field))); + hash.put(*info->table->columns()->get(value_field), new VString(*row->get(value_field))); } exist=info->hash->put_dont_replace(*key, vhash); @@ -739,14 +795,20 @@ static void table_row_to_hash(Table::ele table=new Table(*info->table, table_options/*no rows, just structure*/); info->hash->put(*key, new VTable(table)); } - *table+=row; + Table::element_type row_copy(new ArrayString(row->count())); + row_copy->append(*row); + *table+=row_copy; + break; + } + case C_CODE: { + if(!info->key_code) + info->table->set_current(info->row++); // change context row + exist=info->hash->put_dont_replace(*key, &info->r->process(*info->value_code).as_value()); break; } } if(exist && info->distinct==D_ILLEGAL) - throw Exception(PARSER_RUNTIME, - key, - "duplicate key"); + throw Exception(PARSER_RUNTIME, key, "duplicate key"); } Table2hash_value_type get_value_type(Value& vvalue_type){ @@ -759,17 +821,24 @@ Table2hash_value_type get_value_type(Val } else if (svalue_type == "hash") { return C_HASH; } else { - throw Exception(PARSER_RUNTIME, - &svalue_type, - "must be 'hash', 'table' or 'string'"); + throw Exception(PARSER_RUNTIME, &svalue_type, "must be 'hash', 'table' or 'string'"); } } else { - throw Exception(PARSER_RUNTIME, - 0, - "'type' must be hash"); + throw Exception(PARSER_RUNTIME, 0, "'type' must be string"); } } +static Table2hash_distint get_distinct(Value& vdistinct, Table2hash_value_type& value_type){ + if(vdistinct.is_string()) { + const String& sdistinct=*vdistinct.get_string(); + if(sdistinct!="tables") + throw Exception(PARSER_RUNTIME, &sdistinct, "must be 'tables' or true/false"); + value_type=C_TABLE; + return D_FIRST; + } + return vdistinct.as_bool() ? D_FIRST : D_ILLEGAL; +} + static void _hash(Request& r, MethodParams& params) { Table& self_table=GET_SELF(r, VTable).table(); VHash& result=*new VHash; @@ -779,32 +848,22 @@ static void _hash(Request& r, MethodPara Table2hash_value_type value_type=C_HASH; int param_index=params.count()-1; if(param_index>0) { - if(HashStringValue* options=params.as_no_junction(param_index, PARAM_MUST_NOT_BE_CODE).get_hash()){ // options where specified + + if(params[1].get_junction()) + value_type=C_CODE; + + if(HashStringValue* options=params[param_index].get_hash()){ // can't use .as_hash because the 2nd param could be table so .as_hash throws an error --param_index; int valid_options=0; if(Value* vdistinct_code=options->get(sql_distinct_name)) { // $.distinct ? valid_options++; - Value& vdistinct_value=r.process_to_value(*vdistinct_code); - if(vdistinct_value.is_string()) { - const String& sdistinct=*vdistinct_value.get_string(); - if(sdistinct=="tables") { - value_type=C_TABLE; - distinct=D_FIRST; - } else { - throw Exception(PARSER_RUNTIME, - &sdistinct, - "must be 'tables' or true/false"); - } - } else { - distinct=vdistinct_value.as_bool()?D_FIRST:D_ILLEGAL; - } + distinct=get_distinct(r.process_to_value(*vdistinct_code), value_type); } if(Value* vvalue_type_code=options->get(sql_value_type_name)) { // $.type ? if(value_type==C_TABLE) // $.distinct[tables] already was specified - throw Exception(PARSER_RUNTIME, - 0, - "you can't specify $.distinct[tables] and $.type[] together"); - + throw Exception(PARSER_RUNTIME, 0, "you can't specify $.distinct[tables] and $.type[] together"); + if(value_type==C_CODE) + throw Exception(PARSER_RUNTIME, 0, "you can't specify $.type[] if value is code"); valid_options++; value_type=get_value_type(r.process_to_value(*vvalue_type_code)); } @@ -814,59 +873,57 @@ static void _hash(Request& r, MethodPara } } - if(param_index==2) // options was specified but not as hash - throw Exception(PARSER_RUNTIME, 0, OPTIONS_MUST_BE_HASH); + if(param_index==2) // options were specified but not as hash + throw Exception(PARSER_RUNTIME, 0, "options must be hash"); Array value_fields; + Value* value_code=0; + if(param_index==0){ // list of columns wasn't specified if(value_type==C_STRING) // $.type[string] - throw Exception(PARSER_RUNTIME, - 0, - "you must specify one value field with option $.type[string]"); + throw Exception(PARSER_RUNTIME, 0, "you must specify one value field with option $.type[string]"); for(size_t i=0; icount(); i++) // by all columns, including key value_fields+=i; - } else { // list of columns was specified + } else { // list of columns or code was specified if(value_type==C_TABLE) - throw Exception(PARSER_RUNTIME, - 0, - "you can't specify value field(s) with option $.distinct[tables] or $.type[tables]"); - - Value& value_fields_param=params.as_no_junction(param_index, "value field(s) must not be code"); - if(value_fields_param.is_string()) { // one column as string was specified - value_fields+=self_table.column_name2index(*value_fields_param.get_string(), true); + throw Exception(PARSER_RUNTIME, 0, "you can't specify value field(s) with option $.distinct[tables] or $.type[tables]"); + + Value& value_fields_param=params[1]; + if(value_fields_param.get_junction()){ // code specified + value_code=&value_fields_param; + } else if(value_fields_param.is_string()) { // one column as string was specified + const String &field_name=*value_fields_param.get_string(); + if(!field_name.is_empty()) + value_fields+=self_table.column_name2index(field_name, true); } else if(Table* value_fields_table=value_fields_param.get_table()) { // list of columns were specified in table for(Array_iterator i(*value_fields_table); i.has_next(); ) { const String& value_field_name =*i.next()->get(0); value_fields +=self_table.column_name2index(value_field_name, true); } } else - throw Exception(PARSER_RUNTIME, - 0, - "value field(s) must be string or table"); + throw Exception(PARSER_RUNTIME, 0, "value field(s) must be string or table or code"); } if(value_type==C_STRING && value_fields.count()!=1) - throw Exception(PARSER_RUNTIME, - 0, - "you can specify only one value field with option $.type[string]"); + throw Exception(PARSER_RUNTIME, 0, "you can specify only one value field with option $.type[string]"); { Value* key_param=¶ms[0]; Row_info info={ &r, &self_table, - /*key_code=*/key_param->get_junction()?key_param:0, + /*key_code=*/key_param->get_junction() ? key_param : 0, /*key_field=*/0/*filled below*/, &value_fields, + value_code, &result.hash(), distinct, /*row=*/0, value_type }; - info.key_field=(info.key_code?-1 - :self_table.column_name2index(key_param->as_string(), true)); + info.key_field=(info.key_code ? -1 : self_table.column_name2index(key_param->as_string(), true)); int saved_current=self_table.current(); self_table.for_each(table_row_to_hash, &info); @@ -924,14 +981,14 @@ static void _sort(Request& r, MethodPara old_table.set_current(i); // calculate key value seq[i].row=old_table[i]; - Value& value=r.process_to_value(key_maker).as_expr_result(true/*return string as-is*/); + Value& value=r.process_to_value(key_maker); if(i==0) // determining key values type by first one key_values_are_strings=value.is_string(); if(key_values_are_strings) seq[i].value.c_str=value.as_string().cstr(); else - seq[i].value.d=value.as_double(); + seq[i].value.d=value.as_expr_result().as_double(); } // @todo: handle this elsewhere @@ -942,8 +999,7 @@ static void _sort(Request& r, MethodPara } // sort keys - _qsort(seq, old_count, sizeof(Table_seq_item), - key_values_are_strings?sort_cmp_string:sort_cmp_double); + qsort(seq, old_count, sizeof(Table_seq_item), key_values_are_strings?sort_cmp_string:sort_cmp_double); // reorder table as they require in 'seq' for(i=0; i2) + throw Exception(PARSER_RUNTIME, 0, "locate by expression only has parameters: expression and, maybe, options"); Expression_is_true_info info={&r, &expression_code}; return table.table_first_that(expression_is_true, &info, o); } @@ -979,17 +1034,14 @@ static bool _locate_expression(Table& ta static bool _locate_name_value(Table& table, Request& r, MethodParams& params) { const String& name=params.as_string(0, "column name must be string"); const String& value=params.as_string(1, VALUE_MUST_BE_STRING); - const size_t options_index=2; - Table::Action_options o=get_action_options(r, params, options_index, table); - check_option_param(o.defined, params, options_index, "locate by name has parameters: name, value and, maybe, options"); - + Table::Action_options o=get_action_options(r, params, 2, table); return table.locate(name, value, o); } static void _locate(Request& r, MethodParams& params) { Table& table=GET_SELF(r, VTable).table(); - bool result=params[0].get_junction()? + bool result=params[0].get_junction() || (params.count() == 1) ? _locate_expression(table, r, params) : _locate_name_value(table, r, params); r.write_no_lang(VBool::get(result)); @@ -1000,7 +1052,7 @@ static void _flip(Request& r, MethodPara Table& old_table=GET_SELF(r, VTable).table(); Table& new_table=*new Table(0); if(size_t old_count=old_table.count()) - if(size_t old_cols=old_table.columns()?old_table.columns()->count():old_table[0]->count()) + if(size_t old_cols=old_table.columns()?old_table.columns()->count():old_table.max_cells()) for(size_t column=0; column3?¶ms[3]:0; + + Table& table=GET_SELF(r, VTable).table(); + size_t saved_current=table.current(); + + const String* rownum_var_name=rownum_name.is_empty()? 0 : &rownum_name; + const String* value_var_name=value_name.is_empty()? 0 : &value_name; + + Value* var_context=r.get_method_frame()->caller(); + + if(delim_maybe_code) { // delimiter set + bool need_delim=false; + for(size_t row=0; rowis_empty()) { // we have body + if(need_delim) // need delim & iteration produced string? + r.write_pass_lang(r.process(*delim_maybe_code)); + else + need_delim=true; + } + + r.write_pass_lang(sv_processed); + + if(lskip==Request::SKIP_BREAK) + break; + } + } else { + for(size_t row=0; rowput_element(String(aname, String::L_CLEAN), avalue); // new not required +} + +inline Table::element_type row_from_string(Request& r, Value ¶m){ + if(!param.is_string() && !param.get_junction()) + throw Exception(PARSER_RUNTIME, 0, "row must be string, code or hash"); + Temp_lang temp_lang(r, String::L_PASS_APPENDED); - const String& string=r.process_to_string(params[0]); + const String& string=r.process_to_string(param); // parse cells Table::element_type row=new ArrayString; size_t pos_after=0; string.split(*row, pos_after, "\t", String::L_AS_IS); - GET_SELF(r, VTable).table()+=row; + return row; +} + +static void _append(Request& r, MethodParams& params) { + VTable vtable=GET_SELF(r, VTable); + Table& table=vtable.table(); + + HashStringValue* hash=params[0].get_hash(); + if(hash){ + table+=new ArrayString(); + size_t saved_current=table.current(); + table.set_current(table.count()-1); + hash->for_each(update_cell, &vtable); + table.set_current(saved_current); + } else { + table+=row_from_string(r, params[0]); + } +} + +static void _insert(Request& r, MethodParams& params) { + VTable vtable=GET_SELF(r, VTable); + Table& table=vtable.table(); + HashStringValue* hash=params[0].get_hash(); + if(hash){ + table.insert(table.current(), new ArrayString()); + hash->for_each(update_cell, &vtable); + } else { + table.insert(table.current(), row_from_string(r, params[0])); + } +} + +static void _delete(Request& r, MethodParams&) { + Table& table=GET_SELF(r, VTable).table(); + table.remove_current(); } static void join_named_row(Table& src, Table* dest) { @@ -1039,22 +1194,13 @@ static void join_nameless_row(Table& src *dest+=src[src.current()]; } static void _join(Request& r, MethodParams& params) { - Table* maybe_src=params.as_no_junction(0, "table ref must not be code").get_table(); - if(!maybe_src) - throw Exception(PARSER_RUNTIME, - 0, - "source is not a table"); - Table& src=*maybe_src; + Table& src=*params.as_table(0, "source"); Table::Action_options o=get_action_options(r, params, 1, src); - check_option_param(o.defined, params, 1, - "invalid extra parameter"); Table& dest=GET_SELF(r, VTable).table(); if(&src == &dest) - throw Exception(PARSER_RUNTIME, - 0, - "source and destination are same table"); + throw Exception(PARSER_RUNTIME, 0, "source and destination are same table"); if(dest.columns()) // dest is named src.table_for_each(join_named_row, &dest, o); @@ -1104,7 +1250,7 @@ public: } bool add_row_cell(SQL_Error& error, const char* str, size_t ) { try { - *row+=new String(str, String::L_TAINTED /* no length as 0x00 can be inside */); + *row+=str?new String(str, String::L_TAINTED /* no length as 0x00 can be inside */):&String::Empty; return false; } catch(...) { error=SQL_Error("exception occured in Table_sql_event_handlers::add_row_cell"); @@ -1131,7 +1277,7 @@ static void marshal_bind( // not static, used elsewhere int marshal_binds(HashStringValue& hash, SQL_Driver::Placeholder*& placeholders) { int hash_count=hash.count(); - placeholders=new(UseGC) SQL_Driver::Placeholder[hash_count]; + placeholders=new SQL_Driver::Placeholder[hash_count]; SQL_Driver::Placeholder* ptr=placeholders; hash.for_each(marshal_bind, &ptr); return hash_count; @@ -1158,7 +1304,7 @@ static void _sql(Request& r, MethodParam ulong limit=SQL_NO_LIMIT; ulong offset=0; if(params.count()>1) - if(HashStringValue* options=params.as_hash(1)) { + if(HashStringValue* options=params.as_hash(1, "sql options")) { int valid_options=0; if(Value* vbind=options->get(sql_bind_name)) { valid_options++; @@ -1186,11 +1332,7 @@ static void _sql(Request& r, MethodParam const char* statement_cstr=statement_string.untaint_cstr(r.flang, r.connection()); Table_sql_event_handlers handlers; -#ifdef RESOURCES_DEBUG - struct timeval mt[2]; - //measure:before - gettimeofday(&mt[0],NULL); -#endif + r.connection()->query( statement_cstr, placeholders_count, placeholders, @@ -1198,17 +1340,6 @@ static void _sql(Request& r, MethodParam handlers, statement_string); -#ifdef RESOURCES_DEBUG - //measure:after connect - gettimeofday(&mt[1],NULL); - - double t[2]; - for(int i=0;i<2;i++) - t[i]=mt[i].tv_sec+mt[i].tv_usec/1000000.0; - - r.sql_request_time+=t[1]-t[0]; -#endif - if(bind) unmarshal_bind_updates(*bind, placeholders_count, placeholders); @@ -1268,9 +1399,7 @@ static void _select(Request& r, MethodPa reverse=r.process_to_value(*vreverse).as_bool(); } if(valid_options!=options->count()) - throw Exception(PARSER_RUNTIME, - 0, - "called with invalid option"); + throw Exception(PARSER_RUNTIME, 0, CALLED_WITH_INVALID_OPTION); } Table& result_table=*new Table(source_table.columns()); @@ -1328,6 +1457,11 @@ MTable::MTable(): Methoded("table") { // add_native_method("save_old", Method::CT_DYNAMIC, _save_old, 1, 3); + // ^table.csv-string[] + // ^table.csv-string[nameless] + // ^table.csv-string[nameless;$.encloser["] $.separator[,]] + add_native_method("csv-string", Method::CT_DYNAMIC, _csv_string, 0, 2); + // ^table.count[] // ^table.count[rows] // ^table.count[columns] @@ -1360,9 +1494,19 @@ MTable::MTable(): Methoded("table") { // ^table.flip[] add_native_method("flip", Method::CT_DYNAMIC, _flip, 0, 0); - // ^table.append{r{tab}e{tab}c{tab}o{tab}r{tab}d} + // ^table.foreach[row-num;value]{code} + // ^table.foreach[row-num;value]{code}[delim] + add_native_method("foreach", Method::CT_DYNAMIC, _foreach, 3, 4); + + // ^table.append{row{tab}data} add_native_method("append", Method::CT_DYNAMIC, _append, 1, 1); + // ^table.insert{row{tab}data} before current row + add_native_method("insert", Method::CT_DYNAMIC, _insert, 1, 1); + + // ^table.delete[] current row + add_native_method("delete", Method::CT_DYNAMIC, _delete, 0, 0); + // ^table.join[table][$.limit(10) $.offset(1) $.offset[cur] ] add_native_method("join", Method::CT_DYNAMIC, _join, 1, 2);