ha_connect.cc 112 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
/* Copyright (C) Olivier Bertrand 2004 - 2013

  This program is free software; you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation; version 2 of the License.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with this program; if not, write to the Free Software
  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */

/**
  @file ha_connect.cc

  @brief
  The ha_connect engine is a stubbed storage engine that enables to create tables
Alexander Barkov's avatar
Alexander Barkov committed
21 22 23 24
  based on external data. Principally they are based on plain files of many
  different types, but also on collections of such files, collection of tables,
  ODBC tables retrieving data from other DBMS having an ODBC server, and even
  virtual tables.
25 26 27 28

  @details
  ha_connect will let you create/open/delete tables, the created table can be
  done specifying an already existing file, the drop table command will just
Alexander Barkov's avatar
Alexander Barkov committed
29
  suppress the table definition but not the eventual data file.
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
  Indexes are not yet supported but data can be inserted, updated or deleted.

  You can enable the CONNECT storage engine in your build by doing the
  following during your build process:<br> ./configure
  --with-connect-storage-engine (not implemented yet)

  You can install the CONNECT handler as all other storage handlers.

  Once this is done, MySQL will let you create tables with:<br>
  CREATE TABLE <table name> (...) ENGINE=CONNECT;

  The example storage engine does not use table locks. It
  implements an example "SHARE" that is inserted into a hash by table
  name. This is not used yet.

  Please read the object definition in ha_connect.h before reading the rest
  of this file.

  @note
  This MariaDB CONNECT handler is currently an adaptation of the XDB handler
  that was written for MySQL version 4.1.2-alpha. Its overall design should
  be enhanced in the future to meet MariaDB requirements.

  @note
  It was written also from the Brian's ha_example handler and contains parts
  of it that are there but not currently used, such as table variables.

  @note
  When you create an CONNECT table, the MySQL Server creates a table .frm
  (format) file in the database directory, using the table name as the file
  name as is customary with MySQL. No other files are created. To get an idea
  of what occurs, here is an example select that would do a scan of an entire
  table:

  @code
Alexander Barkov's avatar
Alexander Barkov committed
65
  ha-connect::open
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128
  ha_connect::store_lock
  ha_connect::external_lock
  ha_connect::info
  ha_connect::rnd_init
  ha_connect::extra
  ENUM HA_EXTRA_CACHE        Cache record in HA_rrnd()
  ha_connect::rnd_next
  ha_connect::rnd_next
  ha_connect::rnd_next
  ha_connect::rnd_next
  ha_connect::rnd_next
  ha_connect::rnd_next
  ha_connect::rnd_next
  ha_connect::rnd_next
  ha_connect::rnd_next
  ha_connect::extra
  ENUM HA_EXTRA_NO_CACHE     End caching of records (def)
  ha_connect::external_lock
  ha_connect::extra
  ENUM HA_EXTRA_RESET        Reset database to after open
  @endcode

  Here you see that the connect storage engine has 9 rows called before
  rnd_next signals that it has reached the end of its data. Calls to
  ha_connect::extra() are hints as to what will be occuring to the request.

  Happy use!<br>
    -Olivier
*/

#ifdef USE_PRAGMA_IMPLEMENTATION
#pragma implementation        // gcc: Class implementation
#endif

#define MYSQL_SERVER 1
#define DONT_DEFINE_VOID
//#include "sql_partition.h"
#include "sql_class.h"
#include "create_options.h"
#include "mysql_com.h"
#include "field.h"
#undef  OFFSET

#define NOPARSE
#if defined(UNIX)
#include "osutil.h"
#endif   // UNIX
#include "global.h"
#include "plgdbsem.h"
#include "reldef.h"
#include "tabcol.h"
#include "xindex.h"
#include "connect.h"
#include "user_connect.h"
#include "ha_connect.h"
#include "mycat.h"

#define PLGINI      "plugdb.ini"       /* Configuration settings file  */
#define PLGXINI     "plgcnx.ini"       /* Configuration settings file  */
#define my_strupr(p) my_caseup_str(default_charset_info, (p));
#define my_strlwr(p) my_casedn_str(default_charset_info, (p));
#define my_stricmp(a, b) my_strcasecmp(default_charset_info, (a), (b))

129 130 131
#if defined (WIN32)
typedef struct _WMIutil *PWMIUT;       /* Used to call WMIColumns      */
#endif
132 133 134 135
/****************************************************************************/
/*  CONNECT functions called externally.                                    */
/****************************************************************************/
bool  CntCheckDB(PGLOBAL g, PHC handler, const char *pathname);
Alexander Barkov's avatar
Alexander Barkov committed
136
PTDB  CntGetTDB(PGLOBAL g, const char *name, MODE xmod, PHC);
137 138 139 140 141 142 143 144 145 146 147
bool  CntOpenTable(PGLOBAL g, PTDB tdbp, MODE, char *, char *, bool, PHC);
bool  CntRewindTable(PGLOBAL g, PTDB tdbp);
int   CntCloseTable(PGLOBAL g, PTDB tdbp);
int   CntIndexInit(PGLOBAL g, PTDB tdbp, int id);
RCODE CntReadNext(PGLOBAL g, PTDB tdbp);
RCODE CntIndexRead(PGLOBAL g, PTDB, OPVAL op, const void *k, int n);
RCODE CntWriteRow(PGLOBAL g, PTDB tdbp);
RCODE CntUpdateRow(PGLOBAL g, PTDB tdbp);
RCODE CntDeleteRow(PGLOBAL g, PTDB tdbp, bool all);
bool  CntInfo(PGLOBAL g, PTDB tdbp, PXF info);
int   CntIndexRange(PGLOBAL g, PTDB ptdb, const uchar* *key, uint *len,
Alexander Barkov's avatar
Alexander Barkov committed
148
                    bool *incl, key_part_map *kmap);
149 150 151 152 153 154 155 156 157
#if defined(XML_SUPPORT) && !defined(NOXML2)
void XmlInitParserLib(void);
void XmlCleanupParserLib(void);
#endif   // XML_SUPPORT  &&         !NOXML2)

/****************************************************************************/
/*  Functions called externally by pre_parser.                              */
/****************************************************************************/
PQRYRES DBFColumns(PGLOBAL g, char *fn, BOOL info);
158
PQRYRES CSVColumns(PGLOBAL g, char *fn, char sep, char q, int hdr, int mxr);
Alexander Barkov's avatar
Alexander Barkov committed
159 160 161 162
#if defined(ODBC_SUPPORT)
PQRYRES MyODBCCols(PGLOBAL g, char *tab, char *dsn);
#endif   // ODBC_SUPPORT
#if defined(MYSQL_SUPPORT)
163 164
PQRYRES MyColumns(PGLOBAL g, char *host,  char *db, char *user, char *pwd,
                  char *table, char *colpat, int port, bool key);
Alexander Barkov's avatar
Alexander Barkov committed
165
#endif   // MYSQL_SUPPORT
166
enum enum_field_types PLGtoMYSQL(int type, bool gdf);
167 168 169 170
#if defined(WIN32)
PQRYRES WMIColumns(PGLOBAL g, char *nsp, char *classname, PWMIUT wp= NULL);
#endif   // WIN32
char GetTypeID(char *type);
171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186
bool check_string_char_length(LEX_STRING *str, const char *err_msg,
                              uint max_char_length, CHARSET_INFO *cs,
                              bool no_error);

/***********************************************************************/
/*  DB static variables.                                               */
/***********************************************************************/
extern "C" char  plgxini[];
extern "C" char  plgini[];
extern "C" char  nmfile[];
extern "C" char  pdebug[];

extern "C" {
       char  version[]= "Version 1.00.0005 October 03, 2012";

#if defined(XMSG)
Alexander Barkov's avatar
Alexander Barkov committed
187
       char  msglang[];            // Default message language
188
#endif
Alexander Barkov's avatar
Alexander Barkov committed
189
       int  trace= 0;              // The general trace value
190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242
} // extern "C"

/****************************************************************************/
/*  Initialize the ha_connect static members.                               */
/****************************************************************************/
char  connectini[_MAX_PATH]= "connect.ini";
int   xtrace= 0;
ulong ha_connect::num= 0;
//int  DTVAL::Shift= 0;

static handler *connect_create_handler(handlerton *hton,
                                   TABLE_SHARE *table,
                                   MEM_ROOT *mem_root);

handlerton *connect_hton;

/* Variables for connect share methods */

/*
   Hash used to track the number of open tables; variable for connect share
   methods
*/
static HASH connect_open_tables;

/* The mutex used to init the hash; variable for example share methods */
mysql_mutex_t connect_mutex;


/**
  structure for CREATE TABLE options (table options)

  These can be specified in the CREATE TABLE:
  CREATE TABLE ( ... ) {...here...}
*/
struct ha_table_option_struct {
  const char *type;
  const char *filename;
  const char *optname;
  const char *tabname;
  const char *tablist;
  const char *dbname;
  const char *separator;
//const char *connect;
  const char *qchar;
  const char *module;
  const char *subtype;
  const char *oplist;
  int lrecl;
  int elements;
//int estimate;
  int multiple;
  int header;
  int quoted;
Alexander Barkov's avatar
Alexander Barkov committed
243 244 245 246 247 248
  int ending;
  int compressed;
  bool mapped;
  bool huge;
  bool split;
  bool readonly;
249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271
  };

#if defined(MARIADB)
ha_create_table_option connect_table_option_list[]=
{
  // These option are for stand alone Connect tables
  HA_TOPTION_STRING("TABLE_TYPE", type),
  HA_TOPTION_STRING("FILE_NAME", filename),
  HA_TOPTION_STRING("XFILE_NAME", optname),
//HA_TOPTION_STRING("CONNECT_STRING", connect),
  HA_TOPTION_STRING("TABNAME", tabname),
  HA_TOPTION_STRING("TABLE_LIST", tablist),
  HA_TOPTION_STRING("DB_NAME", dbname),
  HA_TOPTION_STRING("SEP_CHAR", separator),
  HA_TOPTION_STRING("QCHAR", qchar),
  HA_TOPTION_STRING("MODULE", module),
  HA_TOPTION_STRING("SUBTYPE", subtype),
  HA_TOPTION_STRING("OPTION_LIST", oplist),
  HA_TOPTION_NUMBER("LRECL", lrecl, 0, 0, INT_MAX32, 1),
  HA_TOPTION_NUMBER("BLOCK_SIZE", elements, 0, 0, INT_MAX32, 1),
//HA_TOPTION_NUMBER("ESTIMATE", estimate, 0, 0, INT_MAX32, 1),
  HA_TOPTION_NUMBER("MULTIPLE", multiple, 0, 0, 2, 1),
  HA_TOPTION_NUMBER("HEADER", header, 0, 0, 3, 1),
Alexander Barkov's avatar
Alexander Barkov committed
272 273 274
  HA_TOPTION_NUMBER("QUOTED", quoted, -1, 0, 3, 1),
  HA_TOPTION_NUMBER("ENDING", ending, -1, 0, INT_MAX32, 1),
  HA_TOPTION_NUMBER("COMPRESS", compressed, 0, 0, 2, 1),
275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293
//HA_TOPTION_BOOL("COMPRESS", compressed, 0),
  HA_TOPTION_BOOL("MAPPED", mapped, 0),
  HA_TOPTION_BOOL("HUGE", huge, 0),
  HA_TOPTION_BOOL("SPLIT", split, 0),
  HA_TOPTION_BOOL("READONLY", readonly, 0),
  HA_TOPTION_END
};
#endif   // MARIADB


/**
  structure for CREATE TABLE options (field options)

  These can be specified in the CREATE TABLE per field:
  CREATE TABLE ( field ... {...here...}, ... )
*/
struct ha_field_option_struct
{
  int offset;
Alexander Barkov's avatar
Alexander Barkov committed
294 295 296
  int freq;      // Not used by this version
  int opt;       // Not used by this version
  int buflen;
297 298
  const char *dateformat;
  const char *fieldformat;
Alexander Barkov's avatar
Alexander Barkov committed
299
  char *special;
300 301 302 303 304 305
};

#if defined(MARIADB)
ha_create_table_option connect_field_option_list[]=
{
  HA_FOPTION_NUMBER("FLAG", offset, -1, 0, INT_MAX32, 1),
Alexander Barkov's avatar
Alexander Barkov committed
306 307
  HA_FOPTION_NUMBER("FREQUENCY", freq, 0, 0, INT_MAX32, 1), // not used
  HA_FOPTION_NUMBER("OPT_VALUE", opt, 0, 0, 2, 1),  // used for indexing
308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341
  HA_FOPTION_NUMBER("BUF_LENGTH", buflen, 0, 0, INT_MAX32, 1),
  HA_FOPTION_STRING("DATE_FORMAT", dateformat),
  HA_FOPTION_STRING("FIELD_FORMAT", fieldformat),
  HA_FOPTION_STRING("SPECIAL", special),
  HA_FOPTION_END
};
#endif   // MARIADB


/**
  @brief
  Function we use in the creation of our hash to get key.
*/
static uchar* connect_get_key(CONNECT_SHARE *share, size_t *length,
                          my_bool not_used __attribute__((unused)))
{
  *length=share->table_name_length;
  return (uchar*) share->table_name;
}

#ifdef HAVE_PSI_INTERFACE
static PSI_mutex_key ex_key_mutex_connect, ex_key_mutex_CONNECT_SHARE_mutex;

static PSI_mutex_info all_connect_mutexes[]=
{
  { &ex_key_mutex_connect, "connect", PSI_FLAG_GLOBAL},
  { &ex_key_mutex_CONNECT_SHARE_mutex, "CONNECT_SHARE::mutex", 0}
};

/***********************************************************************/
/*  Push G->Message as a MySQL warning.                                */
/***********************************************************************/
bool PushWarning(PGLOBAL g, PTDBASE tdbp)
  {
Alexander Barkov's avatar
Alexander Barkov committed
342 343 344
  PHC    phc;
  THD   *thd;
  MYCAT *cat= (MYCAT*)tdbp->GetDef()->GetCat();
345

Alexander Barkov's avatar
Alexander Barkov committed
346 347 348
  if (!cat || !(phc= cat->GetHandler()) || !phc->GetTable() ||
      !(thd= (phc->GetTable())->in_use))
    return true;
349

Alexander Barkov's avatar
Alexander Barkov committed
350 351
  push_warning(thd, MYSQL_ERROR::WARN_LEVEL_WARN, 0, g->Message);
  return false;
352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405
  } // end of PushWarning

static void init_connect_psi_keys()
{
  const char* category= "connect";
  int count;

  if (PSI_server == NULL)
    return;

  count= array_elements(all_connect_mutexes);
  PSI_server->register_mutex(category, all_connect_mutexes, count);
}
#endif

static int connect_init_func(void *p)
{
  DBUG_ENTER("connect_init_func");

#ifdef HAVE_PSI_INTERFACE
  init_connect_psi_keys();
#endif

  connect_hton= (handlerton *)p;
  mysql_mutex_init(ex_key_mutex_connect, &connect_mutex, MY_MUTEX_INIT_FAST);
//VOID(mysql_mutex_init(&connect_mutex, MY_MUTEX_INIT_FAST));
  (void) my_hash_init(&connect_open_tables, system_charset_info, 32, 0, 0,
                   (my_hash_get_key) connect_get_key, 0, 0);

//connect_hton->name=    "CONNECT";
  connect_hton->state=   SHOW_OPTION_YES;
//connect_hton->comment= "CONNECT handler";
  connect_hton->create=  connect_create_handler;
  connect_hton->flags=   HTON_TEMPORARY_NOT_SUPPORTED | HTON_NO_PARTITION;
#if defined(MARIADB)
  connect_hton->db_type= DB_TYPE_AUTOASSIGN;
  connect_hton->table_options= connect_table_option_list;
  connect_hton->field_options= connect_field_option_list;
#else   // !MARIADB
//connect_hton->system_database= connect_system_database;
//connect_hton->is_supported_system_table= connect_is_supported_system_table;
#endif  // !MARIADB

  if (xtrace)
    printf("connect_init: hton=%p\n", p);

  DTVAL::SetTimeShift();      // Initialize time zone shift once for all
  DBUG_RETURN(0);
}


static int connect_done_func(void *p)
{
  int error= 0;
406
  PCONNECT pc, pn;
407 408 409 410 411
  DBUG_ENTER("connect_done_func");

  if (connect_open_tables.records)
    error= 1;

Alexander Barkov's avatar
Alexander Barkov committed
412 413 414
  for (pc= user_connect::to_users; pc; pc= pn) {
    if (pc->g)
      PlugCleanup(pc->g, true);
415

416 417
    pn= pc->next;
    delete pc;
Alexander Barkov's avatar
Alexander Barkov committed
418
    } // endfor pc
419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461

  my_hash_free(&connect_open_tables);
  mysql_mutex_destroy(&connect_mutex);

  DBUG_RETURN(error);
}


/**
  @brief
  Example of simple lock controls. The "share" it creates is a
  structure we will pass to each example handler. Do you have to have
  one of these? Well, you have pieces that are used for locking, and
  they are needed to function.
*/

static CONNECT_SHARE *get_share(const char *table_name, TABLE *table)
{
  CONNECT_SHARE *share;
  uint length;
  char *tmp_name;

  mysql_mutex_lock(&connect_mutex);
  length=(uint) strlen(table_name);

  if (!(share=(CONNECT_SHARE*)my_hash_search(&connect_open_tables,
                                      (uchar*) table_name, length))) {
    if (!(share=(CONNECT_SHARE *)my_multi_malloc(MYF(MY_WME | MY_ZEROFILL),
                &share, sizeof(*share), &tmp_name, length+1, NullS))) {
      mysql_mutex_unlock(&connect_mutex);
      return NULL;
      } // endif share

    share->use_count=0;
    share->table_name_length=length;
    share->table_name=tmp_name;
    strmov(share->table_name, table_name);

    if (my_hash_insert(&connect_open_tables, (uchar*) share))
      goto error;

    thr_lock_init(&share->lock);
    mysql_mutex_init(ex_key_mutex_CONNECT_SHARE_mutex,
Alexander Barkov's avatar
Alexander Barkov committed
462
                     &share->mutex, MY_MUTEX_INIT_FAST);
463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490
    } // endif share

  share->use_count++;
  mysql_mutex_unlock(&connect_mutex);
  return share;

error:
  mysql_mutex_destroy(&share->mutex);
  my_free(share);
  return NULL;
}


/**
  @brief
  Free lock controls. We call this whenever we close a table. If the table had
  the last reference to the share, then we free memory associated with it.
*/

static int free_share(CONNECT_SHARE *share)
{
  mysql_mutex_lock(&connect_mutex);

  if (!--share->use_count) {
    my_hash_delete(&connect_open_tables, (uchar*) share);
    thr_lock_delete(&share->lock);
    mysql_mutex_destroy(&share->mutex);
#if !defined(MARIADB)
Alexander Barkov's avatar
Alexander Barkov committed
491 492
    my_free(share->table_options);
    my_free(share->field_options);
493 494 495 496 497 498 499 500 501 502 503 504
#endif   // !MARIADB
    my_free(share);
    } // endif share

  mysql_mutex_unlock(&connect_mutex);
  return 0;
}

static handler* connect_create_handler(handlerton *hton,
                                   TABLE_SHARE *table,
                                   MEM_ROOT *mem_root)
{
Alexander Barkov's avatar
Alexander Barkov committed
505
  handler *h= new (mem_root) ha_connect(hton, table);
506 507

  if (xtrace)
Alexander Barkov's avatar
Alexander Barkov committed
508 509
    printf("New CONNECT %p, table: %s\n",
                         h, table ? table->table_name.str : "<null>");
510

Alexander Barkov's avatar
Alexander Barkov committed
511
  return h;
512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531
} // end of connect_create_handler

/****************************************************************************/
/*  ha_connect constructor.                                                 */
/****************************************************************************/
ha_connect::ha_connect(handlerton *hton, TABLE_SHARE *table_arg)
       :handler(hton, table_arg)
{
  hnum= ++num;
  xp= NULL;         // Tested in next call
  xp= (table) ? GetUser(table->in_use) : NULL;
  tdbp= NULL;
  sdval= NULL;
  xmod= MODE_ANY;
  istable= false;
//*tname= '\0';
  bzero((char*) &xinfo, sizeof(XINFO));
  valid_info= false;
  valid_query_id= 0;
  creat_query_id= (table && table->in_use) ? table->in_use->query_id : 0;
Alexander Barkov's avatar
Alexander Barkov committed
532
  stop= false;
533
//hascond= false;
Alexander Barkov's avatar
Alexander Barkov committed
534
  indexing= -1;
535
  data_file_name= NULL;
Alexander Barkov's avatar
Alexander Barkov committed
536
  index_file_name= NULL;
537 538
  enable_activate_all_index= 0;
  int_table_flags= (HA_NO_TRANSACTIONS | HA_NO_PREFIX_CHAR_KEYS);
Alexander Barkov's avatar
Alexander Barkov committed
539
  ref_length= sizeof(int);
540
#if !defined(MARIADB)
Alexander Barkov's avatar
Alexander Barkov committed
541 542 543
  share= NULL;
  table_options= NULL;
  field_options= NULL;
544
#endif   // !MARIADB
Alexander Barkov's avatar
Alexander Barkov committed
545
  tshp= NULL;
546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573
} // end of ha_connect constructor


/****************************************************************************/
/*  ha_connect destructor.                                                  */
/****************************************************************************/
ha_connect::~ha_connect(void)
{
  if (xp) {
    PCONNECT p;

    xp->count--;

    for (p= user_connect::to_users; p; p= p->next)
      if (p == xp)
        break;

    if (p && !p->count) {
      if (p->next)
        p->next->previous= p->previous;

      if (p->previous)
        p->previous->next= p->next;
      else
        user_connect::to_users= p->next;

      } // endif p

Alexander Barkov's avatar
Alexander Barkov committed
574 575
    if (!xp->count) {
      PlugCleanup(xp->g, true);
576
      delete xp;
Alexander Barkov's avatar
Alexander Barkov committed
577
      } // endif count
578 579 580 581

    } // endif xp

#if !defined(MARIADB)
Alexander Barkov's avatar
Alexander Barkov committed
582 583
  my_free(table_options);
  my_free(field_options);
584 585 586 587 588 589 590 591 592 593 594
#endif   // !MARIADB
} // end of ha_connect destructor


/****************************************************************************/
/*  Get a pointer to the user of this handler.                              */
/****************************************************************************/
PCONNECT ha_connect::GetUser(THD *thd)
{
  const char *dbn= NULL;

Alexander Barkov's avatar
Alexander Barkov committed
595
  if (!thd)
596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632
    return NULL;

  if (xp && thd == xp->thdp)
    return xp;

  for (xp= user_connect::to_users; xp; xp= xp->next)
    if (thd == xp->thdp)
      break;

  if (!xp) {
    xp= new user_connect(thd, dbn);

    if (xp->user_init(this)) {
      delete xp;
      xp= NULL;
      } // endif user_init

  } else
    xp->count++;

  return xp;
} // end of GetUser


/****************************************************************************/
/*  Get the global pointer of the user of this handler.                     */
/****************************************************************************/
PGLOBAL ha_connect::GetPlug(THD *thd)
{
  PCONNECT lxp= GetUser(thd);
  return (lxp) ? lxp->g : NULL;
} // end of GetPlug


/****************************************************************************/
/*  Return the value of an option specified in the option list.             */
/****************************************************************************/
633
char *ha_connect::GetListOption(char *opname, const char *oplist, char *def)
634 635 636
{
  char key[16], val[256];
  char *pk, *pv, *pn;
637
  char *opval= def;
638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685
  int n;

  for (pk= (char*)oplist; ; pk= ++pn) {
    pn= strchr(pk, ',');
    pv= strchr(pk, '=');

    if (pv && (!pn || pv < pn)) {
      n= pv - pk;
      memcpy(key, pk, n);
      key[n]= 0;
      pv++;

      if (pn) {
        n= pn - pv;
        memcpy(val, pv, n);
        val[n]= 0;
      } else
        strcpy(val, pv);

    } else {
      if (pn) {
        n= pn - pk;
        memcpy(key, pk, n);
        key[n]= 0;
      } else
        strcpy(key, pk);

      val[0]= 0;
    } // endif pv

    if (!stricmp(opname, key)) {
      opval= (char*)PlugSubAlloc(xp->g, NULL, strlen(val) + 1);
      strcpy(opval, val);
      break;
    } else if (!pn)
      break;

    } // endfor pk

  return opval;
} // end of GetListOption

/****************************************************************************/
/*  Return the table option structure.                                      */
/****************************************************************************/
PTOS ha_connect::GetTableOptionStruct(TABLE *tab)
{
#if defined(MARIADB)
Alexander Barkov's avatar
Alexander Barkov committed
686
  return (tshp) ? tshp->option_struct : tab->s->option_struct;
687
#else   // !MARIADB
Alexander Barkov's avatar
Alexander Barkov committed
688 689 690 691
  if (share && share->table_options)
    return share->table_options;
  else if (table_options)
    return table_options;
692 693

  char  *pk, *pv, *pn, *val;
Alexander Barkov's avatar
Alexander Barkov committed
694
  size_t len= sizeof(ha_table_option_struct) + tab->s->comment.length + 1;
695 696
  PTOS   top= (PTOS)my_malloc(len, MYF(MY_FAE | MY_ZEROFILL));

Alexander Barkov's avatar
Alexander Barkov committed
697 698 699 700
  top->quoted= -1;   // Default value
  top->ending= -1;   // Default value
  pk= (char *)top + sizeof(ha_table_option_struct);
  memcpy(pk, tab->s->comment.str, tab->s->comment.length);
701 702 703 704 705 706 707

  for (; pk; pk= ++pn) {
    pn= strchr(pk, ',');
    pv= strchr(pk, '=');

    if (pn) *pn= 0;

Alexander Barkov's avatar
Alexander Barkov committed
708
    if (pv) *pv= 0;
709

Alexander Barkov's avatar
Alexander Barkov committed
710
    val= (pv && (!pn || pv < pn)) ? pv + 1 : "";
711 712 713 714

    if (!stricmp(pk, "type") || !stricmp(pk, "Table_Type")) {
      top->type= val;
    } else if (!stricmp(pk, "fn") || !stricmp(pk, "filename")
Alexander Barkov's avatar
Alexander Barkov committed
715
                                  || !stricmp(pk, "File_Name")) {
716 717
      top->filename= val;
    } else if (!stricmp(pk, "optfn") || !stricmp(pk, "optname")
Alexander Barkov's avatar
Alexander Barkov committed
718
                                     || !stricmp(pk, "Xfile_Name")) {
719
      top->optname= val;
Alexander Barkov's avatar
Alexander Barkov committed
720
    } else if (!stricmp(pk, "name") || !stricmp(pk, "tabname")) {
721
      top->tabname= val;
Alexander Barkov's avatar
Alexander Barkov committed
722 723
    } else if (!stricmp(pk, "tablist") || !stricmp(pk, "tablelist")
                                       || !stricmp(pk, "Table_list")) {
724 725
      top->tablist= val;
    } else if (!stricmp(pk, "sep") || !stricmp(pk, "separator")
Alexander Barkov's avatar
Alexander Barkov committed
726
                                   || !stricmp(pk, "Sep_Char")) {
727 728
      top->separator= val;
    } else if (!stricmp(pk, "db") || !stricmp(pk, "database")
Alexander Barkov's avatar
Alexander Barkov committed
729
                                  || !stricmp(pk, "DB_Name")) {
730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758
      top->dbname= val;
    } else if (!stricmp(pk, "qchar")) {
      top->qchar= val;
    } else if (!stricmp(pk, "module")) {
      top->module= val;
    } else if (!stricmp(pk, "subtype")) {
      top->subtype= val;
    } else if (!stricmp(pk, "lrecl")) {
      top->lrecl= atoi(val);
    } else if (!stricmp(pk, "elements")) {
      top->elements= atoi(val);
    } else if (!stricmp(pk, "multiple")) {
      top->multiple= atoi(val);
    } else if (!stricmp(pk, "header")) {
      top->header= atoi(val);
    } else if (!stricmp(pk, "quoted")) {
      top->quoted= atoi(val);
    } else if (!stricmp(pk, "ending")) {
      top->ending= atoi(val);
    } else if (!stricmp(pk, "compressed")) {
      top->compressed= atoi(val);
    } else if (!stricmp(pk, "mapped")) {
      top->mapped= (!*val || *val == 'y' || *val == 'Y' || atoi(val) != 0);
    } else if (!stricmp(pk, "huge")) {
      top->huge= (!*val || *val == 'y' || *val == 'Y' || atoi(val) != 0);
    } else if (!stricmp(pk, "split")) {
      top->split= (!*val || *val == 'y' || *val == 'Y' || atoi(val) != 0);
    } else if (!stricmp(pk, "readonly") || !stricmp(pk, "protected")) {
      top->readonly= (!*val || *val == 'y' || *val == 'Y' || atoi(val) != 0);
Alexander Barkov's avatar
Alexander Barkov committed
759
    } // endif's
760

Alexander Barkov's avatar
Alexander Barkov committed
761 762
    if (!pn)
      break;
763 764 765

    } // endfor pk

Alexander Barkov's avatar
Alexander Barkov committed
766 767
  // This to get all other options
  top->oplist= tab->s->comment.str;
768

Alexander Barkov's avatar
Alexander Barkov committed
769 770 771 772
  if (share)
    share->table_options= top;
  else
    table_options= top;
773 774 775 776 777 778 779 780 781 782 783 784 785

  return top;
#endif  // !MARIADB
} // end of GetTableOptionStruct

/****************************************************************************/
/*  Return the value of a string option or NULL if not specified.           */
/****************************************************************************/
char *ha_connect::GetStringOption(char *opname, char *sdef)
{
  char *opval= NULL;
  PTOS  options= GetTableOptionStruct(table);

Alexander Barkov's avatar
Alexander Barkov committed
786 787
  if (!options)
    ;
788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803
  else if (!stricmp(opname, "Type"))
    opval= (char*)options->type;
  else if (!stricmp(opname, "Filename"))
    opval= (char*)options->filename;
  else if (!stricmp(opname, "Optname"))
    opval= (char*)options->optname;
  else if (!stricmp(opname, "Tabname"))
    opval= (char*)options->tabname;
  else if (!stricmp(opname, "Tablist"))
    opval= (char*)options->tablist;
  else if (!stricmp(opname, "Database"))
    opval= (char*)options->dbname;
  else if (!stricmp(opname, "Separator"))
    opval= (char*)options->separator;
  else if (!stricmp(opname, "Connect"))
//  opval= (char*)options->connect;
Alexander Barkov's avatar
Alexander Barkov committed
804
    opval= table->s->connect_string.str;
805 806 807 808 809 810 811 812 813 814
  else if (!stricmp(opname, "Qchar"))
    opval= (char*)options->qchar;
  else if (!stricmp(opname, "Module"))
    opval= (char*)options->module;
  else if (!stricmp(opname, "Subtype"))
    opval= (char*)options->subtype;

  if (!opval && options->oplist)
    opval= GetListOption(opname, options->oplist);

Alexander Barkov's avatar
Alexander Barkov committed
815 816 817 818 819
  if (!opval) {
    if (sdef && !strcmp(sdef, "*")) {
      // Return the handler default value
      if (!stricmp(opname, "Database"))
        opval= (char*)GetDBName(NULL);    // Current database
820

Alexander Barkov's avatar
Alexander Barkov committed
821 822
    } else
      opval= sdef;                        // Caller default
823

Alexander Barkov's avatar
Alexander Barkov committed
824
    } // endif !opval
825 826 827 828 829 830 831 832 833 834 835 836 837

  return opval;
} // end of GetStringOption

/****************************************************************************/
/*  Return the value of a Boolean option or bdef if not specified.          */
/****************************************************************************/
bool ha_connect::GetBooleanOption(char *opname, bool bdef)
{
  bool  opval= bdef;
  char *pv;
  PTOS  options= GetTableOptionStruct(table);

Alexander Barkov's avatar
Alexander Barkov committed
838 839
  if (!options)
    ;
840
  else if (!stricmp(opname, "Mapped"))
Alexander Barkov's avatar
Alexander Barkov committed
841
    opval= options->mapped;
842
  else if (!stricmp(opname, "Huge"))
Alexander Barkov's avatar
Alexander Barkov committed
843
    opval= options->huge;
844
//else if (!stricmp(opname, "Compressed"))
Alexander Barkov's avatar
Alexander Barkov committed
845
//  opval= options->compressed;
846
  else if (!stricmp(opname, "Split"))
Alexander Barkov's avatar
Alexander Barkov committed
847
    opval= options->split;
848
  else if (!stricmp(opname, "Readonly"))
Alexander Barkov's avatar
Alexander Barkov committed
849
    opval= options->readonly;
850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865
  else if (options->oplist)
    if ((pv= GetListOption(opname, options->oplist)))
      opval= (!*pv || *pv == 'y' || *pv == 'Y' || atoi(pv) != 0);

  return opval;
} // end of GetBooleanOption

/****************************************************************************/
/*  Return the value of an integer option or NO_IVAL if not specified.      */
/****************************************************************************/
int ha_connect::GetIntegerOption(char *opname)
{
  int   opval= NO_IVAL;
  char *pv;
  PTOS  options= GetTableOptionStruct(table);

Alexander Barkov's avatar
Alexander Barkov committed
866 867
  if (!options)
    ;
868 869 870 871 872 873
  else if (!stricmp(opname, "Lrecl"))
    opval= options->lrecl;
  else if (!stricmp(opname, "Elements"))
    opval= options->elements;
  else if (!stricmp(opname, "Estimate"))
//  opval= options->estimate;
Alexander Barkov's avatar
Alexander Barkov committed
874
    opval= (int)table->s->max_rows;
875
  else if (!stricmp(opname, "Avglen"))
Alexander Barkov's avatar
Alexander Barkov committed
876
    opval= (int)table->s->avg_row_length;
877 878 879 880 881 882 883 884
  else if (!stricmp(opname, "Multiple"))
    opval= options->multiple;
  else if (!stricmp(opname, "Header"))
    opval= options->header;
  else if (!stricmp(opname, "Quoted"))
    opval= options->quoted;
  else if (!stricmp(opname, "Ending"))
    opval= options->ending;
Alexander Barkov's avatar
Alexander Barkov committed
885 886
  else if (!stricmp(opname, "Compressed"))
    opval= (options->compressed);
887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902

  if (opval == NO_IVAL && options->oplist)
    if ((pv= GetListOption(opname, options->oplist)))
      opval= atoi(pv);

  return opval;
} // end of GetIntegerOption

/****************************************************************************/
/*  Set the value of the opname option (does not work for oplist options)   */
/*  Currently used only to set the Lrecl value.                             */
/****************************************************************************/
bool ha_connect::SetIntegerOption(char *opname, int n)
{
  PTOS options= GetTableOptionStruct(table);

Alexander Barkov's avatar
Alexander Barkov committed
903 904
  if (!options)
    return true;
905 906 907 908 909 910 911 912 913 914 915 916 917 918 919

  if (!stricmp(opname, "Lrecl"))
    options->lrecl= n;
  else if (!stricmp(opname, "Elements"))
    options->elements= n;
//else if (!stricmp(opname, "Estimate"))
//  options->estimate= n;
  else if (!stricmp(opname, "Multiple"))
    options->multiple= n;
  else if (!stricmp(opname, "Header"))
    options->header= n;
  else if (!stricmp(opname, "Quoted"))
    options->quoted= n;
  else if (!stricmp(opname, "Ending"))
    options->ending= n;
Alexander Barkov's avatar
Alexander Barkov committed
920 921 922 923
  else if (!stricmp(opname, "Compressed"))
    options->compressed= n;
  else
    return true;
924 925 926
//else if (options->oplist)
//  SetListOption(opname, options->oplist, n);

Alexander Barkov's avatar
Alexander Barkov committed
927
  return false;
928 929 930 931 932 933 934 935 936 937
} // end of SetIntegerOption

/****************************************************************************/
/*  Return a field option structure.                                        */
/****************************************************************************/
PFOS ha_connect::GetFieldOptionStruct(Field *fdp)
{
#if defined(MARIADB)
  return fdp->option_struct;
#else   // !MARIADB
Alexander Barkov's avatar
Alexander Barkov committed
938 939 940 941
  if (share && share->field_options)
    return &share->field_options[fdp->field_index];
  else if (field_options)
    return &field_options[fdp->field_index];
942 943

  char  *pc, *pk, *pv, *pn, *val;
Alexander Barkov's avatar
Alexander Barkov committed
944 945
  int    i, k, n= table->s->fields;
  size_t len= n + n * sizeof(ha_field_option_struct);
946 947
  PFOS   fp, fop;

Alexander Barkov's avatar
Alexander Barkov committed
948 949
  for (i= 0; i < n; i++)
    len+= table->s->field[i]->comment.length;
950 951

  fop= (PFOS)my_malloc(len, MYF(MY_FAE | MY_ZEROFILL));
Alexander Barkov's avatar
Alexander Barkov committed
952
  pc= (char*)fop + n * sizeof(ha_field_option_struct);
953

Alexander Barkov's avatar
Alexander Barkov committed
954 955 956
  for (i= k= 0; i < n;  i++) {
    fp= &fop[i];
    fp->offset= -1;    // Default value
957

Alexander Barkov's avatar
Alexander Barkov committed
958 959
    if (!table->s->field[i]->comment.length)
      continue;
960

Alexander Barkov's avatar
Alexander Barkov committed
961 962
    memcpy(pc, table->s->field[i]->comment.str,
               table->s->field[i]->comment.length);
963

Alexander Barkov's avatar
Alexander Barkov committed
964
    for (pk= pc; pk; pk= ++pn) {
965 966
      if ((pn= strchr(pk, ','))) *pn= 0;
      if ((pv= strchr(pk, '='))) *pv= 0;
Alexander Barkov's avatar
Alexander Barkov committed
967 968 969 970 971 972 973 974
      val= (pv && (!pn || pv < pn)) ? pv + 1 : "";

      if (!stricmp(pk, "datefmt") || !stricmp(pk, "date_format")) {
        fp->dateformat= val;
      } else if (!stricmp(pk, "fieldfmt") || !stricmp(pk, "field_format")) {
        fp->fieldformat= val;
      } else if (!stricmp(pk, "special")) {
        fp->special= val;
975 976 977 978 979 980 981 982
      } else if (!stricmp(pk, "offset") || !stricmp(pk, "flag")) {
        fp->offset= atoi(val);
      } else if (!stricmp(pk, "freq")) {
        fp->freq= atoi(val);
      } else if (!stricmp(pk, "opt")) {
        fp->opt= atoi(val);
      } else if (!stricmp(pk, "buflen")) {
        fp->buflen= atoi(val);
Alexander Barkov's avatar
Alexander Barkov committed
983
      } // endif's
984

Alexander Barkov's avatar
Alexander Barkov committed
985 986
      if (!pn)
        break;
987

Alexander Barkov's avatar
Alexander Barkov committed
988
      } // endfor pk
989

Alexander Barkov's avatar
Alexander Barkov committed
990 991
    pc+= table->s->field[i]->comment.length + 1;
    } // endfor i
992

Alexander Barkov's avatar
Alexander Barkov committed
993 994 995 996
  if (share)
    share->field_options= fop;
  else
    field_options= fop;
997 998 999 1000 1001 1002 1003 1004 1005 1006

  return &fop[fdp->field_index];
#endif  // !MARIADB
} // end of GetFildOptionStruct

/****************************************************************************/
/*  Returns the column description structure used to make the column.       */
/****************************************************************************/
void *ha_connect::GetColumnOption(void *field, PCOLINFO pcf)
{
Alexander Barkov's avatar
Alexander Barkov committed
1007 1008
  const char *cp;
  int     len;
1009 1010 1011 1012 1013 1014 1015 1016 1017
  ha_field_option_struct *fop;
  Field*  fp;
  Field* *fldp;

  // Double test to be on the safe side
  if (!table)
    return NULL;

  // Find the column to describe
Alexander Barkov's avatar
Alexander Barkov committed
1018
  if (field) {
1019
    fldp= (Field**)field;
Alexander Barkov's avatar
Alexander Barkov committed
1020 1021 1022
    fldp++;
  } else
    fldp= (tshp) ? tshp->field : table->field;
1023 1024 1025 1026 1027 1028

  if (!(fp= *fldp))
    return NULL;

  // Get the CONNECT field options structure
  fop= GetFieldOptionStruct(fp);
Alexander Barkov's avatar
Alexander Barkov committed
1029
  pcf->Flags= 0;
1030 1031

  // Now get column information
Alexander Barkov's avatar
Alexander Barkov committed
1032 1033 1034 1035 1036
  if (fop && fop->special) {
    pcf->Name= "*";
    return fldp;
  } else
    pcf->Name= (char*)fp->field_name;
1037

Alexander Barkov's avatar
Alexander Barkov committed
1038 1039
  pcf->Prec= 0;
  pcf->Opt= (fop) ? fop->opt : 0;
1040 1041

  if ((pcf->Length= fp->field_length) < 0)
Alexander Barkov's avatar
Alexander Barkov committed
1042
    pcf->Length= 256;            // BLOB?
1043 1044 1045 1046

  switch (fp->type()) {
    case MYSQL_TYPE_BLOB:
    case MYSQL_TYPE_VARCHAR:
Alexander Barkov's avatar
Alexander Barkov committed
1047
      pcf->Flags |= U_VAR;
1048
    case MYSQL_TYPE_STRING:
Alexander Barkov's avatar
Alexander Barkov committed
1049
      pcf->Type= TYPE_STRING;
1050 1051

      // Do something for case
Alexander Barkov's avatar
Alexander Barkov committed
1052
      cp= fp->charset()->name;
1053

Alexander Barkov's avatar
Alexander Barkov committed
1054 1055 1056 1057 1058
      // Find if collation name ends by _ci
      if (!strcmp(cp + strlen(cp) - 3, "_ci")) {
        pcf->Prec= 1;      // Case insensitive
        pcf->Opt= 0;       // Prevent index opt until it is safe
        } // endif ci
1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069

      break;
    case MYSQL_TYPE_LONG:
      pcf->Type= TYPE_INT;
      break;
    case MYSQL_TYPE_SHORT:
      pcf->Type= TYPE_SHORT;
      break;
    case MYSQL_TYPE_DOUBLE:
    case MYSQL_TYPE_FLOAT:
      pcf->Type= TYPE_FLOAT;
Alexander Barkov's avatar
Alexander Barkov committed
1070
      pcf->Prec= max(min(fp->decimals(), ((unsigned)pcf->Length - 2)), 0);
1071 1072 1073 1074 1075 1076 1077
      break;
    case MYSQL_TYPE_DATE:
    case MYSQL_TYPE_TIME:
    case MYSQL_TYPE_DATETIME:
    case MYSQL_TYPE_TIMESTAMP:
      pcf->Type= TYPE_DATE;
      break;
1078 1079 1080
    case MYSQL_TYPE_LONGLONG:
      pcf->Type= TYPE_BIGINT;
      break;
1081 1082 1083 1084
    default:
      pcf->Type=TYPE_ERROR;
    } // endswitch type

Alexander Barkov's avatar
Alexander Barkov committed
1085 1086 1087
  // This is used to skip null bit
  if (fp->real_maybe_null())
    pcf->Flags |= U_NULLS;
1088 1089

#if defined(MARIADB)
Alexander Barkov's avatar
Alexander Barkov committed
1090 1091 1092
  // Mark virtual columns as such
  if (fp->vcol_info && !fp->stored_in_db)
    pcf->Flags |= U_VIRTUAL;
1093 1094
#endif   // MARIADB

Alexander Barkov's avatar
Alexander Barkov committed
1095
  pcf->Key= 0;   // Not used when called from MySQL
1096 1097
  pcf->Remark= fp->comment.str;

Alexander Barkov's avatar
Alexander Barkov committed
1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113
  if (fop) {
    pcf->Offset= fop->offset;
//  pcf->Freq= fop->freq;
    pcf->Datefmt= (char*)fop->dateformat;
    pcf->Fieldfmt= (char*)fop->fieldformat;

    // This is useful in particular for date columns
    if ((len= fop->buflen) > pcf->Length)
      pcf->Length= len;

  } else {
    pcf->Offset= -1;
//  pcf->Freq= 0;
    pcf->Datefmt= NULL;
    pcf->Fieldfmt= NULL;
  } // endif fop
1114 1115 1116 1117 1118 1119 1120 1121 1122

  return fldp;
} // end of GetColumnOption

/****************************************************************************/
/*  Returns the index description structure used to make the index.         */
/****************************************************************************/
PIXDEF ha_connect::GetIndexInfo(int n)
{
Alexander Barkov's avatar
Alexander Barkov committed
1123 1124 1125 1126 1127 1128
  char    *name, *pn;
  bool     unique;
  PIXDEF   xdp= NULL;
  PKPDEF   kpp, pkp= NULL;
  PGLOBAL& g= xp->g;
  KEY      kp;
1129 1130

  // Find the index to describe
Alexander Barkov's avatar
Alexander Barkov committed
1131 1132 1133 1134 1135
  if ((unsigned)n < table->s->keynames.count)
//    kp= table->key_info[n];    which one ???
    kp= table->s->key_info[n];
  else
    return NULL;
1136 1137 1138 1139

  // Now get index information
  pn= (char*)table->s->keynames.type_names[n];
  name= (char*)PlugSubAlloc(g, NULL, strlen(pn) + 1);
Alexander Barkov's avatar
Alexander Barkov committed
1140 1141
  strcpy(name, pn);    // This is probably unuseful
  unique= (kp.flags & 1) != 0;
1142 1143 1144 1145

  // Allocate the index description block
  xdp= new(g) INDEXDEF(name, unique, n);

Alexander Barkov's avatar
Alexander Barkov committed
1146 1147 1148 1149 1150
  // Get the the key parts info
  for (int k= 0; (unsigned)k < kp.key_parts; k++) {
    pn= (char*)kp.key_part[k].field->field_name;
    name= (char*)PlugSubAlloc(g, NULL, strlen(pn) + 1);
    strcpy(name, pn);    // This is probably unuseful
1151

Alexander Barkov's avatar
Alexander Barkov committed
1152 1153 1154
    // Allocate the key part description block
    kpp= new(g) KPARTDEF(name, k + 1);
    kpp->SetKlen(kp.key_part[k].length);
1155

Alexander Barkov's avatar
Alexander Barkov committed
1156 1157 1158
    // Index on auto increment column is an XXROW index
    if (kp.key_part[k].field->flags & AUTO_INCREMENT_FLAG && kp.key_parts == 1)
      xdp->SetAuto(true);
1159

Alexander Barkov's avatar
Alexander Barkov committed
1160 1161 1162 1163
    if (pkp)
      pkp->SetNext(kpp);
    else
      xdp->SetToKeyParts(kpp);
1164

Alexander Barkov's avatar
Alexander Barkov committed
1165 1166
    pkp= kpp;
    } // endfor k
1167

Alexander Barkov's avatar
Alexander Barkov committed
1168
  xdp->SetNParts(kp.key_parts);
1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186
  return xdp;
} // end of GetIndexInfo

const char *ha_connect::GetDBName(const char* name)
{
  return (name) ? name : table->s->db.str;
} // end of GetDBName

const char *ha_connect::GetTableName(void)
{
  return table->s->table_name.str;
} // end of GetTableName

/****************************************************************************/
/*  Returns the column real or special name length of a field.              */
/****************************************************************************/
int ha_connect::GetColNameLen(Field *fp)
{
Alexander Barkov's avatar
Alexander Barkov committed
1187
  int n;
1188 1189 1190
  PFOS fop= GetFieldOptionStruct(fp);

  // Now get the column name length
Alexander Barkov's avatar
Alexander Barkov committed
1191 1192 1193 1194
  if (fop && fop->special)
    n= strlen(fop->special) + 1;
  else
    n= strlen(fp->field_name);
1195

Alexander Barkov's avatar
Alexander Barkov committed
1196
  return n;
1197 1198 1199 1200 1201 1202 1203 1204 1205
} // end of GetColNameLen

/****************************************************************************/
/*  Returns the column real or special name of a field.                     */
/****************************************************************************/
char *ha_connect::GetColName(Field *fp)
{
  PFOS fop= GetFieldOptionStruct(fp);

Alexander Barkov's avatar
Alexander Barkov committed
1206
  return (fop && fop->special) ? fop->special : (char*)fp->field_name;
1207 1208 1209 1210 1211 1212 1213 1214 1215 1216
} // end of GetColName

/****************************************************************************/
/*  Adds the column real or special name of a field to a string.            */
/****************************************************************************/
void ha_connect::AddColName(char *cp, Field *fp)
{
  PFOS fop= GetFieldOptionStruct(fp);

  // Now add the column name
Alexander Barkov's avatar
Alexander Barkov committed
1217 1218 1219 1220 1221
  if (fop && fop->special)
    // The prefix * mark the column as "special"
    strcat(strcpy(cp, "*"), strupr(fop->special));
  else
    strcpy(cp, (char*)fp->field_name);
1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238

} // end of AddColName

/****************************************************************************/
/*  Get the table description block of a CONNECT table.                     */
/****************************************************************************/
PTDB ha_connect::GetTDB(PGLOBAL g)
{
  const char *table_name;
  PTDB        tp;

  // Double test to be on the safe side
  if (!g || !table)
    return NULL;

  table_name= GetTableName();

Alexander Barkov's avatar
Alexander Barkov committed
1239 1240 1241 1242 1243
  if (tdbp && !stricmp(tdbp->GetName(), table_name)
           && tdbp->GetMode() == xmod && !xp->CheckQuery(valid_query_id)) {
    tp= tdbp;
    tp->SetMode(xmod);
  } else if ((tp= CntGetTDB(g, table_name, xmod, this)))
1244
    valid_query_id= xp->last_query_id;
Alexander Barkov's avatar
Alexander Barkov committed
1245
  else
1246 1247 1248 1249 1250 1251 1252 1253 1254 1255
    printf("GetTDB: %s\n", g->Message);

  return tp;
} // end of GetTDB

/****************************************************************************/
/*  Open a CONNECT table, restricting column list if cols is true.          */
/****************************************************************************/
bool ha_connect::OpenTable(PGLOBAL g, bool del)
{
Alexander Barkov's avatar
Alexander Barkov committed
1256
  bool  rc= false;
1257 1258 1259
  char *c1= NULL, *c2=NULL;

  // Double test to be on the safe side
Alexander Barkov's avatar
Alexander Barkov committed
1260 1261
  if (!g || !table) {
    printf("OpenTable logical error; g=%p table=%p\n", g, table);
1262
    return true;
Alexander Barkov's avatar
Alexander Barkov committed
1263
    } // endif g
1264 1265

  if (!(tdbp= GetTDB(g)))
Alexander Barkov's avatar
Alexander Barkov committed
1266
    return true;
1267 1268 1269 1270 1271

  // Get the list of used fields (columns)
  char        *p;
  unsigned int k1, k2, n1, n2;
  Field*      *field;
Alexander Barkov's avatar
Alexander Barkov committed
1272 1273
  MY_BITMAP   *map= (xmod != MODE_INSERT) ? table->read_set  : table->write_set;
  MY_BITMAP   *ump= (xmod == MODE_UPDATE) ? table->write_set : NULL;
1274

Alexander Barkov's avatar
Alexander Barkov committed
1275 1276
  k1= k2= 0;
  n1= n2= 1;         // 1 is space for final null character
1277

Alexander Barkov's avatar
Alexander Barkov committed
1278
  for (field= table->field; *field; field++) {
1279 1280 1281 1282 1283
    if (bitmap_is_set(map, (*field)->field_index)) {
      n1+= (GetColNameLen(*field) + 1);
      k1++;
      } // endif

Alexander Barkov's avatar
Alexander Barkov committed
1284
    if (ump && bitmap_is_set(ump, (*field)->field_index)) {
1285 1286 1287 1288
      n2+= (GetColNameLen(*field) + 1);
      k2++;
      } // endif

Alexander Barkov's avatar
Alexander Barkov committed
1289
    } // endfor field
1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319

  if (k1) {
    p= c1= (char*)PlugSubAlloc(g, NULL, n1);

    for (field= table->field; *field; field++)
      if (bitmap_is_set(map, (*field)->field_index)) {
        AddColName(p, *field);
        p+= (strlen(p) + 1);
        } // endif used field

    *p= '\0';          // mark end of list
    } // endif k1

  if (k2) {
    p= c2= (char*)PlugSubAlloc(g, NULL, n2);

    for (field= table->field; *field; field++)
      if (bitmap_is_set(ump, (*field)->field_index)) {
        AddColName(p, *field);
        p+= (strlen(p) + 1);
        } // endif used field

    *p= '\0';          // mark end of list
    } // endif k2

  // Open the table
  if (!(rc= CntOpenTable(g, tdbp, xmod, c1, c2, del, this))) {
    istable= true;
//  strmake(tname, table_name, sizeof(tname)-1);

Alexander Barkov's avatar
Alexander Barkov committed
1320 1321 1322 1323 1324 1325 1326
    if (xmod == MODE_ANY && *tdbp->GetName() != '#') {
      // We are in a create index query
      if (!((PTDBASE)tdbp)->GetDef()->Indexable()) {
        sprintf(g->Message, "Table %s cannot be indexed", tdbp->GetName());
        rc= true;
      } else if (xp) // xp can be null when called from create
        xp->tabp= (PTDBDOS)tdbp;  // The table on which the index is created
1327

Alexander Barkov's avatar
Alexander Barkov committed
1328
      } // endif xmod
1329 1330 1331 1332 1333

//  tdbp->SetOrig((PTBX)table);  // used by CheckCond
  } else
    printf("OpenTable: %s\n", g->Message);

Alexander Barkov's avatar
Alexander Barkov committed
1334 1335 1336 1337
  if (rc) {
    tdbp= NULL;
    valid_info= false;
    } // endif rc
1338 1339 1340 1341 1342 1343 1344 1345 1346 1347

  return rc;
} // end of OpenTable


/****************************************************************************/
/*  IsOpened: returns true if the table is already opened.                  */
/****************************************************************************/
bool ha_connect::IsOpened(void)
{
Alexander Barkov's avatar
Alexander Barkov committed
1348 1349
  return (!xp->CheckQuery(valid_query_id) && tdbp
                                          && tdbp->GetUse() == USE_OPEN);
1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361
} // end of IsOpened


/****************************************************************************/
/*  Close a CONNECT table.                                                  */
/****************************************************************************/
int ha_connect::CloseTable(PGLOBAL g)
{
  int rc= CntCloseTable(g, tdbp);
  tdbp= NULL;
  sdval=NULL;
  valid_info= false;
Alexander Barkov's avatar
Alexander Barkov committed
1362
  indexing= -1;
1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374
  return rc;
} // end of CloseTable


/***********************************************************************/
/*  Make a pseudo record from current row values. Specific to MySQL.   */
/***********************************************************************/
int ha_connect::MakeRecord(char *buf)
{
  char            *p, *fmt, val[32];
  int              rc= 0;
  Field*          *field;
Alexander Barkov's avatar
Alexander Barkov committed
1375
  Field           *fp;
1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407
  my_bitmap_map   *org_bitmap;
  CHARSET_INFO    *charset;
  const MY_BITMAP *map;
  PVAL             value;
  PCOL             colp= NULL;
  DBUG_ENTER("ha_connect::MakeRecord");

  if (xtrace > 1)
#if defined(MARIADB)
    printf("Maps: read=%p write=%p vcol=%p defr=%p defw=%p\n",
            *table->read_set->bitmap, *table->write_set->bitmap,
            *table->vcol_set->bitmap,
            *table->def_read_set.bitmap, *table->def_write_set.bitmap);
#else   // !MARIADB
    printf("Maps: read=%p write=%p defr=%p defw=%p\n",
            *table->read_set->bitmap, *table->write_set->bitmap,
            *table->def_read_set.bitmap, *table->def_write_set.bitmap);
#endif  // !MARIADB

  // Avoid asserts in field::store() for columns that are not updated
  org_bitmap= dbug_tmp_use_all_columns(table, table->write_set);

  // This is for variable_length rows
  memset(buf, 0, table->s->null_bytes);

  // store needs a charset, why not this one?
  charset= table->s->table_charset;

  // When sorting read_set selects all columns, so we use def_read_set
  map= (const MY_BITMAP *)&table->def_read_set;

  // Make the pseudo record from field values
Alexander Barkov's avatar
Alexander Barkov committed
1408 1409
  for (field= table->field; *field && !rc; field++) {
    fp= *field;
1410 1411

#if defined(MARIADB)
Alexander Barkov's avatar
Alexander Barkov committed
1412 1413 1414
    if (fp->vcol_info && !fp->stored_in_db)
      continue;            // This is a virtual column
#endif   // MARIADB
1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470

    if (bitmap_is_set(map, fp->field_index)) {
      // This is a used field, fill the buffer with value
      for (colp= tdbp->GetColumns(); colp; colp= colp->GetNext())
        if (!stricmp(colp->GetName(), GetColName(fp)))
          break;

      if (!colp) {
        printf("Column %s not found\n", fp->field_name);
        dbug_tmp_restore_column_map(table->write_set, org_bitmap);
        DBUG_RETURN(HA_ERR_WRONG_IN_RECORD);
        } // endif colp

      value= colp->GetValue();

      // All this could be better optimized
      if (value->GetType() == TYPE_DATE) {
        if (!sdval)
          sdval= AllocateValue(xp->g, TYPE_STRING, 20);

        switch (fp->type()) {
          case MYSQL_TYPE_DATE:
            fmt= "%Y-%m-%d";
            break;
          case MYSQL_TYPE_TIME:
            fmt= "%H:%M:%S";
            break;
          default:
            fmt= "%Y-%m-%d %H:%M:%S";
          } // endswitch type

        // Get date in the format required by MySQL fields
        value->FormatValue(sdval, fmt);
        p= sdval->GetCharValue();
      } else if (value->GetType() == TYPE_FLOAT)
        p= NULL;
      else
        p= value->GetCharString(val);

      if (p) {
        if (fp->store(p, strlen(p), charset, CHECK_FIELD_WARN)) {
          // Avoid "error" on null fields
          if (value->GetIntValue())
            rc= HA_ERR_WRONG_IN_RECORD;

          DBUG_PRINT("MakeRecord", (p));
          } // endif store

      } else
        if (fp->store(value->GetFloatValue())) {
          rc= HA_ERR_WRONG_IN_RECORD;
          DBUG_PRINT("MakeRecord", (value->GetCharString(val)));
          } // endif store

      } // endif bitmap

Alexander Barkov's avatar
Alexander Barkov committed
1471
    } // endfor field
1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487

  // This is copied from ha_tina and is necessary to avoid asserts
  dbug_tmp_restore_column_map(table->write_set, org_bitmap);
  DBUG_RETURN(rc);
} // end of MakeRecord


/***********************************************************************/
/*  Set row values from a MySQL pseudo record. Specific to MySQL.      */
/***********************************************************************/
int ha_connect::ScanRecord(PGLOBAL g, uchar *buf)
{
  char    attr_buffer[1024];
  int     rc= 0;
  PCOL    colp;
  PVAL    value;
Alexander Barkov's avatar
Alexander Barkov committed
1488
  Field  *fp;
1489 1490 1491 1492 1493 1494 1495
  PTDBASE tp= (PTDBASE)tdbp;
  String  attribute(attr_buffer, sizeof(attr_buffer),
                    table->s->table_charset);
  my_bitmap_map *bmap= dbug_tmp_use_all_columns(table, table->read_set);

  // Scan the pseudo record for field values and set column values
  for (Field **field=table->field ; *field ; field++) {
Alexander Barkov's avatar
Alexander Barkov committed
1496
    fp= *field;
1497 1498

#if defined(MARIADB)
Alexander Barkov's avatar
Alexander Barkov committed
1499 1500 1501
    if ((fp->vcol_info && !fp->stored_in_db) ||
         fp->option_struct->special)
      continue;            // Is a virtual column possible here ???
1502 1503 1504
#endif   // MARIADB

    if (bitmap_is_set(table->write_set, fp->field_index)) {
Alexander Barkov's avatar
Alexander Barkov committed
1505 1506 1507
      for (colp= tp->GetSetCols(); colp; colp= colp->GetNext())
        if (!stricmp(colp->GetName(), fp->field_name))
          break;
1508

Alexander Barkov's avatar
Alexander Barkov committed
1509 1510 1511 1512 1513 1514
      if (!colp) {
        printf("Column %s not found\n", fp->field_name);
        rc= HA_ERR_WRONG_IN_RECORD;
        goto err;
      } else
        value= colp->GetValue();
1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555

      // This is a used field, fill the value from the row buffer
      // All this could be better optimized
      switch (value->GetType()) {
        case TYPE_FLOAT:
          value->SetValue(fp->val_real());
          break;
        case TYPE_DATE:
          if (!sdval) {
            sdval= (DTVAL*)AllocateValue(xp->g, TYPE_DATE, 19);

            // Get date in the format produced by MySQL fields
            ((DTVAL*)sdval)->SetFormat(g, "YYYY-MM-DD hh:mm:ss", 19);
            } // endif sdval

          fp->val_str(&attribute);
          sdval->SetValue_psz(attribute.c_ptr());
          value->SetValue_pval(sdval);
          break;
        default:
          fp->val_str(&attribute);
          value->SetValue_psz(attribute.c_ptr());
        } // endswitch Type

#ifdef NEWCHANGE
    } else if (xmod == MODE_UPDATE) {
      PCOL cp;

      for (cp= tp->GetColumns(); cp; cp= cp->GetNext())
        if (!stricmp(colp->GetName(), cp->GetName()))
          break;

      if (!cp) {
        rc= HA_ERR_WRONG_IN_RECORD;
        goto err;
        } // endif cp

      value->SetValue_pval(cp->GetValue());
    } else // mode Insert
      value->Reset();
#else
Alexander Barkov's avatar
Alexander Barkov committed
1556
    } // endif bitmap_is_set
1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581
#endif

    } // endfor field

 err:
  dbug_tmp_restore_column_map(table->read_set, bmap);
  return rc;
} // end of ScanRecord


/***********************************************************************/
/*  Check change in index column. Specific to MySQL.                   */
/*  Should be elaborated to check for real changes.                    */
/***********************************************************************/
int ha_connect::CheckRecord(PGLOBAL g, const uchar *oldbuf, uchar *newbuf)
{
  return ScanRecord(g, newbuf);
} // end of dummy CheckRecord


/***********************************************************************/
/*  Return the string representing an operator.                        */
/***********************************************************************/
char *ha_connect::GetValStr(OPVAL vop, bool neg)
{
Alexander Barkov's avatar
Alexander Barkov committed
1582
  char *val;
1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603

  switch (vop) {
    case OP_EQ:
      val= " = ";
      break;
    case OP_NE:
      val= " <> ";
      break;
    case OP_GT:
      val= " > ";
      break;
    case OP_GE:
      val= " >= ";
      break;
    case OP_LT:
      val= " < ";
      break;
    case OP_LE:
      val= " <= ";
      break;
    case OP_IN:
Alexander Barkov's avatar
Alexander Barkov committed
1604
      val= (neg) ? " NOT IN (" : " IN (";
1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645
      break;
    case OP_NULL:
      val= " IS NULL";
      break;
    case OP_LIKE:
      val= " LIKE ";
      break;
    case OP_XX:
      val= " BETWEEN ";
      break;
    case OP_EXIST:
      val= " EXISTS ";
      break;
    case OP_AND:
      val= " AND ";
      break;
    case OP_OR:
      val= " OR ";
      break;
    case OP_NOT:
      val= " NOT ";
      break;
    case OP_CNC:
      val= " || ";
      break;
    case OP_ADD:
      val= " + ";
      break;
    case OP_SUB:
      val= " - ";
      break;
    case OP_MULT:
      val= " * ";
      break;
    case OP_DIV:
      val= " / ";
      break;
    default:
      val= " ? ";
    } /* endswitch */

Alexander Barkov's avatar
Alexander Barkov committed
1646
  return val;
1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666
} // end of GetValStr


/***********************************************************************/
/*  Check the WHERE condition and return an ODBC/WQL filter.           */
/***********************************************************************/
PFIL ha_connect::CheckCond(PGLOBAL g, PFIL filp, AMT tty, Item *cond)
{
  unsigned int i;
  bool  ismul= false;
  PPARM pfirst= NULL, pprec= NULL, pp[2]= {NULL, NULL};
  OPVAL vop= OP_XX;

  if (!cond)
    return NULL;

  if (xtrace > 1)
    printf("Cond type=%d\n", cond->type());

  if (cond->type() == COND::COND_ITEM) {
Alexander Barkov's avatar
Alexander Barkov committed
1667
    char      *p1, *p2;
1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683
    Item_cond *cond_item= (Item_cond *)cond;

    if (xtrace > 1)
      printf("Cond: Ftype=%d name=%s\n", cond_item->functype(),
                                         cond_item->func_name());

    switch (cond_item->functype()) {
      case Item_func::COND_AND_FUNC: vop= OP_AND; break;
      case Item_func::COND_OR_FUNC:  vop= OP_OR;  break;
      default: return NULL;
      } // endswitch functype

    List<Item>* arglist= cond_item->argument_list();
    List_iterator<Item> li(*arglist);
    Item *subitem;

Alexander Barkov's avatar
Alexander Barkov committed
1684 1685 1686
    p1= filp + strlen(filp);
    strcpy(p1, "(");
    p2= p1 + 1;
1687 1688 1689

    for (i= 0; i < arglist->elements; i++)
      if ((subitem= li++)) {
Alexander Barkov's avatar
Alexander Barkov committed
1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700
        if (!CheckCond(g, filp, tty, subitem)) {
          if (vop == OP_OR)
            return NULL;
          else
            *p2= 0;

        } else {
          p1= p2 + strlen(p2);
          strcpy(p1, GetValStr(vop, FALSE));
          p2= p1 + strlen(p1);
        } // endif CheckCond
1701 1702 1703 1704

      } else
        return NULL;

Alexander Barkov's avatar
Alexander Barkov committed
1705 1706 1707 1708
    if (*p1 != '(')
      strcpy(p1, ")");
    else
      return NULL;
1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720

  } else if (cond->type() == COND::FUNC_ITEM) {
    unsigned int i;
//  int   n;
    bool  iscol, neg= FALSE;
    Item_func *condf= (Item_func *)cond;
    Item*     *args= condf->arguments();

    if (xtrace > 1)
      printf("Func type=%d argnum=%d\n", condf->functype(),
                                         condf->argument_count());

Alexander Barkov's avatar
Alexander Barkov committed
1721
//  neg= condf->
1722 1723 1724 1725 1726 1727 1728 1729 1730 1731

    switch (condf->functype()) {
      case Item_func::EQUAL_FUNC:
      case Item_func::EQ_FUNC: vop= OP_EQ;  break;
      case Item_func::NE_FUNC: vop= OP_NE;  break;
      case Item_func::LT_FUNC: vop= OP_LT;  break;
      case Item_func::LE_FUNC: vop= OP_LE;  break;
      case Item_func::GE_FUNC: vop= OP_GE;  break;
      case Item_func::GT_FUNC: vop= OP_GT;  break;
      case Item_func::IN_FUNC: vop= OP_IN;
Alexander Barkov's avatar
Alexander Barkov committed
1732
        neg= ((Item_func_opt_neg *)condf)->negated;
1733 1734 1735 1736 1737 1738
      case Item_func::BETWEEN: ismul= true; break;
      default: return NULL;
      } // endswitch functype

    if (condf->argument_count() < 2)
      return NULL;
Alexander Barkov's avatar
Alexander Barkov committed
1739 1740
    else if (ismul && tty == TYPE_AM_WMI)
      return NULL;        // Not supported by WQL
1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753

    for (i= 0; i < condf->argument_count(); i++) {
      if (xtrace > 1)
        printf("Argtype(%d)=%d\n", i, args[i]->type());

      if (i >= 2 && !ismul) {
        if (xtrace > 1)
          printf("Unexpected arg for vop=%d\n", vop);

        continue;
        } // endif i

      if ((iscol= args[i]->type() == COND::FIELD_ITEM)) {
Alexander Barkov's avatar
Alexander Barkov committed
1754 1755
        const char *fnm;
        ha_field_option_struct *fop;
1756 1757 1758 1759
        Item_field *pField= (Item_field *)args[i];

        if (pField->field->table != table)
          return NULL;  // Field does not belong to this table
Alexander Barkov's avatar
Alexander Barkov committed
1760 1761
        else
          fop= GetFieldOptionStruct(pField->field);
1762

Alexander Barkov's avatar
Alexander Barkov committed
1763 1764 1765 1766 1767
        if (fop && fop->special) {
          if (tty == TYPE_AM_TBL && !stricmp(fop->special, "TABID"))
            fnm= "TABID";
          else
            return NULL;
1768

Alexander Barkov's avatar
Alexander Barkov committed
1769 1770 1771 1772
        } else if (tty == TYPE_AM_TBL)
          return NULL;
        else
          fnm= pField->field->field_name;
1773 1774 1775 1776 1777 1778 1779 1780 1781 1782

        if (xtrace > 1) {
          printf("Field index=%d\n", pField->field->field_index);
          printf("Field name=%s\n", pField->field->field_name);
          } // endif xtrace

        // IN and BETWEEN clauses should be col VOP list
        if (i && ismul)
          return NULL;

Alexander Barkov's avatar
Alexander Barkov committed
1783
        strcat(filp, fnm);
1784 1785 1786 1787 1788 1789
      } else {
        char   buff[256];
        String *res, tmp(buff,sizeof(buff), &my_charset_bin);
        Item_basic_constant *pval= (Item_basic_constant *)args[i];

        if ((res= pval->val_str(&tmp)) == NULL)
Alexander Barkov's avatar
Alexander Barkov committed
1790
          return NULL;                      // To be clarified
1791 1792 1793 1794 1795 1796 1797 1798

        if (xtrace > 1)
          printf("Value=%.*s\n", res->length(), res->ptr());

        // IN and BETWEEN clauses should be col VOP list
        if (!i && ismul)
          return NULL;

Alexander Barkov's avatar
Alexander Barkov committed
1799 1800 1801 1802 1803
        // Append the value to the filter
        if (args[i]->type() == COND::STRING_ITEM)
          strcat(strcat(strcat(filp, "'"), res->ptr()), "'");
        else
          strncat(filp, res->ptr(), res->length());
1804 1805 1806

      } // endif

Alexander Barkov's avatar
Alexander Barkov committed
1807 1808 1809 1810 1811 1812
      if (!i)
        strcat(filp, GetValStr(vop, neg));
      else if (vop == OP_XX && i == 1)
        strcat(filp, " AND ");
      else if (vop == OP_IN)
        strcat(filp, (i == condf->argument_count() - 1) ? ")" : ",");
1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838

      } // endfor i

  } else {
    if (xtrace > 1)
      printf("Unsupported condition\n");

    return NULL;
  } // endif's type

  return filp;
} // end of CheckCond


 /**
   Push condition down to the table handler.

   @param  cond   Condition to be pushed. The condition tree must not be
                  modified by the caller.

   @return
     The 'remainder' condition that caller must use to filter out records.
     NULL means the handler will not return rows that do not match the
     passed condition.

   @note
Alexander Barkov's avatar
Alexander Barkov committed
1839 1840 1841 1842 1843 1844
     CONNECT handles the filtering only for table types that construct
     an SQL or WQL query, but still leaves it to MySQL because only some
     parts of the filter may be relevant.
     The first suballocate finds the position where the string will be
     constructed in the sarea. The second one does make the suballocation
     with the proper length.
1845 1846 1847 1848 1849 1850
 */
const COND *ha_connect::cond_push(const COND *cond)
{
  DBUG_ENTER("ha_connect::cond_push");

  if (tdbp) {
Alexander Barkov's avatar
Alexander Barkov committed
1851
    AMT tty= tdbp->GetAmType();
1852 1853

    if (tty == TYPE_AM_WMI || tty == TYPE_AM_ODBC ||
Alexander Barkov's avatar
Alexander Barkov committed
1854
        tty == TYPE_AM_TBL || tty == TYPE_AM_MYSQL) {
1855 1856 1857
      PGLOBAL& g= xp->g;
      PFIL filp= (PFIL)PlugSubAlloc(g, NULL, 0);

Alexander Barkov's avatar
Alexander Barkov committed
1858
      *filp= 0;
1859

Alexander Barkov's avatar
Alexander Barkov committed
1860 1861 1862
      if (CheckCond(g, filp, tty, (Item *)cond)) {
        if (xtrace)
          puts(filp);
1863

Alexander Barkov's avatar
Alexander Barkov committed
1864 1865 1866 1867
        tdbp->SetFilter(filp);
//      cond= NULL;     // This does not work anyway
        PlugSubAlloc(g, NULL, strlen(filp) + 1);
        } // endif filp
1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971

      } // endif tty

    } // endif tdbp

  // Let MySQL do the filtering
  DBUG_RETURN(cond);
} // end of cond_push

/**
  Number of rows in table. It will only be called if
  (table_flags() & (HA_HAS_RECORDS | HA_STATS_RECORDS_IS_EXACT)) != 0
*/
ha_rows ha_connect::records()
{
  if (!valid_info)
    info(HA_STATUS_VARIABLE);

  if (tdbp && tdbp->Cardinality(NULL))
    return stats.records;
  else
    return HA_POS_ERROR;

} // end of records


/**
  Return an error message specific to this handler.

  @param error  error code previously returned by handler
  @param buf    pointer to String where to add error message

  @return
    Returns true if this is a temporary error
*/
bool ha_connect::get_error_message(int error, String* buf)
{
  DBUG_ENTER("ha_connect::get_error_message");

  if (xp && xp->g)
    buf->copy(xp->g->Message, (uint)strlen(xp->g->Message),
              system_charset_info);

  DBUG_RETURN(false);
} // end of get_error_message


/**
  @brief
  If frm_error() is called then we will use this to determine
  the file extensions that exist for the storage engine. This is also
  used by the default rename_table and delete_table method in
  handler.cc.

  For engines that have two file name extentions (separate meta/index file
  and data file), the order of elements is relevant. First element of engine
  file name extentions array should be meta/index file extention. Second
  element - data file extention. This order is assumed by
  prepare_for_repair() when REPAIR TABLE ... USE_FRM is issued.

  @note: PlugDB will handle all file creation/deletion. When dropping
  a CONNECT table, we don't want the PlugDB table to be dropped or erased.
  Therefore we provide a void list of extensions.

  @see
  rename_table method in handler.cc and
  delete_table method in handler.cc
*/
static const char *ha_connect_exts[]= {
  NullS
};


const char **ha_connect::bas_ext() const
{
  return ha_connect_exts;    // a null list, see @note above
} // end of bas_ext


/**
  @brief
  Used for opening tables. The name will be the name of the file.

  @details
  A table is opened when it needs to be opened; e.g. when a request comes in
  for a SELECT on the table (tables are not open and closed for each request,
  they are cached).

  Called from handler.cc by handler::ha_open(). The server opens all tables by
  calling ha_open() which then calls the handler specific open().

  @note
  For CONNECT no open can be done here because field information is not yet
  updated. >>>>> TO BE CHECKED <<<<<
  (Thread information could be get by using 'ha_thd')

  @see
  handler::ha_open() in handler.cc
*/
int ha_connect::open(const char *name, int mode, uint test_if_locked)
{
  int rc= 0;
  DBUG_ENTER("ha_connect::open");

Alexander Barkov's avatar
Alexander Barkov committed
1972
  if (xtrace)
1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999
     printf("open: name=%s mode=%d test=%ud\n", name, mode, test_if_locked);

  if (!(share= get_share(name, table)))
    DBUG_RETURN(1);

  thr_lock_data_init(&share->lock,&lock,NULL);

  // Try to get the user if possible
  if (table && table->in_use) {
    PGLOBAL g= GetPlug(table->in_use);

    // Try to set the database environment
    if (g)
      rc= (CntCheckDB(g, this, name)) ? (-2) : 0;

    } // endif table

  DBUG_RETURN(rc);
} // end of open

/**
  @brief
  Make the indexes for this table
*/
int ha_connect::optimize(THD* thd, HA_CHECK_OPT* check_opt)
{
  int      rc= 0;
Alexander Barkov's avatar
Alexander Barkov committed
2000
  PGLOBAL& g= xp->g;
2001 2002 2003 2004
  PDBUSER  dup= PlgGetUser(g);

  // Ignore error on the opt file
  dup->Check &= ~CHK_OPT;
Alexander Barkov's avatar
Alexander Barkov committed
2005
  tdbp= GetTDB(g);
2006 2007
  dup->Check |= CHK_OPT;

Alexander Barkov's avatar
Alexander Barkov committed
2008 2009 2010 2011 2012 2013
  if (tdbp || (tdbp= GetTDB(g))) {
    if (!((PTDBASE)tdbp)->GetDef()->Indexable()) {
      sprintf(g->Message, "Table %s is not indexable", tdbp->GetName());
      rc= RC_INFO;
    } else
      rc= ((PTDBASE)tdbp)->ResetTableOpt(g, true);
2014

Alexander Barkov's avatar
Alexander Barkov committed
2015
  } else
2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086
    rc= HA_ERR_INTERNAL_ERROR;

  return rc;
} // end of optimize

/**
  @brief
  Closes a table. We call the free_share() function to free any resources
  that we have allocated in the "shared" structure.

  @details
  Called from sql_base.cc, sql_select.cc, and table.cc. In sql_select.cc it is
  only used to close up temporary tables or during the process where a
  temporary table is converted over to being a myisam table.

  For sql_base.cc look at close_data_tables().

  @see
  sql_base.cc, sql_select.cc and table.cc
*/
int ha_connect::close(void)
{
  int rc= 0;
  DBUG_ENTER("ha_connect::close");

  // If this is called by a later query, the table may have
  // been already closed and the tdbp is not valid anymore.
  if (tdbp && xp->last_query_id == valid_query_id)
    rc= CloseTable(xp->g);

  DBUG_RETURN(free_share(share) || rc);
} // end of close


/**
  @brief
  write_row() inserts a row. No extra() hint is given currently if a bulk load
  is happening. buf() is a byte array of data. You can use the field
  information to extract the data from the native byte array type.

    @details
  Example of this would be:
    @code
  for (Field **field=table->field ; *field ; field++)
  {
    ...
  }
    @endcode

  See ha_tina.cc for an example of extracting all of the data as strings.
  ha_berekly.cc has an example of how to store it intact by "packing" it
  for ha_berkeley's own native storage type.

  See the note for update_row() on auto_increments and timestamps. This
  case also applies to write_row().

  Called from item_sum.cc, item_sum.cc, sql_acl.cc, sql_insert.cc,
  sql_insert.cc, sql_select.cc, sql_table.cc, sql_udf.cc, and sql_update.cc.

    @see
  item_sum.cc, item_sum.cc, sql_acl.cc, sql_insert.cc,
  sql_insert.cc, sql_select.cc, sql_table.cc, sql_udf.cc and sql_update.cc
*/
int ha_connect::write_row(uchar *buf)
{
  int      rc= 0;
  PGLOBAL& g= xp->g;
  DBUG_ENTER("ha_connect::write_row");

  // Open the table if it was not opened yet (possible ???)
  if (!IsOpened())
Alexander Barkov's avatar
Alexander Barkov committed
2087 2088 2089 2090 2091
    if (OpenTable(g)) {
      if (strstr(g->Message, "read only"))
        rc= HA_ERR_TABLE_READONLY;
      else
        rc= HA_ERR_INITIALIZATION;
2092

Alexander Barkov's avatar
Alexander Barkov committed
2093 2094
      DBUG_RETURN(rc);
      } // endif tdbp
2095

Alexander Barkov's avatar
Alexander Barkov committed
2096 2097
  if (tdbp->GetMode() == MODE_ANY)
    DBUG_RETURN(0);
2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141

  // Set column values from the passed pseudo record
  if ((rc= ScanRecord(g, buf)))
    DBUG_RETURN(rc);

  // Return result code from write operation
  if (CntWriteRow(g, tdbp)) {
    DBUG_PRINT("write_row", (g->Message));
    printf("write_row: %s\n", g->Message);
    rc= HA_ERR_INTERNAL_ERROR;
    } // endif RC

  DBUG_RETURN(rc);
} // end of write_row


/**
  @brief
  Yes, update_row() does what you expect, it updates a row. old_data will have
  the previous row record in it, while new_data will have the newest data in it.
  Keep in mind that the server can do updates based on ordering if an ORDER BY
  clause was used. Consecutive ordering is not guaranteed.

    @details
  Currently new_data will not have an updated auto_increament record, or
  and updated timestamp field. You can do these for example by doing:
    @code
  if (table->timestamp_field_type & TIMESTAMP_AUTO_SET_ON_UPDATE)
    table->timestamp_field->set_time();
  if (table->next_number_field && record == table->record[0])
    update_auto_increment();
    @endcode

  Called from sql_select.cc, sql_acl.cc, sql_update.cc, and sql_insert.cc.

    @see
  sql_select.cc, sql_acl.cc, sql_update.cc and sql_insert.cc
*/
int ha_connect::update_row(const uchar *old_data, uchar *new_data)
{
  int      rc= 0;
  PGLOBAL& g= xp->g;
  DBUG_ENTER("ha_connect::update_row");

Alexander Barkov's avatar
Alexander Barkov committed
2142
  if (xtrace > 1)
2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197
    printf("update_row: old=%s new=%s\n", old_data, new_data);

  // Check values for possible change in indexed column
  if ((rc= CheckRecord(g, old_data, new_data)))
    return rc;

  if (CntUpdateRow(g, tdbp)) {
    DBUG_PRINT("update_row", (g->Message));
    printf("update_row CONNECT: %s\n", g->Message);
    rc= HA_ERR_INTERNAL_ERROR;
    } // endif RC

  DBUG_RETURN(rc);
} // end of update_row


/**
  @brief
  This will delete a row. buf will contain a copy of the row to be deleted.
  The server will call this right after the current row has been called (from
  either a previous rnd_nexT() or index call).

  @details
  If you keep a pointer to the last row or can access a primary key it will
  make doing the deletion quite a bit easier. Keep in mind that the server does
  not guarantee consecutive deletions. ORDER BY clauses can be used.

  Called in sql_acl.cc and sql_udf.cc to manage internal table
  information.  Called in sql_delete.cc, sql_insert.cc, and
  sql_select.cc. In sql_select it is used for removing duplicates
  while in insert it is used for REPLACE calls.

  @see
  sql_acl.cc, sql_udf.cc, sql_delete.cc, sql_insert.cc and sql_select.cc
*/
int ha_connect::delete_row(const uchar *buf)
{
  int rc= 0;
  DBUG_ENTER("ha_connect::delete_row");

  if (CntDeleteRow(xp->g, tdbp, false)) {
    rc= HA_ERR_INTERNAL_ERROR;
    printf("delete_row CONNECT: %s\n", xp->g->Message);
    } // endif DeleteRow

  DBUG_RETURN(rc);
} // end of delete_row


/****************************************************************************/
/*  We seem to come here at the begining of an index use.                   */
/****************************************************************************/
int ha_connect::index_init(uint idx, bool sorted)
{
  int rc;
Alexander Barkov's avatar
Alexander Barkov committed
2198
  PGLOBAL& g= xp->g;
2199 2200 2201 2202 2203
  DBUG_ENTER("index_init");

  if ((rc= rnd_init(0)))
    return rc;

Alexander Barkov's avatar
Alexander Barkov committed
2204
  indexing= CntIndexInit(g, tdbp, (signed)idx);
2205 2206 2207 2208 2209 2210 2211

  if (indexing <= 0) {
    DBUG_PRINT("index_init", (g->Message));
    printf("index_init CONNECT: %s\n", g->Message);
    active_index= (uint)-1;
    rc= -1;
  } else {
Alexander Barkov's avatar
Alexander Barkov committed
2212 2213 2214
    if (((PTDBDOX)tdbp)->To_Kindex->GetNum_K()) {
      if (((PTDBASE)tdbp)->GetFtype() != RECFM_NAF)
        ((PTDBDOX)tdbp)->GetTxfp()->ResetBuffer(g);
2215

Alexander Barkov's avatar
Alexander Barkov committed
2216 2217 2218
      active_index= idx;
    } else        // Void table
      indexing= 0;
2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231

    rc= 0;
  } // endif indexing

  DBUG_RETURN(rc);
} // end of index_init

/****************************************************************************/
/*  We seem to come here at the end of an index use.                        */
/****************************************************************************/
int ha_connect::index_end()
{
  DBUG_ENTER("index_end");
Alexander Barkov's avatar
Alexander Barkov committed
2232
  active_index= -1;
2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453
  DBUG_RETURN(rnd_end());
} // end of index_end


/****************************************************************************/
/*  This is internally called by all indexed reading functions.             */
/****************************************************************************/
int ha_connect::ReadIndexed(uchar *buf, OPVAL op, const uchar *key, uint key_len)
{
  int rc;

//statistic_increment(ha_read_key_count, &LOCK_status);

  switch (CntIndexRead(xp->g, tdbp, op, key, (int)key_len)) {
    case RC_OK:
      xp->fnd++;
      rc= MakeRecord((char*)buf);
      break;
    case RC_EF:         // End of file
      rc= HA_ERR_END_OF_FILE;
      break;
    case RC_NF:         // Not found
      xp->nfd++;
      rc= (op == OP_SAME) ? HA_ERR_END_OF_FILE : HA_ERR_KEY_NOT_FOUND;
      break;
    default:          // Read error
      DBUG_PRINT("ReadIndexed", (xp->g->Message));
      printf("ReadIndexed: %s\n", xp->g->Message);
      rc= HA_ERR_INTERNAL_ERROR;
    } // endswitch RC

  if (xtrace > 1)
    printf("ReadIndexed: op=%d rc=%d\n", op, rc);

  table->status= (rc == RC_OK) ? 0 : STATUS_NOT_FOUND;
  return rc;
} // end of ReadIndexed


#ifdef NOT_USED
/**
  @brief
  Positions an index cursor to the index specified in the handle. Fetches the
  row if available. If the key value is null, begin at the first key of the
  index.
*/
int ha_connect::index_read_map(uchar *buf, const uchar *key,
                               key_part_map keypart_map __attribute__((unused)),
                               enum ha_rkey_function find_flag
                               __attribute__((unused)))
{
  DBUG_ENTER("ha_connect::index_read");
  DBUG_RETURN(HA_ERR_WRONG_COMMAND);
}
#endif // NOT_USED


/****************************************************************************/
/*  This is called by handler::index_read_map.                              */
/****************************************************************************/
int ha_connect::index_read(uchar * buf, const uchar * key, uint key_len,
                           enum ha_rkey_function find_flag)
{
  int rc;
  OPVAL op= OP_XX;
  DBUG_ENTER("ha_connect::index_read");

  switch(find_flag) {
    case HA_READ_KEY_EXACT:   op= OP_EQ; break;
    case HA_READ_AFTER_KEY:   op= OP_GT; break;
    case HA_READ_KEY_OR_NEXT: op= OP_GE; break;
    default: DBUG_RETURN(-1);
    } // endswitch find_flag

  if (xtrace > 1)
    printf("%p index_read: op=%d\n", this, op);

  if (indexing > 0)
    rc= ReadIndexed(buf, op, key, key_len);
  else
    rc= -1;

  DBUG_RETURN(rc);
} // end of index_read


/**
  @brief
  Used to read forward through the index.
*/
int ha_connect::index_next(uchar *buf)
{
  int rc;
  DBUG_ENTER("ha_connect::index_next");
  //statistic_increment(ha_read_next_count, &LOCK_status);

  if (indexing > 0)
    rc= ReadIndexed(buf, OP_NEXT);
  else if (!indexing)
    rc= rnd_next(buf);
  else
    rc= -1;

  DBUG_RETURN(rc);
} // end of index_next


#ifdef NOT_USED
/**
  @brief
  Used to read backwards through the index.
*/
int ha_connect::index_prev(uchar *buf)
{
  DBUG_ENTER("ha_connect::index_prev");
  DBUG_RETURN(HA_ERR_WRONG_COMMAND);
}
#endif // NOT_USED


/**
  @brief
  index_first() asks for the first key in the index.

    @details
  Called from opt_range.cc, opt_sum.cc, sql_handler.cc, and sql_select.cc.

    @see
  opt_range.cc, opt_sum.cc, sql_handler.cc and sql_select.cc
*/
int ha_connect::index_first(uchar *buf)
{
  int rc;
  DBUG_ENTER("ha_connect::index_first");

  if (indexing > 0)
    rc= ReadIndexed(buf, OP_FIRST);
  else if (indexing < 0)
    rc= -1;
  else if (CntRewindTable(xp->g, tdbp)) {
    table->status= STATUS_NOT_FOUND;
    rc= -1;
  } else
    rc= rnd_next(buf);

  DBUG_RETURN(rc);
} // end of index_first


#ifdef NOT_USED
/**
  @brief
  index_last() asks for the last key in the index.

    @details
  Called from opt_range.cc, opt_sum.cc, sql_handler.cc, and sql_select.cc.

    @see
  opt_range.cc, opt_sum.cc, sql_handler.cc and sql_select.cc
*/
int ha_connect::index_last(uchar *buf)
{
  DBUG_ENTER("ha_connect::index_last");
  DBUG_RETURN(HA_ERR_WRONG_COMMAND);
}
#endif // NOT_USED


/****************************************************************************/
/*  This is called to get more rows having the same index value.            */
/****************************************************************************/
int ha_connect::index_next_same(uchar *buf, const uchar *key, uint keylen)
{
  int rc;
  DBUG_ENTER("ha_connect::index_next_same");
//statistic_increment(ha_read_next_count, &LOCK_status);

  if (!indexing)
    rc= rnd_next(buf);
  else if (indexing > 0)
    rc= ReadIndexed(buf, OP_SAME);
  else
    rc= -1;

  DBUG_RETURN(rc);
} // end of index_next_same


/**
  @brief
  rnd_init() is called when the system wants the storage engine to do a table
  scan. See the example in the introduction at the top of this file to see when
  rnd_init() is called.

    @details
  Called from filesort.cc, records.cc, sql_handler.cc, sql_select.cc, sql_table.cc,
  and sql_update.cc.

    @note
  We always call open and extern_lock/start_stmt before comming here.

    @see
  filesort.cc, records.cc, sql_handler.cc, sql_select.cc, sql_table.cc and sql_update.cc
*/
int ha_connect::rnd_init(bool scan)
{
  PGLOBAL g= ((table && table->in_use) ? GetPlug(table->in_use) :
              (xp) ? xp->g : NULL);
  DBUG_ENTER("ha_connect::rnd_init");

  if (xtrace)
    printf("%p in rnd_init: scan=%d\n", this, scan);

  if (g) {
    // Open the table if it was not opened yet (possible ???)
    if (!IsOpened()) {
      if (!table || xmod == MODE_INSERT)
        DBUG_RETURN(HA_ERR_INITIALIZATION);

      if (OpenTable(g, xmod == MODE_DELETE))
#if defined(MARIADB)
Alexander Barkov's avatar
Alexander Barkov committed
2454
        DBUG_RETURN(HA_ERR_INITIALIZATION);
2455
#else   // !MARIADB
Alexander Barkov's avatar
Alexander Barkov committed
2456
        DBUG_RETURN(HA_ERR_INTERNAL_ERROR);
2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513
#endif  // !MARIADB

    } else
      void(CntRewindTable(g, tdbp));      // Read from beginning

    } // endif g

  xp->nrd= xp->fnd= xp->nfd= 0;
  ftime(&xp->tb1);
  DBUG_RETURN(0);
} // end of rnd_init

/**
  @brief
  Not described.

  @note
  The previous version said:
  Stop scanning of table. Note that this may be called several times during
  execution of a sub select.
  =====> This has been moved to external lock to avoid closing subselect tables.
*/
int ha_connect::rnd_end()
{
  int rc= 0;
  DBUG_ENTER("ha_connect::rnd_end");

  // If this is called by a later query, the table may have
  // been already closed and the tdbp is not valid anymore.
//  if (tdbp && xp->last_query_id == valid_query_id)
//    rc= CloseTable(xp->g);

  DBUG_RETURN(rc);
} // end of rnd_end


/**
  @brief
  This is called for each row of the table scan. When you run out of records
  you should return HA_ERR_END_OF_FILE. Fill buff up with the row information.
  The Field structure for the table is the key to getting data into buf
  in a manner that will allow the server to understand it.

    @details
  Called from filesort.cc, records.cc, sql_handler.cc, sql_select.cc, sql_table.cc,
  and sql_update.cc.

    @see
  filesort.cc, records.cc, sql_handler.cc, sql_select.cc, sql_table.cc and sql_update.cc
*/
int ha_connect::rnd_next(uchar *buf)
{
  int rc;
  DBUG_ENTER("ha_connect::rnd_next");
//statistic_increment(ha_read_rnd_next_count, &LOCK_status);

#if !defined(MARIADB)
Alexander Barkov's avatar
Alexander Barkov committed
2514 2515
  if (!tdbp)   // MySQL ignores error from rnd_init
    DBUG_RETURN(HA_ERR_INTERNAL_ERROR);
2516 2517
#endif   // !MARIADB

Alexander Barkov's avatar
Alexander Barkov committed
2518 2519 2520 2521 2522 2523 2524
  if (tdbp->GetMode() == MODE_ANY) {
    // We will stop on next read
    if (!stop) {
      stop= true;
      DBUG_RETURN(RC_OK);
    } else
      DBUG_RETURN(HA_ERR_END_OF_FILE);
2525

Alexander Barkov's avatar
Alexander Barkov committed
2526
    } // endif Mode
2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608

  switch (CntReadNext(xp->g, tdbp)) {
    case RC_OK:
      rc= MakeRecord((char*)buf);
      break;
    case RC_EF:         // End of file
      rc= HA_ERR_END_OF_FILE;
      break;
    case RC_NF:         // Not found
      rc= HA_ERR_RECORD_DELETED;
      break;
    default:            // Read error
      printf("rnd_next CONNECT: %s\n", xp->g->Message);
      rc= (records()) ? HA_ERR_INTERNAL_ERROR : HA_ERR_END_OF_FILE;
      break;
    } // endswitch RC

#ifndef DBUG_OFF
  if (rc || !(xp->nrd++ % 16384)) {
    ftime(&xp->tb2);
    double elapsed= (double) (xp->tb2.time - xp->tb1.time)
      + ((double) (xp->tb2.millitm - xp->tb1.millitm) / 1000.0);
    DBUG_PRINT("rnd_next", ("rc=%d nrd=%u fnd=%u nfd=%u sec=%.3lf\n",
                             rc, xp->nrd, xp->fnd, xp->nfd, elapsed));
    xp->tb1= xp->tb2;
    xp->fnd= xp->nfd= 0;
    } // endif nrd
#endif

  table->status= (!rc) ? 0 : STATUS_NOT_FOUND;
  DBUG_RETURN(rc);
} // end of rnd_next


/**
  @brief
  position() is called after each call to rnd_next() if the data needs
  to be ordered. You can do something like the following to store
  the position:
    @code
  my_store_ptr(ref, ref_length, current_position);
    @endcode

    @details
  The server uses ref to store data. ref_length in the above case is
  the size needed to store current_position. ref is just a byte array
  that the server will maintain. If you are using offsets to mark rows, then
  current_position should be the offset. If it is a primary key like in
  BDB, then it needs to be a primary key.

  Called from filesort.cc, sql_select.cc, sql_delete.cc, and sql_update.cc.

    @see
  filesort.cc, sql_select.cc, sql_delete.cc and sql_update.cc
*/
void ha_connect::position(const uchar *record)
{
  DBUG_ENTER("ha_connect::position");
  if (((PTDBASE)tdbp)->GetDef()->Indexable())
    my_store_ptr(ref, ref_length, (my_off_t)((PTDBASE)tdbp)->GetRecpos());
  DBUG_VOID_RETURN;
} // end of position


/**
  @brief
  This is like rnd_next, but you are given a position to use
  to determine the row. The position will be of the type that you stored in
  ref. You can use my_get_ptr(pos,ref_length) to retrieve whatever key
  or position you saved when position() was called.

    @details
  Called from filesort.cc, records.cc, sql_insert.cc, sql_select.cc, and sql_update.cc.

    @note
  Is this really useful? It was never called even when sorting.

    @see
  filesort.cc, records.cc, sql_insert.cc, sql_select.cc and sql_update.cc
*/
int ha_connect::rnd_pos(uchar *buf, uchar *pos)
{
Alexander Barkov's avatar
Alexander Barkov committed
2609
  int     rc;
2610 2611 2612
  PTDBASE tp= (PTDBASE)tdbp;
  DBUG_ENTER("ha_connect::rnd_pos");

Alexander Barkov's avatar
Alexander Barkov committed
2613 2614 2615
  if (!tp->SetRecpos(xp->g, (int)my_get_ptr(pos, ref_length)))
    rc= rnd_next(buf);
  else
2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661
    rc= HA_ERR_KEY_NOT_FOUND;

  DBUG_RETURN(rc);
} // end of rnd_pos


/**
  @brief
  ::info() is used to return information to the optimizer. See my_base.h for
  the complete description.

    @details
  Currently this table handler doesn't implement most of the fields really needed.
  SHOW also makes use of this data.

  You will probably want to have the following in your code:
    @code
  if (records < 2)
    records= 2;
    @endcode
  The reason is that the server will optimize for cases of only a single
  record. If, in a table scan, you don't know the number of records, it
  will probably be better to set records to two so you can return as many
  records as you need. Along with records, a few more variables you may wish
  to set are:
    records
    deleted
    data_file_length
    index_file_length
    delete_length
    check_time
  Take a look at the public variables in handler.h for more information.

  Called in filesort.cc, ha_heap.cc, item_sum.cc, opt_sum.cc, sql_delete.cc,
  sql_delete.cc, sql_derived.cc, sql_select.cc, sql_select.cc, sql_select.cc,
  sql_select.cc, sql_select.cc, sql_show.cc, sql_show.cc, sql_show.cc, sql_show.cc,
  sql_table.cc, sql_union.cc, and sql_update.cc.

    @see
  filesort.cc, ha_heap.cc, item_sum.cc, opt_sum.cc, sql_delete.cc, sql_delete.cc,
  sql_derived.cc, sql_select.cc, sql_select.cc, sql_select.cc, sql_select.cc,
  sql_select.cc, sql_show.cc, sql_show.cc, sql_show.cc, sql_show.cc, sql_table.cc,
  sql_union.cc and sql_update.cc
*/
int ha_connect::info(uint flag)
{
Alexander Barkov's avatar
Alexander Barkov committed
2662
  bool    pure= false;
2663 2664 2665 2666 2667 2668 2669 2670 2671 2672
  PGLOBAL g= GetPlug((table) ? table->in_use : NULL);

  DBUG_ENTER("ha_connect::info");

  if (xtrace)
    printf("%p In info: flag=%u valid_info=%d\n", this, flag, valid_info);

  if (!valid_info) {
    // tdbp must be available to get updated info
    if (!tdbp || xp->CheckQuery(valid_query_id)) {
Alexander Barkov's avatar
Alexander Barkov committed
2673 2674
      if (xmod == MODE_ANY) {               // Pure info, not a query
        pure= true;
2675
//      xmod= MODE_READ;
Alexander Barkov's avatar
Alexander Barkov committed
2676
        } // endif xmod
2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721

//    tdbp= OpenTable(g, xmod == MODE_DELETE);
      tdbp= GetTDB(g);
      } // endif tdbp

    valid_info= CntInfo(g, tdbp, &xinfo);
    } // endif valid_info

  if (flag & HA_STATUS_VARIABLE) {
    stats.records= xinfo.records;
    stats.deleted= 0;
    stats.data_file_length= xinfo.data_file_length;
    stats.index_file_length= 0;
    stats.delete_length= 0;
    stats.check_time= 0;
    stats.mean_rec_length= xinfo.mean_rec_length;
    } // endif HA_STATUS_VARIABLE

  if (flag & HA_STATUS_CONST) {
    // This is imported from the previous handler and must be reconsidered
    stats.max_data_file_length= LL(4294967295);
    stats.max_index_file_length= LL(4398046510080);
    stats.create_time= 0;
    data_file_name= xinfo.data_file_name;
    index_file_name= NULL;
//  sortkey= (uint) - 1;           // Table is not sorted
    ref_length= sizeof(int);      // Pointer size to row
    table->s->db_options_in_use= 03;
    stats.block_size= 1024;
    table->s->keys_in_use.set_prefix(table->s->keys);
    table->s->keys_for_keyread= table->s->keys_in_use;
//  table->s->keys_for_keyread.subtract(table->s->read_only_keys);
    table->s->db_record_offset= 0;
    } // endif HA_STATUS_CONST

  if (flag & HA_STATUS_ERRKEY) {
    errkey= 0;
    } // endif HA_STATUS_ERRKEY

  if (flag & HA_STATUS_TIME)
    stats.update_time= 0;

  if (flag & HA_STATUS_AUTO)
    stats.auto_increment_value= 1;

Alexander Barkov's avatar
Alexander Barkov committed
2722 2723
  if (tdbp && pure)
    CloseTable(g);        // Not used anymore
2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775

  DBUG_RETURN(0);
} // end of info


/**
  @brief
  extra() is called whenever the server wishes to send a hint to
  the storage engine. The myisam engine implements the most hints.
  ha_innodb.cc has the most exhaustive list of these hints.

  @note
  This is not yet implemented for CONNECT.

  @see
  ha_innodb.cc
*/
int ha_connect::extra(enum ha_extra_function operation)
{
  DBUG_ENTER("ha_connect::extra");
  DBUG_RETURN(0);
} // end of extra


/**
  @brief
  Used to delete all rows in a table, including cases of truncate and cases where
  the optimizer realizes that all rows will be removed as a result of an SQL statement.

    @details
  Called from item_sum.cc by Item_func_group_concat::clear(),
  Item_sum_count_distinct::clear(), and Item_func_group_concat::clear().
  Called from sql_delete.cc by mysql_delete().
  Called from sql_select.cc by JOIN::reinit().
  Called from sql_union.cc by st_select_lex_unit::exec().

    @see
  Item_func_group_concat::clear(), Item_sum_count_distinct::clear() and
  Item_func_group_concat::clear() in item_sum.cc;
  mysql_delete() in sql_delete.cc;
  JOIN::reinit() in sql_select.cc and
  st_select_lex_unit::exec() in sql_union.cc.
*/
int ha_connect::delete_all_rows()
{
  int     rc= 0;
  PGLOBAL g= xp->g;
  DBUG_ENTER("ha_connect::delete_all_rows");

  // Close and reopen the table so it will be deleted
  rc= CloseTable(g);

Alexander Barkov's avatar
Alexander Barkov committed
2776 2777 2778 2779 2780
  if (!(OpenTable(g))) {
    if (CntDeleteRow(g, tdbp, true)) {
      printf("%s\n", g->Message);
      rc= HA_ERR_INTERNAL_ERROR;
      } // endif
2781

Alexander Barkov's avatar
Alexander Barkov committed
2782 2783
  } else
    rc= HA_ERR_INITIALIZATION;
2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817

  DBUG_RETURN(rc);
} // end of delete_all_rows

/**
  @brief
  This create a lock on the table. If you are implementing a storage engine
  that can handle transacations look at ha_berkely.cc to see how you will
  want to go about doing this. Otherwise you should consider calling flock()
  here. Hint: Read the section "locking functions for mysql" in lock.cc to understand
  this.

    @details
  Called from lock.cc by lock_external() and unlock_external(). Also called
  from sql_table.cc by copy_data_between_tables().

    @note
  Following what we did in the MySQL XDB handler, we use this call to actually
  physically open the table. This could be reconsider when finalizing this handler
  design, which means we have a better understanding of what MariaDB does.

    @see
  lock.cc by lock_external() and unlock_external() in lock.cc;
  the section "locking functions for mysql" in lock.cc;
  copy_data_between_tables() in sql_table.cc.
*/
int ha_connect::external_lock(THD *thd, int lock_type)
{
  int rc= 0;
  bool del= false;
  MODE newmode;
  PGLOBAL g= GetPlug(thd);
  DBUG_ENTER("ha_connect::external_lock");

Alexander Barkov's avatar
Alexander Barkov committed
2818
  if (xtrace)
2819 2820 2821 2822 2823 2824 2825
    printf("%p external_lock: lock_type=%d\n", this, lock_type);

  if (!g)
    DBUG_RETURN(-99);

  // Action will depend on lock_type
  switch (lock_type) {
2826
    case F_WRLCK:
2827 2828
      newmode= MODE_WRITE;
      break;
2829
    case F_RDLCK:
2830 2831
      newmode= MODE_READ;
      break;
2832
    case F_UNLCK:
2833 2834 2835 2836 2837 2838 2839 2840
    default:
      newmode= MODE_ANY;
    } // endswitch mode

  if (newmode == MODE_ANY) {
    // This is unlocking, do it by closing the table
    if (xp->CheckQueryID())
      rc= 2;          // Logical error ???
Alexander Barkov's avatar
Alexander Barkov committed
2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880
    else if (tdbp) {
      if (tdbp->GetMode() == MODE_ANY && *tdbp->GetName() == '#'
                                      && xp->tabp) {
        PDOSDEF defp1= (PDOSDEF)((PTDBASE)tdbp)->GetDef();
        PDOSDEF defp2= (PDOSDEF)xp->tabp->GetDef();
        PIXDEF  xp1, xp2, sxp;

        // Look for new created indexes
        for (xp1= defp1->GetIndx(); xp1; xp1= xp1->GetNext()) {
          for (xp2= defp2->GetIndx(); xp2; xp2= xp2->GetNext())
            if (!stricmp(xp1->GetName(), xp2->GetName()))
              break;        // Index already made

          if (!xp2) {
            // Here we do make the index on tabp
            sxp= xp1->GetNext();
            xp1->SetNext(NULL);
            xp->tabp->MakeIndex(g, xp1, true);
            xp1->SetNext(sxp);
            } // endif xp2

          } // endfor xp1

        // Look for dropped indexes
        for (xp2= defp2->GetIndx(); xp2; xp2= xp2->GetNext()) {
          for (xp1= defp1->GetIndx(); xp1; xp1= xp1->GetNext())
            if (!stricmp(xp1->GetName(), xp2->GetName()))
              break;        // Index not to drop

          if (!xp1) {
            // Here we erase the index file
            sxp= xp2->GetNext();
            xp2->SetNext(NULL);
            defp2->DeleteIndexFile(g, xp2);
            xp2->SetNext(sxp);
            } // endif xp1

          } // endfor xp2

        } // endif Mode
2881 2882

      rc= CloseTable(g);
Alexander Barkov's avatar
Alexander Barkov committed
2883
    } // endif tdbp
2884 2885 2886 2887

    DBUG_RETURN(rc);
    } // endif MODE_ANY

Alexander Barkov's avatar
Alexander Barkov committed
2888
  if (xtrace) {
2889
    printf("%p external_lock: cmdtype=%d\n", this, thd->lex->sql_command);
Alexander Barkov's avatar
Alexander Barkov committed
2890 2891
    printf("Cmd=%s\n", thd->query_string);
    } // endif xtrace
2892 2893

  // Next code is temporarily replaced until sql_command is set
Alexander Barkov's avatar
Alexander Barkov committed
2894
  stop= false;
2895

Alexander Barkov's avatar
Alexander Barkov committed
2896
  if (newmode == MODE_WRITE) {
2897 2898 2899 2900 2901
    switch (thd->lex->sql_command) {
      case SQLCOM_INSERT:
      case SQLCOM_CREATE_TABLE:
      case SQLCOM_LOAD:
      case SQLCOM_INSERT_SELECT:
Alexander Barkov's avatar
Alexander Barkov committed
2902 2903
        newmode= MODE_INSERT;
        break;
2904 2905
//    case SQLCOM_REPLACE:
//    case SQLCOM_REPLACE_SELECT:
Alexander Barkov's avatar
Alexander Barkov committed
2906
//      newmode= MODE_UPDATE;               // To be checked
2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917
//      break;
      case SQLCOM_DELETE:
      case SQLCOM_DELETE_MULTI:
        del= true;
      case SQLCOM_TRUNCATE:
        newmode= MODE_DELETE;
        break;
      case SQLCOM_UPDATE:
      case SQLCOM_UPDATE_MULTI:
        newmode= MODE_UPDATE;
        break;
Alexander Barkov's avatar
Alexander Barkov committed
2918
      case SQLCOM_SELECT:
2919 2920 2921
      case SQLCOM_OPTIMIZE:
        newmode= MODE_READ;
        break;
Alexander Barkov's avatar
Alexander Barkov committed
2922 2923
      case SQLCOM_DROP_TABLE:
      case SQLCOM_RENAME_TABLE:
2924 2925 2926 2927 2928
      case SQLCOM_ALTER_TABLE:
        newmode= MODE_ANY;
        break;
      case SQLCOM_DROP_INDEX:
      case SQLCOM_CREATE_INDEX:
Alexander Barkov's avatar
Alexander Barkov committed
2929 2930
        newmode= MODE_ANY;
        stop= true;
2931 2932
        break;
      default:
Alexander Barkov's avatar
Alexander Barkov committed
2933 2934
        printf("Unsupported sql_command=%d", thd->lex->sql_command);
        sprintf(g->Message, "Unsupported sql_command=%d", thd->lex->sql_command);
2935 2936 2937
        DBUG_RETURN(HA_ERR_INTERNAL_ERROR);
      } // endswitch newmode

Alexander Barkov's avatar
Alexander Barkov committed
2938
  } else if (newmode == MODE_READ) {
2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950
    switch (thd->lex->sql_command) {
      case SQLCOM_INSERT:
      case SQLCOM_CREATE_TABLE:
      case SQLCOM_LOAD:
      case SQLCOM_INSERT_SELECT:
//    case SQLCOM_REPLACE:
//    case SQLCOM_REPLACE_SELECT:
      case SQLCOM_DELETE:
      case SQLCOM_DELETE_MULTI:
      case SQLCOM_TRUNCATE:
      case SQLCOM_UPDATE:
      case SQLCOM_UPDATE_MULTI:
Alexander Barkov's avatar
Alexander Barkov committed
2951
      case SQLCOM_SELECT:
2952 2953 2954 2955
      case SQLCOM_OPTIMIZE:
        break;
      case SQLCOM_DROP_INDEX:
      case SQLCOM_CREATE_INDEX:
Alexander Barkov's avatar
Alexander Barkov committed
2956 2957 2958
        stop= true;
      case SQLCOM_DROP_TABLE:
      case SQLCOM_RENAME_TABLE:
2959 2960 2961 2962
      case SQLCOM_ALTER_TABLE:
        newmode= MODE_ANY;
        break;
      default:
Alexander Barkov's avatar
Alexander Barkov committed
2963 2964
        printf("Unsupported sql_command=%d", thd->lex->sql_command);
        sprintf(g->Message, "Unsupported sql_command=%d", thd->lex->sql_command);
2965 2966 2967
        DBUG_RETURN(HA_ERR_INTERNAL_ERROR);
      } // endswitch newmode

Alexander Barkov's avatar
Alexander Barkov committed
2968
  } // endif's newmode
2969 2970 2971 2972 2973 2974


  if (xtrace)
    printf("New mode=%d\n", newmode);

  // If this is the start of a new query, cleanup the previous one
Alexander Barkov's avatar
Alexander Barkov committed
2975
  if (xp->CheckCleanup()) {
2976
    tdbp= NULL;
Alexander Barkov's avatar
Alexander Barkov committed
2977 2978
    valid_info= false;
    } // endif CheckCleanup
2979 2980 2981 2982 2983

  if (xtrace)
    printf("Calling CntCheckDB db=%s\n", GetDBName(NULL));

  // Set or reset the good database environment
Alexander Barkov's avatar
Alexander Barkov committed
2984
  if (CntCheckDB(g, this, GetDBName(NULL))) {
2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143
    printf("%p external_lock: %s\n", this, g->Message);
    rc= HA_ERR_INTERNAL_ERROR;
  // This can NOT be called without open called first, but
  // the table can have been closed since then
  } else if (!tdbp || xp->CheckQuery(valid_query_id) || xmod != newmode) {
    if (tdbp)
      CloseTable(g);

    xmod= newmode;

    if (!table)
      rc= 3;          // Logical error

    // Delay open until used fields are known
  } // endif tdbp

  if (xtrace)
    printf("external_lock: rc=%d\n", rc);

  DBUG_RETURN(rc);
} // end of external_lock


/**
  @brief
  The idea with handler::store_lock() is: The statement decides which locks
  should be needed for the table. For updates/deletes/inserts we get WRITE
  locks, for SELECT... we get read locks.

    @details
  Before adding the lock into the table lock handler (see thr_lock.c),
  mysqld calls store lock with the requested locks. Store lock can now
  modify a write lock to a read lock (or some other lock), ignore the
  lock (if we don't want to use MySQL table locks at all), or add locks
  for many tables (like we do when we are using a MERGE handler).

  Berkeley DB, for example, changes all WRITE locks to TL_WRITE_ALLOW_WRITE
  (which signals that we are doing WRITES, but are still allowing other
  readers and writers).

  When releasing locks, store_lock() is also called. In this case one
  usually doesn't have to do anything.

  In some exceptional cases MySQL may send a request for a TL_IGNORE;
  This means that we are requesting the same lock as last time and this
  should also be ignored. (This may happen when someone does a flush
  table when we have opened a part of the tables, in which case mysqld
  closes and reopens the tables and tries to get the same locks at last
  time). In the future we will probably try to remove this.

  Called from lock.cc by get_lock_data().

    @note
  In this method one should NEVER rely on table->in_use, it may, in fact,
  refer to a different thread! (this happens if get_lock_data() is called
  from mysql_lock_abort_for_thread() function)

    @see
  get_lock_data() in lock.cc
*/
THR_LOCK_DATA **ha_connect::store_lock(THD *thd,
                                       THR_LOCK_DATA **to,
                                       enum thr_lock_type lock_type)
{
  if (lock_type != TL_IGNORE && lock.type == TL_UNLOCK)
    lock.type=lock_type;
  *to++ = &lock;
  return to;
}


/**
  @brief
  Used to delete a table. By the time delete_table() has been called all
  opened references to this table will have been closed (and your globally
  shared references released). The variable name will just be the name of
  the table. You will need to remove any files you have created at this point.

    @details
  If you do not implement this, the default delete_table() is called from
  handler.cc and it will delete all files with the file extensions returned
  by bas_ext().

  Called from handler.cc by delete_table and ha_create_table(). Only used
  during create if the table_flag HA_DROP_BEFORE_CREATE was specified for
  the storage engine.

    @see
  delete_table and ha_create_table() in handler.cc
*/
int ha_connect::delete_table(const char *name)
{
  DBUG_ENTER("ha_connect::delete_table");
  /* This is not implemented but we want someone to be able that it works. */
  DBUG_RETURN(0);
}


/**
  @brief
  Given a starting key and an ending key, estimate the number of rows that
  will exist between the two keys.

  @details
  end_key may be empty, in which case determine if start_key matches any rows.

  Called from opt_range.cc by check_quick_keys().

  @see
  check_quick_keys() in opt_range.cc
*/
ha_rows ha_connect::records_in_range(uint inx, key_range *min_key,
                                               key_range *max_key)
{
  ha_rows rows;
  DBUG_ENTER("ha_connect::records_in_range");

  if (indexing < 0 || inx != active_index)
    index_init(inx, false);

  if (xtrace)
    printf("records_in_range: inx=%d indexing=%d\n", inx, indexing);

  if (indexing > 0) {
    int          nval;
    uint         len[2];
    const uchar *key[2];
    bool         incl[2];
    key_part_map kmap[2];

    key[0]= (min_key) ? min_key->key : NULL;
    key[1]= (max_key) ? max_key->key : NULL;
    len[0]= (min_key) ? min_key->length : 0;
    len[1]= (max_key) ? max_key->length : 0;
    incl[0]= (min_key) ? (min_key->flag == HA_READ_KEY_EXACT) : false;
    incl[1]= (max_key) ? (max_key->flag == HA_READ_AFTER_KEY) : false;
    kmap[0]= (min_key) ? min_key->keypart_map : 0;
    kmap[1]= (max_key) ? max_key->keypart_map : 0;

    if ((nval= CntIndexRange(xp->g, tdbp, key, len, incl, kmap)) < 0)
      rows= HA_POS_ERROR;
    else
      rows= (ha_rows)nval;

  } else if (indexing < 0)
    rows= HA_POS_ERROR;
  else
    rows= 100000000;        // Don't use missing index

  DBUG_RETURN(rows);
} // end of records_in_range

/**
  Store field definition for create.

  @return
    Return 0 if ok
*/

Alexander Barkov's avatar
Alexander Barkov committed
3144
bool ha_connect::add_fields(THD *thd, void *alt_info,
3145 3146
           LEX_STRING *field_name,
           enum_field_types type,
Alexander Barkov's avatar
Alexander Barkov committed
3147 3148 3149
           char *length, char *decimals,
           uint type_modifier,
//         Item *default_value, Item *on_update_value,
3150
           LEX_STRING *comment,
Alexander Barkov's avatar
Alexander Barkov committed
3151 3152
//         char *change,
//         List<String> *interval_list,
3153
           CHARSET_INFO *cs,
Alexander Barkov's avatar
Alexander Barkov committed
3154 3155
//         uint uint_geom_type,
           void *vcolinfo,
3156 3157 3158 3159 3160
           engine_option_value *create_options)
{
  register Create_field *new_field;
  LEX  *lex= thd->lex;
  Alter_info *alter_info= (Alter_info*)alt_info;
Alexander Barkov's avatar
Alexander Barkov committed
3161
  Virtual_column_info *vcol_info= (Virtual_column_info *)vcolinfo;
3162 3163 3164 3165 3166 3167 3168

  DBUG_ENTER("ha_connect::add_fields");

  if (check_string_char_length(field_name, "", NAME_CHAR_LEN,
                               system_charset_info, 1))
  {
    my_error(ER_TOO_LONG_IDENT, MYF(0), field_name->str); /* purecov: inspected */
Alexander Barkov's avatar
Alexander Barkov committed
3169
    DBUG_RETURN(1);       /* purecov: inspected */
3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194
  }
#if 0
  if (type_modifier & PRI_KEY_FLAG)
  {
    Key *key;
    lex->col_list.push_back(new Key_part_spec(*field_name, 0));
    key= new Key(Key::PRIMARY, null_lex_str,
                      &default_key_create_info,
                      0, lex->col_list, NULL);
    alter_info->key_list.push_back(key);
    lex->col_list.empty();
  }
  if (type_modifier & (UNIQUE_FLAG | UNIQUE_KEY_FLAG))
  {
    Key *key;
    lex->col_list.push_back(new Key_part_spec(*field_name, 0));
    key= new Key(Key::UNIQUE, null_lex_str,
                 &default_key_create_info, 0,
                 lex->col_list, NULL);
    alter_info->key_list.push_back(key);
    lex->col_list.empty();
  }

  if (default_value)
  {
Alexander Barkov's avatar
Alexander Barkov committed
3195
    /*
3196 3197
      Default value should be literal => basic constants =>
      no need fix_fields()
Alexander Barkov's avatar
Alexander Barkov committed
3198 3199

      We allow only one function as part of default value -
3200 3201
      NOW() as default for TIMESTAMP type.
    */
Alexander Barkov's avatar
Alexander Barkov committed
3202
    if (default_value->type() == Item::FUNC_ITEM &&
3203 3204 3205 3206 3207 3208 3209 3210 3211 3212
        !(((Item_func*)default_value)->functype() == Item_func::NOW_FUNC &&
         type == MYSQL_TYPE_TIMESTAMP))
    {
      my_error(ER_INVALID_DEFAULT, MYF(0), field_name->str);
      DBUG_RETURN(1);
    }
    else if (default_value->type() == Item::NULL_ITEM)
    {
      default_value= 0;
      if ((type_modifier & (NOT_NULL_FLAG | AUTO_INCREMENT_FLAG)) ==
Alexander Barkov's avatar
Alexander Barkov committed
3213
    NOT_NULL_FLAG)
3214
      {
Alexander Barkov's avatar
Alexander Barkov committed
3215 3216
  my_error(ER_INVALID_DEFAULT, MYF(0), field_name->str);
  DBUG_RETURN(1);
3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256
      }
    }
    else if (type_modifier & AUTO_INCREMENT_FLAG)
    {
      my_error(ER_INVALID_DEFAULT, MYF(0), field_name->str);
      DBUG_RETURN(1);
    }
  }

  if (on_update_value && type != MYSQL_TYPE_TIMESTAMP)
  {
    my_error(ER_INVALID_ON_UPDATE, MYF(0), field_name->str);
    DBUG_RETURN(1);
  }
#endif // 0

  if (!(new_field= new Create_field()) ||
      new_field->init(thd, field_name->str, type, length, decimals, type_modifier,
                      NULL, NULL, comment, NULL,
                      NULL, cs, 0, vcol_info,
                      create_options))
    DBUG_RETURN(1);

  alter_info->create_list.push_back(new_field);
//lex->last_field=new_field;
  DBUG_RETURN(0);
}

/**
  @brief
  pre_create() is called when creating a table with no columns.

  @details
  When pre_create() is called  the .frm file have not already been
  created. You can overwrite some definitions at this point but the
  main purpose of it is to define the columns for some table types.

  @note
  Not really implemented yet.
*/
3257
bool ha_connect::pre_create(THD *thd, void *crt_info, void *alt_info)
3258
{
3259 3260 3261 3262 3263 3264 3265
  char    ttp= '?', spc= ',', qch= 0, *typn= "DOS";
  char   *fn, *dsn, *tab, *db, *host, *user, *pwd, *prt, *sep;
#if defined(WIN32)
  char   *nsp= NULL, *cls= NULL;
#endif   // WIN32
  int     port= MYSQL_PORT, hdr= 0, mxr= 0;
  bool    ok= false;
3266
  LEX    *lex= thd->lex;
3267
  HA_CREATE_INFO *create_info= (HA_CREATE_INFO *)crt_info;
3268 3269 3270
  engine_option_value *pov;
  PQRYRES qrp;
  PCOLRES crp;
Alexander Barkov's avatar
Alexander Barkov committed
3271
  PGLOBAL g= GetPlug(thd);
3272

3273 3274 3275 3276 3277 3278 3279
  fn= dsn= tab= db= host= user= pwd= prt= sep= NULL;

  if (g) {
    // Set default values
    tab= (char*)create_info->alias;
    db= thd->db;
  } else
3280 3281
    return true;

3282 3283 3284 3285 3286 3287
  // Get the useful create options
  for (pov= create_info->option_list; pov; pov= pov->next)
    if (!stricmp(pov->name.str, "table_type")) {
      typn= pov->value.str;
      ttp= GetTypeID(typn);
    } else if (!stricmp(pov->name.str, "file_name")) {
3288
      fn= pov->value.str;
3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312
    } else if (!stricmp(pov->name.str, "tabname")) {
      tab= pov->value.str;
    } else if (!stricmp(pov->name.str, "db_name")) {
      db= pov->value.str;
    } else if (!stricmp(pov->name.str, "sep_char")) {
      sep= pov->value.str;
      spc= (!strcmp(sep, "\\t")) ? '\t' : *sep;
    } else if (!stricmp(pov->name.str, "qchar")) {
      qch= *pov->value.str;
    } else if (!stricmp(pov->name.str, "quoted")) {
      if (!qch)
        qch= '"';

    } else if (!stricmp(pov->name.str, "header")) {
      hdr= atoi(pov->value.str);
    } else if (!stricmp(pov->name.str, "option_list")) {
      host= GetListOption("host", pov->value.str, "localhost");
      user= GetListOption("user", pov->value.str, "root");
      pwd= GetListOption("password", pov->value.str);
      prt= GetListOption("port", pov->value.str);
      port= (prt) ? atoi(prt) : MYSQL_PORT;
#if defined(WIN32)
      nsp= GetListOption("namespace", pov->value.str);
      cls= GetListOption("class", pov->value.str);
Alexander Barkov's avatar
Alexander Barkov committed
3313
#endif   // WIN32
3314 3315 3316 3317
      mxr= atoi(GetListOption("maxerr", pov->value.str, "0"));
    } // endelse option_list

  switch (ttp) {
Alexander Barkov's avatar
Alexander Barkov committed
3318
#if defined(ODBC_SUPPORT)
3319 3320 3321 3322 3323 3324 3325
    case 'O':       // ODBC
      if (!(dsn= create_info->connect_string.str))
        sprintf(g->Message, "Missing %s connection string", typn);
      else
        ok= true;

      break;
Alexander Barkov's avatar
Alexander Barkov committed
3326
#endif   // ODBC_SUPPORT
3327 3328 3329 3330 3331 3332 3333 3334
    case 'A':       // DBF
    case 'C':       // CSV
      if (!fn)
        sprintf(g->Message, "Missing %s file name", typn);
      else
        ok= true;

      break;
Alexander Barkov's avatar
Alexander Barkov committed
3335
#if defined(MYSQL_SUPPORT)
3336 3337 3338 3339 3340 3341
    case 'Y':       // MYSQL
      if (!user)
        user= "root";       // Avoid crash

      ok= true;
      break;
Alexander Barkov's avatar
Alexander Barkov committed
3342
#endif   // MYSQL_SUPPORT
3343 3344 3345 3346 3347 3348 3349 3350
#if defined(WIN32)
    case 'W':       // WMI
      ok= true;
      break;
#endif   // WIN32
    default:
      sprintf(g->Message, "Cannot get column info for table type %s", typn);
    } // endif ttp
3351

3352 3353
  if (ok) {
    char *length, *decimals, *nm, *rem;
3354 3355 3356 3357 3358 3359 3360 3361 3362 3363
    int   i, len, dec;
    bool  b;
    LEX_STRING *comment, *name;
    enum_field_types type;
    PDBUSER dup= PlgGetUser(g);
    PCATLG  cat= (dup) ? dup->Catalog : NULL;

    if (cat)
      cat->SetDataPath(g, thd->db);
    else
3364
      return true;           // Should never happen
3365

3366 3367 3368 3369
    switch (ttp) {
      case 'A':
        qrp= DBFColumns(g, fn, false);
        break;
Alexander Barkov's avatar
Alexander Barkov committed
3370
#if defined(ODBC_SUPPORT)
3371 3372 3373
      case 'O':
        qrp= MyODBCCols(g, tab, dsn);
        break;
Alexander Barkov's avatar
Alexander Barkov committed
3374 3375
#endif   // ODBC_SUPPORT
#if defined(MYSQL_SUPPORT)
3376 3377 3378
      case 'Y':
        qrp= MyColumns(g, host, db, user, pwd, tab, NULL, port, false);
        break;
Alexander Barkov's avatar
Alexander Barkov committed
3379
#endif   // MYSQL_SUPPORT
3380 3381 3382 3383 3384 3385 3386 3387 3388
      case 'C':
        qrp= CSVColumns(g, fn, spc, qch, hdr, mxr);
        break;
#if defined(WIN32)
      case 'W':
        qrp= WMIColumns(g, nsp, cls);
        break;
#endif   // WIN32
      } // endswitch ttp
3389

3390
    if (!qrp) {
Alexander Barkov's avatar
Alexander Barkov committed
3391
      push_warning(thd, MYSQL_ERROR::WARN_LEVEL_WARN, 0, g->Message);
3392 3393
      return true;
      } // endif qrp
3394 3395 3396 3397

    for (i= 0; i < qrp->Nblin; i++) {
      crp = qrp->Colresp;                    // Column Name
      nm= crp->Kdata->GetCharValue(i);
Alexander Barkov's avatar
Alexander Barkov committed
3398
      name= thd->make_lex_string(NULL, nm, strlen(nm), true);
3399 3400 3401
      crp = crp->Next;                       // Data Type
      type= PLGtoMYSQL(crp->Kdata->GetIntValue(i), true);
      crp = crp->Next;                       // Type Name
3402
      crp = crp->Next;                       // Precision (length)
3403 3404 3405
      len= crp->Kdata->GetIntValue(i);
      length= (char*)PlugSubAlloc(g, NULL, 8);
      sprintf(length, "%d", len);
3406
      crp = crp->Next;                       // Length
3407 3408 3409 3410 3411 3412 3413 3414
      crp = crp->Next;                       // Scale (precision)

      if ((dec= crp->Kdata->GetIntValue(i))) {
        decimals= (char*)PlugSubAlloc(g, NULL, 8);
        sprintf(decimals, "%d", dec);
      } else
        decimals= NULL;

3415 3416 3417 3418 3419
      if ((crp= crp->Next) &&               // Remark (comment)
          (rem= crp->Kdata->GetCharValue(i)))
        comment= thd->make_lex_string(NULL, rem, strlen(rem), true);
      else
        comment= thd->make_lex_string(NULL, "", 0, true);
3420 3421 3422 3423

      // Now add the field
//    b= add_field_to_list(thd, &name, type, length, decimals,
//          0, NULL, NULL, comment, NULL, NULL, NULL, 0, NULL, NULL);
3424
      b= add_fields(thd, alt_info, name, type, length, decimals,
3425 3426 3427 3428 3429 3430
                    0, comment, NULL, NULL, NULL);
      } // endfor i

    return false;
    } // endif ttp

Alexander Barkov's avatar
Alexander Barkov committed
3431
  push_warning(thd, MYSQL_ERROR::WARN_LEVEL_WARN, 0, g->Message);
3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462
  return true;
} // end of pre_create

/**
  @brief
  create() is called to create a database. The variable name will have the name
  of the table.

  @details
  When create() is called you do not need to worry about
  opening the table. Also, the .frm file will have already been
  created so adjusting create_info is not necessary. You can overwrite
  the .frm file at this point if you wish to change the table
  definition, but there are no methods currently provided for doing
  so.

  Called from handle.cc by ha_create_table().

  @note
  Currently we do nothing here because we suppose that the PlugDB matching
  table already exists. At least we should check that the table definition
  for MariaDB exactly match the PlugDB one. Later we should make possible
  to entirely create a table from MariaDB.

  @see
  ha_create_table() in handle.cc
*/

int ha_connect::create(const char *name, TABLE *table_arg,
                       HA_CREATE_INFO *create_info)
{
Alexander Barkov's avatar
Alexander Barkov committed
3463 3464
  int     rc= RC_OK;
  bool    dbf;
3465
  Field* *field;
Alexander Barkov's avatar
Alexander Barkov committed
3466 3467
  Field  *fp;
  TABLE  *st= table;                       // Probably unuseful
3468
  PIXDEF  xdp, pxd= NULL, toidx= NULL;
Alexander Barkov's avatar
Alexander Barkov committed
3469
  PGLOBAL g= GetPlug(table_arg->in_use);
3470 3471

  DBUG_ENTER("ha_connect::create");
Alexander Barkov's avatar
Alexander Barkov committed
3472
  PTOS options= GetTableOptionStruct(table_arg);
3473 3474

  // CONNECT engine specific table options:
Alexander Barkov's avatar
Alexander Barkov committed
3475
  DBUG_ASSERT(options);
3476

Alexander Barkov's avatar
Alexander Barkov committed
3477 3478 3479 3480
  if (!g) {
    rc= HA_ERR_INTERNAL_ERROR;
    DBUG_RETURN(rc);
    } // endif g
3481

Alexander Barkov's avatar
Alexander Barkov committed
3482 3483
  // Check column types
  dbf= (options->type && !stricmp(options->type, "DBF"));
3484

Alexander Barkov's avatar
Alexander Barkov committed
3485 3486
  for (field= table_arg->field; *field; field++) {
    fp= *field;
3487 3488

#if defined(MARIADB)
Alexander Barkov's avatar
Alexander Barkov committed
3489 3490
    if (fp->vcol_info && !fp->stored_in_db)
      continue;            // This is a virtual column
3491 3492 3493
#endif   // MARIADB

    switch (fp->type()) {
Alexander Barkov's avatar
Alexander Barkov committed
3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504
      case MYSQL_TYPE_SHORT:
      case MYSQL_TYPE_LONG:
      case MYSQL_TYPE_FLOAT:
      case MYSQL_TYPE_DOUBLE:
      case MYSQL_TYPE_TIMESTAMP:
      case MYSQL_TYPE_DATE:
      case MYSQL_TYPE_TIME:
      case MYSQL_TYPE_DATETIME:
      case MYSQL_TYPE_YEAR:
      case MYSQL_TYPE_NEWDATE:
      case MYSQL_TYPE_VARCHAR:
3505
      case MYSQL_TYPE_LONGLONG:
Alexander Barkov's avatar
Alexander Barkov committed
3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545
        break;                     // Ok
      case MYSQL_TYPE_VAR_STRING:
      case MYSQL_TYPE_STRING:
      case MYSQL_TYPE_DECIMAL:
      case MYSQL_TYPE_NEWDECIMAL:
      case MYSQL_TYPE_INT24:
        break;                     // To be checked
      case MYSQL_TYPE_TINY:
      case MYSQL_TYPE_BIT:
      case MYSQL_TYPE_NULL:
      case MYSQL_TYPE_ENUM:
      case MYSQL_TYPE_SET:
      case MYSQL_TYPE_TINY_BLOB:
      case MYSQL_TYPE_MEDIUM_BLOB:
      case MYSQL_TYPE_LONG_BLOB:
      case MYSQL_TYPE_BLOB:
      case MYSQL_TYPE_GEOMETRY:
      default:
//      fprintf(stderr, "Unsupported type column %s\n", fp->field_name);
        sprintf(g->Message, "Unsupported type for column %s",
                            fp->field_name);
        rc= HA_ERR_INTERNAL_ERROR;
        my_printf_error(ER_UNKNOWN_ERROR,
                        "Unsupported type for column '%s'",
                        MYF(0), fp->field_name);
        DBUG_RETURN(rc);
      } // endswitch type


    if (dbf) {
      bool b= false;

      if ((b= strlen(fp->field_name) > 11))
        sprintf(g->Message, "DBF: Column name '%s' is too long (max=11)",
                            fp->field_name);
      else if ((b= fp->field_length > 255))
        sprintf(g->Message, "DBF: Column length too big for '%s' (max=255)",
                            fp->field_name);

      if (b) {
3546
        my_message(ER_UNKNOWN_ERROR, g->Message, MYF(0));
Alexander Barkov's avatar
Alexander Barkov committed
3547 3548 3549
        rc= HA_ERR_INTERNAL_ERROR;
        DBUG_RETURN(rc);
        } // endif b
3550

Alexander Barkov's avatar
Alexander Barkov committed
3551
      } // endif dbf
3552

Alexander Barkov's avatar
Alexander Barkov committed
3553
    } // endfor field
3554

Alexander Barkov's avatar
Alexander Barkov committed
3555 3556
  // Check whether indexes were specified
  table= table_arg;       // Used by called functions
3557 3558

  // Get the index definitions
Alexander Barkov's avatar
Alexander Barkov committed
3559 3560 3561
  for (int n= 0; (unsigned)n < table->s->keynames.count; n++) {
    if (xtrace)
      printf("Getting created index %d info\n", n + 1);
3562

Alexander Barkov's avatar
Alexander Barkov committed
3563
    xdp= GetIndexInfo(n);
3564 3565

    if (pxd)
Alexander Barkov's avatar
Alexander Barkov committed
3566 3567 3568
      pxd->SetNext(xdp);
    else
      toidx= xdp;
3569 3570 3571 3572

    pxd= xdp;
    } // endfor n

Alexander Barkov's avatar
Alexander Barkov committed
3573
  if (toidx) {
3574 3575 3576
    PDBUSER dup= PlgGetUser(g);
    PCATLG  cat= (dup) ? dup->Catalog : NULL;

Alexander Barkov's avatar
Alexander Barkov committed
3577
    DBUG_ASSERT(cat);
3578 3579 3580 3581

    if (cat)
      cat->SetDataPath(g, table_arg->in_use->db);

Alexander Barkov's avatar
Alexander Barkov committed
3582 3583 3584 3585 3586
    if ((rc= optimize(NULL, NULL))) {
      printf("Create rc=%d %s\n", rc, g->Message);
      rc= HA_ERR_INTERNAL_ERROR;
    } else
      CloseTable(g);
3587

Alexander Barkov's avatar
Alexander Barkov committed
3588
    } // endif toidx
3589

Alexander Barkov's avatar
Alexander Barkov committed
3590
  table= st;
3591
  DBUG_RETURN(rc);
Alexander Barkov's avatar
Alexander Barkov committed
3592
} // end of create
3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610


/**
  check_if_incompatible_data() called if ALTER TABLE can't detect otherwise
  if new and old definition are compatible

  @details If there are no other explicit signs like changed number of
  fields this function will be called by compare_tables()
  (sql/sql_tables.cc) to decide should we rewrite whole table or only .frm
  file.

*/

bool ha_connect::check_if_incompatible_data(HA_CREATE_INFO *info,
                                        uint table_changes)
{
//ha_table_option_struct *param_old, *param_new;
  DBUG_ENTER("ha_connect::check_if_incompatible_data");
Alexander Barkov's avatar
Alexander Barkov committed
3611
  // TO DO: implement it.
3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625
  DBUG_RETURN(COMPATIBLE_DATA_YES);
}


struct st_mysql_storage_engine connect_storage_engine=
{ MYSQL_HANDLERTON_INTERFACE_VERSION };

struct st_mysql_daemon unusable_connect=
{ MYSQL_DAEMON_INTERFACE_VERSION };

mysql_declare_plugin(connect)
{
  MYSQL_STORAGE_ENGINE_PLUGIN,
  &connect_storage_engine,
Alexander Barkov's avatar
Alexander Barkov committed
3626
  "CONNECT",
3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644
  "Olivier Bertrand",
  "Direct access to external data, including many file formats",
  PLUGIN_LICENSE_GPL,
  connect_init_func,                                /* Plugin Init */
  connect_done_func,                                /* Plugin Deinit */
  0x0001 /* 0.1 */,
  NULL,                                         /* status variables */
  NULL,                                         /* system variables */
  NULL,                                         /* config options */
  0,                                            /* flags */
}
mysql_declare_plugin_end;

#if defined(MARIADB)
maria_declare_plugin(connect)
{
  MYSQL_STORAGE_ENGINE_PLUGIN,
  &connect_storage_engine,
Alexander Barkov's avatar
Alexander Barkov committed
3645
  "CONNECT",
3646 3647 3648 3649 3650
  "Olivier Bertrand",
  "Direct access to external data, including many file formats",
  PLUGIN_LICENSE_GPL,
  connect_init_func,                            /* Plugin Init */
  connect_done_func,                            /* Plugin Deinit */
Alexander Barkov's avatar
Alexander Barkov committed
3651
  0x0001,                                       /* version number (0.1) */
3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693
  NULL,                                         /* status variables */
  NULL,                                         /* system variables */
  "0.1",                                        /* string version */
  MariaDB_PLUGIN_MATURITY_EXPERIMENTAL          /* maturity */
},
{
  MYSQL_DAEMON_PLUGIN,
  &unusable_connect,
  "UNUSABLE",
  "Olivier Bertrand",
  "Unusable Daemon",
  PLUGIN_LICENSE_PROPRIETARY,
  NULL,                                         /* Plugin Init */
  NULL,                                         /* Plugin Deinit */
  0x0101,                                       /* version number (1.1) */
  NULL,                                         /* status variables */
  NULL,                                         /* system variables */
  "1.01.00.000" ,                               /* version, as a string */
  MariaDB_PLUGIN_MATURITY_EXPERIMENTAL          /* maturity */
}
maria_declare_plugin_end;
#endif   // MARIADB

#if defined(WIN32)
/**************************************************************************/
/*  DllMain                                                               */
/**************************************************************************/
bool APIENTRY DllMain(HINSTANCE hInst, ULONG ulReason, PCONTEXT pctx)
  {
  switch (ulReason) {
    case DLL_PROCESS_ATTACH:
      printf("CONNECT Engine loaded...\n");
      GetCurrentDirectory(sizeof(connectini), connectini);
      strcat(connectini, "\\connect.ini");

      if ((xtrace= GetPrivateProfileInt("CONNECT", "Trace", 0, connectini))) {
        printf("connectini=%s xtrace=%d\n", connectini, xtrace);
        printf("plgini=%s\n", plgini);
        printf("plgxini=%s\n", plgxini);
        printf("nmfile=%s\n", nmfile);
        printf("pdebug=%s\n", pdebug);
        printf("version=%s\n", version);
Alexander Barkov's avatar
Alexander Barkov committed
3694
        trace= xtrace;
3695 3696
        } // endif xtrace
#if defined(XML_SUPPORT) && !defined(NOXML2)
Alexander Barkov's avatar
Alexander Barkov committed
3697
      XmlInitParserLib();
3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732
#endif   // XML_SUPPORT  &&         !NOXML2)
      break;
    case DLL_PROCESS_DETACH:
#if defined(XML_SUPPORT) && !defined(NOXML2)
      XmlCleanupParserLib();
#endif   // XML_SUPPORT  &&         !NOXML2)
      break;
    case DLL_THREAD_ATTACH:
      break;
    case DLL_THREAD_DETACH:
      break;
    default:
      break;
    } // endswitch ulReason

  return true;
  } // end of DllMain
#else   // !WIN32
/**************************************************************************/
/*  Library's initialization function.                                    */
/**************************************************************************/
void __attribute__((constructor)) init()
  {
  printf("CONNECT Engine loaded...\n");
  getcwd(connectini, sizeof(connectini));
  strcat(connectini, "/connect.ini");
  printf("connectini=%s\n", connectini);

  if ((xtrace= GetPrivateProfileInt("CONNECT", "Trace", 0, connectini))) {
    printf("connectini=%s xtrace=%d\n", connectini, xtrace);
    printf("plgini=%s\n", plgini);
    printf("plgxini=%s\n", plgxini);
    printf("nmfile=%s\n", nmfile);
    printf("pdebug=%s\n", pdebug);
    printf("version=%s\n", version);
Alexander Barkov's avatar
Alexander Barkov committed
3733
    trace= xtrace;
3734 3735 3736
    } // endif xtrace

#if defined(XML_SUPPORT) && !defined(NOXML2)
Alexander Barkov's avatar
Alexander Barkov committed
3737
    XmlInitParserLib();
3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751
#endif   // XML_SUPPORT  &&         !NOXML2)
  } // end of init

/**************************************************************************/
/*  Library's cleanup function                                            */
/**************************************************************************/
void __attribute__((destructor)) fini()
  {
#if defined(XML_SUPPORT) && !defined(NOXML2)
  XmlCleanupParserLib();
#endif   // XML_SUPPORT  &&         !NOXML2)
  } // end of fini
#endif  // !WIN32