tablestg 0.4.1

Storage for database tables
Documentation
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
pub use atom_file::Data;
use std::hash::Hash;
use std::sync::Arc;

/// Value for Hash Map lookup.
pub trait SmallFixed {
    fn size() -> usize;
    fn load(bytes: &[u8]) -> Self;
    fn save(&self, bytes: &mut [u8]);
}

/// Key for Hash Map lookup.
pub trait Key<T> : Hash
where
    T: SmallFixed,
{
    /// Check that hash lookup has found correct value.
    fn ok(&self, v: &T, ps: &mut PageSet) -> bool;
}

/// [PageSet] - keeps track of changed pages that need saving.
pub mod pageset;
pub use pageset::*;

/// [HashMap] - maps keys to values using 64 bit hash.
pub mod hashmap;
pub use hashmap::*;

/// [Table] -- fixed size record storage. Divided into pages, each page stores up to 64 records.
pub mod table;
pub use table::*;

/// [VarValAddr] and [IdAndVVAddr] -- storage of variable length values.
pub mod varval;
pub use varval::*;

// Private modules.

/// [PageTree] - list of pages implemented as tree.
mod pagetree;
use pagetree::*;

/// [TreeVec] -- a variable length list of bytes. Used to implement [Table].
mod treevec;
use treevec::*;

/// Hash Map Bucket - maps keys to values using 64 bit hash.
mod bucket;

const PAGE_SIZE: u64 = 4612;
// pub const PAGE_SIZE: u64 =  4612;

#[test]
fn test_main() {
    use page_store::*;

    let limits = Limits::default();
    /*
    let _dt = DataType::String{};
    let _dt = DataType::Binary{};
    let _dt = DataType::Int(4);
    let _dt = DataType::Array( 5, Box::new(DataType::String) );
    let _dt = DataType::Map( Box::new(DataType::String), Box::new(DataType::String) );
    let _dt = DataType::Struct( Vec::new() );
    */

    // Construct BlockPageStg.
    let file = atom_file::MultiFileStorage::new("test.db");
    let upd = atom_file::FastFileStorage::new("test.upd");
    let af = atom_file::AtomicFile::new_with_limits(file, upd, &limits.af_lim);
    let ps = BlockPageStg::new(af, &limits);
    let is_new = ps.is_new();

    let spd = SharedPagedData::new_from_ps(ps);

    println!("max page size={}", spd.psi.max_size_page());

    let mut ps = PageSet::new(spd.new_writer());

    if false {
        let (root, len) = if is_new { (ps.new_page(), 0) } else { (3, 410) };
        test_tv(root, len, &mut ps);
    }

    if false {
        println!("Calling test_hash");
        hashmap::test_hash(&mut ps);
    }

    if false {
        test_table(&mut ps);
    }

    if false {
        test_varval(&mut ps);
    }

    test_cust(&mut ps);

    // ps.save();

    spd.shutdown();
}

#[cfg(test)]
fn tos(s: &[u8]) -> &str {
    str::from_utf8(s).unwrap()
}

/*
   For a table with very fragmented ids, you can make a new table with new compact ids, and map the old ids to the new ones using a PagedHashMap.

   Access is slightly slower, due to the extra Hash lookup.
*/

#[derive(serde::Serialize, serde::Deserialize, Clone, Hash, PartialEq, Eq, Debug)]
/// Not yet in use.
pub enum DataType {
    /// e.g. date
    Named(u64),

    /// e.g. `struct{ name: string, email: string, created: date }`
    Struct(Vec<(String, DataType)>),

    /// e.g. `( string, string, int )`
    Tuple(Vec<DataType>),

    /// e.g. `enum{ leaf: int, node: [int] }`
    Enum(Vec<(String, DataType)>),

    /// e.g. `string`
    String(u8),

    /// e.g. `binary(50)` - 50 is the number of bytes stored inline.
    Binary(u8),

    /// e.g. `int`
    Int(u8),

    /// e.g. `[string; 5]`
    Array(usize, Box<DataType>),

    /// e.g. `[string]`
    List(Box<DataType>),

    /// e.g. `[string->int]`
    Map(Box<DataType>, Box<DataType>),
}

impl DataType {
    pub fn to_bytes(&self) -> Vec<u8> {
        postcard::to_stdvec(self).unwrap()
    }
    pub fn from_bytes(b: &[u8]) -> Self {
        postcard::from_bytes(b).unwrap()
    }
}

use pstd::localalloc::Local;
/// `StringA<Local>`
pub type LString = pstd::StringA<Local>;
/// `VecA<T, Local>`
pub type LVec<T> = pstd::VecA<T, Local>;

#[derive(serde::Serialize, serde::Deserialize, Clone, Hash, PartialEq, Eq, Debug)]
/// Generic value.
pub enum Value {
    Int(i64),
    String(LString),
    Binary(LVec<u8>),
    List(LVec<Value>),
    VarVal(u64, u64),
    IList(LVec<i64>),
}

impl Value {
    pub fn to_bytes(&self) -> Vec<u8> {
        postcard::to_stdvec(self).unwrap()
    }
    pub fn from_bytes(b: &[u8]) -> Self {
        postcard::from_bytes(b).unwrap()
    }

    pub fn list(&mut self) -> &mut LVec<Value>
    {
        match self {
            Value::List(list) => list,
            _ => panic!()
        }
    }

    pub fn ilist(&mut self) -> &mut LVec<i64>
    {
        match self {
            Value::IList(list) => list,
            _ => panic!()
        }
    }

    pub fn string(&self) -> &LString
    {
        match self {
            Value::String(s) => s,
            _ => panic!()
        }
    }

    pub fn int(&self) -> i64
    {
        match self {
            Value::Int(x) => *x,
            _ => panic!()
        }
    }
}

#[test]
fn test_value() {
    /*
        use pstd::veca;
        let v1 = Value::List(veca![
            Value::String(LString::from("George Barwood")),
            Value::String(LString::from("george.barwood@gmail.com")),
            Value::String(LString::from("33 Sandpipe Close, GL2 4LZ")),
            Value::Int(-47),
            Value::Int(99),
            Value::VarVal(100, 20),
            Value::IList(veca![1, 2, 3, 4]),
        ]);
        let bytes = v1.to_bytes();
        println!("len={} bytes={:?}", bytes.len(), bytes);

        let v2 = Value::from_bytes(&bytes);
        println!("v2={:?}", v2);
    */
}

#[test]
fn test_datatype() {
    let t1 = DataType::String(20);
    let t2 = DataType::Int(3);
    let t3 = DataType::Struct(vec![
        ("name".to_string(), t1.clone()),
        ("email".to_string(), t1.clone()),
    ]);
    let t4 = DataType::Tuple(vec![t1, t2, t3]);

    let bytes = t4.to_bytes();
    // println!("bytes={:?}", bytes);

    let t5 = DataType::from_bytes(&bytes);
    // println!("t5={:?}", t5);
    assert_eq!(t5, t4);
}

/* System tables.

   VarVal tables with diffent chunk sizes.
   Schema table
     Name : string
   Table table
     Schema, Name, DataType (varval), root/len, next_id

   DataType table
     Schema, Name, DataType (varval)

   Function table
     Schema, Name, Definition (varval)
*/

/* Next: make test that stores customer records, Name, Email, Created in a table.
   Then scans them.
*/

#[cfg(test)]
#[derive(Hash)]
struct CustEmailKey<'a> {
    email: &'a str,
}

#[cfg(test)]
impl <'a> Key<VarValAddr> for CustEmailKey<'a> {
    fn ok(&self, v: &VarValAddr, ps: &mut PageSet) -> bool {

        // First get the list of ids.
        let mut list = v.get_value( ps );
        
        // Now check the email of first element in the list.
        let key = list.ilist()[0];

        // Use the HashMap to retrieve the varval address.
        let hms = ps.cust_hashmap;
        let mut hm = HashMap::restore( hms, ps );
        let addr = hm.get(&key).unwrap();

        // Use the address to retrieve the customer record.
        let mut cr = addr.get_value( ps );

        // Check the email address in the customer data matches self.email
        let email = cr.list()[2].string();

        *self.email == **email
    }
}

#[cfg(test)]
fn init(ps: &mut PageSet)
{
    let hm = HashMap::<IdAndVVAddr>::new(ps, 1);
    ps.cust_hashmap = hm.save();

    let hm = HashMap::<VarValAddr>::new(ps, 1);
    ps.cust_by_email = hm.save();
}

#[cfg(test)]
fn make_cust(ps: &mut PageSet, rid: i64, name: &str, email: &str, postal: &str)
{
    use pstd::veca;

    // Set up a customer record in memory.
    let cr = Value::List(veca![
        Value::Int(rid), // Doesn't need to be stored here.
        Value::String(LString::from(name)),
        Value::String(LString::from(email)),
        Value::String(LString::from(postal)),
    ]);

    // Store the customer record ( which has variable length ).
    let addr = VarValAddr::new( &cr, ps );
    
    {
        // Insert into cust_hashmap.
        let mut hm = HashMap::restore( ps.cust_hashmap, ps );
        
        let val = IdAndVVAddr{ rid, addr };

        hm.insert(&rid, val);
        
        if hm.root_changed() { ps.cust_hashmap = hm.save(); }
    }

    let emkey = CustEmailKey { email };

    // Get the address of list of ids.
    let addr = 
    { 
        let mut hm = HashMap::restore( ps.cust_by_email, ps );
        let addr = hm.remove(&emkey);
        if hm.root_changed() { ps.cust_by_email = hm.save(); }
        addr
    };

    let addr = if let Some(addr) = addr
    {
        // List already exists, append to it.
        let mut list = addr.get_value(ps);   
        list.ilist().push( rid );
        addr.update_value(&list, ps)
        
    } else { 
        // Create list with single element and store it as VarVal.
        let list = Value::IList(veca![rid]);
        VarValAddr::new( &list, ps )
    };

    // Associate addr with emkey.
    let mut hm = HashMap::restore( ps.cust_by_email, ps );
    hm.insert(&emkey, addr);
    if hm.root_changed() { ps.cust_by_email= hm.save(); }
}

#[cfg(test)]
fn list_cust(ps: &mut PageSet, email: &str)
{
    // Get set of customer ids with specified email address.

    let key = CustEmailKey { email };
    let mut hm = HashMap::restore( ps.cust_by_email, ps );
    
    if let Some(addr) = hm.get( &key )
    {
        let list = addr.get_value(ps);
        
        println!( "List of cust ids for {} = {:?}", email, list );
    }
    else
    {
        println!("No cust ids found for email {}", email);
    }
}

#[cfg(test)]
fn test_cust(ps: &mut PageSet) {
    init(ps);
    make_cust(ps, 99, "George Barwood", "george@gmail.com", "33 Sandpipe Close, GL2 4LZ" );
    // Make a duplicate
    make_cust(ps, 100, "George Barwood", "george@gmail.com", "33 Sandpipe Close, GL2 4LZ" );
    // Another duplicate
    make_cust(ps, 101, "George Barwood", "george@gmail.com", "33 Sandpipe Close, GL2 4LZ" );
    
    make_cust(ps, 102, "Marilyn Barwood", "maz.barwood@gmail.com", "33 Sandpipe Close, GL2 4LZ" );

    list_cust(ps, "george@gmail.com" );
    list_cust(ps, "maz.barwood@gmail.com" );
    list_cust(ps, "mary@gmail.com" );
}