-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsetup_step_1_2.sh
More file actions
executable file
Β·316 lines (258 loc) Β· 9.36 KB
/
setup_step_1_2.sh
File metadata and controls
executable file
Β·316 lines (258 loc) Β· 9.36 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
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
#!/bin/bash
# setup_step_1_2.sh
# Run this from your project root (purge-assignment directory)
echo "π Setting up Step 1.2: Database Schema Validation"
echo "=================================================="
echo ""
# Check we're in the right directory
if [ ! -d "store" ] || [ ! -d "migrations" ]; then
echo "β Error: Please run this script from the project root (purge-assignment directory)"
echo " Current directory: $(pwd)"
exit 1
fi
echo "π Creating necessary directories..."
mkdir -p store/src/bin
# 1. Create the performance indexes migration
echo "π Creating migrations/002_performance_indexes.sql..."
cat > migrations/002_performance_indexes.sql << 'MIGRATION_EOF'
-- migrations/002_performance_indexes.sql
-- Performance optimization indexes for Step 1.2
-- ==========================================
-- BALANCES TABLE INDEXES
-- ==========================================
-- Composite index for user-asset lookups (most common query pattern)
CREATE INDEX IF NOT EXISTS idx_balances_user_asset
ON balances(user_id, asset_id);
-- Index for finding non-zero balances by user
CREATE INDEX IF NOT EXISTS idx_balances_user_id_amount
ON balances(user_id, amount)
WHERE amount > 0;
-- ==========================================
-- QUOTES TABLE INDEXES
-- ==========================================
-- Composite index for user quotes with expiration
CREATE INDEX IF NOT EXISTS idx_quotes_user_expires
ON quotes(user_id, expires_at);
-- Partial index for active (non-used) quotes that haven't expired
CREATE INDEX IF NOT EXISTS idx_quotes_expires_at_active
ON quotes(expires_at)
WHERE used = false;
-- Index for recent quotes queries
CREATE INDEX IF NOT EXISTS idx_quotes_created_at
ON quotes(created_at DESC);
-- Index for finding quotes by input/output mints
CREATE INDEX IF NOT EXISTS idx_quotes_mints
ON quotes(input_mint, output_mint);
-- ==========================================
-- USERS TABLE INDEXES
-- ==========================================
-- Index for user analytics and recent signups
CREATE INDEX IF NOT EXISTS idx_users_created_at
ON users(created_at DESC);
-- Index for case-insensitive email lookups
CREATE INDEX IF NOT EXISTS idx_users_email_lower
ON users(LOWER(email));
-- Index on public_key for wallet lookups
CREATE INDEX IF NOT EXISTS idx_users_public_key
ON users(public_key)
WHERE public_key IS NOT NULL;
-- ==========================================
-- ASSETS TABLE INDEXES
-- ==========================================
-- Index for symbol lookups
CREATE INDEX IF NOT EXISTS idx_assets_symbol
ON assets(symbol);
-- ==========================================
-- ANALYZE TABLES FOR QUERY PLANNER
-- ==========================================
ANALYZE users;
ANALYZE assets;
ANALYZE balances;
ANALYZE quotes;
MIGRATION_EOF
# 2. Create the Rust validation test
echo "π Creating store/src/bin/schema_validation.rs..."
cat > store/src/bin/schema_validation.rs << 'RUST_EOF'
// store/src/bin/schema_validation.rs
// Step 1.2: Database Schema Validation and Performance Testing
use anyhow::Result;
use sqlx::{postgres::PgPoolOptions, Pool, Postgres, Row};
use std::time::Instant;
use uuid::Uuid;
#[tokio::main]
async fn main() -> Result<()> {
println!("π Database Schema Validation - Step 1.2");
println!("=========================================\n");
// Get database URL from environment
let database_url = std::env::var("DATABASE_URL")
.unwrap_or_else(|_| "postgres://postgres:password@localhost/solana_wallet".to_string());
println!("π Connecting to database...");
let pool = PgPoolOptions::new()
.max_connections(5)
.connect(&database_url)
.await?;
// Validate tables exist
println!("\nπ Validating Schema Structure");
println!("--------------------------------");
let tables = ["users", "assets", "balances", "quotes"];
for table in &tables {
let exists = sqlx::query_scalar::<_, bool>(
"SELECT EXISTS (
SELECT 1 FROM information_schema.tables
WHERE table_schema = 'public' AND table_name = $1
)"
)
.bind(table)
.fetch_one(&pool)
.await?;
println!(" {} Table '{}'", if exists { "β" } else { "β" }, table);
}
// Check critical columns
println!("\nπ Validating Critical Columns");
println!("--------------------------------");
let has_public_key = sqlx::query_scalar::<_, bool>(
"SELECT EXISTS (
SELECT 1 FROM information_schema.columns
WHERE table_name = 'users' AND column_name = 'public_key'
)"
)
.fetch_one(&pool)
.await?;
println!(" {} users.public_key", if has_public_key { "β" } else { "β" });
let quote_data_type: Option<String> = sqlx::query_scalar(
"SELECT data_type FROM information_schema.columns
WHERE table_name = 'quotes' AND column_name = 'quote_data'"
)
.fetch_optional(&pool)
.await?;
if let Some(data_type) = quote_data_type {
println!(" {} quotes.quote_data is JSONB (type: {})",
if data_type == "jsonb" { "β" } else { "β" }, data_type);
}
// Check indexes
println!("\nπ Index Statistics");
println!("--------------------------------");
let index_count = sqlx::query_scalar::<_, i64>(
"SELECT COUNT(*) FROM pg_indexes
WHERE schemaname = 'public'
AND tablename IN ('users', 'assets', 'balances', 'quotes')"
)
.fetch_one(&pool)
.await?;
println!(" Total indexes: {}", index_count);
// Test query performance
println!("\nβ‘ Query Performance Tests");
println!("--------------------------------");
let start = Instant::now();
let _result = sqlx::query(
"SELECT * FROM users WHERE LOWER(email) = LOWER($1)"
)
.bind("test@example.com")
.fetch_optional(&pool)
.await?;
println!(" User lookup by email: {:?}", start.elapsed());
let start = Instant::now();
let _result = sqlx::query(
"SELECT b.*, a.symbol, a.decimals
FROM balances b
JOIN assets a ON b.asset_id = a.id
WHERE b.user_id = $1"
)
.bind(Uuid::new_v4())
.fetch_all(&pool)
.await?;
println!(" Balance lookup by user: {:?}", start.elapsed());
let start = Instant::now();
let _result = sqlx::query(
"SELECT * FROM quotes
WHERE user_id = $1 AND expires_at > NOW() AND used = false"
)
.bind(Uuid::new_v4())
.fetch_all(&pool)
.await?;
println!(" Active quotes lookup: {:?}", start.elapsed());
// Test sample data insertion
println!("\nπ§ͺ Testing Sample Data Operations");
println!("--------------------------------");
// Start a transaction
let mut tx = pool.begin().await?;
// Create test user
let user_id = Uuid::new_v4();
let email = format!("test-validation-{}@example.com", Uuid::new_v4());
sqlx::query(
"INSERT INTO users (id, email, password_hash, created_at, updated_at)
VALUES ($1, $2, $3, NOW(), NOW())"
)
.bind(&user_id)
.bind(&email)
.bind("test_hash")
.execute(&mut *tx)
.await?;
println!(" β Test user created");
// Rollback (we don't want to keep test data)
tx.rollback().await?;
println!(" β Transaction rolled back");
println!("\nβ
Schema validation complete!");
println!("All tests passed successfully.");
Ok(())
}
RUST_EOF
# 3. Create the validation shell script
echo "π Creating store/validate_schema.sh..."
cat > store/validate_schema.sh << 'SHELL_EOF'
#!/bin/bash
# store/validate_schema.sh
# Script to run Step 1.2: Database Schema Validation
set -e
echo "================================================"
echo "Step 1.2: Database Schema Validation"
echo "================================================"
echo ""
# Set database URL if not already set
export DATABASE_URL="${DATABASE_URL:-postgres://postgres:password@localhost/solana_wallet}"
echo "π Database URL: $DATABASE_URL"
echo ""
# Apply the performance indexes
echo "π Applying performance indexes..."
psql "$DATABASE_URL" < ../migrations/002_performance_indexes.sql 2>/dev/null || {
echo "β
Indexes applied (some may have already existed)"
}
# Build and run the validation test
echo ""
echo "οΏ½οΏ½ Building validation test..."
cargo build --bin schema_validation
echo ""
echo "π§ͺ Running validation test..."
echo ""
cargo run --bin schema_validation
# Show database statistics
echo ""
echo "π Database Statistics:"
echo "----------------------"
psql "$DATABASE_URL" -t << SQL
SELECT
tablename as "Table",
pg_size_pretty(pg_total_relation_size(tablename::regclass)) as "Size"
FROM pg_tables
WHERE schemaname = 'public'
AND tablename IN ('users', 'assets', 'balances', 'quotes')
ORDER BY tablename;
SQL
echo ""
echo "β
Step 1.2 Complete!"
echo ""
SHELL_EOF
# Make the validation script executable
chmod +x store/validate_schema.sh
echo ""
echo "β
Setup complete! Files created:"
echo " β’ migrations/002_performance_indexes.sql"
echo " β’ store/src/bin/schema_validation.rs"
echo " β’ store/validate_schema.sh"
echo ""
echo "π How to run Step 1.2:"
echo " 1. Apply indexes: psql \$DATABASE_URL < migrations/002_performance_indexes.sql"
echo " 2. Run validation: cd store && ./validate_schema.sh"
echo ""
echo "Or run everything at once:"
echo " cd store && ./validate_schema.sh"