-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinspect_database.js
More file actions
420 lines (373 loc) ยท 14.5 KB
/
Copy pathinspect_database.js
File metadata and controls
420 lines (373 loc) ยท 14.5 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
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
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
#!/usr/bin/env node
/**
* Database Inspection Script for ProofEstate
*
* This script connects to the PostgreSQL database and provides
* an interactive way to inspect the data and see correlations
* between on-chain and database records.
*
* Usage: node inspect_database.js
*/
const { Client } = require('pg');
const readline = require('readline');
// Database connection
const client = new Client({
host: 'localhost',
port: 5432,
database: 'proofestate_db',
user: 'postgres',
password: 'password123'
});
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
async function connectDB() {
try {
await client.connect();
console.log('โ
Connected to ProofEstate database');
return true;
} catch (error) {
console.error('โ Database connection failed:', error.message);
console.log('\n๐ Make sure PostgreSQL is running and credentials are correct.');
console.log(' Check DATABASE_ACCESS.md for connection details.');
return false;
}
}
async function showMenu() {
console.log('\n๐ ProofEstate Database Inspector');
console.log('================================');
console.log('1. View all properties');
console.log('2. View properties by status');
console.log('3. View users');
console.log('4. View token holdings');
console.log('5. View rent distributions');
console.log('6. Show on-chain vs database correlation');
console.log('7. Property analytics');
console.log('8. Run custom SQL query');
console.log('9. Exit');
console.log('================================');
}
async function viewProperties() {
try {
const result = await client.query(`
SELECT id, name, address, property_type, status,
asset_value_inr, token_mint, on_chain_address,
created_at
FROM properties
ORDER BY created_at DESC
`);
console.log('\n๐ Properties Overview:');
console.table(result.rows.map(row => ({
ID: row.id.substring(0, 8) + '...',
Name: row.name.substring(0, 30),
Status: row.status,
Type: row.property_type,
Value: `โน${(row.asset_value_inr / 10000000).toFixed(1)}CR`,
'Token Mint': row.token_mint ? row.token_mint.substring(0, 8) + '...' : 'None',
'On-Chain': row.on_chain_address ? 'Yes' : 'No'
})));
console.log(`\nTotal properties: ${result.rows.length}`);
} catch (error) {
console.error('Error fetching properties:', error.message);
}
}
async function viewPropertiesByStatus() {
try {
const result = await client.query(`
SELECT status, COUNT(*) as count,
AVG(asset_value_inr) as avg_value
FROM properties
GROUP BY status
ORDER BY count DESC
`);
console.log('\n๐ Properties by Status:');
console.table(result.rows.map(row => ({
Status: row.status,
Count: row.count,
'Avg Value (CR)': row.avg_value ? `โน${(row.avg_value / 10000000).toFixed(1)}CR` : 'N/A'
})));
} catch (error) {
console.error('Error fetching property stats:', error.message);
}
}
async function viewUsers() {
try {
const result = await client.query(`
SELECT wallet, name, role, email, created_at
FROM users
ORDER BY created_at DESC
`);
console.log('\n๐ฅ Users:');
console.table(result.rows.map(row => ({
Wallet: row.wallet.substring(0, 20) + '...',
Name: row.name || 'N/A',
Role: row.role,
Email: row.email || 'N/A',
Created: new Date(row.created_at).toLocaleDateString()
})));
console.log(`\nTotal users: ${result.rows.length}`);
} catch (error) {
console.error('Error fetching users:', error.message);
}
}
async function viewTokenHoldings() {
try {
const result = await client.query(`
SELECT th.holder_wallet, th.token_amount, th.last_updated,
p.name as property_name, p.token_mint
FROM token_holdings th
JOIN properties p ON th.property_id = p.id
WHERE th.token_amount > 0
ORDER BY th.token_amount DESC
`);
console.log('\n๐ช Token Holdings:');
if (result.rows.length === 0) {
console.log('No token holdings found. Tokens are created when properties are tokenized.');
} else {
console.table(result.rows.map(row => ({
Property: row.property_name.substring(0, 30),
Holder: row.holder_wallet.substring(0, 20) + '...',
Tokens: row.token_amount.toLocaleString(),
'Token Mint': row.token_mint ? row.token_mint.substring(0, 8) + '...' : 'N/A',
Updated: new Date(row.last_updated).toLocaleDateString()
})));
}
console.log(`\nTotal holdings: ${result.rows.length}`);
} catch (error) {
console.error('Error fetching token holdings:', error.message);
}
}
async function viewRentDistributions() {
try {
const result = await client.query(`
SELECT rd.total_amount_usdc, rd.rate_per_token, rd.distribution_date,
rd.tx_signature, p.name as property_name
FROM rent_distributions rd
JOIN properties p ON rd.property_id = p.id
ORDER BY rd.distribution_date DESC
`);
console.log('\n๐ฐ Rent Distributions:');
if (result.rows.length === 0) {
console.log('No rent distributions found. These are created when property owners distribute rental income.');
} else {
console.table(result.rows.map(row => ({
Property: row.property_name.substring(0, 30),
'Amount (USDC)': `$${row.total_amount_usdc}`,
'Rate/Token': `$${row.rate_per_token}`,
Date: new Date(row.distribution_date).toLocaleDateString(),
'TX Signature': row.tx_signature ? row.tx_signature.substring(0, 8) + '...' : 'N/A'
})));
}
console.log(`\nTotal distributions: ${result.rows.length}`);
} catch (error) {
console.error('Error fetching rent distributions:', error.message);
}
}
async function showCorrelation() {
try {
const result = await client.query(`
SELECT
p.id,
p.name,
p.status,
p.on_chain_address,
p.token_mint,
p.metadata_hash,
COALESCE(th.total_tokens_held, 0) as tokens_held,
COALESCE(rd.total_distributions, 0) as rent_distributions,
COALESCE(rd.total_rent_paid, 0) as total_rent_paid
FROM properties p
LEFT JOIN (
SELECT property_id,
SUM(token_amount) as total_tokens_held,
COUNT(*) as holders
FROM token_holdings
WHERE token_amount > 0
GROUP BY property_id
) th ON p.id = th.property_id
LEFT JOIN (
SELECT property_id,
COUNT(*) as total_distributions,
SUM(total_amount_usdc) as total_rent_paid
FROM rent_distributions
GROUP BY property_id
) rd ON p.id = rd.property_id
ORDER BY p.created_at DESC
`);
console.log('\n๐ On-Chain vs Database Correlation:');
console.log('=====================================');
result.rows.forEach((row, index) => {
console.log(`\n${index + 1}. ${row.name}`);
console.log(` Status: ${row.status}`);
console.log(` Database ID: ${row.id}`);
console.log(` On-Chain Address: ${row.on_chain_address || 'Not deployed'}`);
console.log(` Token Mint: ${row.token_mint || 'Not tokenized'}`);
console.log(` Metadata Hash: ${row.metadata_hash || 'Not set'}`);
console.log(` Tokens Held: ${row.tokens_held.toLocaleString()}`);
console.log(` Rent Distributions: ${row.rent_distributions}`);
console.log(` Total Rent Paid: $${row.total_rent_paid || 0}`);
// Analysis
const hasOnChain = row.on_chain_address && row.token_mint;
const hasTokens = row.tokens_held > 0;
const hasRent = row.rent_distributions > 0;
console.log(` ๐ Analysis:`);
if (hasOnChain && hasTokens) {
console.log(` โ
Properly tokenized with active holders`);
} else if (hasOnChain && !hasTokens) {
console.log(` โ ๏ธ Tokenized but no token holders recorded`);
} else if (!hasOnChain && row.status === 'tokenized') {
console.log(` โ Status shows tokenized but missing on-chain data`);
} else {
console.log(` โน๏ธ Not yet tokenized (status: ${row.status})`);
}
if (hasRent) {
console.log(` ๐ฐ Has rent distribution history`);
}
});
// Summary
const tokenizedCount = result.rows.filter(r => r.on_chain_address).length;
const withTokensCount = result.rows.filter(r => r.tokens_held > 0).length;
const withRentCount = result.rows.filter(r => r.rent_distributions > 0).length;
console.log('\n๐ Summary:');
console.log(` Total Properties: ${result.rows.length}`);
console.log(` On-Chain Deployed: ${tokenizedCount}`);
console.log(` With Token Holders: ${withTokensCount}`);
console.log(` With Rent History: ${withRentCount}`);
} catch (error) {
console.error('Error showing correlation:', error.message);
}
}
async function propertyAnalytics() {
try {
console.log('\n๐ Property Analytics:');
console.log('=====================');
// Value distribution
const valueResult = await client.query(`
SELECT
CASE
WHEN asset_value_inr < 10000000 THEN 'Under โน1CR'
WHEN asset_value_inr < 50000000 THEN 'โน1-5CR'
WHEN asset_value_inr < 100000000 THEN 'โน5-10CR'
ELSE 'Over โน10CR'
END as value_range,
COUNT(*) as count,
AVG(asset_value_inr) as avg_value
FROM properties
WHERE asset_value_inr IS NOT NULL
GROUP BY value_range
ORDER BY avg_value
`);
console.log('\n๐ฐ Value Distribution:');
console.table(valueResult.rows);
// Property types
const typeResult = await client.query(`
SELECT property_type, COUNT(*) as count,
AVG(asset_value_inr) as avg_value
FROM properties
WHERE property_type IS NOT NULL
GROUP BY property_type
ORDER BY count DESC
`);
console.log('\n๐ข Property Types:');
console.table(typeResult.rows.map(row => ({
Type: row.property_type,
Count: row.count,
'Avg Value (CR)': row.avg_value ? `โน${(row.avg_value / 10000000).toFixed(1)}CR` : 'N/A'
})));
// Status progression
const statusResult = await client.query(`
SELECT status, COUNT(*) as count,
ROUND(COUNT(*) * 100.0 / (SELECT COUNT(*) FROM properties), 1) as percentage
FROM properties
GROUP BY status
ORDER BY count DESC
`);
console.log('\n๐ Status Distribution:');
console.table(statusResult.rows.map(row => ({
Status: row.status,
Count: row.count,
Percentage: `${row.percentage}%`
})));
} catch (error) {
console.error('Error generating analytics:', error.message);
}
}
async function runCustomQuery() {
return new Promise((resolve) => {
rl.question('\n๐ป Enter SQL query: ', async (query) => {
try {
const result = await client.query(query);
if (result.rows.length === 0) {
console.log('No results returned.');
} else {
console.log(`\n๐ Query Results (${result.rows.length} rows):`);
console.table(result.rows);
}
} catch (error) {
console.error('Query error:', error.message);
}
resolve();
});
});
}
async function main() {
console.log('๐ ProofEstate Database Inspector');
console.log('=================================');
const connected = await connectDB();
if (!connected) {
process.exit(1);
}
while (true) {
await showMenu();
const choice = await new Promise((resolve) => {
rl.question('\nSelect option (1-9): ', resolve);
});
switch (choice) {
case '1':
await viewProperties();
break;
case '2':
await viewPropertiesByStatus();
break;
case '3':
await viewUsers();
break;
case '4':
await viewTokenHoldings();
break;
case '5':
await viewRentDistributions();
break;
case '6':
await showCorrelation();
break;
case '7':
await propertyAnalytics();
break;
case '8':
await runCustomQuery();
break;
case '9':
console.log('\n๐ Goodbye!');
await client.end();
rl.close();
process.exit(0);
default:
console.log('Invalid option. Please try again.');
}
await new Promise((resolve) => {
rl.question('\nPress Enter to continue...', resolve);
});
}
}
// Handle cleanup
process.on('SIGINT', async () => {
console.log('\n\n๐ Shutting down...');
await client.end();
rl.close();
process.exit(0);
});
if (require.main === module) {
main().catch(console.error);
}