~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
{
105
  return length == other.length &&
106
         field_name.length == other.field_name.length &&
1819.9.87 by Magne Mahre, Stewart Smith
Merge Revision revid:magne.mahre@sun.com-20100901173834-7lrqgycyuxsg4ab7 from MySQL InnoDB
107
    !my_strcasecmp(system_charset_info, field_name.str, other.field_name.str);
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 */
1 by brian
clean slate
286
  thr_lock_owner_init(&main_lock_id, &lock_info);
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
    {
2126.3.3 by Brian Aker
Merge in error message rework. Many error messages are fixed in this patch.
422
      errmsg_printf(error::WARN, ER(ER_FORCING_CLOSE),
2008.1.1 by Brian Aker
Adding user identifier that makes use of a shared ptr to handle concurrency
423
                    internal::my_progname,
424
                    thread_id,
425
                    security_ctx->username().c_str());
426
    }
427
2015.3.3 by Brian Aker
Update disconnect code.
428
    disconnect();
942.1.2 by Monty Taylor
Started trying to sort out session lifecycle.
429
  }
430
1 by brian
clean slate
431
  /* Close connection */
2015.3.3 by Brian Aker
Update disconnect code.
432
  if (client)
433
  {
434
    client->close();
2069.4.1 by Brian Aker
A little on the paranoid side, but not the worst plan ever to check our
435
    boost::checked_delete(client);
436
    client= NULL;
2015.3.3 by Brian Aker
Update disconnect code.
437
  }
971.3.6 by Eric Day
Moved the last of the libdrizzleclient calls into Protocol.
438
2281.4.1 by Olaf van der Spek
Prune
439
  if (not cleanup_done)
1 by brian
clean slate
440
    cleanup();
441
2302.1.8 by Olaf van der Spek
Refactor
442
  plugin::StorageEngine::closeConnection(*this);
520.1.22 by Brian Aker
Second pass of thd cleanup
443
  plugin_sessionvar_cleanup(this);
1 by brian
clean slate
444
1487 by Brian Aker
More updates for memory::Root
445
  warn_root.free_root(MYF(0));
1 by brian
clean slate
446
  mysys_var=0;					// Safety (shouldn't be needed)
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
447
2281.4.2 by Olaf van der Spek
Prune
448
  impl_->mem_root.free_root(MYF(0));
2318.6.22 by Olaf van der Spek
Refactor
449
  setCurrentMemRoot(NULL);
450
  setCurrentSession(NULL);
942.1.2 by Monty Taylor
Started trying to sort out session lifecycle.
451
1316.1.1 by Joe Daly
add plugin handle to logging to indicate when the session destructor is called
452
  plugin::Logging::postEndDo(this);
1919.3.45 by Barry.Leslie at PrimeBase
Fixed bug in merged code.
453
  plugin::EventObserver::deregisterSessionEvents(session_event_observers); 
1919.3.47 by Barry.Leslie at PrimeBase
Added back in schema event observer list cleanup.
454
2241.3.12 by Olaf van der Spek
Refactor Session
455
	BOOST_FOREACH(impl_c::schema_event_observers_t::reference it, impl_->schema_event_observers)
2241.3.7 by Olaf van der Spek
Refactor
456
    plugin::EventObserver::deregisterSchemaEvents(it.second);
1 by brian
clean slate
457
}
458
1921.4.1 by Brian Aker
Adding in support for EXECUTE to have WITH NO RETURN.
459
void Session::setClient(plugin::Client *client_arg)
460
{
461
  client= client_arg;
462
  client->setSession(this);
463
}
464
1910.2.8 by Brian Aker
Enapsulate Kill.
465
void Session::awake(Session::killed_state_t state_to_set)
1 by brian
clean slate
466
{
2281.4.1 by Olaf van der Spek
Prune
467
  if (state_to_set == Session::KILL_QUERY && command == COM_SLEEP)
1994.3.2 by Andrew Hutchings
Merge with trunk
468
    return;
469
1910.2.8 by Brian Aker
Enapsulate Kill.
470
  setKilled(state_to_set);
1961 by Brian Aker
This extends our coverage of interrupting active threads. With no crash
471
  scheduler->killSession(this);
472
520.1.21 by Brian Aker
THD -> Session rename
473
  if (state_to_set != Session::KILL_QUERY)
1 by brian
clean slate
474
  {
1126.10.18 by Padraig O'Sullivan
Various small build fixes for when dtrace is enabled.
475
    DRIZZLE_CONNECTION_DONE(thread_id);
1 by brian
clean slate
476
  }
1933.2.4 by Brian Aker
Update user locks to allow for interruption based on boost.
477
1 by brian
clean slate
478
  if (mysys_var)
479
  {
2275.3.4 by Olaf van der Spek
Thread
480
    boost::mutex::scoped_lock scopedLock(mysys_var->mutex);
1 by brian
clean slate
481
    /*
1786.2.1 by Brian Aker
Current boost work (more conversion).
482
      "
1 by brian
clean slate
483
      This broadcast could be up in the air if the victim thread
484
      exits the cond in the time between read and broadcast, but that is
485
      ok since all we want to do is to make the victim thread get out
486
      of waiting on current_cond.
487
      If we see a non-zero current_cond: it cannot be an old value (because
488
      then exit_cond() should have run and it can't because we have mutex); so
489
      it is the true value but maybe current_mutex is not yet non-zero (we're
490
      in the middle of enter_cond() and there is a "memory order
491
      inversion"). So we test the mutex too to not lock 0.
492
493
      Note that there is a small chance we fail to kill. If victim has locked
494
      current_mutex, but hasn't yet entered enter_cond() (which means that
495
      current_cond and current_mutex are 0), then the victim will not get
496
      a signal and it may wait "forever" on the cond (until
497
      we issue a second KILL or the status it's waiting for happens).
520.1.22 by Brian Aker
Second pass of thd cleanup
498
      It's true that we have set its session->killed but it may not
1 by brian
clean slate
499
      see it immediately and so may have time to reach the cond_wait().
500
    */
501
    if (mysys_var->current_cond && mysys_var->current_mutex)
502
    {
1786.2.1 by Brian Aker
Current boost work (more conversion).
503
      mysys_var->current_mutex->lock();
1798.3.10 by Brian Aker
Remove additional (maybe last of?) native_handle actual calls (safe_mutex is
504
      mysys_var->current_cond->notify_all();
1786.2.1 by Brian Aker
Current boost work (more conversion).
505
      mysys_var->current_mutex->unlock();
1 by brian
clean slate
506
    }
507
  }
508
}
509
510
/*
511
  Remember the location of thread info, the structure needed for
1253.1.6 by Monty Taylor
Moved mem_root functions into drizzled::memory:: namespace.
512
  memory::sql_alloc() and the structure for the net buffer
1 by brian
clean slate
513
*/
2269.1.7 by Olaf van der Spek
Use util::string::ptr
514
void Session::storeGlobals()
1 by brian
clean slate
515
{
516
  /*
517
    Assert that thread_stack is initialized: it's necessary to be able
518
    to track stack overrun.
519
  */
51.1.50 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
520
  assert(thread_stack);
2318.6.22 by Olaf van der Spek
Refactor
521
  setCurrentSession(this);
522
  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.
523
2385.3.8 by Olaf van der Spek
Refactor
524
  mysys_var= internal::my_thread_var();
960.1.1 by Monty Taylor
First pass at scheduler plugin.
525
1 by brian
clean slate
526
  /*
527
    Let mysqld define the thread id (not mysys)
520.1.21 by Brian Aker
THD -> Session rename
528
    This allows us to move Session to different threads if needed.
1 by brian
clean slate
529
  */
530
  mysys_var->id= thread_id;
531
532
  /*
520.1.21 by Brian Aker
THD -> Session rename
533
    We have to call thr_lock_info_init() again here as Session may have been
1 by brian
clean slate
534
    created in another thread
535
  */
1689.2.12 by Brian Aker
THR_LOCK_INFO::init() <-- encapsulation
536
  lock_info.init();
1 by brian
clean slate
537
}
538
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.
539
/*
540
  Init Session for query processing.
541
  This has to be called once before we call mysql_parse.
542
  See also comments in session.h.
543
*/
544
934.2.6 by Jay Pipes
This changeset removes a few more C functions from sql_connect.cc/connect.h
545
void Session::prepareForQueries()
546
{
547
  if (variables.max_join_size == HA_POS_ERROR)
548
    options |= OPTION_BIG_SELECTS;
549
2263.3.10 by Olaf van der Spek
Open Tables
550
  open_tables.version= g_refresh_version;
961.1.4 by Brian Aker
Remove another lock for processlist.
551
  set_proc_info(NULL);
934.2.6 by Jay Pipes
This changeset removes a few more C functions from sql_connect.cc/connect.h
552
  command= COM_SLEEP;
2269.1.6 by Olaf van der Spek
Session Times
553
  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.
554
2318.6.24 by Olaf van der Spek
Refactor
555
  mem.reset_defaults(variables.query_alloc_block_size, variables.query_prealloc_size);
2281.4.7 by Olaf van der Spek
XID
556
  transaction.xid_state.xid.set_null();
2224.2.4 by Olaf van der Spek
Undo partial commit
557
  transaction.xid_state.in_session=1;
1764.3.6 by Brian Aker
This includes a query_usage table for looking at performance of previous
558
  if (use_usage)
559
    resetUsage();
934.2.6 by Jay Pipes
This changeset removes a few more C functions from sql_connect.cc/connect.h
560
}
561
2269.1.8 by Olaf van der Spek
Refactor Session
562
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.
563
{
2269.1.7 by Olaf van der Spek
Use util::string::ptr
564
  storeGlobals();
2269.1.8 by Olaf van der Spek
Refactor Session
565
  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.
566
  {
2015.3.3 by Brian Aker
Update disconnect code.
567
    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.
568
    return;
569
  }
570
  prepareForQueries();
1910.2.8 by Brian Aker
Enapsulate Kill.
571
  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.
572
  {
1910.2.8 by Brian Aker
Enapsulate Kill.
573
    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.
574
      break;
575
  }
2015.3.3 by Brian Aker
Update disconnect code.
576
  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.
577
}
578
2318.6.43 by Olaf van der Spek
Refactor
579
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.
580
{
1932.3.3 by Brian Aker
Pull in code to abstract out the session list a bit.
581
  arg->scheduler= plugin::Scheduler::getScheduler();
582
  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.
583
2041.2.2 by Brian Aker
Ubuntu issue?
584
  ++connection_count;
585
586
  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.
587
2039.3.5 by Brian Aker
Switched connection_count to use boost atomic.
588
  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
589
  {
2039.3.5 by Brian Aker
Switched connection_count to use boost atomic.
590
    current_global_counters.max_used_connections= static_cast<uint64_t>(connection_count);
1537.2.1 by Joe Daly
add statistics_variables.h
591
  }
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
1726.3.3 by LinuxJedi
Add a proper connections counter.
593
  current_global_counters.connections++;
1932.3.3 by Brian Aker
Pull in code to abstract out the session list a bit.
594
  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.
595
2282.1.2 by Olaf van der Spek
Session Cache
596
  session::Cache::insert(arg);
1932.3.3 by Brian Aker
Pull in code to abstract out the session list a bit.
597
598
  if (unlikely(plugin::EventObserver::connectSession(*arg)))
599
  {
600
    // We should do something about an error...
601
  }
602
1932.3.13 by Brian Aker
Cleanup session ownership rules such that we know exactly when session has
603
  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.
604
  {
1932.3.11 by Brian Aker
Fix dtrace issue.
605
    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.
606
    char error_message_buff[DRIZZLE_ERRMSG_SIZE];
607
1932.3.3 by Brian Aker
Pull in code to abstract out the session list a bit.
608
    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.
609
1932.3.3 by Brian Aker
Pull in code to abstract out the session list a bit.
610
    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.
611
612
    /* Can't use my_error() since store_globals has not been called. */
613
    /* TODO replace will better error message */
2318.6.43 by Olaf van der Spek
Refactor
614
    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.
615
    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.
616
    return true;
617
  }
618
  return false;
934.2.6 by Jay Pipes
This changeset removes a few more C functions from sql_connect.cc/connect.h
619
}
620
1241.9.55 by Monty Taylor
Moved tree into drizzled/
621
1932.3.3 by Brian Aker
Pull in code to abstract out the session list a bit.
622
/*
623
  Is this session viewable by the current user?
624
*/
2246.4.11 by Olaf van der Spek
Remove const_reference and reference from identifier::User
625
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.
626
{
2159.2.7 by Brian Aker
Merge in shared ptr modification for auth (namely we don't take the hit for
627
  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.
628
}
629
630
1812.3.5 by Brian Aker
Move to boost condition_any
631
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/
632
{
633
  const char* old_msg = get_proc_info();
634
  safe_mutex_assert_owner(mutex);
1786.2.1 by Brian Aker
Current boost work (more conversion).
635
  mysys_var->current_mutex = &mutex;
636
  mysys_var->current_cond = &cond;
1241.9.55 by Monty Taylor
Moved tree into drizzled/
637
  this->set_proc_info(msg);
638
  return old_msg;
639
}
640
641
void Session::exit_cond(const char* old_msg)
642
{
643
  /*
644
    Putting the mutex unlock in exit_cond() ensures that
645
    mysys_var->current_mutex is always unlocked _before_ mysys_var->mutex is
646
    locked (if that would not be the case, you'll get a deadlock if someone
647
    does a Session::awake() on you).
648
  */
1786.2.1 by Brian Aker
Current boost work (more conversion).
649
  mysys_var->current_mutex->unlock();
2275.3.4 by Olaf van der Spek
Thread
650
  boost::mutex::scoped_lock scopedLock(mysys_var->mutex);
1241.9.55 by Monty Taylor
Moved tree into drizzled/
651
  mysys_var->current_mutex = 0;
652
  mysys_var->current_cond = 0;
653
  this->set_proc_info(old_msg);
654
}
655
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...
656
bool Session::authenticate()
657
{
971.6.1 by Eric Day
Renamed Protocol to Client, cleaned up some unnecessary methods along the way.
658
  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.
659
    return false;
971.3.6 by Eric Day
Moved the last of the libdrizzleclient calls into Protocol.
660
1689.5.1 by Joseph Daly
remove increment calls
661
  status_var.aborted_connects++;
1625.2.1 by Joe Daly
initial user stats impl
662
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.
663
  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...
664
}
665
2241.3.13 by Olaf van der Spek
Refactor Session
666
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...
667
{
2241.3.13 by Olaf van der Spek
Refactor Session
668
  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...
669
  {
1689.5.1 by Joseph Daly
remove increment calls
670
    status_var.access_denied++;
1317.1.3 by Monty Taylor
Fixed Authentication plugin interface to use SecurityContext rather than the
671
    /* 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...
672
    return false;
673
  }
674
675
  /* Change database if necessary */
2241.3.13 by Olaf van der Spek
Refactor Session
676
  if (not in_db.empty() && schema::change(*this, identifier::Schema(in_db)))
677
    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...
678
  my_ok();
679
680
  /* Ready to handle queries */
681
  return true;
682
}
1 by brian
clean slate
683
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.
684
bool Session::executeStatement()
685
{
2241.3.13 by Olaf van der Spek
Refactor Session
686
  /*
687
    indicator of uninitialized lex => normal flow of errors handling
688
    (see my_message_sql)
689
  */
690
  lex().current_select= 0;
691
  clear_error();
692
  main_da().reset_diagnostics_area();
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.
693
  char *l_packet= 0;
694
  uint32_t packet_length;
2312.1.4 by Brian Aker
Fix packet length, no pointer to using a pointer there.
695
  if (not client->readCommand(&l_packet, packet_length))
971.3.6 by Eric Day
Moved the last of the libdrizzleclient calls into Protocol.
696
    return false;
697
1910.2.8 by Brian Aker
Enapsulate Kill.
698
  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.
699
    return false;
700
971.3.6 by Eric Day
Moved the last of the libdrizzleclient calls into Protocol.
701
  if (packet_length == 0)
702
    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.
703
2241.3.13 by Olaf van der Spek
Refactor Session
704
  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.
705
706
  if (command >= COM_END)
707
    command= COM_END;                           // Wrong command
708
709
  assert(packet_length);
1921.4.2 by Brian Aker
Adding in concurrent execute support.
710
  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.
711
}
934.2.9 by Jay Pipes
Pulls alloc_query() C function out of sql_parse.cc and adds readAndStoreQuery() member method of Session class.
712
2275.2.6 by Olaf van der Spek
Refactor
713
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.
714
{
715
  /* Remove garbage at start and end of query */
716
  while (in_packet_length > 0 && my_isspace(charset(), in_packet[0]))
717
  {
718
    in_packet++;
719
    in_packet_length--;
720
  }
721
  const char *pos= in_packet + in_packet_length; /* Point at end null */
1921.4.13 by Brian Aker
Fix issue where session info might not be correct.
722
  while (in_packet_length > 0 && (pos[-1] == ';' || my_isspace(charset() ,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.
723
  {
724
    pos--;
725
    in_packet_length--;
726
  }
727
2275.2.6 by Olaf van der Spek
Refactor
728
  util::string::mptr new_query= boost::make_shared<std::string>(in_packet, in_packet_length);
729
  plugin::QueryRewriter::rewriteQuery(*impl_->schema, *new_query);
730
  query= new_query;
731
  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.
732
}
733
2275.2.6 by Olaf van der Spek
Refactor
734
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.
735
{
736
  bool do_release= 0;
737
  bool result= true;
738
2224.2.4 by Olaf van der Spek
Undo partial commit
739
  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.
740
  {
2224.2.4 by Olaf van der Spek
Undo partial commit
741
    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.
742
    return false;
743
  }
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.
744
  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.
745
  {
746
    case COMMIT:
747
      /*
748
       * We don't use endActiveTransaction() here to ensure that this works
749
       * even if there is a problem with the OPTION_AUTO_COMMIT flag
750
       * (Which of course should never happen...)
751
       */
752
      server_status&= ~SERVER_STATUS_IN_TRANS;
2318.6.62 by Olaf van der Spek
Refactor
753
      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.
754
        result= false;
1172.1.2 by Brian Aker
Remove worthless call (ok... for not current replication system).
755
      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.
756
      break;
757
    case COMMIT_RELEASE:
758
      do_release= 1; /* fall through */
759
    case COMMIT_AND_CHAIN:
760
      result= endActiveTransaction();
761
      if (result == true && completion == COMMIT_AND_CHAIN)
762
        result= startTransaction();
763
      break;
764
    case ROLLBACK_RELEASE:
765
      do_release= 1; /* fall through */
766
    case ROLLBACK:
767
    case ROLLBACK_AND_CHAIN:
768
    {
769
      server_status&= ~SERVER_STATUS_IN_TRANS;
2318.6.62 by Olaf van der Spek
Refactor
770
      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.
771
        result= false;
1172.1.2 by Brian Aker
Remove worthless call (ok... for not current replication system).
772
      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.
773
      if (result == true && (completion == ROLLBACK_AND_CHAIN))
774
        result= startTransaction();
775
      break;
776
    }
777
    default:
778
      my_error(ER_UNKNOWN_COM_ERROR, MYF(0));
779
      return false;
780
  }
781
2275.2.6 by Olaf van der Spek
Refactor
782
  if (not result)
1910.2.8 by Brian Aker
Enapsulate Kill.
783
  {
2054.1.2 by Brian Aker
Rename of the Loooongggggg error type over to simply drizzled::error_t
784
    my_error(static_cast<drizzled::error_t>(killed_errno()), MYF(0));
1910.2.8 by Brian Aker
Enapsulate Kill.
785
  }
2275.2.6 by Olaf van der Spek
Refactor
786
  else if (result && do_release)
1910.2.8 by Brian Aker
Enapsulate Kill.
787
  {
788
    setKilled(Session::KILL_CONNECTION);
789
  }
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.
790
791
  return result;
792
}
793
794
bool Session::endActiveTransaction()
795
{
796
  bool result= true;
797
2224.2.5 by Olaf van der Spek
Undo partial commit
798
  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.
799
  {
2224.2.5 by Olaf van der Spek
Undo partial commit
800
    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.
801
    return false;
802
  }
1054.1.8 by Brian Aker
Remove lock_tables list from session.
803
  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.
804
  {
805
    server_status&= ~SERVER_STATUS_IN_TRANS;
2318.6.62 by Olaf van der Spek
Refactor
806
    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.
807
      result= false;
808
  }
1172.1.2 by Brian Aker
Remove worthless call (ok... for not current replication system).
809
  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.
810
  return result;
811
}
812
1206.1.3 by Brian Aker
Valgrind fix for startTransaction()
813
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.
814
{
2275.2.6 by Olaf van der Spek
Refactor
815
  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)
816
817
  options|= OPTION_BEGIN;
818
  server_status|= SERVER_STATUS_IN_TRANS;
819
820
  if (plugin::TransactionalStorageEngine::notifyStartTransaction(this, opt))
2275.2.6 by Olaf van der Spek
Refactor
821
    return false;
822
  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.
823
}
824
520.1.21 by Brian Aker
THD -> Session rename
825
void Session::cleanup_after_query()
1 by brian
clean slate
826
{
827
  /*
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
828
    Reset rand_used so that detection of calls to rand() will save random
1 by brian
clean slate
829
    seeds if needed by the slave.
830
  */
831
  if (first_successful_insert_id_in_cur_stmt > 0)
832
  {
833
    /* set what LAST_INSERT_ID() will return */
1055.2.17 by Jay Pipes
More style cleanups in Session
834
    first_successful_insert_id_in_prev_stmt= first_successful_insert_id_in_cur_stmt;
1 by brian
clean slate
835
    first_successful_insert_id_in_cur_stmt= 0;
51.1.50 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
836
    substitute_null_with_insert_id= true;
1 by brian
clean slate
837
  }
2114.4.10 by Brian Aker
Remove current_session from a couple of locations, encapsulate where in
838
1055.2.17 by Jay Pipes
More style cleanups in Session
839
  arg_of_last_insert_id_function= false;
2114.4.10 by Brian Aker
Remove current_session from a couple of locations, encapsulate where in
840
1 by brian
clean slate
841
  /* Free Items that were created during this execution */
842
  free_items();
2114.4.10 by Brian Aker
Remove current_session from a couple of locations, encapsulate where in
843
844
  /* Reset _where. */
845
  _where= Session::DEFAULT_WHERE;
1532.1.1 by Brian Aker
Merge of change to flip table instance to be share instance
846
847
  /* Reset the temporary shares we built */
2241.3.7 by Olaf van der Spek
Refactor
848
  impl_->temporary_shares.clear();
1 by brian
clean slate
849
}
850
851
/**
2371.1.2 by Brian Aker
Remove the typedef on lexkey
852
  Create a lex_string_t in this connection.
1 by brian
clean slate
853
2371.1.2 by Brian Aker
Remove the typedef on lexkey
854
  @param lex_str  pointer to lex_string_t object to be initialized
1 by brian
clean slate
855
  @param str      initializer to be copied into lex_str
856
  @param length   length of str, in bytes
2371.1.2 by Brian Aker
Remove the typedef on lexkey
857
  @param allocate_lex_string  if true, allocate new lex_string_t object,
1 by brian
clean slate
858
                              instead of using lex_str value
2371.1.2 by Brian Aker
Remove the typedef on lexkey
859
  @return  NULL on failure, or pointer to the lex_string_t object
1 by brian
clean slate
860
*/
2385.2.7 by Olaf van der Spek
Use str_ref
861
lex_string_t* Session::make_lex_string(lex_string_t* lex_str, str_ref str)
862
{
863
  if (not lex_str)
2371.1.2 by Brian Aker
Remove the typedef on lexkey
864
    lex_str= new (mem) lex_string_t;
2385.2.7 by Olaf van der Spek
Use str_ref
865
  lex_str->str= mem_root->strdup(str);
866
  lex_str->length= str.size();
1 by brian
clean slate
867
  return lex_str;
868
}
869
2318.3.11 by Olaf van der Spek
Refactor
870
void Session::send_explain_fields(select_result *result)
1 by brian
clean slate
871
{
872
  List<Item> field_list;
873
  Item *item;
2318.3.11 by Olaf van der Spek
Refactor
874
  const charset_info_st* cs= system_charset_info;
212.2.2 by Patrick Galbraith
Renamed FIELD_TYPE to DRIZZLE_TYPE
875
  field_list.push_back(new Item_return_int("id",3, DRIZZLE_TYPE_LONGLONG));
1 by brian
clean slate
876
  field_list.push_back(new Item_empty_string("select_type", 19, cs));
877
  field_list.push_back(item= new Item_empty_string("table", NAME_CHAR_LEN, cs));
878
  item->maybe_null= 1;
879
  field_list.push_back(item= new Item_empty_string("type", 10, cs));
880
  item->maybe_null= 1;
2318.3.11 by Olaf van der Spek
Refactor
881
  field_list.push_back(item= new Item_empty_string("possible_keys", NAME_CHAR_LEN*MAX_KEY, cs));
1 by brian
clean slate
882
  item->maybe_null=1;
2318.3.11 by Olaf van der Spek
Refactor
883
  field_list.push_back(item= new Item_empty_string("key", NAME_CHAR_LEN, cs));
1 by brian
clean slate
884
  item->maybe_null=1;
2385.2.7 by Olaf van der Spek
Use str_ref
885
  field_list.push_back(item= new Item_empty_string("key_len", MAX_KEY * (MAX_KEY_LENGTH_DECIMAL_WIDTH + 1 /* for comma */), cs));
886
  item->maybe_null=1;
887
  field_list.push_back(item= new Item_empty_string("ref", NAME_CHAR_LEN*MAX_REF_PARTS, cs));
888
  item->maybe_null=1;
889
  field_list.push_back(item= new Item_return_int("rows", 10, DRIZZLE_TYPE_LONGLONG));
2227.4.8 by Olaf van der Spek
Session::lex()
890
  if (lex().describe & DESCRIBE_EXTENDED)
1 by brian
clean slate
891
  {
892
    field_list.push_back(item= new Item_float("filtered", 0.1234, 2, 4));
893
    item->maybe_null=1;
894
  }
895
  item->maybe_null= 1;
896
  field_list.push_back(new Item_empty_string("Extra", 255, cs));
2318.3.10 by Olaf van der Spek
Return void
897
  result->send_fields(field_list);
1 by brian
clean slate
898
}
899
2087.3.1 by Brian Aker
Entire convert over to time_t.
900
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.
901
{
902
  my_message(errcode, err, MYF(0));
903
}
904
1 by brian
clean slate
905
/************************************************************************
906
  Handling writing to file
907
************************************************************************/
908
2087.3.1 by Brian Aker
Entire convert over to time_t.
909
void select_to_file::send_error(drizzled::error_t errcode,const char *err)
1 by brian
clean slate
910
{
911
  my_message(errcode, err, MYF(0));
912
  if (file > 0)
913
  {
1909.1.1 by Brian Aker
Encapsulation of IO_CACHE.
914
    (void) cache->end_io_cache();
1280.1.10 by Monty Taylor
Put everything in drizzled into drizzled namespace.
915
    (void) internal::my_close(file, MYF(0));
1813.2.9 by Monty Taylor
Made data_home be fs::path natively.
916
    (void) internal::my_delete(path.file_string().c_str(), MYF(0));		// Delete file on error
1 by brian
clean slate
917
    file= -1;
918
  }
919
}
920
921
922
bool select_to_file::send_eof()
923
{
1909.1.1 by Brian Aker
Encapsulation of IO_CACHE.
924
  int error= test(cache->end_io_cache());
1280.1.10 by Monty Taylor
Put everything in drizzled into drizzled namespace.
925
  if (internal::my_close(file, MYF(MY_WME)))
1 by brian
clean slate
926
    error= 1;
927
  if (!error)
928
  {
929
    /*
930
      In order to remember the value of affected rows for ROW_COUNT()
931
      function, SELECT INTO has to have an own SQLCOM.
932
      TODO: split from SQLCOM_SELECT
933
    */
836 by Brian Aker
Fixed session call from function to method.
934
    session->my_ok(row_count);
1 by brian
clean slate
935
  }
936
  file= -1;
937
  return error;
938
}
939
940
941
void select_to_file::cleanup()
942
{
943
  /* In case of error send_eof() may be not called: close the file here. */
944
  if (file >= 0)
945
  {
1909.1.1 by Brian Aker
Encapsulation of IO_CACHE.
946
    (void) cache->end_io_cache();
1280.1.10 by Monty Taylor
Put everything in drizzled into drizzled namespace.
947
    (void) internal::my_close(file, MYF(0));
1 by brian
clean slate
948
    file= -1;
949
  }
1813.2.14 by Monty Taylor
Removed API element that SuSE and some older boosts don't have.
950
  path= "";
1 by brian
clean slate
951
  row_count= 0;
952
}
953
1241.9.49 by Monty Taylor
Removed one more public IO_CACHE.
954
select_to_file::select_to_file(file_exchange *ex)
1241.9.52 by Monty Taylor
Fixed valgrind issue.
955
  : exchange(ex),
956
    file(-1),
2296.1.1 by Mark Atwood
Merge in Fixes of Brian's IOCACHE.
957
    cache(static_cast<internal::io_cache_st *>(memory::sql_calloc(sizeof(internal::io_cache_st)))),
1241.9.52 by Monty Taylor
Fixed valgrind issue.
958
    row_count(0L)
1241.9.49 by Monty Taylor
Removed one more public IO_CACHE.
959
{
1813.2.14 by Monty Taylor
Removed API element that SuSE and some older boosts don't have.
960
  path= "";
1241.9.49 by Monty Taylor
Removed one more public IO_CACHE.
961
}
1 by brian
clean slate
962
963
select_to_file::~select_to_file()
964
{
1241.9.49 by Monty Taylor
Removed one more public IO_CACHE.
965
  cleanup();
1 by brian
clean slate
966
}
967
968
/***************************************************************************
969
** Export of select to textfile
970
***************************************************************************/
971
972
select_export::~select_export()
973
{
520.1.22 by Brian Aker
Second pass of thd cleanup
974
  session->sent_row_count=row_count;
1 by brian
clean slate
975
}
976
977
978
/*
979
  Create file with IO cache
980
981
  SYNOPSIS
982
    create_file()
520.1.22 by Brian Aker
Second pass of thd cleanup
983
    session			Thread handle
1 by brian
clean slate
984
    path		File name
985
    exchange		Excange class
986
    cache		IO cache
987
988
  RETURN
989
    >= 0 	File handle
990
   -1		Error
991
*/
992
993
2318.6.43 by Olaf van der Spek
Refactor
994
static int create_file(Session& session,
1813.2.9 by Monty Taylor
Made data_home be fs::path natively.
995
                       fs::path &target_path,
996
                       file_exchange *exchange,
2296.1.1 by Mark Atwood
Merge in Fixes of Brian's IOCACHE.
997
                       internal::io_cache_st *cache)
1 by brian
clean slate
998
{
1813.2.9 by Monty Taylor
Made data_home be fs::path natively.
999
  fs::path to_file(exchange->file_name);
1000
1001
  if (not to_file.has_root_directory())
1 by brian
clean slate
1002
  {
1813.2.9 by Monty Taylor
Made data_home be fs::path natively.
1003
    target_path= fs::system_complete(getDataHomeCatalog());
2318.6.43 by Olaf van der Spek
Refactor
1004
    util::string::ptr schema(session.schema());
2275.2.6 by Olaf van der Spek
Refactor
1005
    if (not schema->empty())
1813.2.9 by Monty Taylor
Made data_home be fs::path natively.
1006
    {
1007
      int count_elements= 0;
2318.6.43 by Olaf van der Spek
Refactor
1008
      for (fs::path::iterator it= to_file.begin(); it != to_file.end(); it++)
1009
        count_elements++;
1813.2.9 by Monty Taylor
Made data_home be fs::path natively.
1010
      if (count_elements == 1)
1976.5.2 by Brian Aker
This resolves the issue where one thread may be looking at schema while
1011
        target_path /= *schema;
1813.2.9 by Monty Taylor
Made data_home be fs::path natively.
1012
    }
1013
    target_path /= to_file;
1 by brian
clean slate
1014
  }
1015
  else
1813.2.9 by Monty Taylor
Made data_home be fs::path natively.
1016
  {
1017
    target_path = exchange->file_name;
1018
  }
1 by brian
clean slate
1019
1813.2.6 by Monty Taylor
Made secure_file_priv be an fs::path from the beginning.
1020
  if (not secure_file_priv.string().empty())
1 by brian
clean slate
1021
  {
1813.2.10 by Monty Taylor
Expand secure-file-priv once at startup rather than on each path check.
1022
    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.
1023
    {
1024
      /* Write only allowed to dir or subdir specified by secure_file_priv */
1025
      my_error(ER_OPTION_PREVENTS_STATEMENT, MYF(0), "--secure-file-priv");
1026
      return -1;
1027
    }
1 by brian
clean slate
1028
  }
1029
1813.2.9 by Monty Taylor
Made data_home be fs::path natively.
1030
  if (!access(target_path.file_string().c_str(), F_OK))
1 by brian
clean slate
1031
  {
1032
    my_error(ER_FILE_EXISTS_ERROR, MYF(0), exchange->file_name);
1033
    return -1;
1034
  }
1035
  /* Create the file world readable */
2318.6.43 by Olaf van der Spek
Refactor
1036
  int file= internal::my_create(target_path.file_string().c_str(), 0666, O_WRONLY|O_EXCL, MYF(MY_WME));
1037
  if (file < 0)
1 by brian
clean slate
1038
    return file;
1039
  (void) fchmod(file, 0666);			// Because of umask()
2318.6.43 by Olaf van der Spek
Refactor
1040
  if (cache->init_io_cache(file, 0, internal::WRITE_CACHE, 0L, 1, MYF(MY_WME)))
1 by brian
clean slate
1041
  {
1280.1.10 by Monty Taylor
Put everything in drizzled into drizzled namespace.
1042
    internal::my_close(file, MYF(0));
1813.2.9 by Monty Taylor
Made data_home be fs::path natively.
1043
    internal::my_delete(target_path.file_string().c_str(), MYF(0));  // Delete file on error, it was just created
1 by brian
clean slate
1044
    return -1;
1045
  }
1046
  return file;
1047
}
1048
1049
1050
int
848 by Brian Aker
typdef class removal (just... use the name of the class).
1051
select_export::prepare(List<Item> &list, Select_Lex_Unit *u)
1 by brian
clean slate
1052
{
1053
  bool blob_flag=0;
51.1.50 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
1054
  bool string_results= false, non_string_results= false;
1 by brian
clean slate
1055
  unit= u;
895 by Brian Aker
Completion (?) of uint conversion.
1056
  if ((uint32_t) strlen(exchange->file_name) + NAME_LEN >= FN_REFLEN)
1813.2.9 by Monty Taylor
Made data_home be fs::path natively.
1057
  {
1058
    path= exchange->file_name;
1059
  }
1 by brian
clean slate
1060
1061
  /* Check if there is any blobs in data */
1062
  {
2183.2.12 by Olaf van der Spek
Use List::begin()
1063
    List<Item>::iterator li(list.begin());
2385.3.14 by Olaf van der Spek
Remove unused Session::query_cache_key var
1064
    while (Item* item= li++)
1 by brian
clean slate
1065
    {
1066
      if (item->max_length >= MAX_BLOB_WIDTH)
1067
      {
2008 by Brian Aker
Formatting + remove default from switch/case.
1068
        blob_flag=1;
1069
        break;
1 by brian
clean slate
1070
      }
2008 by Brian Aker
Formatting + remove default from switch/case.
1071
1 by brian
clean slate
1072
      if (item->result_type() == STRING_RESULT)
51.1.50 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
1073
        string_results= true;
1 by brian
clean slate
1074
      else
51.1.50 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
1075
        non_string_results= true;
1 by brian
clean slate
1076
    }
1077
  }
1078
  field_term_length=exchange->field_term->length();
1079
  field_term_char= field_term_length ?
481 by Brian Aker
Remove all of uchar.
1080
                   (int) (unsigned char) (*exchange->field_term)[0] : INT_MAX;
1 by brian
clean slate
1081
  if (!exchange->line_term->length())
1082
    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()
1083
  field_sep_char= exchange->enclosed->length() ? (int) (unsigned char) (*exchange->enclosed)[0] : field_term_char;
1084
  escape_char= exchange->escaped->length() ? (int) (unsigned char) (*exchange->escaped)[0] : -1;
1 by brian
clean slate
1085
  is_ambiguous_field_sep= test(strchr(ESCAPE_CHARS, field_sep_char));
1086
  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()
1087
  line_sep_char= exchange->line_term->length() ? (int) (unsigned char) (*exchange->line_term)[0] : INT_MAX;
1 by brian
clean slate
1088
  if (!field_term_length)
1089
    exchange->opt_enclosed=0;
1090
  if (!exchange->enclosed->length())
1091
    exchange->opt_enclosed=1;			// A little quicker loop
1092
  fixed_row_size= (!field_term_length && !exchange->enclosed->length() &&
1093
		   !blob_flag);
2318.7.11 by Olaf van der Spek
Use String::c_str() instead of c_ptr_safe()
1094
  if ((is_ambiguous_field_sep && exchange->enclosed->empty() && (string_results || is_unsafe_field_sep)) ||
1095
      (exchange->opt_enclosed && non_string_results && field_term_length && strchr(NUMERIC_CHARS, field_term_char)))
1 by brian
clean slate
1096
  {
673.3.8 by Stewart Smith
fix outfile_loaddata test for drizzle.
1097
    my_error(ER_AMBIGUOUS_FIELD_TERM, MYF(0));
1098
    return 1;
1 by brian
clean slate
1099
  }
673.3.8 by Stewart Smith
fix outfile_loaddata test for drizzle.
1100
2318.6.43 by Olaf van der Spek
Refactor
1101
  if ((file= create_file(*session, path, exchange, cache)) < 0)
673.3.8 by Stewart Smith
fix outfile_loaddata test for drizzle.
1102
    return 1;
1 by brian
clean slate
1103
1104
  return 0;
1105
}
1106
1107
bool select_export::send_data(List<Item> &items)
1108
{
1109
  char buff[MAX_FIELD_WIDTH],null_buff[2],space[MAX_FIELD_WIDTH];
1110
  bool space_inited=0;
1111
  String tmp(buff,sizeof(buff),&my_charset_bin),*res;
1112
  tmp.length(0);
1113
1114
  if (unit->offset_limit_cnt)
1115
  {						// using limit offset,count
1116
    unit->offset_limit_cnt--;
1864.3.18 by Brian Aker
REmove goto from session.
1117
    return false;
1 by brian
clean slate
1118
  }
1119
  row_count++;
2183.2.19 by Olaf van der Spek
Use List::size()
1120
  uint32_t used_length=0,items_left=items.size();
2183.2.12 by Olaf van der Spek
Use List::begin()
1121
  List<Item>::iterator li(items.begin());
1 by brian
clean slate
1122
2385.3.13 by Olaf van der Spek
Refactor iocache
1123
  if (cache->write(exchange->line_start->ptr(), exchange->line_start->length()))
1864.3.18 by Brian Aker
REmove goto from session.
1124
    return true;
1125
2385.3.13 by Olaf van der Spek
Refactor iocache
1126
  while (Item* item=li++)
1 by brian
clean slate
1127
  {
1128
    Item_result result_type=item->result_type();
1129
    bool enclosed = (exchange->enclosed->length() &&
1130
                     (!exchange->opt_enclosed || result_type == STRING_RESULT));
1131
    res=item->str_result(&tmp);
1132
    if (res && enclosed)
1133
    {
2385.3.13 by Olaf van der Spek
Refactor iocache
1134
      if (cache->write(exchange->enclosed->ptr(), exchange->enclosed->length()))
1864.3.18 by Brian Aker
REmove goto from session.
1135
        return true;
1 by brian
clean slate
1136
    }
1137
    if (!res)
1138
    {						// NULL
1139
      if (!fixed_row_size)
1140
      {
1208.3.2 by brian
Update for Cursor renaming.
1141
        if (escape_char != -1)			// Use \N syntax
1142
        {
1143
          null_buff[0]=escape_char;
1144
          null_buff[1]='N';
2385.3.13 by Olaf van der Spek
Refactor iocache
1145
          if (cache->write(null_buff, 2))
1864.3.18 by Brian Aker
REmove goto from session.
1146
            return true;
1208.3.2 by brian
Update for Cursor renaming.
1147
        }
2385.3.13 by Olaf van der Spek
Refactor iocache
1148
        else if (cache->write("NULL", 4))
1864.3.18 by Brian Aker
REmove goto from session.
1149
          return true;
1 by brian
clean slate
1150
      }
1151
      else
1152
      {
1208.3.2 by brian
Update for Cursor renaming.
1153
        used_length=0;				// Fill with space
1 by brian
clean slate
1154
      }
1155
    }
1156
    else
1157
    {
1158
      if (fixed_row_size)
1816.3.1 by Brian Aker
Convert sql_string to use size_t (this should clean up ICC warnings).
1159
        used_length= min(res->length(), static_cast<size_t>(item->max_length));
1 by brian
clean slate
1160
      else
1067.4.1 by Nathan Williams
First few changes at converting cmin to std::min.
1161
        used_length= res->length();
1162
1 by brian
clean slate
1163
      if ((result_type == STRING_RESULT || is_unsafe_field_sep) &&
1208.3.2 by brian
Update for Cursor renaming.
1164
          escape_char != -1)
1 by brian
clean slate
1165
      {
1166
        char *pos, *start, *end;
2254 by Brian Aker
Shift CHARSET_INFO to charset_info_st
1167
        const charset_info_st * const res_charset= res->charset();
1168
        const charset_info_st * const character_set_client= default_charset_info;
748 by Brian Aker
Removal of client side collation.
1169
1 by brian
clean slate
1170
        bool check_second_byte= (res_charset == &my_charset_bin) &&
1208.3.2 by brian
Update for Cursor renaming.
1171
          character_set_client->
1172
          escape_with_backslash_is_dangerous;
51.1.50 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
1173
        assert(character_set_client->mbmaxlen == 2 ||
748 by Brian Aker
Removal of client side collation.
1174
               !character_set_client->escape_with_backslash_is_dangerous);
1208.3.2 by brian
Update for Cursor renaming.
1175
        for (start=pos=(char*) res->ptr(),end=pos+used_length ;
1176
             pos != end ;
1177
             pos++)
1178
        {
1179
          if (use_mb(res_charset))
1180
          {
1181
            int l;
1182
            if ((l=my_ismbchar(res_charset, pos, end)))
1183
            {
1184
              pos += l-1;
1185
              continue;
1186
            }
1187
          }
1 by brian
clean slate
1188
1189
          /*
1190
            Special case when dumping BINARY/VARBINARY/BLOB values
1191
            for the clients with character sets big5, cp932, gbk and sjis,
1192
            which can have the escape character (0x5C "\" by default)
1193
            as the second byte of a multi-byte sequence.
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1194
1 by brian
clean slate
1195
            If
1196
            - pos[0] is a valid multi-byte head (e.g 0xEE) and
1197
            - pos[1] is 0x00, which will be escaped as "\0",
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1198
1 by brian
clean slate
1199
            then we'll get "0xEE + 0x5C + 0x30" in the output file.
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1200
1 by brian
clean slate
1201
            If this file is later loaded using this sequence of commands:
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1202
1 by brian
clean slate
1203
            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
1204
            mysql> LOAD DATA INFILE 'dump.txt' INTO Table t1;
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1205
1 by brian
clean slate
1206
            then 0x5C will be misinterpreted as the second byte
1207
            of a multi-byte character "0xEE + 0x5C", instead of
1208
            escape character for 0x00.
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1209
1 by brian
clean slate
1210
            To avoid this confusion, we'll escape the multi-byte
1211
            head character too, so the sequence "0xEE + 0x00" will be
1212
            dumped as "0x5C + 0xEE + 0x5C + 0x30".
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1213
1 by brian
clean slate
1214
            Note, in the condition below we only check if
1215
            mbcharlen is equal to 2, because there are no
1216
            character sets with mbmaxlen longer than 2
1217
            and with escape_with_backslash_is_dangerous set.
51.1.50 by Jay Pipes
Removed/replaced DBUG symbols and standardized TRUE/FALSE
1218
            assert before the loop makes that sure.
1 by brian
clean slate
1219
          */
1220
1377.6.3 by pawel
changed function-like defines into functions in some files
1221
          if ((needs_escaping(*pos, enclosed) ||
1 by brian
clean slate
1222
               (check_second_byte &&
481 by Brian Aker
Remove all of uchar.
1223
                my_mbcharlen(character_set_client, (unsigned char) *pos) == 2 &&
1 by brian
clean slate
1224
                pos + 1 < end &&
1377.6.3 by pawel
changed function-like defines into functions in some files
1225
                needs_escaping(pos[1], enclosed))) &&
1 by brian
clean slate
1226
              /*
1208.3.2 by brian
Update for Cursor renaming.
1227
                Don't escape field_term_char by doubling - doubling is only
1228
                valid for ENCLOSED BY characters:
1 by brian
clean slate
1229
              */
1230
              (enclosed || !is_ambiguous_field_term ||
481 by Brian Aker
Remove all of uchar.
1231
               (int) (unsigned char) *pos != field_term_char))
1 by brian
clean slate
1232
          {
1208.3.2 by brian
Update for Cursor renaming.
1233
            char tmp_buff[2];
481 by Brian Aker
Remove all of uchar.
1234
            tmp_buff[0]= ((int) (unsigned char) *pos == field_sep_char &&
1 by brian
clean slate
1235
                          is_ambiguous_field_sep) ?
1208.3.2 by brian
Update for Cursor renaming.
1236
              field_sep_char : escape_char;
1237
            tmp_buff[1]= *pos ? *pos : '0';
2385.3.13 by Olaf van der Spek
Refactor iocache
1238
            if (cache->write(start, pos - start) || cache->write(tmp_buff, 2))
1864.3.18 by Brian Aker
REmove goto from session.
1239
              return true;
1208.3.2 by brian
Update for Cursor renaming.
1240
            start=pos+1;
1241
          }
1242
        }
2385.3.13 by Olaf van der Spek
Refactor iocache
1243
        if (cache->write(start, pos - start))
1864.3.18 by Brian Aker
REmove goto from session.
1244
          return true;
1 by brian
clean slate
1245
      }
2385.3.13 by Olaf van der Spek
Refactor iocache
1246
      else if (cache->write(res->ptr(), used_length))
1864.3.18 by Brian Aker
REmove goto from session.
1247
        return true;
1 by brian
clean slate
1248
    }
1249
    if (fixed_row_size)
1250
    {						// Fill with space
1251
      if (item->max_length > used_length)
1252
      {
1208.3.2 by brian
Update for Cursor renaming.
1253
        /* QQ:  Fix by adding a my_b_fill() function */
1254
        if (!space_inited)
1255
        {
1256
          space_inited=1;
1257
          memset(space, ' ', sizeof(space));
1258
        }
1259
        uint32_t length=item->max_length-used_length;
1260
        for (; length > sizeof(space) ; length-=sizeof(space))
1261
        {
2385.3.13 by Olaf van der Spek
Refactor iocache
1262
          if (cache->write(space, sizeof(space)))
1864.3.18 by Brian Aker
REmove goto from session.
1263
            return true;
1208.3.2 by brian
Update for Cursor renaming.
1264
        }
2385.3.13 by Olaf van der Spek
Refactor iocache
1265
        if (cache->write(space, length))
1864.3.18 by Brian Aker
REmove goto from session.
1266
          return true;
1 by brian
clean slate
1267
      }
1268
    }
1269
    if (res && enclosed)
1270
    {
2385.3.13 by Olaf van der Spek
Refactor iocache
1271
      if (cache->write(exchange->enclosed->ptr(), exchange->enclosed->length()))
1864.3.18 by Brian Aker
REmove goto from session.
1272
        return true;
1 by brian
clean slate
1273
    }
1274
    if (--items_left)
1275
    {
2385.3.13 by Olaf van der Spek
Refactor iocache
1276
      if (cache->write(exchange->field_term->ptr(), field_term_length))
1864.3.18 by Brian Aker
REmove goto from session.
1277
        return true;
1 by brian
clean slate
1278
    }
1279
  }
2385.3.13 by Olaf van der Spek
Refactor iocache
1280
  if (cache->write(exchange->line_term->ptr(), exchange->line_term->length()))
1864.3.18 by Brian Aker
REmove goto from session.
1281
  {
1282
    return true;
1283
  }
1284
1285
  return false;
1 by brian
clean slate
1286
}
1287
1288
1289
/***************************************************************************
1290
** Dump  of select to a binary file
1291
***************************************************************************/
1292
1293
1294
int
848 by Brian Aker
typdef class removal (just... use the name of the class).
1295
select_dump::prepare(List<Item> &, Select_Lex_Unit *u)
1 by brian
clean slate
1296
{
1297
  unit= u;
2318.6.43 by Olaf van der Spek
Refactor
1298
  return (file= create_file(*session, path, exchange, cache)) < 0;
1 by brian
clean slate
1299
}
1300
1301
1302
bool select_dump::send_data(List<Item> &items)
1303
{
2183.2.12 by Olaf van der Spek
Use List::begin()
1304
  List<Item>::iterator li(items.begin());
1 by brian
clean slate
1305
  char buff[MAX_FIELD_WIDTH];
1306
  String tmp(buff,sizeof(buff),&my_charset_bin),*res;
1307
  tmp.length(0);
1308
1309
  if (unit->offset_limit_cnt)
1310
  {						// using limit offset,count
1311
    unit->offset_limit_cnt--;
2318.6.58 by Olaf van der Spek
Refactor
1312
    return 0;
1 by brian
clean slate
1313
  }
660.1.3 by Eric Herman
removed trailing whitespace with simple script:
1314
  if (row_count++ > 1)
1 by brian
clean slate
1315
  {
1316
    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.
1317
    return 1;
1 by brian
clean slate
1318
  }
2385.2.10 by Olaf van der Spek
Refactor
1319
  while (Item* item=li++)
1 by brian
clean slate
1320
  {
1321
    res=item->str_result(&tmp);
1322
    if (!res)					// If NULL
1323
    {
2385.3.13 by Olaf van der Spek
Refactor iocache
1324
      if (cache->write("", 1))
1813.2.12 by Monty Taylor
Made load_file work properly with throwing errors and opening files.
1325
        return 1;
1 by brian
clean slate
1326
    }
2385.3.13 by Olaf van der Spek
Refactor iocache
1327
    else if (cache->write(res->ptr(), res->length()))
1 by brian
clean slate
1328
    {
1813.2.9 by Monty Taylor
Made data_home be fs::path natively.
1329
      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.
1330
      return 1;
1 by brian
clean slate
1331
    }
1332
  }
2318.6.58 by Olaf van der Spek
Refactor
1333
  return 0;
1 by brian
clean slate
1334
}
1335
1336
1337
select_subselect::select_subselect(Item_subselect *item_arg)
1338
{
1339
  item= item_arg;
1340
}
1341
1342
1343
bool select_singlerow_subselect::send_data(List<Item> &items)
1344
{
1345
  Item_singlerow_subselect *it= (Item_singlerow_subselect *)item;
1346
  if (it->assigned())
1347
  {
1348
    my_message(ER_SUBQUERY_NO_1_ROW, ER(ER_SUBQUERY_NO_1_ROW), MYF(0));
2318.6.77 by Olaf van der Spek
Refactor
1349
    return 1;
1 by brian
clean slate
1350
  }
1351
  if (unit->offset_limit_cnt)
1352
  {				          // Using limit offset,count
1353
    unit->offset_limit_cnt--;
2318.6.58 by Olaf van der Spek
Refactor
1354
    return 0;
1 by brian
clean slate
1355
  }
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;
482 by Brian Aker
Remove uint.
1358
  for (uint32_t i= 0; (val_item= li++); i++)
1 by brian
clean slate
1359
    it->store(i, val_item);
1360
  it->assigned(1);
2318.6.58 by Olaf van der Spek
Refactor
1361
  return 0;
1 by brian
clean slate
1362
}
1363
1364
1365
void select_max_min_finder_subselect::cleanup()
1366
{
1367
  cache= 0;
1368
}
1369
1370
1371
bool select_max_min_finder_subselect::send_data(List<Item> &items)
1372
{
1373
  Item_maxmin_subselect *it= (Item_maxmin_subselect *)item;
2183.2.12 by Olaf van der Spek
Use List::begin()
1374
  List<Item>::iterator li(items.begin());
1 by brian
clean slate
1375
  Item *val_item= li++;
1376
  it->register_value();
1377
  if (it->assigned())
1378
  {
1379
    cache->store(val_item);
1380
    if ((this->*op)())
1381
      it->store(0, cache);
1382
  }
1383
  else
1384
  {
1385
    if (!cache)
1386
    {
1387
      cache= Item_cache::get_cache(val_item);
1388
      switch (val_item->result_type())
1389
      {
1390
      case REAL_RESULT:
1843.7.1 by Brian Aker
Convert vector to list (it will make deletion a bit faster).
1391
        op= &select_max_min_finder_subselect::cmp_real;
1392
        break;
1 by brian
clean slate
1393
      case INT_RESULT:
1843.7.1 by Brian Aker
Convert vector to list (it will make deletion a bit faster).
1394
        op= &select_max_min_finder_subselect::cmp_int;
1395
        break;
1 by brian
clean slate
1396
      case STRING_RESULT:
1843.7.1 by Brian Aker
Convert vector to list (it will make deletion a bit faster).
1397
        op= &select_max_min_finder_subselect::cmp_str;
1398
        break;
1 by brian
clean slate
1399
      case DECIMAL_RESULT:
1400
        op= &select_max_min_finder_subselect::cmp_decimal;
1401
        break;
1402
      case ROW_RESULT:
1403
        // This case should never be choosen
1843.7.1 by Brian Aker
Convert vector to list (it will make deletion a bit faster).
1404
        assert(0);
1405
        op= 0;
1 by brian
clean slate
1406
      }
1407
    }
1408
    cache->store(val_item);
1409
    it->store(0, cache);
1410
  }
1411
  it->assigned(1);
2318.6.58 by Olaf van der Spek
Refactor
1412
  return 0;
1 by brian
clean slate
1413
}
1414
1415
bool select_max_min_finder_subselect::cmp_real()
1416
{
1417
  Item *maxmin= ((Item_singlerow_subselect *)item)->element_index(0);
1418
  double val1= cache->val_real(), val2= maxmin->val_real();
1419
  if (fmax)
1420
    return (cache->null_value && !maxmin->null_value) ||
1421
      (!cache->null_value && !maxmin->null_value &&
1422
       val1 > val2);
1423
  return (maxmin->null_value && !cache->null_value) ||
1424
    (!cache->null_value && !maxmin->null_value &&
1425
     val1 < val2);
1426
}
1427
1428
bool select_max_min_finder_subselect::cmp_int()
1429
{
1430
  Item *maxmin= ((Item_singlerow_subselect *)item)->element_index(0);
152 by Brian Aker
longlong replacement
1431
  int64_t val1= cache->val_int(), val2= maxmin->val_int();
1 by brian
clean slate
1432
  if (fmax)
1433
    return (cache->null_value && !maxmin->null_value) ||
1434
      (!cache->null_value && !maxmin->null_value &&
1435
       val1 > val2);
1436
  return (maxmin->null_value && !cache->null_value) ||
1437
    (!cache->null_value && !maxmin->null_value &&
1438
     val1 < val2);
1439
}
1440
1441
bool select_max_min_finder_subselect::cmp_decimal()
1442
{
1443
  Item *maxmin= ((Item_singlerow_subselect *)item)->element_index(0);
2030.1.4 by Brian Aker
Change my_decimal to Decimal
1444
  type::Decimal cval, *cvalue= cache->val_decimal(&cval);
1445
  type::Decimal mval, *mvalue= maxmin->val_decimal(&mval);
1 by brian
clean slate
1446
  if (fmax)
1447
    return (cache->null_value && !maxmin->null_value) ||
1448
      (!cache->null_value && !maxmin->null_value &&
2030.1.2 by Brian Aker
First pass in refactoring of the name of my_decimal.
1449
       class_decimal_cmp(cvalue, mvalue) > 0) ;
1 by brian
clean slate
1450
  return (maxmin->null_value && !cache->null_value) ||
1451
    (!cache->null_value && !maxmin->null_value &&
2030.1.2 by Brian Aker
First pass in refactoring of the name of my_decimal.
1452
     class_decimal_cmp(cvalue,mvalue) < 0);
1 by brian
clean slate
1453
}
1454
1455
bool select_max_min_finder_subselect::cmp_str()
1456
{
1457
  String *val1, *val2, buf1, buf2;
1458
  Item *maxmin= ((Item_singlerow_subselect *)item)->element_index(0);
1459
  /*
1460
    as far as both operand is Item_cache buf1 & buf2 will not be used,
1461
    but added for safety
1462
  */
1463
  val1= cache->val_str(&buf1);
1464
  val2= maxmin->val_str(&buf1);
1465
  if (fmax)
1466
    return (cache->null_value && !maxmin->null_value) ||
1467
      (!cache->null_value && !maxmin->null_value &&
1468
       sortcmp(val1, val2, cache->collation.collation) > 0) ;
1469
  return (maxmin->null_value && !cache->null_value) ||
1470
    (!cache->null_value && !maxmin->null_value &&
1471
     sortcmp(val1, val2, cache->collation.collation) < 0);
1472
}
1473
779.1.27 by Monty Taylor
Got rid of __attribute__((unused)) and the like from the .cc files.
1474
bool select_exists_subselect::send_data(List<Item> &)
1 by brian
clean slate
1475
{
1476
  Item_exists_subselect *it= (Item_exists_subselect *)item;
1477
  if (unit->offset_limit_cnt)
77.1.45 by Monty Taylor
Warning fixes.
1478
  { // Using limit offset,count
1 by brian
clean slate
1479
    unit->offset_limit_cnt--;
2318.6.58 by Olaf van der Spek
Refactor
1480
    return 0;
1 by brian
clean slate
1481
  }
1482
  it->value= 1;
1483
  it->assigned(1);
2318.6.58 by Olaf van der Spek
Refactor
1484
  return 0;
1 by brian
clean slate
1485
}
1486
406 by Brian Aker
Cleanup around Query_arena.
1487
/*
1488
  Don't free mem_root, as mem_root is freed in the end of dispatch_command
1489
  (once for any command).
1490
*/
520.1.21 by Brian Aker
THD -> Session rename
1491
void Session::end_statement()
1 by brian
clean slate
1492
{
1493
  /* Cleanup SQL processing state to reuse this statement in next query. */
2227.4.8 by Olaf van der Spek
Session::lex()
1494
  lex().end();
1643.6.16 by Djellel E. Difallah
Fixing memory leaks
1495
  resetResultsetMessage();
1 by brian
clean slate
1496
}
1497
2385.1.7 by Olaf van der Spek
Rename set_db to set_schema
1498
bool Session::copy_db_to(char*& db, size_t& db_length)
202.3.6 by Monty Taylor
First pass at gettexizing the error messages.
1499
{
2275.2.6 by Olaf van der Spek
Refactor
1500
  if (impl_->schema->empty())
2269.1.7 by Olaf van der Spek
Use util::string::ptr
1501
  {
1502
    my_message(ER_NO_DB_ERROR, ER(ER_NO_DB_ERROR), MYF(0));
1503
    return true;
1504
  }
2318.9.10 by Olaf van der Spek
Rename strmake to strdup (standard name)
1505
  db= mem.strdup(*impl_->schema);
2318.8.4 by Olaf van der Spek
Refactor copy_db_to
1506
  db_length= impl_->schema->size();
202.3.6 by Monty Taylor
First pass at gettexizing the error messages.
1507
  return false;
1508
}
1509
1101.1.16 by Monty Taylor
Reverted 1103
1510
/****************************************************************************
1511
  Tmp_Table_Param
1512
****************************************************************************/
1513
1514
void Tmp_Table_Param::init()
1515
{
1516
  field_count= sum_func_count= func_count= hidden_field_count= 0;
1517
  group_parts= group_length= group_null_parts= 0;
1518
  quick_group= 1;
1519
  table_charset= 0;
1520
  precomputed_group_by= 0;
1521
}
1522
2385.3.14 by Olaf van der Spek
Remove unused Session::query_cache_key var
1523
void Tmp_Table_Param::cleanup()
1101.1.16 by Monty Taylor
Reverted 1103
1524
{
1525
  /* Fix for Intel compiler */
1526
  if (copy_field)
1527
  {
2069.4.1 by Brian Aker
A little on the paranoid side, but not the worst plan ever to check our
1528
    boost::checked_array_delete(copy_field);
2053.3.1 by Andrew Hutchings
Clear copy_field completely to avoid stale pointer restore causing crash
1529
    save_copy_field= save_copy_field_end= copy_field= copy_field_end= 0;
1101.1.16 by Monty Taylor
Reverted 1103
1530
  }
1531
}
1532
520.1.21 by Brian Aker
THD -> Session rename
1533
void Session::send_kill_message() const
202.3.6 by Monty Taylor
First pass at gettexizing the error messages.
1534
{
2087.3.1 by Brian Aker
Entire convert over to time_t.
1535
  drizzled::error_t err= static_cast<drizzled::error_t>(killed_errno());
1536
  if (err != EE_OK)
202.3.6 by Monty Taylor
First pass at gettexizing the error messages.
1537
    my_message(err, ER(err), MYF(0));
1538
}
1 by brian
clean slate
1539
2385.1.7 by Olaf van der Spek
Rename set_db to set_schema
1540
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.
1541
{
2269.1.7 by Olaf van der Spek
Use util::string::ptr
1542
  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.
1543
}
1544
1273 by Brian Aker
Revert db patch.
1545
1 by brian
clean slate
1546
/**
1547
  Mark transaction to rollback and mark error as fatal to a sub-statement.
1548
520.1.22 by Brian Aker
Second pass of thd cleanup
1549
  @param  session   Thread handle
2224.2.3 by Olaf van der Spek
Refactor
1550
  @param  all   true <=> rollback main transaction().
1 by brian
clean slate
1551
*/
2153.1.2 by Stewart Smith
replace mark_transaction_to_rollback() with Session::markTransactionForRollback()
1552
void Session::markTransactionForRollback(bool all)
1 by brian
clean slate
1553
{
2153.1.2 by Stewart Smith
replace mark_transaction_to_rollback() with Session::markTransactionForRollback()
1554
  is_fatal_sub_stmt_error= true;
1555
  transaction_rollback_request= all;
1 by brian
clean slate
1556
}
1557
2269.1.7 by Olaf van der Spek
Use util::string::ptr
1558
void Session::disconnect(error_t errcode)
575.4.7 by Monty Taylor
More header cleanup.
1559
{
934.2.6 by Jay Pipes
This changeset removes a few more C functions from sql_connect.cc/connect.h
1560
  /* Allow any plugins to cleanup their session variables */
1561
  plugin_sessionvar_cleanup(this);
1562
1563
  /* If necessary, log any aborted or unauthorized connections */
1910.2.8 by Brian Aker
Enapsulate Kill.
1564
  if (getKilled() || client->wasAborted())
1537.2.1 by Joe Daly
add statistics_variables.h
1565
  {
1689.5.1 by Joseph Daly
remove increment calls
1566
    status_var.aborted_threads++;
1537.2.1 by Joe Daly
add statistics_variables.h
1567
  }
934.2.6 by Jay Pipes
This changeset removes a few more C functions from sql_connect.cc/connect.h
1568
971.6.1 by Eric Day
Renamed Protocol to Client, cleaned up some unnecessary methods along the way.
1569
  if (client->wasAborted())
934.2.6 by Jay Pipes
This changeset removes a few more C functions from sql_connect.cc/connect.h
1570
  {
1910.2.8 by Brian Aker
Enapsulate Kill.
1571
    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
1572
    {
2126.3.3 by Brian Aker
Merge in error message rework. Many error messages are fixed in this patch.
1573
      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
1574
                  , thread_id
2269.1.7 by Olaf van der Spek
Use util::string::ptr
1575
                  , (impl_->schema->empty() ? "unconnected" : impl_->schema->c_str())
2275.2.6 by Olaf van der Spek
Refactor
1576
                  , 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
1577
                  , security_ctx->address().c_str()
2239.1.4 by Olaf van der Spek
Refactor includes
1578
                  , (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
1579
    }
1580
  }
1581
1910.2.8 by Brian Aker
Enapsulate Kill.
1582
  setKilled(Session::KILL_CONNECTION);
1583
971.6.1 by Eric Day
Renamed Protocol to Client, cleaned up some unnecessary methods along the way.
1584
  if (client->isConnected())
575.4.7 by Monty Taylor
More header cleanup.
1585
  {
2015.3.3 by Brian Aker
Update disconnect code.
1586
    if (errcode != EE_OK)
971.3.12 by Eric Day
Started abstracting Protocol, removed init_connect, init_file.
1587
    {
1588
      /*my_error(errcode, ER(errcode));*/
971.6.11 by Eric Day
Removed purecov messages.
1589
      client->sendError(errcode, ER(errcode));
971.3.12 by Eric Day
Started abstracting Protocol, removed init_connect, init_file.
1590
    }
971.6.1 by Eric Day
Renamed Protocol to Client, cleaned up some unnecessary methods along the way.
1591
    client->close();
575.4.7 by Monty Taylor
More header cleanup.
1592
  }
1593
}
735 by Brian Aker
Refactor session.
1594
1595
void Session::reset_for_next_command()
1596
{
1597
  free_list= 0;
1598
  select_number= 1;
1599
1055.2.17 by Jay Pipes
More style cleanups in Session
1600
  is_fatal_error= false;
735 by Brian Aker
Refactor session.
1601
  server_status&= ~ (SERVER_MORE_RESULTS_EXISTS |
1602
                          SERVER_QUERY_NO_INDEX_USED |
1603
                          SERVER_QUERY_NO_GOOD_INDEX_USED);
1604
1605
  clear_error();
2239.1.4 by Olaf van der Spek
Refactor includes
1606
  main_da().reset_diagnostics_area();
735 by Brian Aker
Refactor session.
1607
  total_warn_count=0;			// Warnings for this query
1608
  sent_row_count= examined_row_count= 0;
1609
}
793 by Brian Aker
Pass through on refactoring functions to clases.
1610
1611
/*
1612
  Close all temporary tables created by 'CREATE TEMPORARY TABLE' for thread
1613
*/
1614
2263.3.7 by Olaf van der Spek
Keep functions in Open_tables_state
1615
void Open_tables_state::close_temporary_tables()
793 by Brian Aker
Pass through on refactoring functions to clases.
1616
{
1617
  Table *table;
798.2.20 by Brian Aker
More cleanup of binlog.isopen
1618
  Table *tmp_next;
793 by Brian Aker
Pass through on refactoring functions to clases.
1619
1395.1.11 by Brian Aker
Rename of close_temporary to nukeTable() so that my regex will stop looking
1620
  if (not temporary_tables)
793 by Brian Aker
Pass through on refactoring functions to clases.
1621
    return;
1622
798.2.20 by Brian Aker
More cleanup of binlog.isopen
1623
  for (table= temporary_tables; table; table= tmp_next)
1624
  {
1608 by Brian Aker
This encapsulates prev/next.
1625
    tmp_next= table->getNext();
1395.1.11 by Brian Aker
Rename of close_temporary to nukeTable() so that my regex will stop looking
1626
    nukeTable(table);
798.2.20 by Brian Aker
More cleanup of binlog.isopen
1627
  }
1046.1.6 by Brian Aker
Formatting/style cleanup.
1628
  temporary_tables= NULL;
793 by Brian Aker
Pass through on refactoring functions to clases.
1629
}
855 by Brian Aker
Refactor reset of status.
1630
1109.1.1 by Brian Aker
Applying refactor of tmp table bits back to session. (this all needs to be
1631
/*
1632
  unlink from session->temporary tables and close temporary table
1633
*/
1634
2263.3.7 by Olaf van der Spek
Keep functions in Open_tables_state
1635
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
1636
{
1608 by Brian Aker
This encapsulates prev/next.
1637
  if (table->getPrev())
1109.1.1 by Brian Aker
Applying refactor of tmp table bits back to session. (this all needs to be
1638
  {
1608 by Brian Aker
This encapsulates prev/next.
1639
    table->getPrev()->setNext(table->getNext());
1640
    if (table->getPrev()->getNext())
1641
    {
1642
      table->getNext()->setPrev(table->getPrev());
1643
    }
1109.1.1 by Brian Aker
Applying refactor of tmp table bits back to session. (this all needs to be
1644
  }
1645
  else
1646
  {
1647
    /* removing the item from the list */
1648
    assert(table == temporary_tables);
1649
    /*
1650
      slave must reset its temporary list pointer to zero to exclude
1651
      passing non-zero value to end_slave via rli->save_temporary_tables
1652
      when no temp tables opened, see an invariant below.
1653
    */
1608 by Brian Aker
This encapsulates prev/next.
1654
    temporary_tables= table->getNext();
1109.1.1 by Brian Aker
Applying refactor of tmp table bits back to session. (this all needs to be
1655
    if (temporary_tables)
1608 by Brian Aker
This encapsulates prev/next.
1656
    {
1657
      table->getNext()->setPrev(NULL);
1658
    }
1109.1.1 by Brian Aker
Applying refactor of tmp table bits back to session. (this all needs to be
1659
  }
1395.1.11 by Brian Aker
Rename of close_temporary to nukeTable() so that my regex will stop looking
1660
  nukeTable(table);
1109.1.1 by Brian Aker
Applying refactor of tmp table bits back to session. (this all needs to be
1661
}
1662
1663
/*
1395.1.11 by Brian Aker
Rename of close_temporary to nukeTable() so that my regex will stop looking
1664
  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
1665
1666
  NOTE
1667
  This dosn't unlink table from session->temporary
1668
  If this is needed, use close_temporary_table()
1669
*/
1670
2263.3.7 by Olaf van der Spek
Keep functions in Open_tables_state
1671
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
1672
{
2246.4.3 by Olaf van der Spek
Refactor Session
1673
  plugin::StorageEngine& table_type= *table->getShare()->db_type();
1109.1.4 by Brian Aker
More Table refactor
1674
  table->free_io_cache();
1672.3.2 by Brian Aker
Tiny little cleanup around Table.
1675
  table->delete_table();
2246.4.3 by Olaf van der Spek
Refactor Session
1676
  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
1677
  boost::checked_delete(table->getMutableShare());
1678
  boost::checked_delete(table);
1109.1.1 by Brian Aker
Applying refactor of tmp table bits back to session. (this all needs to be
1679
}
855 by Brian Aker
Refactor reset of status.
1680
1681
/** Clear most status variables. */
1682
extern time_t flush_status_time;
1683
1684
void Session::refresh_status()
1685
{
1686
  /* Reset thread's status variables */
1687
  memset(&status_var, 0, sizeof(status_var));
1688
1689
  flush_status_time= time((time_t*) 0);
1537.2.1 by Joe Daly
add statistics_variables.h
1690
  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.
1691
  current_global_counters.connections= 0;
855 by Brian Aker
Refactor reset of status.
1692
}
995 by Brian Aker
Refactor get_variable to session
1693
2371.1.2 by Brian Aker
Remove the typedef on lexkey
1694
user_var_entry *Session::getVariable(lex_string_t &name, bool create_if_not_exists)
995 by Brian Aker
Refactor get_variable to session
1695
{
1836.4.1 by Brian Aker
Adding in more test case for events (though these do not really have the
1696
  return getVariable(std::string(name.str, name.length), create_if_not_exists);
1697
}
1698
1699
user_var_entry *Session::getVariable(const std::string  &name, bool create_if_not_exists)
1700
{
2132.2.1 by Andrew Hutchings
Don't touch user vars after the have already been cleaned up
1701
  if (cleanup_done)
1702
    return NULL;
995 by Brian Aker
Refactor get_variable to session
1703
2192.4.1 by Olaf van der Spek
Add find_ptr
1704
  if (UserVars::mapped_type* iter= find_ptr(user_vars, name))
1705
    return *iter;
995 by Brian Aker
Refactor get_variable to session
1706
1859.3.1 by Brian Aker
Slight refactor of the uservar class.
1707
  if (not create_if_not_exists)
1708
    return NULL;
1709
2246.3.1 by Olaf van der Spek
Remove std::nothrow from new()
1710
  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.
1711
1712
  std::pair<UserVars::iterator, bool> returnable= user_vars.insert(make_pair(name, entry));
1713
1714
  if (not returnable.second)
995 by Brian Aker
Refactor get_variable to session
1715
  {
2069.4.1 by Brian Aker
A little on the paranoid side, but not the worst plan ever to check our
1716
    boost::checked_delete(entry);
995 by Brian Aker
Refactor get_variable to session
1717
  }
1718
1719
  return entry;
1720
}
1039.1.16 by Brian Aker
A lot of little cleanups (most based off lcov)
1721
1836.4.1 by Brian Aker
Adding in more test case for events (though these do not really have the
1722
void Session::setVariable(const std::string &name, const std::string &value)
1723
{
1724
  user_var_entry *updateable_var= getVariable(name.c_str(), true);
2132.2.1 by Andrew Hutchings
Don't touch user vars after the have already been cleaned up
1725
  if (updateable_var)
1726
  {
1727
    updateable_var->update_hash(false,
1728
                                (void*)value.c_str(),
1729
                                static_cast<uint32_t>(value.length()), STRING_RESULT,
1730
                                &my_charset_bin,
1731
                                DERIVATION_IMPLICIT, false);
1732
  }
1836.4.1 by Brian Aker
Adding in more test case for events (though these do not really have the
1733
}
1734
1922.1.1 by Brian Aker
Move temp tables down to open_table class. (first pass)
1735
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)
1736
{
1608 by Brian Aker
This encapsulates prev/next.
1737
  for (Table *table= temporary_tables ; table ; table= table->getNext())
1039.1.16 by Brian Aker
A lot of little cleanups (most based off lcov)
1738
  {
2263.3.10 by Olaf van der Spek
Open Tables
1739
    if (table->query_id == session_.getQueryId())
1039.1.16 by Brian Aker
A lot of little cleanups (most based off lcov)
1740
    {
1741
      table->query_id= 0;
1208.3.2 by brian
Update for Cursor renaming.
1742
      table->cursor->ha_reset();
1039.1.16 by Brian Aker
A lot of little cleanups (most based off lcov)
1743
    }
1744
  }
1745
}
1746
1747
/*
1055.2.24 by Jay Pipes
Merge with trunk and resolve conflicts.
1748
  Unlocks tables and frees derived tables.
1749
  Put all normal tables used by thread in free list.
1750
1751
  It will only close/mark as free for reuse tables opened by this
1752
  substatement, it will also check if we are closing tables after
1753
  execution of complete query (i.e. we are on upper level) and will
1754
  leave prelocked mode if needed.
1039.1.16 by Brian Aker
A lot of little cleanups (most based off lcov)
1755
*/
1756
void Session::close_thread_tables()
1757
{
2263.3.10 by Olaf van der Spek
Open Tables
1758
  open_tables.clearDerivedTables();
1039.1.16 by Brian Aker
A lot of little cleanups (most based off lcov)
1759
1760
  /*
1761
    Mark all temporary tables used by this statement as free for reuse.
1762
  */
2263.3.10 by Olaf van der Spek
Open Tables
1763
  open_tables.mark_temp_tables_as_free_for_reuse();
1039.1.16 by Brian Aker
A lot of little cleanups (most based off lcov)
1764
  /*
1765
    Let us commit transaction for statement. Since in 5.0 we only have
1766
    one statement transaction and don't allow several nested statement
1767
    transactions this call will do nothing if we are inside of stored
1768
    function or trigger (i.e. statement transaction is already active and
1769
    does not belong to statement for which we do close_thread_tables()).
1770
    TODO: This should be fixed in later releases.
1771
   */
1772
  {
2239.1.4 by Olaf van der Spek
Refactor includes
1773
    main_da().can_overwrite_status= true;
2318.6.62 by Olaf van der Spek
Refactor
1774
    TransactionServices::autocommitOrRollback(*this, is_error());
2239.1.4 by Olaf van der Spek
Refactor includes
1775
    main_da().can_overwrite_status= false;
2224.2.5 by Olaf van der Spek
Undo partial commit
1776
    transaction.stmt.reset();
1039.1.16 by Brian Aker
A lot of little cleanups (most based off lcov)
1777
  }
1778
2263.3.10 by Olaf van der Spek
Open Tables
1779
  if (open_tables.lock)
1039.1.16 by Brian Aker
A lot of little cleanups (most based off lcov)
1780
  {
1781
    /*
1782
      For RBR we flush the pending event just before we unlock all the
1783
      tables.  This means that we are at the end of a topmost
1784
      statement, so we ensure that the STMT_END_F flag is set on the
1785
      pending event.  For statements that are *inside* stored
1786
      functions, the pending event will not be flushed: that will be
1787
      handled either before writing a query log event (inside
1788
      binlog_query()) or when preparing a pending event.
1789
     */
2263.3.10 by Olaf van der Spek
Open Tables
1790
    unlockTables(open_tables.lock);
1791
    open_tables.lock= 0;
1039.1.16 by Brian Aker
A lot of little cleanups (most based off lcov)
1792
  }
1793
  /*
2275.3.1 by Olaf van der Spek
Remove table::Cache::singleton()
1794
    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)
1795
    open_tables list. Another thread may work on it.
2275.3.1 by Olaf van der Spek
Remove table::Cache::singleton()
1796
    (See: table::Cache::removeTable(), wait_completed_table())
1039.1.16 by Brian Aker
A lot of little cleanups (most based off lcov)
1797
    Closing a MERGE child before the parent would be fatal if the
1798
    other thread tries to abort the MERGE lock in between.
1799
  */
2263.3.10 by Olaf van der Spek
Open Tables
1800
  if (open_tables.open_tables_)
2280.1.10 by Olaf van der Spek
Remove unused param
1801
    open_tables.close_open_tables();
1039.1.16 by Brian Aker
A lot of little cleanups (most based off lcov)
1802
}
1054.1.9 by Brian Aker
This is a large number of refactors against the Session class for its
1803
1804
void Session::close_tables_for_reopen(TableList **tables)
1805
{
1806
  /*
1807
    If table list consists only from tables from prelocking set, table list
1808
    for new attempt should be empty, so we have to update list's root pointer.
1809
  */
2227.4.8 by Olaf van der Spek
Session::lex()
1810
  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
1811
    *tables= 0;
2227.4.8 by Olaf van der Spek
Session::lex()
1812
  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
1813
  for (TableList *tmp= *tables; tmp; tmp= tmp->next_global)
1814
    tmp->table= 0;
1815
  close_thread_tables();
1816
}
1817
1109.1.3 by Brian Aker
Move names around a bit (to align similar methods)
1818
bool Session::openTablesLock(TableList *tables)
1054.1.9 by Brian Aker
This is a large number of refactors against the Session class for its
1819
{
1820
  uint32_t counter;
1821
  bool need_reopen;
1822
1823
  for ( ; ; )
1824
  {
1109.1.2 by Brian Aker
More from the table patch
1825
    if (open_tables_from_list(&tables, &counter))
1826
      return true;
1054.1.9 by Brian Aker
This is a large number of refactors against the Session class for its
1827
1415 by Brian Aker
Mass overhaul to use schema_identifier.
1828
    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
1829
      break;
2060.3.1 by Brian Aker
First pass, remove retry.
1830
1415 by Brian Aker
Mass overhaul to use schema_identifier.
1831
    if (not need_reopen)
1109.1.2 by Brian Aker
More from the table patch
1832
      return true;
2060.3.1 by Brian Aker
First pass, remove retry.
1833
1054.1.9 by Brian Aker
This is a large number of refactors against the Session class for its
1834
    close_tables_for_reopen(&tables);
1835
  }
2060.3.1 by Brian Aker
First pass, remove retry.
1836
2227.4.10 by Olaf van der Spek
Session::lex()
1837
  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
1838
}
1839
1608.2.1 by Brian Aker
Modified to table identifier to fix temporary table creation loss of file.
1840
/*
1841
  @note "best_effort" is used in cases were if a failure occurred on this
1842
  operation it would not be surprising because we are only removing because there
1843
  might be an issue (lame engines).
1844
*/
1845
2263.3.7 by Olaf van der Spek
Keep functions in Open_tables_state
1846
bool Open_tables_state::rm_temporary_table(const identifier::Table &identifier, bool best_effort)
1223.4.8 by Brian Aker
More table identifier love :)
1847
{
2263.3.9 by Olaf van der Spek
Open Tables
1848
  if (plugin::StorageEngine::dropTable(session_, identifier))
2246.4.3 by Olaf van der Spek
Refactor Session
1849
		return false;
1850
  if (not best_effort)
1851
    errmsg_printf(error::WARN, _("Could not remove temporary table: '%s', error: %d"), identifier.getSQLPath().c_str(), errno);
1852
  return true;
1223.4.8 by Brian Aker
More table identifier love :)
1853
}
1854
2263.3.7 by Olaf van der Spek
Keep functions in Open_tables_state
1855
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
1856
{
2068.7.1 by Brian Aker
First pass through error correction in SE interface for drop table.
1857
  drizzled::error_t error;
2263.3.9 by Olaf van der Spek
Open Tables
1858
  if (plugin::StorageEngine::dropTable(session_, base, identifier, error))
2246.4.2 by Olaf van der Spek
Refactor Identifier::getSQLPath()
1859
		return false;
1860
  errmsg_printf(error::WARN, _("Could not remove temporary table: '%s', error: %d"), identifier.getSQLPath().c_str(), error);
1861
  return true;
1395.1.12 by Brian Aker
Fixes failure related to Heap's hack on deletion. Also cleans up error
1862
}
1863
2241.3.6 by Olaf van der Spek
Refactor
1864
table::Singular& Session::getInstanceTable()
1618 by Brian Aker
This is a rollup set of patches for modifications to TableIdentifier to have
1865
{
2241.3.7 by Olaf van der Spek
Refactor
1866
  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
1867
  return impl_->temporary_shares.back();
1532.1.1 by Brian Aker
Merge of change to flip table instance to be share instance
1868
}
1869
1878.5.1 by Brian Aker
Update instance for handling construction of virtual_tmp
1870
1871
/**
1872
  Create a reduced Table object with properly set up Field list from a
1873
  list of field definitions.
1874
1875
    The created table doesn't have a table Cursor associated with
1876
    it, has no keys, no group/distinct, no copy_funcs array.
1877
    The sole purpose of this Table object is to use the power of Field
1878
    class to read/write data to/from table->getInsertRecord(). Then one can store
1879
    the record in any container (RB tree, hash, etc).
1880
    The table is created in Session mem_root, so are the table's fields.
1881
    Consequently, if you don't BLOB fields, you don't need to free it.
1882
1883
  @param session         connection handle
1884
  @param field_list  list of column definitions
1885
1886
  @return
1887
    0 if out of memory, Table object in case of success
1888
*/
2241.3.6 by Olaf van der Spek
Refactor
1889
table::Singular& Session::getInstanceTable(std::list<CreateField>& field_list)
1878.5.1 by Brian Aker
Update instance for handling construction of virtual_tmp
1890
{
2241.3.7 by Olaf van der Spek
Refactor
1891
  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
1892
  return impl_->temporary_shares.back();
2239.1.4 by Olaf van der Spek
Refactor includes
1893
}
1894
1895
void Session::clear_error(bool full)
1896
{
1897
  if (main_da().is_error())
1898
    main_da().reset_diagnostics_area();
1899
1900
  if (full)
2318.6.104 by Olaf van der Spek
Refactor
1901
    drizzle_reset_errors(*this, true);
2239.1.4 by Olaf van der Spek
Refactor includes
1902
}
1903
1904
void Session::clearDiagnostics()
1905
{
1906
  main_da().reset_diagnostics_area();
1907
}
1908
1909
/**
1910
  true if there is an error in the error stack.
1911
1912
  Please use this method instead of direct access to
1913
  net.report_error.
1914
1915
  If true, the current (sub)-statement should be aborted.
1916
  The main difference between this member and is_fatal_error
1917
  is that a fatal error can not be handled by a stored
1918
  procedure continue handler, whereas a normal error can.
1919
1920
  To raise this flag, use my_error().
1921
*/
1922
bool Session::is_error() const 
1923
{ 
1924
  return impl_->diagnostics.is_error(); 
1925
}
1926
1927
/** A short cut for session->main_da().set_ok_status(). */
1928
void Session::my_ok(ha_rows affected_rows, ha_rows found_rows_arg, uint64_t passed_id, const char *message)
1929
{
1930
  main_da().set_ok_status(this, affected_rows, found_rows_arg, passed_id, message);
1931
}
1932
1933
/** A short cut for session->main_da().set_eof_status(). */
1934
1935
void Session::my_eof()
1936
{
1937
  main_da().set_eof_status(this);
1878.5.1 by Brian Aker
Update instance for handling construction of virtual_tmp
1938
}
1939
2239.1.9 by Olaf van der Spek
Refactor includes
1940
plugin::StorageEngine* Session::getDefaultStorageEngine()
1941
{
1942
  return variables.storage_engine ? variables.storage_engine : global_system_variables.storage_engine;
1943
}
1944
2385.3.6 by Olaf van der Spek
cppcheck
1945
enum_tx_isolation Session::getTxIsolation() const
2239.1.9 by Olaf van der Spek
Refactor includes
1946
{
1947
  return (enum_tx_isolation)variables.tx_isolation;
1948
}
1949
2240.5.3 by Olaf van der Spek
Session::properties
1950
drizzled::util::Storable* Session::getProperty0(const std::string& arg)
1951
{
2280.1.4 by Olaf van der Spek
Refactor
1952
  return impl_->properties[arg];
2240.5.3 by Olaf van der Spek
Session::properties
1953
}
1954
1955
void Session::setProperty0(const std::string& arg, drizzled::util::Storable* value)
1956
{
2280.1.4 by Olaf van der Spek
Refactor
1957
  // assert(not _properties.count(arg));
1958
  impl_->properties[arg]= value;
2240.5.3 by Olaf van der Spek
Session::properties
1959
}
1960
2241.3.12 by Olaf van der Spek
Refactor Session
1961
plugin::EventObserverList* Session::getSchemaObservers(const std::string &db_name)
1962
{
1963
  if (impl_c::schema_event_observers_t::mapped_type* i= find_ptr(impl_->schema_event_observers, db_name))
1964
    return *i;
1965
  return NULL;
1966
}
1967
1968
plugin::EventObserverList* Session::setSchemaObservers(const std::string &db_name, plugin::EventObserverList* observers)
1969
{
1970
  impl_->schema_event_observers.erase(db_name);
1971
  if (observers)
1972
    impl_->schema_event_observers[db_name] = observers;
1973
	return observers;
1974
}
2241.3.3 by Olaf van der Spek
Refactor Session::transaction (partial)
1975
2269.1.7 by Olaf van der Spek
Use util::string::ptr
1976
util::string::ptr Session::schema() const
1977
{
2275.2.6 by Olaf van der Spek
Refactor
1978
  return impl_->schema;
2269.1.7 by Olaf van der Spek
Use util::string::ptr
1979
}
1980
2269.1.8 by Olaf van der Spek
Refactor Session
1981
void Session::resetQueryString()
1982
{
1983
  query.reset();
1984
  impl_->state.reset();
1985
}
1986
1987
const boost::shared_ptr<session::State>& Session::state()
1988
{
1989
  return impl_->state;
1990
}
1991
2240.5.12 by Olaf van der Spek
Refactor
1992
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
1993
{
2240.5.12 by Olaf van der Spek
Refactor
1994
  static const std::string NONE= "NONE";
1995
  static const std::string GOT_GLOBAL_READ_LOCK= "HAS GLOBAL READ LOCK";
1996
  static const std::string MADE_GLOBAL_READ_LOCK_BLOCK_COMMIT= "HAS GLOBAL READ LOCK WITH BLOCKING COMMIT";
1997
1998
  switch (type) 
1999
  {
1948.2.6 by Brian Aker
Added function global_read_lock(), this way a session can know if it has
2000
    default:
2001
    case Session::NONE:
2002
      return NONE;
2003
    case Session::GOT_GLOBAL_READ_LOCK:
2004
      return GOT_GLOBAL_READ_LOCK;
2005
    case Session::MADE_GLOBAL_READ_LOCK_BLOCK_COMMIT:
2006
      return MADE_GLOBAL_READ_LOCK_BLOCK_COMMIT;
2007
  }
2008
}
2009
2240.5.12 by Olaf van der Spek
Refactor
2010
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
2011
{
2241.2.16 by Olaf van der Spek
Avoid compiler bug
2012
  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
2013
}
2014
1280.1.10 by Monty Taylor
Put everything in drizzled into drizzled namespace.
2015
} /* namespace drizzled */