active?()
click to toggle source
Is this connection alive and ready for queries?
346: def active?
347: @connection.query 'SELECT 1'
348: true
349: rescue PGError
350: false
351: end
adapter_name()
click to toggle source
Returns ‘PostgreSQL’ as adapter name for identification
purposes.
241: def adapter_name
242: ADAPTER_NAME
243: 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.
1025: def add_column(table_name, column_name, type, options = {})
1026: clear_cache!
1027: add_column_sql = "ALTER TABLE #{quote_table_name(table_name)} ADD COLUMN #{quote_column_name(column_name)} #{type_to_sql(type, options[:limit], options[:precision], options[:scale])}"
1028: add_column_options!(add_column_sql, options)
1029:
1030: execute add_column_sql
1031: end
begin_db_transaction()
click to toggle source
Begins a transaction.
702: def begin_db_transaction
703: execute "BEGIN"
704: end
change_column(table_name, column_name, type, options = {})
click to toggle source
Changes the column of a table.
1034: def change_column(table_name, column_name, type, options = {})
1035: clear_cache!
1036: quoted_table_name = quote_table_name(table_name)
1037:
1038: execute "ALTER TABLE #{quoted_table_name} ALTER COLUMN #{quote_column_name(column_name)} TYPE #{type_to_sql(type, options[:limit], options[:precision], options[:scale])}"
1039:
1040: change_column_default(table_name, column_name, options[:default]) if options_include_default?(options)
1041: change_column_null(table_name, column_name, options[:null], options[:default]) if options.key?(:null)
1042: end
change_column_default(table_name, column_name, default)
click to toggle source
Changes the default value of a table column.
1045: def change_column_default(table_name, column_name, default)
1046: clear_cache!
1047: execute "ALTER TABLE #{quote_table_name(table_name)} ALTER COLUMN #{quote_column_name(column_name)} SET DEFAULT #{quote(default)}"
1048: end
change_column_null(table_name, column_name, null, default = nil)
click to toggle source
1050: def change_column_null(table_name, column_name, null, default = nil)
1051: clear_cache!
1052: unless null || default.nil?
1053: execute("UPDATE #{quote_table_name(table_name)} SET #{quote_column_name(column_name)}=#{quote(default)} WHERE #{quote_column_name(column_name)} IS NULL")
1054: end
1055: execute("ALTER TABLE #{quote_table_name(table_name)} ALTER #{quote_column_name(column_name)} #{null ? 'DROP' : 'SET'} NOT NULL")
1056: end
clear_cache!()
click to toggle source
Clears the prepared statements cache.
341: def clear_cache!
342: @statements.clear
343: end
client_min_messages()
click to toggle source
Returns the current client message level.
900: def client_min_messages
901: query('SHOW client_min_messages', 'SCHEMA')[0][0]
902: end
client_min_messages=(level)
click to toggle source
Set the client message level.
905: def client_min_messages=(level)
906: execute("SET client_min_messages TO '#{level}'", 'SCHEMA')
907: end
columns(table_name, name = nil)
click to toggle source
Returns the list of all column definitions for a table.
857: def columns(table_name, name = nil)
858:
859: column_definitions(table_name).collect do |column_name, type, default, notnull|
860: PostgreSQLColumn.new(column_name, default, type, notnull == 'f')
861: end
862: end
commit_db_transaction()
click to toggle source
Commits a transaction.
707: def commit_db_transaction
708: execute "COMMIT"
709: end
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'
748: def create_database(name, options = {})
749: options = options.reverse_merge(:encoding => "utf8")
750:
751: option_string = options.symbolize_keys.sum do |key, value|
752: case key
753: when :owner
754: " OWNER = \"#{value}\""
755: when :template
756: " TEMPLATE = \"#{value}\""
757: when :encoding
758: " ENCODING = '#{value}'"
759: when :tablespace
760: " TABLESPACE = \"#{value}\""
761: when :connection_limit
762: " CONNECTION LIMIT = #{value}"
763: else
764: ""
765: end
766: end
767:
768: execute "CREATE DATABASE #{quote_table_name(name)}#{option_string}"
769: end
create_savepoint()
click to toggle source
720: def create_savepoint
721: execute("SAVEPOINT #{current_savepoint_name}")
722: end
current_database()
click to toggle source
Returns the current database name.
865: def current_database
866: query('select current_database()')[0][0]
867: end
current_schema()
click to toggle source
Returns the current schema name.
870: def current_schema
871: query('SELECT current_schema', 'SCHEMA')[0][0]
872: end
disconnect!()
click to toggle source
Disconnects from the database if already connected. Otherwise, this method
does nothing.
367: def disconnect!
368: clear_cache!
369: @connection.close rescue nil
370: end
encoding()
click to toggle source
Returns the current database encoding format.
875: def encoding
876: query( SELECT pg_encoding_to_char(pg_database.encoding) FROM pg_database WHERE pg_database.datname LIKE '#{current_database}')[0][0]
877: end
escape_bytea(value)
click to toggle source
Escapes binary strings for bytea input to the database.
420: def escape_bytea(value)
421: @connection.escape_bytea(value) if value
422: end
exec_delete(sql, name = 'SQL', binds = [])
click to toggle source
673: def exec_delete(sql, name = 'SQL', binds = [])
674: log(sql, name, binds) do
675: result = binds.empty? ? exec_no_cache(sql, binds) :
676: exec_cache(sql, binds)
677: affected = result.cmd_tuples
678: result.clear
679: affected
680: end
681: end
exec_query(sql, name = 'SQL', binds = [])
click to toggle source
662: def exec_query(sql, name = 'SQL', binds = [])
663: log(sql, name, binds) do
664: result = binds.empty? ? exec_no_cache(sql, binds) :
665: exec_cache(sql, binds)
666:
667: ret = ActiveRecord::Result.new(result.fields, result_as_array(result))
668: result.clear
669: return ret
670: end
671: end
exec_update(sql, name = 'SQL', binds = [])
click to toggle source
execute(sql, name = nil)
click to toggle source
Executes an SQL statement, returning a PGresult object on success or
raising a PGError exception otherwise.
652: def execute(sql, name = nil)
653: log(sql, name) do
654: @connection.async_exec(sql)
655: end
656: end
explain(arel, binds = [])
click to toggle source
DATABASE STATEMENTS ======================================
536: def explain(arel, binds = [])
537: sql = "EXPLAIN #{to_sql(arel, binds)}"
538: ExplainPrettyPrinter.new.pp(exec_query(sql, 'EXPLAIN', binds))
539: end
index_name_length()
click to toggle source
1072: def index_name_length
1073: 63
1074: end
indexes(table_name, name = nil)
click to toggle source
Returns an array of indexes for the given table.
818: def indexes(table_name, name = nil)
819: result = query( SELECT distinct i.relname, d.indisunique, d.indkey, pg_get_indexdef(d.indexrelid), t.oid FROM pg_class t INNER JOIN pg_index d ON t.oid = d.indrelid INNER JOIN pg_class i ON d.indexrelid = i.oid WHERE i.relkind = 'i' AND d.indisprimary = 'f' AND t.relname = '#{table_name}' AND i.relnamespace IN (SELECT oid FROM pg_namespace WHERE nspname = ANY (current_schemas(false)) ) ORDER BY i.relname, name)
820:
821:
822: result.map do |row|
823: index_name = row[0]
824: unique = row[1] == 't'
825: indkey = row[2].split(" ")
826: inddef = row[3]
827: oid = row[4]
828:
829: 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}")]
830:
831: column_names = columns.values_at(*indkey).compact
832:
833:
834: desc_order_columns = inddef.scan(/(\w+) DESC/).flatten
835: orders = desc_order_columns.any? ? Hash[desc_order_columns.map {|order_column| [order_column, :desc]}] : {}
836:
837: column_names.empty? ? nil : IndexDefinition.new(table_name, index_name, unique, column_names, [], orders)
838: end.compact
839: end
insert_sql(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
585: def insert_sql(sql, name = nil, pk = nil, id_value = nil, sequence_name = nil)
586: unless pk
587:
588: table_ref = extract_table_ref_from_insert_sql(sql)
589: pk = primary_key(table_ref) if table_ref
590: end
591:
592: if pk
593: select_value("#{sql} RETURNING #{quote_column_name(pk)}")
594: else
595: super
596: end
597: end
outside_transaction?()
click to toggle source
716: def outside_transaction?
717: @connection.transaction_status == PGconn::PQTRANS_IDLE
718: end
primary_key(table)
click to toggle source
Returns just a table’s primary key
994: def primary_key(table)
995: row = exec_query( SELECT DISTINCT(attr.attname) FROM pg_attribute attr INNER JOIN pg_depend dep ON attr.attrelid = dep.refobjid AND attr.attnum = dep.refobjsubid INNER JOIN pg_constraint cons ON attr.attrelid = cons.conrelid AND attr.attnum = cons.conkey[1] WHERE cons.contype = 'p' AND dep.refobjid = $1::regclass, 'SCHEMA', [[nil, table]]).rows.first
996:
997: row && row.first
998: end
quote_table_name(name)
click to toggle source
Checks the following cases:
485: def quote_table_name(name)
486: schema, name_part = extract_pg_identifier_from_name(name.to_s)
487:
488: unless name_part
489: quote_column_name(schema)
490: else
491: table_name, name_part = extract_pg_identifier_from_name(name_part)
492: "#{quote_column_name(schema)}.#{quote_column_name(table_name)}"
493: end
494: end
reconnect!()
click to toggle source
Close then reopen the connection.
354: def reconnect!
355: clear_cache!
356: @connection.reset
357: configure_connection
358: end
release_savepoint()
click to toggle source
728: def release_savepoint
729: execute("RELEASE SAVEPOINT #{current_savepoint_name}")
730: end
rename_column(table_name, column_name, new_column_name)
click to toggle source
Renames a column in a table.
1059: def rename_column(table_name, column_name, new_column_name)
1060: clear_cache!
1061: execute "ALTER TABLE #{quote_table_name(table_name)} RENAME COLUMN #{quote_column_name(column_name)} TO #{quote_column_name(new_column_name)}"
1062: end
rename_index(table_name, old_name, new_name)
click to toggle source
1068: def rename_index(table_name, old_name, new_name)
1069: execute "ALTER INDEX #{quote_column_name(old_name)} RENAME TO #{quote_table_name(new_name)}"
1070: end
rename_table(name, new_name)
click to toggle source
Renames a table. Also renames a table’s primary key sequence if the
sequence name matches the Active Record default.
Example:
rename_table('octopuses', 'octopi')
1013: def rename_table(name, new_name)
1014: clear_cache!
1015: execute "ALTER TABLE #{quote_table_name(name)} RENAME TO #{quote_table_name(new_name)}"
1016: pk, seq = pk_and_sequence_for(new_name)
1017: if seq == "#{name}_#{pk}_seq"
1018: new_seq = "#{new_name}_#{pk}_seq"
1019: execute "ALTER TABLE #{quote_table_name(seq)} RENAME TO #{quote_table_name(new_seq)}"
1020: end
1021: end
reset!()
click to toggle source
360: def reset!
361: clear_cache!
362: super
363: end
rollback_db_transaction()
click to toggle source
Aborts a transaction.
712: def rollback_db_transaction
713: execute "ROLLBACK"
714: end
rollback_to_savepoint()
click to toggle source
724: def rollback_to_savepoint
725: execute("ROLLBACK TO SAVEPOINT #{current_savepoint_name}")
726: end
schema_exists?(name)
click to toggle source
Returns true if schema exists.
809: def schema_exists?(name)
810: exec_query( SELECT COUNT(*) FROM pg_namespace WHERE nspname = $1, 'SCHEMA', [[nil, name]]).rows.first[0].to_i > 0
811: end
schema_search_path()
click to toggle source
Returns the active schema search path.
895: def schema_search_path
896: @schema_search_path ||= query('SHOW search_path', 'SCHEMA')[0][0]
897: 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.
887: def schema_search_path=(schema_csv)
888: if schema_csv
889: execute("SET search_path TO #{schema_csv}", 'SCHEMA')
890: @schema_search_path = schema_csv
891: end
892: 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.
580: def select_rows(sql, name = nil)
581: select_raw(sql, name).last
582: end
serial_sequence(table, column)
click to toggle source
916: def serial_sequence(table, column)
917: result = exec_query( SELECT pg_get_serial_sequence($1, $2), 'SCHEMA', [[nil, table], [nil, column]])
918: result.rows.first.first
919: end
session_auth=(user)
click to toggle source
Set the authorized user for this session
512: def session_auth=(user)
513: clear_cache!
514: exec_query "SET SESSION AUTHORIZATION #{user}"
515: end
sql_for_insert(sql, pk, id_value, sequence_name, binds)
click to toggle source
684: def sql_for_insert(sql, pk, id_value, sequence_name, binds)
685: unless pk
686:
687: table_ref = extract_table_ref_from_insert_sql(sql)
688: pk = primary_key(table_ref) if table_ref
689: end
690:
691: sql = "#{sql} RETURNING #{quote_column_name(pk)}" if pk
692:
693: [sql, binds]
694: end
substitute_at(column, index)
click to toggle source
658: def substitute_at(column, index)
659: Arel::Nodes::BindParam.new "$#{index + 1}"
660: end
supports_ddl_transactions?()
click to toggle source
398: def supports_ddl_transactions?
399: true
400: end
supports_explain?()
click to toggle source
Returns true.
408: def supports_explain?
409: true
410: end
supports_index_sort_order?()
click to toggle source
251: def supports_index_sort_order?
252: true
253: end
supports_insert_with_returning?()
click to toggle source
394: def supports_insert_with_returning?
395: true
396: end
supports_migrations?()
click to toggle source
Returns true, since this connection adapter supports migrations.
377: def supports_migrations?
378: true
379: end
supports_savepoints?()
click to toggle source
Returns true, since this connection adapter supports savepoints.
403: def supports_savepoints?
404: true
405: end
supports_statement_cache?()
click to toggle source
Returns true, since this connection adapter supports prepared
statement caching.
247: def supports_statement_cache?
248: true
249: end
table_alias_length()
click to toggle source
Returns the configured supported identifier length supported by PostgreSQL
413: def table_alias_length
414: @table_alias_length ||= query('SHOW max_identifier_length')[0][0].to_i
415: end
table_exists?(name)
click to toggle source
Returns true if table exists. If the schema is not specified as part of
name then it will only find tables within the current schema
search path (regardless of permissions to access tables in other schemas)
791: def table_exists?(name)
792: schema, table = Utils.extract_schema_and_table(name.to_s)
793: return false unless table
794:
795: binds = [[nil, table]]
796: binds << [nil, schema] if schema
797:
798: exec_query( SELECT COUNT(*) FROM pg_class c LEFT JOIN pg_namespace n ON n.oid = c.relnamespace WHERE c.relkind in ('v','r') AND c.relname = $1 AND n.nspname = #{schema ? '$2' : 'ANY (current_schemas(false))'}, 'SCHEMA', binds).rows.first[0].to_i > 0
799: end
tables(name = nil)
click to toggle source
Returns the list of all tables in the schema search path or a specified
schema.
780: def tables(name = nil)
781: query( SELECT tablename FROM pg_tables WHERE schemaname = ANY (current_schemas(false)), 'SCHEMA').map { |row| row[0] }
782: end
type_cast(value, column)
click to toggle source
460: def type_cast(value, column)
461: return super unless column
462:
463: case value
464: when String
465: return super unless 'bytea' == column.sql_type
466: { :value => value, :format => 1 }
467: else
468: super
469: end
470: end
type_to_sql(type, limit = nil, precision = nil, scale = nil)
click to toggle source
Maps logical Rails types to PostgreSQL-specific data types.
1077: def type_to_sql(type, limit = nil, precision = nil, scale = nil)
1078: case type.to_s
1079: when 'binary'
1080:
1081:
1082: case limit
1083: when nil, 0..0x3fffffff; super(type)
1084: else raise(ActiveRecordError, "No binary type has byte size #{limit}.")
1085: end
1086: when 'integer'
1087: return 'integer' unless limit
1088:
1089: case limit
1090: when 1, 2; 'smallint'
1091: when 3, 4; 'integer'
1092: when 5..8; 'bigint'
1093: else raise(ActiveRecordError, "No integer type has byte size #{limit}. Use a numeric with precision 0 instead.")
1094: end
1095: else
1096: super
1097: end
1098: 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.
427: def unescape_bytea(value)
428: @connection.unescape_bytea(value) if value
429: end
update_sql(sql, name = nil)
click to toggle source
Executes an UPDATE query and returns the number of affected tuples.
697: def update_sql(sql, name = nil)
698: super.cmd_tuples
699: end