-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathengine.go
More file actions
2304 lines (1962 loc) · 63.9 KB
/
Copy pathengine.go
File metadata and controls
2304 lines (1962 loc) · 63.9 KB
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
package engine
import (
"bytes"
"encoding/binary"
"encoding/json"
"fmt"
"os"
"path/filepath"
"strconv"
"strings"
"sync"
"time"
"github.com/LlamasScripters/PostgresInGo/internal/execution"
"github.com/LlamasScripters/PostgresInGo/internal/index"
"github.com/LlamasScripters/PostgresInGo/internal/parser"
"github.com/LlamasScripters/PostgresInGo/internal/storage"
"github.com/LlamasScripters/PostgresInGo/internal/transaction"
"github.com/LlamasScripters/PostgresInGo/internal/types"
)
// StorageMode defines the storage format type
type StorageMode int
const (
JSONStorage StorageMode = iota // Default JSON-based storage
BinaryStorage // Optimized binary storage
)
// EngineConfig contains engine configuration options
type EngineConfig struct {
DataDir string
StorageMode StorageMode
}
// PostgresEngine represents the main database engine
type PostgresEngine struct {
storageManager *storage.StorageManager
binaryStorage *storage.BinaryStorageManager
transactionManager *transaction.TransactionManager
indexManager *index.IndexManager
queryExecutor *execution.ExecutionEngine
dataDir string
databases map[string]bool
currentDB string
storageMode StorageMode
mu sync.RWMutex
}
// NewPostgresEngine creates a new PostgreSQL engine with default JSON storage
func NewPostgresEngine(dataDir string) (*PostgresEngine, error) {
return NewPostgresEngineWithConfig(EngineConfig{
DataDir: dataDir,
StorageMode: JSONStorage,
})
}
// NewPostgresEngineWithBinary creates a new PostgreSQL engine with binary storage
func NewPostgresEngineWithBinary(dataDir string) (*PostgresEngine, error) {
return NewPostgresEngineWithConfig(EngineConfig{
DataDir: dataDir,
StorageMode: BinaryStorage,
})
}
// NewPostgresEngineWithConfig creates a new PostgreSQL engine with custom configuration
func NewPostgresEngineWithConfig(config EngineConfig) (*PostgresEngine, error) {
// Create data directory if it doesn't exist
if err := os.MkdirAll(config.DataDir, 0755); err != nil {
return nil, fmt.Errorf("failed to create data directory: %w", err)
}
var storageManager *storage.StorageManager
var binaryStorage *storage.BinaryStorageManager
var err error
// Initialize appropriate storage manager
switch config.StorageMode {
case BinaryStorage:
binaryStorage, err = storage.NewBinaryStorageManager(config.DataDir)
if err != nil {
return nil, fmt.Errorf("failed to create binary storage manager: %w", err)
}
storageManager = binaryStorage.StorageManager
default: // JSONStorage
storageManager, err = storage.NewStorageManager(config.DataDir)
if err != nil {
return nil, fmt.Errorf("failed to create storage manager: %w", err)
}
}
// Initialize transaction manager
transactionManager, err := transaction.NewTransactionManager(config.DataDir)
if err != nil {
return nil, fmt.Errorf("failed to create transaction manager: %w", err)
}
// Initialize index manager
indexManager := index.NewIndexManager()
// Initialize query executor
queryExecutor := execution.NewExecutionEngine(storageManager, indexManager)
engine := &PostgresEngine{
storageManager: storageManager,
binaryStorage: binaryStorage,
transactionManager: transactionManager,
indexManager: indexManager,
queryExecutor: queryExecutor,
dataDir: config.DataDir,
databases: make(map[string]bool),
storageMode: config.StorageMode,
}
// Load existing databases
engine.loadDatabases()
return engine, nil
}
// Insert adds new data to a table
func (pe *PostgresEngine) Insert(tableName string, data map[string]any) error {
pe.mu.Lock()
defer pe.mu.Unlock()
// Start transaction
txn := pe.transactionManager.Begin()
defer func() {
if err := recover(); err != nil {
pe.transactionManager.Rollback(txn)
panic(err)
} else {
pe.transactionManager.Commit(txn)
}
}()
// Validate constraints before insertion
if err := pe.validateConstraintsForInsert(tableName, data); err != nil {
return err
}
// Create tuple from data using optimized serialization when available
tuple := &types.Tuple{
Data: pe.serializeDataWithSchema(data, tableName),
}
return pe.storageManager.InsertTuple(tableName, tuple)
}
// insertInternal performs insertion without acquiring locks (for internal use)
func (pe *PostgresEngine) insertInternal(tableName string, data map[string]any) error {
// Start transaction
txn := pe.transactionManager.Begin()
defer func() {
if err := recover(); err != nil {
pe.transactionManager.Rollback(txn)
panic(err)
} else {
pe.transactionManager.Commit(txn)
}
}()
// Validate constraints before insertion
if err := pe.validateConstraintsForInsert(tableName, data); err != nil {
return err
}
// Create tuple from data using optimized serialization when available
tuple := &types.Tuple{
Data: pe.serializeDataWithSchema(data, tableName),
}
return pe.storageManager.InsertTuple(tableName, tuple)
}
// Select retrieves data from a table with optional filtering
func (pe *PostgresEngine) Select(tableName string, filter map[string]any) ([]*types.Tuple, error) {
pe.mu.RLock()
defer pe.mu.RUnlock()
return pe.selectInternal(tableName, filter)
}
// selectInternal performs selection without acquiring locks (for internal use)
func (pe *PostgresEngine) selectInternal(tableName string, filter map[string]any) ([]*types.Tuple, error) {
// Get all tuples for this table directly from storage manager
return pe.getAllTuplesForTable(tableName, filter)
}
// getAllTuplesForTable retrieves all tuples for a table with optional filtering
func (pe *PostgresEngine) getAllTuplesForTable(tableName string, filter map[string]any) ([]*types.Tuple, error) {
// Get all tuples from storage manager
tuples, err := pe.storageManager.GetAllTuples(tableName)
if err != nil {
return nil, err
}
var results []*types.Tuple
for _, tuple := range tuples {
// Apply filter if provided
if filter == nil || pe.matchesFilter(tuple, filter) {
results = append(results, tuple)
}
}
return results, nil
}
// Update modifies existing data in a table
func (pe *PostgresEngine) Update(tableName string, filter map[string]any, updates map[string]any) (int64, error) {
pe.mu.Lock()
defer pe.mu.Unlock()
// Start transaction
txn := pe.transactionManager.Begin()
defer func() {
if err := recover(); err != nil {
pe.transactionManager.Rollback(txn)
panic(err)
} else {
pe.transactionManager.Commit(txn)
}
}()
// Find matching tuples (use internal method to avoid deadlock)
tuples, err := pe.selectInternal(tableName, filter)
if err != nil {
return 0, err
}
updated := int64(0)
for _, tuple := range tuples {
// Update tuple data
newData := pe.mergeData(tuple.Data, updates)
updatedTuple := &types.Tuple{
TID: tuple.TID,
Data: newData,
}
err := pe.storageManager.UpdateTuple(tableName, tuple.TID, updatedTuple)
if err != nil {
return updated, err
}
updated++
}
return updated, nil
}
// updateInternal performs update without acquiring locks (for internal use)
func (pe *PostgresEngine) updateInternal(tableName string, filter map[string]any, updates map[string]any) (int64, error) {
// Start transaction
txn := pe.transactionManager.Begin()
defer func() {
if err := recover(); err != nil {
pe.transactionManager.Rollback(txn)
panic(err)
} else {
pe.transactionManager.Commit(txn)
}
}()
// Find matching tuples (use internal method to avoid deadlock)
tuples, err := pe.selectInternal(tableName, filter)
if err != nil {
return 0, err
}
updated := int64(0)
for _, tuple := range tuples {
// Update tuple data
newData := pe.mergeData(tuple.Data, updates)
updatedTuple := &types.Tuple{
TID: tuple.TID,
Data: newData,
}
err := pe.storageManager.UpdateTuple(tableName, tuple.TID, updatedTuple)
if err != nil {
return updated, err
}
updated++
}
return updated, nil
}
// Delete removes data from a table
func (pe *PostgresEngine) Delete(tableName string, filter map[string]any) (int64, error) {
pe.mu.Lock()
defer pe.mu.Unlock()
// Start transaction
txn := pe.transactionManager.Begin()
defer func() {
if err := recover(); err != nil {
pe.transactionManager.Rollback(txn)
panic(err)
} else {
pe.transactionManager.Commit(txn)
}
}()
// Find matching tuples (use internal method to avoid deadlock)
tuples, err := pe.selectInternal(tableName, filter)
if err != nil {
return 0, err
}
deleted := int64(0)
for _, tuple := range tuples {
err := pe.storageManager.DeleteTuple(tableName, tuple.TID)
if err != nil {
return deleted, err
}
deleted++
}
return deleted, nil
}
// deleteInternal performs deletion without acquiring locks (for internal use)
func (pe *PostgresEngine) deleteInternal(tableName string, filter map[string]any) (int64, error) {
// Start transaction
txn := pe.transactionManager.Begin()
defer func() {
if err := recover(); err != nil {
pe.transactionManager.Rollback(txn)
panic(err)
} else {
pe.transactionManager.Commit(txn)
}
}()
// Find matching tuples (use internal method to avoid deadlock)
tuples, err := pe.selectInternal(tableName, filter)
if err != nil {
return 0, err
}
deleted := int64(0)
for _, tuple := range tuples {
err := pe.storageManager.DeleteTuple(tableName, tuple.TID)
if err != nil {
return deleted, err
}
deleted++
}
return deleted, nil
}
// serializeData converts a map to byte slice for storage
func (pe *PostgresEngine) serializeData(data map[string]any) []byte {
if pe.storageMode == BinaryStorage {
// For binary storage, we need the table schema, but we don't have it here
// Fall back to JSON-style serialization for now
// This will be optimized when we can pass schema information
return pe.serializeDataJSON(data)
}
return pe.serializeDataJSON(data)
}
// serializeDataWithSchema converts a map to byte slice using table schema for binary optimization
func (pe *PostgresEngine) serializeDataWithSchema(data map[string]any, tableName string) []byte {
if pe.storageMode == BinaryStorage && pe.binaryStorage != nil {
// Get table schema for binary serialization
table, err := pe.storageManager.GetTable(tableName)
if err == nil {
return pe.binaryStorage.SerializeTupleBinary(data, table.Schema)
}
}
return pe.serializeDataJSON(data)
}
// serializeDataJSON converts a map to byte slice using JSON-style format
func (pe *PostgresEngine) serializeDataJSON(data map[string]any) []byte {
// Simplified serialization - in a real implementation, this would use a proper format
result := make([]byte, 0, 256)
for key, value := range data {
keyBytes := []byte(key + ":")
result = append(result, keyBytes...)
switch v := value.(type) {
case int:
result = append(result, []byte(fmt.Sprintf("%d", v))...)
case string:
result = append(result, []byte(v)...)
default:
result = append(result, []byte(fmt.Sprintf("%v", v))...)
}
result = append(result, ';')
}
return result
}
// matchesFilter checks if a tuple matches the given filter
func (pe *PostgresEngine) matchesFilter(tuple *types.Tuple, filter map[string]any) bool {
if len(filter) == 0 {
return true
}
// Parse the serialized data back to a map for comparison
tupleData := pe.deserializeData(tuple.Data)
// Check each filter condition
for key, value := range filter {
tupleValue, exists := tupleData[key]
if !exists {
return false
}
// Compare values (simplified comparison)
if fmt.Sprintf("%v", tupleValue) != fmt.Sprintf("%v", value) {
return false
}
}
return true
}
// mergeData merges updates into existing tuple data
func (pe *PostgresEngine) mergeData(_ []byte, updates map[string]any) []byte {
// Simplified merge - in a real implementation, this would deserialize,
// apply updates, and reserialize
return pe.serializeData(updates)
}
// deserializeData converts byte slice back to a map
func (pe *PostgresEngine) deserializeData(data []byte) map[string]any {
// Try binary format first if binary storage is enabled
if pe.storageMode == BinaryStorage && pe.binaryStorage != nil && len(data) > 32 {
// Check if this looks like binary data (has binary tuple header)
if pe.isBinaryFormat(data) {
// We need schema for proper binary deserialization
// For now, fall back to JSON format
return pe.deserializeDataJSON(data)
}
}
return pe.deserializeDataJSON(data)
}
// deserializeDataWithSchema converts byte slice back to a map using table schema
func (pe *PostgresEngine) deserializeDataWithSchema(data []byte, tableName string) map[string]any {
if pe.storageMode == BinaryStorage && pe.binaryStorage != nil {
table, err := pe.storageManager.GetTable(tableName)
if err == nil {
// Always try binary first in binary mode
if pe.isBinaryFormat(data) {
return pe.binaryStorage.DeserializeTupleBinary(data, table.Schema)
}
// Only fallback to JSON if clearly not binary
// This handles migration scenarios
}
}
return pe.deserializeDataJSON(data)
}
// isBinaryFormat checks if data is in cache-aligned binary format
func (pe *PostgresEngine) isBinaryFormat(data []byte) bool {
// Check for cache-aligned binary header (64 bytes minimum)
if len(data) < 64 {
return false
}
// Read magic number first for fast detection
reader := bytes.NewReader(data)
var magic uint16
binary.Read(reader, binary.LittleEndian, &magic)
// Check magic number (0x4254 = "BT")
if magic != 0x4254 {
return false
}
// Read essential header fields to validate structure
var header struct {
ColumnCount uint16
DataSize uint32
Timestamp uint32
Checksum uint32
}
binary.Read(reader, binary.LittleEndian, &header)
// Validate header makes sense
if header.ColumnCount == 0 || header.ColumnCount > 10000 {
return false
}
if header.DataSize == 0 || header.DataSize > uint32(len(data)) {
return false
}
// Additional validation: check if total size matches (64-byte header + data)
expectedSize := 64 + int(header.DataSize)
return expectedSize <= len(data)
}
// deserializeDataJSON converts byte slice back to a map using JSON-style format
func (pe *PostgresEngine) deserializeDataJSON(data []byte) map[string]any {
result := make(map[string]any)
dataStr := string(data)
// Split by semicolon to get key-value pairs
pairs := strings.Split(dataStr, ";")
for _, pair := range pairs {
if len(pair) == 0 {
continue
}
// Split by colon to get key and value
parts := strings.SplitN(pair, ":", 2)
if len(parts) != 2 {
continue
}
key := parts[0]
valueStr := parts[1]
// Try to convert to int, otherwise keep as string
if intVal, err := strconv.Atoi(valueStr); err == nil {
result[key] = intVal
} else {
result[key] = valueStr
}
}
return result
}
// DeserializeDataForTesting exposes data deserialization for testing purposes
func (pe *PostgresEngine) DeserializeDataForTesting(data []byte) map[string]any {
return pe.deserializeData(data)
}
// CreateDatabase creates a new database
func (pe *PostgresEngine) CreateDatabase(name string) error {
pe.mu.Lock()
defer pe.mu.Unlock()
if _, exists := pe.databases[name]; exists {
return fmt.Errorf("database %s already exists", name)
}
// Create database directory
dbDir := fmt.Sprintf("%s/%s", pe.dataDir, name)
if err := os.MkdirAll(dbDir, 0755); err != nil {
return fmt.Errorf("failed to create database directory: %w", err)
}
pe.databases[name] = true
// Save databases metadata
pe.saveDatabases()
return nil
}
// DropDatabase drops a database
func (pe *PostgresEngine) DropDatabase(name string) error {
pe.mu.Lock()
defer pe.mu.Unlock()
if _, exists := pe.databases[name]; !exists {
return fmt.Errorf("database %s does not exist", name)
}
// Remove database directory
dbDir := fmt.Sprintf("%s/%s", pe.dataDir, name)
if err := os.RemoveAll(dbDir); err != nil {
return fmt.Errorf("failed to remove database directory: %w", err)
}
delete(pe.databases, name)
// Save databases metadata
pe.saveDatabases()
return nil
}
// UseDatabase switches to a database
func (pe *PostgresEngine) UseDatabase(name string) error {
pe.mu.Lock()
defer pe.mu.Unlock()
if _, exists := pe.databases[name]; !exists {
return fmt.Errorf("database %s does not exist", name)
}
pe.currentDB = name
return nil
}
// CreateTable creates a new table
func (pe *PostgresEngine) CreateTable(name string, schema types.Schema) error {
pe.mu.Lock()
defer pe.mu.Unlock()
return pe.createTableInternal(name, schema)
}
// createTableInternal creates a new table without acquiring the lock (internal use)
func (pe *PostgresEngine) createTableInternal(name string, schema types.Schema) error {
return pe.storageManager.CreateTable(name, schema)
}
// DropTable drops a table
func (pe *PostgresEngine) DropTable(name string) error {
pe.mu.Lock()
defer pe.mu.Unlock()
// In a real implementation, this would remove the table from storage
return fmt.Errorf("drop table not implemented")
}
// CreateIndex creates a new index
func (pe *PostgresEngine) CreateIndex(name, table string, columns []string) error {
pe.mu.Lock()
defer pe.mu.Unlock()
return pe.createIndexInternal(name, table, columns)
}
// createIndexInternal creates an index without acquiring the lock (internal use)
func (pe *PostgresEngine) createIndexInternal(name, table string, columns []string) error {
// Get table to determine column type
tableObj, err := pe.storageManager.GetTable(table)
if err != nil {
return err
}
// Find column type (simplified - use first column)
var colType types.DataType = types.IntType
for _, col := range tableObj.Schema.Columns {
if col.Name == columns[0] {
colType = col.Type
break
}
}
return pe.indexManager.CreateIndex(name, colType)
}
// DropIndex drops an index
func (pe *PostgresEngine) DropIndex(name string) error {
pe.mu.Lock()
defer pe.mu.Unlock()
return pe.indexManager.DropIndex(name)
}
// BeginTransaction starts a new transaction
func (pe *PostgresEngine) BeginTransaction() (*types.Transaction, error) {
return pe.transactionManager.Begin(), nil
}
// CommitTransaction commits a transaction
func (pe *PostgresEngine) CommitTransaction(txn *types.Transaction) error {
return pe.transactionManager.Commit(txn)
}
// RollbackTransaction rolls back a transaction
func (pe *PostgresEngine) RollbackTransaction(txn *types.Transaction) error {
return pe.transactionManager.Rollback(txn)
}
// InsertTuple inserts a tuple into a table
func (pe *PostgresEngine) InsertTuple(tableName string, tuple *types.Tuple) error {
pe.mu.Lock()
defer pe.mu.Unlock()
return pe.storageManager.InsertTuple(tableName, tuple)
}
// SelectTuple selects a tuple by TID
func (pe *PostgresEngine) SelectTuple(tableName string, tid types.TupleID) (*types.Tuple, error) {
pe.mu.RLock()
defer pe.mu.RUnlock()
return pe.storageManager.SelectTuple(tableName, tid)
}
// UpdateTuple updates a tuple
func (pe *PostgresEngine) UpdateTuple(tableName string, tid types.TupleID, tuple *types.Tuple) error {
pe.mu.Lock()
defer pe.mu.Unlock()
return pe.storageManager.UpdateTuple(tableName, tid, tuple)
}
// DeleteTuple deletes a tuple
func (pe *PostgresEngine) DeleteTuple(tableName string, tid types.TupleID) error {
pe.mu.Lock()
defer pe.mu.Unlock()
return pe.storageManager.DeleteTuple(tableName, tid)
}
// GetTable retrieves a table by name
func (pe *PostgresEngine) GetTable(name string) (*types.Table, error) {
pe.mu.RLock()
defer pe.mu.RUnlock()
return pe.getTableInternal(name)
}
// getTableInternal retrieves a table by name without acquiring the lock (internal use)
func (pe *PostgresEngine) getTableInternal(name string) (*types.Table, error) {
return pe.storageManager.GetTable(name)
}
// GetIndex retrieves an index by name
func (pe *PostgresEngine) GetIndex(name string) (*index.BTree, error) {
pe.mu.RLock()
defer pe.mu.RUnlock()
return pe.indexManager.GetIndex(name)
}
// GetStats returns database statistics
func (pe *PostgresEngine) GetStats() map[string]interface{} {
pe.mu.RLock()
defer pe.mu.RUnlock()
stats := make(map[string]interface{})
stats["databases"] = len(pe.databases)
stats["current_database"] = pe.currentDB
stats["data_directory"] = pe.dataDir
return stats
}
// loadDatabases loads database metadata from disk
func (pe *PostgresEngine) loadDatabases() {
dbFile := filepath.Join(pe.dataDir, "databases.json")
data, err := os.ReadFile(dbFile)
if err != nil {
// File doesn't exist, start fresh
return
}
var databases map[string]bool
err = json.Unmarshal(data, &databases)
if err != nil {
fmt.Printf("Error loading databases: %v\n", err)
return
}
pe.databases = databases
}
// saveDatabases saves database metadata to disk
func (pe *PostgresEngine) saveDatabases() {
dbFile := filepath.Join(pe.dataDir, "databases.json")
data, err := json.MarshalIndent(pe.databases, "", " ")
if err != nil {
fmt.Printf("Error marshaling databases: %v\n", err)
return
}
err = os.WriteFile(dbFile, data, 0644)
if err != nil {
fmt.Printf("Error saving databases: %v\n", err)
}
}
// Close closes the database engine
func (pe *PostgresEngine) Close() error {
pe.mu.Lock()
defer pe.mu.Unlock()
// Save databases metadata
pe.saveDatabases()
// Close storage manager
if err := pe.storageManager.Close(); err != nil {
return err
}
return nil
}
// QueryOptimizer provides query optimization capabilities
type QueryOptimizer struct {
statistics *Statistics
costModel *CostModel
}
// Statistics holds database statistics
type Statistics struct {
TableStats map[string]*types.TableStats
}
// CostModel defines cost parameters for different operations
type CostModel struct {
SeqScanCost float64
IndexScanCost float64
NestedLoopCost float64
HashJoinCost float64
SortMergeCost float64
}
// NewQueryOptimizer creates a new query optimizer
func NewQueryOptimizer() *QueryOptimizer {
return &QueryOptimizer{
statistics: &Statistics{
TableStats: make(map[string]*types.TableStats),
},
costModel: &CostModel{
SeqScanCost: 1.0,
IndexScanCost: 0.1,
NestedLoopCost: 1.0,
HashJoinCost: 0.5,
SortMergeCost: 0.8,
},
}
}
// QueryPlan represents an optimized query plan
type QueryPlan struct {
Root execution.Operator
Cost float64
Cardinality int64
}
// Optimize optimizes a query plan for operations
func (qo *QueryOptimizer) Optimize(operation string, tableName string) (*QueryPlan, error) {
// Simplified optimization - just return a basic plan
plan := &QueryPlan{
Cost: 1.0,
Cardinality: 1,
}
return plan, nil
}
// AlterTableChange represents a table alteration
type AlterTableChange struct {
Type string
Column types.Column
}
// AlterTable alters a table structure
func (pe *PostgresEngine) AlterTable(name string, changes []AlterTableChange) error {
pe.mu.Lock()
defer pe.mu.Unlock()
// In a real implementation, this would modify the table schema
return fmt.Errorf("alter table not implemented")
}
// Constraint validation methods
// validateConstraintsForInsert validates all constraints for an insert operation
func (pe *PostgresEngine) validateConstraintsForInsert(tableName string, data map[string]any) error {
// Validate primary key constraints
if err := pe.storageManager.ValidatePrimaryKey(tableName, data); err != nil {
return err
}
// Validate foreign key constraints
if err := pe.storageManager.ValidateForeignKey(tableName, data); err != nil {
return err
}
// Validate unique constraints
if err := pe.storageManager.ValidateUniqueConstraints(tableName, data); err != nil {
return err
}
// Validate not null constraints
if err := pe.validateNotNullConstraints(tableName, data); err != nil {
return err
}
return nil
}
// validateNotNullConstraints validates not null constraints
func (pe *PostgresEngine) validateNotNullConstraints(tableName string, data map[string]any) error {
table, err := pe.storageManager.GetTable(tableName)
if err != nil {
return err
}
for _, col := range table.Schema.Columns {
if !col.Nullable {
value, exists := data[col.Name]
if !exists || value == nil {
return fmt.Errorf("column '%s' cannot be null", col.Name)
}
}
}
return nil
}
// AddPrimaryKey adds a primary key constraint to a table
func (pe *PostgresEngine) AddPrimaryKey(tableName string, columns []string) error {
pe.mu.Lock()
defer pe.mu.Unlock()
table, err := pe.storageManager.GetTable(tableName)
if err != nil {
return err
}
// Check if table already has a primary key constraint (not just marked columns)
if table.PrimaryKey != nil {
return fmt.Errorf("table '%s' already has a primary key", tableName)
}
// Validate that all columns exist
for _, col := range columns {
if !table.Schema.HasColumn(col) {
return fmt.Errorf("column '%s' does not exist in table '%s'", col, tableName)
}
}
// Create primary key constraint
pkConstraint := &types.Constraint{
Name: fmt.Sprintf("pk_%s", tableName),
Type: types.PrimaryKeyConstraint,
Columns: columns,
}
// Add to table
table.PrimaryKey = pkConstraint
table.Schema.Constraints = append(table.Schema.Constraints, *pkConstraint)
// Mark columns as primary key
for _, colName := range columns {
for i := range table.Schema.Columns {
if table.Schema.Columns[i].Name == colName {
table.Schema.Columns[i].IsPrimaryKey = true
table.Schema.Columns[i].Nullable = false // Primary key columns cannot be null
}
}
}
// Create unique index for primary key
indexName := fmt.Sprintf("idx_pk_%s", tableName)
return pe.createIndexInternal(indexName, tableName, columns)
}
// addPrimaryKeyInternal adds a primary key constraint without acquiring the lock (internal use)
func (pe *PostgresEngine) addPrimaryKeyInternal(tableName string, columns []string) error {
table, err := pe.storageManager.GetTable(tableName)
if err != nil {
return err
}
// Check if table already has a primary key constraint (not just marked columns)
if table.PrimaryKey != nil {
return fmt.Errorf("table '%s' already has a primary key", tableName)
}
// Validate that all columns exist
for _, col := range columns {
if !table.Schema.HasColumn(col) {
return fmt.Errorf("column '%s' does not exist in table '%s'", col, tableName)
}
}
// Create primary key constraint
pkConstraint := &types.Constraint{
Name: fmt.Sprintf("pk_%s", tableName),
Type: types.PrimaryKeyConstraint,
Columns: columns,
}
// Add to table
table.PrimaryKey = pkConstraint
table.Schema.Constraints = append(table.Schema.Constraints, *pkConstraint)
// Mark columns as primary key
for _, colName := range columns {
for i := range table.Schema.Columns {
if table.Schema.Columns[i].Name == colName {
table.Schema.Columns[i].IsPrimaryKey = true
table.Schema.Columns[i].Nullable = false // Primary key columns cannot be null
}
}
}
// Create unique index for primary key
indexName := fmt.Sprintf("idx_pk_%s", tableName)
return pe.createIndexInternal(indexName, tableName, columns)
}
// addForeignKeyInternal adds a foreign key constraint without acquiring the lock (internal use)
func (pe *PostgresEngine) addForeignKeyInternal(tableName string, columns []string, refTable string, refColumns []string, onDelete, onUpdate string) error {
table, err := pe.storageManager.GetTable(tableName)
if err != nil {
return err
}