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
//! Read a database.

use std::path::{Path,PathBuf};
use std::fs::File;
use std::io::Seek;

use crate::merge::Merge;
use crate::record::OwnedRecord;
use crate::key_reader::*;
use crate::Wildcard;

use byteorder::ByteOrder;

/// Read a database in key-timestamp sorted format.
///
/// Open a database with [`new`](#method.new) and then [`get`](#method.get),
/// [`get_filter`](#method.get_filter) or [`get_range`](#method.get_range) to select which keys to read.
pub struct DatabaseReader
{
	_dir: PathBuf,
	txes: Vec<(PathBuf,Reader)>,
}


impl DatabaseReader
{
	/// Open a database at the given path.
	///
	/// All of the committed transactions are opened.
	///
	/// Any transactions that appear after `new` is called
	/// are not opened (create a new `DatabaseReader`).
	pub fn new(dir: &Path)
		-> std::io::Result<DatabaseReader>
	{
		Self::new_opts(dir, true)
	}

	/// Open a database at the given path, but not the `main` file.
	///
	/// This is only useful for doing a minor compaction.
	pub fn without_main_db(dir: &Path)
		-> std::io::Result<DatabaseReader>
	{
		Self::new_opts(dir, false)
	}

	fn new_opts(dir: &Path, include_main_db: bool)
		-> std::io::Result<DatabaseReader>
	{
		let dir_reader = std::fs::read_dir(dir)?;

		let mut paths = vec!();

		for entry in dir_reader
		{
			let entry = entry?;
			if let Some(s) = entry.file_name().to_str()
			{
				if s.starts_with("tx.") && !s.ends_with(".tmp")
				{
					paths.push(entry.path());
				}
			}
		}

		paths.sort();
		let mut txes = Vec::with_capacity(paths.len());

		if include_main_db
		{
			let main_db_name = dir.join("main");
			let mut f = File::open(&main_db_name)?;
			let len = f.seek(std::io::SeekFrom::End(0))? as usize;
			if len == 0
			{
				eprintln!("disregarding main database, it is zero length");
			}
			else
			{
				let main_db = Reader::new(f)?;
				txes.push( (main_db_name, main_db) );
			}
		}

		for p in paths
		{
			let mut f = File::open(&p)?;
			let len = f.seek(std::io::SeekFrom::End(0))? as usize;
			if len == 0
			{
				eprintln!("disregarding {:?}, it is zero length", p);
				continue;
			}
			let r = Reader::new(f)?;
			txes.push( (p,r) );
		}

		Ok(DatabaseReader
		{
			txes,
			_dir: dir.to_owned(),
		})
	}

	/// Get the filenames of each transaction.
	///
	/// This is useful for compacting, because after
	/// compaction is complete, you would delete all
	/// of the transaction files.
	///
	/// This function also returns the path for `main`,
	/// which is overwritten. Don't delete that.
	pub fn transaction_paths(&self) -> Vec<PathBuf>
	{
		self.txes
			.iter()
			.map( |e| e.0.clone())
			.collect()
	}

	/// Get a reader for only a single key
	///
	/// Returns an object that will read all of the
	/// records for only one key.
	pub fn get<'rdr, 'k>(&'rdr self, key: &'k str)
		-> DatabaseKeyReader<'rdr, 'k, std::ops::RangeInclusive<&'k str>>
	{
		self.get_range( key ..= key )
	}

	/// Get a reader for a lexicographic range of keys
	///
	/// Use inclusive or exclusive range syntax to select a range.
	///
	/// Example: `rdr.get_range("chimpan-ay" ..= "chimpan-zee")`
	///
	/// Range queries are always efficient and readahead
	/// may occur.
	pub fn get_range<'d, 'r, RB>(&'d self, range: RB)
		-> DatabaseKeyReader<'d, 'r, RB>
	where
		RB: std::ops::RangeBounds<&'r str> + Clone
	{
		let mut readers = Vec::with_capacity(self.txes.len());

		for tx in &self.txes
		{
			readers.push( tx.1.get_range(range.clone()) );
		}
		let merge = Merge::new(
			readers,
			|a, b|
			{
				a.key().cmp(b.key())
					.then_with(
						||
							byteorder::BigEndian::read_u64(a.value())
								.cmp(&byteorder::BigEndian::read_u64(b.value()))
					)
			},
		);

		DatabaseKeyReader
		{
			_db: self,
			merge: Box::new(merge),
		}
	}

	/// Get a reader that filters on SQL's "LIKE"-like syntax.
	///
	/// A wildcard filter that has a fixed prefix, such as
	/// `"chimp%"` is always efficient.
	pub fn get_filter<'d, 'k>(&'d self, wildcard: &'k Wildcard)
		-> DatabaseKeyReader<'d, 'k, std::ops::RangeFrom<&'k str>>
	{
		let mut readers = Vec::with_capacity(self.txes.len());

		for tx in &self.txes
		{
			readers.push( tx.1.get_filter(wildcard) );
		}
		let merge = Merge::new(
			readers,
			|a, b|
			{
				a.key().cmp(b.key())
					.then_with(
						||
							byteorder::BigEndian::read_u64(a.value())
								.cmp(&byteorder::BigEndian::read_u64(b.value()))
					)
			},
		);

		DatabaseKeyReader
		{
			_db: self,
			merge: Box::new(merge),
		}
	}
}




/// An iterator over the filtered keys in a database.
///
/// Yields an [`OwnedRecord`](record/struct.OwnedRecord.html)
/// for each row in the database, sorted by key and timestamp.
pub struct DatabaseKeyReader<'d, 'r, RB>
where
	RB: std::ops::RangeBounds<&'r str>
{
	_db: &'d DatabaseReader,
	merge: Box<Merge<
		StringKeyRangeReader<'d, 'r, RB>, OwnedRecord,
	>>,
}

impl<'d, 'r, RB> Iterator for DatabaseKeyReader<'d, 'r, RB>
where
	RB: std::ops::RangeBounds<&'r str>
{
	type Item = OwnedRecord;

	fn next(&mut self) -> Option<Self::Item>
	{
		self.merge.next()
	}
}