embedded.py
1 """ 2 Embedded module 3 """ 4 5 from .rdbms import RDBMS 6 7 8 class Embedded(RDBMS): 9 """ 10 Base class for embedded relational databases. An embedded relational database stores all content in a local file. 11 """ 12 13 def __init__(self, config): 14 """ 15 Creates a new Database. 16 17 Args: 18 config: database configuration parameters 19 """ 20 21 super().__init__(config) 22 23 # Path to database file 24 self.path = None 25 26 def load(self, path): 27 # Call parent logic 28 super().load(path) 29 30 # Store path reference 31 self.path = path 32 33 def save(self, path): 34 # Temporary database 35 if not self.path: 36 # Save temporary database 37 self.connection.commit() 38 39 # Copy data from current to new 40 connection = self.copy(path) 41 42 # Close temporary database 43 self.connection.close() 44 45 # Point connection to new connection 46 self.session(connection=connection) 47 self.path = path 48 49 # Paths are equal, commit changes 50 elif self.path == path: 51 self.connection.commit() 52 53 # New path is different from current path, copy data and continue using current connection 54 else: 55 self.copy(path).close() 56 57 def jsonprefix(self): 58 # Return json column prefix 59 return "json_extract(data" 60 61 def jsoncolumn(self, name): 62 # Generate json column using json_extract function 63 return f"json_extract(data, '$.{name}')" 64 65 def copy(self, path): 66 """ 67 Copies the current database into path. 68 69 Args: 70 path: path to write database 71 72 Returns: 73 new connection with data copied over 74 """ 75 76 raise NotImplementedError