Class: SchwabRb::Storage::Database
- Inherits:
-
Object
- Object
- SchwabRb::Storage::Database
- Defined in:
- lib/schwab_rb/storage/database.rb
Instance Attribute Summary collapse
-
#path ⇒ Object
readonly
Returns the value of attribute path.
Instance Method Summary collapse
- #close ⇒ Object
-
#initialize(path = nil) ⇒ Database
constructor
A new instance of Database.
- #load_account_hash(account_number) ⇒ Object
- #load_token(api_key) ⇒ Object
- #save_account(account_number, account_hash) ⇒ Object
- #save_token(api_key, token_hash) ⇒ Object
Constructor Details
#initialize(path = nil) ⇒ Database
Returns a new instance of Database.
10 11 12 13 14 |
# File 'lib/schwab_rb/storage/database.rb', line 10 def initialize(path = nil) @path = path || SchwabRb.configuration.database_path @mutex = Mutex.new @db = nil end |
Instance Attribute Details
#path ⇒ Object (readonly)
Returns the value of attribute path.
8 9 10 |
# File 'lib/schwab_rb/storage/database.rb', line 8 def path @path end |
Instance Method Details
#close ⇒ Object
66 67 68 69 70 71 |
# File 'lib/schwab_rb/storage/database.rb', line 66 def close synchronize do @db&.close @db = nil end end |
#load_account_hash(account_number) ⇒ Object
59 60 61 62 63 64 |
# File 'lib/schwab_rb/storage/database.rb', line 59 def load_account_hash(account_number) row = synchronize do db.get_first_row("SELECT account_hash FROM accounts WHERE account_number = ?", [account_number]) end row&.fetch("account_hash", nil) end |
#load_token(api_key) ⇒ Object
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
# File 'lib/schwab_rb/storage/database.rb', line 27 def load_token(api_key) row = synchronize do db.get_first_row("SELECT * FROM tokens WHERE api_key = ?", [api_key]) end return nil unless row { "timestamp" => row["timestamp"], "token" => { "access_token" => row["access_token"], "refresh_token" => row["refresh_token"], "expires_at" => row["expires_at"], "expires_in" => row["expires_in"], "token_type" => row["token_type"], "scope" => row["scope"], "id_token" => row["id_token"] } } end |
#save_account(account_number, account_hash) ⇒ Object
47 48 49 50 51 52 53 54 55 56 57 |
# File 'lib/schwab_rb/storage/database.rb', line 47 def save_account(account_number, account_hash) synchronize do db.execute(<<~SQL, [account_number, account_hash]) INSERT INTO accounts (account_number, account_hash) VALUES (?, ?) ON CONFLICT(account_number) DO UPDATE SET account_hash = excluded.account_hash, updated_at = CURRENT_TIMESTAMP SQL end end |
#save_token(api_key, token_hash) ⇒ Object
16 17 18 19 20 21 22 23 24 25 |
# File 'lib/schwab_rb/storage/database.rb', line 16 def save_token(api_key, token_hash) synchronize do db.execute("DELETE FROM tokens WHERE api_key = ?", [api_key]) db.execute(<<~SQL, bind_token_params(api_key, token_hash)) INSERT INTO tokens (api_key, access_token, refresh_token, expires_at, expires_in, token_type, scope, id_token, timestamp) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) SQL end end |