source: trunk/FACT++/src/rootifysql.cc@ 19126

Last change on this file since 19126 was 19126, checked in by tbretz, 6 years ago
Implemented the possibility to print basic connection informations.
File size: 30.7 KB
Line 
1#include "Database.h"
2
3#include <regex>
4
5#include <boost/algorithm/string/join.hpp>
6#include <boost/tokenizer.hpp>
7#include <boost/algorithm/string.hpp>
8
9#include "tools.h"
10#include "Time.h"
11#include "Configuration.h"
12
13#include <TROOT.h>
14#include <TSystem.h>
15#include <TFile.h>
16#include <TTree.h>
17
18using namespace std;
19
20// ------------------------------------------------------------------------
21
22void SetupConfiguration(Configuration &conf)
23{
24 po::options_description control("Rootify SQL");
25 control.add_options()
26 ("uri,u", var<string>()->required(), "Database link as in\n\tuser:password@server[:port]/database[/comp].")
27 ("query,q", var<string>(""), "MySQL query (overwrites --file)")
28 ("file", var<string>("rootify.sql"), "An ASCII file with the MySQL query (overwrites --query)")
29 ("ignore-null,i", po_switch(), "Do not skip rows containing any NULL field")
30 ("out,o", var<string>("rootify.root"), "Output root file name")
31 ("force,f", po_switch(), "Force overwriting an existing root file ('RECREATE')")
32 ("update", po_switch(), "Update an existing root file with the new tree ('UPDATE')")
33 ("compression,c", var<uint16_t>(1), "zlib compression level for the root file")
34 ("tree,t", var<string>("Result"), "Name of the root tree")
35 ("ignore", vars<string>(), "Ignore the given columns")
36 ("display,d", po_switch(), "Displays contents on the screen (most usefull in combination with mysql statements as SHOW or EXPLAIN)")
37 ("write", var<string>(""), "Write output to an ascii file")
38 ("null,n", po_switch(), "Redirect the output file to /dev/null (mainly for debugging purposes, e.g. performance studies)")
39 ("no-fill", po_switch(), "Do not fill events into the root file (mainly for debugging purposes, e.g. performance studies)")
40 ("delimiter", var<string>(""), "The delimiter used if contents are displayed with --display (default=\\t)")
41 ("explain", po_switch(), "Requests an EXPLAIN from the server (shows the server optimized query)\nsee also https://dev.mysql.com/doc/refman/explain-output.html")
42 ("profiling", po_switch(), "Turn on profiling and print profile")
43 ("var.*", var<string>(), "Predefined SQL user variables (@VAR)")
44 ("env.*", vars<string>(), "Predefined environment for substitutions in the query ($ENV)")
45 ("list.*", var<string>(), "Predefined environment for substitutions in the query ($ENV). The list is read from the given file (one list entry per line)")
46 ("print-connection", po_switch(), "Print database connection information")
47 ("verbose,v", var<uint16_t>(1), "Verbosity (0: quiet, 1: default, 2: more, 3, ...)")
48 ;
49
50 po::positional_options_description p;
51 p.add("file", 1); // The 1st positional options (n=1)
52 p.add("out", 1); // The 2nd positional options (n=1)
53
54 conf.AddOptions(control);
55 conf.SetArgumentPositions(p);
56}
57
58void PrintUsage()
59{
60 cout <<
61 "rootifysql - Converts the result of a mysql query into a root file\n"
62 "\n"
63 "For convenience, this documentation uses the extended version of the options, "
64 "refer to the output below to get the abbreviations.\n"
65 "\n"
66 "Writes the result of a mysql query into a root file. For each column, a branch is "
67 "created of type double with the field name as name. This is usually the column name "
68 "if not specified otherwise by the AS mysql directive.\n"
69 "\n"
70 "Columns with CHAR or VARCHAR as field type are ignored. DATETIME, DATE and TIME "
71 "columns are converted to unix time (time_t). Rows containing any file which is "
72 "NULL are skipped if not suppressed by the --ignore-null option. Ideally, the query "
73 "is compiled in a way that no NULL field is returned. With the --display option the "
74 "result of the request is printed on the screen (NULL skipping still in action). "
75 "This can be useful to create an ascii file or to show results as 'SHOW DATABASES' "
76 "or 'EXPLAIN table'. To redirect the contents into an ascii file, the option -v0 "
77 "is useful. To suppredd writing to an output file --null can be used.\n"
78 "\n"
79 "The default is to read the query from a file called rootify.sql. Except if a different "
80 "filename is specified by the --file option or a query is given with --query.\n"
81 "\n"
82 "As a trick, the rootify.sql file can be made excutable (chmod u+x rootify.sql). "
83 "If the first line contains '#!rootifysql', the script can be executed directly.\n"
84 "\n"
85 "Columns whose name start with @ are skipped. If you want them in your output file "
86 "give them a name using AS, e.g. 'SELECT @A:=5 AS A'.\n"
87 "\n"
88 "You can use variables in your sql query like @MyVar and define them on the "
89 "command line. In this example with --var.MyVar=5\n"
90 "\n"
91 "You can use environment definitions for substitutions in your SQL query. "
92 "For example --env.TEST=5 would replace $TEST or ${TEST} in your query by 5."
93 "If you specifiy one environmentvariable more than once, a list is created. "
94 "For example --env.TEST=1 --env.TEST=2 --env.TEST=3 would substitute "
95 "$TEST or ${TEST} by '1, 2, 3'. This is useful for the SQL `IN` keyword. "
96 "You can also read the values for an enviroment substitution from a file "
97 "(one element per line), e.g. --env.TEST=file.txt. Lines starting with a # "
98 "are skipped.\n"
99 "\n"
100 "Comments in the query-file can be placed according to the SQL standard inline "
101 "/*comment*/ or introduced with # (shell script style) or -- (SQL style).\n"
102 "\n"
103 "In case of succes, 0 is returned, a value>0 otherwise.\n"
104 "\n"
105 "Usage: rootifysql [rootify.sql [rootify.root]] [-u URI] [-q query|-f file] [-i] [-o out] [-f] [-cN] [-t tree] [-vN]\n"
106 "\n"
107 ;
108 cout << endl;
109}
110
111struct ExplainParser
112{
113 string sql;
114
115 vector<string> vec;
116
117 string substitute(string _str, const regex &expr)
118 {
119 smatch match;
120 while (regex_search(_str, match, expr, regex_constants::format_first_only))
121 {
122 const auto &len = match.length(0);
123 const auto &pos = match.position(0);
124 const auto &str = match.str(0);
125
126 const auto it = find(vec.cbegin(), vec.cend(), str);
127 const size_t id = it==vec.cend() ? vec.size() : it-vec.cbegin();
128
129 _str.replace(pos, len, "{"+to_string(id)+"}");
130
131 if (it==vec.cend())
132 vec.push_back(str);//.substr(1, str.size()-2));
133 }
134
135 return _str;
136 }
137
138 string substitute(const string &str, const string &expr)
139 {
140 return substitute(str, regex(expr));
141 }
142
143 vector<string> queries;
144
145 string resub(string str)
146 {
147 // search for "KEYWORD expression"
148 regex reg("\\{[0-9]+\\}");
149
150 //smatch match;
151 smatch match;
152 while (regex_search(str, match, reg, regex_constants::format_first_only))
153 {
154 const auto &len = match.length(0);
155 const auto &pos = match.position(0);
156 const auto &arg = match.str(0); // Argument
157
158 const auto idx = atoi(arg.c_str()+1);
159
160 str.replace(pos, len, resub(vec[idx]));
161 }
162
163 return str;
164 }
165
166 void expression(string expr, size_t indent=0)
167 {
168 if (expr[0]=='{')
169 {
170 const auto idx = atoi(expr.c_str()+1);
171
172 // This is a subquery
173 if (vec[idx].substr(0,3)=="(/*")
174 {
175 cout << setw(indent) << ' ' << "(\n";
176 find_tokens(vec[idx], indent+4);
177 cout << setw(indent) << ' ' << ") ";
178 }
179 else
180 // This is just something to substitute back
181 if (vec[idx].substr(0,2)=="({")
182 {
183 cout << setw(indent) << ' ' << "(" << resub(vec[idx]) << ") ";
184 }
185 else
186 {
187 if (indent>0)
188 cout << setw(indent) << ' ';
189 cout << resub(vec[idx]);
190 }
191 }
192 else
193 {
194 if (indent>0)
195 cout << setw(indent) << ' ';
196 cout << resub(expr);
197 }
198 }
199
200 void find_tokens(string str, size_t indent=0)
201 {
202 // ( COMMENT )?( TOKEN )?(( {NNN} | NNN )( AS|ON ( {NNN}) ))?(,)?)
203 //regex reg("(\\/\\*\\ select\\#[0-9]+\\ \\*\\/\\ *)?([a-zA-Z ]+)?((\\{[0-9]+\\}|[0-9]+)(\\ ?([Aa][Ss]|[Oo][Nn])\\ ?(\\{[0-9]+\\}))?(,)?)");
204
205 const string _com = "\\/\\*\\ select\\#[0-9]+\\ \\*\\/\\ *";
206
207 const string _tok = "[a-zA-Z_ ]+";
208
209 const string _nnn = "\\{[0-9]+\\}|[0-9]+";
210
211 const string _as = "\\ ?([Aa][Ss])\\ ?";
212
213 // ( _nnn ) ( _as ( _nnn ))?(,)? // can also match noting in between two {NNN}
214 const string _exp = "("+_nnn+")" + "("+_as+"("+_nnn+"))?(,)?";
215
216 // Matche: ( _com )? ( ( _tok )? ( _exp ) | ( _tok ) )
217 regex reg("("+_com+")?" + "(" + "("+_tok+")?"+"("+_exp+")" + "|" + "("+_tok+")" + ")");
218
219 smatch match;
220 while (regex_search(str, match, reg, regex_constants::format_first_only))
221 {
222
223 const auto &com = match.str(1); // comment
224 const auto &tok1 = Tools::Trim(match.str(3)); // token with expression
225 const auto &arg1 = match.str(5); // argument 1
226 const auto &as = match.str(7); // as
227 const auto &arg2 = match.str(8); // argument 2
228 const auto &comma = match.str(9); // comma
229 const auto &tok2 = Tools::Trim(match.str(10)); // token without expression
230
231 if (!com.empty())
232 cout << setw(indent) << ' ' << "\033[34m" << com << "\033[0m" << '\n';
233
234 if (!tok1.empty())
235 cout << setw(indent) << ' ' << "\033[32m" << tok1 << "\033[0m" << '\n';
236 if (!tok2.empty())
237 cout << setw(indent) << ' ' << "\033[32m" << tok2 << "\033[0m" << '\n';
238
239 if (!arg1.empty())
240 {
241 expression(arg1, indent+4);
242
243 if (!as.empty())
244 cout << " \033[33m" << as << "\033[0m ";
245
246 if (!arg2.empty())
247 expression(arg2);
248
249 if (!comma.empty())
250 cout << ',';
251
252 cout << '\n';
253 }
254
255 str = str.substr(match.position(0)+match.length(0));
256 }
257 }
258
259
260 ExplainParser(const string &_sql) : sql(_sql)
261 {
262 // substitute all strings
263 sql = substitute(sql, "'[^']*'");
264
265 // substitute all escaped sequences (`something`.`something-else`)
266 sql = substitute(sql, "`[^`]*`(\\.`[^`]*`)*");
267
268 // substitute all paranthesis
269 sql = substitute(sql, "[a-zA-Z0-9_]*\\([^\\(\\)]*\\)");
270
271 //cout << sql << "\n\n";
272 find_tokens(sql);
273 cout << endl;
274 }
275};
276
277// Remove queries...
278void format(string sql)
279{
280 ExplainParser p(sql);
281
282 /*
283
284 SELECT
285 [ALL | DISTINCT | DISTINCTROW ]
286 [HIGH_PRIORITY]
287 [STRAIGHT_JOIN]
288 [SQL_SMALL_RESULT] [SQL_BIG_RESULT] [SQL_BUFFER_RESULT]
289 [SQL_CACHE | SQL_NO_CACHE] [SQL_CALC_FOUND_ROWS]
290 select_expr [, select_expr ...]
291 [FROM table_references
292 [PARTITION partition_list]
293 [WHERE where_condition]
294 [GROUP BY {col_name | expr | position}, ... [WITH ROLLUP]]
295 [HAVING where_condition]
296 [WINDOW window_name AS (window_spec)
297 [, window_name AS (window_spec)] ...]
298 [ORDER BY {col_name | expr | position}
299 [ASC | DESC], ... [WITH ROLLUP]]
300 [LIMIT {[offset,] row_count | row_count OFFSET offset}]
301 [INTO OUTFILE 'file_name'
302 [CHARACTER SET charset_name]
303 export_options
304 | INTO DUMPFILE 'file_name'
305 | INTO var_name [, var_name]]
306 [FOR {UPDATE | SHARE} [OF tbl_name [, tbl_name] ...] [NOWAIT | SKIP LOCKED]
307 | LOCK IN SHARE MODE]]
308 */
309
310 /*
311table_references:
312 escaped_table_reference [, escaped_table_reference] ...
313
314escaped_table_reference:
315 table_reference
316 | { OJ table_reference }
317
318table_reference:
319 table_factor
320 | join_table
321
322table_factor:
323 tbl_name [PARTITION (partition_names)]
324 [[AS] alias] [index_hint_list]
325 | table_subquery [AS] alias [(col_list)]
326 | ( table_references )
327
328join_table:
329 table_reference [INNER | CROSS] JOIN table_factor [join_condition]
330 | table_reference STRAIGHT_JOIN table_factor
331 | table_reference STRAIGHT_JOIN table_factor ON conditional_expr
332 | table_reference {LEFT|RIGHT} [OUTER] JOIN table_reference join_condition
333 | table_reference NATURAL [INNER | {LEFT|RIGHT} [OUTER]] JOIN table_factor
334
335join_condition:
336 ON conditional_expr
337 | USING (column_list)
338
339index_hint_list:
340 index_hint [, index_hint] ...
341
342index_hint:
343 USE {INDEX|KEY}
344 [FOR {JOIN|ORDER BY|GROUP BY}] ([index_list])
345 | IGNORE {INDEX|KEY}
346 [FOR {JOIN|ORDER BY|GROUP BY}] (index_list)
347 | FORCE {INDEX|KEY}
348 [FOR {JOIN|ORDER BY|GROUP BY}] (index_list)
349
350index_list:
351 index_name [, index_name] ...
352 */
353
354}
355
356int main(int argc, const char* argv[])
357{
358 Time start;
359
360 gROOT->SetBatch();
361
362 Configuration conf(argv[0]);
363 conf.SetPrintUsage(PrintUsage);
364 SetupConfiguration(conf);
365
366 if (!conf.DoParse(argc, argv))
367 return 127;
368
369 // ----------------------------- Evaluate options --------------------------
370 const string uri = conf.Get<string>("uri");
371 const string out = conf.Get<string>("out");
372 const string file = conf.Get<string>("file");
373 const string tree = conf.Get<string>("tree");
374 const bool force = conf.Get<bool>("force");
375 const bool ignorenull = conf.Get<bool>("ignore-null");
376 const bool update = conf.Get<bool>("update");
377 const bool display = conf.Get<bool>("display");
378 const string write = conf.Get<string>("write");
379 const bool noout = conf.Get<bool>("null");
380 const bool nofill = conf.Get<bool>("no-fill");
381 const bool explain = conf.Get<bool>("explain");
382 const bool profiling = conf.Get<bool>("profiling");
383 const uint16_t verbose = conf.Get<uint16_t>("verbose");
384 const uint16_t compression = conf.Get<uint16_t>("compression");
385 const string delimiter = conf.Get<string>("delimiter");
386 const vector<string> _ignore = conf.Vec<string>("ignore");
387 const bool print_connection = conf.Get<bool>("print-connection");
388 //const vector<Map> mymap = conf.Vec<Map>("map");
389
390 // -------------------------------------------------------------------------
391
392 const auto vars = conf.GetWildcardOptions("var.*");
393
394 vector<string> variables;
395 for (const auto &var : vars)
396 variables.emplace_back('@'+var.substr(4)+":="+Tools::Trim(conf.Get<string>(var)));
397
398 // -------------------------------------------------------------------------
399
400 if (verbose>0)
401 cout << "\n------------------------ Rootify SQL -------------------------" << endl;
402
403 string query = conf.Get<string>("query");
404 if (query.empty())
405 {
406 if (verbose>0)
407 cout << "Reading query from file '" << file << "'." << endl;
408
409 ifstream fin(file);
410 if (!fin)
411 {
412 cerr << "Could not open query in '" << file << "': " << strerror(errno) << endl;
413 return 1;
414 }
415 getline(fin, query, (char)fin.eof());
416 }
417
418 if (query.empty())
419 {
420 cerr << "No query specified." << endl;
421 return 2;
422 }
423
424 // -------------------------------------------------------------------------
425
426 map<string, vector<string>> envs;
427
428 for (const auto &env : conf.GetWildcardOptions("env.*"))
429 envs[env.substr(4)] = conf.Vec<string>(env);
430
431 for (const auto &env : conf.GetWildcardOptions("list.*"))
432 {
433 const string fname = conf.Get<string>(env);
434 const string &ident = env.substr(5);
435
436 ifstream fin(fname);
437 if (!fin)
438 {
439 cerr << "Could not open environment in '" << fname << "' for ${" << ident << "}: " << strerror(errno) << endl;
440 return 3;
441 }
442
443 for (string line; getline(fin, line); )
444 if (Tools::Trim(line)[0]!='#')
445 envs[ident].push_back(line);
446
447 if (verbose>0)
448 cout << "Found " << envs[ident].size() << " list element(s) for ${" << ident << "}" << endl;
449 }
450
451 for (const auto &env : envs)
452 {
453 regex rexpr("\\$(\\{"+env.first+"\\}|"+env.first+"\\b)");
454 query = regex_replace(query, rexpr, boost::join(env.second, ", "));
455 }
456
457 // -------------------------- Check for file permssion ---------------------
458 // Strictly speaking, checking for write permission and existance is not necessary,
459 // but it is convenient that the user does not find out that it failed after
460 // waiting long for the query result
461 //
462 // I am using root here instead of boost to be
463 // consistent with the access pattern by TFile
464 TString path(noout?"/dev/null":out.c_str());
465 gSystem->ExpandPathName(path);
466
467 if (!noout)
468 {
469 FileStat_t stat;
470 const Int_t exist = !gSystem->GetPathInfo(path, stat);
471 const Bool_t _write = !gSystem->AccessPathName(path, kWritePermission) && R_ISREG(stat.fMode);
472
473 if ((update && !exist) || (update && exist && !_write) || (force && exist && !_write))
474 {
475 cerr << "File '" << path << "' is not writable." << endl;
476 return 3;
477 }
478
479 if (!update && !force && exist)
480 {
481 cerr << "File '" << path << "' already exists." << endl;
482 return 4;
483 }
484 }
485
486 Time start2;
487
488 // --------------------------- Connect to database -------------------------------------------------
489
490 if (query.back()!='\n')
491 query += '\n';
492
493 if (verbose>0)
494 cout << "Connecting to database..." << endl;
495
496
497 Database connection(uri); // Keep alive while fetching rows
498
499 if (print_connection)
500 {
501 try
502 {
503 const auto &res1 = connection.query("SHOW STATUS LIKE 'Compression'").store();
504 cout << "Compression of databse connection is " << string(res1[0][1]) << endl;
505
506 const auto &res2 = connection.query("SHOW STATUS LIKE 'Ssl_cipher'").store();
507 cout << "Connection to databases is " << (string(res2[0][1]).empty()?"UNENCRYPTED":"ENCRYPTED ("+string(res2[0][1])+")") << endl;
508 }
509 catch (const exception &e)
510 {
511 cerr << "\nSHOW STATUS LIKE COMPRESSION\n\n";
512 cerr << "SQL query failed:\n" << e.what() << endl;
513 return 6;
514 }
515 }
516
517 try
518 {
519 if (profiling)
520 connection.query("SET PROFILING=1").execute();
521 }
522 catch (const exception &e)
523 {
524 cerr << "\nSET profiling=1\n\n";
525 cerr << "SQL query failed:\n" << e.what() << endl;
526 return 6;
527 }
528
529 // -------------------------- Set user defined variables -------------------
530 if (variables.size()>0)
531 {
532 if (verbose>0)
533 cout << "Setting user defined variables..." << endl;
534
535 const string varset =
536 "SET\n "+boost::algorithm::join(variables, ",\n ");
537
538 try
539 {
540 connection.query(varset).execute();
541 }
542 catch (const exception &e)
543 {
544 cerr << '\n' << varset << "\n\n";
545 cerr << "SQL query failed:\n" << e.what() << endl;
546 return 7;
547 }
548
549 if (verbose>2)
550 cout << '\n' << varset << '\n' << endl;
551 }
552
553 // ------------------------- Explain query if requested --------------------
554
555 if (explain)
556 {
557 try
558 {
559 const auto res0 =
560 connection.query("EXPLAIN FORMAT=JSON "+query).store();
561
562 cout << res0[0][0] << endl;
563 cout << endl;
564
565 const mysqlpp::StoreQueryResult res1 =
566 connection.query("EXPLAIN "+query).store();
567
568 for (size_t i=0; i<res1.num_rows(); i++)
569 {
570 const mysqlpp::Row &row = res1[i];
571
572 cout << "\nid : " << row["id"];
573 cout << "\nselect type : " << row["select_type"];
574
575 if (!row["table"].is_null())
576 cout << "\ntable : " << row["table"];
577
578 if (!row["partitions"].is_null())
579 cout << "\npartitions : " << row["partitions"];
580
581 if (!row["key"].is_null())
582 cout << "\nselected key : " << row["key"] << " [len=" << row["key_len"] << "] out of (" << row["possible_keys"] << ")";
583
584 if (!row["type"].is_null())
585 cout << "\njoin type : " << row["type"];
586
587 //if (!row["possible_keys"].is_null())
588 // cout << "\npossible_keys: " << row["possible_keys"];
589
590 //if (!row["key_len"].is_null())
591 // cout << "\nkey_len : " << row["key_len"];
592
593 if (!row["ref"].is_null())
594 cout << "\nref : (" << row["ref"] << ") compared to the index";
595
596 if (!row["rows"].is_null())
597 cout << "\nrows : " << row["rows"];
598
599 if (!row["filtered"].is_null())
600 cout << "\nfiltered : " << row["filtered"];
601
602 if (!row["extra"].is_null())
603 cout << "\nExtra : " << row["extra"];
604
605 cout << endl;
606 }
607
608 cout << endl;
609
610 const mysqlpp::StoreQueryResult res2 =
611 connection.query("SHOW WARNINGS").store();
612
613 for (size_t i=0; i<res2.num_rows(); i++)
614 {
615 const mysqlpp::Row &row = res2[i];
616
617 // 1003 //
618 cout << row["Level"] << '[' << row["Code"] << "]:\n";
619 if (uint32_t(row["Code"])==1003)
620 format(row["Message"].c_str());
621 else
622 cout << row["Message"] << '\n' << endl;
623
624 }
625
626 }
627 catch (const exception &e)
628 {
629 cerr << '\n' << query << "\n\n";
630 cerr << "SQL query failed:\n" << e.what() << endl;
631 return 8;
632 }
633
634 return 0;
635 }
636
637 // -------------------------- Request data from database -------------------
638 if (verbose>0)
639 cout << "Requesting data..." << endl;
640
641 if (verbose>2)
642 cout << '\n' << query << endl;
643
644 const mysqlpp::UseQueryResult res =
645 connection.query(query).use();
646
647 // -------------------------------------------------------------------------
648
649 if (verbose>0)
650 cout << "Opening file '" << path << "' [compression=" << compression << "]..." << endl;
651
652 // ----------------------------- Open output file --------------------------
653 TFile tfile(path, update?"UPDATE":(force?"RECREATE":"CREATE"), "Rootify SQL", compression);
654 if (tfile.IsZombie())
655 return 9;
656
657 // -------------------------------------------------------------------------
658
659 // get the first row to get the field description
660 mysqlpp::Row row = res.fetch_row();
661 if (!row)
662 {
663 cerr << "Empty set returned... nothing to write." << endl;
664 return 10;
665 }
666
667 if (verbose>0)
668 cout << "Trying to setup " << row.size() << " branches..." << endl;
669
670 if (verbose>1)
671 cout << endl;
672
673 const mysqlpp::FieldNames &l = *row.field_list().list;
674
675 vector<double> buf(l.size());
676 vector<uint8_t> typ(l.size(),'n'); // n=number [double], d is used for DateTime
677
678 UInt_t cols = 0;
679
680
681 // -------------------- Configure branches of TTree ------------------------
682 TTree *ttree = new TTree(tree.c_str(), query.c_str());
683
684 size_t skipat = 0;
685 size_t skipreg = 0;
686 for (size_t i=0; i<l.size(); i++)
687 {
688 const string t = row[i].type().sql_name();
689
690 if (t.find("DATETIME")!=string::npos)
691 typ[i] = 'd';
692 else
693 if (t.find("DATE")!=string::npos)
694 typ[i] = 'D';
695 else
696 if (t.find("TIME")!=string::npos)
697 typ[i] = 'T';
698 else
699 if (t.find("VARCHAR")!=string::npos)
700 typ[i] = 'V';
701 else
702 if (t.find("CHAR")!=string::npos)
703 typ[i] = 'C';
704
705 bool found = false;
706 for (const auto &pattern: _ignore)
707 {
708 if (regex_match(l[i], regex(pattern)))
709 {
710 found = true;
711 typ[i] = '-';
712 skipreg++;
713 break;
714 }
715 }
716
717 if (l[i][0]=='@')
718 {
719 typ[i] = '@';
720 skipat++;
721 }
722
723 const bool use = l[i][0]!='@' && typ[i]!='V' && typ[i]!='C' && !found;
724
725 if (verbose>1)
726 cout << (use?" + ":" - ") << l[i].c_str() << " [" << t << "] {" << typ[i] << "}\n";
727
728 if (use)
729 {
730 // string name = l[i];
731 // for (const auto &m: mymap)
732 // name = boost::regex_replace(l[i], boost::regex(m.first), m.second);
733
734 ttree->Branch(l[i].c_str(), buf.data()+i);
735 cols++;
736 }
737 }
738 // -------------------------------------------------------------------------
739
740 if (verbose>1)
741 cout << endl;
742 if (verbose>0)
743 {
744 if (skipreg)
745 cout << skipreg << " branches skipped due to ignore list." << endl;
746 if (skipat)
747 cout << skipat << " branches skipped due to name starting with @." << endl;
748 cout << "Configured " << cols << " branches.\nFilling branches..." << endl;
749 }
750
751 ofstream fout(write);
752 if (!write.empty() && !fout)
753 cout << "WARNING: Writing to '" << write << "' failed: " << strerror(errno) << endl;
754
755 if (display)
756 {
757 cout << endl;
758 cout << "#";
759 for (size_t i=0; i<l.size(); i++)
760 cout << ' ' << l[i].c_str();
761 cout << endl;
762 }
763
764 if (!write.empty())
765 {
766 fout << "#";
767 for (size_t i=0; i<l.size(); i++)
768 fout << ' ' << l[i].c_str();
769 fout << endl;
770 }
771
772 // ---------------------- Fill TTree with DB data --------------------------
773 size_t count = 0;
774 size_t skip = 0;
775 do
776 {
777 count++;
778
779 ostringstream sout;
780
781 size_t idx=0;
782 for (auto col=row.begin(); col!=row.end(); col++, idx++)
783 {
784 if (display || !write.empty())
785 {
786 if (idx>0)
787 sout << (delimiter.empty()?"\t":delimiter);
788 sout << col->c_str();
789 }
790
791 if (!ignorenull && col->is_null())
792 {
793 skip++;
794 break;
795 }
796
797 switch (typ[idx])
798 {
799 case 'd':
800 buf[idx] = time_t((mysqlpp::DateTime)(*col));
801 break;
802
803 case 'D':
804 buf[idx] = time_t((mysqlpp::Date)(*col));
805 break;
806
807 case 'T':
808 buf[idx] = time_t((mysqlpp::Time)(*col));
809 break;
810
811 case 'V':
812 case 'C':
813 case '-':
814 case '@':
815 break;
816
817 default:
818 buf[idx] = atof(col->c_str());
819 }
820 }
821
822 if (idx==row.size())
823 {
824 if (!nofill)
825 ttree->Fill();
826
827 if (display)
828 cout << sout.str() << endl;
829 if (!write.empty())
830 fout << sout.str() << '\n';
831 }
832
833 row = res.fetch_row();
834
835
836 } while (row);
837
838 // -------------------------------------------------------------------------
839
840 if (display)
841 cout << '\n' << endl;
842
843 if (verbose>0)
844 {
845 cout << count << " rows fetched." << endl;
846 if (skip>0)
847 cout << skip << " rows skipped due to NULL field." << endl;
848
849 cout << ttree->GetEntries() << " rows filled into tree." << endl;
850 }
851
852 ttree->Write();
853 tfile.Close();
854
855 if (verbose>0)
856 {
857 const auto sec = Time().UnixTime()-start.UnixTime();
858
859 cout << Tools::Scientific(tfile.GetSize()) << "B written to disk.\n";
860 cout << "File closed.\n";
861 cout << "Execution time: " << sec << "s ";
862 cout << "(" << Tools::Fractional(sec/count) << "s/row)\n";
863 cout << "--------------------------------------------------------------" << endl;
864
865 try
866 {
867 const auto resw =
868 connection.query("SHOW WARNINGS").store();
869
870 if (resw.num_rows()>0)
871 cout << "\n" << resw.num_rows() << " Warning(s) issued:\n\n";
872
873 for (size_t i=0; i<resw.num_rows(); i++)
874 {
875 const mysqlpp::Row &roww = resw[i];
876
877 cout << roww["Level"] << '[' << roww["Code"] << "]: ";
878 cout << roww["Message"] << '\n';
879 }
880 cout << endl;
881
882 }
883 catch (const exception &e)
884 {
885 cerr << "\nSHOW WARNINGS\n\n";
886 cerr << "SQL query failed:\n" << e.what() << endl;
887 return 6;
888 }
889 }
890
891 if (profiling)
892 {
893 try
894 {
895 const auto N =
896 connection.query("SHOW PROFILES").store().num_rows();
897
898 const auto resp =
899 connection.query("SHOW PROFILE ALL FOR QUERY "+to_string(verbose?N-1:N)).store();
900
901 cout << '\n';
902 cout << left;
903 cout << setw(26) << "Status" << ' ';
904 cout << right;
905 cout << setw(11) << "Duration" << ' ';
906 cout << setw(11) << "CPU User" << ' ';
907 cout << setw(11) << "CPU System" << '\n';
908 cout << "--------------------------------------------------------------\n";
909 for (size_t i=0; i<resp.num_rows(); i++)
910 {
911 const mysqlpp::Row &rowp = resp[i];
912
913 cout << left;
914 cout << setw(26) << rowp["Status"] << ' ';
915 cout << right;
916 cout << setw(11) << rowp["Duration"] << ' ';
917 cout << setw(11) << rowp["CPU_user"] << ' ';
918 cout << setw(11) << rowp["CPU_system"] << '\n';
919 }
920 cout << "--------------------------------------------------------------\n";
921 cout << endl;
922 }
923 catch (const exception &e)
924 {
925 cerr << "\nSHOW PROFILE ALL\n\n";
926 cerr << "SQL query failed:\n" << e.what() << '\n' <<endl;
927 return 11;
928 }
929 }
930
931 return 0;
932}
Note: See TracBrowser for help on using the repository browser.