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 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 406 407 408 409 410 411 412 413 414 415 416 417 418 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 462 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 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 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 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 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 633 634 635 636 637 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 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 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 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034
#![deny(clippy::all)]
mod tools;
use keyvaluedb::{
DBKeyRef, DBKeyValueRef, DBOp, DBTransaction, DBTransactionError, DBValue, IoStats,
IoStatsKind, KeyValueDB,
};
use log::*;
use parking_lot::Mutex;
pub use rusqlite::OpenFlags;
use rusqlite::*;
use std::sync::Arc;
use std::{
error,
future::Future,
io,
path::{Path, PathBuf},
pin::Pin,
str::FromStr,
};
use tools::*;
fn other_io_err<E>(e: E) -> io::Error
where
E: Into<Box<dyn error::Error + Send + Sync>>,
{
io::Error::new(io::ErrorKind::Other, e)
}
#[allow(dead_code)]
fn panic_err<E>(e: E) -> io::Error
where
E: Into<Box<dyn error::Error + Send + Sync>>,
{
panic!("should not have failed: {:?}", e.into());
}
///////////////////////////////////////////////////////////////////////////////
/// Database configuration
#[derive(Clone)]
pub struct DatabaseConfig {
/// Set number of columns.
/// The number of columns must not be zero.
pub columns: u32,
/// Set flags used to open the database
pub flags: OpenFlags,
}
impl DatabaseConfig {
/// Create new `DatabaseConfig` with default parameters and specified set of columns.
/// The number of `columns` must not be zero.
pub fn with_columns(columns: u32) -> Self {
assert!(columns > 0, "the number of columns must not be zero");
Self {
columns,
..Default::default()
}
}
/// Create new in-memory database `DatabaseConfig` with default parameters and specified set of columns.
/// The number of `columns` must not be zero.
pub fn with_columns_in_memory(columns: u32) -> Self {
assert!(columns > 0, "the number of columns must not be zero");
Self {
columns,
flags: OpenFlags::SQLITE_OPEN_READ_WRITE
| OpenFlags::SQLITE_OPEN_CREATE
| OpenFlags::SQLITE_OPEN_NO_MUTEX
| OpenFlags::SQLITE_OPEN_MEMORY,
// ..Default::default()
}
}
/// Create new `DatabaseConfig` with default parameters and specified set of columns.
/// Replaces the flags as well.
/// The number of `columns` must not be zero.
pub fn with_columns_and_flags(columns: u32, flags: OpenFlags) -> Self {
assert!(columns > 0, "the number of columns must not be zero");
Self {
columns,
flags,
// ..Default::default()
}
}
}
impl Default for DatabaseConfig {
fn default() -> DatabaseConfig {
DatabaseConfig {
columns: 1,
flags: OpenFlags::SQLITE_OPEN_READ_WRITE
| OpenFlags::SQLITE_OPEN_CREATE
| OpenFlags::SQLITE_OPEN_NO_MUTEX,
}
}
}
///////////////////////////////////////////////////////////////////////////////
/// An sqlite key-value database fulfilling the `KeyValueDB` trait
pub struct DatabaseInner {
path: PathBuf,
config: DatabaseConfig,
connection: rusqlite::Connection,
overall_stats: IoStats,
current_stats: IoStats,
}
#[derive(Clone)]
pub struct Database {
inner: Arc<Mutex<DatabaseInner>>,
}
impl Database {
////////////////////////////////////////////////////////////////
/// Initialization
pub fn open<P: AsRef<Path>>(path: P, config: DatabaseConfig) -> io::Result<Self> {
assert_ne!(config.columns, 0, "number of columns must be >= 1");
let flags = config.flags;
let out = Self {
inner: Arc::new(Mutex::new(DatabaseInner {
path: PathBuf::from(path.as_ref()),
config,
connection: rusqlite::Connection::open_with_flags(path, flags)
.map_err(other_io_err)?,
overall_stats: IoStats::empty(),
current_stats: IoStats::empty(),
})),
};
out.inner
.lock()
.connection
.execute("PRAGMA case_sensitive_like=ON;", [])
.map_err(other_io_err)?;
out.open_resize_columns()?;
Ok(out)
}
pub fn open_with_columns<P: AsRef<Path>>(path: P, columns: u32) -> io::Result<Self> {
assert_ne!(columns, 0, "number of columns must be >= 1");
Self::open(path, DatabaseConfig::with_columns(columns))
}
pub fn open_in_memory_with_columns<P: AsRef<Path>>(path: P, columns: u32) -> io::Result<Self> {
assert_ne!(columns, 0, "number of columns must be >= 1");
Self::open(path, DatabaseConfig::with_columns_in_memory(columns))
}
pub fn path(&self) -> PathBuf {
self.inner.lock().path.clone()
}
pub fn config(&self) -> DatabaseConfig {
self.inner.lock().config.clone()
}
////////////////////////////////////////////////////////////////
/// Low level operations
// The number of column families in the db.
pub fn num_columns(&self) -> io::Result<u32> {
self.with_inner(|inner| {
Self::get_unique_value(&inner.connection, "control", "columns", 0u32)
})
}
/// The number of keys in a column (estimated).
pub fn num_keys(&self, col: u32) -> io::Result<u64> {
self.with_inner(|inner| {
if let Ok(found) = inner.connection.query_row(
&format!("SELECT Count(*) FROM {}", get_column_table_name(col)),
[],
|row| -> Result<u64> { row.get(0) },
) {
return Ok(found);
}
Err(other_io_err("column does not exist"))
})
}
/// Remove the last column family in the database. The deletion is definitive.
pub fn remove_last_column(&self) -> io::Result<()> {
self.with_inner(|inner| {
let columns = Self::get_unique_value(&inner.connection, "control", "columns", 0u32)?;
if columns == 0 {
return Err(other_io_err("no columns exist"));
}
Self::set_unique_value(&inner.connection, "control", "columns", columns - 1)?;
inner
.connection
.execute(
&format!("DROP TABLE {}", get_column_table_name(columns - 1)),
[],
)
.map_err(other_io_err)?;
Ok(())
})
}
/// Add a new column family to the DB.
pub fn add_column(&self) -> io::Result<()> {
self.with_inner(|inner| {
let columns = Self::get_unique_value(&inner.connection, "control", "columns", 0u32)?;
Self::set_unique_value(&inner.connection, "control", "columns", columns + 1)?;
Self::create_column_table(&inner.connection, columns)
})
}
/// Helper to create new transaction for this database.
pub fn transaction(&self) -> DBTransaction {
DBTransaction::new()
}
////////////////////////////////////////////////////////////////
/// Internal helpers
fn with_inner<R, F: FnOnce(&DatabaseInner) -> R>(&self, f: F) -> R {
let inner = self.inner.lock();
f(&inner)
}
fn with_inner_mut<R, F: FnOnce(&mut DatabaseInner) -> R>(&self, f: F) -> R {
let mut inner = self.inner.lock();
f(&mut inner)
}
fn validate_column(col: u32, max: u32) -> io::Result<()> {
if col >= max {
error!("Invalid column number: {} (max {})", col, max);
return Err(other_io_err(format!(
"Invalid column number: {} (max {})",
col, max
)));
}
Ok(())
}
fn create_column_table(conn: &rusqlite::Connection, column: u32) -> io::Result<()> {
conn.execute(&format!("CREATE TABLE IF NOT EXISTS {} (id INTEGER PRIMARY KEY AUTOINCREMENT, [key] TEXT UNIQUE, value BLOB)", get_column_table_name(column)), []).map_err(other_io_err).map(drop)
}
fn get_unique_value<T, K, V>(
conn: &rusqlite::Connection,
table: T,
key: K,
default: V,
) -> io::Result<V>
where
T: AsRef<str>,
K: AsRef<str>,
V: FromStr,
{
if let Ok(found) = conn.query_row(
&format!("SELECT value FROM {} WHERE [key] = ?", table.as_ref()),
[key.as_ref()],
|row| -> Result<String> { row.get(0) },
) {
if let Ok(v) = V::from_str(&found) {
return Ok(v);
}
}
Ok(default)
}
/*
fn get_or_set_default_unique_value<T, K, V>(
conn: &rusqlite::Connection,
table: T,
key: K,
default: V,
) -> io::Result<V>
where
T: AsRef<str>,
K: AsRef<str>,
V: FromStr + ToString,
{
if let Ok(found) = conn.query_row(
&format!("SELECT value FROM {} WHERE [key] = ?", table.as_ref()),
[key.as_ref()],
|row| -> Result<String> { row.get(0) },
) {
if let Ok(v) = V::from_str(&found) {
return Ok(v);
}
}
let out = default.to_string();
Self::set_unique_value(conn, table, key, out)?;
return Ok(default);
}
*/
fn set_unique_value<T, K, V>(
conn: &rusqlite::Connection,
table: T,
key: K,
value: V,
) -> io::Result<()>
where
T: AsRef<str>,
K: AsRef<str>,
V: ToString,
{
let changed = conn
.execute(
&format!(
"INSERT OR REPLACE INTO {} ([key], value) VALUES(?, ?)",
table.as_ref()
),
[key.as_ref(), value.to_string().as_str()],
)
.map_err(other_io_err)?;
assert!(
changed <= 1,
"multiple changes to unique key should not occur"
);
if changed == 0 {
return Err(other_io_err("failed to set unique value"));
}
Ok(())
}
fn load_unique_value_blob<T, K>(
conn: &rusqlite::Connection,
table: T,
key: K,
) -> io::Result<Option<Vec<u8>>>
where
T: AsRef<str>,
K: AsRef<str>,
{
conn.query_row(
&format!("SELECT value FROM {} WHERE [key] = ?", table.as_ref()),
[key.as_ref()],
|row| -> Result<Vec<u8>> { row.get(0) },
)
.optional()
.map_err(other_io_err)
}
// fn load_unique_value_blob_like<T, K>(
// conn: &rusqlite::Connection,
// table: T,
// like: K,
// ) -> io::Result<Option<Vec<u8>>>
// where
// T: AsRef<str>,
// K: AsRef<str>,
// {
// conn.query_row(
// &format!(
// "SELECT value FROM {} WHERE [key] LIKE ? ESCAPE '\\'",
// table.as_ref()
// ),
// [like.as_ref()],
// |row| -> Result<Vec<u8>> { row.get(0) },
// )
// .optional()
// .map_err(other_io_err)
// }
fn store_unique_value_blob<T, K>(
conn: &rusqlite::Connection,
table: T,
key: K,
value: &[u8],
) -> io::Result<()>
where
T: AsRef<str>,
K: AsRef<str>,
{
let changed = conn
.execute(
&format!(
"INSERT OR REPLACE INTO {} ([key], value) VALUES(?, ?)",
table.as_ref()
),
params![key.as_ref(), value],
)
.map_err(other_io_err)?;
assert!(
changed <= 1,
"multiple changes to unique key should not occur"
);
if changed == 0 {
return Err(other_io_err("failed to set unique value"));
}
Ok(())
}
fn remove_unique_value_blob<T, K>(
conn: &rusqlite::Connection,
table: T,
key: K,
) -> io::Result<()>
where
T: AsRef<str>,
K: AsRef<str>,
{
let changed = conn
.execute(
&format!("DELETE FROM {} WHERE [key] = ?", table.as_ref()),
[key.as_ref()],
)
.map_err(other_io_err)?;
assert!(
changed <= 1,
"multiple deletions of unique key should not occur"
);
if changed == 0 {
return Err(other_io_err("failed to remove unique value"));
}
Ok(())
}
fn remove_unique_value_blob_like<T, K>(
conn: &rusqlite::Connection,
table: T,
key: K,
) -> io::Result<usize>
where
T: AsRef<str>,
K: AsRef<str>,
{
let changed = conn
.execute(
&format!(
"DELETE FROM {} WHERE [key] LIKE ? ESCAPE '\\'",
table.as_ref(),
),
[key.as_ref()],
)
.map_err(other_io_err)?;
Ok(changed)
}
fn open_resize_columns(&self) -> io::Result<()> {
self.with_inner(|inner| {
// First see if we have a control table with the number of columns
inner.connection.execute("CREATE TABLE IF NOT EXISTS control (id INTEGER PRIMARY KEY AUTOINCREMENT, [key] TEXT UNIQUE, value TEXT)", []).map_err(other_io_err)?;
// Get column count
let on_disk_columns =
Self::get_unique_value(&inner.connection, "control", "columns", 0u32)?;
// If desired column count is less than or equal to current column count, then allow it, but restrict access to columns
if inner.config.columns <= on_disk_columns {
return Ok(());
}
// Otherwise resize and add other columns
for cn in on_disk_columns..inner.config.columns {
// Create the column table if we don't have it
Self::create_column_table(&inner.connection, cn)?;
}
Self::set_unique_value(
&inner.connection,
"control",
"columns",
inner.config.columns,
)?;
Ok(())
})
}
fn stats_read(inner: &mut DatabaseInner, count: usize, bytes: usize) {
inner.current_stats.reads += count as u64;
inner.overall_stats.reads += count as u64;
inner.current_stats.bytes_read += bytes as u64;
inner.overall_stats.bytes_read += bytes as u64;
}
fn stats_write(inner: &mut DatabaseInner, count: usize, bytes: usize) {
inner.current_stats.writes += count as u64;
inner.overall_stats.writes += count as u64;
inner.current_stats.bytes_written += bytes as u64;
inner.overall_stats.bytes_written += bytes as u64;
}
fn stats_transaction(inner: &mut DatabaseInner, count: usize) {
inner.current_stats.transactions += count as u64;
inner.overall_stats.transactions += count as u64;
}
}
impl KeyValueDB for Database {
fn get<'a>(
&self,
col: u32,
key: &'a [u8],
) -> Pin<Box<dyn Future<Output = io::Result<Option<DBValue>>> + Send + 'a>> {
let this = self.clone();
Box::pin(async move {
this.with_inner_mut(|inner| {
Self::validate_column(col, inner.config.columns)?;
match Self::load_unique_value_blob(
&inner.connection,
get_column_table_name(col),
key_to_text(key),
) {
Ok(someval) => {
match &someval {
Some(val) => Self::stats_read(inner, 1, key.len() + val.len()),
None => Self::stats_read(inner, 1, key.len()),
};
Ok(someval)
}
Err(e) => Err(e),
}
})
})
}
/// Remove a value by key, returning the old value
fn delete<'a>(
&self,
col: u32,
key: &'a [u8],
) -> Pin<Box<dyn Future<Output = io::Result<Option<DBValue>>> + Send + 'a>> {
let this = self.clone();
Box::pin(async move {
this.with_inner_mut(|inner| {
Self::validate_column(col, inner.config.columns)?;
let someval = Self::load_unique_value_blob(
&inner.connection,
get_column_table_name(col),
key_to_text(key),
)?;
match &someval {
Some(val) => {
Self::stats_read(inner, 1, key.len() + val.len());
Self::remove_unique_value_blob(
&inner.connection,
get_column_table_name(col),
key_to_text(key),
)?;
Self::stats_write(inner, 1, 0);
}
None => Self::stats_read(inner, 1, key.len()),
};
Ok(someval)
})
})
}
fn write(
&self,
transaction: DBTransaction,
) -> Pin<Box<dyn Future<Output = Result<(), DBTransactionError>> + Send + 'static>> {
let this = self.clone();
Box::pin(async move {
this.with_inner_mut(|inner| {
Self::stats_transaction(inner, 1);
let mut sw = 0usize;
let mut sbw = 0usize;
let out = {
let tx = inner.connection.transaction().map_err(other_io_err)?;
for op in &transaction.ops {
match op {
DBOp::Insert { col, key, value } => {
Self::validate_column(*col, inner.config.columns)?;
Self::store_unique_value_blob(
&tx,
get_column_table_name(*col),
key_to_text(key),
value,
)?;
sw += 1;
sbw += key.len() + value.len();
}
DBOp::Delete { col, key } => {
Self::validate_column(*col, inner.config.columns)?;
Self::remove_unique_value_blob(
&tx,
get_column_table_name(*col),
key_to_text(key),
)?;
sw += 1;
}
DBOp::DeletePrefix { col, prefix } => {
Self::validate_column(*col, inner.config.columns)?;
Self::remove_unique_value_blob_like(
&tx,
get_column_table_name(*col),
like_key_to_text(prefix) + "%",
)?;
sw += 1;
}
}
}
tx.commit().map_err(other_io_err)
};
Self::stats_write(inner, sw, sbw);
out
})
.map_err(|error| DBTransactionError { error, transaction })
})
}
fn iter<'a, T: 'a, F: FnMut(DBKeyValueRef) -> io::Result<Option<T>> + Send + Sync + 'a>(
&self,
col: u32,
prefix: Option<&'a [u8]>,
mut f: F,
) -> Pin<Box<dyn Future<Output = io::Result<Option<T>>> + Send + 'a>> {
let this = self.clone();
Box::pin(async move {
this.with_inner_mut(|inner| {
if col >= inner.config.columns {
return Err(other_io_err(format!(
"Invalid column number: {} (max {})",
col, inner.config.columns
)));
}
let mut sw = 0usize;
let mut sbw = 0usize;
let mut out = Ok(None);
{
let mut stmt;
let mut rows;
if let Some(p) = prefix {
stmt = match inner.connection.prepare(&format!(
"SELECT key, value FROM {} WHERE [key] LIKE ? ESCAPE '\\'",
get_column_table_name(col)
)) {
Err(e) => {
return Err(other_io_err(format!("SQLite prepare error: {:?}", e)));
}
Ok(v) => v,
};
rows = match stmt.query([like_key_to_text(p) + "%"]) {
Err(e) => {
return Err(other_io_err(format!("SQLite rows error: {:?}", e)));
}
Ok(v) => v,
};
} else {
stmt = match inner.connection.prepare(&format!(
"SELECT key, value FROM {}",
get_column_table_name(col)
)) {
Err(e) => {
return Err(other_io_err(format!("SQLite prepare error: {:?}", e)));
}
Ok(v) => v,
};
rows = match stmt.query([]) {
Err(e) => {
return Err(other_io_err(format!("SQLite query error: {:?}", e)));
}
Ok(v) => v,
};
};
loop {
match rows.next() {
// Iterated value
Ok(Some(row)) => {
let kt: String = match row.get(0) {
Err(e) => {
out = Err(other_io_err(format!(
"SQLite row get column 0 error: {:?}",
e
)));
break;
}
Ok(v) => v,
};
let v: Vec<u8> = match row.get(1) {
Err(e) => {
out = Err(other_io_err(format!(
"SQLite row get column 1 error: {:?}",
e
)));
break;
}
Ok(v) => v,
};
let k: Vec<u8> = match text_to_key(&kt) {
Err(e) => {
out = Err(other_io_err(format!(
"SQLite row get column 0 text convert error: {:?}",
e
)));
break;
}
Ok(v) => v,
};
sw += 1;
sbw += k.len() + v.len();
match f((&k, &v)) {
Ok(None) => (),
Ok(Some(v)) => {
// Callback early termination
out = Ok(Some(v));
break;
}
Err(e) => {
// Callback error termination
out = Err(e);
break;
}
}
}
// Natural iterator termination
Ok(None) => {
break;
}
// Error iterator termination
Err(e) => {
out = Err(other_io_err(format!("SQLite rows error: {:?}", e)));
break;
}
}
}
}
Self::stats_read(inner, sw, sbw);
out
})
})
}
fn iter_keys<'a, T: 'a, F: FnMut(DBKeyRef) -> io::Result<Option<T>> + Send + Sync + 'a>(
&self,
col: u32,
prefix: Option<&'a [u8]>,
mut f: F,
) -> Pin<Box<dyn Future<Output = io::Result<Option<T>>> + Send + 'a>> {
let this = self.clone();
Box::pin(async move {
this.with_inner_mut(|inner| {
if col >= inner.config.columns {
return Err(other_io_err(format!(
"Invalid column number: {} (max {})",
col, inner.config.columns
)));
}
let mut sw = 0usize;
let mut sbw = 0usize;
let mut out = Ok(None);
{
let mut stmt;
let mut rows;
if let Some(p) = prefix {
stmt = match inner.connection.prepare(&format!(
"SELECT key FROM {} WHERE [key] LIKE ? ESCAPE '\\'",
get_column_table_name(col)
)) {
Err(e) => {
return Err(other_io_err(format!("SQLite prepare error: {:?}", e)));
}
Ok(v) => v,
};
rows = match stmt.query([like_key_to_text(p) + "%"]) {
Err(e) => {
return Err(other_io_err(format!("SQLite rows error: {:?}", e)));
}
Ok(v) => v,
};
} else {
stmt = match inner
.connection
.prepare(&format!("SELECT key FROM {}", get_column_table_name(col)))
{
Err(e) => {
return Err(other_io_err(format!("SQLite prepare error: {:?}", e)));
}
Ok(v) => v,
};
rows = match stmt.query([]) {
Err(e) => {
return Err(other_io_err(format!("SQLite query error: {:?}", e)));
}
Ok(v) => v,
};
};
loop {
match rows.next() {
// Iterated value
Ok(Some(row)) => {
let kt: String = match row.get(0) {
Err(e) => {
out = Err(other_io_err(format!(
"SQLite row get column 0 error: {:?}",
e
)));
break;
}
Ok(v) => v,
};
let k: Vec<u8> = match text_to_key(&kt) {
Err(e) => {
out = Err(other_io_err(format!(
"SQLite row get column 0 text convert error: {:?}",
e
)));
break;
}
Ok(v) => v,
};
sw += 1;
sbw += k.len();
match f(&k) {
Ok(None) => (),
Ok(Some(v)) => {
// Callback early termination
out = Ok(Some(v));
break;
}
Err(e) => {
// Callback error termination
out = Err(e);
break;
}
}
}
// Natural iterator termination
Ok(None) => {
break;
}
// Error iterator termination
Err(e) => {
out = Err(other_io_err(format!("SQLite rows error: {:?}", e)));
break;
}
}
}
}
Self::stats_read(inner, sw, sbw);
out
})
})
}
fn io_stats(&self, kind: IoStatsKind) -> IoStats {
self.with_inner_mut(|inner| match kind {
IoStatsKind::Overall => inner.overall_stats.clone(),
IoStatsKind::SincePrevious => {
let stats = inner.current_stats.clone();
inner.current_stats = IoStats::empty();
stats
}
})
}
fn restore(&self, _new_db: &str) -> io::Result<()> {
Err(other_io_err("Attempted to restore sqlite database"))
}
}
#[cfg(test)]
mod tests {
use super::*;
use keyvaluedb_shared_tests as st;
use tempfile::Builder as TempfileBuilder;
fn create(columns: u32) -> io::Result<Database> {
let tempfile = TempfileBuilder::new()
.prefix("")
.tempfile()?
.path()
.to_path_buf();
let config = DatabaseConfig::with_columns(columns);
Database::open(tempfile, config)
}
#[tokio::test]
async fn get_fails_with_non_existing_column() -> io::Result<()> {
let db = create(1)?;
st::test_get_fails_with_non_existing_column(db).await
}
#[tokio::test]
async fn put_and_get() -> io::Result<()> {
let db = create(1)?;
st::test_put_and_get(db).await
}
#[tokio::test]
async fn delete_and_get() -> io::Result<()> {
let db = create(1)?;
st::test_delete_and_get(db).await
}
#[tokio::test]
async fn delete_and_get_single() -> io::Result<()> {
let db = create(1)?;
st::test_delete_and_get_single(db).await
}
#[tokio::test]
async fn delete_prefix() -> io::Result<()> {
let db = create(st::DELETE_PREFIX_NUM_COLUMNS)?;
st::test_delete_prefix(db).await
}
#[tokio::test]
async fn iter() -> io::Result<()> {
let db = create(1)?;
st::test_iter(db).await
}
#[tokio::test]
async fn iter_keys() -> io::Result<()> {
let db = create(1)?;
st::test_iter_keys(db).await
}
#[tokio::test]
async fn iter_with_prefix() -> io::Result<()> {
let db = create(1)?;
st::test_iter_with_prefix(db).await
}
#[tokio::test]
async fn complex() -> io::Result<()> {
let db = create(1)?;
st::test_complex(db).await
}
#[tokio::test]
async fn stats() -> io::Result<()> {
let db = create(st::IO_STATS_NUM_COLUMNS)?;
st::test_io_stats(db).await
}
#[tokio::test]
#[should_panic]
async fn db_config_with_zero_columns() {
let _cfg = DatabaseConfig::with_columns(0);
}
#[tokio::test]
#[should_panic]
async fn open_db_with_zero_columns() {
let cfg = DatabaseConfig {
columns: 0,
..Default::default()
};
let _db = Database::open("", cfg);
}
#[tokio::test]
async fn add_columns() {
let config_1 = DatabaseConfig::default();
let config_5 = DatabaseConfig::with_columns(5);
let tempfile = TempfileBuilder::new()
.prefix("")
.tempfile()
.unwrap()
.path()
.to_path_buf();
// open 1, add 4.
{
let db = Database::open(&tempfile, config_1).unwrap();
assert_eq!(db.num_columns().unwrap(), 1);
for i in 2..=5 {
db.add_column().unwrap();
assert_eq!(db.num_columns().unwrap(), i);
}
}
// reopen as 5.
{
let db = Database::open(&tempfile, config_5).unwrap();
assert_eq!(db.num_columns().unwrap(), 5);
}
}
#[tokio::test]
async fn remove_columns() {
let config_1 = DatabaseConfig::default();
let config_5 = DatabaseConfig::with_columns(5);
let tempfile = TempfileBuilder::new()
.prefix("drop_columns")
.tempfile()
.unwrap()
.path()
.to_path_buf();
// open 5, remove 4.
{
let db = Database::open(&tempfile, config_5).expect("open with 5 columns");
assert_eq!(db.num_columns().unwrap(), 5);
for i in (1..5).rev() {
db.remove_last_column().unwrap();
assert_eq!(db.num_columns().unwrap(), i);
}
}
// reopen as 1.
{
let db = Database::open(&tempfile, config_1).unwrap();
assert_eq!(db.num_columns().unwrap(), 1);
}
}
#[tokio::test]
async fn test_num_keys() {
let tempfile = TempfileBuilder::new()
.prefix("")
.tempfile()
.unwrap()
.path()
.to_path_buf();
let config = DatabaseConfig::with_columns(1);
let db = Database::open(tempfile, config).unwrap();
assert_eq!(
db.num_keys(0).unwrap(),
0,
"database is empty after creation"
);
let key1 = b"beef";
let mut batch = db.transaction();
batch.put(0, key1, key1);
db.write(batch).await.unwrap();
assert_eq!(
db.num_keys(0).unwrap(),
1,
"adding a key increases the count"
);
}
}