Class: MicroSql::PgAdapter
Defined Under Namespace
Modules: Conversion
Constant Summary
collapse
- TRANSACTION_STATUSES =
%w(PQTRANS_IDLE PQTRANS_ACTIVE PQTRANS_INTRANS PQTRANS_INERROR PQTRANS_UNKNOWN)
Instance Method Summary
collapse
Methods inherited from MicroSql
#ask, #exec, #exec!, #insert, #key_value_table, #rollback!, #table
Constructor Details
#initialize(url) ⇒ PgAdapter
Returns a new instance of PgAdapter.
2
3
4
5
6
7
8
9
10
11
12
13
14
|
# File 'lib/micro_sql/pg_adapter.rb', line 2
def initialize(url)
require 'pg'
uri = URI.parse(url)
@impl = PG.connect :host => uri.host,
:port => uri.port || 5433,
:user => uri.user,
:password => uri.password,
:dbname => uri.path[1..-1]
@impl.set_notice_receiver { |result| MicroSql.logger.info(result.error_message) }
end
|
Instance Method Details
#connection ⇒ Object
18
19
20
|
# File 'lib/micro_sql/pg_adapter.rb', line 18
def connection
@impl
end
|
#execute_batch(sql) ⇒ Object
94
95
96
97
98
|
# File 'lib/micro_sql/pg_adapter.rb', line 94
def execute_batch(sql)
sql.split(";").each { |part|
exec!(part)
}
end
|
#primary_key(table) ⇒ Object
80
81
82
83
84
|
# File 'lib/micro_sql/pg_adapter.rb', line 80
def primary_key(table)
keys = primary_keys(table)
raise(Error, "No support for primary key (in table #{table})") if keys.length > 1
keys.first || raise(Error, "No primary key in table #{table}")
end
|
#primary_keys(table) ⇒ Object
65
66
67
68
69
70
71
72
73
74
75
76
77
78
|
# File 'lib/micro_sql/pg_adapter.rb', line 65
def primary_keys(table)
sql = <<-SQL
SELECT pg_attribute.attname
FROM pg_index, pg_class, pg_attribute
WHERE
pg_class.oid = ?::regclass AND
indrelid = pg_class.oid AND
pg_attribute.attrelid = pg_class.oid AND
pg_attribute.attnum = any(pg_index.indkey) AND
indisprimary
SQL
exec(sql, table).map(&:first)
end
|
#tables ⇒ Object
61
62
63
|
# File 'lib/micro_sql/pg_adapter.rb', line 61
def tables
exec("SELECT tablename FROM pg_tables WHERE tablename NOT LIKE 'pg_%' AND tablename NOT LIKE 'sql_%'").map(&:first)
end
|
#transaction(&block) ⇒ Object
31
32
33
34
35
36
37
38
39
40
41
42
43
|
# File 'lib/micro_sql/pg_adapter.rb', line 31
def transaction(&block)
return savepoint_transaction(&block) if transaction?
begin
r = nil
@impl.transaction do
r = yield
end
r
rescue RollbackException
nil
end
end
|
#transaction? ⇒ Boolean
26
27
28
29
|
# File 'lib/micro_sql/pg_adapter.rb', line 26
def transaction?
status = @impl.transaction_status
status == PG::Connection::PQTRANS_INTRANS || status == PG::Connection::PQTRANS_INERROR
end
|
#transaction_status ⇒ Object
22
23
24
|
# File 'lib/micro_sql/pg_adapter.rb', line 22
def transaction_status
TRANSACTION_STATUSES[@impl.transaction_status]
end
|