Main commit
This commit is contained in:
36
src/database.rb
Normal file
36
src/database.rb
Normal file
@@ -0,0 +1,36 @@
|
||||
require 'pg'
|
||||
|
||||
class Database
|
||||
def initialize
|
||||
# Connect once when the bot starts
|
||||
@conn = PG.connect(dbname: 'frugality_database')
|
||||
|
||||
init_tables
|
||||
end
|
||||
|
||||
def init_tables
|
||||
sql = <<~SQL
|
||||
CREATE TABLE IF NOT EXISTS total_money (
|
||||
user_id BIGINT PRIMARY KEY,
|
||||
amount BIGINT DEFAULT 0
|
||||
);
|
||||
SQL
|
||||
|
||||
@conn.exec(sql)
|
||||
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])
|
||||
|
||||
# 2. Check if the user exists
|
||||
if result.num_tuples.zero?
|
||||
return 0 # User has no money/row yet
|
||||
else
|
||||
# 3. Return the value (don't print it)
|
||||
return result[0]['amount'].to_i
|
||||
end
|
||||
end
|
||||
end
|
||||
Reference in New Issue
Block a user