~drizzle-trunk/drizzle/development

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
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
65
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
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
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
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
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
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
/* - mode: c; c-basic-offset: 2; indent-tabs-mode: nil; -*-
 *  vim:expandtab:shiftwidth=2:tabstop=2:smarttab:
 *
 *  Copyright (C) 2010 Brian Aker
 *
 *  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; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  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., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include "config.h"

#include "plugin/schema_engine/schema.h"
#include "drizzled/db.h"
#include "drizzled/sql_table.h"
#include "drizzled/global_charset_info.h"
#include "drizzled/charset.h"
#include "drizzled/charset_info.h"
#include "drizzled/cursor.h"

#include "drizzled/internal/my_sys.h"

#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>

#include <google/protobuf/io/zero_copy_stream.h>
#include <google/protobuf/io/zero_copy_stream_impl.h>

#include <iostream>
#include <fstream>
#include <string>

using namespace std;
using namespace drizzled;

// This should always be the same value as GLOBAL_TEMPORARY_EXT but be
// CASE_UP. --Brian
static SchemaIdentifier TEMPORARY_IDENTIFIER(".TEMPORARY");

#define MY_DB_OPT_FILE "db.opt"
#define DEFAULT_FILE_EXTENSION ".dfe" // Deep Fried Elephant

Schema::Schema():
  drizzled::plugin::StorageEngine("schema",
                                  HTON_ALTER_NOT_SUPPORTED |
                                  HTON_HAS_SCHEMA_DICTIONARY |
                                  HTON_SKIP_STORE_LOCK |
                                  HTON_TEMPORARY_NOT_SUPPORTED),
  schema_cache_filled(false)
{
  table_definition_ext= DEFAULT_FILE_EXTENSION;
  pthread_rwlock_init(&schema_lock, NULL);
  prime();
}

Schema::~Schema()
{
  pthread_rwlock_destroy(&schema_lock);
}

void Schema::prime()
{
  CachedDirectory directory(data_home, CachedDirectory::DIRECTORY);
  CachedDirectory::Entries files= directory.getEntries();

  pthread_rwlock_wrlock(&schema_lock);

  for (CachedDirectory::Entries::iterator fileIter= files.begin();
       fileIter != files.end(); fileIter++)
  {
    CachedDirectory::Entry *entry= *fileIter;
    message::Schema schema_message;

    if (not entry->filename.compare(GLOBAL_TEMPORARY_EXT))
      continue;

    if (readSchemaFile(entry->filename, schema_message))
    {
      SchemaIdentifier schema_identifier(schema_message.name());

      pair<SchemaCache::iterator, bool> ret=
        schema_cache.insert(make_pair(schema_identifier.getPath(), schema_message));

      if (ret.second == false)
     {
        abort(); // If this has happened, something really bad is going down.
      }
    }
  }
  pthread_rwlock_unlock(&schema_lock);
}

void Schema::doGetSchemaIdentifiers(SchemaIdentifierList &set_of_names)
{
  if (not pthread_rwlock_rdlock(&schema_lock))
  {
    for (SchemaCache::iterator iter= schema_cache.begin();
         iter != schema_cache.end();
         iter++)
    {
      set_of_names.push_back(SchemaIdentifier((*iter).second.name()));
    }
    pthread_rwlock_unlock(&schema_lock);

    return;
  }

  // If for some reason getting a lock should fail, we resort to disk

  CachedDirectory directory(data_home, CachedDirectory::DIRECTORY);

  CachedDirectory::Entries files= directory.getEntries();

  for (CachedDirectory::Entries::iterator fileIter= files.begin();
       fileIter != files.end(); fileIter++)
  {
    CachedDirectory::Entry *entry= *fileIter;
    set_of_names.push_back(entry->filename);
  }
}

bool Schema::doGetSchemaDefinition(SchemaIdentifier &schema_identifier, message::Schema &schema_message)
{
  if (not pthread_rwlock_rdlock(&schema_lock))
  {
    SchemaCache::iterator iter= schema_cache.find(schema_identifier.getPath());

    if (iter != schema_cache.end())
    {
      schema_message.CopyFrom(((*iter).second));
      pthread_rwlock_unlock(&schema_lock);
      return true;
    }
    pthread_rwlock_unlock(&schema_lock);

    return false;
  }

  // Fail to disk based means
  return readSchemaFile(schema_identifier.getPath(), schema_message);
}

bool Schema::doCreateSchema(const drizzled::message::Schema &schema_message)
{
  SchemaIdentifier schema_identifier(schema_message.name());

  if (mkdir(schema_identifier.getPath().c_str(), 0777) == -1)
    return false;

  if (not writeSchemaFile(schema_identifier, schema_message))
  {
    rmdir(schema_identifier.getPath().c_str());

    return false;
  }

  if (not pthread_rwlock_wrlock(&schema_lock))
  {
      pair<SchemaCache::iterator, bool> ret=
        schema_cache.insert(make_pair(schema_identifier.getPath(), schema_message));


      if (ret.second == false)
      {
        abort(); // If this has happened, something really bad is going down.
      }
    pthread_rwlock_unlock(&schema_lock);
  }

  return true;
}

bool Schema::doDropSchema(SchemaIdentifier &schema_identifier)
{
  message::Schema schema_message;

  string schema_file(schema_identifier.getPath());
  schema_file.append(1, FN_LIBCHAR);
  schema_file.append(MY_DB_OPT_FILE);

  if (not doGetSchemaDefinition(schema_identifier, schema_message))
    return false;

  // No db.opt file, no love from us.
  if (access(schema_file.c_str(), F_OK))
  {
    perror(schema_file.c_str());
    return false;
  }

  if (unlink(schema_file.c_str()))
  {
    perror(schema_file.c_str());
    return false;
  }

  if (rmdir(schema_identifier.getPath().c_str()))
  {
    perror(schema_identifier.getPath().c_str());
    //@todo If this happens, we want a report of it. For the moment I dump
    //to stderr so I can catch it in Hudson.
    CachedDirectory dir(schema_identifier.getPath());
    cerr << dir;
  }

  if (not pthread_rwlock_wrlock(&schema_lock))
  {
    schema_cache.erase(schema_identifier.getPath());
    pthread_rwlock_unlock(&schema_lock);
  }

  return true;
}

bool Schema::doAlterSchema(const drizzled::message::Schema &schema_message)
{
  SchemaIdentifier schema_identifier(schema_message.name());

  if (access(schema_identifier.getPath().c_str(), F_OK))
    return false;

  if (writeSchemaFile(schema_identifier, schema_message))
  {
    if (not pthread_rwlock_wrlock(&schema_lock))
    {
      schema_cache.erase(schema_identifier.getPath());

      pair<SchemaCache::iterator, bool> ret=
        schema_cache.insert(make_pair(schema_identifier.getPath(), schema_message));

      if (ret.second == false)
      {
        abort(); // If this has happened, something really bad is going down.
      }

      pthread_rwlock_unlock(&schema_lock);
    }
    else
    {
      abort(); // This would leave us out of sync, suck.
    }
  }

  return true;
}

/**
  path is path to database, not schema file 

  @note we do the rename to make it crash safe.
*/
bool Schema::writeSchemaFile(SchemaIdentifier &schema_identifier, const message::Schema &db)
{
  char schema_file_tmp[FN_REFLEN];
  string schema_file(schema_identifier.getPath());


  schema_file.append(1, FN_LIBCHAR);
  schema_file.append(MY_DB_OPT_FILE);

  snprintf(schema_file_tmp, FN_REFLEN, "%sXXXXXX", schema_file.c_str());

  int fd= mkstemp(schema_file_tmp);

  if (fd == -1)
  {
    perror(schema_file_tmp);

    return false;
  }

  if (not db.SerializeToFileDescriptor(fd))
  {
    my_error(ER_CORRUPT_SCHEMA_DEFINITION, MYF(0), schema_file.c_str(),
             db.InitializationErrorString().empty() ? "unknown" :  db.InitializationErrorString().c_str());

    if (close(fd) == -1)
      perror(schema_file_tmp);

    if (unlink(schema_file_tmp))
      perror(schema_file_tmp);

    return false;
  }

  if (close(fd) == -1)
  {
    perror(schema_file_tmp);

    if (unlink(schema_file_tmp))
      perror(schema_file_tmp);

    return false;
  }

  if (rename(schema_file_tmp, schema_file.c_str()) == -1)
  {
    if (unlink(schema_file_tmp))
      perror(schema_file_tmp);

    return false;
  }

  return true;
}


bool Schema::readSchemaFile(const std::string &schema_file_name, drizzled::message::Schema &schema_message)
{
  string db_opt_path(schema_file_name);

  /*
    Pass an empty file name, and the database options file name as extension
    to avoid table name to file name encoding.
  */
  db_opt_path.append(1, FN_LIBCHAR);
  db_opt_path.append(MY_DB_OPT_FILE);

  fstream input(db_opt_path.c_str(), ios::in | ios::binary);

  /**
    @note If parsing fails, either someone has done a "mkdir" or has deleted their opt file.
    So what do we do? We muddle through the adventure by generating 
    one with a name in it, and the charset set to the default.
  */
  if (input.good())
  {
    if (schema_message.ParseFromIstream(&input))
    {
      return true;
    }

    my_error(ER_CORRUPT_SCHEMA_DEFINITION, MYF(0), db_opt_path.c_str(),
             schema_message.InitializationErrorString().empty() ? "unknown" :  schema_message.InitializationErrorString().c_str());
  }
  else
  {
    perror(db_opt_path.c_str());
  }

  return false;
}

bool Schema::doCanCreateTable(drizzled::TableIdentifier &identifier)
{
  if (static_cast<SchemaIdentifier&>(identifier) == TEMPORARY_IDENTIFIER)
  {
    return false;
  }

  return true;
}

void Schema::doGetTableIdentifiers(drizzled::CachedDirectory&,
                                   drizzled::SchemaIdentifier&,
                                   drizzled::TableIdentifiers&)
{
}