Class: AutoREST::SQLiteDB

Inherits:
DBAdapter show all
Defined in:
lib/autorest/db/sqlite.rb

Overview

SQLite adapter for AutoREST.

Uses the sqlite3 gem to connect and query the SQLite database. Automatically discovers tables and primary keys.

Examples:

Initialize adapter

db = AutoREST::SQLiteDB.new("data.db")

Instance Method Summary collapse

Methods inherited from DBAdapter

#close, #columns, #del_row, #insert, #row, #rows, #set_access_tables, #tables, #update

Constructor Details

#initialize(dbname) ⇒ SQLiteDB

Returns a new instance of SQLiteDB.

Parameters:

  • dbname (String)

    Path to the SQLite database file



21
22
23
24
25
# File 'lib/autorest/db/sqlite.rb', line 21

def initialize(dbname)
    conn = SQLite3::Database.new(dbname)
    conn.results_as_hash = true
    super(:sqlite, dbname, conn)
end

Instance Method Details

#escape(input) ⇒ String

Escapes identifiers or values for safe usage in queries.

Parameters:

  • input (String)

    Table or column name

Returns:

  • (String)

    Escaped string



51
52
53
# File 'lib/autorest/db/sqlite.rb', line 51

def escape(input)
    SQLite3::Database.quote(input)
end

#exec_sql(sql) ⇒ Array<Hash>

Executes a raw SQL query.

Parameters:

  • sql (String)

    The SQL query to run

Returns:

  • (Array<Hash>)

    Resulting rows



44
45
46
# File 'lib/autorest/db/sqlite.rb', line 44

def exec_sql(sql)
    @db_conn.execute(sql)
end

#preparevoid

This method returns an undefined value.

Loads table metadata including columns and primary keys.



29
30
31
32
33
34
35
36
37
38
39
# File 'lib/autorest/db/sqlite.rb', line 29

def prepare
    @tables = {}
    @db_conn.execute("SELECT name FROM sqlite_master WHERE type='table'").each do |t|
        tname = t['name']
        row_details = @db_conn.execute("select name, type, pk from pragma_table_info('#{tname}')")
        @tables[tname] = {}
        row_details.each do |row|
            @tables[tname][row['name']] = {type: row['type'], pk: row['pk'] == 1}
        end
    end
end