-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcheck_postgresql_data.py
More file actions
240 lines (201 loc) Β· 11 KB
/
check_postgresql_data.py
File metadata and controls
240 lines (201 loc) Β· 11 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
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
#!/usr/bin/env python3
"""
Check PostgreSQL database with correct credentials
"""
import sys
from pathlib import Path
sys.path.append(str(Path(__file__).parent))
import psycopg2
from sqlalchemy import create_engine, text
import pandas as pd
from datetime import datetime
# Database credentials from the attachment
DB_CONFIG = {
'database': 'floatchat_db',
'user': 'floatchat_user',
'password': 'floatchat_secure_2025',
'host': 'localhost',
'port': '5432'
}
def check_postgresql_data():
"""Check PostgreSQL database with correct credentials."""
print("π CHECKING POSTGRESQL DATABASE")
print("=" * 50)
print(f"Database: {DB_CONFIG['database']}")
print(f"User: {DB_CONFIG['user']}")
print(f"Host: {DB_CONFIG['host']}:{DB_CONFIG['port']}")
print()
try:
# Create connection string
conn_string = f"postgresql://{DB_CONFIG['user']}:{DB_CONFIG['password']}@{DB_CONFIG['host']}:{DB_CONFIG['port']}/{DB_CONFIG['database']}"
engine = create_engine(conn_string)
with engine.connect() as conn:
print("β
Connected to PostgreSQL successfully!")
# Check what tables exist
tables_query = """
SELECT table_name,
(SELECT COUNT(*) FROM information_schema.columns
WHERE table_name = t.table_name AND table_schema = 'public') as column_count
FROM information_schema.tables t
WHERE table_schema = 'public'
AND table_type = 'BASE TABLE'
ORDER BY table_name;
"""
tables = conn.execute(text(tables_query)).fetchall()
print(f"\nπ Found {len(tables)} tables:")
for table_name, col_count in tables:
print(f" π {table_name} ({col_count} columns)")
# Check each ARGO-related table
argo_tables = ['argo_floats', 'argo_profiles', 'argo_measurements']
for table in argo_tables:
if any(t[0] == table for t in tables):
print(f"\nπ Analyzing {table}:")
try:
# Get row count
count_query = f"SELECT COUNT(*) FROM {table}"
total_rows = conn.execute(text(count_query)).scalar()
print(f" π Total rows: {total_rows:,}")
if total_rows > 0:
# Get column info
columns_query = f"""
SELECT column_name, data_type, is_nullable
FROM information_schema.columns
WHERE table_name = '{table}' AND table_schema = 'public'
ORDER BY ordinal_position;
"""
columns = conn.execute(text(columns_query)).fetchall()
print(f" π Columns: {[col[0] for col in columns]}")
# Try to find date columns
date_columns = [col[0] for col in columns if 'date' in col[0].lower() or 'time' in col[0].lower()]
if date_columns:
print(f" π
Date columns: {date_columns}")
# Check date range for the first date column
date_col = date_columns[0]
try:
date_range_query = f"""
SELECT MIN({date_col}) as earliest,
MAX({date_col}) as latest,
COUNT(DISTINCT {date_col}) as unique_dates
FROM {table}
WHERE {date_col} IS NOT NULL
"""
date_result = conn.execute(text(date_range_query)).fetchone()
print(f" π
Date range ({date_col}): {date_result[0]} to {date_result[1]}")
print(f" π
Unique dates: {date_result[2]:,}")
# Check year distribution
year_query = f"""
SELECT EXTRACT(YEAR FROM {date_col}) as year,
COUNT(*) as count
FROM {table}
WHERE {date_col} IS NOT NULL
GROUP BY EXTRACT(YEAR FROM {date_col})
ORDER BY year;
"""
year_results = conn.execute(text(year_query)).fetchall()
print(f" π Year distribution:")
for year, count in year_results:
print(f" {int(year)}: {count:,} records")
# Check for 2024 data specifically
count_2024 = conn.execute(text(f"""
SELECT COUNT(*) FROM {table}
WHERE EXTRACT(YEAR FROM {date_col}) = 2024
""")).scalar()
print(f" π― 2024 data: {count_2024:,} records")
# Check for October 2024
count_oct_2024 = conn.execute(text(f"""
SELECT COUNT(*) FROM {table}
WHERE EXTRACT(YEAR FROM {date_col}) = 2024
AND EXTRACT(MONTH FROM {date_col}) = 10
""")).scalar()
print(f" π― October 2024: {count_oct_2024:,} records")
except Exception as e:
print(f" β Date analysis error: {e}")
# Sample some data
try:
sample_query = f"SELECT * FROM {table} LIMIT 3"
sample_results = conn.execute(text(sample_query)).fetchall()
if sample_results:
print(f" π Sample record columns: {list(sample_results[0].keys())}")
except Exception as e:
print(f" β Sample query error: {e}")
except Exception as e:
print(f" β Error analyzing {table}: {e}")
else:
print(f"\nβ Table {table} not found")
# Check for any processing logs or status tables
print(f"\nπ Checking for processing logs:")
log_tables = ['processing_logs', 'data_quality', 'etl_status', 'import_status']
for log_table in log_tables:
if any(t[0] == log_table for t in tables):
try:
count = conn.execute(text(f"SELECT COUNT(*) FROM {log_table}")).scalar()
print(f" π {log_table}: {count:,} records")
# Get recent logs
recent_logs = conn.execute(text(f"SELECT * FROM {log_table} ORDER BY id DESC LIMIT 3")).fetchall()
if recent_logs:
print(f" Recent entries: {len(recent_logs)}")
except Exception as e:
print(f" β {log_table} error: {e}")
return True
except Exception as e:
print(f"β Database connection error: {e}")
print(f" This might mean:")
print(f" 1. PostgreSQL server is not running")
print(f" 2. Database 'floatchat_db' doesn't exist")
print(f" 3. User 'floatchat_user' doesn't have access")
print(f" 4. Password is incorrect")
return False
def check_database_server():
"""Check if PostgreSQL server is running."""
print(f"\nπ CHECKING POSTGRESQL SERVER STATUS")
print("=" * 50)
try:
# Try to connect to default postgres database
basic_conn_string = f"postgresql://{DB_CONFIG['user']}:{DB_CONFIG['password']}@{DB_CONFIG['host']}:{DB_CONFIG['port']}/postgres"
engine = create_engine(basic_conn_string)
with engine.connect() as conn:
print("β
PostgreSQL server is running!")
# Check if our database exists
db_check_query = """
SELECT datname FROM pg_database
WHERE datname = 'floatchat_db';
"""
result = conn.execute(text(db_check_query)).fetchone()
if result:
print("β
Database 'floatchat_db' exists!")
else:
print("β Database 'floatchat_db' does not exist!")
# List available databases
list_db_query = "SELECT datname FROM pg_database WHERE datistemplate = false;"
databases = conn.execute(text(list_db_query)).fetchall()
print(f" Available databases: {[db[0] for db in databases]}")
return True
except Exception as e:
print(f"β Server connection error: {e}")
return False
def main():
"""Run PostgreSQL data check."""
print("π POSTGRESQL DATA VERIFICATION")
print("=" * 70)
print(f"Checking if ARGO data is safely stored in PostgreSQL...")
print()
# First check if server is running
server_ok = check_database_server()
if server_ok:
# Then check our specific database
data_ok = check_postgresql_data()
print(f"\nπ POSTGRESQL STATUS SUMMARY")
print("=" * 40)
print(f"Server Status: {'β
RUNNING' if server_ok else 'β NOT RUNNING'}")
print(f"Data Status: {'β
ACCESSIBLE' if data_ok else 'β ISSUES FOUND'}")
if data_ok:
print(f"\nπ POSTGRESQL DATA IS SAFE!")
print("Your ARGO data appears to be properly stored in PostgreSQL.")
else:
print(f"\nβ οΈ POSTGRESQL DATA ISSUES DETECTED!")
print("The data may not be properly loaded or accessible.")
else:
print(f"\nβ POSTGRESQL SERVER NOT ACCESSIBLE!")
print("Need to start PostgreSQL server or check connection settings.")
if __name__ == "__main__":
main()