Class: Taupe::Database::SqliteDriver

Inherits:
Object
  • Object
show all
Defined in:
lib/taupe/database/sqlite.rb

Overview

Sqlite database driver

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(dsn) ⇒ SqliteDriver

Constructor

Parameters:

  • dsn (Hash)

    The data source name



15
16
17
18
19
20
# File 'lib/taupe/database/sqlite.rb', line 15

def initialize(dsn)
  db = File.expand_path(dsn)
  fail "Database #{db} not found" unless File.exist? db
  @connection = SQLite3::Database.new db
  @connection.results_as_hash = true
end

Instance Attribute Details

#connectionObject

Accessors



11
12
13
# File 'lib/taupe/database/sqlite.rb', line 11

def connection
  @connection
end

Instance Method Details

#escape(str) ⇒ String

Escape a string

Parameters:

  • str (String)

Returns:

  • (String)


66
67
68
69
70
# File 'lib/taupe/database/sqlite.rb', line 66

def escape(str)
  # Sqlite3 does not implement this kind of thing
  # Use prepare statements instead
  str
end

#exec(query) ⇒ Object

Execute a single query

Parameters:

  • query (String)

    The query to execute

Returns:

  • (Object)


25
26
27
# File 'lib/taupe/database/sqlite.rb', line 25

def exec(query)
  @connection.execute query
end

#fetch(query) ⇒ Array, Object

Fetch objects from database

Parameters:

  • query (String)

    The query to fetch

Returns:

  • (Array, Object)


32
33
34
# File 'lib/taupe/database/sqlite.rb', line 32

def fetch(query)
  exec(query).map(&:symbolize_keys)
end

#guess_schema(table) ⇒ Hash

Guess schema of a table

Parameters:

  • table (String)

    The table name

Returns:



45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/taupe/database/sqlite.rb', line 45

def guess_schema(table)
  results = {}

  query = format('pragma table_info(%s)', table)

  fetch(query).each do |values|
    type = Taupe::Validate.standardize_sql_type values[:type]

    results[values[:name].to_sym] = {
      type: type,
      null: values[:notnull] == 0,
      primary_key: values[:pk] == 1
    }
  end

  results
end

#last_idInteger

Get last inserted id

Returns:

  • (Integer)


38
39
40
# File 'lib/taupe/database/sqlite.rb', line 38

def last_id
  @connection.last_insert_row_id.to_i
end