EZDB 0.1.15

Easy little database
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
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
use std::io::Write;
use std::str::{self};

use crate::auth::{AuthenticationError, User};
use crate::networking_utilities::*;
use crate::PATH_SEP;

/// downloads a table as a csv String from the EZDB server at the given address.
pub fn download_table(
    address: &str,
    username: &str,
    password: &str,
    table_name: &str,
) -> Result<String, ServerError> {
    let mut connection = Connection::connect(address, username, password)?;

    let response = instruction_send_and_confirm(
        Instruction::Download(table_name.to_owned()),
        &mut connection,
    )?;
    println!("Instruction successfully sent");
    println!("response: {}", response);

    let csv: Vec<u8>;
    match parse_response(&response, &connection.user, table_name) {
        Ok(_) => csv = receive_data(&mut connection)?,
        Err(e) => return Err(e),
    }
    println!("received: {}", bytes_to_str(&csv)?);

    match connection.stream.write("OK".as_bytes()) {
        Ok(n) => println!("Wrote 'OK' as {n} bytes"),
        Err(e) => {
            return Err(ServerError::Io(e.kind()));
        }
    };
    connection.stream.flush()?;

    Ok(bytes_to_str(&csv)?.to_owned())
}

/// Uploads a given csv string to the EZDB server at the given address.
/// Will return an error if the string is not strictly formatted
pub fn upload_table(
    address: &str,
    username: &str,
    password: &str,
    table_name: &str,
    csv: &String,
) -> Result<String, ServerError> {
    let mut connection = Connection::connect(address, username, password)?;

    let response =
        instruction_send_and_confirm(Instruction::Upload(table_name.to_owned()), &mut connection)?;

    println!("upload_table - parsing response");
    let confirmation: String = match parse_response(&response, &connection.user, table_name) {
        Ok(_) => data_send_and_confirm(&mut connection, csv.as_bytes())?,
        Err(e) => return Err(e),
    };
    println!("confirmation: {}", confirmation);

    if confirmation == "OK" {
        return Ok("OK".to_owned());
    } else {
        return Err(ServerError::Confirmation(confirmation));
    }
}

/// Updates a given table with a given csv string. If there is an existing record in the database with
/// primary key matching a primary key in the csv passed here, it will be overwritten.
/// If there is no record with the primary key in the passed in csv, a new row will be added
/// preserving the sorted order of the table.
pub fn update_table(
    address: &str,
    username: &str,
    password: &str,
    table_name: &str,
    csv: &str,
) -> Result<String, ServerError> {
    let mut connection = Connection::connect(address, username, password)?;

    let response =
        instruction_send_and_confirm(Instruction::Update(table_name.to_owned()), &mut connection)?;

    let confirmation: String = match parse_response(&response, &connection.user, table_name) {
        Ok(_) => data_send_and_confirm(&mut connection, csv.as_bytes())?,
        Err(e) => return Err(e),
    };

    if confirmation == "OK" {
        println!("Confirmation from server: {}", confirmation);
        return Ok("OK".to_owned());
    } else {
        println!("Confirmation from server: {}", confirmation);
        return Err(ServerError::Confirmation(confirmation));
    }
}

/// Send an EZQL query to the database server
pub fn query_table(
    address: &str,
    username: &str,
    password: &str,
    query: &str,
) -> Result<String, ServerError> {
    let mut connection = Connection::connect(address, username, password)?;

    let response = instruction_send_and_confirm(
        Instruction::Query(query.to_owned()),
        &mut connection,
    )?;
    println!("HERE 1!!!");
    let csv: Vec<u8>;
    match response.as_str() {
        
        // THIS IS WHERE YOU SEND THE BULK OF THE DATA
        //########## SUCCESS BRANCH #################################
        "OK" => csv = receive_data(&mut connection)?,
        //###########################################################
        "Username is incorrect" => {
            return Err(ServerError::Authentication(AuthenticationError::WrongUser(
                connection.user,
            )))
        }
        "Password is incorrect" => {
            return Err(ServerError::Authentication(
                AuthenticationError::WrongPassword,
            ))
        }
        e => panic!("Need to handle error: {}", e),
    };
    println!("HERE 2!!!");


    match connection.stream.write("OK".as_bytes()) {
        Ok(n) => println!("Wrote 'OK' as {n} bytes"),
        Err(e) => {
            return Err(ServerError::Io(e.kind()));
        }
    };

    Ok(bytes_to_str(&csv)?.to_owned())
}

/// Uploads an arbitrary binary blob to the EZDB server at the given address and associates it with the given key
pub fn kv_upload(
    address: &str,
    username: &str,
    password: &str,
    key: &str,
    value: &[u8],
) -> Result<(), ServerError> {
    let mut connection = Connection::connect(address, username, password)?;

    let response =
        instruction_send_and_confirm(Instruction::KvUpload(key.to_owned()), &mut connection)?;

    println!("upload_value - parsing response");
    let confirmation: String = match parse_response(&response, &connection.user, key) {
        Ok(_) => data_send_and_confirm(&mut connection, value)?,
        Err(e) => return Err(e),
    };
    println!("value uploaded successfully");

    if confirmation == "OK" {
        return Ok(());
    } else {
        return Err(ServerError::Confirmation(confirmation));
    }
}

/// Downloads the binary blob associated with the passed key from the EZDB server running at address.
pub fn kv_download(
    address: &str,
    username: &str,
    password: &str,
    key: &str,
) -> Result<Vec<u8>, ServerError> {
    let mut connection = Connection::connect(address, username, password)?;

    let response =
        instruction_send_and_confirm(Instruction::KvDownload(key.to_owned()), &mut connection)?;

    let value: Vec<u8>;

    match parse_response(&response, &connection.user, key) {
        Ok(_) => value = receive_data(&mut connection)?,
        Err(e) => return Err(e),
    }

    match connection.stream.write("OK".as_bytes()) {
        Ok(n) => println!("Wrote 'OK' as {n} bytes"),
        Err(e) => {
            return Err(ServerError::Io(e.kind()));
        }
    };

    Ok(value)
}

/// Overwrites the binary blob associated with the passed in key at the given address
pub fn kv_update(
    address: &str,
    username: &str,
    password: &str,
    key: &str,
    value: &[u8],
) -> Result<(), ServerError> {
    let mut connection = Connection::connect(address, username, password)?;

    let response =
        instruction_send_and_confirm(Instruction::KvUpdate(key.to_owned()), &mut connection)?;

    let confirmation: String;

    println!("upload_value - parsing response");
    match parse_response(&response, &connection.user, key) {
        Ok(_) => confirmation = data_send_and_confirm(&mut connection, value)?,
        Err(e) => return Err(e),
    }
    println!("value uploaded successfully");

    // The reason for the +28 in the length checker is that it accounts for the length of the nonce (IV) and the authentication tag
    // in the aes-gcm encryption. The nonce is 12 bytes and the auth tag is 16 bytes
    let data_len = (value.len() + 28).to_string();
    if confirmation == data_len {
        return Ok(());
    } else {
        return Err(ServerError::Confirmation(confirmation));
    }
}

/// Returns a list of table_names in the database.
pub fn meta_list_tables(
    address: &str,
    username: &str,
    password: &str,
) -> Result<String, ServerError> {
    let mut connection = Connection::connect(address, username, password)?;

    let response = instruction_send_and_confirm(Instruction::MetaListTables, &mut connection)?;

    let value: Vec<u8>;

    match parse_response(&response, &connection.user, "") {
        Ok(_) => value = receive_data(&mut connection)?,
        Err(e) => return Err(e),
    }
    println!("value downloaded successfully");

    match connection.stream.write("OK".as_bytes()) {
        Ok(n) => println!("Wrote 'OK' as {n} bytes"),
        Err(e) => {
            return Err(ServerError::Io(e.kind()));
        }
    };

    let table_list = bytes_to_str(&value)?;

    Ok(table_list.to_owned())
}

/// Returns a list of keys with associated binary blobs.
pub fn meta_list_key_values(
    address: &str,
    username: &str,
    password: &str,
) -> Result<String, ServerError> {
    let mut connection = Connection::connect(address, username, password)?;

    let response = instruction_send_and_confirm(Instruction::MetaListKeyValues, &mut connection)?;

    let value: Vec<u8>;

    match parse_response(&response, &connection.user, "") {
        Ok(_) => value = receive_data(&mut connection)?,
        Err(e) => return Err(e),
    }
    println!("value downloaded successfully");

    match connection.stream.write("OK".as_bytes()) {
        Ok(n) => println!("Wrote 'OK' as {n} bytes"),
        Err(e) => {
            return Err(ServerError::Io(e.kind()));
        }
    };

    let table_list = bytes_to_str(&value)?;

    Ok(table_list.to_owned())
}

pub fn meta_create_new_user(
    user: User,
    address: &str,
    username: &str,
    password: &str,
) -> Result<(), ServerError> {

    let mut connection = Connection::connect(address, username, password)?;

    let user_string = match ron::to_string::<User>(&user) {
        Ok(s) => s,
        Err(e) => todo!(),
    };

    let response = instruction_send_and_confirm(Instruction::NewUser(user_string), &mut connection)?;

    println!("Create new user - parsing response");
    let confirmation: String = match parse_response(&response, &connection.user, "no table") {
        Ok(s) => "OK".to_owned(),
        Err(e) => return Err(e),
    };
    println!("confirmation: {}", confirmation);

    if confirmation == "OK" {
        Ok(())
    } else {
        return Err(ServerError::Confirmation(confirmation));
    }
}


#[cfg(test)]
mod tests {
    #![allow(unused)]
    use std::{fs::remove_file, path::Path};

    use crate::db_structure::EZTable;

    use super::*;

    #[test]
    fn test_no_such_table() {
        let name = "nope";
        let address = "127.0.0.1:3004";
        let username = "admin";
        let password = "admin";
        let table = download_table(address, username, password, name);
        assert!(table.is_err());
    }

    #[test]
    fn test_send_good_csv() {
        let csv = std::fs::read_to_string(format!("test_files{PATH_SEP}good_csv.txt")).unwrap();
        let address = "127.0.0.1:3004";
        let username = "admin";
        let password = "admin";
        let e = upload_table(address, username, password, "good_csv", &csv);
        e.unwrap();
        // assert!(e.is_ok());
    }

    #[test]
    fn test_send_good_csv_twice() {
        let csv = std::fs::read_to_string(format!("test_files{PATH_SEP}good_csv.txt")).unwrap();
        let address = "127.0.0.1:3004";
        let username = "admin";
        let password = "admin";
        let e = upload_table(address, username, password, "good_csv", &csv);
        assert!(e.is_ok());
        println!("About to check second table");
        std::thread::sleep(std::time::Duration::from_secs(2));
        let d = upload_table(address, username, password, "good_csv", &csv);
        assert!(d.is_ok());
    }

    #[test]
    fn test_concurrent_connections() {
        let csv = std::fs::read_to_string(format!("test_files{PATH_SEP}good_csv.txt")).unwrap();
        let address = "127.0.0.1:3004";
        let username = "admin";
        let password = "admin";
        let a = upload_table(address, username, password, "good_csv", &csv);
        assert!(a.is_ok());
        println!("About to check second table");
        std::thread::sleep(std::time::Duration::from_secs(2));
        for _ in 0..100 {
            download_table(address, username, password, "good_csv").unwrap();
        }
    }

    #[test]
    fn test_send_bad_csv() {
        let csv = std::fs::read_to_string(format!("test_files{PATH_SEP}bad_csv.txt")).unwrap();
        let address = "127.0.0.1:3004";
        let username = "admin";
        let password = "admin";
        let e = upload_table(address, username, password, "bad_csv", &csv);
        assert!(e.is_err());
    }

    #[test]
    fn test_receive_csv() {
        println!("Sending...\n##########################");
        // test_send_good_csv();
        let name = "good_csv";
        let address = "127.0.0.1:3004";
        println!("Receiving\n############################");
        let username = "admin";
        let password = "admin";
        let table = download_table(address, username, password, name).unwrap();
        println!("{:?}", table);
        let good_table = EZTable::from_csv_string(
            &std::fs::read_to_string(format!("test_files{PATH_SEP}good_csv.txt")).unwrap(),
            "good_table",
            "test",
        )
        .unwrap();
        assert_eq!(table, good_table.to_string());
    }

    #[test]
    fn test_send_large_csv() {
        // create the large_csv
        let mut i = 0;
        let mut printer = String::from("vnr,t-P;heiti,t-N;magn,i-N\n");
        loop {
            if i > 1_000_000 {
                break;
            }
            printer.push_str(&format!("i{};product name;569\n", i));
            i += 1;
        }
        let address = "127.0.0.1:3004";
        let username = "admin";
        let password = "admin";
        let e = upload_table(address, username, password, "large_csv", &printer).unwrap();
    }

    #[test]
    fn test_query() {
        let csv = std::fs::read_to_string(format!("test_files{PATH_SEP}good_csv.txt")).unwrap();
        let address = "127.0.0.1:3004";
        let username = "admin";
        let password = "admin";
        let e = upload_table(address, username, password, "good_csv", &csv).unwrap();
        assert_eq!(e, "OK");

        let query = "SELECT(table_name: good_csv, primary_keys: *, conditions: ())";
        let username = "admin";
        let password = "admin";
        let response = query_table(address, username, password, query).unwrap();
        let full_table = download_table(address, username, password, "good_csv").unwrap();
        println!("{}", response);
        assert_eq!(response, full_table);
    }

    #[test]
    fn test_kv_upload() {
        let value: &[u8] = &[1, 2, 3, 4, 5, 6, 7, 8, 9];
        let address = "127.0.0.1:3004";
        let username = "admin";
        let password = "admin";
        let e = kv_upload(address, username, password, "test_upload", value).unwrap();
    }

    #[test]
    fn test_kv_download() {
        let value: &[u8] = &[1, 2, 3, 4, 5, 6, 7, 8, 9];
        let address = "127.0.0.1:3004";
        let username = "admin";
        let password = "admin";
        println!("About to upload");
        kv_upload(address, username, password, "test_download", value);
        println!("About to download");
        let e = kv_download(address, username, password, "test_download").unwrap();
        println!("value: {:x?}", e);
    }

    #[test]
    fn test_kv_update() {
        let value: &[u8] = &[1, 2, 3, 4, 5, 6, 7, 8, 9];
        let address = "127.0.0.1:3004";
        let username = "admin";
        let password = "admin";
        kv_upload(address, username, password, "test_update", value);
        let value: &[u8] = &[9, 8, 7, 6, 5, 4, 3, 2, 1];
        kv_update(address, username, password, "test_update", value);
        let e = kv_download(address, username, password, "test_update").unwrap();
        println!("value: {:x?}", e);
    }

    #[test]
    fn test_list_tables() {
        let address = "127.0.0.1:3004";
        let username = "admin";
        let password = "admin";
        // test_send_good_csv();
        // test_send_large_csv();
        // std::thread::sleep(Duration::from_secs(3));
        let tables = meta_list_tables(address, username, password).unwrap();
        println!("tables: \n{}", tables);
    }

    #[test]
    fn test_list_key_values() {
        let address = "127.0.0.1:3004";
        let username = "admin";
        let password = "admin";
        // test_send_good_csv();
        // test_send_large_csv();
        // std::thread::sleep(Duration::from_secs(3));
        let tables = meta_list_key_values(address, username, password).unwrap();
        println!("tables: \n{}", tables);
    }
}