Class: Taupe::Database::PostgresqlDriver
- Inherits:
-
Object
- Object
- Taupe::Database::PostgresqlDriver
- Defined in:
- lib/taupe/database/postgresql.rb
Overview
Postgresql database driver
Instance Attribute Summary collapse
-
#connection ⇒ Object
Accessors.
-
#last_id ⇒ Integer
Get last inserted id.
Instance Method Summary collapse
-
#escape(str) ⇒ String
Escape a string.
-
#exec(query) ⇒ Object
Execute a single query.
-
#fetch(query) ⇒ Array, Object
Fetch objects from database.
-
#guess_schema(table) ⇒ Hash
Guess schema of a table.
-
#initialize(dsn) ⇒ PostgresqlDriver
constructor
Constructor.
Constructor Details
#initialize(dsn) ⇒ PostgresqlDriver
Constructor
15 16 17 |
# File 'lib/taupe/database/postgresql.rb', line 15 def initialize(dsn) @connection = PG::Connection.new dsn end |
Instance Attribute Details
#connection ⇒ Object
Accessors
11 12 13 |
# File 'lib/taupe/database/postgresql.rb', line 11 def connection @connection end |
#last_id ⇒ Integer
Get last inserted id
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
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
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
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
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 |