drizzle
C++ MySQL-protocol-compatible database server
Loading...
Searching...
No Matches
session.cc
1/* -*- mode: c++; c-basic-offset: 2; indent-tabs-mode: nil; -*-
2 * vim:expandtab:shiftwidth=2:tabstop=2:smarttab:
3 *
4 * Copyright (C) 2008 Sun Microsystems, Inc.
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; version 2 of the License.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18 */
19
23
24#include <config.h>
25
26#include <boost/checked_delete.hpp>
27#include <boost/filesystem.hpp>
28#include <boost/ptr_container/ptr_container.hpp>
29#include <drizzled/copy_field.h>
30#include <drizzled/catalog/local.h>
31#include <drizzled/diagnostics_area.h>
32#include <drizzled/display.h>
33#include <drizzled/drizzled.h>
34#include <drizzled/error.h>
35#include <drizzled/gettext.h>
36#include <drizzled/ha_data.h>
37#include <drizzled/identifier.h>
38#include <drizzled/internal/iocache.h>
39#include <drizzled/internal/thread_var.h>
40#include <drizzled/item/cache.h>
41#include <drizzled/item/empty_string.h>
42#include <drizzled/item/float.h>
43#include <drizzled/item/return_int.h>
44#include <drizzled/item/subselect.h>
45#include <drizzled/lock.h>
46#include <drizzled/open_tables_state.h>
47#include <drizzled/plugin/authentication.h>
48#include <drizzled/plugin/authorization.h>
49#include <drizzled/plugin/client.h>
50#include <drizzled/plugin/event_observer.h>
51#include <drizzled/plugin/logging.h>
52#include <drizzled/plugin/query_rewrite.h>
53#include <drizzled/plugin/scheduler.h>
54#include <drizzled/plugin/transactional_storage_engine.h>
55#include <drizzled/probes.h>
56#include <drizzled/pthread_globals.h>
57#include <drizzled/schema.h>
58#include <drizzled/select_dump.h>
59#include <drizzled/select_exists_subselect.h>
60#include <drizzled/select_export.h>
61#include <drizzled/select_max_min_finder_subselect.h>
62#include <drizzled/select_singlerow_subselect.h>
63#include <drizzled/select_subselect.h>
64#include <drizzled/select_to_file.h>
65#include <drizzled/session.h>
66#include <drizzled/session/cache.h>
67#include <drizzled/session/state.h>
68#include <drizzled/session/table_messages.h>
69#include <drizzled/session/times.h>
70#include <drizzled/session/transactions.h>
71#include <drizzled/show.h>
72#include <drizzled/sql_base.h>
73#include <drizzled/sql_lex.h>
74#include <drizzled/system_variables.h>
75#include <drizzled/statement.h>
76#include <drizzled/statistics_variables.h>
77#include <drizzled/table/singular.h>
78#include <drizzled/table_proto.h>
79#include <drizzled/tmp_table_param.h>
80#include <drizzled/transaction_services.h>
81#include <drizzled/user_var_entry.h>
82#include <drizzled/util/backtrace.h>
83#include <drizzled/util/find_ptr.h>
84#include <drizzled/util/functors.h>
85#include <drizzled/util/storable.h>
86#include <plugin/myisam/myisam.h>
87
88#include <algorithm>
89#include <climits>
90#include <fcntl.h>
91#include <sys/stat.h>
92
93using namespace std;
94
95namespace fs= boost::filesystem;
96
97namespace drizzled {
98
99const char* const Session::DEFAULT_WHERE= "field list";
100
101uint64_t g_refresh_version = 1;
102
103bool Key_part_spec::operator==(const Key_part_spec& other) const
104{
105 return length == other.length
106 && field_name.size() == other.field_name.size()
107 && not system_charset_info->strcasecmp(field_name.data(), other.field_name.data());
108}
109
110Open_tables_state::Open_tables_state(Session& session, uint64_t version_arg) :
111 version(version_arg),
112 session_(session)
113{
114 open_tables_= temporary_tables= derived_tables= NULL;
115 extra_lock= lock= NULL;
116}
117
118/*
119 The following functions form part of the C plugin API
120*/
121int tmpfile(const char *prefix)
122{
123 char filename[FN_REFLEN];
124 int fd = internal::create_temp_file(filename, drizzle_tmpdir.c_str(), prefix, MYF(MY_WME));
125 if (fd >= 0)
126 unlink(filename);
127 return fd;
128}
129
130void **Session::getEngineData(const plugin::MonitoredInTransaction *monitored)
131{
132 return static_cast<void **>(&ha_data[monitored->getId()].ha_ptr);
133}
134
135ResourceContext& Session::getResourceContext(const plugin::MonitoredInTransaction& monitored, size_t index)
136{
137 return ha_data[monitored.getId()].resource_context[index];
138}
139
140int64_t session_test_options(const Session *session, int64_t test_options)
141{
142 return session->options & test_options;
143}
144
146{
147public:
148 typedef std::unordered_map<std::string, util::Storable*, util::insensitive_hash, util::insensitive_equal_to> properties_t;
149 typedef std::map<std::string, plugin::EventObserverList*> schema_event_observers_t;
150
151 impl_c(Session& session) :
152 open_tables(session, g_refresh_version),
153 schema(std::make_shared<std::string>())
154 {
155 }
156
157 ~impl_c()
158 {
159 for (properties_t::reference it : properties)
160 delete it.second;
161 }
162
163 Diagnostics_area diagnostics;
164 memory::Root mem_root;
165
172 LEX lex;
173 Open_tables_state open_tables;
174 properties_t properties;
175 schema_event_observers_t schema_event_observers;
176 system_status_var status_var;
177 session::TableMessages table_message_cache;
178 util::string::mptr schema;
179 std::shared_ptr<session::State> state;
180 boost::ptr_vector<table::Singular> temporary_shares;
181 session::Times times;
182 session::Transactions transaction;
183 drizzle_system_variables variables;
184};
185
186Session::shared_ptr Session::make_shared(plugin::Client *client,
187 std::shared_ptr<catalog::Instance> instance_arg)
188{
189 assert(instance_arg);
190 return std::make_shared<Session>(client, instance_arg);
191}
192
193Session::Session(plugin::Client *client_arg, catalog::Instance::shared_ptr catalog_arg) :
194 impl_(new impl_c(*this)),
195 mem(impl_->mem_root),
196 mem_root(&impl_->mem_root),
197 query(new std::string),
198 scheduler(NULL),
199 variables(impl_->variables),
200 status_var(impl_->status_var),
201 lock_id(&main_lock_id),
202 thread_stack(NULL),
203 _where(Session::DEFAULT_WHERE),
204 mysys_var(0),
205 command(COM_CONNECT),
206 ha_data(plugin::num_trx_monitored_objects),
207 query_id(0),
208 warn_query_id(0),
209 transaction(impl_->transaction),
210 open_tables(impl_->open_tables),
211 times(impl_->times),
212 first_successful_insert_id_in_prev_stmt(0),
213 first_successful_insert_id_in_cur_stmt(0),
214 limit_found_rows(0),
215 options(session_startup_options),
216 row_count_func(-1),
217 sent_row_count(0),
218 examined_row_count(0),
219 used_tables(0),
220 total_warn_count(0),
221 row_count(0),
222 thread_id(0),
223 tmp_table(0),
224 _global_read_lock(NONE),
225 count_cuted_fields(CHECK_FIELD_ERROR_FOR_NULL),
226 _killed(NOT_KILLED),
227 no_errors(false),
228 is_fatal_error(false),
229 transaction_rollback_request(false),
230 is_fatal_sub_stmt_error(0),
231 derived_tables_processing(false),
232 m_lip(NULL),
233 arg_of_last_insert_id_function(false),
234 _catalog(catalog_arg),
235 transaction_message(NULL),
236 statement_message(NULL),
237 session_event_observers(NULL),
238 xa_id(0),
239 concurrent_execute_allowed(true),
240 tablespace_op(false),
241 use_usage(false),
242 security_ctx(identifier::User::make_shared()),
243 originating_server_uuid_set(false),
244 client(client_arg)
245{
246 client->setSession(this);
247
248 /*
249 Pass nominal parameters to init only to ensure that
250 the destructor works OK in case of an error. The main_mem_root
251 will be re-initialized in init_for_queries().
252 */
253 mem.init(memory::ROOT_MIN_BLOCK_SIZE);
255 // Must be reset to handle error with Session's created for init of mysqld
256 lex().current_select= 0;
257 memset(&variables, 0, sizeof(variables));
258 scoreboard_index= -1;
259 originating_server_uuid= "";
260 originating_commit_id= 0;
261 cleanup_done= abort_on_warning= no_warnings_for_error= false;
262
263 resultset= NULL;
264
265 /* Variables with default values */
266 proc_info="login";
267
268 plugin_sessionvar_init(this);
269 /*
270 variables= global_system_variables above has reset
271 variables.pseudo_thread_id to 0. We need to correct it here to
272 avoid temporary tables replication failure.
273 */
274 variables.pseudo_thread_id= thread_id;
275 server_status= SERVER_STATUS_AUTOCOMMIT;
276
277 if (variables.max_join_size == HA_POS_ERROR)
278 options |= OPTION_BIG_SELECTS;
279 else
280 options &= ~OPTION_BIG_SELECTS;
281
282 open_options=ha_open_options;
283 update_lock_default= TL_WRITE;
284 session_tx_isolation= (enum_tx_isolation) variables.tx_isolation;
285 memset(warn_count, 0, sizeof(warn_count));
286 memset(&status_var, 0, sizeof(status_var));
287
288 /* Initialize sub structures */
289 warn_root.init(WARN_ALLOC_BLOCK_SIZE);
290
292 lock_info.init(); /* safety: will be reset after start */
293 main_lock_id.info= &lock_info;
294
295 plugin::EventObserver::registerSessionEvents(*this);
296}
297
298Diagnostics_area& Session::main_da()
299{
300 return impl_->diagnostics;
301}
302
303const LEX& Session::lex() const
304{
305 return impl_->lex;
306}
307
308LEX& Session::lex()
309{
310 return impl_->lex;
311}
312
313enum_sql_command Session::getSqlCommand() const
314{
315 return lex().sql_command;
316}
317
318session::TableMessages& Session::getMessageCache()
319{
320 return impl_->table_message_cache;
321}
322
323void statement::Statement::set_command(enum_sql_command v)
324{
325 session().lex().sql_command= v;
326}
327
328LEX& statement::Statement::lex()
329{
330 return session().lex();
331}
332
333session::Transactions& statement::Statement::transaction()
334{
335 return session().transaction;
336}
337
338void Session::add_item_to_list(Item *item)
339{
340 lex().current_select->add_item_to_list(this, item);
341}
342
343void Session::add_value_to_list(Item *value)
344{
345 lex().value_list.push_back(value);
346}
347
348void Session::add_order_to_list(Item *item, bool asc)
349{
350 lex().current_select->add_order_to_list(this, item, asc);
351}
352
353void Session::add_group_to_list(Item *item, bool asc)
354{
355 lex().current_select->add_group_to_list(this, item, asc);
356}
357
359{
360 /* This works because items are allocated with memory::sql_alloc() */
361 for (Item* next; free_list; free_list= next)
362 {
363 next= free_list->next;
364 free_list->delete_self();
365 }
366}
367
368void Session::setAbort(bool arg)
369{
370 mysys_var->abort= arg;
371}
372
373void Session::lockOnSys()
374{
375 if (not mysys_var)
376 return;
377
378 setAbort(true);
379 boost::mutex::scoped_lock scopedLock(mysys_var->mutex);
380 if (mysys_var->current_cond)
381 {
382 mysys_var->current_mutex->lock();
383 mysys_var->current_cond->notify_all();
384 mysys_var->current_mutex->unlock();
385 }
386}
387
388void Session::get_xid(DrizzleXid *xid) const
389{
390 *xid = *(DrizzleXid *) &transaction.xid_state.xid;
391}
392
393/* Do operations that may take a long time */
394
395void Session::cleanup()
396{
397 assert(not cleanup_done);
398
399 setKilled(KILL_CONNECTION);
400
401 /* In the future, you may want to do something about XA_PREPARED here.
402 In the dim distant past there was some #ifdefed out #error here about it.
403 */
404 TransactionServices::rollbackTransaction(*this, true);
405
406 for (UserVars::reference iter : user_vars)
407 boost::checked_delete(iter.second);
408 user_vars.clear();
409
410 open_tables.close_temporary_tables();
411
412 if (global_read_lock)
413 unlockGlobalReadLock();
414
415 cleanup_done= true;
416}
417
418Session::~Session()
419{
420 if (client and client->isConnected())
421 {
422 assert(security_ctx);
423 if (global_system_variables.log_warnings)
424 {
425 errmsg_printf(error::WARN, ER(ER_FORCING_CLOSE), internal::my_progname, thread_id, security_ctx->username().c_str());
426 }
427
428 disconnect();
429 }
430
431 /* Close connection */
432 if (client)
433 {
434 client->close();
435 boost::checked_delete(client);
436 client= NULL;
437 }
438
439 if (not cleanup_done)
440 cleanup();
441
443 plugin_sessionvar_cleanup(this);
444
445 warn_root.free_root(MYF(0));
446 mysys_var=0; // Safety (shouldn't be needed)
447
448 impl_->mem_root.free_root(MYF(0));
449 setCurrentMemRoot(NULL);
450 setCurrentSession(NULL);
451
452 plugin::Logging::postEndDo(this);
453 plugin::EventObserver::deregisterSessionEvents(session_event_observers);
454
455 for (impl_c::schema_event_observers_t::reference it : impl_->schema_event_observers)
456 plugin::EventObserver::deregisterSchemaEvents(it.second);
457}
458
459void Session::setClient(plugin::Client *client_arg)
460{
461 client= client_arg;
462 client->setSession(this);
463}
464
465void Session::awake(Session::killed_state_t state_to_set)
466{
467 if (state_to_set == Session::KILL_QUERY && command == COM_SLEEP)
468 return;
469
470 setKilled(state_to_set);
471 scheduler->killSession(this);
472
473 if (state_to_set != Session::KILL_QUERY)
474 {
475 DRIZZLE_CONNECTION_DONE(thread_id);
476 }
477
478 if (mysys_var)
479 {
480 boost::mutex::scoped_lock scopedLock(mysys_var->mutex);
481 /*
482 "
483 This broadcast could be up in the air if the victim thread
484 exits the cond in the time between read and broadcast, but that is
485 ok since all we want to do is to make the victim thread get out
486 of waiting on current_cond.
487 If we see a non-zero current_cond: it cannot be an old value (because
488 then exit_cond() should have run and it can't because we have mutex); so
489 it is the true value but maybe current_mutex is not yet non-zero (we're
490 in the middle of enter_cond() and there is a "memory order
491 inversion"). So we test the mutex too to not lock 0.
492
493 Note that there is a small chance we fail to kill. If victim has locked
494 current_mutex, but hasn't yet entered enter_cond() (which means that
495 current_cond and current_mutex are 0), then the victim will not get
496 a signal and it may wait "forever" on the cond (until
497 we issue a second KILL or the status it's waiting for happens).
498 It's true that we have set its session->killed but it may not
499 see it immediately and so may have time to reach the cond_wait().
500 */
501 if (mysys_var->current_cond && mysys_var->current_mutex)
502 {
503 mysys_var->current_mutex->lock();
504 mysys_var->current_cond->notify_all();
505 mysys_var->current_mutex->unlock();
506 }
507 }
508}
509
510/*
511 Remember the location of thread info, the structure needed for
512 memory::sql_alloc() and the structure for the net buffer
513*/
514void Session::storeGlobals()
515{
516 /*
517 Assert that thread_stack is initialized: it's necessary to be able
518 to track stack overrun.
519 */
520 assert(thread_stack);
521 setCurrentSession(this);
522 setCurrentMemRoot(&mem);
523
524 mysys_var= internal::my_thread_var2().get();
525
526 /*
527 Let mysqld define the thread id (not mysys)
528 This allows us to move Session to different threads if needed.
529 */
530 mysys_var->id= thread_id;
531
532 /*
533 We have to call thr_lock_info_init() again here as Session may have been
534 created in another thread
535 */
536 lock_info.init();
537}
538
539/*
540 Init Session for query processing.
541 This has to be called once before we call mysql_parse.
542 See also comments in session.h.
543*/
544
546{
547 if (variables.max_join_size == HA_POS_ERROR)
548 options |= OPTION_BIG_SELECTS;
549
550 open_tables.version= g_refresh_version;
551 set_proc_info(NULL);
552 command= COM_SLEEP;
553 times.set_time();
554
555 mem.reset_defaults(variables.query_alloc_block_size, variables.query_prealloc_size);
556 transaction.xid_state.xid.set_null();
557 transaction.xid_state.in_session=1;
558 if (use_usage)
559 resetUsage();
560}
561
562void Session::run()
563{
564 storeGlobals();
565 if (authenticate())
566 {
567 disconnect();
568 return;
569 }
571 while (not client->haveError() && getKilled() != KILL_CONNECTION)
572 {
573 if (not executeStatement())
574 break;
575 }
576 disconnect();
577}
578
579bool Session::schedule(const shared_ptr& arg)
580{
581 arg->scheduler= plugin::Scheduler::getScheduler();
582 assert(arg->scheduler);
583
584 ++connection_count;
585
586 long current_connections= connection_count;
587
588 if (current_connections > 0 and static_cast<uint64_t>(current_connections) > current_global_counters.max_used_connections)
589 {
590 current_global_counters.max_used_connections= static_cast<uint64_t>(connection_count);
591 }
592
593 current_global_counters.connections++;
594 arg->thread_id= arg->variables.pseudo_thread_id= global_thread_id++;
595
596 session::Cache::insert(arg);
597
598 if (DRIZZLE_UNLIKELY(plugin::EventObserver::connectSession(*arg)))
599 {
600 // We should do something about an error...
601 }
602
603 if (plugin::Scheduler::getScheduler()->addSession(arg))
604 {
605 DRIZZLE_CONNECTION_START(arg->getSessionId());
606 char error_message_buff[DRIZZLE_ERRMSG_SIZE];
607
608 arg->setKilled(Session::KILL_CONNECTION);
609
610 arg->status_var.aborted_connects++;
611
612 /* Can't use my_error() since store_globals has not been called. */
613 /* TODO replace will better error message */
614 snprintf(error_message_buff, sizeof(error_message_buff), ER(ER_CANT_CREATE_THREAD), 1);
615 arg->client->sendError(ER_CANT_CREATE_THREAD, error_message_buff);
616 return true;
617 }
618 return false;
619}
620
621
622/*
623 Is this session viewable by the current user?
624*/
625bool Session::isViewable(const identifier::User& user_arg) const
626{
627 return plugin::Authorization::isAuthorized(user_arg, *this, false);
628}
629
630
631const char* Session::enter_cond(boost::condition_variable_any &cond, boost::mutex &mutex, const char* msg)
632{
633 const char* old_msg = get_proc_info();
634 safe_mutex_assert_owner(mutex);
635 mysys_var->current_mutex = &mutex;
636 mysys_var->current_cond = &cond;
637 this->set_proc_info(msg);
638 return old_msg;
639}
640
641void Session::exit_cond(const char* old_msg)
642{
643 /*
644 Putting the mutex unlock in exit_cond() ensures that
645 mysys_var->current_mutex is always unlocked _before_ mysys_var->mutex is
646 locked (if that would not be the case, you'll get a deadlock if someone
647 does a Session::awake() on you).
648 */
649 mysys_var->current_mutex->unlock();
650 boost::mutex::scoped_lock scopedLock(mysys_var->mutex);
651 mysys_var->current_mutex = 0;
652 mysys_var->current_cond = 0;
653 this->set_proc_info(old_msg);
654}
655
657{
658 if (client->authenticate())
659 return false;
660
661 status_var.aborted_connects++;
662
663 return true;
664}
665
666bool Session::checkUser(const std::string &passwd_str, const std::string &in_db)
667{
668 if (not plugin::Authentication::isAuthenticated(*user(), passwd_str))
669 {
670 status_var.access_denied++;
671 /* isAuthenticated has pushed the error message */
672 return false;
673 }
674
675 /* Change database if necessary */
676 if (not in_db.empty() && schema::change(*this, identifier::Schema(catalog().identifier(), in_db)))
677 return false; // change() has pushed the error message
678 my_ok();
679
680 /* Ready to handle queries */
681 return true;
682}
683
685{
686 /*
687 indicator of uninitialized lex => normal flow of errors handling
688 (see my_message_sql)
689 */
690 lex().current_select= 0;
691 clear_error();
692 main_da().reset_diagnostics_area();
693 char *l_packet= 0;
694 uint32_t packet_length;
695 if (not client->readCommand(&l_packet, packet_length))
696 return false;
697
698 if (getKilled() == KILL_CONNECTION)
699 return false;
700
701 if (packet_length == 0)
702 return true;
703
704 enum_server_command l_command= static_cast<enum_server_command>(l_packet[0]);
705
706 if (command >= COM_END)
707 command= COM_END; // Wrong command
708
709 assert(packet_length);
710 return not dispatch_command(l_command, *this, str_ref(l_packet + 1, packet_length - 1));
711}
712
714{
715 /* Remove garbage at start and end of query */
716 while (not v.empty() && charset()->isspace(v.front()))
717 v.pop_front();
718 while (not v.empty() && (v.back() == ';' || charset()->isspace(v.back())))
719 v.pop_back();
720
721 util::string::mptr new_query= std::make_shared<std::string>(v.data(), v.size());
722 plugin::QueryRewriter::rewriteQuery(*impl_->schema, *new_query);
723 query= new_query;
724 impl_->state= std::make_shared<session::State>(v);
725}
726
727bool Session::endTransaction(enum_mysql_completiontype completion)
728{
729 bool do_release= 0;
730 bool result= true;
731
732 if (transaction.xid_state.xa_state != XA_NOTR)
733 {
734 my_error(ER_XAER_RMFAIL, MYF(0), xa_state_names[transaction.xid_state.xa_state]);
735 return false;
736 }
737 switch (completion)
738 {
739 case COMMIT:
740 /*
741 * We don't use endActiveTransaction() here to ensure that this works
742 * even if there is a problem with the OPTION_AUTO_COMMIT flag
743 * (Which of course should never happen...)
744 */
745 server_status&= ~SERVER_STATUS_IN_TRANS;
747 result= false;
748 options&= ~(OPTION_BEGIN);
749 break;
750 case COMMIT_RELEASE:
751 do_release= 1; /* fall through */
752 case COMMIT_AND_CHAIN:
753 result= endActiveTransaction();
754 if (result == true && completion == COMMIT_AND_CHAIN)
755 result= startTransaction();
756 break;
757 case ROLLBACK_RELEASE:
758 do_release= 1; /* fall through */
759 case ROLLBACK:
760 case ROLLBACK_AND_CHAIN:
761 {
762 server_status&= ~SERVER_STATUS_IN_TRANS;
763 if (TransactionServices::rollbackTransaction(*this, true))
764 result= false;
765 options&= ~(OPTION_BEGIN);
766 if (result == true && (completion == ROLLBACK_AND_CHAIN))
767 result= startTransaction();
768 break;
769 }
770 default:
771 my_error(ER_UNKNOWN_COM_ERROR, MYF(0));
772 return false;
773 }
774
775 if (not result)
776 {
777 my_error(static_cast<drizzled::error_t>(killed_errno()), MYF(0));
778 }
779 else if (result && do_release)
780 {
781 setKilled(Session::KILL_CONNECTION);
782 }
783
784 return result;
785}
786
787bool Session::endActiveTransaction()
788{
789 bool result= true;
790
791 if (transaction.xid_state.xa_state != XA_NOTR)
792 {
793 my_error(ER_XAER_RMFAIL, MYF(0), xa_state_names[transaction.xid_state.xa_state]);
794 return false;
795 }
796 if (options & (OPTION_NOT_AUTOCOMMIT | OPTION_BEGIN))
797 {
798 server_status&= ~SERVER_STATUS_IN_TRANS;
800 result= false;
801 }
802 options&= ~(OPTION_BEGIN);
803 return result;
804}
805
806bool Session::startTransaction(start_transaction_option_t opt)
807{
808 assert(not inTransaction());
809
810 options|= OPTION_BEGIN;
811 server_status|= SERVER_STATUS_IN_TRANS;
812
814 return false;
815 return true;
816}
817
819{
820 /*
821 Reset rand_used so that detection of calls to rand() will save random
822 seeds if needed by the slave.
823 */
825 {
826 /* set what LAST_INSERT_ID() will return */
830 }
831
832 arg_of_last_insert_id_function= false;
833
834 /* Free Items that were created during this execution */
835 free_items();
836
837 /* Reset _where. */
839
840 /* Reset the temporary shares we built */
841 impl_->temporary_shares.clear();
842}
843
855{
856 if (not lex_str)
857 lex_str= new (mem) lex_string_t;
858 lex_str->assign(mem_root->strdup(str), str.size());
859 return lex_str;
860}
861
862void Session::send_explain_fields(select_result *result)
863{
864 List<Item> field_list;
865 Item *item;
866 const charset_info_st* cs= system_charset_info;
867 field_list.push_back(new Item_return_int("id",3, DRIZZLE_TYPE_LONGLONG));
868 field_list.push_back(new Item_empty_string("select_type", 19, cs));
869 field_list.push_back(item= new Item_empty_string("table", NAME_CHAR_LEN, cs));
870 item->maybe_null= 1;
871 field_list.push_back(item= new Item_empty_string("type", 10, cs));
872 item->maybe_null= 1;
873 field_list.push_back(item= new Item_empty_string("possible_keys", NAME_CHAR_LEN*MAX_KEY, cs));
874 item->maybe_null=1;
875 field_list.push_back(item= new Item_empty_string("key", NAME_CHAR_LEN, cs));
876 item->maybe_null=1;
877 field_list.push_back(item= new Item_empty_string("key_len", MAX_KEY * (MAX_KEY_LENGTH_DECIMAL_WIDTH + 1 /* for comma */), cs));
878 item->maybe_null=1;
879 field_list.push_back(item= new Item_empty_string("ref", NAME_CHAR_LEN*MAX_REF_PARTS, cs));
880 item->maybe_null=1;
881 field_list.push_back(item= new Item_return_int("rows", 10, DRIZZLE_TYPE_LONGLONG));
882 if (lex().describe & DESCRIBE_EXTENDED)
883 {
884 field_list.push_back(item= new Item_float("filtered", 0.1234, 2, 4));
885 item->maybe_null=1;
886 }
887 item->maybe_null= 1;
888 field_list.push_back(new Item_empty_string("Extra", 255, cs));
889 result->send_fields(field_list);
890}
891
892void select_result::send_error(drizzled::error_t errcode, const char *err)
893{
894 my_message(errcode, err, MYF(0));
895}
896
897/************************************************************************
898 Handling writing to file
899************************************************************************/
900
901void select_to_file::send_error(drizzled::error_t errcode,const char *err)
902{
903 my_message(errcode, err, MYF(0));
904 if (file > 0)
905 {
906 (void) cache->end_io_cache();
907 (void) internal::my_close(file, MYF(0));
908 (void) internal::my_delete(path.string().c_str(), MYF(0)); // Delete file on error
909 file= -1;
910 }
911}
912
913
914bool select_to_file::send_eof()
915{
916 int error= test(cache->end_io_cache());
917 if (internal::my_close(file, MYF(MY_WME)))
918 error= 1;
919 if (!error)
920 {
921 /*
922 In order to remember the value of affected rows for ROW_COUNT()
923 function, SELECT INTO has to have an own SQLCOM.
924 TODO: split from SQLCOM_SELECT
925 */
926 session->my_ok(row_count);
927 }
928 file= -1;
929 return error;
930}
931
932
933void select_to_file::cleanup()
934{
935 /* In case of error send_eof() may be not called: close the file here. */
936 if (file >= 0)
937 {
938 (void) cache->end_io_cache();
939 (void) internal::my_close(file, MYF(0));
940 file= -1;
941 }
942 path= "";
943 row_count= 0;
944}
945
946select_to_file::select_to_file(file_exchange *ex)
947 : exchange(ex),
948 file(-1),
949 cache(static_cast<internal::io_cache_st *>(memory::sql_calloc(sizeof(internal::io_cache_st)))),
950 row_count(0L)
951{
952 path= "";
953}
954
955select_to_file::~select_to_file()
956{
957 cleanup();
958}
959
960/***************************************************************************
961** Export of select to textfile
962***************************************************************************/
963
964select_export::~select_export()
965{
966 session->sent_row_count=row_count;
967}
968
969
970/*
971 Create file with IO cache
972
973 SYNOPSIS
974 create_file()
975 session Thread handle
976 path File name
977 exchange Excange class
978 cache IO cache
979
980 RETURN
981 >= 0 File handle
982 -1 Error
983*/
984
985
986static int create_file(Session& session,
987 fs::path &target_path,
988 file_exchange *exchange,
990{
991 fs::path to_file(exchange->file_name);
992
993 if (not to_file.has_root_directory())
994 {
995 target_path= fs::system_complete(catalog::local_identifier().getPath());
996 util::string::ptr schema(session.schema());
997 if (not schema->empty())
998 {
999 int count_elements= 0;
1000 for (fs::path::iterator it= to_file.begin(); it != to_file.end(); it++)
1001 count_elements++;
1002 if (count_elements == 1)
1003 target_path /= *schema;
1004 }
1005 target_path /= to_file;
1006 }
1007 else
1008 {
1009 target_path = exchange->file_name;
1010 }
1011
1012 if (not secure_file_priv.string().empty())
1013 {
1014 if (target_path.string().substr(0, secure_file_priv.string().size()) != secure_file_priv.string())
1015 {
1016 /* Write only allowed to dir or subdir specified by secure_file_priv */
1017 my_error(ER_OPTION_PREVENTS_STATEMENT, MYF(0), "--secure-file-priv");
1018 return -1;
1019 }
1020 }
1021
1022 if (!access(target_path.string().c_str(), F_OK))
1023 {
1024 my_error(ER_FILE_EXISTS_ERROR, MYF(0), exchange->file_name);
1025 return -1;
1026 }
1027 /* Create the file world readable */
1028 int file= internal::my_create(target_path.string().c_str(), 0666, O_WRONLY|O_EXCL, MYF(MY_WME));
1029 if (file < 0)
1030 return file;
1031 (void) fchmod(file, 0666); // Because of umask()
1032 if (cache->init_io_cache(file, 0, internal::WRITE_CACHE, 0L, 1, MYF(MY_WME)))
1033 {
1034 internal::my_close(file, MYF(0));
1035 internal::my_delete(target_path.string().c_str(), MYF(0)); // Delete file on error, it was just created
1036 return -1;
1037 }
1038 return file;
1039}
1040
1041
1042int
1043select_export::prepare(List<Item> &list, Select_Lex_Unit *u)
1044{
1045 bool blob_flag=0;
1046 bool string_results= false, non_string_results= false;
1047 unit= u;
1048 if ((uint32_t) strlen(exchange->file_name) + NAME_LEN >= FN_REFLEN)
1049 {
1050 path= exchange->file_name;
1051 }
1052
1053 /* Check if there is any blobs in data */
1054 {
1055 List<Item>::iterator li(list.begin());
1056 while (Item* item= li++)
1057 {
1058 if (item->max_length >= MAX_BLOB_WIDTH)
1059 {
1060 blob_flag=1;
1061 break;
1062 }
1063
1064 if (item->result_type() == STRING_RESULT)
1065 string_results= true;
1066 else
1067 non_string_results= true;
1068 }
1069 }
1070 field_term_length=exchange->field_term->length();
1071 field_term_char= field_term_length ?
1072 (int) (unsigned char) (*exchange->field_term)[0] : INT_MAX;
1073 if (!exchange->line_term->length())
1074 exchange->line_term=exchange->field_term; // Use this if it exists
1075 field_sep_char= exchange->enclosed->length() ? (int) (unsigned char) (*exchange->enclosed)[0] : field_term_char;
1076 escape_char= exchange->escaped->length() ? (int) (unsigned char) (*exchange->escaped)[0] : -1;
1077 is_ambiguous_field_sep= test(strchr(ESCAPE_CHARS, field_sep_char));
1078 is_unsafe_field_sep= test(strchr(NUMERIC_CHARS, field_sep_char));
1079 line_sep_char= exchange->line_term->length() ? (int) (unsigned char) (*exchange->line_term)[0] : INT_MAX;
1080 if (!field_term_length)
1081 exchange->opt_enclosed=0;
1082 if (!exchange->enclosed->length())
1083 exchange->opt_enclosed=1; // A little quicker loop
1084 fixed_row_size= (!field_term_length && !exchange->enclosed->length() &&
1085 !blob_flag);
1086 if ((is_ambiguous_field_sep && exchange->enclosed->empty() && (string_results || is_unsafe_field_sep)) ||
1087 (exchange->opt_enclosed && non_string_results && field_term_length && strchr(NUMERIC_CHARS, field_term_char)))
1088 {
1089 my_error(ER_AMBIGUOUS_FIELD_TERM, MYF(0));
1090 return 1;
1091 }
1092
1093 if ((file= create_file(*session, path, exchange, cache)) < 0)
1094 return 1;
1095
1096 return 0;
1097}
1098
1099bool select_export::send_data(List<Item> &items)
1100{
1101 char buff[MAX_FIELD_WIDTH],null_buff[2],space[MAX_FIELD_WIDTH];
1102 bool space_inited=0;
1103 String tmp(buff,sizeof(buff),&my_charset_bin),*res;
1104 tmp.length(0);
1105
1106 if (unit->offset_limit_cnt)
1107 { // using limit offset,count
1108 unit->offset_limit_cnt--;
1109 return false;
1110 }
1111 row_count++;
1112 uint32_t used_length=0,items_left=items.size();
1113 List<Item>::iterator li(items.begin());
1114
1115 if (cache->write(exchange->line_start->ptr(), exchange->line_start->length()))
1116 return true;
1117
1118 while (Item* item=li++)
1119 {
1120 Item_result result_type=item->result_type();
1121 bool enclosed = (exchange->enclosed->length() &&
1122 (!exchange->opt_enclosed || result_type == STRING_RESULT));
1123 res=item->str_result(&tmp);
1124 if (res && enclosed)
1125 {
1126 if (cache->write(exchange->enclosed->ptr(), exchange->enclosed->length()))
1127 return true;
1128 }
1129 if (!res)
1130 { // NULL
1131 if (!fixed_row_size)
1132 {
1133 if (escape_char != -1) // Use \N syntax
1134 {
1135 null_buff[0]=escape_char;
1136 null_buff[1]='N';
1137 if (cache->write(null_buff, 2))
1138 return true;
1139 }
1140 else if (cache->write("NULL", 4))
1141 return true;
1142 }
1143 else
1144 {
1145 used_length=0; // Fill with space
1146 }
1147 }
1148 else
1149 {
1150 if (fixed_row_size)
1151 used_length= min(res->length(), static_cast<size_t>(item->max_length));
1152 else
1153 used_length= res->length();
1154
1155 if ((result_type == STRING_RESULT || is_unsafe_field_sep) &&
1156 escape_char != -1)
1157 {
1158 char *pos, *start, *end;
1159 const charset_info_st* const res_charset= res->charset();
1160
1161 for (start= pos= (char*) res->ptr(),end=pos+used_length; pos != end; pos++)
1162 {
1163 if (use_mb(res_charset))
1164 {
1165 if (int l= my_ismbchar(res_charset, pos, end))
1166 {
1167 pos += l - 1;
1168 continue;
1169 }
1170 }
1171
1172 /*
1173 Special case when dumping BINARY/VARBINARY/BLOB values
1174 for the clients with character sets big5, cp932, gbk and sjis,
1175 which can have the escape character (0x5C "\" by default)
1176 as the second byte of a multi-byte sequence.
1177
1178 If
1179 - pos[0] is a valid multi-byte head (e.g 0xEE) and
1180 - pos[1] is 0x00, which will be escaped as "\0",
1181
1182 then we'll get "0xEE + 0x5C + 0x30" in the output file.
1183
1184 If this file is later loaded using this sequence of commands:
1185
1186 mysql> create table t1 (a varchar(128)) character set big5;
1187 mysql> LOAD DATA INFILE 'dump.txt' INTO Table t1;
1188
1189 then 0x5C will be misinterpreted as the second byte
1190 of a multi-byte character "0xEE + 0x5C", instead of
1191 escape character for 0x00.
1192
1193 To avoid this confusion, we'll escape the multi-byte
1194 head character too, so the sequence "0xEE + 0x00" will be
1195 dumped as "0x5C + 0xEE + 0x5C + 0x30".
1196
1197 Note, in the condition below we only check if
1198 mbcharlen is equal to 2, because there are no
1199 character sets with mbmaxlen longer than 2
1200 and with escape_with_backslash_is_dangerous set.
1201 assert before the loop makes that sure.
1202 */
1203
1204 if (needs_escaping(*pos, enclosed) &&
1205 /*
1206 Don't escape field_term_char by doubling - doubling is only
1207 valid for ENCLOSED BY characters:
1208 */
1209 (enclosed || !is_ambiguous_field_term ||
1210 (int) (unsigned char) *pos != field_term_char))
1211 {
1212 char tmp_buff[2];
1213 tmp_buff[0]= ((int) (unsigned char) *pos == field_sep_char &&
1214 is_ambiguous_field_sep) ? field_sep_char : escape_char;
1215 tmp_buff[1]= *pos ? *pos : '0';
1216 if (cache->write(start, pos - start) || cache->write(tmp_buff, 2))
1217 return true;
1218 start=pos+1;
1219 }
1220 }
1221 if (cache->write(start, pos - start))
1222 return true;
1223 }
1224 else if (cache->write(res->ptr(), used_length))
1225 return true;
1226 }
1227 if (fixed_row_size)
1228 { // Fill with space
1229 if (item->max_length > used_length)
1230 {
1231 /* QQ: Fix by adding a my_b_fill() function */
1232 if (!space_inited)
1233 {
1234 space_inited=1;
1235 memset(space, ' ', sizeof(space));
1236 }
1237 uint32_t length=item->max_length-used_length;
1238 for (; length > sizeof(space) ; length-=sizeof(space))
1239 {
1240 if (cache->write(space, sizeof(space)))
1241 return true;
1242 }
1243 if (cache->write(space, length))
1244 return true;
1245 }
1246 }
1247 if (res && enclosed)
1248 {
1249 if (cache->write(exchange->enclosed->ptr(), exchange->enclosed->length()))
1250 return true;
1251 }
1252 if (--items_left)
1253 {
1254 if (cache->write(exchange->field_term->ptr(), field_term_length))
1255 return true;
1256 }
1257 }
1258 if (cache->write(exchange->line_term->ptr(), exchange->line_term->length()))
1259 {
1260 return true;
1261 }
1262
1263 return false;
1264}
1265
1266
1267/***************************************************************************
1268** Dump of select to a binary file
1269***************************************************************************/
1270
1271
1272int
1273select_dump::prepare(List<Item> &, Select_Lex_Unit *u)
1274{
1275 unit= u;
1276 return (file= create_file(*session, path, exchange, cache)) < 0;
1277}
1278
1279
1280bool select_dump::send_data(List<Item> &items)
1281{
1282 List<Item>::iterator li(items.begin());
1283 char buff[MAX_FIELD_WIDTH];
1284 String tmp(buff,sizeof(buff),&my_charset_bin),*res;
1285 tmp.length(0);
1286
1287 if (unit->offset_limit_cnt)
1288 { // using limit offset,count
1289 unit->offset_limit_cnt--;
1290 return 0;
1291 }
1292 if (row_count++ > 1)
1293 {
1294 my_message(ER_TOO_MANY_ROWS, ER(ER_TOO_MANY_ROWS), MYF(0));
1295 return 1;
1296 }
1297 while (Item* item=li++)
1298 {
1299 res=item->str_result(&tmp);
1300 if (!res) // If NULL
1301 {
1302 if (cache->write("", 1))
1303 return 1;
1304 }
1305 else if (cache->write(res->ptr(), res->length()))
1306 {
1307 my_error(ER_ERROR_ON_WRITE, MYF(0), path.string().c_str(), errno);
1308 return 1;
1309 }
1310 }
1311 return 0;
1312}
1313
1314
1315select_subselect::select_subselect(Item_subselect *item_arg)
1316{
1317 item= item_arg;
1318}
1319
1320
1321bool select_singlerow_subselect::send_data(List<Item> &items)
1322{
1323 Item_singlerow_subselect *it= (Item_singlerow_subselect *)item;
1324 if (it->assigned())
1325 {
1326 my_message(ER_SUBQUERY_NO_1_ROW, ER(ER_SUBQUERY_NO_1_ROW), MYF(0));
1327 return 1;
1328 }
1329 if (unit->offset_limit_cnt)
1330 { // Using limit offset,count
1331 unit->offset_limit_cnt--;
1332 return 0;
1333 }
1334 List<Item>::iterator li(items.begin());
1335 Item *val_item;
1336 for (uint32_t i= 0; (val_item= li++); i++)
1337 it->store(i, val_item);
1338 it->assigned(1);
1339 return 0;
1340}
1341
1342
1343void select_max_min_finder_subselect::cleanup()
1344{
1345 cache= 0;
1346}
1347
1348
1349bool select_max_min_finder_subselect::send_data(List<Item> &items)
1350{
1351 Item_maxmin_subselect *it= (Item_maxmin_subselect *)item;
1352 List<Item>::iterator li(items.begin());
1353 Item *val_item= li++;
1354 it->register_value();
1355 if (it->assigned())
1356 {
1357 cache->store(val_item);
1358 if ((this->*op)())
1359 it->store(0, cache);
1360 }
1361 else
1362 {
1363 if (!cache)
1364 {
1365 cache= Item_cache::get_cache(val_item);
1366 switch (val_item->result_type())
1367 {
1368 case REAL_RESULT:
1369 op= &select_max_min_finder_subselect::cmp_real;
1370 break;
1371 case INT_RESULT:
1372 op= &select_max_min_finder_subselect::cmp_int;
1373 break;
1374 case STRING_RESULT:
1375 op= &select_max_min_finder_subselect::cmp_str;
1376 break;
1377 case DECIMAL_RESULT:
1378 op= &select_max_min_finder_subselect::cmp_decimal;
1379 break;
1380 case ROW_RESULT:
1381 // This case should never be choosen
1382 assert(0);
1383 op= 0;
1384 }
1385 }
1386 cache->store(val_item);
1387 it->store(0, cache);
1388 }
1389 it->assigned(1);
1390 return 0;
1391}
1392
1393bool select_max_min_finder_subselect::cmp_real()
1394{
1395 Item *maxmin= ((Item_singlerow_subselect *)item)->element_index(0);
1396 double val1= cache->val_real(), val2= maxmin->val_real();
1397 if (fmax)
1398 return (cache->null_value && !maxmin->null_value) ||
1399 (!cache->null_value && !maxmin->null_value &&
1400 val1 > val2);
1401 return (maxmin->null_value && !cache->null_value) ||
1402 (!cache->null_value && !maxmin->null_value &&
1403 val1 < val2);
1404}
1405
1406bool select_max_min_finder_subselect::cmp_int()
1407{
1408 Item *maxmin= ((Item_singlerow_subselect *)item)->element_index(0);
1409 int64_t val1= cache->val_int(), val2= maxmin->val_int();
1410 if (fmax)
1411 return (cache->null_value && !maxmin->null_value) ||
1412 (!cache->null_value && !maxmin->null_value &&
1413 val1 > val2);
1414 return (maxmin->null_value && !cache->null_value) ||
1415 (!cache->null_value && !maxmin->null_value &&
1416 val1 < val2);
1417}
1418
1419bool select_max_min_finder_subselect::cmp_decimal()
1420{
1421 Item *maxmin= ((Item_singlerow_subselect *)item)->element_index(0);
1422 type::Decimal cval, *cvalue= cache->val_decimal(&cval);
1423 type::Decimal mval, *mvalue= maxmin->val_decimal(&mval);
1424 if (fmax)
1425 return (cache->null_value && !maxmin->null_value) ||
1426 (!cache->null_value && !maxmin->null_value &&
1427 class_decimal_cmp(cvalue, mvalue) > 0) ;
1428 return (maxmin->null_value && !cache->null_value) ||
1429 (!cache->null_value && !maxmin->null_value &&
1430 class_decimal_cmp(cvalue,mvalue) < 0);
1431}
1432
1433bool select_max_min_finder_subselect::cmp_str()
1434{
1435 String *val1, *val2, buf1, buf2;
1436 Item *maxmin= ((Item_singlerow_subselect *)item)->element_index(0);
1437 /*
1438 as far as both operand is Item_cache buf1 & buf2 will not be used,
1439 but added for safety
1440 */
1441 val1= cache->val_str(&buf1);
1442 val2= maxmin->val_str(&buf1);
1443 if (fmax)
1444 return (cache->null_value && !maxmin->null_value) ||
1445 (!cache->null_value && !maxmin->null_value &&
1446 sortcmp(val1, val2, cache->collation.collation) > 0) ;
1447 return (maxmin->null_value && !cache->null_value) ||
1448 (!cache->null_value && !maxmin->null_value &&
1449 sortcmp(val1, val2, cache->collation.collation) < 0);
1450}
1451
1452bool select_exists_subselect::send_data(List<Item> &)
1453{
1454 Item_exists_subselect *it= (Item_exists_subselect *)item;
1455 if (unit->offset_limit_cnt)
1456 { // Using limit offset,count
1457 unit->offset_limit_cnt--;
1458 return 0;
1459 }
1460 it->value= 1;
1461 it->assigned(1);
1462 return 0;
1463}
1464
1465/*
1466 Don't free mem_root, as mem_root is freed in the end of dispatch_command
1467 (once for any command).
1468*/
1470{
1471 /* Cleanup SQL processing state to reuse this statement in next query. */
1472 lex().end();
1474}
1475
1476str_ref Session::copy_db_to() const
1477{
1478 if (not impl_->schema->empty())
1479 return str_ref(mem.strdup(*impl_->schema), impl_->schema->size());
1480 my_message(ER_NO_DB_ERROR, ER(ER_NO_DB_ERROR), MYF(0));
1481 return str_ref();
1482}
1483
1484/****************************************************************************
1485 Tmp_Table_Param
1486****************************************************************************/
1487
1488void Tmp_Table_Param::init()
1489{
1490 field_count= sum_func_count= func_count= hidden_field_count= 0;
1491 group_parts= group_length= group_null_parts= 0;
1492 quick_group= 1;
1493 table_charset= 0;
1494 precomputed_group_by= 0;
1495}
1496
1497void Tmp_Table_Param::cleanup()
1498{
1499 /* Fix for Intel compiler */
1500 if (copy_field)
1501 {
1502 boost::checked_array_delete(copy_field);
1503 save_copy_field= save_copy_field_end= copy_field= copy_field_end= 0;
1504 }
1505}
1506
1507void Session::send_kill_message() const
1508{
1509 drizzled::error_t err= static_cast<drizzled::error_t>(killed_errno());
1510 if (err != EE_OK)
1511 my_message(err, ER(err), MYF(0));
1512}
1513
1514void Session::set_schema(const std::string& new_db)
1515{
1516 impl_->schema = std::make_shared<std::string>(new_db);
1517}
1518
1519
1531
1532void Session::disconnect(error_t errcode)
1533{
1534 /* Allow any plugins to cleanup their session variables */
1535 plugin_sessionvar_cleanup(this);
1536
1537 /* If necessary, log any aborted or unauthorized connections */
1538 if (getKilled() || client->wasAborted())
1539 {
1540 status_var.aborted_threads++;
1541 }
1542
1543 if (client->wasAborted())
1544 {
1545 if (not getKilled() && variables.log_warnings)
1546 {
1547 errmsg_printf(error::WARN, ER(ER_NEW_ABORTING_CONNECTION)
1548 , thread_id
1549 , (impl_->schema->empty() ? "unconnected" : impl_->schema->c_str())
1550 , security_ctx->username().empty() ? "unauthenticated" : security_ctx->username().c_str()
1551 , security_ctx->address().c_str()
1552 , (main_da().is_error() ? main_da().message() : ER(ER_UNKNOWN_ERROR)));
1553 }
1554 }
1555
1556 setKilled(Session::KILL_CONNECTION);
1557
1558 if (client->isConnected())
1559 {
1560 if (errcode != EE_OK)
1561 {
1562 /*my_error(errcode, ER(errcode));*/
1563 client->sendError(errcode, ER(errcode));
1564 }
1565 client->close();
1566 }
1567}
1568
1570{
1571 free_list= 0;
1572 select_number= 1;
1573
1574 is_fatal_error= false;
1575 server_status&= ~ (SERVER_MORE_RESULTS_EXISTS |
1576 SERVER_QUERY_NO_INDEX_USED |
1577 SERVER_QUERY_NO_GOOD_INDEX_USED);
1578
1579 clear_error();
1580 main_da().reset_diagnostics_area();
1581 total_warn_count=0; // Warnings for this query
1583}
1584
1585/*
1586 Close all temporary tables created by 'CREATE TEMPORARY TABLE' for thread
1587*/
1588
1589void Open_tables_state::close_temporary_tables()
1590{
1591 Table *table;
1592 Table *tmp_next;
1593
1594 if (not temporary_tables)
1595 return;
1596
1597 for (table= temporary_tables; table; table= tmp_next)
1598 {
1599 tmp_next= table->getNext();
1600 nukeTable(table);
1601 }
1602 temporary_tables= NULL;
1603}
1604
1605/*
1606 unlink from session->temporary tables and close temporary table
1607*/
1608
1609void Open_tables_state::close_temporary_table(Table *table)
1610{
1611 if (table->getPrev())
1612 {
1613 table->getPrev()->setNext(table->getNext());
1614 if (table->getPrev()->getNext())
1615 {
1616 table->getNext()->setPrev(table->getPrev());
1617 }
1618 }
1619 else
1620 {
1621 /* removing the item from the list */
1622 assert(table == temporary_tables);
1623 /*
1624 slave must reset its temporary list pointer to zero to exclude
1625 passing non-zero value to end_slave via rli->save_temporary_tables
1626 when no temp tables opened, see an invariant below.
1627 */
1628 temporary_tables= table->getNext();
1629 if (temporary_tables)
1630 {
1631 table->getNext()->setPrev(NULL);
1632 }
1633 }
1634 nukeTable(table);
1635}
1636
1637/*
1638 Close and drop a temporary table
1639
1640 NOTE
1641 This dosn't unlink table from session->temporary
1642 If this is needed, use close_temporary_table()
1643*/
1644
1645void Open_tables_state::nukeTable(Table *table)
1646{
1647 plugin::StorageEngine& table_type= *table->getShare()->db_type();
1648 table->free_io_cache();
1649 table->delete_table();
1650 rm_temporary_table(table_type, identifier::Table(table->getShare()->getTableIdentifier().getCatalog(), table->getShare()->getSchemaName(), table->getShare()->getTableName(), table->getShare()->getPath()));
1651 boost::checked_delete(table->getMutableShare());
1652 boost::checked_delete(table);
1653}
1654
1656extern time_t flush_status_time;
1657
1658void Session::refresh_status()
1659{
1660 /* Reset thread's status variables */
1661 memset(&status_var, 0, sizeof(status_var));
1662
1663 flush_status_time= time((time_t*) 0);
1664 current_global_counters.max_used_connections= 1; /* We set it to one, because we know we exist */
1665 current_global_counters.connections= 0;
1666}
1667
1668user_var_entry* Session::getVariable(str_ref name0, bool create_if_not_exists)
1669{
1670 if (cleanup_done)
1671 return NULL;
1672
1673 string name(name0.data(), name0.size());
1674 if (UserVars::mapped_type* iter= find_ptr(user_vars, name))
1675 return *iter;
1676
1677 if (not create_if_not_exists)
1678 return NULL;
1679
1680 user_var_entry *entry= new user_var_entry(name.c_str(), query_id);
1681
1682 std::pair<UserVars::iterator, bool> returnable= user_vars.insert(make_pair(name, entry));
1683
1684 if (not returnable.second)
1685 {
1686 boost::checked_delete(entry);
1687 }
1688
1689 return entry;
1690}
1691
1692void Session::setVariable(const std::string &name, const std::string &value)
1693{
1694 if (user_var_entry* var= getVariable(name, true))
1695 {
1696 var->update_hash(false, value, STRING_RESULT, &my_charset_bin, DERIVATION_IMPLICIT, false);
1697 }
1698}
1699
1701{
1702 for (Table *table= temporary_tables ; table ; table= table->getNext())
1703 {
1704 if (table->query_id == session_.getQueryId())
1705 {
1706 table->query_id= 0;
1707 table->cursor->ha_reset();
1708 }
1709 }
1710}
1711
1712/*
1713 Unlocks tables and frees derived tables.
1714 Put all normal tables used by thread in free list.
1715
1716 It will only close/mark as free for reuse tables opened by this
1717 substatement, it will also check if we are closing tables after
1718 execution of complete query (i.e. we are on upper level) and will
1719 leave prelocked mode if needed.
1720*/
1722{
1723 open_tables.clearDerivedTables();
1724
1725 /*
1726 Mark all temporary tables used by this statement as free for reuse.
1727 */
1728 open_tables.mark_temp_tables_as_free_for_reuse();
1729 /*
1730 Let us commit transaction for statement. Since in 5.0 we only have
1731 one statement transaction and don't allow several nested statement
1732 transactions this call will do nothing if we are inside of stored
1733 function or trigger (i.e. statement transaction is already active and
1734 does not belong to statement for which we do close_thread_tables()).
1735 TODO: This should be fixed in later releases.
1736 */
1737 {
1738 main_da().can_overwrite_status= true;
1740 main_da().can_overwrite_status= false;
1741 transaction.stmt.reset();
1742 }
1743
1744 if (open_tables.lock)
1745 {
1746 unlockTables(open_tables.lock);
1747 open_tables.lock= 0;
1748 }
1749 /*
1750 Note that we need to hold table::Cache::mutex() while changing the
1751 open_tables list. Another thread may work on it.
1752 (See: table::Cache::removeTable(), wait_completed_table())
1753 Closing a MERGE child before the parent would be fatal if the
1754 other thread tries to abort the MERGE lock in between.
1755 */
1756 if (open_tables.open_tables_)
1757 open_tables.close_open_tables();
1758}
1759
1761{
1762 /*
1763 If table list consists only from tables from prelocking set, table list
1764 for new attempt should be empty, so we have to update list's root pointer.
1765 */
1766 if (lex().first_not_own_table() == *tables)
1767 *tables= 0;
1768 lex().chop_off_not_own_tables();
1769 for (TableList *tmp= *tables; tmp; tmp= tmp->next_global)
1770 tmp->table= 0;
1772}
1773
1775{
1776 uint32_t counter;
1777 bool need_reopen;
1778
1779 for ( ; ; )
1780 {
1781 if (open_tables_from_list(&tables, &counter))
1782 return true;
1783
1784 if (not lock_tables(tables, counter, &need_reopen))
1785 break;
1786
1787 if (not need_reopen)
1788 return true;
1789
1790 close_tables_for_reopen(&tables);
1791 }
1792
1793 return handle_derived(&lex(), &derived_prepare) || handle_derived(&lex(), &derived_filling);
1794}
1795
1796/*
1797 @note "best_effort" is used in cases were if a failure occurred on this
1798 operation it would not be surprising because we are only removing because there
1799 might be an issue (lame engines).
1800*/
1801
1802bool Open_tables_state::rm_temporary_table(const identifier::Table &identifier, bool best_effort)
1803{
1804 if (plugin::StorageEngine::dropTable(session_, identifier))
1805 return false;
1806 if (not best_effort)
1807 errmsg_printf(error::WARN, _("Could not remove temporary table: '%s', error: %d"), identifier.getSQLPath().c_str(), errno);
1808 return true;
1809}
1810
1811bool Open_tables_state::rm_temporary_table(plugin::StorageEngine& base, const identifier::Table &identifier)
1812{
1813 drizzled::error_t error;
1814 if (plugin::StorageEngine::dropTable(session_, base, identifier, error))
1815 return false;
1816 errmsg_printf(error::WARN, _("Could not remove temporary table: '%s', error: %d"), identifier.getSQLPath().c_str(), error);
1817 return true;
1818}
1819
1820table::Singular& Session::getInstanceTable()
1821{
1822 impl_->temporary_shares.push_back(new table::Singular); // This will not go into the tableshare cache, so no key is used.
1823 return impl_->temporary_shares.back();
1824}
1825
1826
1845table::Singular& Session::getInstanceTable(std::list<CreateField>& field_list)
1846{
1847 impl_->temporary_shares.push_back(new table::Singular(this, field_list)); // This will not go into the tableshare cache, so no key is used.
1848 return impl_->temporary_shares.back();
1849}
1850
1851void Session::clear_error(bool full)
1852{
1853 if (main_da().is_error())
1854 main_da().reset_diagnostics_area();
1855
1856 if (full)
1857 drizzle_reset_errors(*this, true);
1858}
1859
1860void Session::clearDiagnostics()
1861{
1862 main_da().reset_diagnostics_area();
1863}
1864
1879{
1880 return impl_->diagnostics.is_error();
1881}
1882
1884void Session::my_ok(ha_rows affected_rows, ha_rows found_rows_arg, uint64_t passed_id, const char *message)
1885{
1886 main_da().set_ok_status(this, affected_rows, found_rows_arg, passed_id, message);
1887}
1888
1890
1892{
1893 main_da().set_eof_status(this);
1894}
1895
1897{
1898 return variables.storage_engine ? variables.storage_engine : global_system_variables.storage_engine;
1899}
1900
1901enum_tx_isolation Session::getTxIsolation() const
1902{
1903 return (enum_tx_isolation)variables.tx_isolation;
1904}
1905
1906drizzled::util::Storable* Session::getProperty0(const std::string& arg)
1907{
1908 return impl_->properties[arg];
1909}
1910
1911void Session::setProperty0(const std::string& arg, drizzled::util::Storable* value)
1912{
1913 // assert(not _properties.count(arg));
1914 impl_->properties[arg]= value;
1915}
1916
1917plugin::EventObserverList* Session::getSchemaObservers(const std::string &db_name)
1918{
1919 if (impl_c::schema_event_observers_t::mapped_type* i= find_ptr(impl_->schema_event_observers, db_name))
1920 return *i;
1921 return NULL;
1922}
1923
1924plugin::EventObserverList* Session::setSchemaObservers(const std::string &db_name, plugin::EventObserverList* observers)
1925{
1926 impl_->schema_event_observers.erase(db_name);
1927 if (observers)
1928 impl_->schema_event_observers[db_name] = observers;
1929 return observers;
1930}
1931
1932util::string::ptr Session::schema() const
1933{
1934 return impl_->schema;
1935}
1936
1937void Session::resetQueryString()
1938{
1939 query.reset();
1940 impl_->state.reset();
1941}
1942
1943const std::shared_ptr<session::State>& Session::state()
1944{
1945 return impl_->state;
1946}
1947
1948const std::string& display::type(drizzled::Session::global_read_lock_t type)
1949{
1950 static const std::string NONE= "NONE";
1951 static const std::string GOT_GLOBAL_READ_LOCK= "HAS GLOBAL READ LOCK";
1952 static const std::string MADE_GLOBAL_READ_LOCK_BLOCK_COMMIT= "HAS GLOBAL READ LOCK WITH BLOCKING COMMIT";
1953
1954 switch (type)
1955 {
1956 default:
1957 case Session::NONE:
1958 return NONE;
1959 case Session::GOT_GLOBAL_READ_LOCK:
1960 return GOT_GLOBAL_READ_LOCK;
1961 case Session::MADE_GLOBAL_READ_LOCK_BLOCK_COMMIT:
1962 return MADE_GLOBAL_READ_LOCK_BLOCK_COMMIT;
1963 }
1964}
1965
1966size_t display::max_string_length(drizzled::Session::global_read_lock_t)
1967{
1968 return display::type(Session::MADE_GLOBAL_READ_LOCK_BLOCK_COMMIT).size();
1969}
1970
1971} /* namespace drizzled */
bool maybe_null
Definition item.h:123
void mark_temp_tables_as_free_for_reuse()
Definition session.cc:1700
uint32_t row_count
Definition session.h:443
bool transaction_rollback_request
Definition session.h:542
void set_proc_info(const char *info)
Definition session.h:605
void readAndStoreQuery(str_ref)
Definition session.cc:713
const char * _where
Definition session.h:266
drizzle_system_variables & variables
Definition session.h:195
void cleanup_after_query()
Definition session.cc:818
void set_schema(const std::string &)
Definition session.cc:1514
bool is_error() const
Definition session.cc:1878
enum_server_command command
Definition session.h:318
plugin::StorageEngine * getDefaultStorageEngine()
Definition session.cc:1896
memory::Root warn_root
Definition session.h:172
void prepareForQueries()
Definition session.cc:545
bool no_warnings_for_error
Definition session.h:561
bool isViewable(const identifier::User &) const
Definition session.cc:625
bool substitute_null_with_insert_id
Definition session.h:556
uint64_t options
Definition session.h:396
memory::Root * mem_root
Definition session.h:114
void markTransactionForRollback(bool all)
Definition session.cc:1526
bool is_fatal_sub_stmt_error
Definition session.h:554
THR_LOCK_INFO lock_info
Definition session.h:199
bool authenticate()
Definition session.cc:656
void reset_for_next_command()
Definition session.cc:1569
THR_LOCK_OWNER main_lock_id
Definition session.h:200
void my_ok(ha_rows affected_rows=0, ha_rows found_rows_arg=0, uint64_t passed_id=0, const char *message=NULL)
Definition session.cc:1884
bool endTransaction(enum enum_mysql_completiontype completion)
Definition session.cc:727
uint64_t first_successful_insert_id_in_cur_stmt
Definition session.h:381
void close_tables_for_reopen(TableList **tables)
Definition session.cc:1760
void resetResultsetMessage()
Definition session.h:942
lex_string_t * make_lex_string(lex_string_t *, str_ref)
Definition session.cc:854
void close_thread_tables()
Definition session.cc:1721
uint64_t first_successful_insert_id_in_prev_stmt
Definition session.h:375
plugin::Scheduler * scheduler
Definition session.h:181
bool checkUser(const std::string &passwd, const std::string &db)
Definition session.cc:666
uint32_t select_number
Definition session.h:494
uint32_t warn_count[(uint32_t) DRIZZLE_ERROR::WARN_LEVEL_END]
Definition session.h:436
void disconnect(enum error_t errcode=EE_OK)
Definition session.cc:1532
char * thread_stack
Definition session.h:207
static const char *const DEFAULT_WHERE
Definition session.h:170
bool openTablesLock(TableList *)
Definition session.cc:1774
bool executeStatement()
Definition session.cc:684
ha_rows examined_row_count
Definition session.h:415
ha_rows cuted_fields
Definition session.h:404
UserVars user_vars
Definition session.h:187
bool inTransaction() const
Definition session.h:767
ha_rows sent_row_count
Definition session.h:410
TableList * next_global
Definition table_list.h:110
static int commitTransaction(Session &, bool all)
static int autocommitOrRollback(Session &, int error)
A set of Session members describing the current authenticated user.
char * strdup(const char *)
Duplicate a null-terminated string into memory allocated from within the specified Root.
Definition root.cc:327
void init(size_t block_size=ROOT_MIN_BLOCK_SIZE)
Initialize memory root.
Definition root.cc:57
static bool isAuthorized(const drizzled::identifier::User &user_ctx, const identifier::Schema &schema_identifier, bool send_error=true)
static void rewriteQuery(const std::string &schema, std::string &to_rewrite)
static void closeConnection(Session &)
static int notifyStartTransaction(Session *session, start_transaction_option_t options)
bool dispatch_command(enum_server_command command, Session &session, str_ref packet)
Definition sql_parse.cc:189
Convert from decimal to binary representation.
Definition common_fwd.h:215
TODO: Rename this file - func.h is stupid.
DRIZZLED_API int tmpfile(const char *prefix)
Definition session.cc:121
time_t flush_status_time
Definition drizzled.cc:251
int class_decimal_cmp(const type::Decimal *a, const type::Decimal *b)
STL namespace.