-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathURLShortnerDB.cpp
More file actions
715 lines (602 loc) · 25.7 KB
/
URLShortnerDB.cpp
File metadata and controls
715 lines (602 loc) · 25.7 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
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
#include "URLShortnerDB.h"
#include "Config.h"
#include "Modals/UserDTO.h"
#include "Modals/SessionDTO.h"
#include "Modals/ShortenedLink.h"
#include "Modals/QuotaDTO.h"
#include <iostream>
#include <sstream>
#include <stdexcept>
#include <fstream>
#include <iomanip>
#include <chrono>
using std::cerr;
using std::cout;
using std::endl;
using std::string;
using std::unique_ptr;
using std::runtime_error;
using std::lock_guard;
using std::unique_lock;
using mysqlx::abi2::Value;
using mysqlx::abi2::RowResult;
// --- CONNECTION POOL HELPERS ---
std::unique_ptr<mysqlx::Session> UrlShortenerDB::getConnection() {
unique_lock<std::mutex> lock(poolMutex);
// Wait until the pool has a connection available (with a timeout)
if (connectionPool.empty()) {
if (poolCv.wait_for(lock, std::chrono::seconds(5)) == std::cv_status::timeout) {
throw std::runtime_error("Database pool timeout: No connections available.");
}
}
if (connectionPool.empty()) {
throw std::runtime_error("Database pool is empty after waiting.");
}
// De-queue the connection and return it
std::unique_ptr<mysqlx::Session> session = std::move(connectionPool.front());
connectionPool.pop();
return session;
}
std::string UrlShortenerDB::getConfig(mysqlx::Session& currentSession, std::string key){
std::string value = "";
try
{
string sql = "SELECT setting_value FROM global_settings WHERE setting_key = ?";
// Use the passed-in currentSession
auto result = executeStatement(currentSession, sql, {Value(key)});
if (auto row = result->fetchOne()) {
value = row[0].get<string>();
}
}
catch(const std::exception& e)
{
value = "invalid request";
}
// Removed returnConnection(std::move(currentSession));
return value;
}
void UrlShortenerDB::returnConnection(std::unique_ptr<mysqlx::Session> session) {
if (session) {
lock_guard<std::mutex> lock(poolMutex);
connectionPool.push(std::move(session));
poolCv.notify_one(); // Notify one waiting thread that a connection is free
}
}
// --- Helper Functions ---
string UrlShortenerDB::getTodayDate() {
time_t now = time(nullptr);
struct tm *ltm = localtime(&now);
char buffer[11]; // YYYY-MM-DD\0
strftime(buffer, sizeof(buffer), "%Y-%m-%d", ltm);
return buffer;
}
// Generates a future timestamp for session/link expiration
string UrlShortenerDB::getFutureTimestamp(int days) {
auto now = std::chrono::system_clock::now();
auto future = now + std::chrono::minutes(24 * days);
time_t future_time = std::chrono::system_clock::to_time_t(future);
struct tm *ltm = localtime(&future_time);
char buffer[20];
strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", ltm);
return buffer;
}
// Helper function to get the current time (YYYY-MM-DD HH:MM:SS)
string UrlShortenerDB::getCurrentTimestamp() {
time_t now = time(nullptr);
struct tm *ltm = localtime(&now);
char buffer[20];
strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", ltm);
return buffer;
}
// Helper method implementation (DECOUPLED FROM SHARED MEMBER)
unique_ptr<RowResult> UrlShortenerDB::executeStatement(
mysqlx::Session& currentSession, // Session parameter
const string& sql,
const std::vector<Value>& params
) {
// Create the statement object using the provided session
mysqlx::SqlStatement stmt = currentSession.sql(sql);
// Bind parameters
for (const auto& param : params) {
stmt.bind(param);
}
// Execute the statement and return the result
return unique_ptr<RowResult>(new RowResult(stmt.execute()));
}
// --- UrlShortenerDB Implementation ---
UrlShortenerDB::UrlShortenerDB() {
// Default pool size
}
UrlShortenerDB::~UrlShortenerDB() {
// All sessions in the pool are closed automatically when unique_ptr is destroyed
}
bool UrlShortenerDB::connect() {
// Use a temporary session object to establish connections for the pool
std::unique_ptr<mysqlx::Session> tempSession;
try {
// --- INITIALIZE POOL ---
for (int i = 0; i < poolSize; ++i) {
tempSession = std::make_unique<mysqlx::Session>(
Config::DB_HOST,
Config::DB_PORT,
Config::DB_USER,
Config::DB_PASS
);
// Add the new, fully connected session to the pool
connectionPool.push(std::move(tempSession));
}
// --- CREATE DATABASE (Use a single pool session for DDL) ---
// We use one connection from the pool for initial DDL (Data Definition Language)
tempSession = getConnection();
tempSession->sql("CREATE DATABASE IF NOT EXISTS " + Config::DB_NAME).execute();
tempSession->sql("USE " + Config::DB_NAME).execute();
// Return the session to the pool
returnConnection(std::move(tempSession));
cerr << "DB_INFO: Database connection pool established with " << poolSize << " sessions to " << Config::DB_NAME << endl;
isConnected = true;
return true;
} catch (const mysqlx::Error &e) {
cerr << "DB_ERROR: MySQL X DevAPI connection failed: " << e.what() << endl;
// Clean up any partially established connections (automatically handled by destructors)
isConnected = false;
return false;
} catch (const std::exception& e) {
cerr << "DB_ERROR: Failed to establish pool: " << e.what() << endl;
isConnected = false;
return false;
}
}
// Uses pool session and correct EXECUTE HELPER
bool UrlShortenerDB::incrementEndpointStat(const std::string& endpoint,
const std::string& method,
const std::string& createdBy) {
if (!isConnected) return false;
std::unique_ptr<mysqlx::Session> currentSession;
try {
currentSession = getConnection();
string sql = "INSERT INTO endpoint_stats (endpoint, endpoint_type, count, created_by, type) "
"VALUES (?, ?, 1, ?, 'USER') "
"ON DUPLICATE KEY UPDATE "
"count = count + 1, "
"created_by = VALUES(created_by), "
"updated_at = CURRENT_TIMESTAMP "
";";
std::vector<Value> params = {
Value(endpoint),
Value(method),
Value(createdBy)
};
UrlShortenerDB::executeStatement(*currentSession, sql, params);
returnConnection(std::move(currentSession));
return true;
} catch (const std::exception& e) {
std::cerr << "DB_ERROR: Failed to update endpoint stats: " << e.what() << std::endl;
returnConnection(std::move(currentSession));
return false;
}
}
// Uses pool session for DDL execution
bool UrlShortenerDB::setupDatabase() {
if (!isConnected) {
cerr << "DB_ERROR: Cannot set up database: No active pool." << endl;
return false;
}
std::unique_ptr<mysqlx::Session> currentSession;
try {
currentSession = getConnection();
cerr << "DB_INFO: Executing table creation and initial settings SQL." << endl;
// Read the schema file
std::ifstream file("../schema.sql");
if (!file.is_open()) {
cerr << "DB_ERROR: Could not open schema.sql" << endl;
returnConnection(std::move(currentSession));
return false;
}
std::stringstream buffer;
buffer << file.rdbuf();
string sqlContent = buffer.str();
// Split by ';' and execute
std::vector<string> statements;
string current;
for (char c : sqlContent) {
current += c;
if (c == ';') {
if (!current.empty()) {
statements.push_back(current);
current.clear();
}
}
}
// Execute each statement
for (auto& stmt : statements) {
try {
// ... (Trimming and cleaning logic remains the same) ...
string trimmed = stmt;
trimmed.erase(0, trimmed.find_first_not_of(" \n\r\t"));
trimmed.erase(trimmed.find_last_not_of(" \n\r\t") + 1);
if (trimmed.empty() || trimmed.rfind("--", 0) == 0) continue;
size_t comment_pos = trimmed.find("--");
if (comment_pos != string::npos) {
trimmed = trimmed.substr(0, comment_pos);
trimmed.erase(trimmed.find_last_not_of(" \n\r\t") + 1);
}
std::replace(trimmed.begin(), trimmed.end(), '\n', ' ');
std::replace(trimmed.begin(), trimmed.end(), '\r', ' ');
if (trimmed.empty()) continue;
// Execute the SQL directly on the pool session
currentSession->sql(trimmed).execute();
} catch (const mysqlx::Error &e) {
cerr << "DB_WARN: Failed to execute SQL statement: " << e.what() << endl;
cerr << "Statement: " << stmt << endl;
}
}
returnConnection(std::move(currentSession));
cerr << "DB_INFO: Schema setup completed successfully." << endl;
return true;
} catch (const std::exception &e) {
cerr << "DB_ERROR: Exception while setting up DB: " << e.what() << endl;
returnConnection(std::move(currentSession));
return false;
}
}
// --- User & Session Methods ---
bool UrlShortenerDB::createUser(const User& user) {
if (!isConnected) return false;
std::unique_ptr<mysqlx::Session> currentSession;
try {
currentSession = getConnection();
string sql = "INSERT INTO users (google_id, email, name, created_at, updated_at) VALUES (?, ?, ?, NOW(), NOW())";
std::vector<Value> params = {
Value(user.google_id),
Value(user.email),
Value(user.name)
};
currentSession->sql(sql).bind(params).execute();
returnConnection(std::move(currentSession));
return true;
} catch (const mysqlx::Error& e) {
cerr << "DB_ERROR: Failed to create user: " << e.what() << endl;
returnConnection(std::move(currentSession));
return false;
}
}
unique_ptr<User> UrlShortenerDB::findUserByGoogleId(const string& google_id) {
if (!isConnected) return nullptr;
std::unique_ptr<mysqlx::Session> currentSession;
unique_ptr<User> user = nullptr;
try {
currentSession = getConnection();
string sql = "SELECT id, google_id, email, name, created_at FROM users WHERE google_id = ?";
auto result = executeStatement(*currentSession, sql, {Value(google_id)});
if (auto row = result->fetchOne()) {
user = std::make_unique<User>();
user->id = row[0].get<unsigned int>();
user->google_id = row[1].get<string>();
user->email = row[2].get<string>();
user->name = row[3].get<string>();
user->created_at = row[4].get<string>();
}
} catch (const std::exception& e) {
cerr << "DB_ERROR: Failed to find user by Google ID: " << e.what() << endl;
}
returnConnection(std::move(currentSession));
return user;
}
// Find user by email (essential for standard OAuth lookup)
unique_ptr<User> UrlShortenerDB::findUserByEmail(const string& email) {
if (!isConnected) return nullptr;
std::unique_ptr<mysqlx::Session> currentSession;
unique_ptr<User> user = nullptr;
try {
currentSession = getConnection();
string sql = "SELECT id, google_id, email, name, created_at FROM users WHERE email = ?";
auto result = executeStatement(*currentSession, sql, {Value(email)});
if (auto row = result->fetchOne()) {
user = std::make_unique<User>();
user->id = row[0].get<unsigned int>();
user->google_id = row[1].get<string>();
user->email = row[2].get<string>();
user->name = row[3].get<string>();
user->created_at = row[4].get<string>();
}
} catch (const std::exception& e) {
cerr << "DB_ERROR: Failed to find user by Email: " << e.what() << endl;
}
returnConnection(std::move(currentSession));
return user;
}
// Explicitly refers to the DTO struct and avoids ambiguity
bool UrlShortenerDB::createSession(const ::Session& sessionObj) {
if (!isConnected) return false;
std::unique_ptr<mysqlx::Session> currentSession;
try {
currentSession = getConnection();
string sql = "INSERT INTO sessions (user_id, session_token, expires_at, created_at, updated_at) VALUES (?, ?, ?, NOW(), NOW())";
std::vector<Value> params = {
Value(sessionObj.user_id),
Value(sessionObj.session_token),
Value(sessionObj.expires_at) // formatted string (YYYY-MM-DD HH:MM:SS)
};
currentSession->sql(sql).bind(params).execute();
returnConnection(std::move(currentSession));
return true;
} catch (const mysqlx::Error& e) {
cerr << "DB_ERROR: Failed to create session: " << e.what() << endl;
returnConnection(std::move(currentSession));
return false;
}
}
bool UrlShortenerDB::deleteSession(const string& token) {
if (!isConnected) return false;
std::unique_ptr<mysqlx::Session> currentSession;
try {
currentSession = getConnection();
string sql = "DELETE FROM sessions WHERE session_token = ?";
currentSession->sql(sql).bind(Value(token)).execute();
cerr << "DB_INFO: Session deleted successfully." << endl;
returnConnection(std::move(currentSession));
return true;
} catch (const mysqlx::Error& e) {
cerr << "DB_ERROR: Failed to delete session: " << e.what() << endl;
returnConnection(std::move(currentSession));
return false;
}
}
unique_ptr<::Session> UrlShortenerDB::findSessionByToken(const string& token) {
if (!isConnected) return nullptr;
std::unique_ptr<mysqlx::Session> currentSession;
unique_ptr<::Session> sessionObj = nullptr;
try {
currentSession = getConnection();
string sql = "SELECT id, user_id, session_token, expires_at FROM sessions WHERE session_token = ? AND expires_at > NOW()";
auto result = executeStatement(*currentSession, sql, {Value(token)});
if (auto row = result->fetchOne()) {
sessionObj = std::make_unique<::Session>();
sessionObj->id = row[0].get<unsigned int>();
sessionObj->user_id = row[1].get<unsigned int>();
sessionObj->session_token = row[2].get<string>();
sessionObj->expires_at = row[3].get<string>();
}
} catch (const std::exception& e) {
cerr << "DB_ERROR: Failed to find session: " << e.what() << endl;
}
returnConnection(std::move(currentSession));
return sessionObj;
}
bool UrlShortenerDB::setLinkFavorite(const int&userId, const string&code, const bool&isFav){
if (!isConnected) return false;
std::unique_ptr<mysqlx::Session> currentSession;
try{
currentSession = getConnection();
string sql="UPDATE shortened_links SET is_favourite = ? WHERE user_id = ? AND short_code = ?;";
std::vector<Value> params = {
Value(isFav),
Value(userId),
Value(code)
};
UrlShortenerDB::executeStatement(*currentSession, sql, params);
returnConnection(std::move(currentSession));
return true;
}
catch (const mysqlx::Error &e) {
cerr<<"ERROR IN CHANGING FAVOURITE VALUE"<<" "<<e.what()<<endl;
returnConnection(std::move(currentSession));
return false;
}
}
bool UrlShortenerDB::deleteLink(const int&id, const string&code){
if (!isConnected) return false;
std::unique_ptr<mysqlx::Session> currentSession;
try{
currentSession = getConnection();
string sql="DELETE FROM shortened_links"
" WHERE user_id = ?"
" AND short_code = ?;";
std::vector<Value> params = {
Value(id),
Value(code),
};
UrlShortenerDB::executeStatement(*currentSession, sql, params);
returnConnection(std::move(currentSession));
return true;
}
catch (const mysqlx::Error &e) {
cerr<<"ERROR IN DELETING LINK";
returnConnection(std::move(currentSession));
return false;
}
}
bool UrlShortenerDB::createLink(const ShortenedLink& link) {
if (!isConnected) return false;
std::unique_ptr<mysqlx::Session> currentSession;
try {
currentSession = getConnection();
string sql = "INSERT INTO shortened_links "
"(original_url, short_code, user_id, guest_identifier, expires_at, created_at, updated_at) "
"VALUES (?, ?, ?, ?, ?, NOW(), NOW())";
// Handle optional user_id (Authenticated Link Creation)
Value user_id_val = link.user_id ? Value(*link.user_id) : Value(nullptr);
// Calculate expiration date
auto now = std::chrono::system_clock::now();
now += std::chrono::hours(24 * Config::LINK_EXPIRED_IN);
std::time_t t = std::chrono::system_clock::to_time_t(now);
char buffer[20];
std::strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", std::localtime(&t));
std::string expires_at = !link.expires_at.empty() ? link.expires_at : std::string(buffer);
// Handle optional expires_at (Link Expiration)
Value expires_at_val = Value(expires_at);
std::vector<Value> params = {
Value(link.original_url),
Value(link.short_code),
user_id_val,
Value(link.guest_identifier),
expires_at_val
};
currentSession->sql(sql).bind(params).execute();
returnConnection(std::move(currentSession));
return true;
} catch (const mysqlx::Error &e) {
std::string err_msg = e.what();
std::cerr << "DB_ERROR: " << err_msg << std::endl;
// Detect duplicate key by checking text in the error message
if (err_msg.find("Duplicate entry") != std::string::npos) {
std::cerr << "DB_ERROR: Short code already exists." << std::endl;
}
returnConnection(std::move(currentSession));
return false;
}
}
// Implements Link Analytics (Click Tracking)
bool UrlShortenerDB::incrementLinkClicks(unsigned int link_id) {
if (!isConnected) return false;
std::unique_ptr<mysqlx::Session> currentSession;
try {
currentSession = getConnection();
string sql = "UPDATE shortened_links SET clicks = clicks + 1, updated_at = NOW() WHERE id = ?";
currentSession->sql(sql).bind(Value(link_id)).execute();
returnConnection(std::move(currentSession));
return true;
} catch (const mysqlx::Error& e) {
cerr << "DB_ERROR: Failed to increment clicks: " << e.what() << endl;
returnConnection(std::move(currentSession));
return false;
}
}
unique_ptr<std::vector<ShortenedLink>> UrlShortenerDB::getLinksByUserId(unsigned int user_id) {
if (!isConnected) return nullptr;
std::unique_ptr<mysqlx::Session> currentSession;
unique_ptr<std::vector<ShortenedLink>> links = nullptr;
try {
currentSession = getConnection();
string sql = "SELECT id, original_url, short_code, expires_at, clicks, created_at FROM shortened_links WHERE user_id = ? ORDER BY created_at DESC";
auto result = executeStatement(*currentSession, sql, {Value(user_id)});
links = std::make_unique<std::vector<ShortenedLink>>();
for (auto row : *result) {
ShortenedLink link;
link.id = row[0].get<unsigned int>();
link.original_url = row[1].get<string>();
link.short_code = row[2].get<string>();
link.expires_at = row[3].get<string>();
link.clicks = row[4].get<unsigned int>();
link.created_at = row[5].get<string>();
links->push_back(std::move(link));
}
} catch (const std::exception& e) {
cerr << "DB_ERROR: Failed to fetch user links: " << e.what() << endl;
}
returnConnection(std::move(currentSession));
return links;
}
unique_ptr<ShortenedLink> UrlShortenerDB::getLinkByShortCode(const string& code) {
if (!isConnected) return nullptr;
std::unique_ptr<mysqlx::Session> currentSession;
unique_ptr<ShortenedLink> link = nullptr;
try {
currentSession = getConnection();
// Check for the code AND ensure it hasn't expired (Link Expiration)
string sql = "SELECT id, original_url, short_code, user_id, expires_at, clicks FROM shortened_links "
"WHERE short_code = ? AND (expires_at IS NULL OR expires_at > NOW())";
auto result = executeStatement(*currentSession, sql, {Value(code)});
if (auto row = result->fetchOne()) {
link = std::make_unique<ShortenedLink>();
link->id = row[0].get<unsigned int>();
link->original_url = row[1].get<string>();
link->short_code = row[2].get<string>();
// Handle nullable user_id (Authenticated Link Creation)
if (!row[3].isNull()) {
link->user_id = std::make_unique<unsigned int>(row[3].get<unsigned int>());
}
link->expires_at = row[4].get<string>();
link->clicks = row[5].get<unsigned int>(); // Link Analytics
}
} catch (const std::exception& e) {
cerr << "DB_ERROR: Failed to get link: " << e.what() << endl;
}
returnConnection(std::move(currentSession));
return link;
}
// --- Quota Management ---
bool UrlShortenerDB::isQuotaLimitEnabled() {
if (!isConnected) return true; // Default to true if DB fails (fail-safe)
std::unique_ptr<mysqlx::Session> currentSession;
bool enabled = true;
try {
currentSession = getConnection();
string sql = "SELECT setting_value FROM global_settings WHERE setting_key = 'MAX_LINK_LIMIT_ENABLED'";
auto result = executeStatement(*currentSession, sql, {});
if (auto row = result->fetchOne()) {
string value = row[0].get<string>();
enabled = (value == "true");
}
} catch (const std::exception& e) {
cerr << "DB_ERROR: Failed to read global setting: " << e.what() << endl;
}
returnConnection(std::move(currentSession));
return enabled;
}
std::string UrlShortenerDB::getConfig(std::string key){
if (!isConnected) throw runtime_error("Database not connected");
std::unique_ptr<mysqlx::Session> currentSession;
std::string value = "";
try
{
currentSession = getConnection();
string sql = "use database ";
sql+=Config::DB_NAME;
auto result = executeStatement(*currentSession, sql, {});
sql = "SELECT setting_value FROM global_settings WHERE setting_key = ?";
result = executeStatement(*currentSession, sql, {Value(key)});
if (auto row = result->fetchOne()) {
value = row[0].get<string>();
}
}
catch(const std::exception& e)
{
cerr<<"DB_ERROR: FAILED TO GET THE CONFIG FOR KEY: "<<key<<" with error"<<e.what()<<endl;
value = "invalid request"; // Use a specific error value
}
returnConnection(std::move(currentSession));
return value;
}
bool UrlShortenerDB::checkAndUpdateGuestQuota(const string& guest_identifier, const string& today_date) {
if (!isConnected) return false;
std::unique_ptr<mysqlx::Session> currentSession;
bool success = false;
try {
currentSession = getConnection();
// SELECT current quota
string select_sql = "SELECT links_created FROM guest_daily_quotas WHERE guest_identifier = ? AND quota_date = ?";
auto result = executeStatement(*currentSession, select_sql, {Value(guest_identifier), Value(today_date)});
unsigned int links_created_today = 0;
if (auto row = result->fetchOne()) {
links_created_today = row[0].get<unsigned int>();
}
int MAX_GUEST_LINKS_PER_DAY = 5;
std::string config_val = getConfig(*currentSession, "MAX_GUEST_LINKS_PER_DAY");
if (config_val != "invalid request" && !config_val.empty()) {
try {
MAX_GUEST_LINKS_PER_DAY = std::stoi(config_val);
} catch (const std::exception&) {
cerr << "DB_CONFIG_ERROR: Failed to convert MAX_GUEST_LINKS_PER_DAY to int." << endl;
}
} else {
cerr<<"DB_CONFIG_ERROR: Unable to find config for key MAX_GUEST_LINKS_PER_DAY, using default 5."<<endl;
}
if (links_created_today >= MAX_GUEST_LINKS_PER_DAY ) {
cerr << "DB_CHECK: Quota limit reached (" << links_created_today << "/" << MAX_GUEST_LINKS_PER_DAY << ") for " << guest_identifier << endl;
success = false; // Quota exceeded
} else {
// INSERT or UPDATE quota (ON DUPLICATE KEY UPDATE)
string upsert_sql = "INSERT INTO guest_daily_quotas (guest_identifier, quota_date, links_created, created_at, updated_at) "
"VALUES (?, ?, 1, NOW(), NOW()) "
"ON DUPLICATE KEY UPDATE links_created = links_created + 1, updated_at = NOW()";
currentSession->sql(upsert_sql).bind(Value(guest_identifier)).bind(Value(today_date)).execute();
success = true; // Quota check passed and updated
}
} catch (const mysqlx::Error& e) {
cerr << "DB_ERROR: Quota check failed: " << e.what() << endl;
success = false;
}
returnConnection(std::move(currentSession));
return success;
}