Database Examples๏ƒ

This section contains examples demonstrating the database storage capabilities of True Storage.

Basic SQLite Storage๏ƒ

The following example demonstrates basic operations with SQLite storage:

Basic SQLite Storage Example๏ƒ
 1"""Basic SQLite Storage Demo
 2
 3This demo shows basic operations with the SQLite storage backend.
 4"""
 5
 6import logging
 7from true_storage.database import SQLiteStorage
 8
 9def main():
10    # Configure logging
11    logging.basicConfig(
12        level=logging.INFO,
13        format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
14    )
15
16    print("๐Ÿš€ Initializing SQLite Store...")
17    # Create an in-memory database for demonstration
18    store = SQLiteStorage(":memory:")
19
20    print("\n๐Ÿ“ Storing and retrieving data...")
21    
22    # Store some user data
23    user1 = {
24        "id": 1,
25        "name": "Alice",
26        "email": "alice@example.com"
27    }
28    user2 = {
29        "id": 2,
30        "name": "Bob",
31        "email": "bob@example.com"
32    }
33    
34    # Store users
35    store.store("user:1", user1)
36    store.store("user:2", user2)
37    print("โœ… Stored user data")
38
39    # Retrieve users
40    retrieved_user1 = store.retrieve("user:1")
41    print(f"\nRetrieved User 1:")
42    print(f"Name: {retrieved_user1['name']}")
43    print(f"Email: {retrieved_user1['email']}")
44
45    retrieved_user2 = store.retrieve("user:2")
46    print(f"\nRetrieved User 2:")
47    print(f"Name: {retrieved_user2['name']}")
48    print(f"Email: {retrieved_user2['email']}")
49
50    # Delete a user
51    print("\n๐Ÿ—‘๏ธ Deleting User 1...")
52    store.delete("user:1")
53    
54    try:
55        store.retrieve("user:1")
56    except KeyError:
57        print("โœ… User 1 successfully deleted")
58
59    # Clear all data
60    print("\n๐Ÿงน Clearing all data...")
61    store.clear()
62    
63    try:
64        store.retrieve("user:2")
65    except KeyError:
66        print("โœ… All data successfully cleared")
67
68if __name__ == "__main__":
69    main()
Key features demonstrated:
  • SQLite storage initialization

  • Storing and retrieving data

  • Deleting data

  • Error handling

Filesystem Storage๏ƒ

The following example shows how to use filesystem-based storage:

Filesystem Storage Example๏ƒ
 1"""
 2Filesystem Store Demo
 3
 4This demo shows operations with the filesystem-based storage backend.
 5"""
 6
 7import json
 8import tempfile
 9import logging
10from pathlib import Path
11from true_storage.database import FileSystemStorage
12
13def main():
14    # Configure logging
15    logging.basicConfig(
16        level=logging.INFO,
17        format='%(asctime)s - %(levelname)s - %(message)s'
18    )
19
20    # Create a temporary directory for demonstration
21    with tempfile.TemporaryDirectory() as temp_dir:
22        print(f"\nInitializing FileSystem Store in {temp_dir}...")
23        store = FileSystemStorage(temp_dir)
24
25        # Store some data
26        print("\nStoring data...")
27        data = {
28            "config": {
29                "app_name": "Demo App",
30                "version": "1.0.0",
31                "settings": {
32                    "debug": True,
33                    "max_connections": 100
34                }
35            },
36            "users": [
37                {"id": 1, "name": "Alice", "role": "admin"},
38                {"id": 2, "name": "Bob", "role": "user"}
39            ]
40        }
41
42        # Store data in different paths
43        print("\nCreating directory structure...")
44        store.store("config/app.json", data["config"])  # Store Python dict directly
45        store.store("data/users.json", data["users"])   # Store Python list directly
46
47        # Read data back
48        print("\nReading configuration...")
49        config = store.retrieve("config/app.json")  # Retrieved as Python dict
50        print("App Configuration:")
51        print(f"  Name: {config['app_name']}")
52        print(f"  Version: {config['version']}")
53        print(f"  Debug Mode: {config['settings']['debug']}")
54
55        print("\nReading users...")
56        users = store.retrieve("data/users.json")  # Retrieved as Python list
57        for user in users:
58            print(f"  User {user['id']}: {user['name']} ({user['role']})")
59
60        # Update data
61        print("\nUpdating configuration...")
62        config["settings"]["debug"] = False
63        store.store("config/app.json", config)
64
65        # Verify update
66        print("\nVerifying update...")
67        updated_config = store.retrieve("config/app.json")
68        print(f"Debug Mode is now: {updated_config['settings']['debug']}")
69
70        # Delete data
71        print("\nDeleting user data...")
72        store.delete("data/users.json")
73
74        # Check existence
75        print("\nChecking file existence:")
76        files = ["config/app.json", "data/users.json"]
77        for file in files:
78            exists = store.exists(file)
79            print(f"  {file}: {'Exists' if exists else 'Not found'}")
80
81        print("\nCleanup will happen automatically when exiting the context")
82
83    print("\nDemo completed!")
84
85if __name__ == "__main__":
86    main()
Key features demonstrated:
  • Filesystem storage initialization

  • Hierarchical storage with directories

  • Atomic file operations

  • Directory cleanup