2011-03-18 23:37:00 +01:00
|
|
|
// Copyright (c) 2011 The LevelDB Authors. All rights reserved.
|
|
|
|
// Use of this source code is governed by a BSD-style license that can be
|
|
|
|
// found in the LICENSE file. See the AUTHORS file for names of contributors.
|
|
|
|
|
|
|
|
#include "db/builder.h"
|
|
|
|
|
|
|
|
#include "db/filename.h"
|
|
|
|
#include "db/dbformat.h"
|
|
|
|
#include "db/table_cache.h"
|
|
|
|
#include "db/version_edit.h"
|
2011-03-30 20:35:40 +02:00
|
|
|
#include "leveldb/db.h"
|
|
|
|
#include "leveldb/env.h"
|
|
|
|
#include "leveldb/iterator.h"
|
2011-03-18 23:37:00 +01:00
|
|
|
|
|
|
|
namespace leveldb {
|
|
|
|
|
|
|
|
Status BuildTable(const std::string& dbname,
|
|
|
|
Env* env,
|
|
|
|
const Options& options,
|
|
|
|
TableCache* table_cache,
|
|
|
|
Iterator* iter,
|
2011-06-22 04:36:45 +02:00
|
|
|
FileMetaData* meta) {
|
2011-03-18 23:37:00 +01:00
|
|
|
Status s;
|
|
|
|
meta->file_size = 0;
|
|
|
|
iter->SeekToFirst();
|
|
|
|
|
|
|
|
std::string fname = TableFileName(dbname, meta->number);
|
|
|
|
if (iter->Valid()) {
|
2013-01-20 11:07:13 +01:00
|
|
|
unique_ptr<WritableFile> file;
|
2011-03-18 23:37:00 +01:00
|
|
|
s = env->NewWritableFile(fname, &file);
|
|
|
|
if (!s.ok()) {
|
|
|
|
return s;
|
|
|
|
}
|
|
|
|
|
2013-01-20 11:07:13 +01:00
|
|
|
TableBuilder* builder = new TableBuilder(options, file.get(), 0);
|
2011-03-18 23:37:00 +01:00
|
|
|
meta->smallest.DecodeFrom(iter->key());
|
|
|
|
for (; iter->Valid(); iter->Next()) {
|
|
|
|
Slice key = iter->key();
|
|
|
|
meta->largest.DecodeFrom(key);
|
|
|
|
builder->Add(key, iter->value());
|
|
|
|
}
|
|
|
|
|
|
|
|
// Finish and check for builder errors
|
|
|
|
if (s.ok()) {
|
|
|
|
s = builder->Finish();
|
|
|
|
if (s.ok()) {
|
|
|
|
meta->file_size = builder->FileSize();
|
|
|
|
assert(meta->file_size > 0);
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
builder->Abandon();
|
|
|
|
}
|
|
|
|
delete builder;
|
|
|
|
|
|
|
|
// Finish and check for file errors
|
2012-08-16 01:38:08 +02:00
|
|
|
if (s.ok() && !options.disableDataSync) {
|
2012-08-27 21:10:26 +02:00
|
|
|
if (options.use_fsync) {
|
|
|
|
s = file->Fsync();
|
|
|
|
} else {
|
|
|
|
s = file->Sync();
|
|
|
|
}
|
2011-03-18 23:37:00 +01:00
|
|
|
}
|
|
|
|
if (s.ok()) {
|
|
|
|
s = file->Close();
|
|
|
|
}
|
|
|
|
|
|
|
|
if (s.ok()) {
|
|
|
|
// Verify that the table is usable
|
2011-03-28 22:43:44 +02:00
|
|
|
Iterator* it = table_cache->NewIterator(ReadOptions(),
|
|
|
|
meta->number,
|
|
|
|
meta->file_size);
|
2011-03-18 23:37:00 +01:00
|
|
|
s = it->status();
|
|
|
|
delete it;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Check for input iterator errors
|
|
|
|
if (!iter->status().ok()) {
|
|
|
|
s = iter->status();
|
|
|
|
}
|
|
|
|
|
|
|
|
if (s.ok() && meta->file_size > 0) {
|
2011-06-22 04:36:45 +02:00
|
|
|
// Keep it
|
2011-03-18 23:37:00 +01:00
|
|
|
} else {
|
|
|
|
env->DeleteFile(fname);
|
|
|
|
}
|
|
|
|
return s;
|
|
|
|
}
|
|
|
|
|
2011-10-31 18:22:06 +01:00
|
|
|
} // namespace leveldb
|