|
| 1 | +"""Transaction example for sqlite-vec-client. |
| 2 | +
|
| 3 | +Demonstrates: |
| 4 | +- Atomic transactions with context manager |
| 5 | +- All CRUD operations in a single transaction |
| 6 | +- Rollback on error |
| 7 | +- Transaction isolation |
| 8 | +""" |
| 9 | + |
| 10 | +from sqlite_vec_client import SQLiteVecClient |
| 11 | + |
| 12 | + |
| 13 | +def main(): |
| 14 | + client = SQLiteVecClient(table="products", db_path=":memory:") |
| 15 | + client.create_table(dim=64, distance="cosine") |
| 16 | + |
| 17 | + # Example 1: Successful transaction with all CRUD operations |
| 18 | + print("Example 1: Successful transaction") |
| 19 | + print("-" * 50) |
| 20 | + |
| 21 | + with client.transaction(): |
| 22 | + # CREATE: Add initial products |
| 23 | + texts = [f"Product {i}" for i in range(5)] |
| 24 | + embeddings = [[float(i)] * 64 for i in range(5)] |
| 25 | + metadata = [{"price": i * 10, "stock": 100} for i in range(5)] |
| 26 | + rowids = client.add(texts=texts, embeddings=embeddings, metadata=metadata) |
| 27 | + print(f"[+] Added {len(rowids)} products: {rowids}") |
| 28 | + |
| 29 | + # READ: Get a product |
| 30 | + product = client.get(rowids[0]) |
| 31 | + if product: |
| 32 | + print(f"[+] Retrieved product {product[0]}: {product[1]}") |
| 33 | + |
| 34 | + # UPDATE: Update single product |
| 35 | + updated = client.update( |
| 36 | + rowids[0], text="Updated Product 0", metadata={"price": 99} |
| 37 | + ) |
| 38 | + print(f"[+] Updated product {rowids[0]}: {updated}") |
| 39 | + |
| 40 | + # UPDATE: Bulk update |
| 41 | + updates = [ |
| 42 | + (rowids[1], "Bulk Updated 1", {"price": 150}, None), |
| 43 | + (rowids[2], None, {"price": 200, "stock": 50}, None), |
| 44 | + ] |
| 45 | + count = client.update_many(updates) |
| 46 | + print(f"[+] Bulk updated {count} products") |
| 47 | + |
| 48 | + # DELETE: Delete single product |
| 49 | + deleted = client.delete(rowids[3]) |
| 50 | + print(f"[+] Deleted product {rowids[3]}: {deleted}") |
| 51 | + |
| 52 | + # DELETE: Bulk delete |
| 53 | + deleted_count = client.delete_many([rowids[4]]) |
| 54 | + print(f"[+] Bulk deleted {deleted_count} products") |
| 55 | + |
| 56 | + # Transaction committed - verify results |
| 57 | + print("\n[+] Transaction committed successfully") |
| 58 | + print(f" Total products remaining: {client.count()}") |
| 59 | + |
| 60 | + # Example 2: Failed transaction with rollback |
| 61 | + print("\n\nExample 2: Failed transaction (rollback)") |
| 62 | + print("-" * 50) |
| 63 | + |
| 64 | + initial_count = client.count() |
| 65 | + print(f"Initial count: {initial_count}") |
| 66 | + |
| 67 | + try: |
| 68 | + with client.transaction(): |
| 69 | + # Add more products |
| 70 | + new_texts = ["New Product 1", "New Product 2"] |
| 71 | + new_embeddings = [[1.0] * 64, [2.0] * 64] |
| 72 | + new_rowids = client.add(texts=new_texts, embeddings=new_embeddings) |
| 73 | + print(f"[+] Added {len(new_rowids)} products: {new_rowids}") |
| 74 | + |
| 75 | + # Update existing |
| 76 | + client.update(rowids[0], text="This will be rolled back") |
| 77 | + print(f"[+] Updated product {rowids[0]}") |
| 78 | + |
| 79 | + # Simulate error |
| 80 | + raise ValueError("Simulated error - transaction will rollback") |
| 81 | + |
| 82 | + except ValueError as e: |
| 83 | + print(f"\n[-] Error occurred: {e}") |
| 84 | + print("[+] Transaction rolled back automatically") |
| 85 | + |
| 86 | + # Verify rollback |
| 87 | + final_count = client.count() |
| 88 | + print(f" Final count: {final_count}") |
| 89 | + print(f" Count unchanged: {initial_count == final_count}") |
| 90 | + |
| 91 | + # Verify data not changed |
| 92 | + product = client.get(rowids[0]) |
| 93 | + if product: |
| 94 | + print(f" Product {rowids[0]} text: {product[1]}") |
| 95 | + |
| 96 | + # Example 3: Nested operations with similarity search |
| 97 | + print("\n\nExample 3: Complex transaction with search") |
| 98 | + print("-" * 50) |
| 99 | + |
| 100 | + with client.transaction(): |
| 101 | + # Add products with similar embeddings |
| 102 | + similar_texts = ["Red Apple", "Green Apple", "Orange"] |
| 103 | + similar_embeddings = [ |
| 104 | + [0.9, 0.1] + [0.0] * 62, |
| 105 | + [0.85, 0.15] + [0.0] * 62, |
| 106 | + [0.5, 0.5] + [0.0] * 62, |
| 107 | + ] |
| 108 | + similar_rowids = client.add(texts=similar_texts, embeddings=similar_embeddings) |
| 109 | + print(f"[+] Added {len(similar_rowids)} products") |
| 110 | + |
| 111 | + # Search within transaction |
| 112 | + query_emb = [0.9, 0.1] + [0.0] * 62 |
| 113 | + results = client.similarity_search(embedding=query_emb, top_k=2) |
| 114 | + print(f"[+] Found {len(results)} similar products:") |
| 115 | + for rowid, text, distance in results: |
| 116 | + dist_str = f"{distance:.4f}" if distance is not None else "N/A" |
| 117 | + print(f" [{rowid}] {text} (distance: {dist_str})") |
| 118 | + |
| 119 | + # Update based on search results |
| 120 | + for rowid, text, distance in results: |
| 121 | + if distance is not None and distance < 0.1: |
| 122 | + client.update(rowid, metadata={"featured": True}) |
| 123 | + print(f"[+] Marked product {rowid} as featured") |
| 124 | + |
| 125 | + print("\n[+] Complex transaction completed") |
| 126 | + print(f" Total products: {client.count()}") |
| 127 | + |
| 128 | + # Example 4: Batch operations in transaction |
| 129 | + print("\n\nExample 4: Large batch operations") |
| 130 | + print("-" * 50) |
| 131 | + |
| 132 | + with client.transaction(): |
| 133 | + # Bulk insert |
| 134 | + batch_size = 20 |
| 135 | + batch_texts = [f"Batch Product {i}" for i in range(batch_size)] |
| 136 | + batch_embeddings = [[float(i % 10)] * 64 for i in range(batch_size)] |
| 137 | + batch_rowids = client.add(texts=batch_texts, embeddings=batch_embeddings) |
| 138 | + print(f"[+] Bulk inserted {len(batch_rowids)} products") |
| 139 | + |
| 140 | + # Bulk update all |
| 141 | + bulk_updates = [ |
| 142 | + (rid, None, {"batch": True, "processed": True}, None) |
| 143 | + for rid in batch_rowids[:10] |
| 144 | + ] |
| 145 | + updated = client.update_many(bulk_updates) |
| 146 | + print(f"[+] Bulk updated {updated} products") |
| 147 | + |
| 148 | + # Bulk delete some |
| 149 | + deleted = client.delete_many(batch_rowids[10:15]) |
| 150 | + print(f"[+] Bulk deleted {deleted} products") |
| 151 | + |
| 152 | + print("\n[+] Batch operations completed") |
| 153 | + print(f" Final total: {client.count()}") |
| 154 | + |
| 155 | + client.close() |
| 156 | + |
| 157 | + |
| 158 | +if __name__ == "__main__": |
| 159 | + main() |
0 commit comments