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
#![forbid(unsafe_code)]
#![deny(missing_docs)]
pub use crate::{
atomfile::AtomicFile,
builtin::standard_builtins,
pstore::{AccessPagedData, SharedPagedData},
stg::{MemFile, SimpleFileStorage, Storage},
};
#[cfg(feature = "gentrans")]
pub use crate::gentrans::{GenTransaction, Part};
#[cfg(feature = "builtin")]
pub use crate::{
builtin::check_types,
compile::{c_bool, c_float, c_int, c_value},
exec::EvalEnv,
expr::ObjRef,
expr::{Block, DataKind, Expr},
run::{CExp, CExpPtr, CompileFunc},
value::Value,
};
#[cfg(not(feature = "builtin"))]
use crate::{
compile::{c_bool, c_int, c_value},
exec::EvalEnv,
expr::{Block, DataKind, Expr},
run::{CExp, CExpPtr, CompileFunc},
value::Value,
};
use crate::{
bytes::ByteStorage,
compact::CompactFile,
expr::*,
page::{Page, PagePtr},
parse::Parser,
run::*,
sortedfile::{Asc, Id, Record, SortedFile},
table::{ColInfo, IndexInfo, Row, SaveOp, Table},
util::{nd, newmap, SmallSet},
value::*,
};
use std::{
any::Any,
cell::{Cell, RefCell},
cmp::Ordering,
collections::{BTreeMap, BTreeSet},
panic,
rc::Rc,
sync::{Arc, Mutex, RwLock},
};
use rustc_hash::{FxHashMap as HashMap, FxHashSet as HashSet};
#[cfg(feature = "max")]
#[macro_use]
pub mod util;
#[cfg(not(feature = "max"))]
#[macro_use]
mod util;
#[cfg(feature = "gentrans")]
pub mod gentrans;
pub mod stg;
pub mod pstore;
pub mod atomfile;
#[cfg(feature = "max")]
pub mod builtin;
#[cfg(not(feature = "max"))]
mod builtin;
#[cfg(feature = "max")]
pub mod compact;
#[cfg(not(feature = "max"))]
mod compact;
#[cfg(feature = "builtin")]
pub mod compile;
#[cfg(not(feature = "builtin"))]
mod compile;
#[cfg(feature = "max")]
pub mod exec;
#[cfg(not(feature = "max"))]
mod exec;
#[cfg(feature = "builtin")]
pub mod expr;
#[cfg(not(feature = "builtin"))]
mod expr;
#[cfg(feature = "max")]
pub mod page;
#[cfg(not(feature = "max"))]
mod page;
#[cfg(feature = "max")]
pub mod parse;
#[cfg(not(feature = "max"))]
mod parse;
#[cfg(feature = "max")]
pub mod run;
#[cfg(not(feature = "max"))]
mod run;
#[cfg(feature = "max")]
pub mod sortedfile;
#[cfg(not(feature = "max"))]
mod sortedfile;
#[cfg(feature = "max")]
pub mod sys;
#[cfg(not(feature = "max"))]
mod sys;
#[cfg(feature = "max")]
pub mod table;
#[cfg(not(feature = "max"))]
mod table;
#[cfg(feature = "builtin")]
pub mod value;
#[cfg(not(feature = "builtin"))]
mod value;
#[cfg(feature = "max")]
pub mod cexp;
#[cfg(not(feature = "max"))]
mod cexp;
#[cfg(feature = "max")]
pub mod bytes;
#[cfg(not(feature = "max"))]
mod bytes;
pub type Data = Arc<Vec<u8>>;
pub type DB = Rc<Database>;
pub type BuiltinMap = HashMap<String, (DataKind, CompileFunc)>;
pub struct Database {
pub file: AccessPagedData,
pub builtins: Arc<BuiltinMap>,
pub sys_schema: Rc<Table>,
pub sys_table: Rc<Table>,
pub sys_column: Rc<Table>,
pub sys_index: Rc<Table>,
pub sys_index_col: Rc<Table>,
pub sys_function: Rc<Table>,
pub schemas: RefCell<HashMap<String, i64>>,
pub tables: RefCell<HashMap<ObjRef, Rc<Table>>>,
pub functions: RefCell<HashMap<ObjRef, Rc<Function>>>,
pub lastid: Cell<i64>,
pub err: Cell<bool>,
pub is_new: bool,
bs: Vec<ByteStorage>,
function_reset: Cell<bool>,
page_size_max: usize,
}
const SYS_ROOT_LAST: u64 = 15;
impl Database {
pub fn new(file: AccessPagedData, initsql: &str, builtins: Arc<BuiltinMap>) -> DB {
let is_new = file.is_new();
let mut tb = TableBuilder::new();
let sys_schema = tb.nt("Schema", &[("Name", STRING)]);
let sys_table = tb.nt(
"Table",
&[
("Root", INT),
("Schema", INT),
("Name", STRING),
("IdGen", INT),
],
);
let sys_column = tb.nt("Column", &[("Table", INT), ("Name", STRING), ("Type", INT)]);
let sys_index = tb.nt("Index", &[("Root", INT), ("Table", INT), ("Name", STRING)]);
let sys_index_col = tb.nt("IndexColumn", &[("Index", INT), ("ColId", INT)]);
let sys_function = tb.nt(
"Function",
&[("Schema", INT), ("Name", NAMESTR), ("Def", BIGSTR)],
);
sys_schema.add_index(tb.rt(), vec![0]);
sys_table.add_index(tb.rt(), vec![1, 2]);
sys_column.add_index(tb.rt(), vec![0]);
sys_index.add_index(tb.rt(), vec![1]);
sys_index_col.add_index(tb.rt(), vec![0]);
sys_function.add_index(tb.rt(), vec![0, 1]);
let mut bs = Vec::new();
for ft in 0..bytes::NFT {
bs.push(ByteStorage::new(ft as u64, ft));
}
let page_size_max = file.spd.page_size_max();
let db = Rc::new(Database {
file,
sys_schema,
sys_table,
sys_column,
sys_index,
sys_index_col,
sys_function,
bs,
schemas: newmap(),
functions: newmap(),
tables: newmap(),
builtins,
function_reset: Cell::new(false),
lastid: Cell::new(0),
err: Cell::new(false),
is_new,
page_size_max,
});
assert!(tb.alloc as u64 - 1 == SYS_ROOT_LAST);
if is_new {
for _ft in 0..bytes::NFT {
db.alloc_page(); }
}
for t in &tb.list {
if !is_new {
t.id_gen.set(sys::get_id_gen(&db, t.id as u64));
}
db.publish_table(t.clone());
}
if is_new {
let sysinit = "
CREATE SCHEMA sys
GO
CREATE TABLE sys.Schema( Name string )
CREATE TABLE sys.Table( Root int, Schema int, Name string, IdGen int )
CREATE TABLE sys.Column( Table int, Name string, Type int )
CREATE TABLE sys.Index( Root int, Table int, Name string )
CREATE TABLE sys.IndexColumn( Index int, ColId int )
CREATE TABLE sys.Function( Schema int, Name string(31), Def string(249) )
GO
CREATE INDEX ByName ON sys.Schema(Name)
CREATE INDEX BySchemaName ON sys.Table(Schema,Name)
CREATE INDEX ByTable ON sys.Column(Table)
CREATE INDEX ByTable ON sys.Index(Table)
CREATE INDEX ByIndex ON sys.IndexColumn(Index)
CREATE INDEX BySchemaName ON sys.Function(Schema,Name)
GO
";
let mut dq = DummyTransaction {};
db.run(sysinit, &mut dq);
db.run(initsql, &mut dq);
db.save();
}
db
}
pub fn run(self: &DB, source: &str, tr: &mut dyn Transaction) {
if let Some(e) = self.go(source, tr) {
let err = format!(
"{} in {} at line {} column {}.",
e.msg, e.rname, e.line, e.column
);
println!("Run error {}", &err);
tr.set_error(err);
self.err.set(true);
}
}
pub fn run_timed(self: &DB, source: &str, tr: &mut dyn Transaction) {
let start = std::time::Instant::now();
self.run(source, tr);
println!(
"run_timed path={} run time={} micro sec.",
tr.arg(0, ""),
start.elapsed().as_micros()
);
}
fn go(self: &DB, source: &str, tr: &mut dyn Transaction) -> Option<SqlError> {
let mut p = Parser::new(source, self);
let result = std::panic::catch_unwind(panic::AssertUnwindSafe(|| {
p.batch(tr);
}));
if let Err(x) = result {
Some(if let Some(e) = x.downcast_ref::<SqlError>() {
SqlError {
msg: e.msg.clone(),
line: e.line,
column: e.column,
rname: e.rname.clone(),
}
} else if let Some(s) = x.downcast_ref::<&str>() {
p.make_error((*s).to_string())
} else if let Some(s) = x.downcast_ref::<String>() {
p.make_error(s.to_string())
} else {
p.make_error("unrecognised/unexpected error".to_string())
})
} else {
None
}
}
pub fn changed(self: &DB) -> bool {
if self.err.get() {
return false;
}
for bs in &self.bs {
if bs.changed() {
return true;
}
}
let tm = &*self.tables.borrow();
for t in tm.values() {
if t.id_gen_dirty.get() {
return true;
}
if t.file.changed() {
return true;
}
}
false
}
pub fn save(self: &DB) -> usize {
let op = if self.err.get() {
self.err.set(false);
SaveOp::RollBack
} else {
SaveOp::Save
};
for bs in &self.bs {
bs.save(self, op);
}
let tm = &*self.tables.borrow();
for t in tm.values() {
if t.id_gen_dirty.get() {
if op == SaveOp::Save {
sys::save_id_gen(self, t.id as u64, t.id_gen.get());
} else {
t.id_gen.set(sys::get_id_gen(self, t.id as u64));
}
t.id_gen_dirty.set(false);
}
}
for t in tm.values() {
t.save(self, op);
}
if self.function_reset.get() {
for function in self.functions.borrow().values() {
function.ilist.borrow_mut().clear();
}
self.functions.borrow_mut().clear();
self.function_reset.set(false);
}
self.file.save(op)
}
#[cfg(not(feature = "max"))]
fn get_table(self: &DB, name: &ObjRef) -> Option<Rc<Table>> {
if let Some(t) = self.tables.borrow().get(name) {
return Some(t.clone());
}
sys::get_table(self, name)
}
#[cfg(feature = "max")]
pub fn get_table(self: &DB, name: &ObjRef) -> Option<Rc<Table>> {
if let Some(t) = self.tables.borrow().get(name) {
return Some(t.clone());
}
sys::get_table(self, name)
}
#[cfg(feature = "max")]
pub fn table(self: &DB, schema: &str, name: &str) -> Rc<Table> {
self.get_table(&ObjRef::new(schema, name)).unwrap()
}
fn get_function(self: &DB, name: &ObjRef) -> Option<Rc<Function>> {
if let Some(f) = self.functions.borrow().get(name) {
return Some(f.clone());
}
sys::get_function(self, name)
}
fn publish_table(&self, table: Rc<Table>) {
let name = table.info.name.clone();
self.tables.borrow_mut().insert(name, table);
}
fn encode(self: &DB, val: &Value, size: usize) -> Code {
let bytes = match val {
Value::RcBinary(x) => &**x,
Value::ArcBinary(x) => &**x,
Value::String(x) => x.as_bytes(),
_ => {
return Code {
id: u64::MAX,
ft: 0,
};
}
};
if bytes.len() < size {
return Code {
id: u64::MAX,
ft: 0,
};
}
let tbe = &bytes[size - 9..];
let ft = bytes::fragment_type(tbe.len());
let id = self.bs[ft].encode(self, &bytes[size - 9..]);
Code { id, ft }
}
fn decode(self: &DB, code: Code, inline: usize) -> Vec<u8> {
self.bs[code.ft].decode(self, code.id, inline)
}
fn delcode(self: &DB, code: Code) {
if code.id != u64::MAX {
self.bs[code.ft].delcode(self, code.id);
}
}
fn alloc_page(self: &DB) -> u64 {
self.file.alloc_page()
}
fn free_page(self: &DB, lpnum: u64) {
self.file.free_page(lpnum);
}
#[cfg(feature = "pack")]
fn lp_size(&self, pnum: u64) -> u64 {
self.file.spd.file.read().unwrap().lp_size(pnum) as u64
}
#[cfg(feature = "pack")]
fn repack_file(self: &DB, k: i64, schema: &str, tname: &str) -> i64 {
if k >= 0 {
let name = ObjRef::new(schema, tname);
if let Some(t) = self.get_table(&name) {
return t.repack(self, k as usize);
}
} else {
let k = (-k - 1) as usize;
if k < 4 {
return self.bs[k].repack_file(self);
}
}
-1
}
#[cfg(feature = "verify")]
pub fn verify(self: &DB) -> String {
let (mut pages, total) = self.file.spd.file.read().unwrap().get_info();
let total = total as usize;
let free = pages.len();
for bs in &self.bs {
bs.file.get_used(self, &mut pages);
}
let tm = &*self.tables.borrow();
for t in tm.values() {
t.get_used(self, &mut pages);
}
assert!(pages.len() == total);
format!(
"All Ok. Logical page summary: free={} used={} total={}.",
free,
total - free,
total
)
}
} impl Drop for Database {
fn drop(&mut self) {
for function in self.functions.borrow().values() {
function.ilist.borrow_mut().clear();
}
}
}
struct TableBuilder {
alloc: usize,
list: Vec<Rc<Table>>,
}
impl TableBuilder {
fn new() -> Self {
Self {
alloc: bytes::NFT,
list: Vec::new(),
}
}
fn nt(&mut self, name: &str, ct: &[(&str, DataType)]) -> Rc<Table> {
let root = self.rt();
let id = 1 + (root - bytes::NFT as u64);
let name = ObjRef::new("sys", name);
let info = ColInfo::new(name, ct);
let table = Table::new(id as i64, root, 1, Rc::new(info));
self.list.push(table.clone());
table
}
fn rt(&mut self) -> u64 {
let result = self.alloc;
self.alloc += 1;
result as u64
}
}
pub trait Transaction: Any {
fn status_code(&mut self, _code: i64) {}
fn header(&mut self, _name: &str, _value: &str) {}
fn selected(&mut self, values: &[Value]);
fn global(&self, _kind: i64) -> i64 {
0
}
fn arg(&mut self, _kind: i64, _name: &str) -> Rc<String> {
Rc::new(String::new())
}
fn file_attr(&mut self, _fnum: i64, _atx: i64) -> Rc<String> {
Rc::new(String::new())
}
fn file_content(&mut self, _fnum: i64) -> Arc<Vec<u8>> {
nd()
}
fn set_error(&mut self, err: String);
fn get_error(&mut self) -> String {
String::new()
}
fn set_extension(&mut self, _ext: Box<dyn Any + Send + Sync>) {}
fn get_extension(&mut self) -> Box<dyn Any + Send + Sync> {
Box::new(())
}
}
struct DummyTransaction {}
impl Transaction for DummyTransaction {
fn selected(&mut self, _values: &[Value]) {}
fn set_error(&mut self, err: String) {
println!("Error: {}", err);
}
}