Updated database content, new "add" command for earnings.

This commit is contained in:
2026-01-05 19:16:04 -03:00
parent ac6f366083
commit 86e1af1a66
3 changed files with 80 additions and 5 deletions

View File

@@ -19,27 +19,44 @@ require 'pg'
class Database
def initialize
# Connect once when the bot starts
@conn = PG.connect(dbname: 'frugality_database')
@conn = PG.connect(dbname: 'fgbot_db')
init_tables
end
def init_tables
sql = <<~SQL
CREATE TABLE IF NOT EXISTS total_money (
sql_wallet = <<~SQL
CREATE TABLE IF NOT EXISTS wallets (
user_id BIGINT PRIMARY KEY,
amount BIGINT DEFAULT 0
);
SQL
@conn.exec(sql)
sql_ledger = <<~SQL
CREATE TABLE IF NOT EXISTS transactions (
id SERIAL PRIMARY KEY,
user_id BIGINT NOT NULL,
amount BIGINT NOT NULL,
reason VARCHAR(50),
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
SQL
sql_index = <<~SQL
CREATE INDEX IF NOT EXISTS idx_user_history
ON transactions(user_id, created_at);
SQL
@conn.exec(sql_wallet)
@conn.exec(sql_ledger)
@conn.exec(sql_index)
puts "Database tables have been initialized."
end
# We pass the user_id
def get_currency(user_id)
# 1. Run the query using parameters ($1) to prevent SQL injection
result = @conn.exec_params("SELECT amount FROM total_money WHERE user_id = $1", [user_id])
result = @conn.exec_params("SELECT amount FROM wallets WHERE user_id = $1", [user_id])
# 2. Check if the user exists
if result.num_tuples.zero?
@@ -49,4 +66,23 @@ class Database
return result[0]['amount'].to_i
end
end
def update_balance(user_id, amount, reason = "transaction")
@conn.transaction do
@conn.exec_params(
"INSERT INTO transactions (user_id, amount, reason) VALUES ($1, $2, $3)",
[user_id, amount, reason]
)
# We update the user's wallet
sql_update = <<~SQL
INSERT INTO wallets (user_id, amount)
VALUES ($1, $2)
ON CONFLICT (user_id)
DO UPDATE SET amount = wallets.amount + $2
SQL
@conn.exec_params(sql_update, [user_id, amount])
end
end
end