File size: 2,471 Bytes
bf20cb7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#pragma once

#include "wayy_db/table.hpp"
#include "wayy_db/wal.hpp"

#include <memory>
#include <shared_mutex>
#include <string>
#include <unordered_map>
#include <vector>

namespace wayy_db {

/// High-level database interface managing multiple tables
class Database {
public:
    /// Create an in-memory database
    Database();

    /// Create or open a persistent database at the given path
    explicit Database(const std::string& path);

    /// Move-only semantics
    Database(Database&&) = default;
    Database& operator=(Database&&) = default;
    Database(const Database&) = delete;
    Database& operator=(const Database&) = delete;

    ~Database() = default;

    /// Database path (empty for in-memory)
    const std::string& path() const { return path_; }

    /// Check if database is persistent
    bool is_persistent() const { return !path_.empty(); }

    /// List all table names
    std::vector<std::string> tables() const;

    /// Check if a table exists
    bool has_table(const std::string& name) const;

    /// Get a table by name (loads from disk if persistent and not cached)
    Table& table(const std::string& name);
    Table& operator[](const std::string& name) { return table(name); }

    /// Create a new table
    Table& create_table(const std::string& name);

    /// Add an existing table to the database
    void add_table(Table table);

    /// Drop a table (removes from disk if persistent)
    void drop_table(const std::string& name);

    /// Save all modified tables to disk (no-op for in-memory)
    void save();

    /// Reload table list from disk
    void refresh();

    /// WAL: checkpoint (flush WAL, save tables, truncate WAL)
    void checkpoint();

    /// WAL: get access to WAL for logging (may be null for in-memory DB)
    WriteAheadLog* wal() { return wal_.get(); }

private:
    std::string path_;
    std::unordered_map<std::string, Table> tables_;
    std::unordered_map<std::string, bool> loaded_;  // Track which tables are loaded

    // Write-ahead log (persistent databases only)
    std::unique_ptr<WriteAheadLog> wal_;

    // Mutex for thread-safe access (mutable allows const methods to lock)
    // Uses shared_mutex for concurrent reads, exclusive writes
    mutable std::shared_mutex mutex_;

    /// Get the directory path for a table
    std::string table_path(const std::string& name) const;

    /// Scan directory for existing tables
    void scan_tables();
};

}  // namespace wayy_db