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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
|
#!/usr/bin/env python3
"""
Test client for SeaweedFS PostgreSQL protocol support.
This script demonstrates how to connect to SeaweedFS using standard PostgreSQL
libraries and execute various types of queries.
Requirements:
pip install psycopg2-binary
Usage:
python test_client.py
python test_client.py --host localhost --port 5432 --user seaweedfs --database default
"""
import sys
import argparse
import time
import traceback
try:
import psycopg2
import psycopg2.extras
except ImportError:
print("Error: psycopg2 not found. Install with: pip install psycopg2-binary")
sys.exit(1)
def test_connection(host, port, user, database, password=None):
"""Test basic connection to SeaweedFS PostgreSQL server."""
print(f"๐ Testing connection to {host}:{port}/{database} as user '{user}'")
try:
conn_params = {
'host': host,
'port': port,
'user': user,
'database': database,
'connect_timeout': 10
}
if password:
conn_params['password'] = password
conn = psycopg2.connect(**conn_params)
print("โ
Connection successful!")
# Test basic query
cursor = conn.cursor()
cursor.execute("SELECT 1 as test")
result = cursor.fetchone()
print(f"โ
Basic query successful: {result}")
cursor.close()
conn.close()
return True
except Exception as e:
print(f"โ Connection failed: {e}")
return False
def test_system_queries(host, port, user, database, password=None):
"""Test PostgreSQL system queries."""
print("\n๐ง Testing PostgreSQL system queries...")
try:
conn_params = {
'host': host,
'port': port,
'user': user,
'database': database
}
if password:
conn_params['password'] = password
conn = psycopg2.connect(**conn_params)
cursor = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
system_queries = [
("Version", "SELECT version()"),
("Current Database", "SELECT current_database()"),
("Current User", "SELECT current_user"),
("Server Encoding", "SELECT current_setting('server_encoding')"),
("Client Encoding", "SELECT current_setting('client_encoding')"),
]
for name, query in system_queries:
try:
cursor.execute(query)
result = cursor.fetchone()
print(f" โ
{name}: {result[0]}")
except Exception as e:
print(f" โ {name}: {e}")
cursor.close()
conn.close()
except Exception as e:
print(f"โ System queries failed: {e}")
def test_schema_queries(host, port, user, database, password=None):
"""Test schema and metadata queries."""
print("\n๐ Testing schema queries...")
try:
conn_params = {
'host': host,
'port': port,
'user': user,
'database': database
}
if password:
conn_params['password'] = password
conn = psycopg2.connect(**conn_params)
cursor = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
schema_queries = [
("Show Databases", "SHOW DATABASES"),
("Show Tables", "SHOW TABLES"),
("List Schemas", "SELECT 'public' as schema_name"),
]
for name, query in schema_queries:
try:
cursor.execute(query)
results = cursor.fetchall()
print(f" โ
{name}: Found {len(results)} items")
for row in results[:3]: # Show first 3 results
print(f" - {dict(row)}")
if len(results) > 3:
print(f" ... and {len(results) - 3} more")
except Exception as e:
print(f" โ {name}: {e}")
cursor.close()
conn.close()
except Exception as e:
print(f"โ Schema queries failed: {e}")
def test_data_queries(host, port, user, database, password=None):
"""Test data queries on actual topics."""
print("\n๐ Testing data queries...")
try:
conn_params = {
'host': host,
'port': port,
'user': user,
'database': database
}
if password:
conn_params['password'] = password
conn = psycopg2.connect(**conn_params)
cursor = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
# First, try to get available tables/topics
cursor.execute("SHOW TABLES")
tables = cursor.fetchall()
if not tables:
print(" โน๏ธ No tables/topics found for data testing")
cursor.close()
conn.close()
return
# Test with first available table
table_name = tables[0][0] if tables[0] else 'test_topic'
print(f" ๐ Testing with table: {table_name}")
test_queries = [
(f"Count records in {table_name}", f"SELECT COUNT(*) FROM \"{table_name}\""),
(f"Sample data from {table_name}", f"SELECT * FROM \"{table_name}\" LIMIT 3"),
(f"System columns from {table_name}", f"SELECT _timestamp_ns, _key, _source FROM \"{table_name}\" LIMIT 3"),
(f"Describe {table_name}", f"DESCRIBE \"{table_name}\""),
]
for name, query in test_queries:
try:
cursor.execute(query)
results = cursor.fetchall()
if "COUNT" in query.upper():
count = results[0][0] if results else 0
print(f" โ
{name}: {count} records")
elif "DESCRIBE" in query.upper():
print(f" โ
{name}: {len(results)} columns")
for row in results[:5]: # Show first 5 columns
print(f" - {dict(row)}")
else:
print(f" โ
{name}: {len(results)} rows")
for row in results:
print(f" - {dict(row)}")
except Exception as e:
print(f" โ {name}: {e}")
cursor.close()
conn.close()
except Exception as e:
print(f"โ Data queries failed: {e}")
def test_prepared_statements(host, port, user, database, password=None):
"""Test prepared statements."""
print("\n๐ Testing prepared statements...")
try:
conn_params = {
'host': host,
'port': port,
'user': user,
'database': database
}
if password:
conn_params['password'] = password
conn = psycopg2.connect(**conn_params)
cursor = conn.cursor()
# Test parameterized query
try:
cursor.execute("SELECT %s as param1, %s as param2", ("hello", 42))
result = cursor.fetchone()
print(f" โ
Prepared statement: {result}")
except Exception as e:
print(f" โ Prepared statement: {e}")
cursor.close()
conn.close()
except Exception as e:
print(f"โ Prepared statements test failed: {e}")
def test_transaction_support(host, port, user, database, password=None):
"""Test transaction support (should be no-op for read-only)."""
print("\n๐ Testing transaction support...")
try:
conn_params = {
'host': host,
'port': port,
'user': user,
'database': database
}
if password:
conn_params['password'] = password
conn = psycopg2.connect(**conn_params)
cursor = conn.cursor()
transaction_commands = [
"BEGIN",
"SELECT 1 as in_transaction",
"COMMIT",
"SELECT 1 as after_commit",
]
for cmd in transaction_commands:
try:
cursor.execute(cmd)
if "SELECT" in cmd:
result = cursor.fetchone()
print(f" โ
{cmd}: {result}")
else:
print(f" โ
{cmd}: OK")
except Exception as e:
print(f" โ {cmd}: {e}")
cursor.close()
conn.close()
except Exception as e:
print(f"โ Transaction test failed: {e}")
def test_performance(host, port, user, database, password=None, iterations=10):
"""Test query performance."""
print(f"\nโก Testing performance ({iterations} iterations)...")
try:
conn_params = {
'host': host,
'port': port,
'user': user,
'database': database
}
if password:
conn_params['password'] = password
times = []
for i in range(iterations):
start_time = time.time()
conn = psycopg2.connect(**conn_params)
cursor = conn.cursor()
cursor.execute("SELECT 1")
result = cursor.fetchone()
cursor.close()
conn.close()
elapsed = time.time() - start_time
times.append(elapsed)
if i < 3: # Show first 3 iterations
print(f" Iteration {i+1}: {elapsed:.3f}s")
avg_time = sum(times) / len(times)
min_time = min(times)
max_time = max(times)
print(f" โ
Performance results:")
print(f" - Average: {avg_time:.3f}s")
print(f" - Min: {min_time:.3f}s")
print(f" - Max: {max_time:.3f}s")
except Exception as e:
print(f"โ Performance test failed: {e}")
def main():
parser = argparse.ArgumentParser(description="Test SeaweedFS PostgreSQL Protocol")
parser.add_argument("--host", default="localhost", help="PostgreSQL server host")
parser.add_argument("--port", type=int, default=5432, help="PostgreSQL server port")
parser.add_argument("--user", default="seaweedfs", help="PostgreSQL username")
parser.add_argument("--password", help="PostgreSQL password")
parser.add_argument("--database", default="default", help="PostgreSQL database")
parser.add_argument("--skip-performance", action="store_true", help="Skip performance tests")
args = parser.parse_args()
print("๐งช SeaweedFS PostgreSQL Protocol Test Client")
print("=" * 50)
# Test basic connection first
if not test_connection(args.host, args.port, args.user, args.database, args.password):
print("\nโ Basic connection failed. Cannot continue with other tests.")
sys.exit(1)
# Run all tests
try:
test_system_queries(args.host, args.port, args.user, args.database, args.password)
test_schema_queries(args.host, args.port, args.user, args.database, args.password)
test_data_queries(args.host, args.port, args.user, args.database, args.password)
test_prepared_statements(args.host, args.port, args.user, args.database, args.password)
test_transaction_support(args.host, args.port, args.user, args.database, args.password)
if not args.skip_performance:
test_performance(args.host, args.port, args.user, args.database, args.password)
except KeyboardInterrupt:
print("\n\nโ ๏ธ Tests interrupted by user")
sys.exit(0)
except Exception as e:
print(f"\nโ Unexpected error during testing: {e}")
traceback.print_exc()
sys.exit(1)
print("\n๐ All tests completed!")
print("\nTo use SeaweedFS with PostgreSQL tools:")
print(f" psql -h {args.host} -p {args.port} -U {args.user} -d {args.database}")
print(f" Connection string: postgresql://{args.user}@{args.host}:{args.port}/{args.database}")
if __name__ == "__main__":
main()
|