active?()
click to toggle source
Is this connection alive and ready for queries?
def active?
if @connection.respond_to?(:status)
@connection.status == PGconn::CONNECTION_OK
else
@connection.query 'SELECT 1'
true
end
rescue PGError, NoMethodError
false
end
adapter_name()
click to toggle source
Returns ‘PostgreSQL’ as adapter name for identification purposes.
def adapter_name
ADAPTER_NAME
end
add_column(table_name, column_name, type, options = {})
click to toggle source
Adds a new column to the named table. See TableDefinition#column for
details of the options you can use.
def add_column(table_name, column_name, type, options = {})
default = options[:default]
notnull = options[:null] == false
execute("ALTER TABLE #{quote_table_name(table_name)} ADD COLUMN #{quote_column_name(column_name)} #{type_to_sql(type, options[:limit], options[:precision], options[:scale])}")
change_column_default(table_name, column_name, default) if options_include_default?(options)
change_column_null(table_name, column_name, false, default) if notnull
end
begin_db_transaction()
click to toggle source
Begins a transaction.
def begin_db_transaction
execute "BEGIN"
end
change_column(table_name, column_name, type, options = {})
click to toggle source
Changes the column of a table.
def change_column(table_name, column_name, type, options = {})
quoted_table_name = quote_table_name(table_name)
begin
execute "ALTER TABLE #{quoted_table_name} ALTER COLUMN #{quote_column_name(column_name)} TYPE #{type_to_sql(type, options[:limit], options[:precision], options[:scale])}"
rescue ActiveRecord::StatementInvalid => e
raise e if postgresql_version > 80000
begin
begin_db_transaction
tmp_column_name = "#{column_name}_ar_tmp"
add_column(table_name, tmp_column_name, type, options)
execute "UPDATE #{quoted_table_name} SET #{quote_column_name(tmp_column_name)} = CAST(#{quote_column_name(column_name)} AS #{type_to_sql(type, options[:limit], options[:precision], options[:scale])})"
remove_column(table_name, column_name)
rename_column(table_name, tmp_column_name, column_name)
commit_db_transaction
rescue
rollback_db_transaction
end
end
change_column_default(table_name, column_name, options[:default]) if options_include_default?(options)
change_column_null(table_name, column_name, options[:null], options[:default]) if options.key?(:null)
end
change_column_default(table_name, column_name, default)
click to toggle source
Changes the default value of a table column.
def change_column_default(table_name, column_name, default)
execute "ALTER TABLE #{quote_table_name(table_name)} ALTER COLUMN #{quote_column_name(column_name)} SET DEFAULT #{quote(default)}"
end
change_column_null(table_name, column_name, null, default = nil)
click to toggle source
def change_column_null(table_name, column_name, null, default = nil)
unless null || default.nil?
execute("UPDATE #{quote_table_name(table_name)} SET #{quote_column_name(column_name)}=#{quote(default)} WHERE #{quote_column_name(column_name)} IS NULL")
end
execute("ALTER TABLE #{quote_table_name(table_name)} ALTER #{quote_column_name(column_name)} #{null ? 'DROP' : 'SET'} NOT NULL")
end
client_min_messages()
click to toggle source
Returns the current client message level.
def client_min_messages
query('SHOW client_min_messages')[0][0]
end
client_min_messages=(level)
click to toggle source
Set the client message level.
def client_min_messages=(level)
execute("SET client_min_messages TO '#{level}'")
end
columns(table_name, name = nil)
click to toggle source
Returns the list of all column definitions for a table.
def columns(table_name, name = nil)
column_definitions(table_name).collect do |name, type, default, notnull|
PostgreSQLColumn.new(name, default, type, notnull == 'f')
end
end
commit_db_transaction()
click to toggle source
Commits a transaction.
def commit_db_transaction
execute "COMMIT"
end
create(sql, name = nil, pk = nil, id_value = nil, sequence_name = nil)
click to toggle source
create_database(name, options = {})
click to toggle source
Create a new PostgreSQL database. Options include :owner,
:template, :encoding, :tablespace, and
:connection_limit (note that MySQL uses :charset while
PostgreSQL uses :encoding).
Example:
create_database config[:database], config
create_database 'foo_development', :encoding => 'unicode'
def create_database(name, options = {})
options = options.reverse_merge(:encoding => "utf8")
option_string = options.symbolize_keys.sum do |key, value|
case key
when :owner
" OWNER = \"#{value}\""
when :template
" TEMPLATE = \"#{value}\""
when :encoding
" ENCODING = '#{value}'"
when :tablespace
" TABLESPACE = \"#{value}\""
when :connection_limit
" CONNECTION LIMIT = #{value}"
else
""
end
end
execute "CREATE DATABASE #{quote_table_name(name)}#{option_string}"
end
create_savepoint()
click to toggle source
def create_savepoint
execute("SAVEPOINT #{current_savepoint_name}")
end
current_database()
click to toggle source
Returns the current database name.
def current_database
query('select current_database()')[0][0]
end
disconnect!()
click to toggle source
Close the connection.
def disconnect!
@connection.close rescue nil
end
encoding()
click to toggle source
Returns the current database encoding format.
def encoding
query( SELECT pg_encoding_to_char(pg_database.encoding) FROM pg_database WHERE pg_database.datname LIKE '#{current_database}')[0][0]
end
escape_bytea(value)
click to toggle source
Escapes binary strings for bytea input to the database.
def escape_bytea(value)
@connection.escape_bytea(value) if value
end
execute(sql, name = nil)
click to toggle source
Executes an SQL statement, returning a PGresult object on success or
raising a PGError exception otherwise.
def execute(sql, name = nil)
log(sql, name) do
if @async
@connection.async_exec(sql)
else
@connection.exec(sql)
end
end
end
index_name_length()
click to toggle source
def index_name_length
63
end
indexes(table_name, name = nil)
click to toggle source
Returns the list of all indexes for a table.
def indexes(table_name, name = nil)
schemas = schema_search_path.split(/,/).map { |p| quote(p) }.join(',')
result = query( SELECT distinct i.relname, d.indisunique, d.indkey, t.oid FROM pg_class t, pg_class i, pg_index d WHERE i.relkind = 'i' AND d.indexrelid = i.oid AND d.indisprimary = 'f' AND t.oid = d.indrelid AND t.relname = '#{table_name}' AND i.relnamespace IN (SELECT oid FROM pg_namespace WHERE nspname IN (#{schemas}) ) ORDER BY i.relname, name)
result.map do |row|
index_name = row[0]
unique = row[1] == 't'
indkey = row[2].split(" ")
oid = row[3]
columns = Hash[query( SELECT a.attnum, a.attname FROM pg_attribute a WHERE a.attrelid = #{oid} AND a.attnum IN (#{indkey.join(",")}), "Columns for index #{row[0]} on #{table_name}")]
column_names = columns.values_at(*indkey).compact
column_names.empty? ? nil : IndexDefinition.new(table_name, index_name, unique, column_names)
end.compact
end
insert(sql, name = nil, pk = nil, id_value = nil, sequence_name = nil)
click to toggle source
Executes an INSERT query and returns the new record’s ID
def insert(sql, name = nil, pk = nil, id_value = nil, sequence_name = nil)
table = sql.split(" ", 4)[2].gsub('"', '')
if supports_insert_with_returning?
pk, sequence_name = *pk_and_sequence_for(table) unless pk
if pk
id = select_value("#{sql} RETURNING #{quote_column_name(pk)}")
clear_query_cache
return id
end
end
if insert_id = super
insert_id
else
unless pk || sequence_name
pk, sequence_name = *pk_and_sequence_for(table)
end
if pk && sequence_name ||= default_sequence_name(table, pk)
last_insert_id(table, sequence_name)
end
end
end
outside_transaction?()
click to toggle source
def outside_transaction?
@connection.transaction_status == PGconn::PQTRANS_IDLE
end
primary_key(table)
click to toggle source
Returns just a table’s primary key
def primary_key(table)
pk_and_sequence = pk_and_sequence_for(table)
pk_and_sequence && pk_and_sequence.first
end
quote_table_name(name)
click to toggle source
Checks the following cases:
def quote_table_name(name)
schema, name_part = extract_pg_identifier_from_name(name.to_s)
unless name_part
quote_column_name(schema)
else
table_name, name_part = extract_pg_identifier_from_name(name_part)
"#{quote_column_name(schema)}.#{quote_column_name(table_name)}"
end
end
reconnect!()
click to toggle source
Close then reopen the connection.
def reconnect!
if @connection.respond_to?(:reset)
@connection.reset
configure_connection
else
disconnect!
connect
end
end
release_savepoint()
click to toggle source
def release_savepoint
execute("RELEASE SAVEPOINT #{current_savepoint_name}")
end
rename_column(table_name, column_name, new_column_name)
click to toggle source
Renames a column in a table.
def rename_column(table_name, column_name, new_column_name)
execute "ALTER TABLE #{quote_table_name(table_name)} RENAME COLUMN #{quote_column_name(column_name)} TO #{quote_column_name(new_column_name)}"
end
rename_table(name, new_name)
click to toggle source
Renames a table.
def rename_table(name, new_name)
execute "ALTER TABLE #{quote_table_name(name)} RENAME TO #{quote_table_name(new_name)}"
end
rollback_db_transaction()
click to toggle source
Aborts a transaction.
def rollback_db_transaction
execute "ROLLBACK"
end
rollback_to_savepoint()
click to toggle source
def rollback_to_savepoint
execute("ROLLBACK TO SAVEPOINT #{current_savepoint_name}")
end
schema_search_path()
click to toggle source
Returns the active schema search path.
def schema_search_path
@schema_search_path ||= query('SHOW search_path')[0][0]
end
schema_search_path=(schema_csv)
click to toggle source
Sets the schema search path to a string of comma-separated schema names.
Names beginning with $ have to be quoted (e.g. $user => ‘$user’).
See: www.postgresql.org/docs/current/static/ddl-schemas.html
This should be not be called manually but set in database.yml.
def schema_search_path=(schema_csv)
if schema_csv
execute "SET search_path TO #{schema_csv}"
@schema_search_path = schema_csv
end
end
select_rows(sql, name = nil)
click to toggle source
Executes a SELECT query and returns an array of rows. Each row is an array
of field values.
def select_rows(sql, name = nil)
select_raw(sql, name).last
end
supports_ddl_transactions?()
click to toggle source
def supports_ddl_transactions?
true
end
supports_insert_with_returning?()
click to toggle source
def supports_insert_with_returning?
postgresql_version >= 80200
end
supports_migrations?()
click to toggle source
Does PostgreSQL support migrations?
def supports_migrations?
true
end
supports_savepoints?()
click to toggle source
def supports_savepoints?
true
end
table_alias_length()
click to toggle source
Returns the configured supported identifier length supported by PostgreSQL,
or report the default of 63 on PostgreSQL 7.x.
def table_alias_length
@table_alias_length ||= (postgresql_version >= 80000 ? query('SHOW max_identifier_length')[0][0].to_i : 63)
end
table_exists?(name)
click to toggle source
def table_exists?(name)
name = name.to_s
schema, table = name.split('.', 2)
unless table
table = schema
schema = nil
end
if name =~ /^"/
table = name
schema = nil
end
query( SELECT COUNT(*) FROM pg_tables WHERE tablename = '#{table.gsub(/(^"|"$)/,'')}' #{schema ? "AND schemaname = '#{schema}'" : ''}).first[0].to_i > 0
end
tables(name = nil)
click to toggle source
Returns the list of all tables in the schema search path or a specified
schema.
def tables(name = nil)
query( SELECT tablename FROM pg_tables WHERE schemaname = ANY (current_schemas(false)), name).map { |row| row[0] }
end
type_to_sql(type, limit = nil, precision = nil, scale = nil)
click to toggle source
Maps logical Rails types to
PostgreSQL-specific data types.
def type_to_sql(type, limit = nil, precision = nil, scale = nil)
return super unless type.to_s == 'integer'
return 'integer' unless limit
case limit
when 1, 2; 'smallint'
when 3, 4; 'integer'
when 5..8; 'bigint'
else raise(ActiveRecordError, "No integer type has byte size #{limit}. Use a numeric with precision 0 instead.")
end
end
unescape_bytea(value)
click to toggle source
Unescapes bytea output from a database to the binary string it represents.
NOTE: This is NOT an inverse of escape_bytea! This
is only to be used
on escaped binary output from database drive.
def unescape_bytea(value)
@connection.unescape_bytea(value) if value
end
update_sql(sql, name = nil)
click to toggle source
Executes an UPDATE query and returns the number of affected tuples.
def update_sql(sql, name = nil)
super.cmd_tuples
end