-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconnection_pool_example.py
More file actions
78 lines (55 loc) · 2.16 KB
/
connection_pool_example.py
File metadata and controls
78 lines (55 loc) · 2.16 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
"""Example demonstrating connection pooling for concurrent access."""
import concurrent.futures
import time
from sqlite_vec_client import ConnectionPool, SQLiteVecClient
def worker_task(worker_id: int, pool: ConnectionPool) -> tuple[int, float]:
"""Simulate a worker performing database operations.
Args:
worker_id: Worker identifier
pool: Connection pool to use
Returns:
Tuple of (worker_id, execution_time)
"""
start = time.time()
# Create client with pooled connection (no db_path needed)
client = SQLiteVecClient(table=f"docs_{worker_id}", pool=pool)
# Create table if needed
client.create_table(dim=384)
# Add some data
texts = [f"Document {i} from worker {worker_id}" for i in range(10)]
embeddings = [[0.1 * i] * 384 for i in range(10)]
client.add(texts, embeddings)
# Perform similarity search
query = [0.5] * 384
_ = client.similarity_search(query, top_k=5)
# Close (returns connection to pool)
client.close()
elapsed = time.time() - start
return worker_id, elapsed
def main() -> None:
"""Demonstrate connection pooling with concurrent workers."""
print("Connection Pooling Example")
print("=" * 50)
# Create connection pool
pool = ConnectionPool(
connection_factory=lambda: SQLiteVecClient.create_connection("./pooled.db"),
pool_size=5,
)
print("Created connection pool with size=5\n")
# Run concurrent workers
num_workers = 10
print(f"Running {num_workers} concurrent workers...")
with concurrent.futures.ThreadPoolExecutor(max_workers=num_workers) as executor:
futures = [executor.submit(worker_task, i, pool) for i in range(num_workers)]
results = [f.result() for f in concurrent.futures.as_completed(futures)]
# Print results
print("\nWorker execution times:")
for worker_id, elapsed in sorted(results):
print(f" Worker {worker_id}: {elapsed:.3f}s")
avg_time = sum(t for _, t in results) / len(results)
print(f"\nAverage execution time: {avg_time:.3f}s")
# Cleanup
pool.close_all()
print("\nPool closed successfully")
if __name__ == "__main__":
main()