~drizzle-trunk/drizzle/development

520.6.3 by Monty Taylor
Moved scheduler.h out of common_includes.
1
/* -*- mode: c++; c-basic-offset: 2; indent-tabs-mode: nil; -*-
2
 *  vim:expandtab:shiftwidth=2:tabstop=2:smarttab:
3
 *
1999.6.1 by kalebral at gmail
update Copyright strings to a more common format to help with creating the master debian copyright file
4
 *  Copyright (C) 2008 Sun Microsystems, Inc.
520.6.3 by Monty Taylor
Moved scheduler.h out of common_includes.
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
 */
1 by brian
clean slate
19
1055.2.13 by Jay Pipes
Documentation and style fixes in Session class. Doxygen should finally pick up the Statement and Session classes now. Removes the silly Query_arena class, as it's not needed anymore.
20
/**
21
 * @file Implementation of the Session class and API
22
 */
23
2173.2.1 by Monty Taylor
Fixes incorrect usage of include
24
#include <config.h>
2154.2.11 by Brian Aker
Further strip out includes.
25
2241.2.8 by Olaf van der Spek
Refactor
26
#include <boost/checked_delete.hpp>
27
#include <boost/filesystem.hpp>
2318.6.96 by Olaf van der Spek
Refactor
28
#include <boost/ptr_container/ptr_container.hpp>
2154.2.11 by Brian Aker
Further strip out includes.
29
#include <drizzled/copy_field.h>
2187.7.1 by Brian Aker
Merge in sort/fix for header file discoverd.
30
#include <drizzled/data_home.h>
2241.2.8 by Olaf van der Spek
Refactor
31
#include <drizzled/diagnostics_area.h>
2187.7.1 by Brian Aker
Merge in sort/fix for header file discoverd.
32
#include <drizzled/display.h>
33
#include <drizzled/drizzled.h>
2173.2.1 by Monty Taylor
Fixes incorrect usage of include
34
#include <drizzled/error.h>
35
#include <drizzled/gettext.h>
2241.2.8 by Olaf van der Spek
Refactor
36
#include <drizzled/ha_data.h>
2187.7.1 by Brian Aker
Merge in sort/fix for header file discoverd.
37
#include <drizzled/identifier.h>
38
#include <drizzled/internal/iocache.h>
39
#include <drizzled/internal/thread_var.h>
2173.2.1 by Monty Taylor
Fixes incorrect usage of include
40
#include <drizzled/item/cache.h>
2187.7.1 by Brian Aker
Merge in sort/fix for header file discoverd.
41
#include <drizzled/item/empty_string.h>
2173.2.1 by Monty Taylor
Fixes incorrect usage of include
42
#include <drizzled/item/float.h>
43
#include <drizzled/item/return_int.h>
2241.2.8 by Olaf van der Spek
Refactor
44
#include <drizzled/item/subselect.h>
2187.7.1 by Brian Aker
Merge in sort/fix for header file discoverd.
45
#include <drizzled/lock.h>
2263.3.11 by Olaf van der Spek
Open Tables
46
#include <drizzled/open_tables_state.h>
2187.7.1 by Brian Aker
Merge in sort/fix for header file discoverd.
47
#include <drizzled/plugin/authentication.h>
2239.1.6 by Olaf van der Spek
Refactor includes
48
#include <drizzled/plugin/authorization.h>
2173.2.1 by Monty Taylor
Fixes incorrect usage of include
49
#include <drizzled/plugin/client.h>
2187.7.1 by Brian Aker
Merge in sort/fix for header file discoverd.
50
#include <drizzled/plugin/event_observer.h>
51
#include <drizzled/plugin/logging.h>
52
#include <drizzled/plugin/query_rewrite.h>
2173.2.1 by Monty Taylor
Fixes incorrect usage of include
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>
2241.2.8 by Olaf van der Spek
Refactor
57
#include <drizzled/schema.h>
2187.7.1 by Brian Aker
Merge in sort/fix for header file discoverd.
58
#include <drizzled/select_dump.h>
59
#include <drizzled/select_exists_subselect.h>
2154.2.17 by Brian Aker
Additional removal of session
60
#include <drizzled/select_export.h>
2187.7.1 by Brian Aker
Merge in sort/fix for header file discoverd.
61
#include <drizzled/select_max_min_finder_subselect.h>
62
#include <drizzled/select_singlerow_subselect.h>
2154.2.17 by Brian Aker
Additional removal of session
63
#include <drizzled/select_subselect.h>
2187.7.1 by Brian Aker
Merge in sort/fix for header file discoverd.
64
#include <drizzled/select_to_file.h>
65
#include <drizzled/session.h>
66
#include <drizzled/session/cache.h>
2269.1.3 by Olaf van der Spek
Session Times
67
#include <drizzled/session/state.h>
2241.2.8 by Olaf van der Spek
Refactor
68
#include <drizzled/session/table_messages.h>
2269.1.3 by Olaf van der Spek
Session Times
69
#include <drizzled/session/times.h>
2241.3.4 by Olaf van der Spek
Refactor Session::transaction
70
#include <drizzled/session/transactions.h>
2187.7.1 by Brian Aker
Merge in sort/fix for header file discoverd.
71
#include <drizzled/show.h>
72
#include <drizzled/sql_base.h>
2241.2.8 by Olaf van der Spek
Refactor
73
#include <drizzled/sql_lex.h>
2241.3.9 by Olaf van der Spek
Merge refactor2 fixes (sorry Lee)
74
#include <drizzled/system_variables.h>
2241.2.8 by Olaf van der Spek
Refactor
75
#include <drizzled/statement.h>
2241.3.1 by Olaf van der Spek
Refactor Session::status_var
76
#include <drizzled/statistics_variables.h>
2187.7.1 by Brian Aker
Merge in sort/fix for header file discoverd.
77
#include <drizzled/table/singular.h>
78
#include <drizzled/table_proto.h>
2154.2.17 by Brian Aker
Additional removal of session
79
#include <drizzled/tmp_table_param.h>
2187.7.1 by Brian Aker
Merge in sort/fix for header file discoverd.
80
#include <drizzled/transaction_services.h>
2154.2.24 by Brian Aker
Merge in all changes for current_session, etc.
81
#include <drizzled/user_var_entry.h>
2241.2.8 by Olaf van der Spek
Refactor
82
#include <drizzled/util/backtrace.h>
83
#include <drizzled/util/find_ptr.h>
2173.2.1 by Monty Taylor
Fixes incorrect usage of include
84
#include <drizzled/util/functors.h>
2280.1.4 by Olaf van der Spek
Refactor
85
#include <drizzled/util/storable.h>
2187.7.1 by Brian Aker
Merge in sort/fix for header file discoverd.
86
#include <plugin/myisam/myisam.h>
1921.4.2 by Brian Aker
Adding in concurrent execute support.
87
1067.4.1 by Nathan Williams
First few changes at converting cmin to std::min.
88
#include <algorithm>
1241.9.24 by Monty Taylor
Removed m_string.h from server_includes.h.
89
#include <climits>
2154.2.11 by Brian Aker
Further strip out includes.
90
#include <fcntl.h>
91
#include <sys/stat.h>
2069.4.1 by Brian Aker
A little on the paranoid side, but not the worst plan ever to check our
92
1067.4.1 by Nathan Williams
First few changes at converting cmin to std::min.
93
using namespace std;
1786.3.2 by Monty Taylor
Cleaned up the initial pass at this. It's not perfect, but it does work.
94
2241.2.7 by Olaf van der Spek
Merge includes branch
95
namespace fs= boost::filesystem;
96
97
namespace drizzled {
1067.4.1 by Nathan Williams
First few changes at converting cmin to std::min.
98
2318.6.43 by Olaf van der Spek
Refactor
99
const char* const Session::DEFAULT_WHERE= "field list";
1 by brian
clean slate
100
2263.3.6 by Olaf van der Spek
Remove refresh_version.*
101
uint64_t g_refresh_version = 1;
102
1 by brian
clean slate
103
bool Key_part_spec::operator==(const Key_part_spec& other) const
104
{
2445.1.1 by Olaf van der Spek
Refactor
105
  return length == other.length 
106
    && field_name.size() == other.field_name.size()
2456.1.4 by Olaf van der Spek
Refactor
107
    && not system_charset_info->strcasecmp(field_name.data(), other.field_name.data());
1 by brian
clean slate
108
}
109
2263.3.9 by Olaf van der Spek
Open Tables
110
Open_tables_state::Open_tables_state(Session& session, uint64_t version_arg) :
111
  version(version_arg),
112
  session_(session)
1 by brian
clean slate
113
{
2263.3.1 by Olaf van der Spek
Rename Open_tables_state::open_tables
114
  open_tables_= temporary_tables= derived_tables= NULL;
1539 by Brian Aker
Simplify out Open_tables_state() backup/restore (no longer needed).
115
  extra_lock= lock= NULL;
1 by brian
clean slate
116
}
117
118
/*
119
  The following functions form part of the C plugin API
120
*/
2026.2.1 by Monty Taylor
Renamed things prefixed mysql_ or mysqld_
121
int tmpfile(const char *prefix)
1 by brian
clean slate
122
{
123
  char filename[FN_REFLEN];
1556.1.1 by Brian Aker
Updates for moving temporary directory.
124
  int fd = internal::create_temp_file(filename, drizzle_tmpdir.c_str(), prefix, MYF(MY_WME));
2241.2.6 by Olaf van der Spek
Refactor
125
  if (fd >= 0)
1 by brian
clean slate
126
    unlink(filename);
127
  return fd;
128
}
129
1273.1.30 by Jay Pipes
* Completes the blueprint for splitting the XA Resource Manager
130
void **Session::getEngineData(const plugin::MonitoredInTransaction *monitored)
1240.9.6 by Monty Taylor
Removed some casts- also removed a few c-interface functions and made them actual methods on session. Also made the ha_data private. (fancy that)
131
{
1273.1.30 by Jay Pipes
* Completes the blueprint for splitting the XA Resource Manager
132
  return static_cast<void **>(&ha_data[monitored->getId()].ha_ptr);
1240.9.6 by Monty Taylor
Removed some casts- also removed a few c-interface functions and made them actual methods on session. Also made the ha_data private. (fancy that)
133
}
134
2241.2.9 by Olaf van der Spek
Refactor
135
ResourceContext& Session::getResourceContext(const plugin::MonitoredInTransaction& monitored, size_t index)
1240.9.6 by Monty Taylor
Removed some casts- also removed a few c-interface functions and made them actual methods on session. Also made the ha_data private. (fancy that)
136
{
2241.2.9 by Olaf van der Spek
Refactor
137
  return ha_data[monitored.getId()].resource_context[index];
520.1.22 by Brian Aker
Second pass of thd cleanup
138
}
139
140
int64_t session_test_options(const Session *session, int64_t test_options)
141
{
142
  return session->options & test_options;
143
}
144
2227.4.11 by Olaf van der Spek
Refactor Session
145
class Session::impl_c
146
{
2234.1.2 by Olaf van der Spek
Refactor includes
147
public:
2280.1.4 by Olaf van der Spek
Refactor
148
  typedef boost::unordered_map<std::string, util::Storable*, util::insensitive_hash, util::insensitive_equal_to> properties_t;
2241.3.12 by Olaf van der Spek
Refactor Session
149
  typedef std::map<std::string, plugin::EventObserverList*> schema_event_observers_t;
2240.5.13 by Olaf van der Spek
Refactor
150
2263.3.10 by Olaf van der Spek
Open Tables
151
  impl_c(Session& session) :
2269.1.11 by Olaf van der Spek
Session Times
152
    open_tables(session, g_refresh_version),
153
    schema(boost::make_shared<std::string>())
2263.3.10 by Olaf van der Spek
Open Tables
154
  {
155
  }
156
2280.1.4 by Olaf van der Spek
Refactor
157
  ~impl_c()
158
  {
159
    BOOST_FOREACH(properties_t::reference it, properties)
160
      delete it.second;
161
  }
162
2239.1.4 by Olaf van der Spek
Refactor includes
163
  Diagnostics_area diagnostics;
2281.4.2 by Olaf van der Spek
Prune
164
  memory::Root mem_root;
165
2234.1.2 by Olaf van der Spek
Refactor includes
166
  /**
167
    The lex to hold the parsed tree of conventional (non-prepared) queries.
168
    Whereas for prepared and stored procedure statements we use an own lex
169
    instance for each new query, for conventional statements we reuse
170
    the same lex. (@see mysql_parse for details).
171
  */
172
  LEX lex;
2263.3.10 by Olaf van der Spek
Open Tables
173
  Open_tables_state open_tables;
2240.5.13 by Olaf van der Spek
Refactor
174
  properties_t properties;
2241.3.12 by Olaf van der Spek
Refactor Session
175
  schema_event_observers_t schema_event_observers;
2241.3.1 by Olaf van der Spek
Refactor Session::status_var
176
  system_status_var status_var;
2239.1.8 by Olaf van der Spek
Refactor includes
177
  session::TableMessages table_message_cache;
2269.1.7 by Olaf van der Spek
Use util::string::ptr
178
  util::string::mptr schema;
2269.1.8 by Olaf van der Spek
Refactor Session
179
  boost::shared_ptr<session::State> state;
2318.6.96 by Olaf van der Spek
Refactor
180
  boost::ptr_vector<table::Singular> temporary_shares;
2269.1.3 by Olaf van der Spek
Session Times
181
	session::Times times;
2241.3.4 by Olaf van der Spek
Refactor Session::transaction
182
	session::Transactions transaction;
2241.3.2 by Olaf van der Spek
Refactor Session::variables
183
  drizzle_system_variables variables;
2227.4.11 by Olaf van der Spek
Refactor Session
184
};
185
2039.6.3 by Brian Aker
Update for session to have a catalog object.
186
Session::Session(plugin::Client *client_arg, catalog::Instance::shared_ptr catalog_arg) :
2263.3.10 by Olaf van der Spek
Open Tables
187
  impl_(new impl_c(*this)),
2318.6.20 by Olaf van der Spek
Refactor
188
  mem(impl_->mem_root),
2281.4.2 by Olaf van der Spek
Prune
189
  mem_root(&impl_->mem_root),
1932.3.2 by Brian Aker
1) Make sure the query string always has an std::string in it.
190
  query(new std::string),
971.3.64 by Eric Day
Cleaned up Scheduler plugin, moved more code to the schedular plugins, reworked some functions to be methods in Session, removed some dead code.
191
  scheduler(NULL),
2241.3.2 by Olaf van der Spek
Refactor Session::variables
192
  variables(impl_->variables),
2241.3.1 by Olaf van der Spek
Refactor Session::status_var
193
  status_var(impl_->status_var),
1055.2.16 by Jay Pipes
Removes dead Session::catalog member variable
194
  lock_id(&main_lock_id),
2008.1.1 by Brian Aker
Adding user identifier that makes use of a shared ptr to handle concurrency
195
  thread_stack(NULL),
2114.4.10 by Brian Aker
Remove current_session from a couple of locations, encapsulate where in
196
  _where(Session::DEFAULT_WHERE),
2040.4.2 by Brian Aker
First pass on removing some of the calls currently to boost::posix_time. (we
197
  mysys_var(0),
198
  command(COM_CONNECT),
1273.1.30 by Jay Pipes
* Completes the blueprint for splitting the XA Resource Manager
199
  ha_data(plugin::num_trx_monitored_objects),
2040.4.2 by Brian Aker
First pass on removing some of the calls currently to boost::posix_time. (we
200
  query_id(0),
201
  warn_query_id(0),
2241.3.4 by Olaf van der Spek
Refactor Session::transaction
202
	transaction(impl_->transaction),
2263.3.10 by Olaf van der Spek
Open Tables
203
  open_tables(impl_->open_tables),
2269.1.2 by Olaf van der Spek
Session Times
204
	times(impl_->times),
1055.2.16 by Jay Pipes
Removes dead Session::catalog member variable
205
  first_successful_insert_id_in_prev_stmt(0),
206
  first_successful_insert_id_in_cur_stmt(0),
1055.2.17 by Jay Pipes
More style cleanups in Session
207
  limit_found_rows(0),
2040.4.2 by Brian Aker
First pass on removing some of the calls currently to boost::posix_time. (we
208
  options(session_startup_options),
209
  row_count_func(-1),
210
  sent_row_count(0),
211
  examined_row_count(0),
212
  used_tables(0),
213
  total_warn_count(0),
214
  row_count(0),
215
  thread_id(0),
216
  tmp_table(0),
1910.2.2 by Brian Aker
First pass through the global lock refactor merge.
217
  _global_read_lock(NONE),
2040.4.2 by Brian Aker
First pass on removing some of the calls currently to boost::posix_time. (we
218
  count_cuted_fields(CHECK_FIELD_ERROR_FOR_NULL),
1910.2.8 by Brian Aker
Enapsulate Kill.
219
  _killed(NOT_KILLED),
1055.2.17 by Jay Pipes
More style cleanups in Session
220
  no_errors(false),
221
  is_fatal_error(false),
222
  transaction_rollback_request(false),
1055.2.16 by Jay Pipes
Removes dead Session::catalog member variable
223
  is_fatal_sub_stmt_error(0),
224
  derived_tables_processing(false),
225
  m_lip(NULL),
2227.4.13 by Olaf van der Spek
Refactor Session
226
  arg_of_last_insert_id_function(false),
227
  _catalog(catalog_arg),
1143.2.11 by Jay Pipes
Fixes a bug appearing on hades b/c forgot to initalize statement_message and transaction_message members of Session to NULL
228
  transaction_message(NULL),
1502.5.2 by Barry.Leslie at PrimeBase
Changes made to drizzle source when building in the events plugin.
229
  statement_message(NULL),
1764.3.6 by Brian Aker
This includes a query_usage table for looking at performance of previous
230
  session_event_observers(NULL),
2227.4.12 by Olaf van der Spek
Refactor Session
231
  xa_id(0),
232
  concurrent_execute_allowed(true),
233
  tablespace_op(false),
2241.2.4 by Olaf van der Spek
Refactor
234
  use_usage(false),
235
  security_ctx(identifier::User::make_shared()),
2290.1.2 by Joseph Daly
server uuid as part of replication table
236
  originating_server_uuid_set(false),
2241.2.4 by Olaf van der Spek
Refactor
237
  client(client_arg)
1 by brian
clean slate
238
{
971.6.1 by Eric Day
Renamed Protocol to Client, cleaned up some unnecessary methods along the way.
239
  client->setSession(this);
961.1.3 by Brian Aker
Remove additional lock for proceslist.
240
1 by brian
clean slate
241
  /*
2318.6.23 by Olaf van der Spek
Refactor
242
    Pass nominal parameters to init only to ensure that
1 by brian
clean slate
243
    the destructor works OK in case of an error. The main_mem_root
244
    will be re-initialized in init_for_queries().
245
  */
2318.6.23 by Olaf van der Spek
Refactor
246
  mem.init(memory::ROOT_MIN_BLOCK_SIZE);
1 by brian
clean slate
247
  cuted_fields= sent_row_count= row_count= 0L;
520.1.21 by Brian Aker
THD -> Session rename
248
  // Must be reset to handle error with Session's created for init of mysqld
2227.4.8 by Olaf van der Spek
Session::lex()
249
  lex().current_select= 0;
212.6.1 by Mats Kindahl
Replacing all bzero() calls with memset() calls and removing the bzero.c file.
250
  memset(&variables, 0, sizeof(variables));
1561.3.20 by Joe Daly
add a index in session.h this will allow repeated lookups without having to iterate through the scoreboard looking for our slot
251
  scoreboard_index= -1;
2290.1.2 by Joseph Daly
server uuid as part of replication table
252
  originating_server_uuid= "";
253
  originating_commit_id= 0;
2221.11.1 by Olaf van der Spek
Session::getLex()
254
  cleanup_done= abort_on_warning= no_warnings_for_error= false;
1643.6.13 by Djellel E. Difallah
adding tests
255
1643.6.1 by Djellel E. Difallah
Added hook points and the interface for the Query Cache plugin
256
  resultset= NULL;
1 by brian
clean slate
257
258
  /* Variables with default values */
259
  proc_info="login";
260
1039.1.13 by Brian Aker
Removed dead bit in Session.
261
  plugin_sessionvar_init(this);
262
  /*
263
    variables= global_system_variables above has reset
264
    variables.pseudo_thread_id to 0. We need to correct it here to
265
    avoid temporary tables replication failure.
266
  */
267
  variables.pseudo_thread_id= thread_id;
268
  server_status= SERVER_STATUS_AUTOCOMMIT;
269
270
  if (variables.max_join_size == HA_POS_ERROR)
271
    options |= OPTION_BIG_SELECTS;
272
  else
273
    options &= ~OPTION_BIG_SELECTS;
274
275
  open_options=ha_open_options;
276
  update_lock_default= TL_WRITE;
277
  session_tx_isolation= (enum_tx_isolation) variables.tx_isolation;
278
  memset(warn_count, 0, sizeof(warn_count));
279
  memset(&status_var, 0, sizeof(status_var));
280
1 by brian
clean slate
281
  /* Initialize sub structures */
2318.6.23 by Olaf van der Spek
Refactor
282
  warn_root.init(WARN_ALLOC_BLOCK_SIZE);
1 by brian
clean slate
283
51.1.50 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
284
  substitute_null_with_insert_id = false;
1689.2.12 by Brian Aker
THR_LOCK_INFO::init() <-- encapsulation
285
  lock_info.init(); /* safety: will be reset after start */
2445.1.16 by Olaf van der Spek
Refactor
286
  main_lock_id.info= &lock_info;
1 by brian
clean slate
287
2221.11.1 by Olaf van der Spek
Session::getLex()
288
  plugin::EventObserver::registerSessionEvents(*this);
2224.2.2 by Olaf van der Spek
Refactor
289
}
290
2239.1.4 by Olaf van der Spek
Refactor includes
291
Diagnostics_area& Session::main_da()
292
{
293
  return impl_->diagnostics;
294
}
295
2234.1.1 by Olaf van der Spek
Refactor includes
296
const LEX& Session::lex() const
297
{
2234.1.2 by Olaf van der Spek
Refactor includes
298
  return impl_->lex;
2234.1.1 by Olaf van der Spek
Refactor includes
299
}
300
301
LEX& Session::lex()
302
{
2234.1.2 by Olaf van der Spek
Refactor includes
303
  return impl_->lex;
2234.1.1 by Olaf van der Spek
Refactor includes
304
}
305
306
enum_sql_command Session::getSqlCommand() const
307
{
308
  return lex().sql_command;
309
}
310
2239.1.8 by Olaf van der Spek
Refactor includes
311
session::TableMessages& Session::getMessageCache()
312
{
313
  return impl_->table_message_cache;
314
}
315
2224.2.6 by Olaf van der Spek
Statement::set_command
316
void statement::Statement::set_command(enum_sql_command v)
317
{
2227.4.8 by Olaf van der Spek
Session::lex()
318
	session().lex().sql_command= v;
2224.2.6 by Olaf van der Spek
Statement::set_command
319
}
320
2224.2.8 by Olaf van der Spek
Statement::lex()
321
LEX& statement::Statement::lex()
322
{
2227.4.10 by Olaf van der Spek
Session::lex()
323
	return session().lex();
2224.2.8 by Olaf van der Spek
Statement::lex()
324
}
325
2224.2.2 by Olaf van der Spek
Refactor
326
session::Transactions& statement::Statement::transaction()
327
{
328
	return session().transaction;
1 by brian
clean slate
329
}
330
2318.6.31 by Olaf van der Spek
Refactor
331
void Session::add_item_to_list(Item *item)
2227.4.13 by Olaf van der Spek
Refactor Session
332
{
2318.6.31 by Olaf van der Spek
Refactor
333
  lex().current_select->add_item_to_list(this, item);
2227.4.13 by Olaf van der Spek
Refactor Session
334
}
335
2318.6.31 by Olaf van der Spek
Refactor
336
void Session::add_value_to_list(Item *value)
2227.4.13 by Olaf van der Spek
Refactor Session
337
{
2241.2.11 by Olaf van der Spek
Refactor
338
	lex().value_list.push_back(value);
2227.4.13 by Olaf van der Spek
Refactor Session
339
}
340
2318.6.31 by Olaf van der Spek
Refactor
341
void Session::add_order_to_list(Item *item, bool asc)
2227.4.13 by Olaf van der Spek
Refactor Session
342
{
2318.6.30 by Olaf van der Spek
Refactor
343
  lex().current_select->add_order_to_list(this, item, asc);
2227.4.13 by Olaf van der Spek
Refactor Session
344
}
345
2318.6.31 by Olaf van der Spek
Refactor
346
void Session::add_group_to_list(Item *item, bool asc)
2227.4.13 by Olaf van der Spek
Refactor Session
347
{
2318.6.31 by Olaf van der Spek
Refactor
348
  lex().current_select->add_group_to_list(this, item, asc);
2227.4.13 by Olaf van der Spek
Refactor Session
349
}
350
1100.3.29 by Padraig O'Sullivan
Removed the Statement class. Copied any members it had that were needed by
351
void Session::free_items()
1055.2.13 by Jay Pipes
Documentation and style fixes in Session class. Doxygen should finally pick up the Statement and Session classes now. Removes the silly Query_arena class, as it's not needed anymore.
352
{
1253.1.6 by Monty Taylor
Moved mem_root functions into drizzled::memory:: namespace.
353
  /* This works because items are allocated with memory::sql_alloc() */
2318.6.32 by Olaf van der Spek
Refactor
354
  for (Item* next; free_list; free_list= next)
1055.2.13 by Jay Pipes
Documentation and style fixes in Session class. Doxygen should finally pick up the Statement and Session classes now. Removes the silly Query_arena class, as it's not needed anymore.
355
  {
356
    next= free_list->next;
357
    free_list->delete_self();
358
  }
359
}
1 by brian
clean slate
360
1689.2.26 by Brian Aker
More encapsulation of the thread var.
361
void Session::setAbort(bool arg)
362
{
363
  mysys_var->abort= arg;
364
}
365
366
void Session::lockOnSys()
367
{
368
  if (not mysys_var)
369
    return;
370
371
  setAbort(true);
2275.3.4 by Olaf van der Spek
Thread
372
  boost::mutex::scoped_lock scopedLock(mysys_var->mutex);
1689.2.26 by Brian Aker
More encapsulation of the thread var.
373
  if (mysys_var->current_cond)
374
  {
1786.2.1 by Brian Aker
Current boost work (more conversion).
375
    mysys_var->current_mutex->lock();
1798.3.1 by Brian Aker
Remove native_handle usage.
376
    mysys_var->current_cond->notify_all();
1786.2.1 by Brian Aker
Current boost work (more conversion).
377
    mysys_var->current_mutex->unlock();
1689.2.26 by Brian Aker
More encapsulation of the thread var.
378
  }
379
}
380
2385.3.6 by Olaf van der Spek
cppcheck
381
void Session::get_xid(DrizzleXid *xid) const
1490 by Brian Aker
Updates to remove a fe bits of dead code around C support for plugins
382
{
2224.2.4 by Olaf van der Spek
Undo partial commit
383
  *xid = *(DrizzleXid *) &transaction.xid_state.xid;
1490 by Brian Aker
Updates to remove a fe bits of dead code around C support for plugins
384
}
385
1 by brian
clean slate
386
/* Do operations that may take a long time */
387
2241.2.11 by Olaf van der Spek
Refactor
388
void Session::cleanup()
1 by brian
clean slate
389
{
2281.4.1 by Olaf van der Spek
Prune
390
  assert(not cleanup_done);
1 by brian
clean slate
391
1910.2.8 by Brian Aker
Enapsulate Kill.
392
  setKilled(KILL_CONNECTION);
1 by brian
clean slate
393
#ifdef ENABLE_WHEN_BINLOG_WILL_BE_ABLE_TO_PREPARE
2224.2.4 by Olaf van der Spek
Undo partial commit
394
  if (transaction.xid_state.xa_state == XA_PREPARED)
1 by brian
clean slate
395
  {
396
#error xid_state in the cache should be replaced by the allocated value
397
  }
398
#endif
399
  {
2318.6.62 by Olaf van der Spek
Refactor
400
    TransactionServices::rollbackTransaction(*this, true);
1 by brian
clean slate
401
  }
1689.3.4 by Brian Aker
Remove the hash in session, for a boost based one.
402
2246.4.1 by Olaf van der Spek
Use BOOST_FOREACH
403
  BOOST_FOREACH(UserVars::reference iter, user_vars)
404
    boost::checked_delete(iter.second);
1689.3.4 by Brian Aker
Remove the hash in session, for a boost based one.
405
  user_vars.clear();
406
2263.3.10 by Olaf van der Spek
Open Tables
407
  open_tables.close_temporary_tables();
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
408
1 by brian
clean slate
409
  if (global_read_lock)
1910.2.2 by Brian Aker
First pass through the global lock refactor merge.
410
    unlockGlobalReadLock();
1 by brian
clean slate
411
947 by Brian Aker
Merge fix
412
  cleanup_done= true;
51.1.50 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
413
}
1 by brian
clean slate
414
520.1.21 by Brian Aker
THD -> Session rename
415
Session::~Session()
1 by brian
clean slate
416
{
2015.3.3 by Brian Aker
Update disconnect code.
417
  if (client and client->isConnected())
942.1.2 by Monty Taylor
Started trying to sort out session lifecycle.
418
  {
2008.1.1 by Brian Aker
Adding user identifier that makes use of a shared ptr to handle concurrency
419
    assert(security_ctx);
942.1.2 by Monty Taylor
Started trying to sort out session lifecycle.
420
    if (global_system_variables.log_warnings)
2008.1.1 by Brian Aker
Adding user identifier that makes use of a shared ptr to handle concurrency
421
    {
2440.2.9 by Olaf van der Spek
Refactor
422
      errmsg_printf(error::WARN, ER(ER_FORCING_CLOSE), internal::my_progname, thread_id, security_ctx->username().c_str());
2008.1.1 by Brian Aker
Adding user identifier that makes use of a shared ptr to handle concurrency
423
    }
424
2015.3.3 by Brian Aker
Update disconnect code.
425
    disconnect();
942.1.2 by Monty Taylor
Started trying to sort out session lifecycle.
426
  }
427
1 by brian
clean slate
428
  /* Close connection */
2015.3.3 by Brian Aker
Update disconnect code.
429
  if (client)
430
  {
431
    client->close();
2069.4.1 by Brian Aker
A little on the paranoid side, but not the worst plan ever to check our
432
    boost::checked_delete(client);
433
    client= NULL;
2015.3.3 by Brian Aker
Update disconnect code.
434
  }
971.3.6 by Eric Day
Moved the last of the libdrizzleclient calls into Protocol.
435
2281.4.1 by Olaf van der Spek
Prune
436
  if (not cleanup_done)
1 by brian
clean slate
437
    cleanup();
438
2302.1.8 by Olaf van der Spek
Refactor
439
  plugin::StorageEngine::closeConnection(*this);
520.1.22 by Brian Aker
Second pass of thd cleanup
440
  plugin_sessionvar_cleanup(this);
1 by brian
clean slate
441
1487 by Brian Aker
More updates for memory::Root
442
  warn_root.free_root(MYF(0));
1 by brian
clean slate
443
  mysys_var=0;					// Safety (shouldn't be needed)
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
444
2281.4.2 by Olaf van der Spek
Prune
445
  impl_->mem_root.free_root(MYF(0));
2318.6.22 by Olaf van der Spek
Refactor
446
  setCurrentMemRoot(NULL);
447
  setCurrentSession(NULL);
942.1.2 by Monty Taylor
Started trying to sort out session lifecycle.
448
1316.1.1 by Joe Daly
add plugin handle to logging to indicate when the session destructor is called
449
  plugin::Logging::postEndDo(this);
1919.3.45 by Barry.Leslie at PrimeBase
Fixed bug in merged code.
450
  plugin::EventObserver::deregisterSessionEvents(session_event_observers); 
1919.3.47 by Barry.Leslie at PrimeBase
Added back in schema event observer list cleanup.
451
2241.3.12 by Olaf van der Spek
Refactor Session
452
	BOOST_FOREACH(impl_c::schema_event_observers_t::reference it, impl_->schema_event_observers)
2241.3.7 by Olaf van der Spek
Refactor
453
    plugin::EventObserver::deregisterSchemaEvents(it.second);
1 by brian
clean slate
454
}
455
1921.4.1 by Brian Aker
Adding in support for EXECUTE to have WITH NO RETURN.
456
void Session::setClient(plugin::Client *client_arg)
457
{
458
  client= client_arg;
459
  client->setSession(this);
460
}
461
1910.2.8 by Brian Aker
Enapsulate Kill.
462
void Session::awake(Session::killed_state_t state_to_set)
1 by brian
clean slate
463
{
2281.4.1 by Olaf van der Spek
Prune
464
  if (state_to_set == Session::KILL_QUERY && command == COM_SLEEP)
1994.3.2 by Andrew Hutchings
Merge with trunk
465
    return;
466
1910.2.8 by Brian Aker
Enapsulate Kill.
467
  setKilled(state_to_set);
1961 by Brian Aker
This extends our coverage of interrupting active threads. With no crash
468
  scheduler->killSession(this);
469
520.1.21 by Brian Aker
THD -> Session rename
470
  if (state_to_set != Session::KILL_QUERY)
1 by brian
clean slate
471
  {
1126.10.18 by Padraig O'Sullivan
Various small build fixes for when dtrace is enabled.
472
    DRIZZLE_CONNECTION_DONE(thread_id);
1 by brian
clean slate
473
  }
1933.2.4 by Brian Aker
Update user locks to allow for interruption based on boost.
474
1 by brian
clean slate
475
  if (mysys_var)
476
  {
2275.3.4 by Olaf van der Spek
Thread
477
    boost::mutex::scoped_lock scopedLock(mysys_var->mutex);
1 by brian
clean slate
478
    /*
1786.2.1 by Brian Aker
Current boost work (more conversion).
479
      "
1 by brian
clean slate
480
      This broadcast could be up in the air if the victim thread
481
      exits the cond in the time between read and broadcast, but that is
482
      ok since all we want to do is to make the victim thread get out
483
      of waiting on current_cond.
484
      If we see a non-zero current_cond: it cannot be an old value (because
485
      then exit_cond() should have run and it can't because we have mutex); so
486
      it is the true value but maybe current_mutex is not yet non-zero (we're
487
      in the middle of enter_cond() and there is a "memory order
488
      inversion"). So we test the mutex too to not lock 0.
489
490
      Note that there is a small chance we fail to kill. If victim has locked
491
      current_mutex, but hasn't yet entered enter_cond() (which means that
492
      current_cond and current_mutex are 0), then the victim will not get
493
      a signal and it may wait "forever" on the cond (until
494
      we issue a second KILL or the status it's waiting for happens).
520.1.22 by Brian Aker
Second pass of thd cleanup
495
      It's true that we have set its session->killed but it may not
1 by brian
clean slate
496
      see it immediately and so may have time to reach the cond_wait().
497
    */
498
    if (mysys_var->current_cond && mysys_var->current_mutex)
499
    {
1786.2.1 by Brian Aker
Current boost work (more conversion).
500
      mysys_var->current_mutex->lock();
1798.3.10 by Brian Aker
Remove additional (maybe last of?) native_handle actual calls (safe_mutex is
501
      mysys_var->current_cond->notify_all();
1786.2.1 by Brian Aker
Current boost work (more conversion).
502
      mysys_var->current_mutex->unlock();
1 by brian
clean slate
503
    }
504
  }
505
}
506
507
/*
508
  Remember the location of thread info, the structure needed for
1253.1.6 by Monty Taylor
Moved mem_root functions into drizzled::memory:: namespace.
509
  memory::sql_alloc() and the structure for the net buffer
1 by brian
clean slate
510
*/
2269.1.7 by Olaf van der Spek
Use util::string::ptr
511
void Session::storeGlobals()
1 by brian
clean slate
512
{
513
  /*
514
    Assert that thread_stack is initialized: it's necessary to be able
515
    to track stack overrun.
516
  */
51.1.50 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
517
  assert(thread_stack);
2318.6.22 by Olaf van der Spek
Refactor
518
  setCurrentSession(this);
519
  setCurrentMemRoot(&mem);
971.3.64 by Eric Day
Cleaned up Scheduler plugin, moved more code to the schedular plugins, reworked some functions to be methods in Session, removed some dead code.
520
2415.1.4 by Brian Aker
Wrap thread specfic
521
  mysys_var= internal::my_thread_var2().get();
960.1.1 by Monty Taylor
First pass at scheduler plugin.
522
1 by brian
clean slate
523
  /*
524
    Let mysqld define the thread id (not mysys)
520.1.21 by Brian Aker
THD -> Session rename
525
    This allows us to move Session to different threads if needed.
1 by brian
clean slate
526
  */
527
  mysys_var->id= thread_id;
528
529
  /*
520.1.21 by Brian Aker
THD -> Session rename
530
    We have to call thr_lock_info_init() again here as Session may have been
1 by brian
clean slate
531
    created in another thread
532
  */
1689.2.12 by Brian Aker
THR_LOCK_INFO::init() <-- encapsulation
533
  lock_info.init();
1 by brian
clean slate
534
}
535
971.3.64 by Eric Day
Cleaned up Scheduler plugin, moved more code to the schedular plugins, reworked some functions to be methods in Session, removed some dead code.
536
/*
537
  Init Session for query processing.
538
  This has to be called once before we call mysql_parse.
539
  See also comments in session.h.
540
*/
541
934.2.6 by Jay Pipes
This changeset removes a few more C functions from sql_connect.cc/connect.h
542
void Session::prepareForQueries()
543
{
544
  if (variables.max_join_size == HA_POS_ERROR)
545
    options |= OPTION_BIG_SELECTS;
546
2263.3.10 by Olaf van der Spek
Open Tables
547
  open_tables.version= g_refresh_version;
961.1.4 by Brian Aker
Remove another lock for processlist.
548
  set_proc_info(NULL);
934.2.6 by Jay Pipes
This changeset removes a few more C functions from sql_connect.cc/connect.h
549
  command= COM_SLEEP;
2269.1.6 by Olaf van der Spek
Session Times
550
  times.set_time();
971.3.64 by Eric Day
Cleaned up Scheduler plugin, moved more code to the schedular plugins, reworked some functions to be methods in Session, removed some dead code.
551
2318.6.24 by Olaf van der Spek
Refactor
552
  mem.reset_defaults(variables.query_alloc_block_size, variables.query_prealloc_size);
2281.4.7 by Olaf van der Spek
XID
553
  transaction.xid_state.xid.set_null();
2224.2.4 by Olaf van der Spek
Undo partial commit
554
  transaction.xid_state.in_session=1;
1764.3.6 by Brian Aker
This includes a query_usage table for looking at performance of previous
555
  if (use_usage)
556
    resetUsage();
934.2.6 by Jay Pipes
This changeset removes a few more C functions from sql_connect.cc/connect.h
557
}
558
2269.1.8 by Olaf van der Spek
Refactor Session
559
void Session::run()
971.3.64 by Eric Day
Cleaned up Scheduler plugin, moved more code to the schedular plugins, reworked some functions to be methods in Session, removed some dead code.
560
{
2269.1.7 by Olaf van der Spek
Use util::string::ptr
561
  storeGlobals();
2269.1.8 by Olaf van der Spek
Refactor Session
562
  if (authenticate())
971.3.64 by Eric Day
Cleaned up Scheduler plugin, moved more code to the schedular plugins, reworked some functions to be methods in Session, removed some dead code.
563
  {
2015.3.3 by Brian Aker
Update disconnect code.
564
    disconnect();
971.3.64 by Eric Day
Cleaned up Scheduler plugin, moved more code to the schedular plugins, reworked some functions to be methods in Session, removed some dead code.
565
    return;
566
  }
567
  prepareForQueries();
1910.2.8 by Brian Aker
Enapsulate Kill.
568
  while (not client->haveError() && getKilled() != KILL_CONNECTION)
971.3.64 by Eric Day
Cleaned up Scheduler plugin, moved more code to the schedular plugins, reworked some functions to be methods in Session, removed some dead code.
569
  {
1910.2.8 by Brian Aker
Enapsulate Kill.
570
    if (not executeStatement())
971.3.64 by Eric Day
Cleaned up Scheduler plugin, moved more code to the schedular plugins, reworked some functions to be methods in Session, removed some dead code.
571
      break;
572
  }
2015.3.3 by Brian Aker
Update disconnect code.
573
  disconnect();
971.3.64 by Eric Day
Cleaned up Scheduler plugin, moved more code to the schedular plugins, reworked some functions to be methods in Session, removed some dead code.
574
}
575
2318.6.43 by Olaf van der Spek
Refactor
576
bool Session::schedule(const shared_ptr& arg)
971.3.64 by Eric Day
Cleaned up Scheduler plugin, moved more code to the schedular plugins, reworked some functions to be methods in Session, removed some dead code.
577
{
1932.3.3 by Brian Aker
Pull in code to abstract out the session list a bit.
578
  arg->scheduler= plugin::Scheduler::getScheduler();
579
  assert(arg->scheduler);
971.3.64 by Eric Day
Cleaned up Scheduler plugin, moved more code to the schedular plugins, reworked some functions to be methods in Session, removed some dead code.
580
2041.2.2 by Brian Aker
Ubuntu issue?
581
  ++connection_count;
582
583
  long current_connections= connection_count;
971.3.64 by Eric Day
Cleaned up Scheduler plugin, moved more code to the schedular plugins, reworked some functions to be methods in Session, removed some dead code.
584
2039.3.5 by Brian Aker
Switched connection_count to use boost atomic.
585
  if (current_connections > 0 and static_cast<uint64_t>(current_connections) > current_global_counters.max_used_connections)
1537.2.1 by Joe Daly
add statistics_variables.h
586
  {
2039.3.5 by Brian Aker
Switched connection_count to use boost atomic.
587
    current_global_counters.max_used_connections= static_cast<uint64_t>(connection_count);
1537.2.1 by Joe Daly
add statistics_variables.h
588
  }
971.3.64 by Eric Day
Cleaned up Scheduler plugin, moved more code to the schedular plugins, reworked some functions to be methods in Session, removed some dead code.
589
1726.3.3 by LinuxJedi
Add a proper connections counter.
590
  current_global_counters.connections++;
1932.3.3 by Brian Aker
Pull in code to abstract out the session list a bit.
591
  arg->thread_id= arg->variables.pseudo_thread_id= global_thread_id++;
971.3.64 by Eric Day
Cleaned up Scheduler plugin, moved more code to the schedular plugins, reworked some functions to be methods in Session, removed some dead code.
592
2282.1.2 by Olaf van der Spek
Session Cache
593
  session::Cache::insert(arg);
1932.3.3 by Brian Aker
Pull in code to abstract out the session list a bit.
594
595
  if (unlikely(plugin::EventObserver::connectSession(*arg)))
596
  {
597
    // We should do something about an error...
598
  }
599
1932.3.13 by Brian Aker
Cleanup session ownership rules such that we know exactly when session has
600
  if (plugin::Scheduler::getScheduler()->addSession(arg))
971.3.64 by Eric Day
Cleaned up Scheduler plugin, moved more code to the schedular plugins, reworked some functions to be methods in Session, removed some dead code.
601
  {
1932.3.11 by Brian Aker
Fix dtrace issue.
602
    DRIZZLE_CONNECTION_START(arg->getSessionId());
971.3.64 by Eric Day
Cleaned up Scheduler plugin, moved more code to the schedular plugins, reworked some functions to be methods in Session, removed some dead code.
603
    char error_message_buff[DRIZZLE_ERRMSG_SIZE];
604
1932.3.3 by Brian Aker
Pull in code to abstract out the session list a bit.
605
    arg->setKilled(Session::KILL_CONNECTION);
971.3.64 by Eric Day
Cleaned up Scheduler plugin, moved more code to the schedular plugins, reworked some functions to be methods in Session, removed some dead code.
606
1932.3.3 by Brian Aker
Pull in code to abstract out the session list a bit.
607
    arg->status_var.aborted_connects++;
971.3.64 by Eric Day
Cleaned up Scheduler plugin, moved more code to the schedular plugins, reworked some functions to be methods in Session, removed some dead code.
608
609
    /* Can't use my_error() since store_globals has not been called. */
610
    /* TODO replace will better error message */
2318.6.43 by Olaf van der Spek
Refactor
611
    snprintf(error_message_buff, sizeof(error_message_buff), ER(ER_CANT_CREATE_THREAD), 1);
1932.3.3 by Brian Aker
Pull in code to abstract out the session list a bit.
612
    arg->client->sendError(ER_CANT_CREATE_THREAD, error_message_buff);
971.3.64 by Eric Day
Cleaned up Scheduler plugin, moved more code to the schedular plugins, reworked some functions to be methods in Session, removed some dead code.
613
    return true;
614
  }
615
  return false;
934.2.6 by Jay Pipes
This changeset removes a few more C functions from sql_connect.cc/connect.h
616
}
617
1241.9.55 by Monty Taylor
Moved tree into drizzled/
618
1932.3.3 by Brian Aker
Pull in code to abstract out the session list a bit.
619
/*
620
  Is this session viewable by the current user?
621
*/
2246.4.11 by Olaf van der Spek
Remove const_reference and reference from identifier::User
622
bool Session::isViewable(const identifier::User& user_arg) const
1932.3.3 by Brian Aker
Pull in code to abstract out the session list a bit.
623
{
2159.2.7 by Brian Aker
Merge in shared ptr modification for auth (namely we don't take the hit for
624
  return plugin::Authorization::isAuthorized(user_arg, *this, false);
1932.3.3 by Brian Aker
Pull in code to abstract out the session list a bit.
625
}
626
627
1812.3.5 by Brian Aker
Move to boost condition_any
628
const char* Session::enter_cond(boost::condition_variable_any &cond, boost::mutex &mutex, const char* msg)
1241.9.55 by Monty Taylor
Moved tree into drizzled/
629
{
630
  const char* old_msg = get_proc_info();
631
  safe_mutex_assert_owner(mutex);
1786.2.1 by Brian Aker
Current boost work (more conversion).
632
  mysys_var->current_mutex = &mutex;
633
  mysys_var->current_cond = &cond;
1241.9.55 by Monty Taylor
Moved tree into drizzled/
634
  this->set_proc_info(msg);
635
  return old_msg;
636
}
637
638
void Session::exit_cond(const char* old_msg)
639
{
640
  /*
641
    Putting the mutex unlock in exit_cond() ensures that
642
    mysys_var->current_mutex is always unlocked _before_ mysys_var->mutex is
643
    locked (if that would not be the case, you'll get a deadlock if someone
644
    does a Session::awake() on you).
645
  */
1786.2.1 by Brian Aker
Current boost work (more conversion).
646
  mysys_var->current_mutex->unlock();
2275.3.4 by Olaf van der Spek
Thread
647
  boost::mutex::scoped_lock scopedLock(mysys_var->mutex);
1241.9.55 by Monty Taylor
Moved tree into drizzled/
648
  mysys_var->current_mutex = 0;
649
  mysys_var->current_cond = 0;
650
  this->set_proc_info(old_msg);
651
}
652
934.2.4 by Jay Pipes
This changeset pulls check_user(), check_connection(), and login_connection() out of sql_connect.cc and makes them member methods of Session, where they belong. Also, made sure that functions that return a bool return true when it succeeds, and not false...
653
bool Session::authenticate()
654
{
971.6.1 by Eric Day
Renamed Protocol to Client, cleaned up some unnecessary methods along the way.
655
  if (client->authenticate())
971.3.64 by Eric Day
Cleaned up Scheduler plugin, moved more code to the schedular plugins, reworked some functions to be methods in Session, removed some dead code.
656
    return false;
971.3.6 by Eric Day
Moved the last of the libdrizzleclient calls into Protocol.
657
1689.5.1 by Joseph Daly
remove increment calls
658
  status_var.aborted_connects++;
1625.2.1 by Joe Daly
initial user stats impl
659
971.3.64 by Eric Day
Cleaned up Scheduler plugin, moved more code to the schedular plugins, reworked some functions to be methods in Session, removed some dead code.
660
  return true;
934.2.4 by Jay Pipes
This changeset pulls check_user(), check_connection(), and login_connection() out of sql_connect.cc and makes them member methods of Session, where they belong. Also, made sure that functions that return a bool return true when it succeeds, and not false...
661
}
662
2241.3.13 by Olaf van der Spek
Refactor Session
663
bool Session::checkUser(const std::string &passwd_str, const std::string &in_db)
934.2.4 by Jay Pipes
This changeset pulls check_user(), check_connection(), and login_connection() out of sql_connect.cc and makes them member methods of Session, where they belong. Also, made sure that functions that return a bool return true when it succeeds, and not false...
664
{
2241.3.13 by Olaf van der Spek
Refactor Session
665
  if (not plugin::Authentication::isAuthenticated(*user(), passwd_str))
934.2.4 by Jay Pipes
This changeset pulls check_user(), check_connection(), and login_connection() out of sql_connect.cc and makes them member methods of Session, where they belong. Also, made sure that functions that return a bool return true when it succeeds, and not false...
666
  {
1689.5.1 by Joseph Daly
remove increment calls
667
    status_var.access_denied++;
1317.1.3 by Monty Taylor
Fixed Authentication plugin interface to use SecurityContext rather than the
668
    /* isAuthenticated has pushed the error message */
934.2.4 by Jay Pipes
This changeset pulls check_user(), check_connection(), and login_connection() out of sql_connect.cc and makes them member methods of Session, where they belong. Also, made sure that functions that return a bool return true when it succeeds, and not false...
669
    return false;
670
  }
671
672
  /* Change database if necessary */
2241.3.13 by Olaf van der Spek
Refactor Session
673
  if (not in_db.empty() && schema::change(*this, identifier::Schema(in_db)))
674
    return false; // change() has pushed the error message
934.2.4 by Jay Pipes
This changeset pulls check_user(), check_connection(), and login_connection() out of sql_connect.cc and makes them member methods of Session, where they belong. Also, made sure that functions that return a bool return true when it succeeds, and not false...
675
  my_ok();
676
677
  /* Ready to handle queries */
678
  return true;
679
}
1 by brian
clean slate
680
934.2.8 by Jay Pipes
Refactors the do_command() function out of the sql_parse.cc stuff and implements it as a member method, executeStatement() on the Session object.
681
bool Session::executeStatement()
682
{
2241.3.13 by Olaf van der Spek
Refactor Session
683
  /*
684
    indicator of uninitialized lex => normal flow of errors handling
685
    (see my_message_sql)
686
  */
687
  lex().current_select= 0;
688
  clear_error();
689
  main_da().reset_diagnostics_area();
934.2.8 by Jay Pipes
Refactors the do_command() function out of the sql_parse.cc stuff and implements it as a member method, executeStatement() on the Session object.
690
  char *l_packet= 0;
691
  uint32_t packet_length;
2312.1.4 by Brian Aker
Fix packet length, no pointer to using a pointer there.
692
  if (not client->readCommand(&l_packet, packet_length))
971.3.6 by Eric Day
Moved the last of the libdrizzleclient calls into Protocol.
693
    return false;
694
1910.2.8 by Brian Aker
Enapsulate Kill.
695
  if (getKilled() == KILL_CONNECTION)
1724.4.2 by LinuxJedi
Fix "server gone away" in drizzle client. After a connection is killed it can execute one query afterwards, which can give rubbish back. Now check if we are killed after readCommand.
696
    return false;
697
971.3.6 by Eric Day
Moved the last of the libdrizzleclient calls into Protocol.
698
  if (packet_length == 0)
699
    return true;
934.2.8 by Jay Pipes
Refactors the do_command() function out of the sql_parse.cc stuff and implements it as a member method, executeStatement() on the Session object.
700
2241.3.13 by Olaf van der Spek
Refactor Session
701
  enum_server_command l_command= static_cast<enum_server_command>(l_packet[0]);
934.2.8 by Jay Pipes
Refactors the do_command() function out of the sql_parse.cc stuff and implements it as a member method, executeStatement() on the Session object.
702
703
  if (command >= COM_END)
704
    command= COM_END;                           // Wrong command
705
706
  assert(packet_length);
1921.4.2 by Brian Aker
Adding in concurrent execute support.
707
  return not dispatch_command(l_command, this, l_packet+1, (uint32_t) (packet_length-1));
934.2.8 by Jay Pipes
Refactors the do_command() function out of the sql_parse.cc stuff and implements it as a member method, executeStatement() on the Session object.
708
}
934.2.9 by Jay Pipes
Pulls alloc_query() C function out of sql_parse.cc and adds readAndStoreQuery() member method of Session class.
709
2275.2.6 by Olaf van der Spek
Refactor
710
void Session::readAndStoreQuery(const char *in_packet, uint32_t in_packet_length)
934.2.9 by Jay Pipes
Pulls alloc_query() C function out of sql_parse.cc and adds readAndStoreQuery() member method of Session class.
711
{
712
  /* Remove garbage at start and end of query */
2445.1.3 by Olaf van der Spek
Refactor
713
  while (in_packet_length > 0 && charset()->isspace(in_packet[0]))
934.2.9 by Jay Pipes
Pulls alloc_query() C function out of sql_parse.cc and adds readAndStoreQuery() member method of Session class.
714
  {
715
    in_packet++;
716
    in_packet_length--;
717
  }
718
  const char *pos= in_packet + in_packet_length; /* Point at end null */
2445.1.3 by Olaf van der Spek
Refactor
719
  while (in_packet_length > 0 && (pos[-1] == ';' || charset()->isspace(pos[-1])))
934.2.9 by Jay Pipes
Pulls alloc_query() C function out of sql_parse.cc and adds readAndStoreQuery() member method of Session class.
720
  {
721
    pos--;
722
    in_packet_length--;
723
  }
724
2275.2.6 by Olaf van der Spek
Refactor
725
  util::string::mptr new_query= boost::make_shared<std::string>(in_packet, in_packet_length);
726
  plugin::QueryRewriter::rewriteQuery(*impl_->schema, *new_query);
727
  query= new_query;
728
  impl_->state= boost::make_shared<session::State>(in_packet, in_packet_length);
934.2.9 by Jay Pipes
Pulls alloc_query() C function out of sql_parse.cc and adds readAndStoreQuery() member method of Session class.
729
}
730
2275.2.6 by Olaf van der Spek
Refactor
731
bool Session::endTransaction(enum_mysql_completiontype completion)
934.2.11 by Jay Pipes
Moves end_trans(), begin_trans(), end_active_trans() out of the parser module and adds startTransaction(), endTransaction(), and endActiveTransaction() member methods of Session object.
732
{
733
  bool do_release= 0;
734
  bool result= true;
735
2224.2.4 by Olaf van der Spek
Undo partial commit
736
  if (transaction.xid_state.xa_state != XA_NOTR)
934.2.11 by Jay Pipes
Moves end_trans(), begin_trans(), end_active_trans() out of the parser module and adds startTransaction(), endTransaction(), and endActiveTransaction() member methods of Session object.
737
  {
2224.2.4 by Olaf van der Spek
Undo partial commit
738
    my_error(ER_XAER_RMFAIL, MYF(0), xa_state_names[transaction.xid_state.xa_state]);
934.2.11 by Jay Pipes
Moves end_trans(), begin_trans(), end_active_trans() out of the parser module and adds startTransaction(), endTransaction(), and endActiveTransaction() member methods of Session object.
739
    return false;
740
  }
971.3.64 by Eric Day
Cleaned up Scheduler plugin, moved more code to the schedular plugins, reworked some functions to be methods in Session, removed some dead code.
741
  switch (completion)
934.2.11 by Jay Pipes
Moves end_trans(), begin_trans(), end_active_trans() out of the parser module and adds startTransaction(), endTransaction(), and endActiveTransaction() member methods of Session object.
742
  {
743
    case COMMIT:
744
      /*
745
       * We don't use endActiveTransaction() here to ensure that this works
746
       * even if there is a problem with the OPTION_AUTO_COMMIT flag
747
       * (Which of course should never happen...)
748
       */
749
      server_status&= ~SERVER_STATUS_IN_TRANS;
2318.6.62 by Olaf van der Spek
Refactor
750
      if (TransactionServices::commitTransaction(*this, true))
934.2.11 by Jay Pipes
Moves end_trans(), begin_trans(), end_active_trans() out of the parser module and adds startTransaction(), endTransaction(), and endActiveTransaction() member methods of Session object.
751
        result= false;
1172.1.2 by Brian Aker
Remove worthless call (ok... for not current replication system).
752
      options&= ~(OPTION_BEGIN);
934.2.11 by Jay Pipes
Moves end_trans(), begin_trans(), end_active_trans() out of the parser module and adds startTransaction(), endTransaction(), and endActiveTransaction() member methods of Session object.
753
      break;
754
    case COMMIT_RELEASE:
755
      do_release= 1; /* fall through */
756
    case COMMIT_AND_CHAIN:
757
      result= endActiveTransaction();
758
      if (result == true && completion == COMMIT_AND_CHAIN)
759
        result= startTransaction();
760
      break;
761
    case ROLLBACK_RELEASE:
762
      do_release= 1; /* fall through */
763
    case ROLLBACK:
764
    case ROLLBACK_AND_CHAIN:
765
    {
766
      server_status&= ~SERVER_STATUS_IN_TRANS;
2318.6.62 by Olaf van der Spek
Refactor
767
      if (TransactionServices::rollbackTransaction(*this, true))
934.2.11 by Jay Pipes
Moves end_trans(), begin_trans(), end_active_trans() out of the parser module and adds startTransaction(), endTransaction(), and endActiveTransaction() member methods of Session object.
768
        result= false;
1172.1.2 by Brian Aker
Remove worthless call (ok... for not current replication system).
769
      options&= ~(OPTION_BEGIN);
934.2.11 by Jay Pipes
Moves end_trans(), begin_trans(), end_active_trans() out of the parser module and adds startTransaction(), endTransaction(), and endActiveTransaction() member methods of Session object.
770
      if (result == true && (completion == ROLLBACK_AND_CHAIN))
771
        result= startTransaction();
772
      break;
773
    }
774
    default:
775
      my_error(ER_UNKNOWN_COM_ERROR, MYF(0));
776
      return false;
777
  }
778
2275.2.6 by Olaf van der Spek
Refactor
779
  if (not result)
1910.2.8 by Brian Aker
Enapsulate Kill.
780
  {
2054.1.2 by Brian Aker
Rename of the Loooongggggg error type over to simply drizzled::error_t
781
    my_error(static_cast<drizzled::error_t>(killed_errno()), MYF(0));
1910.2.8 by Brian Aker
Enapsulate Kill.
782
  }
2275.2.6 by Olaf van der Spek
Refactor
783
  else if (result && do_release)
1910.2.8 by Brian Aker
Enapsulate Kill.
784
  {
785
    setKilled(Session::KILL_CONNECTION);
786
  }
934.2.11 by Jay Pipes
Moves end_trans(), begin_trans(), end_active_trans() out of the parser module and adds startTransaction(), endTransaction(), and endActiveTransaction() member methods of Session object.
787
788
  return result;
789
}
790
791
bool Session::endActiveTransaction()
792
{
793
  bool result= true;
794
2224.2.5 by Olaf van der Spek
Undo partial commit
795
  if (transaction.xid_state.xa_state != XA_NOTR)
934.2.11 by Jay Pipes
Moves end_trans(), begin_trans(), end_active_trans() out of the parser module and adds startTransaction(), endTransaction(), and endActiveTransaction() member methods of Session object.
796
  {
2224.2.5 by Olaf van der Spek
Undo partial commit
797
    my_error(ER_XAER_RMFAIL, MYF(0), xa_state_names[transaction.xid_state.xa_state]);
934.2.11 by Jay Pipes
Moves end_trans(), begin_trans(), end_active_trans() out of the parser module and adds startTransaction(), endTransaction(), and endActiveTransaction() member methods of Session object.
798
    return false;
799
  }
1054.1.8 by Brian Aker
Remove lock_tables list from session.
800
  if (options & (OPTION_NOT_AUTOCOMMIT | OPTION_BEGIN))
934.2.11 by Jay Pipes
Moves end_trans(), begin_trans(), end_active_trans() out of the parser module and adds startTransaction(), endTransaction(), and endActiveTransaction() member methods of Session object.
801
  {
802
    server_status&= ~SERVER_STATUS_IN_TRANS;
2318.6.62 by Olaf van der Spek
Refactor
803
    if (TransactionServices::commitTransaction(*this, true))
934.2.11 by Jay Pipes
Moves end_trans(), begin_trans(), end_active_trans() out of the parser module and adds startTransaction(), endTransaction(), and endActiveTransaction() member methods of Session object.
804
      result= false;
805
  }
1172.1.2 by Brian Aker
Remove worthless call (ok... for not current replication system).
806
  options&= ~(OPTION_BEGIN);
934.2.11 by Jay Pipes
Moves end_trans(), begin_trans(), end_active_trans() out of the parser module and adds startTransaction(), endTransaction(), and endActiveTransaction() member methods of Session object.
807
  return result;
808
}
809
1206.1.3 by Brian Aker
Valgrind fix for startTransaction()
810
bool Session::startTransaction(start_transaction_option_t opt)
934.2.11 by Jay Pipes
Moves end_trans(), begin_trans(), end_active_trans() out of the parser module and adds startTransaction(), endTransaction(), and endActiveTransaction() member methods of Session object.
811
{
2275.2.6 by Olaf van der Spek
Refactor
812
  assert(not inTransaction());
2140.2.2 by Stewart Smith
change Session::startTransaction() to assert that there is not already a transaction in progress before starting one (i.e. NO IMPLICIT COMMIT)
813
814
  options|= OPTION_BEGIN;
815
  server_status|= SERVER_STATUS_IN_TRANS;
816
817
  if (plugin::TransactionalStorageEngine::notifyStartTransaction(this, opt))
2275.2.6 by Olaf van der Spek
Refactor
818
    return false;
819
  return true;
934.2.11 by Jay Pipes
Moves end_trans(), begin_trans(), end_active_trans() out of the parser module and adds startTransaction(), endTransaction(), and endActiveTransaction() member methods of Session object.
820
}
821
520.1.21 by Brian Aker
THD -> Session rename
822
void Session::cleanup_after_query()
1 by brian
clean slate
823
{
824
  /*
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
825
    Reset rand_used so that detection of calls to rand() will save random
1 by brian
clean slate
826
    seeds if needed by the slave.
827
  */
828
  if (first_successful_insert_id_in_cur_stmt > 0)
829
  {
830
    /* set what LAST_INSERT_ID() will return */
1055.2.17 by Jay Pipes
More style cleanups in Session
831
    first_successful_insert_id_in_prev_stmt= first_successful_insert_id_in_cur_stmt;
1 by brian
clean slate
832
    first_successful_insert_id_in_cur_stmt= 0;
51.1.50 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
833
    substitute_null_with_insert_id= true;
1 by brian
clean slate
834
  }
2114.4.10 by Brian Aker
Remove current_session from a couple of locations, encapsulate where in
835
1055.2.17 by Jay Pipes
More style cleanups in Session
836
  arg_of_last_insert_id_function= false;
2114.4.10 by Brian Aker
Remove current_session from a couple of locations, encapsulate where in
837
1 by brian
clean slate
838
  /* Free Items that were created during this execution */
839
  free_items();
2114.4.10 by Brian Aker
Remove current_session from a couple of locations, encapsulate where in
840
841
  /* Reset _where. */
842
  _where= Session::DEFAULT_WHERE;
1532.1.1 by Brian Aker
Merge of change to flip table instance to be share instance
843
844
  /* Reset the temporary shares we built */
2241.3.7 by Olaf van der Spek
Refactor
845
  impl_->temporary_shares.clear();
1 by brian
clean slate
846
}
847
848
/**
2371.1.2 by Brian Aker
Remove the typedef on lexkey
849
  Create a lex_string_t in this connection.
1 by brian
clean slate
850
2371.1.2 by Brian Aker
Remove the typedef on lexkey
851
  @param lex_str  pointer to lex_string_t object to be initialized
1 by brian
clean slate
852
  @param str      initializer to be copied into lex_str
853
  @param length   length of str, in bytes
2371.1.2 by Brian Aker
Remove the typedef on lexkey
854
  @param allocate_lex_string  if true, allocate new lex_string_t object,
1 by brian
clean slate
855
                              instead of using lex_str value
2371.1.2 by Brian Aker
Remove the typedef on lexkey
856
  @return  NULL on failure, or pointer to the lex_string_t object
1 by brian
clean slate
857
*/
2385.2.7 by Olaf van der Spek
Use str_ref
858
lex_string_t* Session::make_lex_string(lex_string_t* lex_str, str_ref str)
859
{
860
  if (not lex_str)
2371.1.2 by Brian Aker
Remove the typedef on lexkey
861
    lex_str= new (mem) lex_string_t;
2430.1.1 by Olaf van der Spek
Use lex_string assign(), data() and size()
862
  lex_str->assign(mem_root->strdup(str), str.size());
1 by brian
clean slate
863
  return lex_str;
864
}
865
2318.3.11 by Olaf van der Spek
Refactor
866
void Session::send_explain_fields(select_result *result)
1 by brian
clean slate
867
{
868
  List<Item> field_list;
869
  Item *item;
2318.3.11 by Olaf van der Spek
Refactor
870
  const charset_info_st* cs= system_charset_info;
212.2.2 by Patrick Galbraith
Renamed FIELD_TYPE to DRIZZLE_TYPE
871
  field_list.push_back(new Item_return_int("id",3, DRIZZLE_TYPE_LONGLONG));
1 by brian
clean slate
872
  field_list.push_back(new Item_empty_string("select_type", 19, cs));
873
  field_list.push_back(item= new Item_empty_string("table", NAME_CHAR_LEN, cs));
874
  item->maybe_null= 1;
875
  field_list.push_back(item= new Item_empty_string("type", 10, cs));
876
  item->maybe_null= 1;
2318.3.11 by Olaf van der Spek
Refactor
877
  field_list.push_back(item= new Item_empty_string("possible_keys", NAME_CHAR_LEN*MAX_KEY, cs));
1 by brian
clean slate
878
  item->maybe_null=1;
2318.3.11 by Olaf van der Spek
Refactor
879
  field_list.push_back(item= new Item_empty_string("key", NAME_CHAR_LEN, cs));
1 by brian
clean slate
880
  item->maybe_null=1;
2385.2.7 by Olaf van der Spek
Use str_ref
881
  field_list.push_back(item= new Item_empty_string("key_len", MAX_KEY * (MAX_KEY_LENGTH_DECIMAL_WIDTH + 1 /* for comma */), cs));
882
  item->maybe_null=1;
883
  field_list.push_back(item= new Item_empty_string("ref", NAME_CHAR_LEN*MAX_REF_PARTS, cs));
884
  item->maybe_null=1;
885
  field_list.push_back(item= new Item_return_int("rows", 10, DRIZZLE_TYPE_LONGLONG));
2227.4.8 by Olaf van der Spek
Session::lex()
886
  if (lex().describe & DESCRIBE_EXTENDED)
1 by brian
clean slate
887
  {
888
    field_list.push_back(item= new Item_float("filtered", 0.1234, 2, 4));
889
    item->maybe_null=1;
890
  }
891
  item->maybe_null= 1;
892
  field_list.push_back(new Item_empty_string("Extra", 255, cs));
2318.3.10 by Olaf van der Spek
Return void
893
  result->send_fields(field_list);
1 by brian
clean slate
894
}
895
2087.3.1 by Brian Aker
Entire convert over to time_t.
896
void select_result::send_error(drizzled::error_t errcode, const char *err)
1241.9.57 by Monty Taylor
Oy. Bigger change than I normally like - but this stuff is all intertwined.
897
{
898
  my_message(errcode, err, MYF(0));
899
}
900
1 by brian
clean slate
901
/************************************************************************
902
  Handling writing to file
903
************************************************************************/
904
2087.3.1 by Brian Aker
Entire convert over to time_t.
905
void select_to_file::send_error(drizzled::error_t errcode,const char *err)
1 by brian
clean slate
906
{
907
  my_message(errcode, err, MYF(0));
908
  if (file > 0)
909
  {
1909.1.1 by Brian Aker
Encapsulation of IO_CACHE.
910
    (void) cache->end_io_cache();
1280.1.10 by Monty Taylor
Put everything in drizzled into drizzled namespace.
911
    (void) internal::my_close(file, MYF(0));
1813.2.9 by Monty Taylor
Made data_home be fs::path natively.
912
    (void) internal::my_delete(path.file_string().c_str(), MYF(0));		// Delete file on error
1 by brian
clean slate
913
    file= -1;
914
  }
915
}
916
917
918
bool select_to_file::send_eof()
919
{
1909.1.1 by Brian Aker
Encapsulation of IO_CACHE.
920
  int error= test(cache->end_io_cache());
1280.1.10 by Monty Taylor
Put everything in drizzled into drizzled namespace.
921
  if (internal::my_close(file, MYF(MY_WME)))
1 by brian
clean slate
922
    error= 1;
923
  if (!error)
924
  {
925
    /*
926
      In order to remember the value of affected rows for ROW_COUNT()
927
      function, SELECT INTO has to have an own SQLCOM.
928
      TODO: split from SQLCOM_SELECT
929
    */
836 by Brian Aker
Fixed session call from function to method.
930
    session->my_ok(row_count);
1 by brian
clean slate
931
  }
932
  file= -1;
933
  return error;
934
}
935
936
937
void select_to_file::cleanup()
938
{
939
  /* In case of error send_eof() may be not called: close the file here. */
940
  if (file >= 0)
941
  {
1909.1.1 by Brian Aker
Encapsulation of IO_CACHE.
942
    (void) cache->end_io_cache();
1280.1.10 by Monty Taylor
Put everything in drizzled into drizzled namespace.
943
    (void) internal::my_close(file, MYF(0));
1 by brian
clean slate
944
    file= -1;
945
  }
1813.2.14 by Monty Taylor
Removed API element that SuSE and some older boosts don't have.
946
  path= "";
1 by brian
clean slate
947
  row_count= 0;
948
}
949
1241.9.49 by Monty Taylor
Removed one more public IO_CACHE.
950
select_to_file::select_to_file(file_exchange *ex)
1241.9.52 by Monty Taylor
Fixed valgrind issue.
951
  : exchange(ex),
952
    file(-1),
2296.1.1 by Mark Atwood
Merge in Fixes of Brian's IOCACHE.
953
    cache(static_cast<internal::io_cache_st *>(memory::sql_calloc(sizeof(internal::io_cache_st)))),
1241.9.52 by Monty Taylor
Fixed valgrind issue.
954
    row_count(0L)
1241.9.49 by Monty Taylor
Removed one more public IO_CACHE.
955
{
1813.2.14 by Monty Taylor
Removed API element that SuSE and some older boosts don't have.
956
  path= "";
1241.9.49 by Monty Taylor
Removed one more public IO_CACHE.
957
}
1 by brian
clean slate
958
959
select_to_file::~select_to_file()
960
{
1241.9.49 by Monty Taylor
Removed one more public IO_CACHE.
961
  cleanup();
1 by brian
clean slate
962
}
963
964
/***************************************************************************
965
** Export of select to textfile
966
***************************************************************************/
967
968
select_export::~select_export()
969
{
520.1.22 by Brian Aker
Second pass of thd cleanup
970
  session->sent_row_count=row_count;
1 by brian
clean slate
971
}
972
973
974
/*
975
  Create file with IO cache
976
977
  SYNOPSIS
978
    create_file()
520.1.22 by Brian Aker
Second pass of thd cleanup
979
    session			Thread handle
1 by brian
clean slate
980
    path		File name
981
    exchange		Excange class
982
    cache		IO cache
983
984
  RETURN
985
    >= 0 	File handle
986
   -1		Error
987
*/
988
989
2318.6.43 by Olaf van der Spek
Refactor
990
static int create_file(Session& session,
1813.2.9 by Monty Taylor
Made data_home be fs::path natively.
991
                       fs::path &target_path,
992
                       file_exchange *exchange,
2296.1.1 by Mark Atwood
Merge in Fixes of Brian's IOCACHE.
993
                       internal::io_cache_st *cache)
1 by brian
clean slate
994
{
1813.2.9 by Monty Taylor
Made data_home be fs::path natively.
995
  fs::path to_file(exchange->file_name);
996
997
  if (not to_file.has_root_directory())
1 by brian
clean slate
998
  {
1813.2.9 by Monty Taylor
Made data_home be fs::path natively.
999
    target_path= fs::system_complete(getDataHomeCatalog());
2318.6.43 by Olaf van der Spek
Refactor
1000
    util::string::ptr schema(session.schema());
2275.2.6 by Olaf van der Spek
Refactor
1001
    if (not schema->empty())
1813.2.9 by Monty Taylor
Made data_home be fs::path natively.
1002
    {
1003
      int count_elements= 0;
2318.6.43 by Olaf van der Spek
Refactor
1004
      for (fs::path::iterator it= to_file.begin(); it != to_file.end(); it++)
1005
        count_elements++;
1813.2.9 by Monty Taylor
Made data_home be fs::path natively.
1006
      if (count_elements == 1)
1976.5.2 by Brian Aker
This resolves the issue where one thread may be looking at schema while
1007
        target_path /= *schema;
1813.2.9 by Monty Taylor
Made data_home be fs::path natively.
1008
    }
1009
    target_path /= to_file;
1 by brian
clean slate
1010
  }
1011
  else
1813.2.9 by Monty Taylor
Made data_home be fs::path natively.
1012
  {
1013
    target_path = exchange->file_name;
1014
  }
1 by brian
clean slate
1015
1813.2.6 by Monty Taylor
Made secure_file_priv be an fs::path from the beginning.
1016
  if (not secure_file_priv.string().empty())
1 by brian
clean slate
1017
  {
1813.2.10 by Monty Taylor
Expand secure-file-priv once at startup rather than on each path check.
1018
    if (target_path.file_string().substr(0, secure_file_priv.file_string().size()) != secure_file_priv.file_string())
1786.3.2 by Monty Taylor
Cleaned up the initial pass at this. It's not perfect, but it does work.
1019
    {
1020
      /* Write only allowed to dir or subdir specified by secure_file_priv */
1021
      my_error(ER_OPTION_PREVENTS_STATEMENT, MYF(0), "--secure-file-priv");
1022
      return -1;
1023
    }
1 by brian
clean slate
1024
  }
1025
1813.2.9 by Monty Taylor
Made data_home be fs::path natively.
1026
  if (!access(target_path.file_string().c_str(), F_OK))
1 by brian
clean slate
1027
  {
1028
    my_error(ER_FILE_EXISTS_ERROR, MYF(0), exchange->file_name);
1029
    return -1;
1030
  }
1031
  /* Create the file world readable */
2318.6.43 by Olaf van der Spek
Refactor
1032
  int file= internal::my_create(target_path.file_string().c_str(), 0666, O_WRONLY|O_EXCL, MYF(MY_WME));
1033
  if (file < 0)
1 by brian
clean slate
1034
    return file;
1035
  (void) fchmod(file, 0666);			// Because of umask()
2318.6.43 by Olaf van der Spek
Refactor
1036
  if (cache->init_io_cache(file, 0, internal::WRITE_CACHE, 0L, 1, MYF(MY_WME)))
1 by brian
clean slate
1037
  {
1280.1.10 by Monty Taylor
Put everything in drizzled into drizzled namespace.
1038
    internal::my_close(file, MYF(0));
1813.2.9 by Monty Taylor
Made data_home be fs::path natively.
1039
    internal::my_delete(target_path.file_string().c_str(), MYF(0));  // Delete file on error, it was just created
1 by brian
clean slate
1040
    return -1;
1041
  }
1042
  return file;
1043
}
1044
1045
1046
int
848 by Brian Aker
typdef class removal (just... use the name of the class).
1047
select_export::prepare(List<Item> &list, Select_Lex_Unit *u)
1 by brian
clean slate
1048
{
1049
  bool blob_flag=0;
51.1.50 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
1050
  bool string_results= false, non_string_results= false;
1 by brian
clean slate
1051
  unit= u;
895 by Brian Aker
Completion (?) of uint conversion.
1052
  if ((uint32_t) strlen(exchange->file_name) + NAME_LEN >= FN_REFLEN)
1813.2.9 by Monty Taylor
Made data_home be fs::path natively.
1053
  {
1054
    path= exchange->file_name;
1055
  }
1 by brian
clean slate
1056
1057
  /* Check if there is any blobs in data */
1058
  {
2183.2.12 by Olaf van der Spek
Use List::begin()
1059
    List<Item>::iterator li(list.begin());
2385.3.14 by Olaf van der Spek
Remove unused Session::query_cache_key var
1060
    while (Item* item= li++)
1 by brian
clean slate
1061
    {
1062
      if (item->max_length >= MAX_BLOB_WIDTH)
1063
      {
2008 by Brian Aker
Formatting + remove default from switch/case.
1064
        blob_flag=1;
1065
        break;
1 by brian
clean slate
1066
      }
2008 by Brian Aker
Formatting + remove default from switch/case.
1067
1 by brian
clean slate
1068
      if (item->result_type() == STRING_RESULT)
51.1.50 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
1069
        string_results= true;
1 by brian
clean slate
1070
      else
51.1.50 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
1071
        non_string_results= true;
1 by brian
clean slate
1072
    }
1073
  }
1074
  field_term_length=exchange->field_term->length();
1075
  field_term_char= field_term_length ?
481 by Brian Aker
Remove all of uchar.
1076
                   (int) (unsigned char) (*exchange->field_term)[0] : INT_MAX;
1 by brian
clean slate
1077
  if (!exchange->line_term->length())
1078
    exchange->line_term=exchange->field_term;	// Use this if it exists
2318.7.11 by Olaf van der Spek
Use String::c_str() instead of c_ptr_safe()
1079
  field_sep_char= exchange->enclosed->length() ? (int) (unsigned char) (*exchange->enclosed)[0] : field_term_char;
1080
  escape_char= exchange->escaped->length() ? (int) (unsigned char) (*exchange->escaped)[0] : -1;
1 by brian
clean slate
1081
  is_ambiguous_field_sep= test(strchr(ESCAPE_CHARS, field_sep_char));
1082
  is_unsafe_field_sep= test(strchr(NUMERIC_CHARS, field_sep_char));
2318.7.11 by Olaf van der Spek
Use String::c_str() instead of c_ptr_safe()
1083
  line_sep_char= exchange->line_term->length() ? (int) (unsigned char) (*exchange->line_term)[0] : INT_MAX;
1 by brian
clean slate
1084
  if (!field_term_length)
1085
    exchange->opt_enclosed=0;
1086
  if (!exchange->enclosed->length())
1087
    exchange->opt_enclosed=1;			// A little quicker loop
1088
  fixed_row_size= (!field_term_length && !exchange->enclosed->length() &&
1089
		   !blob_flag);
2318.7.11 by Olaf van der Spek
Use String::c_str() instead of c_ptr_safe()
1090
  if ((is_ambiguous_field_sep && exchange->enclosed->empty() && (string_results || is_unsafe_field_sep)) ||
1091
      (exchange->opt_enclosed && non_string_results && field_term_length && strchr(NUMERIC_CHARS, field_term_char)))
1 by brian
clean slate
1092
  {
673.3.8 by Stewart Smith
fix outfile_loaddata test for drizzle.
1093
    my_error(ER_AMBIGUOUS_FIELD_TERM, MYF(0));
1094
    return 1;
1 by brian
clean slate
1095
  }
673.3.8 by Stewart Smith
fix outfile_loaddata test for drizzle.
1096
2318.6.43 by Olaf van der Spek
Refactor
1097
  if ((file= create_file(*session, path, exchange, cache)) < 0)
673.3.8 by Stewart Smith
fix outfile_loaddata test for drizzle.
1098
    return 1;
1 by brian
clean slate
1099
1100
  return 0;
1101
}
1102
1103
bool select_export::send_data(List<Item> &items)
1104
{
1105
  char buff[MAX_FIELD_WIDTH],null_buff[2],space[MAX_FIELD_WIDTH];
1106
  bool space_inited=0;
1107
  String tmp(buff,sizeof(buff),&my_charset_bin),*res;
1108
  tmp.length(0);
1109
1110
  if (unit->offset_limit_cnt)
1111
  {						// using limit offset,count
1112
    unit->offset_limit_cnt--;
1864.3.18 by Brian Aker
REmove goto from session.
1113
    return false;
1 by brian
clean slate
1114
  }
1115
  row_count++;
2183.2.19 by Olaf van der Spek
Use List::size()
1116
  uint32_t used_length=0,items_left=items.size();
2183.2.12 by Olaf van der Spek
Use List::begin()
1117
  List<Item>::iterator li(items.begin());
1 by brian
clean slate
1118
2385.3.13 by Olaf van der Spek
Refactor iocache
1119
  if (cache->write(exchange->line_start->ptr(), exchange->line_start->length()))
1864.3.18 by Brian Aker
REmove goto from session.
1120
    return true;
1121
2385.3.13 by Olaf van der Spek
Refactor iocache
1122
  while (Item* item=li++)
1 by brian
clean slate
1123
  {
1124
    Item_result result_type=item->result_type();
1125
    bool enclosed = (exchange->enclosed->length() &&
1126
                     (!exchange->opt_enclosed || result_type == STRING_RESULT));
1127
    res=item->str_result(&tmp);
1128
    if (res && enclosed)
1129
    {
2385.3.13 by Olaf van der Spek
Refactor iocache
1130
      if (cache->write(exchange->enclosed->ptr(), exchange->enclosed->length()))
1864.3.18 by Brian Aker
REmove goto from session.
1131
        return true;
1 by brian
clean slate
1132
    }
1133
    if (!res)
1134
    {						// NULL
1135
      if (!fixed_row_size)
1136
      {
1208.3.2 by brian
Update for Cursor renaming.
1137
        if (escape_char != -1)			// Use \N syntax
1138
        {
1139
          null_buff[0]=escape_char;
1140
          null_buff[1]='N';
2385.3.13 by Olaf van der Spek
Refactor iocache
1141
          if (cache->write(null_buff, 2))
1864.3.18 by Brian Aker
REmove goto from session.
1142
            return true;
1208.3.2 by brian
Update for Cursor renaming.
1143
        }
2385.3.13 by Olaf van der Spek
Refactor iocache
1144
        else if (cache->write("NULL", 4))
1864.3.18 by Brian Aker
REmove goto from session.
1145
          return true;
1 by brian
clean slate
1146
      }
1147
      else
1148
      {
1208.3.2 by brian
Update for Cursor renaming.
1149
        used_length=0;				// Fill with space
1 by brian
clean slate
1150
      }
1151
    }
1152
    else
1153
    {
1154
      if (fixed_row_size)
1816.3.1 by Brian Aker
Convert sql_string to use size_t (this should clean up ICC warnings).
1155
        used_length= min(res->length(), static_cast<size_t>(item->max_length));
1 by brian
clean slate
1156
      else
1067.4.1 by Nathan Williams
First few changes at converting cmin to std::min.
1157
        used_length= res->length();
1158
1 by brian
clean slate
1159
      if ((result_type == STRING_RESULT || is_unsafe_field_sep) &&
1208.3.2 by brian
Update for Cursor renaming.
1160
          escape_char != -1)
1 by brian
clean slate
1161
      {
1162
        char *pos, *start, *end;
2445.1.7 by Olaf van der Spek
Refactor
1163
        const charset_info_st* const res_charset= res->charset();
748 by Brian Aker
Removal of client side collation.
1164
2445.1.7 by Olaf van der Spek
Refactor
1165
        for (start= pos= (char*) res->ptr(),end=pos+used_length; pos != end; pos++)
1208.3.2 by brian
Update for Cursor renaming.
1166
        {
1167
          if (use_mb(res_charset))
1168
          {
2445.1.7 by Olaf van der Spek
Refactor
1169
            if (int l= my_ismbchar(res_charset, pos, end))
1208.3.2 by brian
Update for Cursor renaming.
1170
            {
2445.1.7 by Olaf van der Spek
Refactor
1171
              pos += l - 1;
1208.3.2 by brian
Update for Cursor renaming.
1172
              continue;
1173
            }
1174
          }
1 by brian
clean slate
1175
1176
          /*
1177
            Special case when dumping BINARY/VARBINARY/BLOB values
1178
            for the clients with character sets big5, cp932, gbk and sjis,
1179
            which can have the escape character (0x5C "\" by default)
1180
            as the second byte of a multi-byte sequence.
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1181
1 by brian
clean slate
1182
            If
1183
            - pos[0] is a valid multi-byte head (e.g 0xEE) and
1184
            - pos[1] is 0x00, which will be escaped as "\0",
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1185
1 by brian
clean slate
1186
            then we'll get "0xEE + 0x5C + 0x30" in the output file.
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1187
1 by brian
clean slate
1188
            If this file is later loaded using this sequence of commands:
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1189
1 by brian
clean slate
1190
            mysql> create table t1 (a varchar(128)) character set big5;
327.1.5 by Brian Aker
Refactor around classes. TABLE_LIST has been factored out of table.h
1191
            mysql> LOAD DATA INFILE 'dump.txt' INTO Table t1;
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1192
1 by brian
clean slate
1193
            then 0x5C will be misinterpreted as the second byte
1194
            of a multi-byte character "0xEE + 0x5C", instead of
1195
            escape character for 0x00.
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1196
1 by brian
clean slate
1197
            To avoid this confusion, we'll escape the multi-byte
1198
            head character too, so the sequence "0xEE + 0x00" will be
1199
            dumped as "0x5C + 0xEE + 0x5C + 0x30".
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1200
1 by brian
clean slate
1201
            Note, in the condition below we only check if
1202
            mbcharlen is equal to 2, because there are no
1203
            character sets with mbmaxlen longer than 2
1204
            and with escape_with_backslash_is_dangerous set.
51.1.50 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
1205
            assert before the loop makes that sure.
1 by brian
clean slate
1206
          */
1207
2445.1.7 by Olaf van der Spek
Refactor
1208
          if (needs_escaping(*pos, enclosed) &&
1 by brian
clean slate
1209
              /*
1208.3.2 by brian
Update for Cursor renaming.
1210
                Don't escape field_term_char by doubling - doubling is only
1211
                valid for ENCLOSED BY characters:
1 by brian
clean slate
1212
              */
1213
              (enclosed || !is_ambiguous_field_term ||
481 by Brian Aker
Remove all of uchar.
1214
               (int) (unsigned char) *pos != field_term_char))
1 by brian
clean slate
1215
          {
1208.3.2 by brian
Update for Cursor renaming.
1216
            char tmp_buff[2];
481 by Brian Aker
Remove all of uchar.
1217
            tmp_buff[0]= ((int) (unsigned char) *pos == field_sep_char &&
2445.1.7 by Olaf van der Spek
Refactor
1218
                          is_ambiguous_field_sep) ? field_sep_char : escape_char;
1208.3.2 by brian
Update for Cursor renaming.
1219
            tmp_buff[1]= *pos ? *pos : '0';
2385.3.13 by Olaf van der Spek
Refactor iocache
1220
            if (cache->write(start, pos - start) || cache->write(tmp_buff, 2))
1864.3.18 by Brian Aker
REmove goto from session.
1221
              return true;
1208.3.2 by brian
Update for Cursor renaming.
1222
            start=pos+1;
1223
          }
1224
        }
2385.3.13 by Olaf van der Spek
Refactor iocache
1225
        if (cache->write(start, pos - start))
1864.3.18 by Brian Aker
REmove goto from session.
1226
          return true;
1 by brian
clean slate
1227
      }
2385.3.13 by Olaf van der Spek
Refactor iocache
1228
      else if (cache->write(res->ptr(), used_length))
1864.3.18 by Brian Aker
REmove goto from session.
1229
        return true;
1 by brian
clean slate
1230
    }
1231
    if (fixed_row_size)
1232
    {						// Fill with space
1233
      if (item->max_length > used_length)
1234
      {
1208.3.2 by brian
Update for Cursor renaming.
1235
        /* QQ:  Fix by adding a my_b_fill() function */
1236
        if (!space_inited)
1237
        {
1238
          space_inited=1;
1239
          memset(space, ' ', sizeof(space));
1240
        }
1241
        uint32_t length=item->max_length-used_length;
1242
        for (; length > sizeof(space) ; length-=sizeof(space))
1243
        {
2385.3.13 by Olaf van der Spek
Refactor iocache
1244
          if (cache->write(space, sizeof(space)))
1864.3.18 by Brian Aker
REmove goto from session.
1245
            return true;
1208.3.2 by brian
Update for Cursor renaming.
1246
        }
2385.3.13 by Olaf van der Spek
Refactor iocache
1247
        if (cache->write(space, length))
1864.3.18 by Brian Aker
REmove goto from session.
1248
          return true;
1 by brian
clean slate
1249
      }
1250
    }
1251
    if (res && enclosed)
1252
    {
2385.3.13 by Olaf van der Spek
Refactor iocache
1253
      if (cache->write(exchange->enclosed->ptr(), exchange->enclosed->length()))
1864.3.18 by Brian Aker
REmove goto from session.
1254
        return true;
1 by brian
clean slate
1255
    }
1256
    if (--items_left)
1257
    {
2385.3.13 by Olaf van der Spek
Refactor iocache
1258
      if (cache->write(exchange->field_term->ptr(), field_term_length))
1864.3.18 by Brian Aker
REmove goto from session.
1259
        return true;
1 by brian
clean slate
1260
    }
1261
  }
2385.3.13 by Olaf van der Spek
Refactor iocache
1262
  if (cache->write(exchange->line_term->ptr(), exchange->line_term->length()))
1864.3.18 by Brian Aker
REmove goto from session.
1263
  {
1264
    return true;
1265
  }
1266
1267
  return false;
1 by brian
clean slate
1268
}
1269
1270
1271
/***************************************************************************
1272
** Dump  of select to a binary file
1273
***************************************************************************/
1274
1275
1276
int
848 by Brian Aker
typdef class removal (just... use the name of the class).
1277
select_dump::prepare(List<Item> &, Select_Lex_Unit *u)
1 by brian
clean slate
1278
{
1279
  unit= u;
2318.6.43 by Olaf van der Spek
Refactor
1280
  return (file= create_file(*session, path, exchange, cache)) < 0;
1 by brian
clean slate
1281
}
1282
1283
1284
bool select_dump::send_data(List<Item> &items)
1285
{
2183.2.12 by Olaf van der Spek
Use List::begin()
1286
  List<Item>::iterator li(items.begin());
1 by brian
clean slate
1287
  char buff[MAX_FIELD_WIDTH];
1288
  String tmp(buff,sizeof(buff),&my_charset_bin),*res;
1289
  tmp.length(0);
1290
1291
  if (unit->offset_limit_cnt)
1292
  {						// using limit offset,count
1293
    unit->offset_limit_cnt--;
2318.6.58 by Olaf van der Spek
Refactor
1294
    return 0;
1 by brian
clean slate
1295
  }
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1296
  if (row_count++ > 1)
1 by brian
clean slate
1297
  {
1298
    my_message(ER_TOO_MANY_ROWS, ER(ER_TOO_MANY_ROWS), MYF(0));
1813.2.12 by Monty Taylor
Made load_file work properly with throwing errors and opening files.
1299
    return 1;
1 by brian
clean slate
1300
  }
2385.2.10 by Olaf van der Spek
Refactor
1301
  while (Item* item=li++)
1 by brian
clean slate
1302
  {
1303
    res=item->str_result(&tmp);
1304
    if (!res)					// If NULL
1305
    {
2385.3.13 by Olaf van der Spek
Refactor iocache
1306
      if (cache->write("", 1))
1813.2.12 by Monty Taylor
Made load_file work properly with throwing errors and opening files.
1307
        return 1;
1 by brian
clean slate
1308
    }
2385.3.13 by Olaf van der Spek
Refactor iocache
1309
    else if (cache->write(res->ptr(), res->length()))
1 by brian
clean slate
1310
    {
1813.2.9 by Monty Taylor
Made data_home be fs::path natively.
1311
      my_error(ER_ERROR_ON_WRITE, MYF(0), path.file_string().c_str(), errno);
1813.2.12 by Monty Taylor
Made load_file work properly with throwing errors and opening files.
1312
      return 1;
1 by brian
clean slate
1313
    }
1314
  }
2318.6.58 by Olaf van der Spek
Refactor
1315
  return 0;
1 by brian
clean slate
1316
}
1317
1318
1319
select_subselect::select_subselect(Item_subselect *item_arg)
1320
{
1321
  item= item_arg;
1322
}
1323
1324
1325
bool select_singlerow_subselect::send_data(List<Item> &items)
1326
{
1327
  Item_singlerow_subselect *it= (Item_singlerow_subselect *)item;
1328
  if (it->assigned())
1329
  {
1330
    my_message(ER_SUBQUERY_NO_1_ROW, ER(ER_SUBQUERY_NO_1_ROW), MYF(0));
2318.6.77 by Olaf van der Spek
Refactor
1331
    return 1;
1 by brian
clean slate
1332
  }
1333
  if (unit->offset_limit_cnt)
1334
  {				          // Using limit offset,count
1335
    unit->offset_limit_cnt--;
2318.6.58 by Olaf van der Spek
Refactor
1336
    return 0;
1 by brian
clean slate
1337
  }
2183.2.12 by Olaf van der Spek
Use List::begin()
1338
  List<Item>::iterator li(items.begin());
1 by brian
clean slate
1339
  Item *val_item;
482 by Brian Aker
Remove uint.
1340
  for (uint32_t i= 0; (val_item= li++); i++)
1 by brian
clean slate
1341
    it->store(i, val_item);
1342
  it->assigned(1);
2318.6.58 by Olaf van der Spek
Refactor
1343
  return 0;
1 by brian
clean slate
1344
}
1345
1346
1347
void select_max_min_finder_subselect::cleanup()
1348
{
1349
  cache= 0;
1350
}
1351
1352
1353
bool select_max_min_finder_subselect::send_data(List<Item> &items)
1354
{
1355
  Item_maxmin_subselect *it= (Item_maxmin_subselect *)item;
2183.2.12 by Olaf van der Spek
Use List::begin()
1356
  List<Item>::iterator li(items.begin());
1 by brian
clean slate
1357
  Item *val_item= li++;
1358
  it->register_value();
1359
  if (it->assigned())
1360
  {
1361
    cache->store(val_item);
1362
    if ((this->*op)())
1363
      it->store(0, cache);
1364
  }
1365
  else
1366
  {
1367
    if (!cache)
1368
    {
1369
      cache= Item_cache::get_cache(val_item);
1370
      switch (val_item->result_type())
1371
      {
1372
      case REAL_RESULT:
1843.7.1 by Brian Aker
Convert vector to list (it will make deletion a bit faster).
1373
        op= &select_max_min_finder_subselect::cmp_real;
1374
        break;
1 by brian
clean slate
1375
      case INT_RESULT:
1843.7.1 by Brian Aker
Convert vector to list (it will make deletion a bit faster).
1376
        op= &select_max_min_finder_subselect::cmp_int;
1377
        break;
1 by brian
clean slate
1378
      case STRING_RESULT:
1843.7.1 by Brian Aker
Convert vector to list (it will make deletion a bit faster).
1379
        op= &select_max_min_finder_subselect::cmp_str;
1380
        break;
1 by brian
clean slate
1381
      case DECIMAL_RESULT:
1382
        op= &select_max_min_finder_subselect::cmp_decimal;
1383
        break;
1384
      case ROW_RESULT:
1385
        // This case should never be choosen
1843.7.1 by Brian Aker
Convert vector to list (it will make deletion a bit faster).
1386
        assert(0);
1387
        op= 0;
1 by brian
clean slate
1388
      }
1389
    }
1390
    cache->store(val_item);
1391
    it->store(0, cache);
1392
  }
1393
  it->assigned(1);
2318.6.58 by Olaf van der Spek
Refactor
1394
  return 0;
1 by brian
clean slate
1395
}
1396
1397
bool select_max_min_finder_subselect::cmp_real()
1398
{
1399
  Item *maxmin= ((Item_singlerow_subselect *)item)->element_index(0);
1400
  double val1= cache->val_real(), val2= maxmin->val_real();
1401
  if (fmax)
1402
    return (cache->null_value && !maxmin->null_value) ||
1403
      (!cache->null_value && !maxmin->null_value &&
1404
       val1 > val2);
1405
  return (maxmin->null_value && !cache->null_value) ||
1406
    (!cache->null_value && !maxmin->null_value &&
1407
     val1 < val2);
1408
}
1409
1410
bool select_max_min_finder_subselect::cmp_int()
1411
{
1412
  Item *maxmin= ((Item_singlerow_subselect *)item)->element_index(0);
152 by Brian Aker
longlong replacement
1413
  int64_t val1= cache->val_int(), val2= maxmin->val_int();
1 by brian
clean slate
1414
  if (fmax)
1415
    return (cache->null_value && !maxmin->null_value) ||
1416
      (!cache->null_value && !maxmin->null_value &&
1417
       val1 > val2);
1418
  return (maxmin->null_value && !cache->null_value) ||
1419
    (!cache->null_value && !maxmin->null_value &&
1420
     val1 < val2);
1421
}
1422
1423
bool select_max_min_finder_subselect::cmp_decimal()
1424
{
1425
  Item *maxmin= ((Item_singlerow_subselect *)item)->element_index(0);
2030.1.4 by Brian Aker
Change my_decimal to Decimal
1426
  type::Decimal cval, *cvalue= cache->val_decimal(&cval);
1427
  type::Decimal mval, *mvalue= maxmin->val_decimal(&mval);
1 by brian
clean slate
1428
  if (fmax)
1429
    return (cache->null_value && !maxmin->null_value) ||
1430
      (!cache->null_value && !maxmin->null_value &&
2030.1.2 by Brian Aker
First pass in refactoring of the name of my_decimal.
1431
       class_decimal_cmp(cvalue, mvalue) > 0) ;
1 by brian
clean slate
1432
  return (maxmin->null_value && !cache->null_value) ||
1433
    (!cache->null_value && !maxmin->null_value &&
2030.1.2 by Brian Aker
First pass in refactoring of the name of my_decimal.
1434
     class_decimal_cmp(cvalue,mvalue) < 0);
1 by brian
clean slate
1435
}
1436
1437
bool select_max_min_finder_subselect::cmp_str()
1438
{
1439
  String *val1, *val2, buf1, buf2;
1440
  Item *maxmin= ((Item_singlerow_subselect *)item)->element_index(0);
1441
  /*
1442
    as far as both operand is Item_cache buf1 & buf2 will not be used,
1443
    but added for safety
1444
  */
1445
  val1= cache->val_str(&buf1);
1446
  val2= maxmin->val_str(&buf1);
1447
  if (fmax)
1448
    return (cache->null_value && !maxmin->null_value) ||
1449
      (!cache->null_value && !maxmin->null_value &&
1450
       sortcmp(val1, val2, cache->collation.collation) > 0) ;
1451
  return (maxmin->null_value && !cache->null_value) ||
1452
    (!cache->null_value && !maxmin->null_value &&
1453
     sortcmp(val1, val2, cache->collation.collation) < 0);
1454
}
1455
779.1.27 by Monty Taylor
Got rid of __attribute__((unused)) and the like from the .cc files.
1456
bool select_exists_subselect::send_data(List<Item> &)
1 by brian
clean slate
1457
{
1458
  Item_exists_subselect *it= (Item_exists_subselect *)item;
1459
  if (unit->offset_limit_cnt)
77.1.45 by Monty Taylor
Warning fixes.
1460
  { // Using limit offset,count
1 by brian
clean slate
1461
    unit->offset_limit_cnt--;
2318.6.58 by Olaf van der Spek
Refactor
1462
    return 0;
1 by brian
clean slate
1463
  }
1464
  it->value= 1;
1465
  it->assigned(1);
2318.6.58 by Olaf van der Spek
Refactor
1466
  return 0;
1 by brian
clean slate
1467
}
1468
406 by Brian Aker
Cleanup around Query_arena.
1469
/*
1470
  Don't free mem_root, as mem_root is freed in the end of dispatch_command
1471
  (once for any command).
1472
*/
520.1.21 by Brian Aker
THD -> Session rename
1473
void Session::end_statement()
1 by brian
clean slate
1474
{
1475
  /* Cleanup SQL processing state to reuse this statement in next query. */
2227.4.8 by Olaf van der Spek
Session::lex()
1476
  lex().end();
1643.6.16 by Djellel E. Difallah
Fixing memory leaks
1477
  resetResultsetMessage();
1 by brian
clean slate
1478
}
1479
2430.1.9 by Olaf van der Spek
Add const
1480
str_ref Session::copy_db_to() const
202.3.6 by Monty Taylor
First pass at gettexizing the error messages.
1481
{
2430.1.9 by Olaf van der Spek
Add const
1482
  if (not impl_->schema->empty())
1483
    return str_ref(mem.strdup(*impl_->schema), impl_->schema->size());
1484
  my_message(ER_NO_DB_ERROR, ER(ER_NO_DB_ERROR), MYF(0));
1485
  return str_ref();
202.3.6 by Monty Taylor
First pass at gettexizing the error messages.
1486
}
1487
1101.1.16 by Monty Taylor
Reverted 1103
1488
/****************************************************************************
1489
  Tmp_Table_Param
1490
****************************************************************************/
1491
1492
void Tmp_Table_Param::init()
1493
{
1494
  field_count= sum_func_count= func_count= hidden_field_count= 0;
1495
  group_parts= group_length= group_null_parts= 0;
1496
  quick_group= 1;
1497
  table_charset= 0;
1498
  precomputed_group_by= 0;
1499
}
1500
2385.3.14 by Olaf van der Spek
Remove unused Session::query_cache_key var
1501
void Tmp_Table_Param::cleanup()
1101.1.16 by Monty Taylor
Reverted 1103
1502
{
1503
  /* Fix for Intel compiler */
1504
  if (copy_field)
1505
  {
2069.4.1 by Brian Aker
A little on the paranoid side, but not the worst plan ever to check our
1506
    boost::checked_array_delete(copy_field);
2053.3.1 by Andrew Hutchings
Clear copy_field completely to avoid stale pointer restore causing crash
1507
    save_copy_field= save_copy_field_end= copy_field= copy_field_end= 0;
1101.1.16 by Monty Taylor
Reverted 1103
1508
  }
1509
}
1510
520.1.21 by Brian Aker
THD -> Session rename
1511
void Session::send_kill_message() const
202.3.6 by Monty Taylor
First pass at gettexizing the error messages.
1512
{
2087.3.1 by Brian Aker
Entire convert over to time_t.
1513
  drizzled::error_t err= static_cast<drizzled::error_t>(killed_errno());
1514
  if (err != EE_OK)
202.3.6 by Monty Taylor
First pass at gettexizing the error messages.
1515
    my_message(err, ER(err), MYF(0));
1516
}
1 by brian
clean slate
1517
2385.1.7 by Olaf van der Spek
Rename set_db to set_schema
1518
void Session::set_schema(const std::string& new_db)
656.1.22 by Monty Taylor
Removed my_malloc related stuff from log_event and session.
1519
{
2269.1.7 by Olaf van der Spek
Use util::string::ptr
1520
  impl_->schema = boost::make_shared<std::string>(new_db);
656.1.22 by Monty Taylor
Removed my_malloc related stuff from log_event and session.
1521
}
1522
1273 by Brian Aker
Revert db patch.
1523
1 by brian
clean slate
1524
/**
1525
  Mark transaction to rollback and mark error as fatal to a sub-statement.
1526
520.1.22 by Brian Aker
Second pass of thd cleanup
1527
  @param  session   Thread handle
2224.2.3 by Olaf van der Spek
Refactor
1528
  @param  all   true <=> rollback main transaction().
1 by brian
clean slate
1529
*/
2153.1.2 by Stewart Smith
replace mark_transaction_to_rollback() with Session::markTransactionForRollback()
1530
void Session::markTransactionForRollback(bool all)
1 by brian
clean slate
1531
{
2153.1.2 by Stewart Smith
replace mark_transaction_to_rollback() with Session::markTransactionForRollback()
1532
  is_fatal_sub_stmt_error= true;
1533
  transaction_rollback_request= all;
1 by brian
clean slate
1534
}
1535
2269.1.7 by Olaf van der Spek
Use util::string::ptr
1536
void Session::disconnect(error_t errcode)
575.4.7 by Monty Taylor
More header cleanup.
1537
{
934.2.6 by Jay Pipes
This changeset removes a few more C functions from sql_connect.cc/connect.h
1538
  /* Allow any plugins to cleanup their session variables */
1539
  plugin_sessionvar_cleanup(this);
1540
1541
  /* If necessary, log any aborted or unauthorized connections */
1910.2.8 by Brian Aker
Enapsulate Kill.
1542
  if (getKilled() || client->wasAborted())
1537.2.1 by Joe Daly
add statistics_variables.h
1543
  {
1689.5.1 by Joseph Daly
remove increment calls
1544
    status_var.aborted_threads++;
1537.2.1 by Joe Daly
add statistics_variables.h
1545
  }
934.2.6 by Jay Pipes
This changeset removes a few more C functions from sql_connect.cc/connect.h
1546
971.6.1 by Eric Day
Renamed Protocol to Client, cleaned up some unnecessary methods along the way.
1547
  if (client->wasAborted())
934.2.6 by Jay Pipes
This changeset removes a few more C functions from sql_connect.cc/connect.h
1548
  {
1910.2.8 by Brian Aker
Enapsulate Kill.
1549
    if (not getKilled() && variables.log_warnings > 1)
934.2.6 by Jay Pipes
This changeset removes a few more C functions from sql_connect.cc/connect.h
1550
    {
2126.3.3 by Brian Aker
Merge in error message rework. Many error messages are fixed in this patch.
1551
      errmsg_printf(error::WARN, ER(ER_NEW_ABORTING_CONNECTION)
934.2.6 by Jay Pipes
This changeset removes a few more C functions from sql_connect.cc/connect.h
1552
                  , thread_id
2269.1.7 by Olaf van der Spek
Use util::string::ptr
1553
                  , (impl_->schema->empty() ? "unconnected" : impl_->schema->c_str())
2275.2.6 by Olaf van der Spek
Refactor
1554
                  , security_ctx->username().empty() ? "unauthenticated" : security_ctx->username().c_str()
2008.1.1 by Brian Aker
Adding user identifier that makes use of a shared ptr to handle concurrency
1555
                  , security_ctx->address().c_str()
2239.1.4 by Olaf van der Spek
Refactor includes
1556
                  , (main_da().is_error() ? main_da().message() : ER(ER_UNKNOWN_ERROR)));
934.2.6 by Jay Pipes
This changeset removes a few more C functions from sql_connect.cc/connect.h
1557
    }
1558
  }
1559
1910.2.8 by Brian Aker
Enapsulate Kill.
1560
  setKilled(Session::KILL_CONNECTION);
1561
971.6.1 by Eric Day
Renamed Protocol to Client, cleaned up some unnecessary methods along the way.
1562
  if (client->isConnected())
575.4.7 by Monty Taylor
More header cleanup.
1563
  {
2015.3.3 by Brian Aker
Update disconnect code.
1564
    if (errcode != EE_OK)
971.3.12 by Eric Day
Started abstracting Protocol, removed init_connect, init_file.
1565
    {
1566
      /*my_error(errcode, ER(errcode));*/
971.6.11 by Eric Day
Removed purecov messages.
1567
      client->sendError(errcode, ER(errcode));
971.3.12 by Eric Day
Started abstracting Protocol, removed init_connect, init_file.
1568
    }
971.6.1 by Eric Day
Renamed Protocol to Client, cleaned up some unnecessary methods along the way.
1569
    client->close();
575.4.7 by Monty Taylor
More header cleanup.
1570
  }
1571
}
735 by Brian Aker
Refactor session.
1572
1573
void Session::reset_for_next_command()
1574
{
1575
  free_list= 0;
1576
  select_number= 1;
1577
1055.2.17 by Jay Pipes
More style cleanups in Session
1578
  is_fatal_error= false;
735 by Brian Aker
Refactor session.
1579
  server_status&= ~ (SERVER_MORE_RESULTS_EXISTS |
1580
                          SERVER_QUERY_NO_INDEX_USED |
1581
                          SERVER_QUERY_NO_GOOD_INDEX_USED);
1582
1583
  clear_error();
2239.1.4 by Olaf van der Spek
Refactor includes
1584
  main_da().reset_diagnostics_area();
735 by Brian Aker
Refactor session.
1585
  total_warn_count=0;			// Warnings for this query
1586
  sent_row_count= examined_row_count= 0;
1587
}
793 by Brian Aker
Pass through on refactoring functions to clases.
1588
1589
/*
1590
  Close all temporary tables created by 'CREATE TEMPORARY TABLE' for thread
1591
*/
1592
2263.3.7 by Olaf van der Spek
Keep functions in Open_tables_state
1593
void Open_tables_state::close_temporary_tables()
793 by Brian Aker
Pass through on refactoring functions to clases.
1594
{
1595
  Table *table;
798.2.20 by Brian Aker
More cleanup of binlog.isopen
1596
  Table *tmp_next;
793 by Brian Aker
Pass through on refactoring functions to clases.
1597
1395.1.11 by Brian Aker
Rename of close_temporary to nukeTable() so that my regex will stop looking
1598
  if (not temporary_tables)
793 by Brian Aker
Pass through on refactoring functions to clases.
1599
    return;
1600
798.2.20 by Brian Aker
More cleanup of binlog.isopen
1601
  for (table= temporary_tables; table; table= tmp_next)
1602
  {
1608 by Brian Aker
This encapsulates prev/next.
1603
    tmp_next= table->getNext();
1395.1.11 by Brian Aker
Rename of close_temporary to nukeTable() so that my regex will stop looking
1604
    nukeTable(table);
798.2.20 by Brian Aker
More cleanup of binlog.isopen
1605
  }
1046.1.6 by Brian Aker
Formatting/style cleanup.
1606
  temporary_tables= NULL;
793 by Brian Aker
Pass through on refactoring functions to clases.
1607
}
855 by Brian Aker
Refactor reset of status.
1608
1109.1.1 by Brian Aker
Applying refactor of tmp table bits back to session. (this all needs to be
1609
/*
1610
  unlink from session->temporary tables and close temporary table
1611
*/
1612
2263.3.7 by Olaf van der Spek
Keep functions in Open_tables_state
1613
void Open_tables_state::close_temporary_table(Table *table)
1109.1.1 by Brian Aker
Applying refactor of tmp table bits back to session. (this all needs to be
1614
{
1608 by Brian Aker
This encapsulates prev/next.
1615
  if (table->getPrev())
1109.1.1 by Brian Aker
Applying refactor of tmp table bits back to session. (this all needs to be
1616
  {
1608 by Brian Aker
This encapsulates prev/next.
1617
    table->getPrev()->setNext(table->getNext());
1618
    if (table->getPrev()->getNext())
1619
    {
1620
      table->getNext()->setPrev(table->getPrev());
1621
    }
1109.1.1 by Brian Aker
Applying refactor of tmp table bits back to session. (this all needs to be
1622
  }
1623
  else
1624
  {
1625
    /* removing the item from the list */
1626
    assert(table == temporary_tables);
1627
    /*
1628
      slave must reset its temporary list pointer to zero to exclude
1629
      passing non-zero value to end_slave via rli->save_temporary_tables
1630
      when no temp tables opened, see an invariant below.
1631
    */
1608 by Brian Aker
This encapsulates prev/next.
1632
    temporary_tables= table->getNext();
1109.1.1 by Brian Aker
Applying refactor of tmp table bits back to session. (this all needs to be
1633
    if (temporary_tables)
1608 by Brian Aker
This encapsulates prev/next.
1634
    {
1635
      table->getNext()->setPrev(NULL);
1636
    }
1109.1.1 by Brian Aker
Applying refactor of tmp table bits back to session. (this all needs to be
1637
  }
1395.1.11 by Brian Aker
Rename of close_temporary to nukeTable() so that my regex will stop looking
1638
  nukeTable(table);
1109.1.1 by Brian Aker
Applying refactor of tmp table bits back to session. (this all needs to be
1639
}
1640
1641
/*
1395.1.11 by Brian Aker
Rename of close_temporary to nukeTable() so that my regex will stop looking
1642
  Close and drop a temporary table
1109.1.1 by Brian Aker
Applying refactor of tmp table bits back to session. (this all needs to be
1643
1644
  NOTE
1645
  This dosn't unlink table from session->temporary
1646
  If this is needed, use close_temporary_table()
1647
*/
1648
2263.3.7 by Olaf van der Spek
Keep functions in Open_tables_state
1649
void Open_tables_state::nukeTable(Table *table)
1109.1.1 by Brian Aker
Applying refactor of tmp table bits back to session. (this all needs to be
1650
{
2246.4.3 by Olaf van der Spek
Refactor Session
1651
  plugin::StorageEngine& table_type= *table->getShare()->db_type();
1109.1.4 by Brian Aker
More Table refactor
1652
  table->free_io_cache();
1672.3.2 by Brian Aker
Tiny little cleanup around Table.
1653
  table->delete_table();
2246.4.3 by Olaf van der Spek
Refactor Session
1654
  rm_temporary_table(table_type, identifier::Table(table->getShare()->getSchemaName(), table->getShare()->getTableName(), table->getShare()->getPath()));
2069.4.1 by Brian Aker
A little on the paranoid side, but not the worst plan ever to check our
1655
  boost::checked_delete(table->getMutableShare());
1656
  boost::checked_delete(table);
1109.1.1 by Brian Aker
Applying refactor of tmp table bits back to session. (this all needs to be
1657
}
855 by Brian Aker
Refactor reset of status.
1658
1659
/** Clear most status variables. */
1660
extern time_t flush_status_time;
1661
1662
void Session::refresh_status()
1663
{
1664
  /* Reset thread's status variables */
1665
  memset(&status_var, 0, sizeof(status_var));
1666
1667
  flush_status_time= time((time_t*) 0);
1537.2.1 by Joe Daly
add statistics_variables.h
1668
  current_global_counters.max_used_connections= 1; /* We set it to one, because we know we exist */
1726.3.3 by LinuxJedi
Add a proper connections counter.
1669
  current_global_counters.connections= 0;
855 by Brian Aker
Refactor reset of status.
1670
}
995 by Brian Aker
Refactor get_variable to session
1671
2440.2.9 by Olaf van der Spek
Refactor
1672
user_var_entry* Session::getVariable(str_ref name0, bool create_if_not_exists)
1836.4.1 by Brian Aker
Adding in more test case for events (though these do not really have the
1673
{
2132.2.1 by Andrew Hutchings
Don't touch user vars after the have already been cleaned up
1674
  if (cleanup_done)
1675
    return NULL;
995 by Brian Aker
Refactor get_variable to session
1676
2440.2.9 by Olaf van der Spek
Refactor
1677
  string name(name0.data(), name0.size());
2192.4.1 by Olaf van der Spek
Add find_ptr
1678
  if (UserVars::mapped_type* iter= find_ptr(user_vars, name))
1679
    return *iter;
995 by Brian Aker
Refactor get_variable to session
1680
1859.3.1 by Brian Aker
Slight refactor of the uservar class.
1681
  if (not create_if_not_exists)
1682
    return NULL;
1683
2246.3.1 by Olaf van der Spek
Remove std::nothrow from new()
1684
  user_var_entry *entry= new user_var_entry(name.c_str(), query_id);
1859.3.1 by Brian Aker
Slight refactor of the uservar class.
1685
1686
  std::pair<UserVars::iterator, bool> returnable= user_vars.insert(make_pair(name, entry));
1687
1688
  if (not returnable.second)
995 by Brian Aker
Refactor get_variable to session
1689
  {
2069.4.1 by Brian Aker
A little on the paranoid side, but not the worst plan ever to check our
1690
    boost::checked_delete(entry);
995 by Brian Aker
Refactor get_variable to session
1691
  }
1692
1693
  return entry;
1694
}
1039.1.16 by Brian Aker
A lot of little cleanups (most based off lcov)
1695
1836.4.1 by Brian Aker
Adding in more test case for events (though these do not really have the
1696
void Session::setVariable(const std::string &name, const std::string &value)
1697
{
2440.2.9 by Olaf van der Spek
Refactor
1698
  if (user_var_entry* var= getVariable(name, true))
2132.2.1 by Andrew Hutchings
Don't touch user vars after the have already been cleaned up
1699
  {
2440.2.10 by Olaf van der Spek
Use data_ref
1700
    var->update_hash(false, value, STRING_RESULT, &my_charset_bin, DERIVATION_IMPLICIT, false);
2132.2.1 by Andrew Hutchings
Don't touch user vars after the have already been cleaned up
1701
  }
1836.4.1 by Brian Aker
Adding in more test case for events (though these do not really have the
1702
}
1703
1922.1.1 by Brian Aker
Move temp tables down to open_table class. (first pass)
1704
void Open_tables_state::mark_temp_tables_as_free_for_reuse()
1039.1.16 by Brian Aker
A lot of little cleanups (most based off lcov)
1705
{
1608 by Brian Aker
This encapsulates prev/next.
1706
  for (Table *table= temporary_tables ; table ; table= table->getNext())
1039.1.16 by Brian Aker
A lot of little cleanups (most based off lcov)
1707
  {
2263.3.10 by Olaf van der Spek
Open Tables
1708
    if (table->query_id == session_.getQueryId())
1039.1.16 by Brian Aker
A lot of little cleanups (most based off lcov)
1709
    {
1710
      table->query_id= 0;
1208.3.2 by brian
Update for Cursor renaming.
1711
      table->cursor->ha_reset();
1039.1.16 by Brian Aker
A lot of little cleanups (most based off lcov)
1712
    }
1713
  }
1714
}
1715
1716
/*
1055.2.24 by Jay Pipes
Merge with trunk and resolve conflicts.
1717
  Unlocks tables and frees derived tables.
1718
  Put all normal tables used by thread in free list.
1719
1720
  It will only close/mark as free for reuse tables opened by this
1721
  substatement, it will also check if we are closing tables after
1722
  execution of complete query (i.e. we are on upper level) and will
1723
  leave prelocked mode if needed.
1039.1.16 by Brian Aker
A lot of little cleanups (most based off lcov)
1724
*/
1725
void Session::close_thread_tables()
1726
{
2263.3.10 by Olaf van der Spek
Open Tables
1727
  open_tables.clearDerivedTables();
1039.1.16 by Brian Aker
A lot of little cleanups (most based off lcov)
1728
1729
  /*
1730
    Mark all temporary tables used by this statement as free for reuse.
1731
  */
2263.3.10 by Olaf van der Spek
Open Tables
1732
  open_tables.mark_temp_tables_as_free_for_reuse();
1039.1.16 by Brian Aker
A lot of little cleanups (most based off lcov)
1733
  /*
1734
    Let us commit transaction for statement. Since in 5.0 we only have
1735
    one statement transaction and don't allow several nested statement
1736
    transactions this call will do nothing if we are inside of stored
1737
    function or trigger (i.e. statement transaction is already active and
1738
    does not belong to statement for which we do close_thread_tables()).
1739
    TODO: This should be fixed in later releases.
1740
   */
1741
  {
2239.1.4 by Olaf van der Spek
Refactor includes
1742
    main_da().can_overwrite_status= true;
2318.6.62 by Olaf van der Spek
Refactor
1743
    TransactionServices::autocommitOrRollback(*this, is_error());
2239.1.4 by Olaf van der Spek
Refactor includes
1744
    main_da().can_overwrite_status= false;
2224.2.5 by Olaf van der Spek
Undo partial commit
1745
    transaction.stmt.reset();
1039.1.16 by Brian Aker
A lot of little cleanups (most based off lcov)
1746
  }
1747
2263.3.10 by Olaf van der Spek
Open Tables
1748
  if (open_tables.lock)
1039.1.16 by Brian Aker
A lot of little cleanups (most based off lcov)
1749
  {
1750
    /*
1751
      For RBR we flush the pending event just before we unlock all the
1752
      tables.  This means that we are at the end of a topmost
1753
      statement, so we ensure that the STMT_END_F flag is set on the
1754
      pending event.  For statements that are *inside* stored
1755
      functions, the pending event will not be flushed: that will be
1756
      handled either before writing a query log event (inside
1757
      binlog_query()) or when preparing a pending event.
1758
     */
2263.3.10 by Olaf van der Spek
Open Tables
1759
    unlockTables(open_tables.lock);
1760
    open_tables.lock= 0;
1039.1.16 by Brian Aker
A lot of little cleanups (most based off lcov)
1761
  }
1762
  /*
2275.3.1 by Olaf van der Spek
Remove table::Cache::singleton()
1763
    Note that we need to hold table::Cache::mutex() while changing the
1039.1.16 by Brian Aker
A lot of little cleanups (most based off lcov)
1764
    open_tables list. Another thread may work on it.
2275.3.1 by Olaf van der Spek
Remove table::Cache::singleton()
1765
    (See: table::Cache::removeTable(), wait_completed_table())
1039.1.16 by Brian Aker
A lot of little cleanups (most based off lcov)
1766
    Closing a MERGE child before the parent would be fatal if the
1767
    other thread tries to abort the MERGE lock in between.
1768
  */
2263.3.10 by Olaf van der Spek
Open Tables
1769
  if (open_tables.open_tables_)
2280.1.10 by Olaf van der Spek
Remove unused param
1770
    open_tables.close_open_tables();
1039.1.16 by Brian Aker
A lot of little cleanups (most based off lcov)
1771
}
1054.1.9 by Brian Aker
This is a large number of refactors against the Session class for its
1772
1773
void Session::close_tables_for_reopen(TableList **tables)
1774
{
1775
  /*
1776
    If table list consists only from tables from prelocking set, table list
1777
    for new attempt should be empty, so we have to update list's root pointer.
1778
  */
2227.4.8 by Olaf van der Spek
Session::lex()
1779
  if (lex().first_not_own_table() == *tables)
1054.1.9 by Brian Aker
This is a large number of refactors against the Session class for its
1780
    *tables= 0;
2227.4.8 by Olaf van der Spek
Session::lex()
1781
  lex().chop_off_not_own_tables();
1054.1.9 by Brian Aker
This is a large number of refactors against the Session class for its
1782
  for (TableList *tmp= *tables; tmp; tmp= tmp->next_global)
1783
    tmp->table= 0;
1784
  close_thread_tables();
1785
}
1786
1109.1.3 by Brian Aker
Move names around a bit (to align similar methods)
1787
bool Session::openTablesLock(TableList *tables)
1054.1.9 by Brian Aker
This is a large number of refactors against the Session class for its
1788
{
1789
  uint32_t counter;
1790
  bool need_reopen;
1791
1792
  for ( ; ; )
1793
  {
1109.1.2 by Brian Aker
More from the table patch
1794
    if (open_tables_from_list(&tables, &counter))
1795
      return true;
1054.1.9 by Brian Aker
This is a large number of refactors against the Session class for its
1796
1415 by Brian Aker
Mass overhaul to use schema_identifier.
1797
    if (not lock_tables(tables, counter, &need_reopen))
1054.1.9 by Brian Aker
This is a large number of refactors against the Session class for its
1798
      break;
2060.3.1 by Brian Aker
First pass, remove retry.
1799
1415 by Brian Aker
Mass overhaul to use schema_identifier.
1800
    if (not need_reopen)
1109.1.2 by Brian Aker
More from the table patch
1801
      return true;
2060.3.1 by Brian Aker
First pass, remove retry.
1802
1054.1.9 by Brian Aker
This is a large number of refactors against the Session class for its
1803
    close_tables_for_reopen(&tables);
1804
  }
2060.3.1 by Brian Aker
First pass, remove retry.
1805
2227.4.10 by Olaf van der Spek
Session::lex()
1806
  return handle_derived(&lex(), &derived_prepare) || handle_derived(&lex(), &derived_filling);
1054.1.9 by Brian Aker
This is a large number of refactors against the Session class for its
1807
}
1808
1608.2.1 by Brian Aker
Modified to table identifier to fix temporary table creation loss of file.
1809
/*
1810
  @note "best_effort" is used in cases were if a failure occurred on this
1811
  operation it would not be surprising because we are only removing because there
1812
  might be an issue (lame engines).
1813
*/
1814
2263.3.7 by Olaf van der Spek
Keep functions in Open_tables_state
1815
bool Open_tables_state::rm_temporary_table(const identifier::Table &identifier, bool best_effort)
1223.4.8 by Brian Aker
More table identifier love :)
1816
{
2263.3.9 by Olaf van der Spek
Open Tables
1817
  if (plugin::StorageEngine::dropTable(session_, identifier))
2246.4.3 by Olaf van der Spek
Refactor Session
1818
		return false;
1819
  if (not best_effort)
1820
    errmsg_printf(error::WARN, _("Could not remove temporary table: '%s', error: %d"), identifier.getSQLPath().c_str(), errno);
1821
  return true;
1223.4.8 by Brian Aker
More table identifier love :)
1822
}
1823
2263.3.7 by Olaf van der Spek
Keep functions in Open_tables_state
1824
bool Open_tables_state::rm_temporary_table(plugin::StorageEngine& base, const identifier::Table &identifier)
1109.1.1 by Brian Aker
Applying refactor of tmp table bits back to session. (this all needs to be
1825
{
2068.7.1 by Brian Aker
First pass through error correction in SE interface for drop table.
1826
  drizzled::error_t error;
2263.3.9 by Olaf van der Spek
Open Tables
1827
  if (plugin::StorageEngine::dropTable(session_, base, identifier, error))
2246.4.2 by Olaf van der Spek
Refactor Identifier::getSQLPath()
1828
		return false;
1829
  errmsg_printf(error::WARN, _("Could not remove temporary table: '%s', error: %d"), identifier.getSQLPath().c_str(), error);
1830
  return true;
1395.1.12 by Brian Aker
Fixes failure related to Heap's hack on deletion. Also cleans up error
1831
}
1832
2241.3.6 by Olaf van der Spek
Refactor
1833
table::Singular& Session::getInstanceTable()
1618 by Brian Aker
This is a rollup set of patches for modifications to TableIdentifier to have
1834
{
2241.3.7 by Olaf van der Spek
Refactor
1835
  impl_->temporary_shares.push_back(new table::Singular); // This will not go into the tableshare cache, so no key is used.
2318.6.96 by Olaf van der Spek
Refactor
1836
  return impl_->temporary_shares.back();
1532.1.1 by Brian Aker
Merge of change to flip table instance to be share instance
1837
}
1838
1878.5.1 by Brian Aker
Update instance for handling construction of virtual_tmp
1839
1840
/**
1841
  Create a reduced Table object with properly set up Field list from a
1842
  list of field definitions.
1843
1844
    The created table doesn't have a table Cursor associated with
1845
    it, has no keys, no group/distinct, no copy_funcs array.
1846
    The sole purpose of this Table object is to use the power of Field
1847
    class to read/write data to/from table->getInsertRecord(). Then one can store
1848
    the record in any container (RB tree, hash, etc).
1849
    The table is created in Session mem_root, so are the table's fields.
1850
    Consequently, if you don't BLOB fields, you don't need to free it.
1851
1852
  @param session         connection handle
1853
  @param field_list  list of column definitions
1854
1855
  @return
1856
    0 if out of memory, Table object in case of success
1857
*/
2241.3.6 by Olaf van der Spek
Refactor
1858
table::Singular& Session::getInstanceTable(std::list<CreateField>& field_list)
1878.5.1 by Brian Aker
Update instance for handling construction of virtual_tmp
1859
{
2241.3.7 by Olaf van der Spek
Refactor
1860
  impl_->temporary_shares.push_back(new table::Singular(this, field_list)); // This will not go into the tableshare cache, so no key is used.
2318.6.96 by Olaf van der Spek
Refactor
1861
  return impl_->temporary_shares.back();
2239.1.4 by Olaf van der Spek
Refactor includes
1862
}
1863
1864
void Session::clear_error(bool full)
1865
{
1866
  if (main_da().is_error())
1867
    main_da().reset_diagnostics_area();
1868
1869
  if (full)
2318.6.104 by Olaf van der Spek
Refactor
1870
    drizzle_reset_errors(*this, true);
2239.1.4 by Olaf van der Spek
Refactor includes
1871
}
1872
1873
void Session::clearDiagnostics()
1874
{
1875
  main_da().reset_diagnostics_area();
1876
}
1877
1878
/**
1879
  true if there is an error in the error stack.
1880
1881
  Please use this method instead of direct access to
1882
  net.report_error.
1883
1884
  If true, the current (sub)-statement should be aborted.
1885
  The main difference between this member and is_fatal_error
1886
  is that a fatal error can not be handled by a stored
1887
  procedure continue handler, whereas a normal error can.
1888
1889
  To raise this flag, use my_error().
1890
*/
1891
bool Session::is_error() const 
1892
{ 
1893
  return impl_->diagnostics.is_error(); 
1894
}
1895
1896
/** A short cut for session->main_da().set_ok_status(). */
1897
void Session::my_ok(ha_rows affected_rows, ha_rows found_rows_arg, uint64_t passed_id, const char *message)
1898
{
1899
  main_da().set_ok_status(this, affected_rows, found_rows_arg, passed_id, message);
1900
}
1901
1902
/** A short cut for session->main_da().set_eof_status(). */
1903
1904
void Session::my_eof()
1905
{
1906
  main_da().set_eof_status(this);
1878.5.1 by Brian Aker
Update instance for handling construction of virtual_tmp
1907
}
1908
2239.1.9 by Olaf van der Spek
Refactor includes
1909
plugin::StorageEngine* Session::getDefaultStorageEngine()
1910
{
1911
  return variables.storage_engine ? variables.storage_engine : global_system_variables.storage_engine;
1912
}
1913
2385.3.6 by Olaf van der Spek
cppcheck
1914
enum_tx_isolation Session::getTxIsolation() const
2239.1.9 by Olaf van der Spek
Refactor includes
1915
{
1916
  return (enum_tx_isolation)variables.tx_isolation;
1917
}
1918
2240.5.3 by Olaf van der Spek
Session::properties
1919
drizzled::util::Storable* Session::getProperty0(const std::string& arg)
1920
{
2280.1.4 by Olaf van der Spek
Refactor
1921
  return impl_->properties[arg];
2240.5.3 by Olaf van der Spek
Session::properties
1922
}
1923
1924
void Session::setProperty0(const std::string& arg, drizzled::util::Storable* value)
1925
{
2280.1.4 by Olaf van der Spek
Refactor
1926
  // assert(not _properties.count(arg));
1927
  impl_->properties[arg]= value;
2240.5.3 by Olaf van der Spek
Session::properties
1928
}
1929
2241.3.12 by Olaf van der Spek
Refactor Session
1930
plugin::EventObserverList* Session::getSchemaObservers(const std::string &db_name)
1931
{
1932
  if (impl_c::schema_event_observers_t::mapped_type* i= find_ptr(impl_->schema_event_observers, db_name))
1933
    return *i;
1934
  return NULL;
1935
}
1936
1937
plugin::EventObserverList* Session::setSchemaObservers(const std::string &db_name, plugin::EventObserverList* observers)
1938
{
1939
  impl_->schema_event_observers.erase(db_name);
1940
  if (observers)
1941
    impl_->schema_event_observers[db_name] = observers;
1942
	return observers;
1943
}
2241.3.3 by Olaf van der Spek
Refactor Session::transaction (partial)
1944
2269.1.7 by Olaf van der Spek
Use util::string::ptr
1945
util::string::ptr Session::schema() const
1946
{
2275.2.6 by Olaf van der Spek
Refactor
1947
  return impl_->schema;
2269.1.7 by Olaf van der Spek
Use util::string::ptr
1948
}
1949
2269.1.8 by Olaf van der Spek
Refactor Session
1950
void Session::resetQueryString()
1951
{
1952
  query.reset();
1953
  impl_->state.reset();
1954
}
1955
1956
const boost::shared_ptr<session::State>& Session::state()
1957
{
1958
  return impl_->state;
1959
}
1960
2240.5.12 by Olaf van der Spek
Refactor
1961
const std::string& display::type(drizzled::Session::global_read_lock_t type)
1948.2.6 by Brian Aker
Added function global_read_lock(), this way a session can know if it has
1962
{
2240.5.12 by Olaf van der Spek
Refactor
1963
  static const std::string NONE= "NONE";
1964
  static const std::string GOT_GLOBAL_READ_LOCK= "HAS GLOBAL READ LOCK";
1965
  static const std::string MADE_GLOBAL_READ_LOCK_BLOCK_COMMIT= "HAS GLOBAL READ LOCK WITH BLOCKING COMMIT";
1966
1967
  switch (type) 
1968
  {
1948.2.6 by Brian Aker
Added function global_read_lock(), this way a session can know if it has
1969
    default:
1970
    case Session::NONE:
1971
      return NONE;
1972
    case Session::GOT_GLOBAL_READ_LOCK:
1973
      return GOT_GLOBAL_READ_LOCK;
1974
    case Session::MADE_GLOBAL_READ_LOCK_BLOCK_COMMIT:
1975
      return MADE_GLOBAL_READ_LOCK_BLOCK_COMMIT;
1976
  }
1977
}
1978
2240.5.12 by Olaf van der Spek
Refactor
1979
size_t display::max_string_length(drizzled::Session::global_read_lock_t)
1948.2.6 by Brian Aker
Added function global_read_lock(), this way a session can know if it has
1980
{
2241.2.16 by Olaf van der Spek
Avoid compiler bug
1981
  return display::type(Session::MADE_GLOBAL_READ_LOCK_BLOCK_COMMIT).size();
1948.2.6 by Brian Aker
Added function global_read_lock(), this way a session can know if it has
1982
}
1983
1280.1.10 by Monty Taylor
Put everything in drizzled into drizzled namespace.
1984
} /* namespace drizzled */