Class: TimeBuffer::DatabaseConnector

Inherits:
Object
  • Object
show all
Defined in:
lib/time_buffer/database_connector.rb

Constant Summary collapse

FILE_LOCATION =
"usage_data.db"

Instance Method Summary collapse

Constructor Details

#initializeDatabaseConnector

Returns a new instance of DatabaseConnector.



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
# File 'lib/time_buffer/database_connector.rb', line 7

def initialize
  return if File.exist?(FILE_LOCATION)

  # 1. Applications Table
  connection.execute <<-SQL
    CREATE TABLE IF NOT EXISTS applications (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      bundle_id TEXT UNIQUE NOT NULL,
      app_name TEXT NOT NULL
    );
  SQL

  # 2. Time Sessions Table
  connection.execute <<-SQL
    CREATE TABLE IF NOT EXISTS time_sessions (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      application_id INTEGER NOT NULL,
      start_time DATETIME NOT NULL,
      end_time DATETIME,
      metadata JSONB,
      FOREIGN KEY (application_id) REFERENCES applications(id)
    );
  SQL

  # 3. Daily Summaries Table
  connection.execute <<-SQL
    CREATE TABLE IF NOT EXISTS daily_summaries (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      application_id INTEGER NOT NULL,
      date DATE NOT NULL,
      total_duration INTEGER NOT NULL,
      FOREIGN KEY (application_id) REFERENCES applications(id),
      UNIQUE(application_id, date)
    );
  SQL

  puts "Database initialized successfully."
end

Instance Method Details

#connectObject



46
47
48
# File 'lib/time_buffer/database_connector.rb', line 46

def connect
  @db = SQLite3::Database.new(FILE_LOCATION)
end

#connectionObject



50
51
52
# File 'lib/time_buffer/database_connector.rb', line 50

def connection
  @db || connect
end

#execute(sql, *params) ⇒ Object



54
55
56
57
# File 'lib/time_buffer/database_connector.rb', line 54

def execute(sql, *params)
  # puts "Writing to db: #{params}"
  connection.execute(sql, *params)
end