Merge lp:~posulliv/drizzle/inject into lp:drizzle/7.0

Proposed by Padraig O'Sullivan
Status: Work in progress
Proposed branch: lp:~posulliv/drizzle/inject
Merge into: lp:drizzle/7.0
Diff against target: 6024 lines (+5945/-0)
15 files modified
plugin/stad/client.cc (+4635/-0)
plugin/stad/common/injection_exception.hpp (+60/-0)
plugin/stad/common/keywords.cpp (+67/-0)
plugin/stad/common/keywords.hpp (+42/-0)
plugin/stad/common/randomizer.cpp (+49/-0)
plugin/stad/common/sql_tokenizer.cpp (+148/-0)
plugin/stad/common/sql_tokenizer.hpp (+63/-0)
plugin/stad/injection_prevention.cpp (+187/-0)
plugin/stad/injection_prevention.hpp (+52/-0)
plugin/stad/plugin.am (+32/-0)
plugin/stad/plugin.ini (+10/-0)
plugin/stad/tests/r/attacks.result (+152/-0)
plugin/stad/tests/r/simple.result (+193/-0)
plugin/stad/tests/t/attacks.test (+150/-0)
plugin/stad/tests/t/simple.test (+105/-0)
To merge this branch: bzr merge lp:~posulliv/drizzle/inject
Reviewer Review Type Date Requested Status
Padraig O'Sullivan (community) Disapprove
Review via email: mp+41791@code.launchpad.net

Description of the change

This branch contains a query rewriting plugin that can prevent SQL injection attacks. The concept of SQL randomization is used in this plugin (for more info see the research paper - http://www1.cs.columbia.edu/~locasto/projects/candidacy/papers/boyd2004sqlrand.pdf)

Examples of the types of SQL injection attacks it can prevent are in the test suite for the plugin. This plugin is not enabled by default. Examples of client applications that use this plugin are being developed and will be documented in the next few days.

I wasn't sure what the model for plugin distribution in drizzle is. I wouldn't ask to merge it into trunk if I knew of another way to distribute a plugin?

To post a comment you must log in.
Revision history for this message
Monty Taylor (mordred) wrote :

Setting this to work in progress since you're not actively wanting it merged at the moment.

Revision history for this message
Padraig O'Sullivan (posulliv) wrote :

Yep, I think I'll switch to just making this an out-of-tree plugin for now. It will help push me to understand what is needed to distribute a plugin not included in the source anyway which is good :)

review: Disapprove

Unmerged revisions

1954. By Padraig O'Sullivan

Adding SQL injection prevention plugin.

Preview Diff

[H/L] Next/Prev Comment, [J/K] Next/Prev File, [N/P] Next/Prev Hunk
1=== added directory 'plugin/stad'
2=== added file 'plugin/stad/client.cc'
3--- plugin/stad/client.cc 1970-01-01 00:00:00 +0000
4+++ plugin/stad/client.cc 2010-11-24 20:50:51 +0000
5@@ -0,0 +1,4635 @@
6+/* - mode: c; c-basic-offset: 2; indent-tabs-mode: nil; -*-
7+ * vim:expandtab:shiftwidth=2:tabstop=2:smarttab:
8+ *
9+ * Copyright (C) 2010 Vijay Samuel
10+ * Copyright (C) 2008 MySQL
11+ *
12+ * This program is free software; you can redistribute it and/or modify
13+ * it under the terms of the GNU General Public License as published by
14+ * the Free Software Foundation; either version 2 of the License, or
15+ * (at your option) any later version.
16+ *
17+ * This program is distributed in the hope that it will be useful,
18+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
19+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20+ * GNU General Public License for more details.
21+ *
22+ * You should have received a copy of the GNU General Public License
23+ * along with this program; if not, write to the Free Software
24+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
25+ */
26+
27+/* drizzle command tool
28+ * Commands compatible with mSQL by David J. Hughes
29+ *
30+ * Written by:
31+ * Michael 'Monty' Widenius
32+ * Andi Gutmans <andi@zend.com>
33+ * Zeev Suraski <zeev@zend.com>
34+ * Jani Tolonen <jani@mysql.com>
35+ * Matt Wagner <matt@mysql.com>
36+ * Jeremy Cole <jcole@mysql.com>
37+ * Tonu Samuel <tonu@mysql.com>
38+ * Harrison Fisk <harrison@mysql.com>
39+ *
40+ **/
41+
42+#include "config.h"
43+#include <libdrizzle/drizzle_client.h>
44+
45+#include <client/get_password.h>
46+
47+#if TIME_WITH_SYS_TIME
48+# include <sys/time.h>
49+# include <time.h>
50+#else
51+# if HAVE_SYS_TIME_H
52+# include <sys/time.h>
53+# else
54+# include <time.h>
55+# endif
56+#endif
57+
58+#include <cerrno>
59+#include <string>
60+#include <drizzled/gettext.h>
61+#include <iostream>
62+#include <fstream>
63+#include <map>
64+#include <algorithm>
65+#include <limits.h>
66+#include <cassert>
67+#include <stdarg.h>
68+#include <math.h>
69+#include "client/linebuffer.h"
70+#include <signal.h>
71+#include <sys/ioctl.h>
72+#include <drizzled/configmake.h>
73+#include <drizzled/utf8/utf8.h>
74+#include <cstdlib>
75+
76+#if defined(HAVE_CURSES_H) && defined(HAVE_TERM_H)
77+#include <curses.h>
78+#ifdef __sun
79+#undef clear
80+#undef erase
81+#endif
82+#include <term.h>
83+#else
84+#if defined(HAVE_TERMIOS_H)
85+#include <termios.h>
86+#include <unistd.h>
87+#elif defined(HAVE_TERMBITS_H)
88+#include <termbits.h>
89+#elif defined(HAVE_ASM_TERMBITS_H) && (!defined __GLIBC__ || !(__GLIBC__ > 2 || __GLIBC__ == 2 && __GLIBC_MINOR__ > 0))
90+#include <asm/termbits.h> // Standard linux
91+#endif
92+#if defined(HAVE_TERMCAP_H)
93+#include <termcap.h>
94+#else
95+#ifdef HAVE_CURSES_H
96+#include <curses.h>
97+#endif
98+#undef SYSV // hack to avoid syntax error
99+#ifdef HAVE_TERM_H
100+#include <term.h>
101+#endif
102+#endif
103+#endif
104+
105+#ifdef HAVE_LIBREADLINE
106+# if defined(HAVE_READLINE_READLINE_H)
107+# include <readline/readline.h>
108+# elif defined(HAVE_READLINE_H)
109+# include <readline.h>
110+# else /* !defined(HAVE_READLINE_H) */
111+extern char *readline ();
112+# endif /* !defined(HAVE_READLINE_H) */
113+char *cmdline = NULL;
114+#else /* !defined(HAVE_READLINE_READLINE_H) */
115+ /* no readline */
116+# error Readline Required
117+#endif /* HAVE_LIBREADLINE */
118+
119+#ifdef HAVE_READLINE_HISTORY
120+# if defined(HAVE_READLINE_HISTORY_H)
121+# include <readline/history.h>
122+# elif defined(HAVE_HISTORY_H)
123+# include <history.h>
124+# else /* !defined(HAVE_HISTORY_H) */
125+extern void add_history ();
126+extern int write_history ();
127+extern int read_history ();
128+# endif /* defined(HAVE_READLINE_HISTORY_H) */
129+ /* no history */
130+#endif /* HAVE_READLINE_HISTORY */
131+
132+/**
133+ Make the old readline interface look like the new one.
134+*/
135+#ifndef HAVE_RL_COMPLETION
136+typedef char **rl_completion_func_t(const char *, int, int);
137+#define rl_completion_matches(str, func) \
138+ completion_matches((char *)str, (CPFunction *)func)
139+#endif
140+
141+#ifdef HAVE_RL_COMPENTRY
142+# ifdef HAVE_WORKING_RL_COMPENTRY
143+typedef rl_compentry_func_t drizzle_compentry_func_t;
144+# else
145+/* Snow Leopard ships an rl_compentry which cannot be assigned to
146+ * rl_completion_entry_function. We must undo the complete and total
147+ * ass-bagery.
148+ */
149+typedef Function drizzle_compentry_func_t;
150+# endif
151+#else
152+typedef Function drizzle_compentry_func_t;
153+#endif
154+
155+#if defined(HAVE_LOCALE_H)
156+#include <locale.h>
157+#endif
158+
159+
160+
161+#if !defined(HAVE_VIDATTR)
162+#undef vidattr
163+#define vidattr(A) {} // Can't get this to work
164+#endif
165+#include <boost/program_options.hpp>
166+#include <drizzled/program_options/config_file.h>
167+
168+#include "common/sql_tokenizer.hpp"
169+
170+using namespace std;
171+namespace po=boost::program_options;
172+namespace dpo=drizzled::program_options;
173+
174+/* Don't try to make a nice table if the data is too big */
175+const uint32_t MAX_COLUMN_LENGTH= 1024;
176+
177+/* Buffer to hold 'version' and 'version_comment' */
178+const int MAX_SERVER_VERSION_LENGTH= 128;
179+
180+
181+#define PROMPT_CHAR '\\'
182+
183+class Status
184+{
185+public:
186+
187+ Status(int in_exit_status,
188+ uint32_t in_query_start_line,
189+ char *in_file_name,
190+ LineBuffer *in_line_buff,
191+ bool in_batch,
192+ bool in_add_to_history)
193+ :
194+ exit_status(in_exit_status),
195+ query_start_line(in_query_start_line),
196+ file_name(in_file_name),
197+ line_buff(in_line_buff),
198+ batch(in_batch),
199+ add_to_history(in_add_to_history)
200+ {}
201+
202+ Status() :
203+ exit_status(0),
204+ query_start_line(0),
205+ file_name(NULL),
206+ line_buff(NULL),
207+ batch(false),
208+ add_to_history(false)
209+ {}
210+
211+ int getExitStatus() const
212+ {
213+ return exit_status;
214+ }
215+
216+ uint32_t getQueryStartLine() const
217+ {
218+ return query_start_line;
219+ }
220+
221+ const char *getFileName() const
222+ {
223+ return file_name;
224+ }
225+
226+ LineBuffer *getLineBuff() const
227+ {
228+ return line_buff;
229+ }
230+
231+ bool getBatch() const
232+ {
233+ return batch;
234+ }
235+
236+ bool getAddToHistory() const
237+ {
238+ return add_to_history;
239+ }
240+
241+ void setExitStatus(int in_exit_status)
242+ {
243+ exit_status= in_exit_status;
244+ }
245+
246+ void setQueryStartLine(uint32_t in_query_start_line)
247+ {
248+ query_start_line= in_query_start_line;
249+ }
250+
251+ void setFileName(char *in_file_name)
252+ {
253+ file_name= in_file_name;
254+ }
255+
256+ void setLineBuff(int max_size, FILE *file=NULL)
257+ {
258+ line_buff= new(std::nothrow) LineBuffer(max_size, file);
259+ }
260+
261+ void setLineBuff(LineBuffer *in_line_buff)
262+ {
263+ line_buff= in_line_buff;
264+ }
265+
266+ void setBatch(bool in_batch)
267+ {
268+ batch= in_batch;
269+ }
270+
271+ void setAddToHistory(bool in_add_to_history)
272+ {
273+ add_to_history= in_add_to_history;
274+ }
275+
276+private:
277+ int exit_status;
278+ uint32_t query_start_line;
279+ char *file_name;
280+ LineBuffer *line_buff;
281+ bool batch,add_to_history;
282+};
283+
284+static map<string, string>::iterator completion_iter;
285+static map<string, string>::iterator completion_end;
286+static map<string, string> completion_map;
287+static string completion_string;
288+
289+
290+enum enum_info_type { INFO_INFO,INFO_ERROR,INFO_RESULT};
291+typedef enum enum_info_type INFO_TYPE;
292+
293+static drizzle_st drizzle; /* The library handle */
294+static drizzle_con_st con; /* The connection */
295+static bool ignore_errors= false, quick= false,
296+ connected= false, opt_raw_data= false, unbuffered= false,
297+ output_tables= false, opt_rehash= true, skip_updates= false,
298+ safe_updates= false, one_database= false,
299+ opt_shutdown= false, opt_ping= false,
300+ vertical= false, line_numbers= true, column_names= true,
301+ opt_nopager= true, opt_outfile= false, named_cmds= false,
302+ opt_nobeep= false, opt_reconnect= true,
303+ opt_secure_auth= false,
304+ default_pager_set= false, opt_sigint_ignore= false,
305+ auto_vertical_output= false,
306+ show_warnings= false, executing_query= false, interrupted_query= false,
307+ use_drizzle_protocol= false, opt_local_infile;
308+static uint32_t show_progress_size= 0;
309+static bool column_types_flag;
310+static bool preserve_comments= false;
311+static uint32_t opt_max_input_line;
312+static uint32_t opt_drizzle_port= 0;
313+static int opt_silent, verbose= 0;
314+static drizzle_capabilities_t connect_flag= DRIZZLE_CAPABILITIES_NONE;
315+static char *histfile;
316+static char *histfile_tmp;
317+static string *glob_buffer;
318+static string *processed_prompt= NULL;
319+static char *default_prompt= NULL;
320+static char *full_username= NULL,*part_username= NULL;
321+static Status status;
322+static uint32_t select_limit;
323+static uint32_t max_join_size;
324+static uint32_t opt_connect_timeout= 0;
325+std::string current_db,
326+ delimiter_str,
327+ current_host,
328+ current_prompt,
329+ current_user,
330+ opt_verbose,
331+ current_password,
332+ opt_password,
333+ opt_protocol,
334+ randomization_key;
335+// TODO: Need to i18n these
336+static const char *day_names[]= {"Sun","Mon","Tue","Wed","Thu","Fri","Sat"};
337+static const char *month_names[]= {"Jan","Feb","Mar","Apr","May","Jun","Jul",
338+ "Aug","Sep","Oct","Nov","Dec"};
339+/* @TODO: Remove this */
340+#define FN_REFLEN 512
341+
342+static string default_pager("");
343+static string pager("");
344+static string outfile("");
345+static FILE *PAGER, *OUTFILE;
346+static uint32_t prompt_counter;
347+static char *delimiter= NULL;
348+static uint32_t delimiter_length= 1;
349+unsigned short terminal_width= 80;
350+
351+int drizzleclient_real_query_for_lazy(const char *buf, size_t length,
352+ drizzle_result_st *result,
353+ uint32_t *error_code);
354+int drizzleclient_store_result_for_lazy(drizzle_result_st *result);
355+
356+
357+void tee_fprintf(FILE *file, const char *fmt, ...);
358+void tee_fputs(const char *s, FILE *file);
359+void tee_puts(const char *s, FILE *file);
360+void tee_putc(int c, FILE *file);
361+static void tee_print_sized_data(const char *, unsigned int, unsigned int, bool);
362+/* The names of functions that actually do the manipulation. */
363+static int process_options(void);
364+static int com_quit(string *str,const char*),
365+ com_go(string *str,const char*), com_ego(string *str,const char*),
366+ com_print(string *str,const char*),
367+ com_help(string *str,const char*), com_clear(string *str,const char*),
368+ com_connect(string *str,const char*), com_status(string *str,const char*),
369+ com_use(string *str,const char*), com_source(string *str, const char*),
370+ com_rehash(string *str, const char*), com_tee(string *str, const char*),
371+ com_notee(string *str, const char*),
372+ com_prompt(string *str, const char*), com_delimiter(string *str, const char*),
373+ com_warnings(string *str, const char*), com_nowarnings(string *str, const char*),
374+ com_nopager(string *str, const char*), com_pager(string *str, const char*);
375+
376+static int read_and_execute(bool interactive);
377+static int sql_connect(const string &host, const string &database, const string &user, const string &password,
378+ uint32_t silent);
379+static const char *server_version_string(drizzle_con_st *con);
380+static int put_info(const char *str,INFO_TYPE info,uint32_t error,
381+ const char *sql_state);
382+static int put_error(drizzle_con_st *con, drizzle_result_st *res);
383+static void safe_put_field(const char *pos,uint32_t length);
384+static void init_pager(void);
385+static void end_pager(void);
386+static void init_tee(const char *);
387+static void end_tee(void);
388+static const char* construct_prompt(void);
389+static char *get_arg(char *line, bool get_next_arg);
390+static void init_username(void);
391+static void add_int_to_prompt(int toadd);
392+static int get_result_width(drizzle_result_st *res);
393+static int get_field_disp_length(drizzle_column_st * field);
394+static const char * strcont(register const char *str, register const char *set);
395+
396+/* A class which contains information on the commands this program
397+ can understand. */
398+class Commands
399+{
400+private:
401+ const char *name; /* User printable name of the function. */
402+ char cmd_char; /* msql command character */
403+public:
404+Commands(const char *in_name,
405+ char in_cmd_char,
406+ int (*in_func)(string *str,const char *name),
407+ bool in_takes_params,
408+ const char *in_doc)
409+ :
410+ name(in_name),
411+ cmd_char(in_cmd_char),
412+ func(in_func),
413+ takes_params(in_takes_params),
414+ doc(in_doc)
415+ {}
416+
417+ Commands()
418+ :
419+ name(),
420+ cmd_char(),
421+ func(NULL),
422+ takes_params(false),
423+ doc()
424+ {}
425+
426+ int (*func)(string *str,const char *);/* Function to call to do the job. */
427+
428+ const char *getName() const
429+ {
430+ return name;
431+ }
432+
433+ char getCmdChar() const
434+ {
435+ return cmd_char;
436+ }
437+
438+ bool getTakesParams() const
439+ {
440+ return takes_params;
441+ }
442+
443+ const char *getDoc() const
444+ {
445+ return doc;
446+ }
447+
448+ void setName(const char *in_name)
449+ {
450+ name= in_name;
451+ }
452+
453+ void setCmdChar(char in_cmd_char)
454+ {
455+ cmd_char= in_cmd_char;
456+ }
457+
458+ void setTakesParams(bool in_takes_params)
459+ {
460+ takes_params= in_takes_params;
461+ }
462+
463+ void setDoc(const char *in_doc)
464+ {
465+ doc= in_doc;
466+ }
467+
468+private:
469+ bool takes_params; /* Max parameters for command */
470+ const char *doc; /* Documentation for this function. */
471+};
472+
473+
474+static Commands commands[] = {
475+ Commands( "?", '?', com_help, 0, N_("Synonym for `help'.") ),
476+ Commands( "clear", 'c', com_clear, 0, N_("Clear command.")),
477+ Commands( "connect",'r', com_connect,1,
478+ N_("Reconnect to the server. Optional arguments are db and host.")),
479+ Commands( "delimiter", 'd', com_delimiter, 1,
480+ N_("Set statement delimiter. NOTE: Takes the rest of the line as new delimiter.") ),
481+ Commands( "ego", 'G', com_ego, 0,
482+ N_("Send command to drizzle server, display result vertically.")),
483+ Commands( "exit", 'q', com_quit, 0, N_("Exit drizzle. Same as quit.")),
484+ Commands( "go", 'g', com_go, 0, N_("Send command to drizzle server.") ),
485+ Commands( "help", 'h', com_help, 0, N_("Display this help.") ),
486+ Commands( "nopager",'n', com_nopager,0, N_("Disable pager, print to stdout.") ),
487+ Commands( "notee", 't', com_notee, 0, N_("Don't write into outfile.") ),
488+ Commands( "pager", 'P', com_pager, 1,
489+ N_("Set PAGER [to_pager]. Print the query results via PAGER.") ),
490+ Commands( "print", 'p', com_print, 0, N_("Print current command.") ),
491+ Commands( "prompt", 'R', com_prompt, 1, N_("Change your drizzle prompt.")),
492+ Commands( "quit", 'q', com_quit, 0, N_("Quit drizzle.") ),
493+ Commands( "rehash", '#', com_rehash, 0, N_("Rebuild completion hash.") ),
494+ Commands( "source", '.', com_source, 1,
495+ N_("Execute an SQL script file. Takes a file name as an argument.")),
496+ Commands( "status", 's', com_status, 0, N_("Get status information from the server.")),
497+ Commands( "tee", 'T', com_tee, 1,
498+ N_("Set outfile [to_outfile]. Append everything into given outfile.") ),
499+ Commands( "use", 'u', com_use, 1,
500+ N_("Use another database. Takes database name as argument.") ),
501+ Commands( "warnings", 'W', com_warnings, 0,
502+ N_("Show warnings after every statement.") ),
503+ Commands( "nowarning", 'w', com_nowarnings, 0,
504+ N_("Don't show warnings after every statement.") ),
505+ /* Get bash-like expansion for some commands */
506+ Commands( "create table", 0, 0, 0, ""),
507+ Commands( "create database", 0, 0, 0, ""),
508+ Commands( "show databases", 0, 0, 0, ""),
509+ Commands( "show fields from", 0, 0, 0, ""),
510+ Commands( "show keys from", 0, 0, 0, ""),
511+ Commands( "show tables", 0, 0, 0, ""),
512+ Commands( "load data from", 0, 0, 0, ""),
513+ Commands( "alter table", 0, 0, 0, ""),
514+ Commands( "set option", 0, 0, 0, ""),
515+ Commands( "lock tables", 0, 0, 0, ""),
516+ Commands( "unlock tables", 0, 0, 0, ""),
517+ /* generated 2006-12-28. Refresh occasionally from lexer. */
518+ Commands( "ACTION", 0, 0, 0, ""),
519+ Commands( "ADD", 0, 0, 0, ""),
520+ Commands( "AFTER", 0, 0, 0, ""),
521+ Commands( "AGAINST", 0, 0, 0, ""),
522+ Commands( "AGGREGATE", 0, 0, 0, ""),
523+ Commands( "ALL", 0, 0, 0, ""),
524+ Commands( "ALGORITHM", 0, 0, 0, ""),
525+ Commands( "ALTER", 0, 0, 0, ""),
526+ Commands( "ANALYZE", 0, 0, 0, ""),
527+ Commands( "AND", 0, 0, 0, ""),
528+ Commands( "ANY", 0, 0, 0, ""),
529+ Commands( "AS", 0, 0, 0, ""),
530+ Commands( "ASC", 0, 0, 0, ""),
531+ Commands( "ASCII", 0, 0, 0, ""),
532+ Commands( "ASENSITIVE", 0, 0, 0, ""),
533+ Commands( "AUTO_INCREMENT", 0, 0, 0, ""),
534+ Commands( "AVG", 0, 0, 0, ""),
535+ Commands( "AVG_ROW_LENGTH", 0, 0, 0, ""),
536+ Commands( "BEFORE", 0, 0, 0, ""),
537+ Commands( "BEGIN", 0, 0, 0, ""),
538+ Commands( "BETWEEN", 0, 0, 0, ""),
539+ Commands( "BIGINT", 0, 0, 0, ""),
540+ Commands( "BINARY", 0, 0, 0, ""),
541+ Commands( "BIT", 0, 0, 0, ""),
542+ Commands( "BLOB", 0, 0, 0, ""),
543+ Commands( "BOOL", 0, 0, 0, ""),
544+ Commands( "BOOLEAN", 0, 0, 0, ""),
545+ Commands( "BOTH", 0, 0, 0, ""),
546+ Commands( "BTREE", 0, 0, 0, ""),
547+ Commands( "BY", 0, 0, 0, ""),
548+ Commands( "BYTE", 0, 0, 0, ""),
549+ Commands( "CACHE", 0, 0, 0, ""),
550+ Commands( "CALL", 0, 0, 0, ""),
551+ Commands( "CASCADE", 0, 0, 0, ""),
552+ Commands( "CASCADED", 0, 0, 0, ""),
553+ Commands( "CASE", 0, 0, 0, ""),
554+ Commands( "CHAIN", 0, 0, 0, ""),
555+ Commands( "CHANGE", 0, 0, 0, ""),
556+ Commands( "CHANGED", 0, 0, 0, ""),
557+ Commands( "CHAR", 0, 0, 0, ""),
558+ Commands( "CHARACTER", 0, 0, 0, ""),
559+ Commands( "CHECK", 0, 0, 0, ""),
560+ Commands( "CHECKSUM", 0, 0, 0, ""),
561+ Commands( "CLIENT", 0, 0, 0, ""),
562+ Commands( "CLOSE", 0, 0, 0, ""),
563+ Commands( "COLLATE", 0, 0, 0, ""),
564+ Commands( "COLLATION", 0, 0, 0, ""),
565+ Commands( "COLUMN", 0, 0, 0, ""),
566+ Commands( "COLUMNS", 0, 0, 0, ""),
567+ Commands( "COMMENT", 0, 0, 0, ""),
568+ Commands( "COMMIT", 0, 0, 0, ""),
569+ Commands( "COMMITTED", 0, 0, 0, ""),
570+ Commands( "COMPACT", 0, 0, 0, ""),
571+ Commands( "COMPRESSED", 0, 0, 0, ""),
572+ Commands( "CONCURRENT", 0, 0, 0, ""),
573+ Commands( "CONDITION", 0, 0, 0, ""),
574+ Commands( "CONNECTION", 0, 0, 0, ""),
575+ Commands( "CONSISTENT", 0, 0, 0, ""),
576+ Commands( "CONSTRAINT", 0, 0, 0, ""),
577+ Commands( "CONTAINS", 0, 0, 0, ""),
578+ Commands( "CONTINUE", 0, 0, 0, ""),
579+ Commands( "CONVERT", 0, 0, 0, ""),
580+ Commands( "CREATE", 0, 0, 0, ""),
581+ Commands( "CROSS", 0, 0, 0, ""),
582+ Commands( "CUBE", 0, 0, 0, ""),
583+ Commands( "CURRENT_DATE", 0, 0, 0, ""),
584+ Commands( "CURRENT_TIMESTAMP", 0, 0, 0, ""),
585+ Commands( "CURRENT_USER", 0, 0, 0, ""),
586+ Commands( "CURSOR", 0, 0, 0, ""),
587+ Commands( "DATA", 0, 0, 0, ""),
588+ Commands( "DATABASE", 0, 0, 0, ""),
589+ Commands( "DATABASES", 0, 0, 0, ""),
590+ Commands( "DATE", 0, 0, 0, ""),
591+ Commands( "DATETIME", 0, 0, 0, ""),
592+ Commands( "DAY", 0, 0, 0, ""),
593+ Commands( "DAY_HOUR", 0, 0, 0, ""),
594+ Commands( "DAY_MICROSECOND", 0, 0, 0, ""),
595+ Commands( "DAY_MINUTE", 0, 0, 0, ""),
596+ Commands( "DAY_SECOND", 0, 0, 0, ""),
597+ Commands( "DEALLOCATE", 0, 0, 0, ""),
598+ Commands( "DEC", 0, 0, 0, ""),
599+ Commands( "DECIMAL", 0, 0, 0, ""),
600+ Commands( "DECLARE", 0, 0, 0, ""),
601+ Commands( "DEFAULT", 0, 0, 0, ""),
602+ Commands( "DEFINER", 0, 0, 0, ""),
603+ Commands( "DELAYED", 0, 0, 0, ""),
604+ Commands( "DELETE", 0, 0, 0, ""),
605+ Commands( "DESC", 0, 0, 0, ""),
606+ Commands( "DESCRIBE", 0, 0, 0, ""),
607+ Commands( "DETERMINISTIC", 0, 0, 0, ""),
608+ Commands( "DISABLE", 0, 0, 0, ""),
609+ Commands( "DISCARD", 0, 0, 0, ""),
610+ Commands( "DISTINCT", 0, 0, 0, ""),
611+ Commands( "DISTINCTROW", 0, 0, 0, ""),
612+ Commands( "DIV", 0, 0, 0, ""),
613+ Commands( "DOUBLE", 0, 0, 0, ""),
614+ Commands( "DROP", 0, 0, 0, ""),
615+ Commands( "DUMPFILE", 0, 0, 0, ""),
616+ Commands( "DUPLICATE", 0, 0, 0, ""),
617+ Commands( "DYNAMIC", 0, 0, 0, ""),
618+ Commands( "EACH", 0, 0, 0, ""),
619+ Commands( "ELSE", 0, 0, 0, ""),
620+ Commands( "ELSEIF", 0, 0, 0, ""),
621+ Commands( "ENABLE", 0, 0, 0, ""),
622+ Commands( "ENCLOSED", 0, 0, 0, ""),
623+ Commands( "END", 0, 0, 0, ""),
624+ Commands( "ENGINE", 0, 0, 0, ""),
625+ Commands( "ENGINES", 0, 0, 0, ""),
626+ Commands( "ENUM", 0, 0, 0, ""),
627+ Commands( "ERRORS", 0, 0, 0, ""),
628+ Commands( "ESCAPE", 0, 0, 0, ""),
629+ Commands( "ESCAPED", 0, 0, 0, ""),
630+ Commands( "EXISTS", 0, 0, 0, ""),
631+ Commands( "EXIT", 0, 0, 0, ""),
632+ Commands( "EXPLAIN", 0, 0, 0, ""),
633+ Commands( "EXTENDED", 0, 0, 0, ""),
634+ Commands( "FALSE", 0, 0, 0, ""),
635+ Commands( "FAST", 0, 0, 0, ""),
636+ Commands( "FETCH", 0, 0, 0, ""),
637+ Commands( "FIELDS", 0, 0, 0, ""),
638+ Commands( "FILE", 0, 0, 0, ""),
639+ Commands( "FIRST", 0, 0, 0, ""),
640+ Commands( "FIXED", 0, 0, 0, ""),
641+ Commands( "FLOAT", 0, 0, 0, ""),
642+ Commands( "FLOAT4", 0, 0, 0, ""),
643+ Commands( "FLOAT8", 0, 0, 0, ""),
644+ Commands( "FLUSH", 0, 0, 0, ""),
645+ Commands( "FOR", 0, 0, 0, ""),
646+ Commands( "FORCE", 0, 0, 0, ""),
647+ Commands( "FOREIGN", 0, 0, 0, ""),
648+ Commands( "FOUND", 0, 0, 0, ""),
649+ Commands( "FRAC_SECOND", 0, 0, 0, ""),
650+ Commands( "FROM", 0, 0, 0, ""),
651+ Commands( "FULL", 0, 0, 0, ""),
652+ Commands( "FUNCTION", 0, 0, 0, ""),
653+ Commands( "GLOBAL", 0, 0, 0, ""),
654+ Commands( "GRANT", 0, 0, 0, ""),
655+ Commands( "GRANTS", 0, 0, 0, ""),
656+ Commands( "GROUP", 0, 0, 0, ""),
657+ Commands( "HANDLER", 0, 0, 0, ""),
658+ Commands( "HASH", 0, 0, 0, ""),
659+ Commands( "HAVING", 0, 0, 0, ""),
660+ Commands( "HELP", 0, 0, 0, ""),
661+ Commands( "HIGH_PRIORITY", 0, 0, 0, ""),
662+ Commands( "HOSTS", 0, 0, 0, ""),
663+ Commands( "HOUR", 0, 0, 0, ""),
664+ Commands( "HOUR_MICROSECOND", 0, 0, 0, ""),
665+ Commands( "HOUR_MINUTE", 0, 0, 0, ""),
666+ Commands( "HOUR_SECOND", 0, 0, 0, ""),
667+ Commands( "IDENTIFIED", 0, 0, 0, ""),
668+ Commands( "IF", 0, 0, 0, ""),
669+ Commands( "IGNORE", 0, 0, 0, ""),
670+ Commands( "IMPORT", 0, 0, 0, ""),
671+ Commands( "IN", 0, 0, 0, ""),
672+ Commands( "INDEX", 0, 0, 0, ""),
673+ Commands( "INDEXES", 0, 0, 0, ""),
674+ Commands( "INFILE", 0, 0, 0, ""),
675+ Commands( "INNER", 0, 0, 0, ""),
676+ Commands( "INNOBASE", 0, 0, 0, ""),
677+ Commands( "INNODB", 0, 0, 0, ""),
678+ Commands( "INOUT", 0, 0, 0, ""),
679+ Commands( "INSENSITIVE", 0, 0, 0, ""),
680+ Commands( "INSERT", 0, 0, 0, ""),
681+ Commands( "INSERT_METHOD", 0, 0, 0, ""),
682+ Commands( "INT", 0, 0, 0, ""),
683+ Commands( "INT1", 0, 0, 0, ""),
684+ Commands( "INT2", 0, 0, 0, ""),
685+ Commands( "INT3", 0, 0, 0, ""),
686+ Commands( "INT4", 0, 0, 0, ""),
687+ Commands( "INT8", 0, 0, 0, ""),
688+ Commands( "INTEGER", 0, 0, 0, ""),
689+ Commands( "INTERVAL", 0, 0, 0, ""),
690+ Commands( "INTO", 0, 0, 0, ""),
691+ Commands( "IO_THREAD", 0, 0, 0, ""),
692+ Commands( "IS", 0, 0, 0, ""),
693+ Commands( "ISOLATION", 0, 0, 0, ""),
694+ Commands( "ISSUER", 0, 0, 0, ""),
695+ Commands( "ITERATE", 0, 0, 0, ""),
696+ Commands( "INVOKER", 0, 0, 0, ""),
697+ Commands( "JOIN", 0, 0, 0, ""),
698+ Commands( "KEY", 0, 0, 0, ""),
699+ Commands( "KEYS", 0, 0, 0, ""),
700+ Commands( "KILL", 0, 0, 0, ""),
701+ Commands( "LANGUAGE", 0, 0, 0, ""),
702+ Commands( "LAST", 0, 0, 0, ""),
703+ Commands( "LEADING", 0, 0, 0, ""),
704+ Commands( "LEAVE", 0, 0, 0, ""),
705+ Commands( "LEAVES", 0, 0, 0, ""),
706+ Commands( "LEFT", 0, 0, 0, ""),
707+ Commands( "LEVEL", 0, 0, 0, ""),
708+ Commands( "LIKE", 0, 0, 0, ""),
709+ Commands( "LIMIT", 0, 0, 0, ""),
710+ Commands( "LINES", 0, 0, 0, ""),
711+ Commands( "LINESTRING", 0, 0, 0, ""),
712+ Commands( "LOAD", 0, 0, 0, ""),
713+ Commands( "LOCAL", 0, 0, 0, ""),
714+ Commands( "LOCALTIMESTAMP", 0, 0, 0, ""),
715+ Commands( "LOCK", 0, 0, 0, ""),
716+ Commands( "LOCKS", 0, 0, 0, ""),
717+ Commands( "LOGS", 0, 0, 0, ""),
718+ Commands( "LONG", 0, 0, 0, ""),
719+ Commands( "LOOP", 0, 0, 0, ""),
720+ Commands( "MATCH", 0, 0, 0, ""),
721+ Commands( "MAX_CONNECTIONS_PER_HOUR", 0, 0, 0, ""),
722+ Commands( "MAX_QUERIES_PER_HOUR", 0, 0, 0, ""),
723+ Commands( "MAX_ROWS", 0, 0, 0, ""),
724+ Commands( "MAX_UPDATES_PER_HOUR", 0, 0, 0, ""),
725+ Commands( "MAX_USER_CONNECTIONS", 0, 0, 0, ""),
726+ Commands( "MEDIUM", 0, 0, 0, ""),
727+ Commands( "MERGE", 0, 0, 0, ""),
728+ Commands( "MICROSECOND", 0, 0, 0, ""),
729+ Commands( "MIGRATE", 0, 0, 0, ""),
730+ Commands( "MINUTE", 0, 0, 0, ""),
731+ Commands( "MINUTE_MICROSECOND", 0, 0, 0, ""),
732+ Commands( "MINUTE_SECOND", 0, 0, 0, ""),
733+ Commands( "MIN_ROWS", 0, 0, 0, ""),
734+ Commands( "MOD", 0, 0, 0, ""),
735+ Commands( "MODE", 0, 0, 0, ""),
736+ Commands( "MODIFIES", 0, 0, 0, ""),
737+ Commands( "MODIFY", 0, 0, 0, ""),
738+ Commands( "MONTH", 0, 0, 0, ""),
739+ Commands( "MULTILINESTRING", 0, 0, 0, ""),
740+ Commands( "MULTIPOINT", 0, 0, 0, ""),
741+ Commands( "MULTIPOLYGON", 0, 0, 0, ""),
742+ Commands( "MUTEX", 0, 0, 0, ""),
743+ Commands( "NAME", 0, 0, 0, ""),
744+ Commands( "NAMES", 0, 0, 0, ""),
745+ Commands( "NATIONAL", 0, 0, 0, ""),
746+ Commands( "NATURAL", 0, 0, 0, ""),
747+ Commands( "NCHAR", 0, 0, 0, ""),
748+ Commands( "NEW", 0, 0, 0, ""),
749+ Commands( "NEXT", 0, 0, 0, ""),
750+ Commands( "NO", 0, 0, 0, ""),
751+ Commands( "NONE", 0, 0, 0, ""),
752+ Commands( "NOT", 0, 0, 0, ""),
753+ Commands( "NULL", 0, 0, 0, ""),
754+ Commands( "NUMERIC", 0, 0, 0, ""),
755+ Commands( "NVARCHAR", 0, 0, 0, ""),
756+ Commands( "OFFSET", 0, 0, 0, ""),
757+ Commands( "ON", 0, 0, 0, ""),
758+ Commands( "ONE", 0, 0, 0, ""),
759+ Commands( "ONE_SHOT", 0, 0, 0, ""),
760+ Commands( "OPEN", 0, 0, 0, ""),
761+ Commands( "OPTIMIZE", 0, 0, 0, ""),
762+ Commands( "OPTION", 0, 0, 0, ""),
763+ Commands( "OPTIONALLY", 0, 0, 0, ""),
764+ Commands( "OR", 0, 0, 0, ""),
765+ Commands( "ORDER", 0, 0, 0, ""),
766+ Commands( "OUT", 0, 0, 0, ""),
767+ Commands( "OUTER", 0, 0, 0, ""),
768+ Commands( "OUTFILE", 0, 0, 0, ""),
769+ Commands( "PACK_KEYS", 0, 0, 0, ""),
770+ Commands( "PARTIAL", 0, 0, 0, ""),
771+ Commands( "PASSWORD", 0, 0, 0, ""),
772+ Commands( "PHASE", 0, 0, 0, ""),
773+ Commands( "PRECISION", 0, 0, 0, ""),
774+ Commands( "PREPARE", 0, 0, 0, ""),
775+ Commands( "PREV", 0, 0, 0, ""),
776+ Commands( "PRIMARY", 0, 0, 0, ""),
777+ Commands( "PRIVILEGES", 0, 0, 0, ""),
778+ Commands( "PROCEDURE", 0, 0, 0, ""),
779+ Commands( "PROCESS", 0, 0, 0, ""),
780+ Commands( "PROCESSLIST", 0, 0, 0, ""),
781+ Commands( "PURGE", 0, 0, 0, ""),
782+ Commands( "QUARTER", 0, 0, 0, ""),
783+ Commands( "QUERY", 0, 0, 0, ""),
784+ Commands( "QUICK", 0, 0, 0, ""),
785+ Commands( "READ", 0, 0, 0, ""),
786+ Commands( "READS", 0, 0, 0, ""),
787+ Commands( "REAL", 0, 0, 0, ""),
788+ Commands( "RECOVER", 0, 0, 0, ""),
789+ Commands( "REDUNDANT", 0, 0, 0, ""),
790+ Commands( "REFERENCES", 0, 0, 0, ""),
791+ Commands( "REGEXP", 0, 0, 0, ""),
792+ Commands( "RELEASE", 0, 0, 0, ""),
793+ Commands( "RELOAD", 0, 0, 0, ""),
794+ Commands( "RENAME", 0, 0, 0, ""),
795+ Commands( "REPAIR", 0, 0, 0, ""),
796+ Commands( "REPEATABLE", 0, 0, 0, ""),
797+ Commands( "REPLACE", 0, 0, 0, ""),
798+ Commands( "REPEAT", 0, 0, 0, ""),
799+ Commands( "REQUIRE", 0, 0, 0, ""),
800+ Commands( "RESET", 0, 0, 0, ""),
801+ Commands( "RESTORE", 0, 0, 0, ""),
802+ Commands( "RESTRICT", 0, 0, 0, ""),
803+ Commands( "RESUME", 0, 0, 0, ""),
804+ Commands( "RETURN", 0, 0, 0, ""),
805+ Commands( "RETURNS", 0, 0, 0, ""),
806+ Commands( "REVOKE", 0, 0, 0, ""),
807+ Commands( "RIGHT", 0, 0, 0, ""),
808+ Commands( "RLIKE", 0, 0, 0, ""),
809+ Commands( "ROLLBACK", 0, 0, 0, ""),
810+ Commands( "ROLLUP", 0, 0, 0, ""),
811+ Commands( "ROUTINE", 0, 0, 0, ""),
812+ Commands( "ROW", 0, 0, 0, ""),
813+ Commands( "ROWS", 0, 0, 0, ""),
814+ Commands( "ROW_FORMAT", 0, 0, 0, ""),
815+ Commands( "RTREE", 0, 0, 0, ""),
816+ Commands( "SAVEPOINT", 0, 0, 0, ""),
817+ Commands( "SCHEMA", 0, 0, 0, ""),
818+ Commands( "SCHEMAS", 0, 0, 0, ""),
819+ Commands( "SECOND", 0, 0, 0, ""),
820+ Commands( "SECOND_MICROSECOND", 0, 0, 0, ""),
821+ Commands( "SECURITY", 0, 0, 0, ""),
822+ Commands( "SELECT", 0, 0, 0, ""),
823+ Commands( "SENSITIVE", 0, 0, 0, ""),
824+ Commands( "SEPARATOR", 0, 0, 0, ""),
825+ Commands( "SERIAL", 0, 0, 0, ""),
826+ Commands( "SERIALIZABLE", 0, 0, 0, ""),
827+ Commands( "SESSION", 0, 0, 0, ""),
828+ Commands( "SET", 0, 0, 0, ""),
829+ Commands( "SHARE", 0, 0, 0, ""),
830+ Commands( "SHOW", 0, 0, 0, ""),
831+ Commands( "SHUTDOWN", 0, 0, 0, ""),
832+ Commands( "SIGNED", 0, 0, 0, ""),
833+ Commands( "SIMPLE", 0, 0, 0, ""),
834+ Commands( "SLAVE", 0, 0, 0, ""),
835+ Commands( "SNAPSHOT", 0, 0, 0, ""),
836+ Commands( "SOME", 0, 0, 0, ""),
837+ Commands( "SONAME", 0, 0, 0, ""),
838+ Commands( "SOUNDS", 0, 0, 0, ""),
839+ Commands( "SPATIAL", 0, 0, 0, ""),
840+ Commands( "SPECIFIC", 0, 0, 0, ""),
841+ Commands( "SQL", 0, 0, 0, ""),
842+ Commands( "SQLEXCEPTION", 0, 0, 0, ""),
843+ Commands( "SQLSTATE", 0, 0, 0, ""),
844+ Commands( "SQLWARNING", 0, 0, 0, ""),
845+ Commands( "SQL_BIG_RESULT", 0, 0, 0, ""),
846+ Commands( "SQL_BUFFER_RESULT", 0, 0, 0, ""),
847+ Commands( "SQL_CACHE", 0, 0, 0, ""),
848+ Commands( "SQL_CALC_FOUND_ROWS", 0, 0, 0, ""),
849+ Commands( "SQL_NO_CACHE", 0, 0, 0, ""),
850+ Commands( "SQL_SMALL_RESULT", 0, 0, 0, ""),
851+ Commands( "SQL_THREAD", 0, 0, 0, ""),
852+ Commands( "SQL_TSI_FRAC_SECOND", 0, 0, 0, ""),
853+ Commands( "SQL_TSI_SECOND", 0, 0, 0, ""),
854+ Commands( "SQL_TSI_MINUTE", 0, 0, 0, ""),
855+ Commands( "SQL_TSI_HOUR", 0, 0, 0, ""),
856+ Commands( "SQL_TSI_DAY", 0, 0, 0, ""),
857+ Commands( "SQL_TSI_WEEK", 0, 0, 0, ""),
858+ Commands( "SQL_TSI_MONTH", 0, 0, 0, ""),
859+ Commands( "SQL_TSI_QUARTER", 0, 0, 0, ""),
860+ Commands( "SQL_TSI_YEAR", 0, 0, 0, ""),
861+ Commands( "SSL", 0, 0, 0, ""),
862+ Commands( "START", 0, 0, 0, ""),
863+ Commands( "STARTING", 0, 0, 0, ""),
864+ Commands( "STATUS", 0, 0, 0, ""),
865+ Commands( "STOP", 0, 0, 0, ""),
866+ Commands( "STORAGE", 0, 0, 0, ""),
867+ Commands( "STRAIGHT_JOIN", 0, 0, 0, ""),
868+ Commands( "STRING", 0, 0, 0, ""),
869+ Commands( "STRIPED", 0, 0, 0, ""),
870+ Commands( "SUBJECT", 0, 0, 0, ""),
871+ Commands( "SUPER", 0, 0, 0, ""),
872+ Commands( "SUSPEND", 0, 0, 0, ""),
873+ Commands( "TABLE", 0, 0, 0, ""),
874+ Commands( "TABLES", 0, 0, 0, ""),
875+ Commands( "TABLESPACE", 0, 0, 0, ""),
876+ Commands( "TEMPORARY", 0, 0, 0, ""),
877+ Commands( "TEMPTABLE", 0, 0, 0, ""),
878+ Commands( "TERMINATED", 0, 0, 0, ""),
879+ Commands( "TEXT", 0, 0, 0, ""),
880+ Commands( "THEN", 0, 0, 0, ""),
881+ Commands( "TIMESTAMP", 0, 0, 0, ""),
882+ Commands( "TIMESTAMPADD", 0, 0, 0, ""),
883+ Commands( "TIMESTAMPDIFF", 0, 0, 0, ""),
884+ Commands( "TO", 0, 0, 0, ""),
885+ Commands( "TRAILING", 0, 0, 0, ""),
886+ Commands( "TRANSACTION", 0, 0, 0, ""),
887+ Commands( "TRUE", 0, 0, 0, ""),
888+ Commands( "TRUNCATE", 0, 0, 0, ""),
889+ Commands( "TYPE", 0, 0, 0, ""),
890+ Commands( "TYPES", 0, 0, 0, ""),
891+ Commands( "UNCOMMITTED", 0, 0, 0, ""),
892+ Commands( "UNDEFINED", 0, 0, 0, ""),
893+ Commands( "UNDO", 0, 0, 0, ""),
894+ Commands( "UNICODE", 0, 0, 0, ""),
895+ Commands( "UNION", 0, 0, 0, ""),
896+ Commands( "UNIQUE", 0, 0, 0, ""),
897+ Commands( "UNKNOWN", 0, 0, 0, ""),
898+ Commands( "UNLOCK", 0, 0, 0, ""),
899+ Commands( "UNTIL", 0, 0, 0, ""),
900+ Commands( "UPDATE", 0, 0, 0, ""),
901+ Commands( "UPGRADE", 0, 0, 0, ""),
902+ Commands( "USAGE", 0, 0, 0, ""),
903+ Commands( "USE", 0, 0, 0, ""),
904+ Commands( "USER", 0, 0, 0, ""),
905+ Commands( "USER_RESOURCES", 0, 0, 0, ""),
906+ Commands( "USING", 0, 0, 0, ""),
907+ Commands( "UTC_DATE", 0, 0, 0, ""),
908+ Commands( "UTC_TIMESTAMP", 0, 0, 0, ""),
909+ Commands( "VALUE", 0, 0, 0, ""),
910+ Commands( "VALUES", 0, 0, 0, ""),
911+ Commands( "VARBINARY", 0, 0, 0, ""),
912+ Commands( "VARCHAR", 0, 0, 0, ""),
913+ Commands( "VARCHARACTER", 0, 0, 0, ""),
914+ Commands( "VARIABLES", 0, 0, 0, ""),
915+ Commands( "VARYING", 0, 0, 0, ""),
916+ Commands( "WARNINGS", 0, 0, 0, ""),
917+ Commands( "WEEK", 0, 0, 0, ""),
918+ Commands( "WHEN", 0, 0, 0, ""),
919+ Commands( "WHERE", 0, 0, 0, ""),
920+ Commands( "WHILE", 0, 0, 0, ""),
921+ Commands( "VIEW", 0, 0, 0, ""),
922+ Commands( "WITH", 0, 0, 0, ""),
923+ Commands( "WORK", 0, 0, 0, ""),
924+ Commands( "WRITE", 0, 0, 0, ""),
925+ Commands( "XOR", 0, 0, 0, ""),
926+ Commands( "XA", 0, 0, 0, ""),
927+ Commands( "YEAR", 0, 0, 0, ""),
928+ Commands( "YEAR_MONTH", 0, 0, 0, ""),
929+ Commands( "ZEROFILL", 0, 0, 0, ""),
930+ Commands( "ABS", 0, 0, 0, ""),
931+ Commands( "ACOS", 0, 0, 0, ""),
932+ Commands( "ADDDATE", 0, 0, 0, ""),
933+ Commands( "AREA", 0, 0, 0, ""),
934+ Commands( "ASIN", 0, 0, 0, ""),
935+ Commands( "ASBINARY", 0, 0, 0, ""),
936+ Commands( "ASTEXT", 0, 0, 0, ""),
937+ Commands( "ATAN", 0, 0, 0, ""),
938+ Commands( "ATAN2", 0, 0, 0, ""),
939+ Commands( "BENCHMARK", 0, 0, 0, ""),
940+ Commands( "BIN", 0, 0, 0, ""),
941+ Commands( "BIT_OR", 0, 0, 0, ""),
942+ Commands( "BIT_AND", 0, 0, 0, ""),
943+ Commands( "BIT_XOR", 0, 0, 0, ""),
944+ Commands( "CAST", 0, 0, 0, ""),
945+ Commands( "CEIL", 0, 0, 0, ""),
946+ Commands( "CEILING", 0, 0, 0, ""),
947+ Commands( "CENTROID", 0, 0, 0, ""),
948+ Commands( "CHAR_LENGTH", 0, 0, 0, ""),
949+ Commands( "CHARACTER_LENGTH", 0, 0, 0, ""),
950+ Commands( "COALESCE", 0, 0, 0, ""),
951+ Commands( "COERCIBILITY", 0, 0, 0, ""),
952+ Commands( "COMPRESS", 0, 0, 0, ""),
953+ Commands( "CONCAT", 0, 0, 0, ""),
954+ Commands( "CONCAT_WS", 0, 0, 0, ""),
955+ Commands( "CONNECTION_ID", 0, 0, 0, ""),
956+ Commands( "CONV", 0, 0, 0, ""),
957+ Commands( "CONVERT_TZ", 0, 0, 0, ""),
958+ Commands( "COUNT", 0, 0, 0, ""),
959+ Commands( "COS", 0, 0, 0, ""),
960+ Commands( "COT", 0, 0, 0, ""),
961+ Commands( "CRC32", 0, 0, 0, ""),
962+ Commands( "CROSSES", 0, 0, 0, ""),
963+ Commands( "CURDATE", 0, 0, 0, ""),
964+ Commands( "DATE_ADD", 0, 0, 0, ""),
965+ Commands( "DATEDIFF", 0, 0, 0, ""),
966+ Commands( "DATE_FORMAT", 0, 0, 0, ""),
967+ Commands( "DATE_SUB", 0, 0, 0, ""),
968+ Commands( "DAYNAME", 0, 0, 0, ""),
969+ Commands( "DAYOFMONTH", 0, 0, 0, ""),
970+ Commands( "DAYOFWEEK", 0, 0, 0, ""),
971+ Commands( "DAYOFYEAR", 0, 0, 0, ""),
972+ Commands( "DECODE", 0, 0, 0, ""),
973+ Commands( "DEGREES", 0, 0, 0, ""),
974+ Commands( "DES_ENCRYPT", 0, 0, 0, ""),
975+ Commands( "DES_DECRYPT", 0, 0, 0, ""),
976+ Commands( "DIMENSION", 0, 0, 0, ""),
977+ Commands( "DISJOINT", 0, 0, 0, ""),
978+ Commands( "ELT", 0, 0, 0, ""),
979+ Commands( "ENCODE", 0, 0, 0, ""),
980+ Commands( "ENCRYPT", 0, 0, 0, ""),
981+ Commands( "ENDPOINT", 0, 0, 0, ""),
982+ Commands( "ENVELOPE", 0, 0, 0, ""),
983+ Commands( "EQUALS", 0, 0, 0, ""),
984+ Commands( "EXTERIORRING", 0, 0, 0, ""),
985+ Commands( "EXTRACT", 0, 0, 0, ""),
986+ Commands( "EXP", 0, 0, 0, ""),
987+ Commands( "EXPORT_SET", 0, 0, 0, ""),
988+ Commands( "FIELD", 0, 0, 0, ""),
989+ Commands( "FIND_IN_SET", 0, 0, 0, ""),
990+ Commands( "FLOOR", 0, 0, 0, ""),
991+ Commands( "FORMAT", 0, 0, 0, ""),
992+ Commands( "FOUND_ROWS", 0, 0, 0, ""),
993+ Commands( "FROM_DAYS", 0, 0, 0, ""),
994+ Commands( "FROM_UNIXTIME", 0, 0, 0, ""),
995+ Commands( "GET_LOCK", 0, 0, 0, ""),
996+ Commands( "GLENGTH", 0, 0, 0, ""),
997+ Commands( "GREATEST", 0, 0, 0, ""),
998+ Commands( "GROUP_CONCAT", 0, 0, 0, ""),
999+ Commands( "GROUP_UNIQUE_USERS", 0, 0, 0, ""),
1000+ Commands( "HEX", 0, 0, 0, ""),
1001+ Commands( "IFNULL", 0, 0, 0, ""),
1002+ Commands( "INSTR", 0, 0, 0, ""),
1003+ Commands( "INTERIORRINGN", 0, 0, 0, ""),
1004+ Commands( "INTERSECTS", 0, 0, 0, ""),
1005+ Commands( "ISCLOSED", 0, 0, 0, ""),
1006+ Commands( "ISEMPTY", 0, 0, 0, ""),
1007+ Commands( "ISNULL", 0, 0, 0, ""),
1008+ Commands( "IS_FREE_LOCK", 0, 0, 0, ""),
1009+ Commands( "IS_USED_LOCK", 0, 0, 0, ""),
1010+ Commands( "LAST_INSERT_ID", 0, 0, 0, ""),
1011+ Commands( "ISSIMPLE", 0, 0, 0, ""),
1012+ Commands( "LAST_DAY", 0, 0, 0, ""),
1013+ Commands( "LCASE", 0, 0, 0, ""),
1014+ Commands( "LEAST", 0, 0, 0, ""),
1015+ Commands( "LENGTH", 0, 0, 0, ""),
1016+ Commands( "LN", 0, 0, 0, ""),
1017+ Commands( "LOAD_FILE", 0, 0, 0, ""),
1018+ Commands( "LOCATE", 0, 0, 0, ""),
1019+ Commands( "LOG", 0, 0, 0, ""),
1020+ Commands( "LOG2", 0, 0, 0, ""),
1021+ Commands( "LOG10", 0, 0, 0, ""),
1022+ Commands( "LOWER", 0, 0, 0, ""),
1023+ Commands( "LPAD", 0, 0, 0, ""),
1024+ Commands( "LTRIM", 0, 0, 0, ""),
1025+ Commands( "MAKE_SET", 0, 0, 0, ""),
1026+ Commands( "MAKEDATE", 0, 0, 0, ""),
1027+ Commands( "MASTER_POS_WAIT", 0, 0, 0, ""),
1028+ Commands( "MAX", 0, 0, 0, ""),
1029+ Commands( "MBRCONTAINS", 0, 0, 0, ""),
1030+ Commands( "MBRDISJOINT", 0, 0, 0, ""),
1031+ Commands( "MBREQUAL", 0, 0, 0, ""),
1032+ Commands( "MBRINTERSECTS", 0, 0, 0, ""),
1033+ Commands( "MBROVERLAPS", 0, 0, 0, ""),
1034+ Commands( "MBRTOUCHES", 0, 0, 0, ""),
1035+ Commands( "MBRWITHIN", 0, 0, 0, ""),
1036+ Commands( "MD5", 0, 0, 0, ""),
1037+ Commands( "MID", 0, 0, 0, ""),
1038+ Commands( "MIN", 0, 0, 0, ""),
1039+ Commands( "MONTHNAME", 0, 0, 0, ""),
1040+ Commands( "NAME_CONST", 0, 0, 0, ""),
1041+ Commands( "NOW", 0, 0, 0, ""),
1042+ Commands( "NULLIF", 0, 0, 0, ""),
1043+ Commands( "NUMPOINTS", 0, 0, 0, ""),
1044+ Commands( "OCTET_LENGTH", 0, 0, 0, ""),
1045+ Commands( "OCT", 0, 0, 0, ""),
1046+ Commands( "ORD", 0, 0, 0, ""),
1047+ Commands( "OVERLAPS", 0, 0, 0, ""),
1048+ Commands( "PERIOD_ADD", 0, 0, 0, ""),
1049+ Commands( "PERIOD_DIFF", 0, 0, 0, ""),
1050+ Commands( "PI", 0, 0, 0, ""),
1051+ Commands( "POINTN", 0, 0, 0, ""),
1052+ Commands( "POSITION", 0, 0, 0, ""),
1053+ Commands( "POW", 0, 0, 0, ""),
1054+ Commands( "POWER", 0, 0, 0, ""),
1055+ Commands( "QUOTE", 0, 0, 0, ""),
1056+ Commands( "RADIANS", 0, 0, 0, ""),
1057+ Commands( "RAND", 0, 0, 0, ""),
1058+ Commands( "RELEASE_LOCK", 0, 0, 0, ""),
1059+ Commands( "REVERSE", 0, 0, 0, ""),
1060+ Commands( "ROUND", 0, 0, 0, ""),
1061+ Commands( "ROW_COUNT", 0, 0, 0, ""),
1062+ Commands( "RPAD", 0, 0, 0, ""),
1063+ Commands( "RTRIM", 0, 0, 0, ""),
1064+ Commands( "SESSION_USER", 0, 0, 0, ""),
1065+ Commands( "SUBDATE", 0, 0, 0, ""),
1066+ Commands( "SIGN", 0, 0, 0, ""),
1067+ Commands( "SIN", 0, 0, 0, ""),
1068+ Commands( "SHA", 0, 0, 0, ""),
1069+ Commands( "SHA1", 0, 0, 0, ""),
1070+ Commands( "SLEEP", 0, 0, 0, ""),
1071+ Commands( "SOUNDEX", 0, 0, 0, ""),
1072+ Commands( "SPACE", 0, 0, 0, ""),
1073+ Commands( "SQRT", 0, 0, 0, ""),
1074+ Commands( "SRID", 0, 0, 0, ""),
1075+ Commands( "STARTPOINT", 0, 0, 0, ""),
1076+ Commands( "STD", 0, 0, 0, ""),
1077+ Commands( "STDDEV", 0, 0, 0, ""),
1078+ Commands( "STDDEV_POP", 0, 0, 0, ""),
1079+ Commands( "STDDEV_SAMP", 0, 0, 0, ""),
1080+ Commands( "STR_TO_DATE", 0, 0, 0, ""),
1081+ Commands( "STRCMP", 0, 0, 0, ""),
1082+ Commands( "SUBSTR", 0, 0, 0, ""),
1083+ Commands( "SUBSTRING", 0, 0, 0, ""),
1084+ Commands( "SUBSTRING_INDEX", 0, 0, 0, ""),
1085+ Commands( "SUM", 0, 0, 0, ""),
1086+ Commands( "SYSDATE", 0, 0, 0, ""),
1087+ Commands( "SYSTEM_USER", 0, 0, 0, ""),
1088+ Commands( "TAN", 0, 0, 0, ""),
1089+ Commands( "TIME_FORMAT", 0, 0, 0, ""),
1090+ Commands( "TO_DAYS", 0, 0, 0, ""),
1091+ Commands( "TOUCHES", 0, 0, 0, ""),
1092+ Commands( "TRIM", 0, 0, 0, ""),
1093+ Commands( "UCASE", 0, 0, 0, ""),
1094+ Commands( "UNCOMPRESS", 0, 0, 0, ""),
1095+ Commands( "UNCOMPRESSED_LENGTH", 0, 0, 0, ""),
1096+ Commands( "UNHEX", 0, 0, 0, ""),
1097+ Commands( "UNIQUE_USERS", 0, 0, 0, ""),
1098+ Commands( "UNIX_TIMESTAMP", 0, 0, 0, ""),
1099+ Commands( "UPPER", 0, 0, 0, ""),
1100+ Commands( "UUID", 0, 0, 0, ""),
1101+ Commands( "VARIANCE", 0, 0, 0, ""),
1102+ Commands( "VAR_POP", 0, 0, 0, ""),
1103+ Commands( "VAR_SAMP", 0, 0, 0, ""),
1104+ Commands( "VERSION", 0, 0, 0, ""),
1105+ Commands( "WEEKDAY", 0, 0, 0, ""),
1106+ Commands( "WEEKOFYEAR", 0, 0, 0, ""),
1107+ Commands( "WITHIN", 0, 0, 0, ""),
1108+ Commands( "X", 0, 0, 0, ""),
1109+ Commands( "Y", 0, 0, 0, ""),
1110+ Commands( "YEARWEEK", 0, 0, 0, ""),
1111+ /* end sentinel */
1112+ Commands((char *)NULL, 0, 0, 0, "")
1113+};
1114+
1115+
1116+int history_length;
1117+static int not_in_history(const char *line);
1118+static void initialize_readline (char *name);
1119+static void fix_history(string *final_command);
1120+
1121+static Commands *find_command(const char *name,char cmd_name);
1122+static bool add_line(string *buffer,char *line,char *in_string,
1123+ bool *ml_comment);
1124+static void remove_cntrl(string *buffer);
1125+static void print_table_data(drizzle_result_st *result);
1126+static void print_tab_data(drizzle_result_st *result);
1127+static void print_table_data_vertically(drizzle_result_st *result);
1128+static void print_warnings(uint32_t error_code);
1129+static uint32_t start_timer(void);
1130+static void end_timer(uint32_t start_time,char *buff);
1131+static void drizzle_end_timer(uint32_t start_time,char *buff);
1132+static void nice_time(double sec,char *buff,bool part_second);
1133+extern "C" void drizzle_end(int sig);
1134+extern "C" void handle_sigint(int sig);
1135+#if defined(HAVE_TERMIOS_H) && defined(GWINSZ_IN_SYS_IOCTL)
1136+static void window_resize(int sig);
1137+#endif
1138+
1139+/**
1140+ Shutdown the server that we are currently connected to.
1141+
1142+ @retval
1143+ true success
1144+ @retval
1145+ false failure
1146+*/
1147+static bool server_shutdown(void)
1148+{
1149+ drizzle_result_st result;
1150+ drizzle_return_t ret;
1151+
1152+ if (verbose)
1153+ {
1154+ printf(_("shutting down drizzled"));
1155+ if (opt_drizzle_port > 0)
1156+ printf(_(" on port %d"), opt_drizzle_port);
1157+ printf("... ");
1158+ }
1159+
1160+ if (drizzle_shutdown(&con, &result, DRIZZLE_SHUTDOWN_DEFAULT,
1161+ &ret) == NULL || ret != DRIZZLE_RETURN_OK)
1162+ {
1163+ if (ret == DRIZZLE_RETURN_ERROR_CODE)
1164+ {
1165+ fprintf(stderr, _("shutdown failed; error: '%s'"),
1166+ drizzle_result_error(&result));
1167+ drizzle_result_free(&result);
1168+ }
1169+ else
1170+ {
1171+ fprintf(stderr, _("shutdown failed; error: '%s'"),
1172+ drizzle_con_error(&con));
1173+ }
1174+ return false;
1175+ }
1176+
1177+ drizzle_result_free(&result);
1178+
1179+ if (verbose)
1180+ printf(_("done\n"));
1181+
1182+ return true;
1183+}
1184+
1185+/**
1186+ Ping the server that we are currently connected to.
1187+
1188+ @retval
1189+ true success
1190+ @retval
1191+ false failure
1192+*/
1193+static bool server_ping(void)
1194+{
1195+ drizzle_result_st result;
1196+ drizzle_return_t ret;
1197+
1198+ if (drizzle_ping(&con, &result, &ret) != NULL && ret == DRIZZLE_RETURN_OK)
1199+ {
1200+ if (opt_silent < 2)
1201+ printf(_("drizzled is alive\n"));
1202+ }
1203+ else
1204+ {
1205+ if (ret == DRIZZLE_RETURN_ERROR_CODE)
1206+ {
1207+ fprintf(stderr, _("ping failed; error: '%s'"),
1208+ drizzle_result_error(&result));
1209+ drizzle_result_free(&result);
1210+ }
1211+ else
1212+ {
1213+ fprintf(stderr, _("drizzled won't answer to ping, error: '%s'"),
1214+ drizzle_con_error(&con));
1215+ }
1216+ return false;
1217+ }
1218+ drizzle_result_free(&result);
1219+ return true;
1220+}
1221+
1222+/**
1223+ Execute command(s) specified by the user.
1224+
1225+ @param error error status of command execution.
1226+ If an error had occurred, this variable will be set
1227+ to 1 whereas on success, it shall be set to 0. This
1228+ value will be supplied to the exit() function used
1229+ by the caller.
1230+
1231+ @retval
1232+ false no commands were executed
1233+ @retval
1234+ true at least one command was executed
1235+*/
1236+static bool execute_commands(int *error)
1237+{
1238+ bool executed= false;
1239+ *error= 0;
1240+
1241+ if (opt_ping)
1242+ {
1243+ if (server_ping() == false)
1244+ *error= 1;
1245+ executed= true;
1246+ }
1247+
1248+ if (opt_shutdown)
1249+ {
1250+ if (server_shutdown() == false)
1251+ *error= 1;
1252+ executed= true;
1253+ }
1254+ return executed;
1255+}
1256+
1257+static void check_timeout_value(uint32_t in_connect_timeout)
1258+{
1259+ opt_connect_timeout= 0;
1260+ if (in_connect_timeout > 3600*12)
1261+ {
1262+ cout << _("Error: Invalid Value for connect_timeout");
1263+ exit(-1);
1264+ }
1265+ opt_connect_timeout= in_connect_timeout;
1266+}
1267+
1268+static void check_max_input_line(uint32_t in_max_input_line)
1269+{
1270+ opt_max_input_line= 0;
1271+ if (in_max_input_line < 4096 || in_max_input_line > (int64_t)2*1024L*1024L*1024L)
1272+ {
1273+ cout << _("Error: Invalid Value for max_input_line");
1274+ exit(-1);
1275+ }
1276+ opt_max_input_line= in_max_input_line - (in_max_input_line % 1024);
1277+}
1278+
1279+int main(int argc,char *argv[])
1280+{
1281+try
1282+{
1283+
1284+#if defined(ENABLE_NLS)
1285+# if defined(HAVE_LOCALE_H)
1286+ setlocale(LC_ALL, "");
1287+# endif
1288+ bindtextdomain("drizzle", LOCALEDIR);
1289+ textdomain("drizzle");
1290+#endif
1291+
1292+ po::options_description commandline_options(N_("Options used only in command line"));
1293+ commandline_options.add_options()
1294+ ("help,?",N_("Displays this help and exit."))
1295+ ("batch,B",N_("Don't use history file. Disable interactive behavior. (Enables --silent)"))
1296+ ("column-type-info", po::value<bool>(&column_types_flag)->default_value(false)->zero_tokens(),
1297+ N_("Display column type information."))
1298+ ("comments,c", po::value<bool>(&preserve_comments)->default_value(false)->zero_tokens(),
1299+ N_("Preserve comments. Send comments to the server. The default is --skip-comments (discard comments), enable with --comments"))
1300+ ("vertical,E", po::value<bool>(&vertical)->default_value(false)->zero_tokens(),
1301+ N_("Print the output of a query (rows) vertically."))
1302+ ("force,f", po::value<bool>(&ignore_errors)->default_value(false)->zero_tokens(),
1303+ N_("Continue even if we get an sql error."))
1304+ ("named-commands,G", po::value<bool>(&named_cmds)->default_value(false)->zero_tokens(),
1305+ N_("Enable named commands. Named commands mean this program's internal commands; see drizzle> help . When enabled, the named commands can be used from any line of the query, otherwise only from the first line, before an enter."))
1306+ ("no-beep,b", po::value<bool>(&opt_nobeep)->default_value(false)->zero_tokens(),
1307+ N_("Turn off beep on error."))
1308+ ("disable-line-numbers", N_("Do not write line numbers for errors."))
1309+ ("disable-column-names", N_("Do not write column names in results."))
1310+ ("skip-column-names,N",
1311+ N_("Don't write column names in results. WARNING: -N is deprecated, use long version of this options instead."))
1312+ ("set-variable,O", po::value<string>(),
1313+ N_("Change the value of a variable. Please note that this option is deprecated; you can set variables directly with --variable-name=value."))
1314+ ("table,t", po::value<bool>(&output_tables)->default_value(false)->zero_tokens(),
1315+ N_("Output in table format."))
1316+ ("safe-updates,U", po::value<bool>(&safe_updates)->default_value(false)->zero_tokens(),
1317+ N_("Only allow UPDATE and DELETE that uses keys."))
1318+ ("i-am-a-dummy,U", po::value<bool>(&safe_updates)->default_value(false)->zero_tokens(),
1319+ N_("Synonym for option --safe-updates, -U."))
1320+ ("verbose,v", po::value<string>(&opt_verbose)->default_value(""),
1321+ N_("-v vvv implies that verbose= 3, Used to specify verbose"))
1322+ ("version,V", N_("Output version information and exit."))
1323+ ("secure-auth", po::value<bool>(&opt_secure_auth)->default_value(false)->zero_tokens(),
1324+ N_("Refuse client connecting to server if it uses old (pre-4.1.1) protocol"))
1325+ ("show-warnings", po::value<bool>(&show_warnings)->default_value(false)->zero_tokens(),
1326+ N_("Show warnings after every statement."))
1327+ ("show-progress-size", po::value<uint32_t>(&show_progress_size)->default_value(0),
1328+ N_("Number of lines before each import progress report."))
1329+ ("ping", po::value<bool>(&opt_ping)->default_value(false)->zero_tokens(),
1330+ N_("Ping the server to check if it's alive."))
1331+ ("no-defaults", po::value<bool>()->default_value(false)->zero_tokens(),
1332+ N_("Configuration file defaults are not used if no-defaults is set"))
1333+ ;
1334+
1335+ po::options_description drizzle_options(N_("Options specific to the drizzle client"));
1336+ drizzle_options.add_options()
1337+ ("disable-auto-rehash,A",
1338+ N_("Disable automatic rehashing. One doesn't need to use 'rehash' to get table and field completion, but startup and reconnecting may take a longer time."))
1339+ ("auto-vertical-output", po::value<bool>(&auto_vertical_output)->default_value(false)->zero_tokens(),
1340+ N_("Automatically switch to vertical output mode if the result is wider than the terminal width."))
1341+ ("database,D", po::value<string>(&current_db)->default_value(""),
1342+ N_("Database to use."))
1343+ ("default-character-set",po::value<string>(),
1344+ N_("(not used)"))
1345+ ("delimiter", po::value<string>(&delimiter_str)->default_value(";"),
1346+ N_("Delimiter to be used."))
1347+ ("execute,e", po::value<string>(),
1348+ N_("Execute command and quit. (Disables --force and history file)"))
1349+ ("key,k", po::value<string>(&randomization_key)->default_value(""),
1350+ N_("Randomization key."))
1351+ ("local-infile", po::value<bool>(&opt_local_infile)->default_value(false)->zero_tokens(),
1352+ N_("Enable LOAD DATA LOCAL INFILE."))
1353+ ("unbuffered,n", po::value<bool>(&unbuffered)->default_value(false)->zero_tokens(),
1354+ N_("Flush buffer after each query."))
1355+ ("sigint-ignore", po::value<bool>(&opt_sigint_ignore)->default_value(false)->zero_tokens(),
1356+ N_("Ignore SIGINT (CTRL-C)"))
1357+ ("one-database,o", po::value<bool>(&one_database)->default_value(false)->zero_tokens(),
1358+ N_("Only update the default database. This is useful for skipping updates to other database in the update log."))
1359+ ("pager", po::value<string>(),
1360+ N_("Pager to use to display results. If you don't supply an option the default pager is taken from your ENV variable PAGER. Valid pagers are less, more, cat [> filename], etc. See interactive help (\\h) also. This option does not work in batch mode. Disable with --disable-pager. This option is disabled by default."))
1361+ ("disable-pager", po::value<bool>(&opt_nopager)->default_value(false)->zero_tokens(),
1362+ N_("Disable pager and print to stdout. See interactive help (\\h) also."))
1363+ ("prompt", po::value<string>(&current_prompt)->default_value(""),
1364+ N_("Set the drizzle prompt to this value."))
1365+ ("quick,q", po::value<bool>(&quick)->default_value(false)->zero_tokens(),
1366+ N_("Don't cache result, print it row by row. This may slow down the server if the output is suspended. Doesn't use history file."))
1367+ ("raw,r", po::value<bool>(&opt_raw_data)->default_value(false)->zero_tokens(),
1368+ N_("Write fields without conversion. Used with --batch."))
1369+ ("disable-reconnect", N_("Do not reconnect if the connection is lost."))
1370+ ("shutdown", po::value<bool>()->zero_tokens(),
1371+ N_("Shutdown the server"))
1372+ ("silent,s", N_("Be more silent. Print results with a tab as separator, each row on new line."))
1373+ ("tee", po::value<string>(),
1374+ N_("Append everything into outfile. See interactive help (\\h) also. Does not work in batch mode. Disable with --disable-tee. This option is disabled by default."))
1375+ ("disable-tee", po::value<bool>()->default_value(false)->zero_tokens(),
1376+ N_("Disable outfile. See interactive help (\\h) also."))
1377+ ("connect_timeout", po::value<uint32_t>(&opt_connect_timeout)->default_value(0)->notifier(&check_timeout_value),
1378+ N_("Number of seconds before connection timeout."))
1379+ ("max_input_line", po::value<uint32_t>(&opt_max_input_line)->default_value(16*1024L*1024L)->notifier(&check_max_input_line),
1380+ N_("Max length of input line"))
1381+ ("select_limit", po::value<uint32_t>(&select_limit)->default_value(1000L),
1382+ N_("Automatic limit for SELECT when using --safe-updates"))
1383+ ("max_join_size", po::value<uint32_t>(&max_join_size)->default_value(1000000L),
1384+ N_("Automatic limit for rows in a join when using --safe-updates"))
1385+ ;
1386+
1387+ po::options_description client_options(N_("Options specific to the client"));
1388+ client_options.add_options()
1389+ ("host,h", po::value<string>(&current_host)->default_value("localhost"),
1390+ N_("Connect to host"))
1391+ ("password,P", po::value<string>(&current_password)->default_value(PASSWORD_SENTINEL),
1392+ N_("Password to use when connecting to server. If password is not given it's asked from the tty."))
1393+ ("port,p", po::value<uint32_t>()->default_value(0),
1394+ N_("Port number to use for connection or 0 for default to, in order of preference, drizzle.cnf, $DRIZZLE_TCP_PORT, built-in default"))
1395+ ("user,u", po::value<string>(&current_user)->default_value(""),
1396+ N_("User for login if not current user."))
1397+ ("protocol",po::value<string>(&opt_protocol)->default_value("mysql"),
1398+ N_("The protocol of connection (mysql or drizzle)."))
1399+ ;
1400+
1401+ po::options_description long_options(N_("Allowed Options"));
1402+ long_options.add(commandline_options).add(drizzle_options).add(client_options);
1403+
1404+ std::string system_config_dir_drizzle(SYSCONFDIR);
1405+ system_config_dir_drizzle.append("/drizzle/drizzle.cnf");
1406+
1407+ std::string system_config_dir_client(SYSCONFDIR);
1408+ system_config_dir_client.append("/drizzle/client.cnf");
1409+
1410+ std::string user_config_dir((getenv("XDG_CONFIG_HOME")? getenv("XDG_CONFIG_HOME"):"~/.config"));
1411+
1412+ po::variables_map vm;
1413+
1414+ po::positional_options_description p;
1415+ p.add("database", 1);
1416+
1417+ // Disable allow_guessing
1418+ int style = po::command_line_style::default_style & ~po::command_line_style::allow_guessing;
1419+
1420+ po::store(po::command_line_parser(argc, argv).options(long_options).
1421+ style(style).positional(p).extra_parser(parse_password_arg).run(),
1422+ vm);
1423+
1424+ if (! vm["no-defaults"].as<bool>())
1425+ {
1426+ std::string user_config_dir_drizzle(user_config_dir);
1427+ user_config_dir_drizzle.append("/drizzle/drizzle.cnf");
1428+
1429+ std::string user_config_dir_client(user_config_dir);
1430+ user_config_dir_client.append("/drizzle/client.cnf");
1431+
1432+ ifstream user_drizzle_ifs(user_config_dir_drizzle.c_str());
1433+ po::store(dpo::parse_config_file(user_drizzle_ifs, drizzle_options), vm);
1434+
1435+ ifstream user_client_ifs(user_config_dir_client.c_str());
1436+ po::store(dpo::parse_config_file(user_client_ifs, client_options), vm);
1437+
1438+ ifstream system_drizzle_ifs(system_config_dir_drizzle.c_str());
1439+ store(dpo::parse_config_file(system_drizzle_ifs, drizzle_options), vm);
1440+
1441+ ifstream system_client_ifs(system_config_dir_client.c_str());
1442+ po::store(dpo::parse_config_file(system_client_ifs, client_options), vm);
1443+ }
1444+
1445+ po::notify(vm);
1446+
1447+ default_prompt= strdup(getenv("DRIZZLE_PS1") ?
1448+ getenv("DRIZZLE_PS1") :
1449+ "drizzle> ");
1450+ if (default_prompt == NULL)
1451+ {
1452+ fprintf(stderr, _("Memory allocation error while constructing initial "
1453+ "prompt. Aborting.\n"));
1454+ exit(ENOMEM);
1455+ }
1456+ current_prompt= strdup(default_prompt);
1457+ if (current_prompt.empty())
1458+ {
1459+ fprintf(stderr, _("Memory allocation error while constructing initial "
1460+ "prompt. Aborting.\n"));
1461+ exit(ENOMEM);
1462+ }
1463+ processed_prompt= new string();
1464+ processed_prompt->reserve(32);
1465+
1466+ prompt_counter=0;
1467+
1468+ outfile.clear(); // no (default) outfile
1469+ pager.assign("stdout"); // the default, if --pager wasn't given
1470+ {
1471+ const char *tmp= getenv("PAGER");
1472+ if (tmp && strlen(tmp))
1473+ {
1474+ default_pager_set= 1;
1475+ default_pager.assign(tmp);
1476+ }
1477+ }
1478+ if (! isatty(0) || ! isatty(1))
1479+ {
1480+ status.setBatch(1); opt_silent=1;
1481+ ignore_errors=0;
1482+ }
1483+ else
1484+ status.setAddToHistory(1);
1485+ status.setExitStatus(1);
1486+
1487+ {
1488+ /*
1489+ The file descriptor-layer may be out-of-sync with the file-number layer,
1490+ so we make sure that "stdout" is really open. If its file is closed then
1491+ explicitly close the FD layer.
1492+ */
1493+ int stdout_fileno_copy;
1494+ stdout_fileno_copy= dup(fileno(stdout)); /* Okay if fileno fails. */
1495+ if (stdout_fileno_copy == -1)
1496+ fclose(stdout);
1497+ else
1498+ close(stdout_fileno_copy); /* Clean up dup(). */
1499+ }
1500+
1501+ /* Inverted Booleans */
1502+
1503+ line_numbers= (vm.count("disable-line-numbers")) ? false : true;
1504+ column_names= (vm.count("disable-column-names")) ? false : true;
1505+ opt_rehash= (vm.count("disable-auto-rehash")) ? false : true;
1506+ opt_reconnect= (vm.count("disable-reconnect")) ? false : true;
1507+
1508+ /* Don't rehash with --shutdown */
1509+ if (vm.count("shutdown"))
1510+ {
1511+ opt_rehash= false;
1512+ opt_shutdown= true;
1513+ }
1514+
1515+ if (vm.count("delimiter"))
1516+ {
1517+ /* Check that delimiter does not contain a backslash */
1518+ if (! strstr(delimiter_str.c_str(), "\\"))
1519+ {
1520+ delimiter= (char *)delimiter_str.c_str();
1521+ }
1522+ else
1523+ {
1524+ put_info(_("DELIMITER cannot contain a backslash character"),
1525+ INFO_ERROR,0,0);
1526+ exit(-1);
1527+ }
1528+
1529+ delimiter_length= (uint32_t)strlen(delimiter);
1530+ }
1531+ if (vm.count("tee"))
1532+ {
1533+ if (vm["tee"].as<string>().empty())
1534+ {
1535+ if (opt_outfile)
1536+ end_tee();
1537+ }
1538+ else
1539+ init_tee(vm["tee"].as<string>().c_str());
1540+ }
1541+ if (vm["disable-tee"].as<bool>() == true)
1542+ {
1543+ if (opt_outfile)
1544+ end_tee();
1545+ }
1546+ if (vm.count("pager"))
1547+ {
1548+ if (vm["pager"].as<string>().empty())
1549+ opt_nopager= 1;
1550+ else
1551+ {
1552+ opt_nopager= 0;
1553+ if (vm[pager].as<string>().length())
1554+ {
1555+ default_pager_set= 1;
1556+ pager.assign(vm["pager"].as<string>());
1557+ default_pager.assign(pager);
1558+ }
1559+ else if (default_pager_set)
1560+ pager.assign(default_pager);
1561+ else
1562+ opt_nopager= 1;
1563+ }
1564+ }
1565+ if (vm.count("disable-pager"))
1566+ {
1567+ opt_nopager= 1;
1568+ }
1569+
1570+ if (vm.count("no-auto-rehash"))
1571+ opt_rehash= 0;
1572+
1573+ if (vm.count("skip-column-names"))
1574+ column_names= 0;
1575+
1576+ if (vm.count("execute"))
1577+ {
1578+ status.setBatch(1);
1579+ status.setAddToHistory(1);
1580+ if (status.getLineBuff() == NULL)
1581+ status.setLineBuff(opt_max_input_line,NULL);
1582+ if (status.getLineBuff() == NULL)
1583+ {
1584+ exit(1);
1585+ }
1586+ status.getLineBuff()->addString(vm["execute"].as<string>().c_str());
1587+ }
1588+
1589+ if (one_database)
1590+ skip_updates= true;
1591+
1592+ if (vm.count("protocol"))
1593+ {
1594+ std::transform(opt_protocol.begin(), opt_protocol.end(),
1595+ opt_protocol.begin(), ::tolower);
1596+
1597+ if (not opt_protocol.compare("mysql"))
1598+ use_drizzle_protocol=false;
1599+ else if (not opt_protocol.compare("drizzle"))
1600+ use_drizzle_protocol=true;
1601+ else
1602+ {
1603+ cout << _("Error: Unknown protocol") << " '" << opt_protocol << "'" << endl;
1604+ exit(-1);
1605+ }
1606+ }
1607+
1608+ if (vm.count("port"))
1609+ {
1610+ opt_drizzle_port= vm["port"].as<uint32_t>();
1611+
1612+ /* If the port number is > 65535 it is not a valid port
1613+ This also helps with potential data loss casting unsigned long to a
1614+ uint32_t. */
1615+ if (opt_drizzle_port > 65535)
1616+ {
1617+ printf(_("Error: Value of %" PRIu32 " supplied for port is not valid.\n"), opt_drizzle_port);
1618+ exit(-1);
1619+ }
1620+ }
1621+
1622+ if (vm.count("password"))
1623+ {
1624+ if (!opt_password.empty())
1625+ opt_password.erase();
1626+ if (current_password == PASSWORD_SENTINEL)
1627+ {
1628+ opt_password= "";
1629+ }
1630+ else
1631+ {
1632+ opt_password= current_password;
1633+ tty_password= false;
1634+ }
1635+ }
1636+ else
1637+ {
1638+ tty_password= true;
1639+ }
1640+
1641+
1642+ if (!opt_verbose.empty())
1643+ {
1644+ verbose= opt_verbose.length();
1645+ }
1646+
1647+ if (vm.count("batch"))
1648+ {
1649+ status.setBatch(1);
1650+ status.setAddToHistory(0);
1651+ if (opt_silent < 1)
1652+ {
1653+ opt_silent= 1;
1654+ }
1655+ }
1656+ if (vm.count("silent"))
1657+ {
1658+ opt_silent++;
1659+ }
1660+
1661+ if (vm.count("help") || vm.count("version"))
1662+ {
1663+ printf(_("Drizzle client %s build %s, for %s-%s (%s) using readline %s\n"),
1664+ drizzle_version(), VERSION,
1665+ HOST_VENDOR, HOST_OS, HOST_CPU,
1666+ rl_library_version);
1667+ if (vm.count("version"))
1668+ exit(0);
1669+ printf(_("Copyright (C) 2008 Sun Microsystems\n"
1670+ "This software comes with ABSOLUTELY NO WARRANTY. "
1671+ "This is free software,\n"
1672+ "and you are welcome to modify and redistribute it "
1673+ "under the GPL license\n"));
1674+ printf(_("Usage: drizzle [OPTIONS] [database]\n"));
1675+ cout << long_options;
1676+ exit(0);
1677+ }
1678+
1679+
1680+ if (process_options())
1681+ {
1682+ exit(1);
1683+ }
1684+
1685+ memset(&drizzle, 0, sizeof(drizzle));
1686+ if (sql_connect(current_host, current_db, current_user, opt_password,opt_silent))
1687+ {
1688+ quick= 1; // Avoid history
1689+ status.setExitStatus(1);
1690+ drizzle_end(-1);
1691+ }
1692+
1693+ int command_error;
1694+ if (execute_commands(&command_error) != false)
1695+ {
1696+ /* we've executed a command so exit before we go into readline mode */
1697+ exit(command_error);
1698+ }
1699+
1700+ if (status.getBatch() && !status.getLineBuff())
1701+ {
1702+ status.setLineBuff(opt_max_input_line, stdin);
1703+ if (status.getLineBuff() == NULL)
1704+ {
1705+ exit(1);
1706+ }
1707+ }
1708+
1709+ if (!status.getBatch())
1710+ ignore_errors=1; // Don't abort monitor
1711+
1712+ if (opt_sigint_ignore)
1713+ signal(SIGINT, SIG_IGN);
1714+ else
1715+ signal(SIGINT, handle_sigint); // Catch SIGINT to clean up
1716+ signal(SIGQUIT, drizzle_end); // Catch SIGQUIT to clean up
1717+
1718+#if defined(HAVE_TERMIOS_H) && defined(GWINSZ_IN_SYS_IOCTL)
1719+ /* Readline will call this if it installs a handler */
1720+ signal(SIGWINCH, window_resize);
1721+ /* call the SIGWINCH handler to get the default term width */
1722+ window_resize(0);
1723+#endif
1724+ std::vector<char> output_buff;
1725+ output_buff.resize(512);
1726+
1727+ snprintf(&output_buff[0], output_buff.size(),
1728+ _("Welcome to the Drizzle client.. Commands end with %s or \\g."),
1729+ delimiter);
1730+
1731+ put_info(&output_buff[0], INFO_INFO, 0, 0);
1732+
1733+ glob_buffer= new string();
1734+ glob_buffer->reserve(512);
1735+
1736+ snprintf(&output_buff[0], output_buff.size(),
1737+ _("Your Drizzle connection id is %u\nConnection protocol: %s\nServer version: %s\n"),
1738+ drizzle_con_thread_id(&con),
1739+ opt_protocol.c_str(),
1740+ server_version_string(&con));
1741+ put_info(&output_buff[0], INFO_INFO, 0, 0);
1742+
1743+
1744+ initialize_readline((char *)current_prompt.c_str());
1745+ if (!status.getBatch() && !quick)
1746+ {
1747+ /* read-history from file, default ~/.drizzle_history*/
1748+ if (getenv("DRIZZLE_HISTFILE"))
1749+ histfile= strdup(getenv("DRIZZLE_HISTFILE"));
1750+ else if (getenv("HOME"))
1751+ {
1752+ histfile=(char*) malloc(strlen(getenv("HOME")) + strlen("/.drizzle_history") + 2);
1753+ if (histfile)
1754+ sprintf(histfile,"%s/.drizzle_history",getenv("HOME"));
1755+ char link_name[FN_REFLEN];
1756+ ssize_t sym_link_size= readlink(histfile,link_name,FN_REFLEN-1);
1757+ if (sym_link_size >= 0)
1758+ {
1759+ link_name[sym_link_size]= '\0';
1760+ if (strncmp(link_name, "/dev/null", 10) == 0)
1761+ {
1762+ /* The .drizzle_history file is a symlink to /dev/null, don't use it */
1763+ free(histfile);
1764+ histfile= 0;
1765+ }
1766+ }
1767+ }
1768+ if (histfile)
1769+ {
1770+ if (verbose)
1771+ tee_fprintf(stdout, _("Reading history-file %s\n"),histfile);
1772+ read_history(histfile);
1773+ if (!(histfile_tmp= (char*) malloc((uint32_t) strlen(histfile) + 5)))
1774+ {
1775+ fprintf(stderr, _("Couldn't allocate memory for temp histfile!\n"));
1776+ exit(1);
1777+ }
1778+ sprintf(histfile_tmp, "%s.TMP", histfile);
1779+ }
1780+ }
1781+
1782+ put_info(_("Type 'help;' or '\\h' for help. "
1783+ "Type '\\c' to clear the buffer.\n"),INFO_INFO,0,0);
1784+ status.setExitStatus(read_and_execute(!status.getBatch()));
1785+ if (opt_outfile)
1786+ end_tee();
1787+ drizzle_end(0);
1788+}
1789+
1790+ catch(exception &err)
1791+ {
1792+ cerr << _("Error:") << err.what() << endl;
1793+ }
1794+ return(0); // Keep compiler happy
1795+}
1796+
1797+void drizzle_end(int sig)
1798+{
1799+ drizzle_con_free(&con);
1800+ drizzle_free(&drizzle);
1801+ if (!status.getBatch() && !quick && histfile)
1802+ {
1803+ /* write-history */
1804+ if (verbose)
1805+ tee_fprintf(stdout, _("Writing history-file %s\n"),histfile);
1806+ if (!write_history(histfile_tmp))
1807+ rename(histfile_tmp, histfile);
1808+ }
1809+ delete status.getLineBuff();
1810+ status.setLineBuff(0);
1811+
1812+ if (sig >= 0)
1813+ put_info(sig ? _("Aborted") : _("Bye"), INFO_RESULT,0,0);
1814+ delete glob_buffer;
1815+ delete processed_prompt;
1816+ opt_password.erase();
1817+ free(histfile);
1818+ free(histfile_tmp);
1819+ current_db.erase();
1820+ current_host.erase();
1821+ current_user.erase();
1822+ free(full_username);
1823+ free(part_username);
1824+ free(default_prompt);
1825+ current_prompt.erase();
1826+ exit(status.getExitStatus());
1827+}
1828+
1829+
1830+/*
1831+ This function handles sigint calls
1832+ If query is in process, kill query
1833+ no query in process, terminate like previous behavior
1834+*/
1835+extern "C"
1836+void handle_sigint(int sig)
1837+{
1838+ char kill_buffer[40];
1839+ drizzle_con_st kill_drizzle;
1840+ drizzle_result_st res;
1841+ drizzle_return_t ret;
1842+
1843+ /* terminate if no query being executed, or we already tried interrupting */
1844+ if (!executing_query || interrupted_query) {
1845+ goto err;
1846+ }
1847+
1848+ if (drizzle_con_add_tcp(&drizzle, &kill_drizzle, current_host.c_str(),
1849+ opt_drizzle_port, current_user.c_str(), opt_password.c_str(), NULL,
1850+ use_drizzle_protocol ? DRIZZLE_CON_EXPERIMENTAL : DRIZZLE_CON_MYSQL) == NULL)
1851+ {
1852+ goto err;
1853+ }
1854+
1855+ /* kill_buffer is always big enough because max length of %lu is 15 */
1856+ sprintf(kill_buffer, "KILL /*!50000 QUERY */ %u",
1857+ drizzle_con_thread_id(&con));
1858+
1859+ if (drizzle_query_str(&kill_drizzle, &res, kill_buffer, &ret) != NULL)
1860+ drizzle_result_free(&res);
1861+
1862+ drizzle_con_free(&kill_drizzle);
1863+ tee_fprintf(stdout, _("Query aborted by Ctrl+C\n"));
1864+
1865+ interrupted_query= 1;
1866+
1867+ return;
1868+
1869+err:
1870+ drizzle_end(sig);
1871+}
1872+
1873+
1874+#if defined(HAVE_TERMIOS_H) && defined(GWINSZ_IN_SYS_IOCTL)
1875+void window_resize(int)
1876+{
1877+ struct winsize window_size;
1878+
1879+ if (ioctl(fileno(stdin), TIOCGWINSZ, &window_size) == 0)
1880+ terminal_width= window_size.ws_col;
1881+}
1882+#endif
1883+
1884+
1885+
1886+static int process_options(void)
1887+{
1888+ char *tmp, *pagpoint;
1889+
1890+
1891+ tmp= (char *) getenv("DRIZZLE_HOST");
1892+ if (tmp)
1893+ current_host.assign(tmp);
1894+
1895+ pagpoint= getenv("PAGER");
1896+ if (!((char*) (pagpoint)))
1897+ {
1898+ pager.assign("stdout");
1899+ opt_nopager= 1;
1900+ }
1901+ else
1902+ {
1903+ pager.assign(pagpoint);
1904+ }
1905+ default_pager.assign(pager);
1906+
1907+ //
1908+
1909+ if (status.getBatch()) /* disable pager and outfile in this case */
1910+ {
1911+ default_pager.assign("stdout");
1912+ pager.assign("stdout");
1913+ opt_nopager= 1;
1914+ default_pager_set= 0;
1915+ opt_outfile= 0;
1916+ opt_reconnect= 0;
1917+ connect_flag= DRIZZLE_CAPABILITIES_NONE; /* Not in interactive mode */
1918+ }
1919+
1920+ if (tty_password)
1921+ opt_password= client_get_tty_password(NULL);
1922+ return(0);
1923+}
1924+
1925+static int read_and_execute(bool interactive)
1926+{
1927+ char *line;
1928+ char in_string=0;
1929+ uint32_t line_number=0;
1930+ bool ml_comment= 0;
1931+ Commands *com;
1932+ status.setExitStatus(1);
1933+
1934+ for (;;)
1935+ {
1936+ if (!interactive)
1937+ {
1938+ if (status.getLineBuff())
1939+ line= status.getLineBuff()->readline();
1940+ else
1941+ line= 0;
1942+
1943+ line_number++;
1944+ if (show_progress_size > 0)
1945+ {
1946+ if ((line_number % show_progress_size) == 0)
1947+ fprintf(stderr, _("Processing line: %"PRIu32"\n"), line_number);
1948+ }
1949+ if (!glob_buffer->empty())
1950+ status.setQueryStartLine(line_number);
1951+ }
1952+ else
1953+ {
1954+ string prompt(ml_comment
1955+ ? " /*> "
1956+ : glob_buffer->empty()
1957+ ? construct_prompt()
1958+ : not in_string
1959+ ? " -> "
1960+ : in_string == '\''
1961+ ? " '> "
1962+ : in_string == '`'
1963+ ? " `> "
1964+ : " \"> ");
1965+ if (opt_outfile && glob_buffer->empty())
1966+ fflush(OUTFILE);
1967+
1968+ if (opt_outfile)
1969+ fputs(prompt.c_str(), OUTFILE);
1970+ line= readline(prompt.c_str());
1971+ /*
1972+ When Ctrl+d or Ctrl+z is pressed, the line may be NULL on some OS
1973+ which may cause coredump.
1974+ */
1975+ if (opt_outfile && line)
1976+ fprintf(OUTFILE, "%s\n", line);
1977+ }
1978+ // End of file
1979+ if (!line)
1980+ {
1981+ status.setExitStatus(0);
1982+ break;
1983+ }
1984+
1985+ /* randomize the input query here */
1986+ string output_query(line, strlen(line));
1987+ sql_tokenizer tokenizer(randomization_key);
1988+ tokenizer.randomize_query(output_query);
1989+ free(line);
1990+ line = (char*) calloc(output_query.length(), 1);
1991+ memcpy(line, output_query.c_str(), output_query.length());
1992+ if (! line)
1993+ {
1994+ status.setExitStatus(0);
1995+ break;
1996+ }
1997+
1998+ /*
1999+ Check if line is a drizzle command line
2000+ (We want to allow help, print and clear anywhere at line start
2001+ */
2002+ if ((named_cmds || (glob_buffer->empty()))
2003+ && !ml_comment && !in_string && (com=find_command(line,0)))
2004+ {
2005+ if ((*com->func)(glob_buffer,line) > 0)
2006+ break;
2007+ // If buffer was emptied
2008+ if (glob_buffer->empty())
2009+ in_string=0;
2010+ if (interactive && status.getAddToHistory() && not_in_history(line))
2011+ add_history(line);
2012+ continue;
2013+ }
2014+ if (add_line(glob_buffer,line,&in_string,&ml_comment))
2015+ break;
2016+ }
2017+ /* if in batch mode, send last query even if it doesn't end with \g or go */
2018+
2019+ if (!interactive && !status.getExitStatus())
2020+ {
2021+ remove_cntrl(glob_buffer);
2022+ if (!glob_buffer->empty())
2023+ {
2024+ status.setExitStatus(1);
2025+ if (com_go(glob_buffer,line) <= 0)
2026+ status.setExitStatus(0);
2027+ }
2028+ }
2029+
2030+ return status.getExitStatus();
2031+}
2032+
2033+
2034+static Commands *find_command(const char *name,char cmd_char)
2035+{
2036+ uint32_t len;
2037+ const char *end;
2038+
2039+ if (!name)
2040+ {
2041+ len=0;
2042+ end=0;
2043+ }
2044+ else
2045+ {
2046+ while (isspace(*name))
2047+ name++;
2048+ /*
2049+ If there is an \\g in the row or if the row has a delimiter but
2050+ this is not a delimiter command, let add_line() take care of
2051+ parsing the row and calling find_command()
2052+ */
2053+ if (strstr(name, "\\g") || (strstr(name, delimiter) &&
2054+ !(strlen(name) >= 9 &&
2055+ !strcmp(name, "delimiter"))))
2056+ return(NULL);
2057+ if ((end=strcont(name," \t")))
2058+ {
2059+ len=(uint32_t) (end - name);
2060+ while (isspace(*end))
2061+ end++;
2062+ if (!*end)
2063+ end=0; // no arguments to function
2064+ }
2065+ else
2066+ len=(uint32_t) strlen(name);
2067+ }
2068+
2069+ for (uint32_t i= 0; commands[i].getName(); i++)
2070+ {
2071+ if (commands[i].func &&
2072+ ((name && !strncmp(name, commands[i].getName(), len)
2073+ && !commands[i].getName()[len] && (!end || (end && commands[i].getTakesParams()))) || (!name && commands[i].getCmdChar() == cmd_char)))
2074+ {
2075+ return(&commands[i]);
2076+ }
2077+ }
2078+ return(NULL);
2079+}
2080+
2081+
2082+static bool add_line(string *buffer, char *line, char *in_string,
2083+ bool *ml_comment)
2084+{
2085+ unsigned char inchar;
2086+ char *pos, *out;
2087+ Commands *com;
2088+ bool need_space= 0;
2089+ bool ss_comment= 0;
2090+
2091+
2092+ if (!line[0] && (buffer->empty()))
2093+ return(0);
2094+ if (status.getAddToHistory() && line[0] && not_in_history(line))
2095+ add_history(line);
2096+ char *end_of_line=line+(uint32_t) strlen(line);
2097+
2098+ for (pos=out=line ; (inchar= (unsigned char) *pos) ; pos++)
2099+ {
2100+ if (!preserve_comments)
2101+ {
2102+ // Skip spaces at the beggining of a statement
2103+ if (isspace(inchar) && (out == line) &&
2104+ (buffer->empty()))
2105+ continue;
2106+ }
2107+
2108+ // Accept multi-byte characters as-is
2109+ if (not drizzled::utf8::is_single(*pos))
2110+ {
2111+ int length;
2112+ if ((length= drizzled::utf8::sequence_length(*pos)))
2113+ {
2114+ if (!*ml_comment || preserve_comments)
2115+ {
2116+ while (length--)
2117+ *out++ = *pos++;
2118+ pos--;
2119+ }
2120+ else
2121+ pos+= length - 1;
2122+ continue;
2123+ }
2124+ }
2125+ if (!*ml_comment && inchar == '\\' &&
2126+ !(*in_string && (drizzle_con_status(&con) & DRIZZLE_CON_STATUS_NO_BACKSLASH_ESCAPES)))
2127+ {
2128+ // Found possbile one character command like \c
2129+
2130+ if (!(inchar = (unsigned char) *++pos))
2131+ break; // readline adds one '\'
2132+ if (*in_string || inchar == 'N') // \N is short for NULL
2133+ { // Don't allow commands in string
2134+ *out++='\\';
2135+ *out++= (char) inchar;
2136+ continue;
2137+ }
2138+ if ((com=find_command(NULL,(char) inchar)))
2139+ {
2140+ // Flush previously accepted characters
2141+ if (out != line)
2142+ {
2143+ buffer->append(line, (out-line));
2144+ out= line;
2145+ }
2146+
2147+ if ((*com->func)(buffer,pos-1) > 0)
2148+ return(1); // Quit
2149+ if (com->getTakesParams())
2150+ {
2151+ if (ss_comment)
2152+ {
2153+ /*
2154+ If a client-side macro appears inside a server-side comment,
2155+ discard all characters in the comment after the macro (that is,
2156+ until the end of the comment rather than the next delimiter)
2157+ */
2158+ for (pos++; *pos && (*pos != '*' || *(pos + 1) != '/'); pos++)
2159+ ;
2160+ pos--;
2161+ }
2162+ else
2163+ {
2164+ for (pos++ ;
2165+ *pos && (*pos != *delimiter ||
2166+ strncmp(pos + 1, delimiter + 1,
2167+ strlen(delimiter + 1))) ; pos++)
2168+ ; // Remove parameters
2169+ if (!*pos)
2170+ pos--;
2171+ else
2172+ pos+= delimiter_length - 1; // Point at last delim char
2173+ }
2174+ }
2175+ }
2176+ else
2177+ {
2178+ string buff(_("Unknown command: "));
2179+ buff.push_back('\'');
2180+ buff.push_back(inchar);
2181+ buff.push_back('\'');
2182+ buff.push_back('.');
2183+ if (put_info(buff.c_str(),INFO_ERROR,0,0) > 0)
2184+ return(1);
2185+ *out++='\\';
2186+ *out++=(char) inchar;
2187+ continue;
2188+ }
2189+ }
2190+ else if (!*ml_comment && !*in_string &&
2191+ (end_of_line - pos) >= 10 &&
2192+ !strncmp(pos, "delimiter ", 10))
2193+ {
2194+ // Flush previously accepted characters
2195+ if (out != line)
2196+ {
2197+ buffer->append(line, (out - line));
2198+ out= line;
2199+ }
2200+
2201+ // Flush possible comments in the buffer
2202+ if (!buffer->empty())
2203+ {
2204+ if (com_go(buffer, 0) > 0) // < 0 is not fatal
2205+ return(1);
2206+ assert(buffer!=NULL);
2207+ buffer->clear();
2208+ }
2209+
2210+ /*
2211+ Delimiter wants the get rest of the given line as argument to
2212+ allow one to change ';' to ';;' and back
2213+ */
2214+ buffer->append(pos);
2215+ if (com_delimiter(buffer, pos) > 0)
2216+ return(1);
2217+
2218+ buffer->clear();
2219+ break;
2220+ }
2221+ else if (!*ml_comment && !*in_string && !strncmp(pos, delimiter,
2222+ strlen(delimiter)))
2223+ {
2224+ // Found a statement. Continue parsing after the delimiter
2225+ pos+= delimiter_length;
2226+
2227+ if (preserve_comments)
2228+ {
2229+ while (isspace(*pos))
2230+ *out++= *pos++;
2231+ }
2232+ // Flush previously accepted characters
2233+ if (out != line)
2234+ {
2235+ buffer->append(line, (out-line));
2236+ out= line;
2237+ }
2238+
2239+ if (preserve_comments && ((*pos == '#') ||
2240+ ((*pos == '-') &&
2241+ (pos[1] == '-') &&
2242+ isspace(pos[2]))))
2243+ {
2244+ // Add trailing single line comments to this statement
2245+ buffer->append(pos);
2246+ pos+= strlen(pos);
2247+ }
2248+
2249+ pos--;
2250+
2251+ if ((com= find_command(buffer->c_str(), 0)))
2252+ {
2253+
2254+ if ((*com->func)(buffer, buffer->c_str()) > 0)
2255+ return(1); // Quit
2256+ }
2257+ else
2258+ {
2259+ if (com_go(buffer, 0) > 0) // < 0 is not fatal
2260+ return(1);
2261+ }
2262+ buffer->clear();
2263+ }
2264+ else if (!*ml_comment
2265+ && (!*in_string
2266+ && (inchar == '#'
2267+ || (inchar == '-'
2268+ && pos[1] == '-'
2269+ && isspace(pos[2])))))
2270+ {
2271+ // Flush previously accepted characters
2272+ if (out != line)
2273+ {
2274+ buffer->append(line, (out - line));
2275+ out= line;
2276+ }
2277+
2278+ // comment to end of line
2279+ if (preserve_comments)
2280+ buffer->append(pos);
2281+
2282+ break;
2283+ }
2284+ else if (!*in_string && inchar == '/' && *(pos+1) == '*' &&
2285+ *(pos+2) != '!')
2286+ {
2287+ if (preserve_comments)
2288+ {
2289+ *out++= *pos++; // copy '/'
2290+ *out++= *pos; // copy '*'
2291+ }
2292+ else
2293+ pos++;
2294+ *ml_comment= 1;
2295+ if (out != line)
2296+ {
2297+ buffer->append(line, (out-line));
2298+ out=line;
2299+ }
2300+ }
2301+ else if (*ml_comment && !ss_comment && inchar == '*' && *(pos + 1) == '/')
2302+ {
2303+ if (preserve_comments)
2304+ {
2305+ *out++= *pos++; // copy '*'
2306+ *out++= *pos; // copy '/'
2307+ }
2308+ else
2309+ pos++;
2310+ *ml_comment= 0;
2311+ if (out != line)
2312+ {
2313+ buffer->append(line, (out - line));
2314+ out= line;
2315+ }
2316+ // Consumed a 2 chars or more, and will add 1 at most,
2317+ // so using the 'line' buffer to edit data in place is ok.
2318+ need_space= 1;
2319+ }
2320+ else
2321+ {
2322+ // Add found char to buffer
2323+ if (!*in_string && inchar == '/' && *(pos + 1) == '*' &&
2324+ *(pos + 2) == '!')
2325+ ss_comment= 1;
2326+ else if (!*in_string && ss_comment && inchar == '*' && *(pos + 1) == '/')
2327+ ss_comment= 0;
2328+ if (inchar == *in_string)
2329+ *in_string= 0;
2330+ else if (!*ml_comment && !*in_string &&
2331+ (inchar == '\'' || inchar == '"' || inchar == '`'))
2332+ *in_string= (char) inchar;
2333+ if (!*ml_comment || preserve_comments)
2334+ {
2335+ if (need_space && !isspace((char)inchar))
2336+ *out++= ' ';
2337+ need_space= 0;
2338+ *out++= (char) inchar;
2339+ }
2340+ }
2341+ }
2342+ if (out != line || (buffer->length() > 0))
2343+ {
2344+ *out++='\n';
2345+ uint32_t length=(uint32_t) (out-line);
2346+ if ((!*ml_comment || preserve_comments))
2347+ buffer->append(line, length);
2348+ }
2349+ return(0);
2350+}
2351+
2352+/*****************************************************************
2353+ Interface to Readline Completion
2354+******************************************************************/
2355+
2356+
2357+static char **mysql_completion (const char *text, int start, int end);
2358+extern "C" char *new_command_generator(const char *text, int);
2359+
2360+/*
2361+ Tell the GNU Readline library how to complete. We want to try to complete
2362+ on command names if this is the first word in the line, or on filenames
2363+ if not.
2364+*/
2365+static char *no_completion(const char *, int)
2366+{
2367+ /* No filename completion */
2368+ return 0;
2369+}
2370+
2371+
2372+/* glues pieces of history back together if in pieces */
2373+static void fix_history(string *final_command)
2374+{
2375+ int total_lines = 1;
2376+ const char *ptr = final_command->c_str();
2377+ char str_char = '\0'; /* Character if we are in a string or not */
2378+
2379+ /* Converted buffer */
2380+ string fixed_buffer;
2381+ fixed_buffer.reserve(512);
2382+
2383+ /* find out how many lines we have and remove newlines */
2384+ while (*ptr != '\0')
2385+ {
2386+ switch (*ptr) {
2387+ /* string character */
2388+ case '"':
2389+ case '\'':
2390+ case '`':
2391+ // open string
2392+ if (str_char == '\0')
2393+ str_char = *ptr;
2394+ else if (str_char == *ptr) /* close string */
2395+ str_char = '\0';
2396+ fixed_buffer.append(ptr, 1);
2397+ break;
2398+ case '\n':
2399+ /*
2400+ not in string, change to space
2401+ if in string, leave it alone
2402+ */
2403+ fixed_buffer.append((str_char == '\0') ? " " : "\n");
2404+ total_lines++;
2405+ break;
2406+ case '\\':
2407+ fixed_buffer.append("\\");
2408+ /* need to see if the backslash is escaping anything */
2409+ if (str_char)
2410+ {
2411+ ptr++;
2412+ /* special characters that need escaping */
2413+ if (*ptr == '\'' || *ptr == '"' || *ptr == '\\')
2414+ fixed_buffer.append(ptr, 1);
2415+ else
2416+ ptr--;
2417+ }
2418+ break;
2419+ default:
2420+ fixed_buffer.append(ptr, 1);
2421+ }
2422+ ptr++;
2423+ }
2424+ if (total_lines > 1)
2425+ add_history(fixed_buffer.c_str());
2426+}
2427+
2428+/*
2429+ returns 0 if line matches the previous history entry
2430+ returns 1 if the line doesn't match the previous history entry
2431+*/
2432+static int not_in_history(const char *line)
2433+{
2434+ HIST_ENTRY *oldhist = history_get(history_length);
2435+
2436+ if (oldhist == 0)
2437+ return 1;
2438+ if (strcmp(oldhist->line,line) == 0)
2439+ return 0;
2440+ return 1;
2441+}
2442+
2443+static void initialize_readline (char *name)
2444+{
2445+ /* Allow conditional parsing of the ~/.inputrc file. */
2446+ rl_readline_name= name;
2447+
2448+ /* Tell the completer that we want a crack first. */
2449+ rl_attempted_completion_function= (rl_completion_func_t*)&mysql_completion;
2450+ rl_completion_entry_function= (drizzle_compentry_func_t*)&no_completion;
2451+}
2452+
2453+
2454+/*
2455+ Attempt to complete on the contents of TEXT. START and END show the
2456+ region of TEXT that contains the word to complete. We can use the
2457+ entire line in case we want to do some simple parsing. Return the
2458+ array of matches, or NULL if there aren't any.
2459+*/
2460+char **mysql_completion (const char *text, int, int)
2461+{
2462+ if (!status.getBatch() && !quick)
2463+ return rl_completion_matches(text, new_command_generator);
2464+ else
2465+ return (char**) 0;
2466+}
2467+
2468+inline string lower_string(const string &from_string)
2469+{
2470+ string to_string= from_string;
2471+ transform(to_string.begin(), to_string.end(),
2472+ to_string.begin(), ::tolower);
2473+ return to_string;
2474+}
2475+inline string lower_string(const char * from_string)
2476+{
2477+ string to_string= from_string;
2478+ return lower_string(to_string);
2479+}
2480+
2481+template <class T>
2482+class CompletionMatch :
2483+ public unary_function<const string&, bool>
2484+{
2485+ string match_text;
2486+ T match_func;
2487+public:
2488+ CompletionMatch(string text) : match_text(text) {}
2489+ inline bool operator() (const pair<string,string> &match_against) const
2490+ {
2491+ string sub_match=
2492+ lower_string(match_against.first.substr(0,match_text.size()));
2493+ return match_func(sub_match,match_text);
2494+ }
2495+};
2496+
2497+
2498+
2499+extern "C"
2500+char *new_command_generator(const char *text, int state)
2501+{
2502+
2503+ if (!state)
2504+ {
2505+ completion_string= lower_string(text);
2506+ if (completion_string.size() == 0)
2507+ {
2508+ completion_iter= completion_map.begin();
2509+ completion_end= completion_map.end();
2510+ }
2511+ else
2512+ {
2513+ completion_iter= find_if(completion_map.begin(), completion_map.end(),
2514+ CompletionMatch<equal_to<string> >(completion_string));
2515+ completion_end= find_if(completion_iter, completion_map.end(),
2516+ CompletionMatch<not_equal_to<string> >(completion_string));
2517+ }
2518+ }
2519+ if (completion_iter == completion_end || (size_t)state > completion_map.size())
2520+ return NULL;
2521+ char *result= (char *)malloc((*completion_iter).second.size()+1);
2522+ strcpy(result, (*completion_iter).second.c_str());
2523+ completion_iter++;
2524+ return result;
2525+}
2526+
2527+/* Build up the completion hash */
2528+
2529+static void build_completion_hash(bool rehash, bool write_info)
2530+{
2531+ Commands *cmd=commands;
2532+ drizzle_return_t ret;
2533+ drizzle_result_st databases,tables,fields;
2534+ drizzle_row_t database_row,table_row;
2535+ drizzle_column_st *sql_field;
2536+ string tmp_str, tmp_str_lower;
2537+
2538+ if (status.getBatch() || quick || current_db.empty())
2539+ return; // We don't need completion in batches
2540+ if (!rehash)
2541+ return;
2542+
2543+ completion_map.clear();
2544+
2545+ /* hash this file's known subset of SQL commands */
2546+ while (cmd->getName()) {
2547+ tmp_str= cmd->getName();
2548+ tmp_str_lower= lower_string(tmp_str);
2549+ completion_map[tmp_str_lower]= tmp_str;
2550+ cmd++;
2551+ }
2552+
2553+ /* hash Drizzle functions (to be implemented) */
2554+
2555+ /* hash all database names */
2556+ if (drizzle_query_str(&con, &databases, "show databases", &ret) != NULL)
2557+ {
2558+ if (ret == DRIZZLE_RETURN_OK)
2559+ {
2560+ if (drizzle_result_buffer(&databases) != DRIZZLE_RETURN_OK)
2561+ put_info(drizzle_error(&drizzle),INFO_INFO,0,0);
2562+ else
2563+ {
2564+ while ((database_row=drizzle_row_next(&databases)))
2565+ {
2566+ tmp_str= database_row[0];
2567+ tmp_str_lower= lower_string(tmp_str);
2568+ completion_map[tmp_str_lower]= tmp_str;
2569+ }
2570+ }
2571+ }
2572+
2573+ drizzle_result_free(&databases);
2574+ }
2575+
2576+ /* hash all table names */
2577+ if (drizzle_query_str(&con, &tables, "show tables", &ret) != NULL)
2578+ {
2579+ if (ret != DRIZZLE_RETURN_OK)
2580+ {
2581+ drizzle_result_free(&tables);
2582+ return;
2583+ }
2584+
2585+ if (drizzle_result_buffer(&tables) != DRIZZLE_RETURN_OK)
2586+ put_info(drizzle_error(&drizzle),INFO_INFO,0,0);
2587+ else
2588+ {
2589+ if (drizzle_result_row_count(&tables) > 0 && !opt_silent && write_info)
2590+ {
2591+ tee_fprintf(stdout,
2592+ _("Reading table information for completion of "
2593+ "table and column names\n"
2594+ "You can turn off this feature to get a quicker "
2595+ "startup with -A\n\n"));
2596+ }
2597+ while ((table_row=drizzle_row_next(&tables)))
2598+ {
2599+ tmp_str= table_row[0];
2600+ tmp_str_lower= lower_string(tmp_str);
2601+ completion_map[tmp_str_lower]= tmp_str;
2602+ }
2603+ }
2604+ }
2605+ else
2606+ return;
2607+
2608+ /* hash all field names, both with the table prefix and without it */
2609+ if (drizzle_result_row_count(&tables) == 0)
2610+ {
2611+ drizzle_result_free(&tables);
2612+ return;
2613+ }
2614+
2615+ drizzle_row_seek(&tables, 0);
2616+
2617+ while ((table_row=drizzle_row_next(&tables)))
2618+ {
2619+ string query;
2620+
2621+ query.append("show fields in '");
2622+ query.append(table_row[0]);
2623+ query.append("'");
2624+
2625+ if (drizzle_query(&con, &fields, query.c_str(), query.length(),
2626+ &ret) != NULL)
2627+ {
2628+ if (ret == DRIZZLE_RETURN_OK &&
2629+ drizzle_result_buffer(&fields) == DRIZZLE_RETURN_OK)
2630+ {
2631+ while ((sql_field=drizzle_column_next(&fields)))
2632+ {
2633+ tmp_str=table_row[0];
2634+ tmp_str.append(".");
2635+ tmp_str.append(drizzle_column_name(sql_field));
2636+ tmp_str_lower= lower_string(tmp_str);
2637+ completion_map[tmp_str_lower]= tmp_str;
2638+
2639+ tmp_str=drizzle_column_name(sql_field);
2640+ tmp_str_lower= lower_string(tmp_str);
2641+ completion_map[tmp_str_lower]= tmp_str;
2642+ }
2643+ }
2644+ drizzle_result_free(&fields);
2645+ }
2646+ }
2647+ drizzle_result_free(&tables);
2648+ completion_iter= completion_map.begin();
2649+}
2650+
2651+/* for gnu readline */
2652+
2653+
2654+static int reconnect(void)
2655+{
2656+ if (opt_reconnect)
2657+ {
2658+ put_info(_("No connection. Trying to reconnect..."),INFO_INFO,0,0);
2659+ (void) com_connect((string *)0, 0);
2660+ if (opt_rehash && connected)
2661+ com_rehash(NULL, NULL);
2662+ }
2663+ if (! connected)
2664+ return put_info(_("Can't connect to the server\n"),INFO_ERROR,0,0);
2665+ return 0;
2666+}
2667+
2668+static void get_current_db(void)
2669+{
2670+ drizzle_return_t ret;
2671+ drizzle_result_st res;
2672+
2673+ current_db.erase();
2674+ current_db= "";
2675+ /* In case of error below current_db will be NULL */
2676+ if (drizzle_query_str(&con, &res, "SELECT DATABASE()", &ret) != NULL)
2677+ {
2678+ if (ret == DRIZZLE_RETURN_OK &&
2679+ drizzle_result_buffer(&res) == DRIZZLE_RETURN_OK)
2680+ {
2681+ drizzle_row_t row= drizzle_row_next(&res);
2682+ if (row[0])
2683+ current_db.assign(row[0]);
2684+ drizzle_result_free(&res);
2685+ }
2686+ }
2687+}
2688+
2689+/***************************************************************************
2690+ The different commands
2691+***************************************************************************/
2692+
2693+int drizzleclient_real_query_for_lazy(const char *buf, size_t length,
2694+ drizzle_result_st *result,
2695+ uint32_t *error_code)
2696+{
2697+ drizzle_return_t ret;
2698+
2699+ for (uint32_t retry=0;; retry++)
2700+ {
2701+ int error;
2702+ if (drizzle_query(&con,result,buf,length,&ret) != NULL &&
2703+ ret == DRIZZLE_RETURN_OK)
2704+ {
2705+ return 0;
2706+ }
2707+ error= put_error(&con, result);
2708+
2709+ if (ret == DRIZZLE_RETURN_ERROR_CODE)
2710+ {
2711+ *error_code= drizzle_result_error_code(result);
2712+ drizzle_result_free(result);
2713+ }
2714+
2715+ if (ret != DRIZZLE_RETURN_SERVER_GONE || retry > 1 ||
2716+ !opt_reconnect)
2717+ {
2718+ return error;
2719+ }
2720+
2721+ if (reconnect())
2722+ return error;
2723+ }
2724+}
2725+
2726+int drizzleclient_store_result_for_lazy(drizzle_result_st *result)
2727+{
2728+ if (drizzle_result_buffer(result) == DRIZZLE_RETURN_OK)
2729+ return 0;
2730+
2731+ if (drizzle_con_error(&con)[0])
2732+ {
2733+ int ret= put_error(&con, result);
2734+ drizzle_result_free(result);
2735+ return ret;
2736+ }
2737+ return 0;
2738+}
2739+
2740+static int
2741+com_help(string *buffer, const char *)
2742+{
2743+ register int i, j;
2744+ char buff[32], *end;
2745+ std::vector<char> output_buff;
2746+ output_buff.resize(512);
2747+
2748+ put_info(_("List of all Drizzle commands:"), INFO_INFO,0,0);
2749+ if (!named_cmds)
2750+ {
2751+ snprintf(&output_buff[0], output_buff.size(),
2752+ _("Note that all text commands must be first on line and end with '%s' or \\g"),
2753+ delimiter);
2754+ put_info(&output_buff[0], INFO_INFO, 0, 0);
2755+ }
2756+ for (i = 0; commands[i].getName(); i++)
2757+ {
2758+ end= strcpy(buff, commands[i].getName());
2759+ end+= strlen(commands[i].getName());
2760+ for (j= (int)strlen(commands[i].getName()); j < 10; j++)
2761+ end= strcpy(end, " ")+1;
2762+ if (commands[i].func)
2763+ tee_fprintf(stdout, "%s(\\%c) %s\n", buff,
2764+ commands[i].getCmdChar(), _(commands[i].getDoc()));
2765+ }
2766+ tee_fprintf(stdout, "\n");
2767+ buffer->clear();
2768+ return 0;
2769+}
2770+
2771+
2772+static int
2773+com_clear(string *buffer, const char *)
2774+{
2775+ if (status.getAddToHistory())
2776+ fix_history(buffer);
2777+ buffer->clear();
2778+ return 0;
2779+}
2780+
2781+
2782+/*
2783+ Execute command
2784+ Returns: 0 if ok
2785+ -1 if not fatal error
2786+ 1 if fatal error
2787+*/
2788+static int
2789+com_go(string *buffer, const char *)
2790+{
2791+ char buff[200]; /* about 110 chars used so far */
2792+ char time_buff[52+3+1]; /* time max + space&parens + NUL */
2793+ drizzle_result_st result;
2794+ drizzle_return_t ret;
2795+ uint32_t timer, warnings= 0;
2796+ uint32_t error= 0;
2797+ uint32_t error_code= 0;
2798+ int err= 0;
2799+
2800+ interrupted_query= 0;
2801+
2802+ /* Remove garbage for nicer messages */
2803+ remove_cntrl(buffer);
2804+
2805+ if (buffer->empty())
2806+ {
2807+ // Ignore empty quries
2808+ if (status.getBatch())
2809+ return 0;
2810+ return put_info(_("No query specified\n"),INFO_ERROR,0,0);
2811+
2812+ }
2813+ if (!connected && reconnect())
2814+ {
2815+ // Remove query on error
2816+ buffer->clear();
2817+ return opt_reconnect ? -1 : 1; // Fatal error
2818+ }
2819+ if (verbose)
2820+ (void) com_print(buffer, 0);
2821+
2822+ if (skip_updates &&
2823+ ((buffer->length() < 4) || (buffer->find( "SET ") != 0)))
2824+ {
2825+ (void) put_info(_("Ignoring query to other database"),INFO_INFO,0,0);
2826+ return 0;
2827+ }
2828+
2829+ timer=start_timer();
2830+ executing_query= 1;
2831+ error= drizzleclient_real_query_for_lazy(buffer->c_str(),buffer->length(),&result, &error_code);
2832+
2833+ if (status.getAddToHistory())
2834+ {
2835+ buffer->append(vertical ? "\\G" : delimiter);
2836+ /* Append final command onto history */
2837+ fix_history(buffer);
2838+ }
2839+
2840+ buffer->clear();
2841+
2842+ if (error)
2843+ goto end;
2844+
2845+ do
2846+ {
2847+ char *pos;
2848+
2849+ if (quick)
2850+ {
2851+ if (drizzle_column_buffer(&result) != DRIZZLE_RETURN_OK)
2852+ {
2853+ error= put_error(&con, &result);
2854+ goto end;
2855+ }
2856+ }
2857+ else
2858+ {
2859+ error= drizzleclient_store_result_for_lazy(&result);
2860+ if (error)
2861+ goto end;
2862+ }
2863+
2864+ if (verbose >= 3 || !opt_silent)
2865+ drizzle_end_timer(timer,time_buff);
2866+ else
2867+ time_buff[0]= '\0';
2868+
2869+ /* Every branch must truncate buff . */
2870+ if (drizzle_result_column_count(&result) > 0)
2871+ {
2872+ if (!quick && drizzle_result_row_count(&result) == 0 &&
2873+ !column_types_flag)
2874+ {
2875+ strcpy(buff, _("Empty set"));
2876+ }
2877+ else
2878+ {
2879+ init_pager();
2880+ if (vertical || (auto_vertical_output &&
2881+ (terminal_width < get_result_width(&result))))
2882+ print_table_data_vertically(&result);
2883+ else if (opt_silent && verbose <= 2 && !output_tables)
2884+ print_tab_data(&result);
2885+ else
2886+ print_table_data(&result);
2887+ sprintf(buff,
2888+ ngettext("%ld row in set","%ld rows in set",
2889+ (long) drizzle_result_row_count(&result)),
2890+ (long) drizzle_result_row_count(&result));
2891+ end_pager();
2892+ if (drizzle_result_error_code(&result))
2893+ error= put_error(&con, &result);
2894+ }
2895+ }
2896+ else if (drizzle_result_affected_rows(&result) == ~(uint64_t) 0)
2897+ strcpy(buff,_("Query OK"));
2898+ else
2899+ sprintf(buff, ngettext("Query OK, %ld row affected",
2900+ "Query OK, %ld rows affected",
2901+ (long) drizzle_result_affected_rows(&result)),
2902+ (long) drizzle_result_affected_rows(&result));
2903+
2904+ pos= strchr(buff, '\0');
2905+ if ((warnings= drizzle_result_warning_count(&result)))
2906+ {
2907+ *pos++= ',';
2908+ *pos++= ' ';
2909+ char warnings_buff[20];
2910+ memset(warnings_buff,0,20);
2911+ sprintf(warnings_buff, "%d", warnings);
2912+ strcpy(pos, warnings_buff);
2913+ pos+= strlen(warnings_buff);
2914+ pos= strcpy(pos, " warning")+8;
2915+ if (warnings != 1)
2916+ *pos++= 's';
2917+ }
2918+ strcpy(pos, time_buff);
2919+ put_info(buff,INFO_RESULT,0,0);
2920+ if (strcmp(drizzle_result_info(&result), ""))
2921+ put_info(drizzle_result_info(&result),INFO_RESULT,0,0);
2922+ put_info("",INFO_RESULT,0,0); // Empty row
2923+
2924+ if (unbuffered)
2925+ fflush(stdout);
2926+ drizzle_result_free(&result);
2927+
2928+ if (drizzle_con_status(&con) & DRIZZLE_CON_STATUS_MORE_RESULTS_EXISTS)
2929+ {
2930+ if (drizzle_result_read(&con, &result, &ret) == NULL ||
2931+ ret != DRIZZLE_RETURN_OK)
2932+ {
2933+ if (ret == DRIZZLE_RETURN_ERROR_CODE)
2934+ {
2935+ error_code= drizzle_result_error_code(&result);
2936+ drizzle_result_free(&result);
2937+ }
2938+
2939+ error= put_error(&con, NULL);
2940+ goto end;
2941+ }
2942+ }
2943+
2944+ } while (drizzle_con_status(&con) & DRIZZLE_CON_STATUS_MORE_RESULTS_EXISTS);
2945+ if (err >= 1)
2946+ error= put_error(&con, NULL);
2947+
2948+end:
2949+
2950+ /* Show warnings if any or error occured */
2951+ if (show_warnings == 1 && (warnings >= 1 || error))
2952+ print_warnings(error_code);
2953+
2954+ if (!error && !status.getBatch() &&
2955+ drizzle_con_status(&con) & DRIZZLE_CON_STATUS_DB_DROPPED)
2956+ {
2957+ get_current_db();
2958+ }
2959+
2960+ executing_query= 0;
2961+ return error; /* New command follows */
2962+}
2963+
2964+
2965+static void init_pager()
2966+{
2967+ if (!opt_nopager)
2968+ {
2969+ if (!(PAGER= popen(pager.c_str(), "w")))
2970+ {
2971+ tee_fprintf(stdout,_( "popen() failed! defaulting PAGER to stdout!\n"));
2972+ PAGER= stdout;
2973+ }
2974+ }
2975+ else
2976+ PAGER= stdout;
2977+}
2978+
2979+static void end_pager()
2980+{
2981+ if (!opt_nopager)
2982+ pclose(PAGER);
2983+}
2984+
2985+
2986+static void init_tee(const char *file_name)
2987+{
2988+ FILE* new_outfile;
2989+ if (opt_outfile)
2990+ end_tee();
2991+ if (!(new_outfile= fopen(file_name, "a")))
2992+ {
2993+ tee_fprintf(stdout, _("Error logging to file '%s'\n"), file_name);
2994+ return;
2995+ }
2996+ OUTFILE = new_outfile;
2997+ outfile.assign(file_name);
2998+ tee_fprintf(stdout, _("Logging to file '%s'\n"), file_name);
2999+ opt_outfile= 1;
3000+
3001+ return;
3002+}
3003+
3004+
3005+static void end_tee()
3006+{
3007+ fclose(OUTFILE);
3008+ OUTFILE= 0;
3009+ opt_outfile= 0;
3010+ return;
3011+}
3012+
3013+
3014+static int
3015+com_ego(string *buffer,const char *line)
3016+{
3017+ int result;
3018+ bool oldvertical=vertical;
3019+ vertical=1;
3020+ result=com_go(buffer,line);
3021+ vertical=oldvertical;
3022+ return result;
3023+}
3024+
3025+
3026+static const char *fieldtype2str(drizzle_column_type_t type)
3027+{
3028+ switch (type) {
3029+ case DRIZZLE_COLUMN_TYPE_BLOB: return "BLOB";
3030+ case DRIZZLE_COLUMN_TYPE_DATE: return "DATE";
3031+ case DRIZZLE_COLUMN_TYPE_DATETIME: return "DATETIME";
3032+ case DRIZZLE_COLUMN_TYPE_NEWDECIMAL: return "DECIMAL";
3033+ case DRIZZLE_COLUMN_TYPE_DOUBLE: return "DOUBLE";
3034+ case DRIZZLE_COLUMN_TYPE_ENUM: return "ENUM";
3035+ case DRIZZLE_COLUMN_TYPE_LONG: return "LONG";
3036+ case DRIZZLE_COLUMN_TYPE_LONGLONG: return "LONGLONG";
3037+ case DRIZZLE_COLUMN_TYPE_NULL: return "NULL";
3038+ case DRIZZLE_COLUMN_TYPE_TIMESTAMP: return "TIMESTAMP";
3039+ default: return "?-unknown-?";
3040+ }
3041+}
3042+
3043+static char *fieldflags2str(uint32_t f) {
3044+ static char buf[1024];
3045+ char *s=buf;
3046+ *s=0;
3047+#define ff2s_check_flag(X) \
3048+ if (f & DRIZZLE_COLUMN_FLAGS_ ## X) { s=strcpy(s, # X " ")+strlen(# X " "); \
3049+ f &= ~ DRIZZLE_COLUMN_FLAGS_ ## X; }
3050+ ff2s_check_flag(NOT_NULL);
3051+ ff2s_check_flag(PRI_KEY);
3052+ ff2s_check_flag(UNIQUE_KEY);
3053+ ff2s_check_flag(MULTIPLE_KEY);
3054+ ff2s_check_flag(BLOB);
3055+ ff2s_check_flag(UNSIGNED);
3056+ ff2s_check_flag(BINARY);
3057+ ff2s_check_flag(ENUM);
3058+ ff2s_check_flag(AUTO_INCREMENT);
3059+ ff2s_check_flag(TIMESTAMP);
3060+ ff2s_check_flag(SET);
3061+ ff2s_check_flag(NO_DEFAULT_VALUE);
3062+ ff2s_check_flag(NUM);
3063+ ff2s_check_flag(PART_KEY);
3064+ ff2s_check_flag(GROUP);
3065+ ff2s_check_flag(UNIQUE);
3066+ ff2s_check_flag(BINCMP);
3067+ ff2s_check_flag(ON_UPDATE_NOW);
3068+#undef ff2s_check_flag
3069+ if (f)
3070+ sprintf(s, " unknows=0x%04x", f);
3071+ return buf;
3072+}
3073+
3074+static void
3075+print_field_types(drizzle_result_st *result)
3076+{
3077+ drizzle_column_st *field;
3078+ uint32_t i=0;
3079+
3080+ while ((field = drizzle_column_next(result)))
3081+ {
3082+ tee_fprintf(PAGER, _("Field %3u: `%s`\n"
3083+ "Catalog: `%s`\n"
3084+ "Database: `%s`\n"
3085+ "Table: `%s`\n"
3086+ "Org_table: `%s`\n"
3087+ "Type: UTF-8\n"
3088+ "Collation: %s (%u)\n"
3089+ "Length: %lu\n"
3090+ "Max_length: %lu\n"
3091+ "Decimals: %u\n"
3092+ "Flags: %s\n\n"),
3093+ ++i,
3094+ drizzle_column_name(field), drizzle_column_catalog(field),
3095+ drizzle_column_db(field), drizzle_column_table(field),
3096+ drizzle_column_orig_table(field),
3097+ fieldtype2str(drizzle_column_type(field)),
3098+ drizzle_column_charset(field), drizzle_column_size(field),
3099+ drizzle_column_max_size(field), drizzle_column_decimals(field),
3100+ fieldflags2str(drizzle_column_flags(field)));
3101+ }
3102+ tee_puts("", PAGER);
3103+}
3104+
3105+static void
3106+print_table_data(drizzle_result_st *result)
3107+{
3108+ drizzle_row_t cur;
3109+ drizzle_return_t ret;
3110+ drizzle_column_st *field;
3111+ std::vector<bool> num_flag;
3112+ string separator;
3113+
3114+ separator.reserve(256);
3115+
3116+ num_flag.resize(drizzle_result_column_count(result));
3117+ if (column_types_flag)
3118+ {
3119+ print_field_types(result);
3120+ if (!drizzle_result_row_count(result))
3121+ return;
3122+ drizzle_column_seek(result,0);
3123+ }
3124+ separator.append("+");
3125+ while ((field = drizzle_column_next(result)))
3126+ {
3127+ uint32_t x, length= 0;
3128+
3129+ if (column_names)
3130+ {
3131+ uint32_t name_length= strlen(drizzle_column_name(field));
3132+
3133+ /* Check if the max_byte value is really the maximum in terms
3134+ of visual length since multibyte characters can affect the
3135+ length of the separator. */
3136+ length= drizzled::utf8::char_length(drizzle_column_name(field));
3137+
3138+ if (name_length == drizzle_column_max_size(field))
3139+ {
3140+ if (length < drizzle_column_max_size(field))
3141+ drizzle_column_set_max_size(field, length);
3142+ }
3143+ else
3144+ {
3145+ length= name_length;
3146+ }
3147+ }
3148+
3149+ if (quick)
3150+ length=max(length,drizzle_column_size(field));
3151+ else
3152+ length=max(length,(uint32_t)drizzle_column_max_size(field));
3153+ if (length < 4 &&
3154+ !(drizzle_column_flags(field) & DRIZZLE_COLUMN_FLAGS_NOT_NULL))
3155+ {
3156+ // Room for "NULL"
3157+ length=4;
3158+ }
3159+ drizzle_column_set_max_size(field, length);
3160+
3161+ for (x=0; x< (length+2); x++)
3162+ separator.append("-");
3163+ separator.append("+");
3164+ }
3165+
3166+ tee_puts((char*) separator.c_str(), PAGER);
3167+ if (column_names)
3168+ {
3169+ drizzle_column_seek(result,0);
3170+ (void) tee_fputs("|", PAGER);
3171+ for (uint32_t off=0; (field = drizzle_column_next(result)) ; off++)
3172+ {
3173+ uint32_t name_length= (uint32_t) strlen(drizzle_column_name(field));
3174+ uint32_t numcells= drizzled::utf8::char_length(drizzle_column_name(field));
3175+ uint32_t display_length= drizzle_column_max_size(field) + name_length -
3176+ numcells;
3177+ tee_fprintf(PAGER, " %-*s |",(int) min(display_length,
3178+ MAX_COLUMN_LENGTH),
3179+ drizzle_column_name(field));
3180+ num_flag[off]= ((drizzle_column_type(field) <= DRIZZLE_COLUMN_TYPE_LONGLONG) ||
3181+ (drizzle_column_type(field) == DRIZZLE_COLUMN_TYPE_NEWDECIMAL));
3182+ }
3183+ (void) tee_fputs("\n", PAGER);
3184+ tee_puts((char*) separator.c_str(), PAGER);
3185+ }
3186+
3187+ while (1)
3188+ {
3189+ if (quick)
3190+ {
3191+ cur= drizzle_row_buffer(result, &ret);
3192+ if (ret != DRIZZLE_RETURN_OK)
3193+ {
3194+ (void)put_error(&con, result);
3195+ break;
3196+ }
3197+ }
3198+ else
3199+ cur= drizzle_row_next(result);
3200+
3201+ if (cur == NULL || interrupted_query)
3202+ break;
3203+
3204+ size_t *lengths= drizzle_row_field_sizes(result);
3205+ (void) tee_fputs("| ", PAGER);
3206+ drizzle_column_seek(result, 0);
3207+ for (uint32_t off= 0; off < drizzle_result_column_count(result); off++)
3208+ {
3209+ const char *buffer;
3210+ uint32_t data_length;
3211+ uint32_t field_max_length;
3212+ uint32_t visible_length;
3213+ uint32_t extra_padding;
3214+
3215+ if (cur[off] == NULL)
3216+ {
3217+ buffer= "NULL";
3218+ data_length= 4;
3219+ }
3220+ else
3221+ {
3222+ buffer= cur[off];
3223+ data_length= (uint32_t) lengths[off];
3224+ }
3225+
3226+ field= drizzle_column_next(result);
3227+ field_max_length= drizzle_column_max_size(field);
3228+
3229+ /*
3230+ How many text cells on the screen will this string span? If it contains
3231+ multibyte characters, then the number of characters we occupy on screen
3232+ will be fewer than the number of bytes we occupy in memory.
3233+
3234+ We need to find how much screen real-estate we will occupy to know how
3235+ many extra padding-characters we should send with the printing function.
3236+ */
3237+ visible_length= drizzled::utf8::char_length(buffer);
3238+ extra_padding= data_length - visible_length;
3239+
3240+ if (field_max_length > MAX_COLUMN_LENGTH)
3241+ tee_print_sized_data(buffer, data_length, MAX_COLUMN_LENGTH+extra_padding, false);
3242+ else
3243+ {
3244+ if (num_flag[off] != 0) /* if it is numeric, we right-justify it */
3245+ tee_print_sized_data(buffer, data_length, field_max_length+extra_padding, true);
3246+ else
3247+ tee_print_sized_data(buffer, data_length,
3248+ field_max_length+extra_padding, false);
3249+ }
3250+ tee_fputs(" | ", PAGER);
3251+ }
3252+ (void) tee_fputs("\n", PAGER);
3253+ if (quick)
3254+ drizzle_row_free(result, cur);
3255+ }
3256+ tee_puts(separator.c_str(), PAGER);
3257+}
3258+
3259+/**
3260+ Return the length of a field after it would be rendered into text.
3261+
3262+ This doesn't know or care about multibyte characters. Assume we're
3263+ using such a charset. We can't know that all of the upcoming rows
3264+ for this column will have bytes that each render into some fraction
3265+ of a character. It's at least possible that a row has bytes that
3266+ all render into one character each, and so the maximum length is
3267+ still the number of bytes. (Assumption 1: This can't be better
3268+ because we can never know the number of characters that the DB is
3269+ going to send -- only the number of bytes. 2: Chars <= Bytes.)
3270+
3271+ @param field Pointer to a field to be inspected
3272+
3273+ @returns number of character positions to be used, at most
3274+*/
3275+static int get_field_disp_length(drizzle_column_st *field)
3276+{
3277+ uint32_t length= column_names ? strlen(drizzle_column_name(field)) : 0;
3278+
3279+ if (quick)
3280+ length= max(length, drizzle_column_size(field));
3281+ else
3282+ length= max(length, (uint32_t)drizzle_column_max_size(field));
3283+
3284+ if (length < 4 &&
3285+ !(drizzle_column_flags(field) & DRIZZLE_COLUMN_FLAGS_NOT_NULL))
3286+ {
3287+ length= 4; /* Room for "NULL" */
3288+ }
3289+
3290+ return length;
3291+}
3292+
3293+/**
3294+ For a new result, return the max number of characters that any
3295+ upcoming row may return.
3296+
3297+ @param result Pointer to the result to judge
3298+
3299+ @returns The max number of characters in any row of this result
3300+*/
3301+static int get_result_width(drizzle_result_st *result)
3302+{
3303+ unsigned int len= 0;
3304+ drizzle_column_st *field;
3305+ uint16_t offset;
3306+
3307+ offset= drizzle_column_current(result);
3308+ assert(offset == 0);
3309+
3310+ while ((field= drizzle_column_next(result)) != NULL)
3311+ len+= get_field_disp_length(field) + 3; /* plus bar, space, & final space */
3312+
3313+ (void) drizzle_column_seek(result, offset);
3314+
3315+ return len + 1; /* plus final bar. */
3316+}
3317+
3318+static void
3319+tee_print_sized_data(const char *data, unsigned int data_length, unsigned int total_bytes_to_send, bool right_justified)
3320+{
3321+ /*
3322+ For '\0's print ASCII spaces instead, as '\0' is eaten by (at
3323+ least my) console driver, and that messes up the pretty table
3324+ grid. (The \0 is also the reason we can't use fprintf() .)
3325+ */
3326+ unsigned int i;
3327+ const char *p;
3328+
3329+ if (right_justified)
3330+ for (i= data_length; i < total_bytes_to_send; i++)
3331+ tee_putc((int)' ', PAGER);
3332+
3333+ for (i= 0, p= data; i < data_length; i+= 1, p+= 1)
3334+ {
3335+ if (*p == '\0')
3336+ tee_putc((int)' ', PAGER);
3337+ else
3338+ tee_putc((int)*p, PAGER);
3339+ }
3340+
3341+ if (! right_justified)
3342+ for (i= data_length; i < total_bytes_to_send; i++)
3343+ tee_putc((int)' ', PAGER);
3344+}
3345+
3346+
3347+
3348+static void
3349+print_table_data_vertically(drizzle_result_st *result)
3350+{
3351+ drizzle_row_t cur;
3352+ drizzle_return_t ret;
3353+ uint32_t max_length=0;
3354+ drizzle_column_st *field;
3355+
3356+ while ((field = drizzle_column_next(result)))
3357+ {
3358+ uint32_t length= strlen(drizzle_column_name(field));
3359+ if (length > max_length)
3360+ max_length= length;
3361+ drizzle_column_set_max_size(field, length);
3362+ }
3363+
3364+ for (uint32_t row_count=1;; row_count++)
3365+ {
3366+ if (quick)
3367+ {
3368+ cur= drizzle_row_buffer(result, &ret);
3369+ if (ret != DRIZZLE_RETURN_OK)
3370+ {
3371+ (void)put_error(&con, result);
3372+ break;
3373+ }
3374+ }
3375+ else
3376+ cur= drizzle_row_next(result);
3377+
3378+ if (cur == NULL || interrupted_query)
3379+ break;
3380+ drizzle_column_seek(result,0);
3381+ tee_fprintf(PAGER,
3382+ "*************************** %d. row ***************************\n", row_count);
3383+ for (uint32_t off=0; off < drizzle_result_column_count(result); off++)
3384+ {
3385+ field= drizzle_column_next(result);
3386+ tee_fprintf(PAGER, "%*s: ",(int) max_length,drizzle_column_name(field));
3387+ tee_fprintf(PAGER, "%s\n",cur[off] ? (char*) cur[off] : "NULL");
3388+ }
3389+ if (quick)
3390+ drizzle_row_free(result, cur);
3391+ }
3392+}
3393+
3394+
3395+/* print_warnings should be called right after executing a statement */
3396+
3397+static void print_warnings(uint32_t error_code)
3398+{
3399+ const char *query;
3400+ drizzle_result_st result;
3401+ drizzle_row_t cur;
3402+ uint64_t num_rows;
3403+ uint32_t new_code= 0;
3404+ FILE *out;
3405+
3406+ /* Get the warnings */
3407+ query= "show warnings";
3408+ drizzleclient_real_query_for_lazy(query, strlen(query),&result,&new_code);
3409+ drizzleclient_store_result_for_lazy(&result);
3410+
3411+ /* Bail out when no warnings */
3412+ if (!(num_rows= drizzle_result_row_count(&result)))
3413+ goto end;
3414+
3415+ cur= drizzle_row_next(&result);
3416+
3417+ /*
3418+ Don't print a duplicate of the current error. It is possible for SHOW
3419+ WARNINGS to return multiple errors with the same code, but different
3420+ messages. To be safe, skip printing the duplicate only if it is the only
3421+ warning.
3422+ */
3423+ if (!cur || (num_rows == 1 &&
3424+ error_code == (uint32_t) strtoul(cur[1], NULL, 10)))
3425+ {
3426+ goto end;
3427+ }
3428+
3429+ /* Print the warnings */
3430+ if (status.getBatch())
3431+ {
3432+ out= stderr;
3433+ }
3434+ else
3435+ {
3436+ init_pager();
3437+ out= PAGER;
3438+ }
3439+ do
3440+ {
3441+ tee_fprintf(out, "%s (Code %s): %s\n", cur[0], cur[1], cur[2]);
3442+ } while ((cur= drizzle_row_next(&result)));
3443+
3444+ if (not status.getBatch())
3445+ end_pager();
3446+
3447+end:
3448+ drizzle_result_free(&result);
3449+}
3450+
3451+
3452+static void
3453+safe_put_field(const char *pos,uint32_t length)
3454+{
3455+ if (!pos)
3456+ tee_fputs("NULL", PAGER);
3457+ else
3458+ {
3459+ if (opt_raw_data)
3460+ tee_fputs(pos, PAGER);
3461+ else for (const char *end=pos+length ; pos != end ; pos++)
3462+ {
3463+ int l;
3464+ if ((l = drizzled::utf8::sequence_length(*pos)))
3465+ {
3466+ while (l--)
3467+ tee_putc(*pos++, PAGER);
3468+ pos--;
3469+ continue;
3470+ }
3471+ if (!*pos)
3472+ tee_fputs("\\0", PAGER); // This makes everything hard
3473+ else if (*pos == '\t')
3474+ tee_fputs("\\t", PAGER); // This would destroy tab format
3475+ else if (*pos == '\n')
3476+ tee_fputs("\\n", PAGER); // This too
3477+ else if (*pos == '\\')
3478+ tee_fputs("\\\\", PAGER);
3479+ else
3480+ tee_putc(*pos, PAGER);
3481+ }
3482+ }
3483+}
3484+
3485+
3486+static void
3487+print_tab_data(drizzle_result_st *result)
3488+{
3489+ drizzle_row_t cur;
3490+ drizzle_return_t ret;
3491+ drizzle_column_st *field;
3492+ size_t *lengths;
3493+
3494+ if (opt_silent < 2 && column_names)
3495+ {
3496+ int first=0;
3497+ while ((field = drizzle_column_next(result)))
3498+ {
3499+ if (first++)
3500+ (void) tee_fputs("\t", PAGER);
3501+ (void) tee_fputs(drizzle_column_name(field), PAGER);
3502+ }
3503+ (void) tee_fputs("\n", PAGER);
3504+ }
3505+ while (1)
3506+ {
3507+ if (quick)
3508+ {
3509+ cur= drizzle_row_buffer(result, &ret);
3510+ if (ret != DRIZZLE_RETURN_OK)
3511+ {
3512+ (void)put_error(&con, result);
3513+ break;
3514+ }
3515+ }
3516+ else
3517+ cur= drizzle_row_next(result);
3518+
3519+ if (cur == NULL)
3520+ break;
3521+
3522+ lengths= drizzle_row_field_sizes(result);
3523+ safe_put_field(cur[0],lengths[0]);
3524+ for (uint32_t off=1 ; off < drizzle_result_column_count(result); off++)
3525+ {
3526+ (void) tee_fputs("\t", PAGER);
3527+ safe_put_field(cur[off], lengths[off]);
3528+ }
3529+ (void) tee_fputs("\n", PAGER);
3530+ if (quick)
3531+ drizzle_row_free(result, cur);
3532+ }
3533+}
3534+
3535+static int
3536+com_tee(string *, const char *line )
3537+{
3538+ char file_name[FN_REFLEN], *end;
3539+ const char *param;
3540+
3541+ if (status.getBatch())
3542+ return 0;
3543+ while (isspace(*line))
3544+ line++;
3545+ if (!(param =strchr(line, ' '))) // if outfile wasn't given, use the default
3546+ {
3547+ if (outfile.empty())
3548+ {
3549+ printf(_("No previous outfile available, you must give a filename!\n"));
3550+ return 0;
3551+ }
3552+ else if (opt_outfile)
3553+ {
3554+ tee_fprintf(stdout, _("Currently logging to file '%s'\n"), outfile.c_str());
3555+ return 0;
3556+ }
3557+ else
3558+ param= outfile.c_str(); //resume using the old outfile
3559+ }
3560+
3561+ /* @TODO: Replace this with string methods */
3562+ /* eliminate the spaces before the parameters */
3563+ while (isspace(*param))
3564+ param++;
3565+ strncpy(file_name, param, sizeof(file_name) - 1);
3566+ end= file_name + strlen(file_name);
3567+ /* remove end space from command line */
3568+ while (end > file_name && (isspace(end[-1]) ||
3569+ iscntrl(end[-1])))
3570+ end--;
3571+ end[0]= 0;
3572+ if (end == file_name)
3573+ {
3574+ printf(_("No outfile specified!\n"));
3575+ return 0;
3576+ }
3577+ init_tee(file_name);
3578+ return 0;
3579+}
3580+
3581+
3582+static int
3583+com_notee(string *, const char *)
3584+{
3585+ if (opt_outfile)
3586+ end_tee();
3587+ tee_fprintf(stdout, _("Outfile disabled.\n"));
3588+ return 0;
3589+}
3590+
3591+/*
3592+ Sorry, this command is not available in Windows.
3593+*/
3594+
3595+static int
3596+com_pager(string *, const char *line)
3597+{
3598+ const char *param;
3599+
3600+ if (status.getBatch())
3601+ return 0;
3602+ /* Skip spaces in front of the pager command */
3603+ while (isspace(*line))
3604+ line++;
3605+ /* Skip the pager command */
3606+ param= strchr(line, ' ');
3607+ /* Skip the spaces between the command and the argument */
3608+ while (param && isspace(*param))
3609+ param++;
3610+ if (!param || (*param == '\0')) // if pager was not given, use the default
3611+ {
3612+ if (!default_pager_set)
3613+ {
3614+ tee_fprintf(stdout, _("Default pager wasn't set, using stdout.\n"));
3615+ opt_nopager=1;
3616+ pager.assign("stdout");
3617+ PAGER= stdout;
3618+ return 0;
3619+ }
3620+ pager.assign(default_pager);
3621+ }
3622+ else
3623+ {
3624+ string pager_name(param);
3625+ string::iterator end= pager_name.end();
3626+ while (end > pager_name.begin() &&
3627+ (isspace(*(end-1)) || iscntrl(*(end-1))))
3628+ --end;
3629+ pager_name.erase(end, pager_name.end());
3630+ pager.assign(pager_name);
3631+ default_pager.assign(pager_name);
3632+ }
3633+ opt_nopager=0;
3634+ tee_fprintf(stdout, _("PAGER set to '%s'\n"), pager.c_str());
3635+ return 0;
3636+}
3637+
3638+
3639+static int
3640+com_nopager(string *, const char *)
3641+{
3642+ pager.assign("stdout");
3643+ opt_nopager=1;
3644+ PAGER= stdout;
3645+ tee_fprintf(stdout, _("PAGER set to stdout\n"));
3646+ return 0;
3647+}
3648+
3649+/* If arg is given, exit without errors. This happens on command 'quit' */
3650+
3651+static int
3652+com_quit(string *, const char *)
3653+{
3654+ /* let the screen auto close on a normal shutdown */
3655+ status.setExitStatus(0);
3656+ return 1;
3657+}
3658+
3659+static int
3660+com_rehash(string *, const char *)
3661+{
3662+ build_completion_hash(1, 0);
3663+ return 0;
3664+}
3665+
3666+
3667+
3668+static int
3669+com_print(string *buffer,const char *)
3670+{
3671+ tee_puts("--------------", stdout);
3672+ (void) tee_fputs(buffer->c_str(), stdout);
3673+ if ( (buffer->length() == 0)
3674+ || (buffer->c_str())[(buffer->length())-1] != '\n')
3675+ tee_putc('\n', stdout);
3676+ tee_puts("--------------\n", stdout);
3677+ /* If empty buffer */
3678+ return 0;
3679+}
3680+
3681+/* ARGSUSED */
3682+static int
3683+com_connect(string *buffer, const char *line)
3684+{
3685+ char *tmp, buff[256];
3686+ bool save_rehash= opt_rehash;
3687+ int error;
3688+
3689+ memset(buff, 0, sizeof(buff));
3690+ if (buffer)
3691+ {
3692+ /*
3693+ Two null bytes are needed in the end of buff to allow
3694+ get_arg to find end of string the second time it's called.
3695+ */
3696+ tmp= strncpy(buff, line, sizeof(buff)-2);
3697+#ifdef EXTRA_DEBUG
3698+ tmp[1]= 0;
3699+#endif
3700+ tmp= get_arg(buff, 0);
3701+ if (tmp && *tmp)
3702+ {
3703+ current_db.erase();
3704+ current_db.assign(tmp);
3705+ tmp= get_arg(buff, 1);
3706+ if (tmp)
3707+ {
3708+ current_host.erase();
3709+ current_host=strdup(tmp);
3710+ }
3711+ }
3712+ else
3713+ {
3714+ /* Quick re-connect */
3715+ opt_rehash= 0;
3716+ }
3717+ // command used
3718+ assert(buffer!=NULL);
3719+ buffer->clear();
3720+ }
3721+ else
3722+ opt_rehash= 0;
3723+ error=sql_connect(current_host, current_db, current_user, opt_password,0);
3724+ opt_rehash= save_rehash;
3725+
3726+ if (connected)
3727+ {
3728+ sprintf(buff, _("Connection id: %u"), drizzle_con_thread_id(&con));
3729+ put_info(buff,INFO_INFO,0,0);
3730+ sprintf(buff, _("Current database: %.128s\n"),
3731+ !current_db.empty() ? current_db.c_str() : _("*** NONE ***"));
3732+ put_info(buff,INFO_INFO,0,0);
3733+ }
3734+ return error;
3735+}
3736+
3737+
3738+static int com_source(string *, const char *line)
3739+{
3740+ char source_name[FN_REFLEN], *end;
3741+ const char *param;
3742+ LineBuffer *line_buff;
3743+ int error;
3744+ Status old_status;
3745+ FILE *sql_file;
3746+
3747+ /* Skip space from file name */
3748+ while (isspace(*line))
3749+ line++;
3750+ if (!(param = strchr(line, ' '))) // Skip command name
3751+ return put_info(_("Usage: \\. <filename> | source <filename>"),
3752+ INFO_ERROR, 0,0);
3753+ while (isspace(*param))
3754+ param++;
3755+ end= strncpy(source_name,param,sizeof(source_name)-1);
3756+ end+= strlen(source_name);
3757+ while (end > source_name && (isspace(end[-1]) ||
3758+ iscntrl(end[-1])))
3759+ end--;
3760+ end[0]=0;
3761+
3762+ /* open file name */
3763+ if (!(sql_file = fopen(source_name, "r")))
3764+ {
3765+ char buff[FN_REFLEN+60];
3766+ sprintf(buff, _("Failed to open file '%s', error: %d"), source_name,errno);
3767+ return put_info(buff, INFO_ERROR, 0 ,0);
3768+ }
3769+
3770+ line_buff= new(std::nothrow) LineBuffer(opt_max_input_line,sql_file);
3771+ if (line_buff == NULL)
3772+ {
3773+ fclose(sql_file);
3774+ return put_info(_("Can't initialize LineBuffer"), INFO_ERROR, 0, 0);
3775+ }
3776+
3777+ /* Save old status */
3778+ old_status=status;
3779+ memset(&status, 0, sizeof(status));
3780+
3781+ // Run in batch mode
3782+ status.setBatch(old_status.getBatch());
3783+ status.setLineBuff(line_buff);
3784+ status.setFileName(source_name);
3785+ // Empty command buffer
3786+ assert(glob_buffer!=NULL);
3787+ glob_buffer->clear();
3788+ error= read_and_execute(false);
3789+ // Continue as before
3790+ status=old_status;
3791+ fclose(sql_file);
3792+ delete status.getLineBuff();
3793+ line_buff=0;
3794+ status.setLineBuff(0);
3795+ return error;
3796+}
3797+
3798+
3799+/* ARGSUSED */
3800+static int
3801+com_delimiter(string *, const char *line)
3802+{
3803+ char buff[256], *tmp;
3804+
3805+ strncpy(buff, line, sizeof(buff) - 1);
3806+ tmp= get_arg(buff, 0);
3807+
3808+ if (!tmp || !*tmp)
3809+ {
3810+ put_info(_("DELIMITER must be followed by a 'delimiter' character or string"),
3811+ INFO_ERROR, 0, 0);
3812+ return 0;
3813+ }
3814+ else
3815+ {
3816+ if (strstr(tmp, "\\"))
3817+ {
3818+ put_info(_("DELIMITER cannot contain a backslash character"),
3819+ INFO_ERROR, 0, 0);
3820+ return 0;
3821+ }
3822+ }
3823+ strncpy(delimiter, tmp, sizeof(delimiter) - 1);
3824+ delimiter_length= (int)strlen(delimiter);
3825+ delimiter_str= delimiter;
3826+ return 0;
3827+}
3828+
3829+/* ARGSUSED */
3830+static int
3831+com_use(string *, const char *line)
3832+{
3833+ char *tmp, buff[FN_REFLEN + 1];
3834+ int select_db;
3835+ drizzle_result_st result;
3836+ drizzle_return_t ret;
3837+
3838+ memset(buff, 0, sizeof(buff));
3839+ strncpy(buff, line, sizeof(buff) - 1);
3840+ tmp= get_arg(buff, 0);
3841+ if (!tmp || !*tmp)
3842+ {
3843+ put_info(_("USE must be followed by a database name"), INFO_ERROR, 0, 0);
3844+ return 0;
3845+ }
3846+ /*
3847+ We need to recheck the current database, because it may change
3848+ under our feet, for example if DROP DATABASE or RENAME DATABASE
3849+ (latter one not yet available by the time the comment was written)
3850+ */
3851+ get_current_db();
3852+
3853+ if (current_db.empty() || strcmp(current_db.c_str(),tmp))
3854+ {
3855+ if (one_database)
3856+ {
3857+ skip_updates= 1;
3858+ select_db= 0; // don't do drizzleclient_select_db()
3859+ }
3860+ else
3861+ select_db= 2; // do drizzleclient_select_db() and build_completion_hash()
3862+ }
3863+ else
3864+ {
3865+ /*
3866+ USE to the current db specified.
3867+ We do need to send drizzleclient_select_db() to make server
3868+ update database level privileges, which might
3869+ change since last USE (see bug#10979).
3870+ For performance purposes, we'll skip rebuilding of completion hash.
3871+ */
3872+ skip_updates= 0;
3873+ select_db= 1; // do only drizzleclient_select_db(), without completion
3874+ }
3875+
3876+ if (select_db)
3877+ {
3878+ /*
3879+ reconnect once if connection is down or if connection was found to
3880+ be down during query
3881+ */
3882+ if (!connected && reconnect())
3883+ return opt_reconnect ? -1 : 1; // Fatal error
3884+ for (bool try_again= true; try_again; try_again= false)
3885+ {
3886+ if (drizzle_select_db(&con,&result,tmp,&ret) == NULL ||
3887+ ret != DRIZZLE_RETURN_OK)
3888+ {
3889+ if (ret == DRIZZLE_RETURN_ERROR_CODE)
3890+ {
3891+ int error= put_error(&con, &result);
3892+ drizzle_result_free(&result);
3893+ return error;
3894+ }
3895+
3896+ if (ret != DRIZZLE_RETURN_SERVER_GONE || !try_again)
3897+ return put_error(&con, NULL);
3898+
3899+ if (reconnect())
3900+ return opt_reconnect ? -1 : 1; // Fatal error
3901+ }
3902+ else
3903+ drizzle_result_free(&result);
3904+ }
3905+ current_db.erase();
3906+ current_db.assign(tmp);
3907+ if (select_db > 1)
3908+ build_completion_hash(opt_rehash, 1);
3909+ }
3910+
3911+ put_info(_("Database changed"),INFO_INFO, 0, 0);
3912+ return 0;
3913+}
3914+
3915+static int
3916+com_warnings(string *, const char *)
3917+{
3918+ show_warnings = 1;
3919+ put_info(_("Show warnings enabled."),INFO_INFO, 0, 0);
3920+ return 0;
3921+}
3922+
3923+static int
3924+com_nowarnings(string *, const char *)
3925+{
3926+ show_warnings = 0;
3927+ put_info(_("Show warnings disabled."),INFO_INFO, 0, 0);
3928+ return 0;
3929+}
3930+
3931+/*
3932+ Gets argument from a command on the command line. If get_next_arg is
3933+ not defined, skips the command and returns the first argument. The
3934+ line is modified by adding zero to the end of the argument. If
3935+ get_next_arg is defined, then the function searches for end of string
3936+ first, after found, returns the next argument and adds zero to the
3937+ end. If you ever wish to use this feature, remember to initialize all
3938+ items in the array to zero first.
3939+*/
3940+
3941+char *get_arg(char *line, bool get_next_arg)
3942+{
3943+ char *ptr, *start;
3944+ bool quoted= 0, valid_arg= 0;
3945+ char qtype= 0;
3946+
3947+ ptr= line;
3948+ if (get_next_arg)
3949+ {
3950+ for (; *ptr; ptr++) ;
3951+ if (*(ptr + 1))
3952+ ptr++;
3953+ }
3954+ else
3955+ {
3956+ /* skip leading white spaces */
3957+ while (isspace(*ptr))
3958+ ptr++;
3959+ if (*ptr == '\\') // short command was used
3960+ ptr+= 2;
3961+ else
3962+ while (*ptr &&!isspace(*ptr)) // skip command
3963+ ptr++;
3964+ }
3965+ if (!*ptr)
3966+ return NULL;
3967+ while (isspace(*ptr))
3968+ ptr++;
3969+ if (*ptr == '\'' || *ptr == '\"' || *ptr == '`')
3970+ {
3971+ qtype= *ptr;
3972+ quoted= 1;
3973+ ptr++;
3974+ }
3975+ for (start=ptr ; *ptr; ptr++)
3976+ {
3977+ if (*ptr == '\\' && ptr[1]) // escaped character
3978+ {
3979+ // Remove the backslash
3980+ strcpy(ptr, ptr+1);
3981+ }
3982+ else if ((!quoted && *ptr == ' ') || (quoted && *ptr == qtype))
3983+ {
3984+ *ptr= 0;
3985+ break;
3986+ }
3987+ }
3988+ valid_arg= ptr != start;
3989+ return valid_arg ? start : NULL;
3990+}
3991+
3992+
3993+static int
3994+sql_connect(const string &host, const string &database, const string &user, const string &password,
3995+ uint32_t silent)
3996+{
3997+ drizzle_return_t ret;
3998+ if (connected)
3999+ {
4000+ connected= 0;
4001+ drizzle_con_free(&con);
4002+ drizzle_free(&drizzle);
4003+ }
4004+ drizzle_create(&drizzle);
4005+ if (drizzle_con_add_tcp(&drizzle, &con, (char *)host.c_str(),
4006+ opt_drizzle_port, (char *)user.c_str(),
4007+ (char *)password.c_str(), (char *)database.c_str(),
4008+ use_drizzle_protocol ? DRIZZLE_CON_EXPERIMENTAL : DRIZZLE_CON_MYSQL) == NULL)
4009+ {
4010+ (void) put_error(&con, NULL);
4011+ (void) fflush(stdout);
4012+ return 1;
4013+ }
4014+
4015+/* XXX add this back in
4016+ if (opt_connect_timeout)
4017+ {
4018+ uint32_t timeout=opt_connect_timeout;
4019+ drizzleclient_options(&drizzle,DRIZZLE_OPT_CONNECT_TIMEOUT,
4020+ (char*) &timeout);
4021+ }
4022+*/
4023+
4024+/* XXX Do we need this?
4025+ if (safe_updates)
4026+ {
4027+ char init_command[100];
4028+ sprintf(init_command,
4029+ "SET SQL_SAFE_UPDATES=1,SQL_SELECT_LIMIT=%"PRIu32
4030+ ",MAX_JOIN_SIZE=%"PRIu32,
4031+ select_limit, max_join_size);
4032+ drizzleclient_options(&drizzle, DRIZZLE_INIT_COMMAND, init_command);
4033+ }
4034+*/
4035+ if ((ret= drizzle_con_connect(&con)) != DRIZZLE_RETURN_OK)
4036+ {
4037+ if (!silent || (ret != DRIZZLE_RETURN_GETADDRINFO &&
4038+ ret != DRIZZLE_RETURN_COULD_NOT_CONNECT))
4039+ {
4040+ (void) put_error(&con, NULL);
4041+ (void) fflush(stdout);
4042+ return ignore_errors ? -1 : 1; // Abort
4043+ }
4044+ return -1; // Retryable
4045+ }
4046+ connected=1;
4047+
4048+ build_completion_hash(opt_rehash, 1);
4049+ return 0;
4050+}
4051+
4052+
4053+static int
4054+com_status(string *, const char *)
4055+{
4056+/*
4057+ char buff[40];
4058+ uint64_t id;
4059+*/
4060+ drizzle_result_st result;
4061+ drizzle_return_t ret;
4062+
4063+ tee_puts("--------------", stdout);
4064+ printf(_("Drizzle client %s build %s, for %s-%s (%s) using readline %s\n"),
4065+ drizzle_version(), VERSION,
4066+ HOST_VENDOR, HOST_OS, HOST_CPU,
4067+ rl_library_version);
4068+
4069+ if (connected)
4070+ {
4071+ tee_fprintf(stdout, _("\nConnection id:\t\t%lu\n"),drizzle_con_thread_id(&con));
4072+ /*
4073+ Don't remove "limit 1",
4074+ it is protection againts SQL_SELECT_LIMIT=0
4075+ */
4076+ if (drizzle_query_str(&con,&result,"select DATABASE(), USER() limit 1",
4077+ &ret) != NULL && ret == DRIZZLE_RETURN_OK &&
4078+ drizzle_result_buffer(&result) == DRIZZLE_RETURN_OK)
4079+ {
4080+ drizzle_row_t cur=drizzle_row_next(&result);
4081+ if (cur)
4082+ {
4083+ tee_fprintf(stdout, _("Current database:\t%s\n"), cur[0] ? cur[0] : "");
4084+ tee_fprintf(stdout, _("Current user:\t\t%s\n"), cur[1]);
4085+ }
4086+ drizzle_result_free(&result);
4087+ }
4088+ else if (ret == DRIZZLE_RETURN_ERROR_CODE)
4089+ drizzle_result_free(&result);
4090+ tee_puts(_("SSL:\t\t\tNot in use"), stdout);
4091+ }
4092+ else
4093+ {
4094+ vidattr(A_BOLD);
4095+ tee_fprintf(stdout, _("\nNo connection\n"));
4096+ vidattr(A_NORMAL);
4097+ return 0;
4098+ }
4099+ if (skip_updates)
4100+ {
4101+ vidattr(A_BOLD);
4102+ tee_fprintf(stdout, _("\nAll updates ignored to this database\n"));
4103+ vidattr(A_NORMAL);
4104+ }
4105+ tee_fprintf(stdout, _("Current pager:\t\t%s\n"), pager.c_str());
4106+ tee_fprintf(stdout, _("Using outfile:\t\t'%s'\n"), opt_outfile ? outfile.c_str() : "");
4107+ tee_fprintf(stdout, _("Using delimiter:\t%s\n"), delimiter);
4108+ tee_fprintf(stdout, _("Server version:\t\t%s\n"), server_version_string(&con));
4109+ tee_fprintf(stdout, _("Protocol:\t\t%s\n"), opt_protocol.c_str());
4110+ tee_fprintf(stdout, _("Protocol version:\t%d\n"), drizzle_con_protocol_version(&con));
4111+ tee_fprintf(stdout, _("Connection:\t\t%s\n"), drizzle_con_host(&con));
4112+/* XXX need to save this from result
4113+ if ((id= drizzleclient_insert_id(&drizzle)))
4114+ tee_fprintf(stdout, "Insert id:\t\t%s\n", internal::llstr(id, buff));
4115+*/
4116+
4117+ if (drizzle_con_uds(&con))
4118+ tee_fprintf(stdout, _("UNIX socket:\t\t%s\n"), drizzle_con_uds(&con));
4119+ else
4120+ tee_fprintf(stdout, _("TCP port:\t\t%d\n"), drizzle_con_port(&con));
4121+
4122+ if (safe_updates)
4123+ {
4124+ vidattr(A_BOLD);
4125+ tee_fprintf(stdout, _("\nNote that you are running in safe_update_mode:\n"));
4126+ vidattr(A_NORMAL);
4127+ tee_fprintf(stdout, _("\
4128+UPDATEs and DELETEs that don't use a key in the WHERE clause are not allowed.\n\
4129+(One can force an UPDATE/DELETE by adding LIMIT # at the end of the command.)\n \
4130+SELECT has an automatic 'LIMIT %lu' if LIMIT is not used.\n \
4131+Max number of examined row combination in a join is set to: %lu\n\n"),
4132+ select_limit, max_join_size);
4133+ }
4134+ tee_puts("--------------\n", stdout);
4135+ return 0;
4136+}
4137+
4138+static const char *
4139+server_version_string(drizzle_con_st *local_con)
4140+{
4141+ static string buf("");
4142+ static bool server_version_string_reserved= false;
4143+
4144+ if (!server_version_string_reserved)
4145+ {
4146+ buf.reserve(MAX_SERVER_VERSION_LENGTH);
4147+ server_version_string_reserved= true;
4148+ }
4149+ /* Only one thread calls this, so no synchronization is needed */
4150+ if (buf[0] == '\0')
4151+ {
4152+ drizzle_result_st result;
4153+ drizzle_return_t ret;
4154+
4155+ buf.append(drizzle_con_server_version(local_con));
4156+
4157+ /* "limit 1" is protection against SQL_SELECT_LIMIT=0 */
4158+ (void)drizzle_query_str(local_con, &result,
4159+ "select @@version_comment limit 1", &ret);
4160+ if (ret == DRIZZLE_RETURN_OK &&
4161+ drizzle_result_buffer(&result) == DRIZZLE_RETURN_OK)
4162+ {
4163+ drizzle_row_t cur = drizzle_row_next(&result);
4164+ if (cur && cur[0])
4165+ {
4166+ buf.append(" ");
4167+ buf.append(cur[0]);
4168+ }
4169+ drizzle_result_free(&result);
4170+ }
4171+ else if (ret == DRIZZLE_RETURN_ERROR_CODE)
4172+ drizzle_result_free(&result);
4173+ }
4174+
4175+ return buf.c_str();
4176+}
4177+
4178+static int
4179+put_info(const char *str,INFO_TYPE info_type, uint32_t error, const char *sqlstate)
4180+{
4181+ FILE *file= (info_type == INFO_ERROR ? stderr : stdout);
4182+ static int inited=0;
4183+
4184+ if (status.getBatch())
4185+ {
4186+ if (info_type == INFO_ERROR)
4187+ {
4188+ (void) fflush(file);
4189+ fprintf(file,_("ERROR"));
4190+ if (error)
4191+ {
4192+ if (sqlstate)
4193+ (void) fprintf(file," %d (%s)",error, sqlstate);
4194+ else
4195+ (void) fprintf(file," %d",error);
4196+ }
4197+ if (status.getQueryStartLine() && line_numbers)
4198+ {
4199+ (void) fprintf(file," at line %"PRIu32,status.getQueryStartLine());
4200+ if (status.getFileName())
4201+ (void) fprintf(file," in file: '%s'", status.getFileName());
4202+ }
4203+ (void) fprintf(file,": %s\n",str);
4204+ (void) fflush(file);
4205+ if (!ignore_errors)
4206+ return 1;
4207+ }
4208+ else if (info_type == INFO_RESULT && verbose > 1)
4209+ tee_puts(str, file);
4210+ if (unbuffered)
4211+ fflush(file);
4212+ return info_type == INFO_ERROR ? -1 : 0;
4213+ }
4214+ if (!opt_silent || info_type == INFO_ERROR)
4215+ {
4216+ if (!inited)
4217+ {
4218+ inited=1;
4219+#ifdef HAVE_SETUPTERM
4220+ (void) setupterm((char *)0, 1, (int *) 0);
4221+#endif
4222+ }
4223+ if (info_type == INFO_ERROR)
4224+ {
4225+ if (!opt_nobeep)
4226+ /* This should make a bell */
4227+ putchar('\a');
4228+ vidattr(A_STANDOUT);
4229+ if (error)
4230+ {
4231+ if (sqlstate)
4232+ (void) tee_fprintf(file, _("ERROR %d (%s): "), error, sqlstate);
4233+ else
4234+ (void) tee_fprintf(file, _("ERROR %d: "), error);
4235+ }
4236+ else
4237+ tee_puts(_("ERROR: "), file);
4238+ }
4239+ else
4240+ vidattr(A_BOLD);
4241+ (void) tee_puts(str, file);
4242+ vidattr(A_NORMAL);
4243+ }
4244+ if (unbuffered)
4245+ fflush(file);
4246+ return info_type == INFO_ERROR ? -1 : 0;
4247+}
4248+
4249+
4250+static int
4251+put_error(drizzle_con_st *local_con, drizzle_result_st *res)
4252+{
4253+ const char *error;
4254+
4255+ if (res != NULL)
4256+ {
4257+ error= drizzle_result_error(res);
4258+ if (!strcmp(error, ""))
4259+ error= drizzle_con_error(local_con);
4260+ }
4261+ else
4262+ error= drizzle_con_error(local_con);
4263+
4264+ return put_info(error, INFO_ERROR,
4265+ res == NULL ? drizzle_con_error_code(local_con) :
4266+ drizzle_result_error_code(res),
4267+ res == NULL ? drizzle_con_sqlstate(local_con) :
4268+ drizzle_result_sqlstate(res));
4269+}
4270+
4271+
4272+static void remove_cntrl(string *buffer)
4273+{
4274+ const char *start= buffer->c_str();
4275+ const char *end= start + (buffer->length());
4276+ while (start < end && !isgraph(end[-1]))
4277+ end--;
4278+ uint32_t pos_to_truncate= (end-start);
4279+ if (buffer->length() > pos_to_truncate)
4280+ buffer->erase(pos_to_truncate);
4281+}
4282+
4283+
4284+void tee_fprintf(FILE *file, const char *fmt, ...)
4285+{
4286+ va_list args;
4287+
4288+ va_start(args, fmt);
4289+ (void) vfprintf(file, fmt, args);
4290+ va_end(args);
4291+
4292+ if (opt_outfile)
4293+ {
4294+ va_start(args, fmt);
4295+ (void) vfprintf(OUTFILE, fmt, args);
4296+ va_end(args);
4297+ }
4298+}
4299+
4300+
4301+void tee_fputs(const char *s, FILE *file)
4302+{
4303+ fputs(s, file);
4304+ if (opt_outfile)
4305+ fputs(s, OUTFILE);
4306+}
4307+
4308+
4309+void tee_puts(const char *s, FILE *file)
4310+{
4311+ fputs(s, file);
4312+ fputc('\n', file);
4313+ if (opt_outfile)
4314+ {
4315+ fputs(s, OUTFILE);
4316+ fputc('\n', OUTFILE);
4317+ }
4318+}
4319+
4320+void tee_putc(int c, FILE *file)
4321+{
4322+ putc(c, file);
4323+ if (opt_outfile)
4324+ putc(c, OUTFILE);
4325+}
4326+
4327+#include <sys/times.h>
4328+#ifdef _SC_CLK_TCK // For mit-pthreads
4329+#undef CLOCKS_PER_SEC
4330+#define CLOCKS_PER_SEC (sysconf(_SC_CLK_TCK))
4331+#endif
4332+
4333+static uint32_t start_timer(void)
4334+{
4335+ struct tms tms_tmp;
4336+ return times(&tms_tmp);
4337+}
4338+
4339+
4340+/**
4341+ Write as many as 52+1 bytes to buff, in the form of a legible
4342+ duration of time.
4343+
4344+ len("4294967296 days, 23 hours, 59 minutes, 60.00 seconds") -> 52
4345+*/
4346+static void nice_time(double sec,char *buff,bool part_second)
4347+{
4348+ uint32_t tmp;
4349+ ostringstream tmp_buff_str;
4350+
4351+ if (sec >= 3600.0*24)
4352+ {
4353+ tmp=(uint32_t) floor(sec/(3600.0*24));
4354+ sec-= 3600.0*24*tmp;
4355+ tmp_buff_str << tmp;
4356+
4357+ if (tmp > 1)
4358+ tmp_buff_str << " days ";
4359+ else
4360+ tmp_buff_str << " day ";
4361+
4362+ }
4363+ if (sec >= 3600.0)
4364+ {
4365+ tmp=(uint32_t) floor(sec/3600.0);
4366+ sec-=3600.0*tmp;
4367+ tmp_buff_str << tmp;
4368+
4369+ if (tmp > 1)
4370+ tmp_buff_str << _(" hours ");
4371+ else
4372+ tmp_buff_str << _(" hour ");
4373+ }
4374+ if (sec >= 60.0)
4375+ {
4376+ tmp=(uint32_t) floor(sec/60.0);
4377+ sec-=60.0*tmp;
4378+ tmp_buff_str << tmp << _(" min ");
4379+ }
4380+ if (part_second)
4381+ tmp_buff_str.precision(2);
4382+ else
4383+ tmp_buff_str.precision(0);
4384+ tmp_buff_str << sec << _(" sec");
4385+ strcpy(buff, tmp_buff_str.str().c_str());
4386+}
4387+
4388+
4389+static void end_timer(uint32_t start_time,char *buff)
4390+{
4391+ nice_time((double) (start_timer() - start_time) /
4392+ CLOCKS_PER_SEC,buff,1);
4393+}
4394+
4395+
4396+static void drizzle_end_timer(uint32_t start_time,char *buff)
4397+{
4398+ buff[0]=' ';
4399+ buff[1]='(';
4400+ end_timer(start_time,buff+2);
4401+ strcpy(strchr(buff, '\0'),")");
4402+}
4403+
4404+static const char * construct_prompt()
4405+{
4406+ // Erase the old prompt
4407+ assert(processed_prompt!=NULL);
4408+ processed_prompt->clear();
4409+
4410+ // Get the date struct
4411+ time_t lclock = time(NULL);
4412+ struct tm *t = localtime(&lclock);
4413+
4414+ /* parse thru the settings for the prompt */
4415+ string::iterator c= current_prompt.begin();
4416+ while (c != current_prompt.end())
4417+ {
4418+ if (*c != PROMPT_CHAR)
4419+ {
4420+ processed_prompt->push_back(*c);
4421+ }
4422+ else
4423+ {
4424+ int getHour;
4425+ int getYear;
4426+ /* Room for Dow MMM DD HH:MM:SS YYYY */
4427+ char dateTime[32];
4428+ switch (*++c) {
4429+ case '\0':
4430+ // stop it from going beyond if ends with %
4431+ --c;
4432+ break;
4433+ case 'c':
4434+ add_int_to_prompt(++prompt_counter);
4435+ break;
4436+ case 'v':
4437+ if (connected)
4438+ processed_prompt->append(drizzle_con_server_version(&con));
4439+ else
4440+ processed_prompt->append("not_connected");
4441+ break;
4442+ case 'd':
4443+ processed_prompt->append(not current_db.empty() ? current_db : "(none)");
4444+ break;
4445+ case 'h':
4446+ {
4447+ const char *prompt= connected ? drizzle_con_host(&con) : "not_connected";
4448+ if (strstr(prompt, "Localhost"))
4449+ processed_prompt->append("localhost");
4450+ else
4451+ {
4452+ const char *end=strrchr(prompt,' ');
4453+ if (end != NULL)
4454+ processed_prompt->append(prompt, (end-prompt));
4455+ }
4456+ break;
4457+ }
4458+ case 'p':
4459+ {
4460+ if (!connected)
4461+ {
4462+ processed_prompt->append("not_connected");
4463+ break;
4464+ }
4465+
4466+ if (drizzle_con_uds(&con))
4467+ {
4468+ const char *pos=strrchr(drizzle_con_uds(&con),'/');
4469+ processed_prompt->append(pos ? pos+1 : drizzle_con_uds(&con));
4470+ }
4471+ else
4472+ add_int_to_prompt(drizzle_con_port(&con));
4473+ }
4474+ break;
4475+ case 'U':
4476+ if (!full_username)
4477+ init_username();
4478+ processed_prompt->append(full_username ? full_username :
4479+ (!current_user.empty() ? current_user : "(unknown)"));
4480+ break;
4481+ case 'u':
4482+ if (!full_username)
4483+ init_username();
4484+ processed_prompt->append(part_username ? part_username :
4485+ (!current_user.empty() ? current_user : _("(unknown)")));
4486+ break;
4487+ case PROMPT_CHAR:
4488+ {
4489+ processed_prompt->append(PROMPT_CHAR, 1);
4490+ }
4491+ break;
4492+ case 'n':
4493+ {
4494+ processed_prompt->append('\n', 1);
4495+ }
4496+ break;
4497+ case ' ':
4498+ case '_':
4499+ {
4500+ processed_prompt->append(' ', 1);
4501+ }
4502+ break;
4503+ case 'R':
4504+ if (t->tm_hour < 10)
4505+ add_int_to_prompt(0);
4506+ add_int_to_prompt(t->tm_hour);
4507+ break;
4508+ case 'r':
4509+ getHour = t->tm_hour % 12;
4510+ if (getHour == 0)
4511+ getHour=12;
4512+ if (getHour < 10)
4513+ add_int_to_prompt(0);
4514+ add_int_to_prompt(getHour);
4515+ break;
4516+ case 'm':
4517+ if (t->tm_min < 10)
4518+ add_int_to_prompt(0);
4519+ add_int_to_prompt(t->tm_min);
4520+ break;
4521+ case 'y':
4522+ getYear = t->tm_year % 100;
4523+ if (getYear < 10)
4524+ add_int_to_prompt(0);
4525+ add_int_to_prompt(getYear);
4526+ break;
4527+ case 'Y':
4528+ add_int_to_prompt(t->tm_year+1900);
4529+ break;
4530+ case 'D':
4531+ strftime(dateTime, 32, "%a %b %d %H:%M:%S %Y", localtime(&lclock));
4532+ processed_prompt->append(dateTime);
4533+ break;
4534+ case 's':
4535+ if (t->tm_sec < 10)
4536+ add_int_to_prompt(0);
4537+ add_int_to_prompt(t->tm_sec);
4538+ break;
4539+ case 'w':
4540+ processed_prompt->append(day_names[t->tm_wday]);
4541+ break;
4542+ case 'P':
4543+ processed_prompt->append(t->tm_hour < 12 ? "am" : "pm");
4544+ break;
4545+ case 'o':
4546+ add_int_to_prompt(t->tm_mon+1);
4547+ break;
4548+ case 'O':
4549+ processed_prompt->append(month_names[t->tm_mon]);
4550+ break;
4551+ case '\'':
4552+ processed_prompt->append("'");
4553+ break;
4554+ case '"':
4555+ processed_prompt->append("\"");
4556+ break;
4557+ case 'S':
4558+ processed_prompt->append(";");
4559+ break;
4560+ case 't':
4561+ processed_prompt->append("\t");
4562+ break;
4563+ case 'l':
4564+ processed_prompt->append(delimiter_str);
4565+ break;
4566+ default:
4567+ processed_prompt->push_back(*c);
4568+ }
4569+ }
4570+ ++c;
4571+ }
4572+ return processed_prompt->c_str();
4573+}
4574+
4575+
4576+static void add_int_to_prompt(int toadd)
4577+{
4578+ ostringstream buffer;
4579+ buffer << toadd;
4580+ processed_prompt->append(buffer.str().c_str());
4581+}
4582+
4583+static void init_username()
4584+{
4585+/* XXX need this?
4586+ free(full_username);
4587+ free(part_username);
4588+
4589+ drizzle_result_st *result;
4590+ if (!drizzleclient_query(&drizzle,"select USER()") &&
4591+ (result=drizzleclient_use_result(&drizzle)))
4592+ {
4593+ drizzle_row_t cur=drizzleclient_fetch_row(result);
4594+ full_username= strdup(cur[0]);
4595+ part_username= strdup(strtok(cur[0],"@"));
4596+ (void) drizzleclient_fetch_row(result); // Read eof
4597+ }
4598+*/
4599+}
4600+
4601+static int com_prompt(string *, const char *line)
4602+{
4603+ const char *ptr=strchr(line, ' ');
4604+ if (ptr == NULL)
4605+ tee_fprintf(stdout, _("Returning to default PROMPT of %s\n"),
4606+ default_prompt);
4607+ prompt_counter = 0;
4608+ char * tmpptr= strdup(ptr ? ptr+1 : default_prompt);
4609+ if (tmpptr == NULL)
4610+ tee_fprintf(stdout, _("Memory allocation error. Not changing prompt\n"));
4611+ else
4612+ {
4613+ current_prompt.erase();
4614+ current_prompt= tmpptr;
4615+ tee_fprintf(stdout, _("PROMPT set to '%s'\n"), current_prompt.c_str());
4616+ }
4617+ return 0;
4618+}
4619+
4620+/*
4621+ strcont(str, set) if str contanies any character in the string set.
4622+ The result is the position of the first found character in str, or NULL
4623+ if there isn't anything found.
4624+*/
4625+
4626+static const char * strcont(register const char *str, register const char *set)
4627+{
4628+ register const char * start = (const char *) set;
4629+
4630+ while (*str)
4631+ {
4632+ while (*set)
4633+ {
4634+ if (*set++ == *str)
4635+ return ((const char*) str);
4636+ }
4637+ set=start; str++;
4638+ }
4639+ return NULL;
4640+} /* strcont */
4641
4642=== added directory 'plugin/stad/common'
4643=== added file 'plugin/stad/common/injection_exception.hpp'
4644--- plugin/stad/common/injection_exception.hpp 1970-01-01 00:00:00 +0000
4645+++ plugin/stad/common/injection_exception.hpp 2010-11-24 20:50:51 +0000
4646@@ -0,0 +1,60 @@
4647+/*
4648+ * Copyright (C) 2010 Padraig O'Sullivan
4649+ *
4650+ * This program is free software; you can redistribute it and/or modify
4651+ * it under the terms of the GNU General Public License as published by
4652+ * the Free Software Foundation; either version 2 of the License, or
4653+ * (at your option) any later version.
4654+ *
4655+ * This program is distributed in the hope that it will be useful,
4656+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
4657+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
4658+ * GNU General Public License for more details.
4659+ *
4660+ * You should have received a copy of the GNU General Public License
4661+ * along with this program; if not, write to the Free Software
4662+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
4663+ */
4664+
4665+#include <exception>
4666+#include <string>
4667+
4668+class injection_exception : public std::exception
4669+{
4670+public:
4671+
4672+ injection_exception()
4673+ :
4674+ _error_code(0),
4675+ _message()
4676+ {}
4677+
4678+ injection_exception(const std::string& msg, int in_error = 0)
4679+ :
4680+ _error_code(in_error),
4681+ _message(msg)
4682+ {}
4683+
4684+ virtual ~injection_exception() throw() {}
4685+
4686+ virtual const char* what() const throw()
4687+ {
4688+ return _message.c_str();
4689+ }
4690+
4691+ int error_code() const
4692+ {
4693+ return _error_code;
4694+ }
4695+
4696+ const std::string& message() const
4697+ {
4698+ return _message;
4699+ }
4700+
4701+private:
4702+
4703+ const int _error_code;
4704+ const std::string _message;
4705+
4706+};
4707
4708=== added file 'plugin/stad/common/keywords.cpp'
4709--- plugin/stad/common/keywords.cpp 1970-01-01 00:00:00 +0000
4710+++ plugin/stad/common/keywords.cpp 2010-11-24 20:50:51 +0000
4711@@ -0,0 +1,67 @@
4712+/*
4713+ * Copyright (C) 2010 Padraig O'Sullivan
4714+ *
4715+ * This program is free software; you can redistribute it and/or modify
4716+ * it under the terms of the GNU General Public License as published by
4717+ * the Free Software Foundation; either version 2 of the License, or
4718+ * (at your option) any later version.
4719+ *
4720+ * This program is distributed in the hope that it will be useful,
4721+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
4722+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
4723+ * GNU General Public License for more details.
4724+ *
4725+ * You should have received a copy of the GNU General Public License
4726+ * along with this program; if not, write to the Free Software
4727+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
4728+ */
4729+
4730+#include <string>
4731+#include <iostream>
4732+#include <algorithm>
4733+#include <boost/tokenizer.hpp>
4734+#include <boost/unordered_map.hpp>
4735+
4736+#include "keywords.hpp"
4737+
4738+using namespace std;
4739+using namespace boost;
4740+
4741+
4742+keywords::keywords()
4743+ :
4744+ _keywords()
4745+{
4746+ _keywords.insert(make_pair("add", "add"));
4747+ _keywords.insert(make_pair("all", "all"));
4748+ _keywords.insert(make_pair("alter", "alter"));
4749+ _keywords.insert(make_pair("analyze", "analyze"));
4750+ _keywords.insert(make_pair("and", "and"));
4751+ _keywords.insert(make_pair("any", "any"));
4752+ _keywords.insert(make_pair("as", "as"));
4753+ _keywords.insert(make_pair("asc", "asc"));
4754+ _keywords.insert(make_pair("before", "before"));
4755+ _keywords.insert(make_pair("between", "between"));
4756+ _keywords.insert(make_pair("by", "by"));
4757+ _keywords.insert(make_pair("count", "count"));
4758+ _keywords.insert(make_pair("distinct", "distinct"));
4759+ _keywords.insert(make_pair("drop", "drop"));
4760+ _keywords.insert(make_pair("from", "from"));
4761+ _keywords.insert(make_pair("having", "having"));
4762+ _keywords.insert(make_pair("or", "or"));
4763+ _keywords.insert(make_pair("select", "select"));
4764+ _keywords.insert(make_pair("union", "union"));
4765+ _keywords.insert(make_pair("where", "where"));
4766+}
4767+
4768+
4769+bool keywords::is_keyword(const string& word)
4770+{
4771+ boost::unordered_map<string, string>::iterator iter = _keywords.find(word);
4772+ if (iter != _keywords.end())
4773+ {
4774+ return true;
4775+ }
4776+ return false;
4777+}
4778+
4779
4780=== added file 'plugin/stad/common/keywords.hpp'
4781--- plugin/stad/common/keywords.hpp 1970-01-01 00:00:00 +0000
4782+++ plugin/stad/common/keywords.hpp 2010-11-24 20:50:51 +0000
4783@@ -0,0 +1,42 @@
4784+/*
4785+ * Copyright (C) 2010 Padraig O'Sullivan
4786+ *
4787+ * This program is free software; you can redistribute it and/or modify
4788+ * it under the terms of the GNU General Public License as published by
4789+ * the Free Software Foundation; either version 2 of the License, or
4790+ * (at your option) any later version.
4791+ *
4792+ * This program is distributed in the hope that it will be useful,
4793+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
4794+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
4795+ * GNU General Public License for more details.
4796+ *
4797+ * You should have received a copy of the GNU General Public License
4798+ * along with this program; if not, write to the Free Software
4799+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
4800+ */
4801+
4802+#include <string>
4803+#include <boost/unordered_map.hpp>
4804+
4805+class keywords
4806+{
4807+
4808+public:
4809+
4810+ static keywords& singleton()
4811+ {
4812+ static keywords keyword_holder;
4813+ return keyword_holder;
4814+ }
4815+
4816+ /** return true iff the given string is a keyword */
4817+ bool is_keyword(const std::string& word);
4818+
4819+private:
4820+
4821+ keywords();
4822+
4823+ boost::unordered_map<std::string, std::string> _keywords;
4824+
4825+};
4826
4827=== added file 'plugin/stad/common/randomizer.cpp'
4828--- plugin/stad/common/randomizer.cpp 1970-01-01 00:00:00 +0000
4829+++ plugin/stad/common/randomizer.cpp 2010-11-24 20:50:51 +0000
4830@@ -0,0 +1,49 @@
4831+/*
4832+ * Copyright (C) 2010 Padraig O'Sullivan
4833+ *
4834+ * This program is free software; you can redistribute it and/or modify
4835+ * it under the terms of the GNU General Public License as published by
4836+ * the Free Software Foundation; either version 2 of the License, or
4837+ * (at your option) any later version.
4838+ *
4839+ * This program is distributed in the hope that it will be useful,
4840+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
4841+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
4842+ * GNU General Public License for more details.
4843+ *
4844+ * You should have received a copy of the GNU General Public License
4845+ * along with this program; if not, write to the Free Software
4846+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
4847+ */
4848+
4849+
4850+#include <string>
4851+#include <iostream>
4852+
4853+#include <boost/program_options.hpp>
4854+
4855+#include "sql_tokenizer.hpp"
4856+
4857+
4858+using namespace std;
4859+namespace po=boost::program_options;
4860+
4861+int main(int argc, char* argv[])
4862+{
4863+ string randomization_key;
4864+ string query;
4865+ po::variables_map vm;
4866+ po::options_description my_options("Options specific to the drizzle client");
4867+ my_options.add_options()
4868+ ("key,k", po::value<string>(&randomization_key)->default_value(""),
4869+ "Randomization key.")
4870+ ("query,q", po::value<string>(&query)->default_value(""),
4871+ "Input query.")
4872+ ;
4873+ po::store(po::parse_command_line(argc, argv, my_options), vm);
4874+ po::notify(vm);
4875+ sql_tokenizer tokenizer(randomization_key);
4876+ tokenizer.randomize_query(query);
4877+ cout << "randomized query is: " << endl << query << endl;
4878+ return 0;
4879+}
4880
4881=== added file 'plugin/stad/common/sql_tokenizer.cpp'
4882--- plugin/stad/common/sql_tokenizer.cpp 1970-01-01 00:00:00 +0000
4883+++ plugin/stad/common/sql_tokenizer.cpp 2010-11-24 20:50:51 +0000
4884@@ -0,0 +1,148 @@
4885+/*
4886+ * Copyright (C) 2010 Padraig O'Sullivan
4887+ *
4888+ * This program is free software; you can redistribute it and/or modify
4889+ * it under the terms of the GNU General Public License as published by
4890+ * the Free Software Foundation; either version 2 of the License, or
4891+ * (at your option) any later version.
4892+ *
4893+ * This program is distributed in the hope that it will be useful,
4894+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
4895+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
4896+ * GNU General Public License for more details.
4897+ *
4898+ * You should have received a copy of the GNU General Public License
4899+ * along with this program; if not, write to the Free Software
4900+ * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
4901+ */
4902+
4903+#include <string>
4904+#include <iostream>
4905+#include <algorithm>
4906+#include <boost/tokenizer.hpp>
4907+#include <boost/unordered_map.hpp>
4908+
4909+#include "sql_tokenizer.hpp"
4910+#include "keywords.hpp"
4911+#include "injection_exception.hpp"
4912+
4913+using namespace std;
4914+using namespace boost;
4915+
4916+
4917+sql_tokenizer::sql_tokenizer()
4918+ :
4919+ _separator1(""),
4920+ _separator2(" "),
4921+ _separator3(""),
4922+ _randomization_key("")
4923+{
4924+}
4925+
4926+
4927+sql_tokenizer::sql_tokenizer(const string& in_key)
4928+ :
4929+ _separator1(""),
4930+ _separator2(" "),
4931+ _separator3(""),
4932+ _randomization_key(in_key)
4933+{
4934+}
4935+
4936+
4937+void sql_tokenizer::derandomize_query(string& output_query)
4938+{
4939+ escaped_list_separator<char> els(_separator1, _separator2, _separator3);
4940+ tokenizer<escaped_list_separator<char> > tok(output_query, els);
4941+ string new_query;
4942+ for (tokenizer<escaped_list_separator<char> >::iterator iter = tok.begin();
4943+ iter != tok.end();
4944+ ++iter)
4945+ {
4946+ string token(*iter);
4947+ size_t pos = token.rfind(_randomization_key);
4948+ if (pos != string::npos)
4949+ {
4950+ if (starts_with_keyword(token))
4951+ {
4952+ token.erase(pos);
4953+ }
4954+ }
4955+ else
4956+ {
4957+ if (starts_with_keyword(token))
4958+ {
4959+ /* if its a keyword, throw an exception */
4960+ throw injection_exception("SQL INJECTION!!!");
4961+ }
4962+ }
4963+ new_query.append(token);
4964+ new_query.append(" ");
4965+ }
4966+ output_query.assign(new_query);
4967+}
4968+
4969+
4970+void sql_tokenizer::randomize_query(string& output_query)
4971+{
4972+ escaped_list_separator<char> els(_separator1, _separator2, _separator3);
4973+ tokenizer<escaped_list_separator<char> > tok(output_query, els);
4974+ string new_query;
4975+ for (tokenizer<escaped_list_separator<char> >::iterator iter = tok.begin();
4976+ iter != tok.end();
4977+ ++iter)
4978+ {
4979+ string token(*iter);
4980+ if (starts_with_keyword(token))
4981+ {
4982+ token.append(_randomization_key);
4983+ }
4984+ new_query.append(token);
4985+ new_query.append(" ");
4986+ }
4987+ output_query.assign(new_query);
4988+}
4989+
4990+
4991+const std::string& sql_tokenizer::get_randomization_key() const
4992+{
4993+ return _randomization_key;
4994+}
4995+
4996+
4997+void sql_tokenizer::set_randomization_key(const string& new_key)
4998+{
4999+ _randomization_key.assign(new_key);
5000+}
The diff has been truncated for viewing.

Subscribers

People subscribed via source and target branches