|
| 1 | +#!/usr/bin/env python3 |
| 2 | +""" |
| 3 | +🚀 Instant AsyncPG + PostgreSQL |
| 4 | +================================ |
| 5 | +
|
| 6 | +Zero-config asyncpg with real PostgreSQL in 30 seconds. |
| 7 | +Shows the proper configuration for asyncpg with py-pglite. |
| 8 | +
|
| 9 | +Usage: |
| 10 | + pip install py-pglite[asyncpg] |
| 11 | + python simple_asyncpg.py |
| 12 | +
|
| 13 | +Recent findings: asyncpg DOES work with PGlite TCP mode when configured properly! |
| 14 | +""" |
| 15 | + |
| 16 | +import asyncio |
| 17 | +import json |
| 18 | +import logging |
| 19 | + |
| 20 | +from py_pglite import PGliteConfig |
| 21 | +from py_pglite import PGliteManager |
| 22 | + |
| 23 | + |
| 24 | +logger = logging.getLogger(__name__) |
| 25 | + |
| 26 | + |
| 27 | +try: |
| 28 | + import asyncpg |
| 29 | +except ImportError: |
| 30 | + logger.info( |
| 31 | + "❌ asyncpg not available. Install with: pip install py-pglite[asyncpg]" |
| 32 | + ) |
| 33 | + exit(1) |
| 34 | + |
| 35 | + |
| 36 | +async def main(): |
| 37 | + """⚡ Instant PostgreSQL with asyncpg - proper configuration!""" |
| 38 | + |
| 39 | + # print("🚀 Starting py-pglite with asyncpg...") |
| 40 | + |
| 41 | + # Enable TCP mode (required for asyncpg) |
| 42 | + config = PGliteConfig(use_tcp=True, tcp_port=5432) |
| 43 | + |
| 44 | + with PGliteManager(config): |
| 45 | + logger.info(f"✅ PGlite started on {config.tcp_host}:{config.tcp_port}") |
| 46 | + |
| 47 | + # Connect with asyncpg using the CRITICAL configuration discovered |
| 48 | + # Key finding: server_settings={} prevents hanging! |
| 49 | + conn = await asyncio.wait_for( |
| 50 | + asyncpg.connect( |
| 51 | + host=config.tcp_host, |
| 52 | + port=config.tcp_port, |
| 53 | + user="postgres", |
| 54 | + password="postgres", |
| 55 | + database="postgres", |
| 56 | + ssl=False, |
| 57 | + server_settings={}, # CRITICAL: Empty server_settings prevents hanging |
| 58 | + ), |
| 59 | + timeout=10.0, |
| 60 | + ) |
| 61 | + |
| 62 | + try: |
| 63 | + logger.info("✅ Connected to PostgreSQL via asyncpg!") |
| 64 | + |
| 65 | + # Test 1: Basic query |
| 66 | + result = await conn.fetchval("SELECT version()") |
| 67 | + logger.info(f"📊 PostgreSQL Version: {result[:50]}...") |
| 68 | + |
| 69 | + # Test 2: Create table with advanced types |
| 70 | + await conn.execute(""" |
| 71 | + CREATE TABLE async_demo ( |
| 72 | + id SERIAL PRIMARY KEY, |
| 73 | + name TEXT NOT NULL, |
| 74 | + data JSONB, |
| 75 | + tags TEXT[], |
| 76 | + created TIMESTAMP DEFAULT NOW() |
| 77 | + ) |
| 78 | + """) |
| 79 | + logger.info("✅ Table created with JSONB and array support!") |
| 80 | + |
| 81 | + # Test 3: Insert with prepared statements |
| 82 | + stmt = await conn.prepare(""" |
| 83 | + INSERT INTO async_demo (name, data, tags) |
| 84 | + VALUES ($1, $2, $3) RETURNING id |
| 85 | + """) |
| 86 | + |
| 87 | + user_id = await stmt.fetchval( |
| 88 | + "Alice", |
| 89 | + json.dumps({"role": "admin", "score": 95}), |
| 90 | + ["python", "asyncpg", "postgresql"], |
| 91 | + ) |
| 92 | + logger.info(f"✅ Inserted user with ID: {user_id}") |
| 93 | + |
| 94 | + # Test 4: Complex query with JSON operations |
| 95 | + row = await conn.fetchrow( |
| 96 | + """ |
| 97 | + SELECT |
| 98 | + name, |
| 99 | + data->>'role' as role, |
| 100 | + data->>'score' as score, |
| 101 | + array_length(tags, 1) as tag_count, |
| 102 | + created |
| 103 | + FROM async_demo |
| 104 | + WHERE id = $1 |
| 105 | + """, |
| 106 | + user_id, |
| 107 | + ) |
| 108 | + |
| 109 | + logger.info("✅ Query result:") |
| 110 | + logger.info(f" Name: {row['name']}") |
| 111 | + logger.info(f" Role: {row['role']}") |
| 112 | + logger.info(f" Score: {row['score']}") |
| 113 | + logger.info(f" Tags: {row['tag_count']} tags") |
| 114 | + logger.info(f" Created: {row['created']}") |
| 115 | + |
| 116 | + # Test 5: Transaction support |
| 117 | + async with conn.transaction(): |
| 118 | + await conn.execute(""" |
| 119 | + INSERT INTO async_demo (name, data, tags) VALUES |
| 120 | + ('Bob', '{"role": "user"}', ARRAY['beginner']), |
| 121 | + ('Carol', '{"role": "moderator"}', ARRAY['advanced', 'helper']) |
| 122 | + """) |
| 123 | + count = await conn.fetchval("SELECT COUNT(*) FROM async_demo") |
| 124 | + logger.info(f"✅ Transaction: {count} total records") |
| 125 | + |
| 126 | + # Test 6: Batch operations |
| 127 | + batch_data = [ |
| 128 | + (f"User{i}", json.dumps({"level": i}), [f"tag{i}", "batch"]) |
| 129 | + for i in range(1, 4) |
| 130 | + ] |
| 131 | + |
| 132 | + await conn.executemany( |
| 133 | + """ |
| 134 | + INSERT INTO async_demo (name, data, tags) VALUES ($1, $2, $3) |
| 135 | + """, |
| 136 | + batch_data, |
| 137 | + ) |
| 138 | + |
| 139 | + final_count = await conn.fetchval("SELECT COUNT(*) FROM async_demo") |
| 140 | + logger.info(f"✅ Batch insert completed: {final_count} total records") |
| 141 | + |
| 142 | + # Test 7: Advanced PostgreSQL features |
| 143 | + stats = await conn.fetchrow(""" |
| 144 | + SELECT |
| 145 | + COUNT(*) as total_users, |
| 146 | + COUNT(*) FILTER (WHERE data->>'role' = 'admin') as admins, |
| 147 | + AVG((data->>'score')::int) FILTER (WHERE data ? 'score') as avg_score |
| 148 | + FROM async_demo |
| 149 | + """) |
| 150 | + |
| 151 | + # print("✅ Advanced query:") |
| 152 | + logger.info(f" Total users: {stats['total_users']}") |
| 153 | + logger.info(f" Admins: {stats['admins']}") |
| 154 | + logger.info(f" Avg score: {stats['avg_score']}") |
| 155 | + |
| 156 | + finally: |
| 157 | + # Handle connection cleanup with timeout (addresses hanging issue) |
| 158 | + try: |
| 159 | + await asyncio.wait_for(conn.close(), timeout=5.0) |
| 160 | + logger.info("✅ Connection closed cleanly") |
| 161 | + except asyncio.TimeoutError: |
| 162 | + logger.info("⚠️ Connection cleanup timed out (known limitation)") |
| 163 | + # This is not a failure - all operations completed successfully |
| 164 | + |
| 165 | + logger.info("🎉 asyncpg + py-pglite demo completed successfully!") |
| 166 | + logger.info( |
| 167 | + "💡 Key finding: server_settings={} is critical for asyncpg compatibility" |
| 168 | + ) |
| 169 | + |
| 170 | + |
| 171 | +if __name__ == "__main__": |
| 172 | + asyncio.run(main()) |
0 commit comments