Class: Taupe::Database::PostgresqlDriver

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

Overview

Postgresql database driver

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(dsn) ⇒ PostgresqlDriver

Constructor

Parameters:

  • dsn (Hash)

    The data source name



15
16
17
# File 'lib/taupe/database/postgresql.rb', line 15

def initialize(dsn)
  @connection = PG::Connection.new dsn
end

Instance Attribute Details

#connectionObject

Accessors



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

def connection
  @connection
end

#last_idInteger

Get last inserted id

Returns:

  • (Integer)


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

def last_id
  @last_id
end

Instance Method Details

#escape(str) ⇒ String

Escape a string

Parameters:

  • str (String)

Returns:

  • (String)


84
85
86
# File 'lib/taupe/database/postgresql.rb', line 84

def escape(str)
  @connection.escape_string str
end

#exec(query) ⇒ Object

Execute a single query

Parameters:

  • query (String)

    The query to execute

Returns:

  • (Object)


22
23
24
25
26
27
28
29
# File 'lib/taupe/database/postgresql.rb', line 22

def exec(query)
  result = @connection.exec query

  @last_id = nil
  @last_id = result[0].flatten[0] if query.upcase.include?('RETURNING')

  result
end

#fetch(query) ⇒ Array, Object

Fetch objects from database

Parameters:

  • query (String)

    The query to fetch

Returns:

  • (Array, Object)


34
35
36
# File 'lib/taupe/database/postgresql.rb', line 34

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

#guess_schema(table) ⇒ Hash

Guess schema of a table

Parameters:

  • table (String)

    The table name

Returns:



54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
# File 'lib/taupe/database/postgresql.rb', line 54

def guess_schema(table)
  results = {}

  query = 'SELECT'
  query << ' column_name, data_type, character_maximum_length,'
  query << ' column_default, is_nullable'
  query << ' FROM INFORMATION_SCHEMA.COLUMNS'
  query << format(' WHERE table_name = \'%s\'', table)
  query << ' ORDER BY ordinal_position'

  fetch(query).each do |values|
    type = Taupe::Validate.standardize_sql_type values[:data_type]
    pkey = false
    unless values[:column_default].nil?
      pkey = true unless values[:column_default].match('nextval').nil?
    end

    results[values[:column_name].to_sym] = {
      type: type,
      null: values[:is_nullable] != 'NO',
      primary_key: pkey
    }
  end

  results
end