Module: ArJdbc::PostgreSQL
- Included in:
- ActiveRecord::ConnectionAdapters::PostgreSQLAdapter
- Defined in:
- lib/arjdbc/postgresql/adapter.rb,
lib/arjdbc/postgresql/column.rb,
lib/arjdbc/postgresql/explain_support.rb,
lib/arjdbc/postgresql/schema_creation.rb
Overview
Strives to provide Rails built-in PostgreSQL adapter (API) compatibility.
Defined Under Namespace
Modules: Column, ExplainSupport Classes: SchemaCreation
Constant Summary collapse
- ADAPTER_NAME =
'PostgreSQL'.freeze
- NATIVE_DATABASE_TYPES =
{ :primary_key => "serial primary key", :string => { :name => "character varying", :limit => 255 }, :text => { :name => "text" }, :integer => { :name => "integer" }, :float => { :name => "float" }, :numeric => { :name => "numeric" }, :decimal => { :name => "decimal" }, # :limit => 1000 :datetime => { :name => "timestamp" }, :timestamp => { :name => "timestamp" }, :time => { :name => "time" }, :date => { :name => "date" }, :binary => { :name => "bytea" }, :boolean => { :name => "boolean" }, :xml => { :name => "xml" }, # AR-JDBC added : #:timestamptz => { :name => "timestamptz" }, #:timetz => { :name => "timetz" }, :money => { :name=>"money" }, :char => { :name => "char" }, :serial => { :name => "serial" }, # auto-inc integer, bigserial, smallserial }
Class Method Summary collapse
Instance Method Summary collapse
- #adapter_name ⇒ Object
-
#add_column(table_name, column_name, type, options = {}) ⇒ Object
Adds a new column to the named table.
-
#add_index(table_name, column_name, options = {}) ⇒ Object
unless const_defined? :SchemaCreation.
-
#add_order_by_for_association_limiting!(sql, options) ⇒ Object
ORDER BY clause for the passed order option.
- #all_schemas ⇒ Object
-
#change_column(table_name, column_name, type, options = {}) ⇒ Object
Changes the column of a table.
-
#change_column_default(table_name, column_name, default) ⇒ Object
Changes the default value of a table column.
-
#change_column_null(table_name, column_name, null, default = nil) ⇒ Object
unless const_defined? :SchemaCreation.
-
#client_min_messages ⇒ Object
Returns the current client message level.
-
#client_min_messages=(level) ⇒ Object
Set the client message level.
-
#collation ⇒ Object
Returns the current database collation.
-
#columns(table_name, name = nil) ⇒ Object
Returns the list of all column definitions for a table.
-
#columns_for_distinct(columns, orders) ⇒ Object
PostgreSQL requires the ORDER BY columns in the select list for distinct queries, and requires that the ORDER BY include the distinct column.
-
#configure_connection ⇒ Object
Configures the encoding, verbosity, schema search path, and time zone of the connection.
-
#create_database(name, options = {}) ⇒ Object
Create a new PostgreSQL database.
- #create_savepoint(name = current_savepoint_name(true)) ⇒ Object
-
#create_schema(schema_name, pg_username = nil) ⇒ Object
Creates a schema for the given schema name.
-
#ctype ⇒ Object
Returns the current database ctype.
-
#current_database ⇒ Object
current database name.
-
#current_schema ⇒ Object
Returns the current schema name.
- #default_sequence_name(table_name, pk = nil) ⇒ Object
- #disable_extension(name) ⇒ Object
- #disable_referential_integrity ⇒ Object
- #distinct(columns, orders) ⇒ Object
- #drop_database(name) ⇒ Object
-
#drop_schema(schema_name) ⇒ Object
Drops the schema for the given schema name.
-
#enable_extension(name) ⇒ Object
NOTE: only since AR-4.0 but should not hurt on other versions.
-
#encoding ⇒ Object
Returns the current database encoding format.
- #escape_bytea(string) ⇒ Object
- #exec_insert(sql, name, binds, pk = nil, sequence_name = nil) ⇒ Object
- #extension_enabled?(name) ⇒ Boolean
- #extensions ⇒ Object
- #index_algorithms ⇒ Object
- #index_name_length ⇒ Object
-
#indexes(table_name, name = nil) ⇒ Object
Returns an array of indexes for the given table.
- #insert_sql(sql, name = nil, pk = nil, id_value = nil, sequence_name = nil, binds = []) ⇒ Object
- #last_insert_id(table, sequence_name = nil) ⇒ Object
- #last_insert_id_result(sequence_name) ⇒ Object
-
#last_inserted_id(result) ⇒ Integer, NilClass
Take an id from the result of an INSERT query.
-
#migration_keys ⇒ Object
Adds
:arrayas a valid migration key. -
#multi_column_index_limit ⇒ Object
Gets the maximum number columns postgres has, default 32.
-
#multi_column_index_limit=(limit) ⇒ Object
Sets the maximum number columns postgres has, default 32.
- #native_database_types ⇒ Object
-
#pk_and_sequence_for(table) ⇒ Object
Find a table's primary key and sequence.
- #postgresql_version ⇒ Object
-
#prepare_column_options(column, types) ⇒ Object
Adds
:arrayoption to the default set provided by theAbstractAdapter. - #primary_key(table) ⇒ Object
- #quote(value, column = nil) ⇒ String
- #quote_bit(value) ⇒ String
- #quote_column_name(name) ⇒ Object
-
#quote_string(string) ⇒ String
Quotes a string, escaping any ' (single quote) and \ (backslash) chars.
- #quote_table_name(name) ⇒ Object
- #quote_table_name_for_assignment(table, attr) ⇒ Object
-
#quoted_date(value) ⇒ Object
Quote date/time values for use in SQL input.
- #recreate_database(name, options = {}) ⇒ Object
- #release_savepoint(name = current_savepoint_name) ⇒ Object
- #remove_index!(table_name, index_name) ⇒ Object
-
#rename_column(table_name, column_name, new_column_name) ⇒ Object
unless const_defined? :SchemaCreation.
- #rename_table(table_name, new_name) ⇒ Object
-
#reset_pk_sequence!(table, pk = nil, sequence = nil) ⇒ Object
Resets sequence to the max value of the table's primary key if present.
- #rollback_to_savepoint(name = current_savepoint_name) ⇒ Object
- #schema_creation ⇒ Object
-
#schema_exists?(name) ⇒ Boolean
Returns true if schema exists.
-
#schema_names ⇒ Object
Returns an array of schema names.
-
#schema_search_path ⇒ Object
Returns the active schema search path.
-
#schema_search_path=(schema_csv) ⇒ Object
Sets the schema search path to a string of comma-separated schema names.
-
#session_auth=(user) ⇒ Object
Set the authorized user for this session.
- #set_client_encoding(encoding) ⇒ Object
-
#set_standard_conforming_strings ⇒ Object
Enable standard-conforming strings if available.
- #sql_for_insert(sql, pk, id_value, sequence_name, binds) ⇒ Object
-
#standard_conforming_strings=(enable) ⇒ Object
Enable standard-conforming strings if available.
- #standard_conforming_strings? ⇒ Boolean
-
#structure_dump ⇒ Object
deprecated
Deprecated.
no longer used - handled with (AR built-in) Rake tasks
- #supports_ddl_transactions? ⇒ Boolean
- #supports_disable_referential_integrity? ⇒ Boolean
- #supports_extensions? ⇒ Boolean
- #supports_hex_escaped_bytea? ⇒ Boolean
- #supports_index_sort_order? ⇒ Boolean
- #supports_insert_with_returning? ⇒ Boolean
-
#supports_migrations? ⇒ Boolean
Does PostgreSQL support migrations?.
- #supports_partial_index? ⇒ Boolean
-
#supports_primary_key? ⇒ Boolean
Does PostgreSQL support finding primary key on non-Active Record tables?.
-
#supports_ranges? ⇒ Boolean
Range data-types weren't introduced until PostgreSQL 9.2.
- #supports_savepoints? ⇒ Boolean
-
#supports_standard_conforming_strings? ⇒ Boolean
Does PostgreSQL support standard conforming strings?.
- #supports_transaction_isolation?(level = nil) ⇒ Boolean
-
#table_alias_length ⇒ Object
Returns the configured supported identifier length supported by PostgreSQL, or report the default of 63 on PostgreSQL 7.x.
- #table_exists?(name) ⇒ Boolean
- #tables(name = nil) ⇒ Object
- #type_cast(value, column, array_member = false) ⇒ Object
-
#type_to_sql(type, limit = nil, precision = nil, scale = nil) ⇒ Object
Maps logical Rails types to PostgreSQL-specific data types.
- #use_insert_returning? ⇒ Boolean
Class Method Details
.arel_visitor_type(config = nil) ⇒ Object
32 33 34 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 32 def self.arel_visitor_type(config = nil) ::Arel::Visitors::PostgreSQL end |
.column_selector ⇒ Object
5 6 7 |
# File 'lib/arjdbc/postgresql/column.rb', line 5 def self.column_selector [ /postgre/i, lambda { |cfg, column| column.extend(Column) } ] end |
.jdbc_connection_class ⇒ Object
17 18 19 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 17 def self.jdbc_connection_class ::ActiveRecord::ConnectionAdapters::PostgreSQLJdbcConnection end |
Instance Method Details
#adapter_name ⇒ Object
44 45 46 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 44 def adapter_name ADAPTER_NAME end |
#add_column(table_name, column_name, type, options = {}) ⇒ Object
Adds a new column to the named table. See TableDefinition#column for details of the options you can use.
959 960 961 962 963 964 965 966 967 968 969 970 971 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 959 def add_column(table_name, column_name, type, = {}) default = [:default] notnull = [:null] == false sql_type = type_to_sql(type, [:limit], [:precision], [:scale]) sql_type << "[]" if [:array] # Add the column. execute("ALTER TABLE #{quote_table_name(table_name)} ADD COLUMN #{quote_column_name(column_name)} #{sql_type}") change_column_default(table_name, column_name, default) if () change_column_null(table_name, column_name, false, default) if notnull end |
#add_index(table_name, column_name, options = {}) ⇒ Object
unless const_defined? :SchemaCreation
1019 1020 1021 1022 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 1019 def add_index(table_name, column_name, = {}) index_name, index_type, index_columns, , index_algorithm, index_using = (table_name, column_name, ) execute "CREATE #{index_type} INDEX #{index_algorithm} #{quote_column_name(index_name)} ON #{quote_table_name(table_name)} #{index_using} (#{index_columns})#{index_options}" end |
#add_order_by_for_association_limiting!(sql, options) ⇒ Object
ORDER BY clause for the passed order option.
PostgreSQL does not allow arbitrary ordering when using DISTINCT ON, so we work around this by wrapping the SQL as a sub-select and ordering in that query.
779 780 781 782 783 784 785 786 787 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 779 def add_order_by_for_association_limiting!(sql, ) return sql if [:order].blank? order = [:order].split(',').collect { |s| s.strip }.reject(&:blank?) order.map! { |s| 'DESC' if s =~ /\bdesc$/i } order = order.zip((0...order.size).to_a).map { |s,i| "id_list.alias_#{i} #{s}" }.join(', ') sql.replace "SELECT * FROM (#{sql}) AS id_list ORDER BY #{order}" end |
#all_schemas ⇒ Object
698 699 700 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 698 def all_schemas select('SELECT nspname FROM pg_namespace').map { |row| row["nspname"] } end |
#change_column(table_name, column_name, type, options = {}) ⇒ Object
Changes the column of a table.
974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 974 def change_column(table_name, column_name, type, = {}) quoted_table_name = quote_table_name(table_name) sql_type = type_to_sql(type, [:limit], [:precision], [:scale]) sql_type << "[]" if [:array] begin execute "ALTER TABLE #{quoted_table_name} ALTER COLUMN #{quote_column_name(column_name)} TYPE #{sql_type}" rescue ActiveRecord::StatementInvalid => e raise e if postgresql_version > 80000 # This is PostgreSQL 7.x, so we have to use a more arcane way of doing it. begin begin_db_transaction tmp_column_name = "#{column_name}_ar_tmp" add_column(table_name, tmp_column_name, type, ) execute "UPDATE #{quoted_table_name} SET #{quote_column_name(tmp_column_name)} = CAST(#{quote_column_name(column_name)} AS #{sql_type})" 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, [:default]) if () change_column_null(table_name, column_name, [:null], [:default]) if .key?(:null) end |
#change_column_default(table_name, column_name, default) ⇒ Object
Changes the default value of a table column.
1003 1004 1005 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 1003 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) ⇒ Object
unless const_defined? :SchemaCreation
1007 1008 1009 1010 1011 1012 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 1007 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 ⇒ Object
Returns the current client message level.
731 732 733 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 731 def select_value('SHOW client_min_messages', 'SCHEMA') end |
#client_min_messages=(level) ⇒ Object
Set the client message level.
736 737 738 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 736 def (level) execute("SET client_min_messages TO '#{level}'", 'SCHEMA') end |
#collation ⇒ Object
Returns the current database collation.
589 590 591 592 593 594 595 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 589 def collation select_value( "SELECT pg_database.datcollate" << " FROM pg_database" << " WHERE pg_database.datname LIKE '#{current_database}'", 'SCHEMA') end |
#columns(table_name, name = nil) ⇒ Object
Returns the list of all column definitions for a table.
1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 1033 def columns(table_name, name = nil) klass = ::ActiveRecord::ConnectionAdapters::PostgreSQLColumn column_definitions(table_name).map do |row| # name, type, default, notnull, oid, fmod name = row[0]; type = row[1]; default = row[2] notnull = row[3]; oid = row[4]; fmod = row[5] # oid = OID::TYPE_MAP.fetch(oid.to_i, fmod.to_i) { OID::Identity.new } notnull = notnull == 't' if notnull.is_a?(String) # JDBC gets true/false # for ID columns we get a bit of non-sense default : # e.g. "nextval('mixed_cases_id_seq'::regclass" if default =~ /^nextval\(.*?\:\:regclass\)$/ default = nil elsif default =~ /^\(([-+]?[\d\.]+)\)$/ # e.g. "(-1)" for a negative default default = $1 end klass.new(name, default, oid, type, ! notnull) end end |
#columns_for_distinct(columns, orders) ⇒ Object
PostgreSQL requires the ORDER BY columns in the select list for distinct queries, and requires that the ORDER BY include the distinct column.
758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 758 def columns_for_distinct(columns, orders) if orders.is_a?(String) orders = orders.split(','); orders.each(&:strip!) end order_columns = orders.reject(&:blank?).map! do |column| column = column.to_sql unless column.is_a?(String) # handle AREL node column.gsub(/\s+(ASC|DESC)\s*(NULLS\s+(FIRST|LAST)\s*)?/i, '') # remove ASC/DESC end order_columns.reject!(&:blank?) i = -1; order_columns.map! { |c| "#{c} AS alias_#{i += 1}" } columns = [ columns ]; columns.flatten! columns.push( *order_columns ).join(', ') end |
#configure_connection ⇒ Object
Configures the encoding, verbosity, schema search path, and time zone of the connection.
This is called on connection.connect and should not be called manually.
74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 74 def configure_connection #if encoding = config[:encoding] # The client_encoding setting is set by the driver and should not be altered. # If the driver detects a change it will abort the connection. # see http://jdbc.postgresql.org/documentation/91/connect.html # self.set_client_encoding(encoding) #end self. = config[:min_messages] || 'warning' self.schema_search_path = config[:schema_search_path] || config[:schema_order] # Use standard-conforming strings if available so we don't have to do the E'...' dance. set_standard_conforming_strings # If using Active Record's time zone support configure the connection to return # TIMESTAMP WITH ZONE types in UTC. # (SET TIME ZONE does not use an equals sign like other SET variables) if ActiveRecord::Base.default_timezone == :utc execute("SET time zone 'UTC'", 'SCHEMA') elsif tz = local_tz execute("SET time zone '#{tz}'", 'SCHEMA') end # if defined? ActiveRecord::Base.default_timezone # SET statements from :variables config hash # http://www.postgresql.org/docs/8.3/static/sql-set.html (config[:variables] || {}).map do |k, v| if v == ':default' || v == :default # Sets the value to the global or compile default execute("SET SESSION #{k.to_s} TO DEFAULT", 'SCHEMA') elsif ! v.nil? execute("SET SESSION #{k.to_s} TO #{quote(v)}", 'SCHEMA') end end end |
#create_database(name, options = {}) ⇒ Object
Create a new PostgreSQL database. Options include :owner, :template, :encoding, :collation, :ctype, :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'
653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 653 def create_database(name, = {}) = { :encoding => 'utf8' }.merge!(.symbolize_keys) option_string = .sum do |key, value| case key when :owner " OWNER = \"#{value}\"" when :template " TEMPLATE = \"#{value}\"" when :encoding " ENCODING = '#{value}'" when :collation " LC_COLLATE = '#{value}'" when :ctype " LC_CTYPE = '#{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(name = current_savepoint_name(true)) ⇒ Object
347 348 349 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 347 def create_savepoint(name = current_savepoint_name(true)) log("SAVEPOINT #{name}", 'Savepoint') { super } end |
#create_schema(schema_name, pg_username = nil) ⇒ Object
Creates a schema for the given schema name.
685 686 687 688 689 690 691 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 685 def create_schema(schema_name, pg_username = nil) if pg_username.nil? # AR 4.0 compatibility - accepts only single argument execute "CREATE SCHEMA #{schema_name}" else execute("CREATE SCHEMA \"#{schema_name}\" AUTHORIZATION \"#{pg_username}\"") end end |
#ctype ⇒ Object
Returns the current database ctype.
598 599 600 601 602 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 598 def ctype select_value( "SELECT pg_database.datctype FROM pg_database WHERE pg_database.datname LIKE '#{current_database}'", 'SCHEMA') end |
#current_database ⇒ Object
current database name
575 576 577 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 575 def current_database select_value('SELECT current_database()', 'SCHEMA') end |
#current_schema ⇒ Object
Returns the current schema name.
570 571 572 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 570 def current_schema select_value('SELECT current_schema', 'SCHEMA') end |
#default_sequence_name(table_name, pk = nil) ⇒ Object
409 410 411 412 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 409 def default_sequence_name(table_name, pk = nil) default_pk, default_seq = pk_and_sequence_for(table_name) default_seq || "#{table_name}_#{pk || default_pk || 'id'}_seq" end |
#disable_extension(name) ⇒ Object
369 370 371 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 369 def disable_extension(name) execute("DROP EXTENSION IF EXISTS \"#{name}\" CASCADE") end |
#disable_referential_integrity ⇒ Object
928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 928 def disable_referential_integrity if supports_disable_referential_integrity? begin execute(tables.collect { |name| "ALTER TABLE #{quote_table_name(name)} DISABLE TRIGGER ALL" }.join(";")) rescue execute(tables.collect { |name| "ALTER TABLE #{quote_table_name(name)} DISABLE TRIGGER USER" }.join(";")) end end yield ensure if supports_disable_referential_integrity? begin execute(tables.collect { |name| "ALTER TABLE #{quote_table_name(name)} ENABLE TRIGGER ALL" }.join(";")) rescue execute(tables.collect { |name| "ALTER TABLE #{quote_table_name(name)} ENABLE TRIGGER USER" }.join(";")) end end end |
#distinct(columns, orders) ⇒ Object
751 752 753 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 751 def distinct(columns, orders) "DISTINCT #{columns_for_distinct(columns, orders)}" end |
#drop_database(name) ⇒ Object
680 681 682 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 680 def drop_database(name) execute "DROP DATABASE IF EXISTS #{quote_table_name(name)}" end |
#drop_schema(schema_name) ⇒ Object
Drops the schema for the given schema name.
694 695 696 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 694 def drop_schema schema_name execute "DROP SCHEMA #{schema_name} CASCADE" end |
#enable_extension(name) ⇒ Object
NOTE: only since AR-4.0 but should not hurt on other versions
365 366 367 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 365 def enable_extension(name) execute("CREATE EXTENSION IF NOT EXISTS \"#{name}\"") end |
#encoding ⇒ Object
Returns the current database encoding format.
580 581 582 583 584 585 586 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 580 def encoding select_value( "SELECT pg_encoding_to_char(pg_database.encoding)" << " FROM pg_database" << " WHERE pg_database.datname LIKE '#{current_database}'", 'SCHEMA') end |
#escape_bytea(string) ⇒ Object
877 878 879 880 881 882 883 884 885 886 887 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 877 def escape_bytea(string) if string if supports_hex_escaped_bytea? "\\\\x#{string.unpack("H*")[0]}" else result = '' string.each_byte { |c| result << sprintf('\\\\%03o', c) } result end end end |
#exec_insert(sql, name, binds, pk = nil, sequence_name = nil) ⇒ Object
531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 531 def exec_insert(sql, name, binds, pk = nil, sequence_name = nil) # NOTE: 3.2 does not pass the PK on #insert (passed only into #sql_for_insert) : # sql, binds = sql_for_insert(to_sql(arel, binds), pk, id_value, sequence_name, binds) # 3.2 : # value = exec_insert(sql, name, binds) # 4.x : # value = exec_insert(sql, name, binds, pk, sequence_name) if use_insert_returning? && ( pk || (sql.is_a?(String) && sql =~ /RETURNING "?\S+"?$/) ) exec_query(sql, name, binds) # due RETURNING clause returns a result set else result = super if pk unless sequence_name table_ref = extract_table_ref_from_insert_sql(sql) sequence_name = default_sequence_name(table_ref, pk) return result unless sequence_name end last_insert_id_result(sequence_name) else result end end end |
#extension_enabled?(name) ⇒ Boolean
373 374 375 376 377 378 379 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 373 def extension_enabled?(name) if supports_extensions? rows = select_rows("SELECT EXISTS(SELECT * FROM pg_available_extensions WHERE name = '#{name}' AND installed_version IS NOT NULL)", 'SCHEMA') available = rows.first.first # true/false or 't'/'f' available == true || available == 't' end end |
#extensions ⇒ Object
381 382 383 384 385 386 387 388 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 381 def extensions if supports_extensions? rows = select_rows "SELECT extname from pg_extension", "SCHEMA" rows.map { |row| row.first } else [] end end |
#index_algorithms ⇒ Object
390 391 392 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 390 def index_algorithms { :concurrently => 'CONCURRENTLY' } end |
#index_name_length ⇒ Object
1028 1029 1030 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 1028 def index_name_length 63 end |
#indexes(table_name, name = nil) ⇒ Object
Returns an array of indexes for the given table.
1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 1113 def indexes(table_name, name = nil) # NOTE: maybe it's better to leave things of to the JDBC API ?! result = select_rows(" SELECT distinct i.relname, d.indisunique, d.indkey, pg_get_indexdef(d.indexrelid), t.oid\n FROM pg_class t\n INNER JOIN pg_index d ON t.oid = d.indrelid\n INNER JOIN pg_class i ON d.indexrelid = i.oid\n WHERE i.relkind = 'i'\n AND d.indisprimary = 'f'\n AND t.relname = '\#{table_name}'\n AND i.relnamespace IN (SELECT oid FROM pg_namespace WHERE nspname = ANY (current_schemas(false)) )\n ORDER BY i.relname\n SQL\n\n result.map! do |row|\n index_name = row[0]\n unique = row[1].is_a?(String) ? row[1] == 't' : row[1] # JDBC gets us a boolean\n indkey = row[2].is_a?(Java::OrgPostgresqlUtil::PGobject) ? row[2].value : row[2]\n indkey = indkey.split(\" \")\n inddef = row[3]\n oid = row[4]\n\n columns = select_rows(<<-SQL, \"SCHEMA\")\n SELECT a.attnum, a.attname\n FROM pg_attribute a\n WHERE a.attrelid = \#{oid}\n AND a.attnum IN (\#{indkey.join(\",\")})\n SQL\n\n columns = Hash[ columns.each { |column| column[0] = column[0].to_s } ]\n column_names = columns.values_at(*indkey).compact\n\n unless column_names.empty?\n # add info on sort order for columns (only desc order is explicitly specified, asc is the default)\n desc_order_columns = inddef.scan(/(\\w+) DESC/).flatten\n orders = desc_order_columns.any? ? Hash[ desc_order_columns.map { |column| [column, :desc] } ] : {}\n\n if ActiveRecord::VERSION::MAJOR > 3 # AR4 supports `where` and `using` index options\n where = inddef.scan(/WHERE (.+)$/).flatten[0]\n using = inddef.scan(/USING (.+?) /).flatten[0].to_sym\n\n IndexDefinition.new(table_name, index_name, unique, column_names, [], orders, where, nil, using)\n else\n IndexDefinition.new(table_name, index_name, unique, column_names, [], orders)\n end\n end\n end\n result.compact!\n result\nend\n", 'SCHEMA') |
#insert_sql(sql, name = nil, pk = nil, id_value = nil, sequence_name = nil, binds = []) ⇒ Object
488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 488 def insert_sql(sql, name = nil, pk = nil, id_value = nil, sequence_name = nil, binds = []) unless pk # Extract the table from the insert sql. Yuck. table_ref = extract_table_ref_from_insert_sql(sql) pk = primary_key(table_ref) if table_ref end if pk && use_insert_returning? # && id_value.nil? select_value("#{to_sql(sql, binds)} RETURNING #{quote_column_name(pk)}") else execute(sql, name, binds) # super unless id_value table_ref ||= extract_table_ref_from_insert_sql(sql) # If neither PK nor sequence name is given, look them up. if table_ref && ! ( pk ||= primary_key(table_ref) ) && ! sequence_name pk, sequence_name = pk_and_sequence_for(table_ref) end # If a PK is given, fallback to default sequence name. # Don't fetch last insert id for a table without a PK. if pk && sequence_name ||= default_sequence_name(table_ref, pk) id_value = last_insert_id(table_ref, sequence_name) end end id_value end end |
#last_insert_id(table, sequence_name = nil) ⇒ Object
631 632 633 634 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 631 def last_insert_id(table, sequence_name = nil) sequence_name = table if sequence_name.nil? # AR-4.0 1 argument last_insert_id_result(sequence_name) end |
#last_insert_id_result(sequence_name) ⇒ Object
636 637 638 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 636 def last_insert_id_result(sequence_name) select_value("SELECT currval('#{sequence_name}')", 'SQL') end |
#last_inserted_id(result) ⇒ Integer, NilClass
Take an id from the result of an INSERT query.
623 624 625 626 627 628 629 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 623 def last_inserted_id(result) return nil if result.nil? return result if result.is_a? Integer # <ActiveRecord::Result @hash_rows=nil, @columns=["id"], @rows=[[3]]> # but it will work with [{ 'id' => 1 }] Hash wrapped results as well result.first.first[1] # .first = { "id"=>1 } .first = [ "id", 1 ] end |
#migration_keys ⇒ Object
Adds :array as a valid migration key.
250 251 252 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 250 def migration_keys super + [:array] end |
#multi_column_index_limit ⇒ Object
Gets the maximum number columns postgres has, default 32
741 742 743 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 741 def multi_column_index_limit defined?(@multi_column_index_limit) && @multi_column_index_limit || 32 end |
#multi_column_index_limit=(limit) ⇒ Object
Sets the maximum number columns postgres has, default 32
746 747 748 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 746 def multi_column_index_limit=(limit) @multi_column_index_limit = limit end |
#native_database_types ⇒ Object
238 239 240 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 238 def native_database_types NATIVE_DATABASE_TYPES end |
#pk_and_sequence_for(table) ⇒ Object
Find a table's primary key and sequence.
430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 430 def pk_and_sequence_for(table) # try looking for a seq with a dependency on the table's primary key : result = select(" SELECT attr.attname, seq.relname\n FROM pg_class seq,\n pg_attribute attr,\n pg_depend dep,\n pg_constraint cons\n WHERE seq.oid = dep.objid\n AND seq.relkind = 'S'\n AND attr.attrelid = dep.refobjid\n AND attr.attnum = dep.refobjsubid\n AND attr.attrelid = cons.conrelid\n AND attr.attnum = cons.conkey[1]\n AND cons.contype = 'p'\n AND dep.refobjid = '\#{quote_table_name(table)}'::regclass\n end_sql\n\n if result.nil? || result.empty?\n # if that fails, try parsing the primary key's default value :\n result = select(<<-end_sql, 'PK and Custom Sequence')[0]\n SELECT attr.attname,\n CASE\n WHEN pg_get_expr(def.adbin, def.adrelid) !~* 'nextval' THEN NULL\n WHEN split_part(pg_get_expr(def.adbin, def.adrelid), '''', 2) ~ '.' THEN\n substr(split_part(pg_get_expr(def.adbin, def.adrelid), '''', 2),\n strpos(split_part(pg_get_expr(def.adbin, def.adrelid), '''', 2), '.')+1)\n ELSE split_part(pg_get_expr(def.adbin, def.adrelid), '''', 2)\n END as relname\n FROM pg_class t\n JOIN pg_attribute attr ON (t.oid = attrelid)\n JOIN pg_attrdef def ON (adrelid = attrelid AND adnum = attnum)\n JOIN pg_constraint cons ON (conrelid = adrelid AND adnum = conkey[1])\n WHERE t.oid = '\#{quote_table_name(table)}'::regclass\n AND cons.contype = 'p'\n AND pg_get_expr(def.adbin, def.adrelid) ~* 'nextval|uuid_generate'\n end_sql\n end\n\n [ result['attname'], result['relname'] ]\nrescue\n nil\nend\n", 'PK and Serial Sequence')[0] |
#postgresql_version ⇒ Object
48 49 50 51 52 53 54 55 56 57 58 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 48 def postgresql_version @postgresql_version ||= begin value = select_value('SELECT version()') if value =~ /PostgreSQL (\d+)\.(\d+)\.(\d+)/ ($1.to_i * 10000) + ($2.to_i * 100) + $3.to_i else 0 end end end |
#prepare_column_options(column, types) ⇒ Object
Adds :array option to the default set provided by the AbstractAdapter.
243 244 245 246 247 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 243 def (column, types) spec = super spec[:array] = 'true' if column.respond_to?(:array) && column.array spec end |
#primary_key(table) ⇒ Object
474 475 476 477 478 479 480 481 482 483 484 485 486 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 474 def primary_key(table) result = select(" SELECT attr.attname\n FROM pg_attribute attr\n INNER JOIN pg_constraint cons ON attr.attrelid = cons.conrelid AND attr.attnum = cons.conkey[1]\n WHERE cons.contype = 'p'\n AND cons.conrelid = '\#{quote_table_name(table)}'::regclass\n end_sql\n\n result && result['attname']\n # pk_and_sequence = pk_and_sequence_for(table)\n # pk_and_sequence && pk_and_sequence.first\nend\n", 'SCHEMA').first |
#quote(value, column = nil) ⇒ String
791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 791 def quote(value, column = nil) return super unless column return value if sql_literal?(value) case value when Float if value.infinite? && ( column.type == :datetime || column.type == :timestamp ) "'#{value.to_s.downcase}'" elsif value.infinite? || value.nan? "'#{value.to_s}'" else super end when Numeric if column.respond_to?(:sql_type) && column.sql_type == 'money' # not truly string input, so doesn't require (or allow) escape syntax : ( column.type == :string || column.type == :text ) ? "'#{value}'" : super else super end when String return "E'#{escape_bytea(value)}'::bytea" if column.type == :binary return "xml '#{quote_string(value)}'" if column.type == :xml if column.respond_to?(:sql_type) && column.sql_type[0, 3] == 'bit' quote_bit(value) else super end when Array if AR4_COMPAT && column.array? # will be always falsy in AR < 4.0 column_class = ::ActiveRecord::ConnectionAdapters::PostgreSQLColumn "'#{column_class.array_to_string(value, column, self).gsub(/'/, "''")}'" else super end when Hash if column.type == :hstore # only in AR-4.0 column_class = ::ActiveRecord::ConnectionAdapters::PostgreSQLColumn super(column_class.hstore_to_string(value), column) elsif column.type == :json # only in AR-4.0 column_class = ::ActiveRecord::ConnectionAdapters::PostgreSQLColumn super(column_class.json_to_string(value), column) else super end when Range if column.type.to_s[-5..-1] == 'range' # :'xxxrange' only in AR-4.0 column_class = ::ActiveRecord::ConnectionAdapters::PostgreSQLColumn "'#{column_class.range_to_string(value)}'::#{column.sql_type}" else super end when IPAddr if column.type == :inet || column.type == :cidr # only in AR-4.0 column_class = ::ActiveRecord::ConnectionAdapters::PostgreSQLColumn super(column_class.cidr_to_string(value), column) else super end else super end end |
#quote_bit(value) ⇒ String
860 861 862 863 864 865 866 867 868 869 870 871 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 860 def quote_bit(value) case value # NOTE: as reported with #60 this is not quite "right" : # "0103" will be treated as hexadecimal string # "0102" will be treated as hexadecimal string # "0101" will be treated as binary string # "0100" will be treated as binary string # ... but is kept due Rails compatibility when /^[01]*$/ then "B'#{value}'" # Bit-string notation when /^[0-9A-F]*$/i then "X'#{value}'" # Hexadecimal notation end end |
#quote_column_name(name) ⇒ Object
907 908 909 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 907 def quote_column_name(name) %("#{name.to_s.gsub("\"", "\"\"")}") end |
#quote_string(string) ⇒ String
Quotes a string, escaping any ' (single quote) and \ (backslash) chars.
851 852 853 854 855 856 857 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 851 def quote_string(string) quoted = string.gsub("'", "''") unless standard_conforming_strings? quoted.gsub!(/\\/, '\&\&') end quoted end |
#quote_table_name(name) ⇒ Object
890 891 892 893 894 895 896 897 898 899 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 890 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 |
#quote_table_name_for_assignment(table, attr) ⇒ Object
902 903 904 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 902 def quote_table_name_for_assignment(table, attr) quote_column_name(attr) end |
#quoted_date(value) ⇒ Object
Quote date/time values for use in SQL input.
Includes microseconds if the value is a Time responding to usec.
914 915 916 917 918 919 920 921 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 914 def quoted_date(value) result = super if value.acts_like?(:time) && value.respond_to?(:usec) result = "#{result}.#{sprintf("%06d", value.usec)}" end result = "#{result.sub(/^-/, '')} BC" if value.year < 0 result end |
#recreate_database(name, options = {}) ⇒ Object
640 641 642 643 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 640 def recreate_database(name, = {}) drop_database(name) create_database(name, ) end |
#release_savepoint(name = current_savepoint_name) ⇒ Object
357 358 359 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 357 def release_savepoint(name = current_savepoint_name) log("RELEASE SAVEPOINT #{name}", 'Savepoint') { super } end |
#remove_index!(table_name, index_name) ⇒ Object
1024 1025 1026 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 1024 def remove_index!(table_name, index_name) execute "DROP INDEX #{quote_table_name(index_name)}" end |
#rename_column(table_name, column_name, new_column_name) ⇒ Object
unless const_defined? :SchemaCreation
1014 1015 1016 1017 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 1014 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)}" rename_column_indexes(table_name, column_name, new_column_name) if respond_to?(:rename_column_indexes) # AR-4.0 SchemaStatements end |
#rename_table(table_name, new_name) ⇒ Object
947 948 949 950 951 952 953 954 955 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 947 def rename_table(table_name, new_name) execute "ALTER TABLE #{quote_table_name(table_name)} RENAME TO #{quote_table_name(new_name)}" pk, seq = pk_and_sequence_for(new_name) if seq == "#{table_name}_#{pk}_seq" new_seq = "#{new_name}_#{pk}_seq" execute "ALTER TABLE #{quote_table_name(seq)} RENAME TO #{quote_table_name(new_seq)}" end rename_table_indexes(table_name, new_name) if respond_to?(:rename_table_indexes) # AR-4.0 SchemaStatements end |
#reset_pk_sequence!(table, pk = nil, sequence = nil) ⇒ Object
Resets sequence to the max value of the table's primary key if present.
415 416 417 418 419 420 421 422 423 424 425 426 427 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 415 def reset_pk_sequence!(table, pk = nil, sequence = nil) if ! pk || ! sequence default_pk, default_sequence = pk_and_sequence_for(table) pk ||= default_pk; sequence ||= default_sequence end if pk && sequence quoted_sequence = quote_column_name(sequence) select_value " SELECT setval('\#{quoted_sequence}', (SELECT COALESCE(MAX(\#{quote_column_name pk})+(SELECT increment_by FROM \#{quoted_sequence}), (SELECT min_value FROM \#{quoted_sequence})) FROM \#{quote_table_name(table)}), false)\n end_sql\n end\nend\n", 'Reset Sequence' |
#rollback_to_savepoint(name = current_savepoint_name) ⇒ Object
352 353 354 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 352 def rollback_to_savepoint(name = current_savepoint_name) log("ROLLBACK TO SAVEPOINT #{name}", 'Savepoint') { super } end |
#schema_creation ⇒ Object
37 38 39 |
# File 'lib/arjdbc/postgresql/schema_creation.rb', line 37 def schema_creation SchemaCreation.new self end |
#schema_exists?(name) ⇒ Boolean
Returns true if schema exists.
565 566 567 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 565 def schema_exists?(name) select_value("SELECT COUNT(*) FROM pg_namespace WHERE nspname = '#{name}'", 'SCHEMA').to_i > 0 end |
#schema_names ⇒ Object
Returns an array of schema names.
556 557 558 559 560 561 562 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 556 def schema_names select_values( "SELECT nspname FROM pg_namespace" << " WHERE nspname !~ '^pg_.*' AND nspname NOT IN ('information_schema')" << " ORDER by nspname;", 'SCHEMA') end |
#schema_search_path ⇒ Object
Returns the active schema search path.
605 606 607 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 605 def schema_search_path @schema_search_path ||= select_value('SHOW search_path', 'SCHEMA') end |
#schema_search_path=(schema_csv) ⇒ Object
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: http://www.postgresql.org/docs/current/static/ddl-schemas.html
This should be not be called manually but set in database.yml.
614 615 616 617 618 619 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 614 def schema_search_path=(schema_csv) if schema_csv execute "SET search_path TO #{schema_csv}" @schema_search_path = schema_csv end end |
#session_auth=(user) ⇒ Object
Set the authorized user for this session.
395 396 397 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 395 def session_auth=(user) execute "SET SESSION AUTHORIZATION #{user}" end |
#set_client_encoding(encoding) ⇒ Object
67 68 69 70 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 67 def set_client_encoding(encoding) ActiveRecord::Base.logger.warn "client_encoding is set by the driver and should not be altered, ('#{encoding}' ignored)" ActiveRecord::Base.logger.debug "Set the 'allowEncodingChanges' driver property (e.g. using config[:properties]) if you need to override the client encoding when doing a copy." end |
#set_standard_conforming_strings ⇒ Object
Enable standard-conforming strings if available.
255 256 257 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 255 def set_standard_conforming_strings self.standard_conforming_strings=(true) end |
#sql_for_insert(sql, pk, id_value, sequence_name, binds) ⇒ Object
516 517 518 519 520 521 522 523 524 525 526 527 528 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 516 def sql_for_insert(sql, pk, id_value, sequence_name, binds) unless pk # Extract the table from the insert sql. Yuck. table_ref = extract_table_ref_from_insert_sql(sql) pk = primary_key(table_ref) if table_ref end if pk && use_insert_returning? sql = "#{sql} RETURNING #{quote_column_name(pk)}" end [ sql, binds ] end |
#standard_conforming_strings=(enable) ⇒ Object
Enable standard-conforming strings if available.
260 261 262 263 264 265 266 267 268 269 270 271 272 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 260 def standard_conforming_strings=(enable) = self. begin self. = 'panic' value = enable ? "on" : "off" execute("SET standard_conforming_strings = #{value}", 'SCHEMA') @standard_conforming_strings = ( value == "on" ) rescue @standard_conforming_strings = :unsupported ensure self. = end end |
#standard_conforming_strings? ⇒ Boolean
274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 274 def standard_conforming_strings? if @standard_conforming_strings.nil? = self. begin self. = 'panic' value = select_one('SHOW standard_conforming_strings', 'SCHEMA')['standard_conforming_strings'] @standard_conforming_strings = ( value == "on" ) rescue @standard_conforming_strings = :unsupported ensure self. = end end @standard_conforming_strings == true # return false if :unsupported end |
#structure_dump ⇒ Object
no longer used - handled with (AR built-in) Rake tasks
703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 703 def structure_dump database = @config[:database] if database.nil? if @config[:url] =~ /\/([^\/]*)$/ database = $1 else raise "Could not figure out what database this url is for #{@config["url"]}" end end ENV['PGHOST'] = @config[:host] if @config[:host] ENV['PGPORT'] = @config[:port].to_s if @config[:port] ENV['PGPASSWORD'] = @config[:password].to_s if @config[:password] search_path = "--schema=#{@config[:schema_search_path]}" if @config[:schema_search_path] @connection.connection.close begin definition = `pg_dump -i -U "#{@config[:username]}" -s -x -O #{search_path} #{database}` raise "Error dumping database" if $?.exitstatus == 1 # need to patch away any references to SQL_ASCII as it breaks the JDBC driver definition.gsub(/SQL_ASCII/, 'UNICODE') ensure reconnect! end end |
#supports_ddl_transactions? ⇒ Boolean
314 315 316 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 314 def supports_ddl_transactions? true end |
#supports_disable_referential_integrity? ⇒ Boolean
924 925 926 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 924 def supports_disable_referential_integrity? true end |
#supports_extensions? ⇒ Boolean
361 362 363 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 361 def supports_extensions? postgresql_version >= 90200 end |
#supports_hex_escaped_bytea? ⇒ Boolean
306 307 308 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 306 def supports_hex_escaped_bytea? postgresql_version >= 90000 end |
#supports_index_sort_order? ⇒ Boolean
322 323 324 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 322 def supports_index_sort_order? true end |
#supports_insert_with_returning? ⇒ Boolean
310 311 312 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 310 def supports_insert_with_returning? postgresql_version >= 80200 end |
#supports_migrations? ⇒ Boolean
Does PostgreSQL support migrations?
291 292 293 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 291 def supports_migrations? true end |
#supports_partial_index? ⇒ Boolean
326 327 328 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 326 def supports_partial_index? true end |
#supports_primary_key? ⇒ Boolean
Does PostgreSQL support finding primary key on non-Active Record tables?
296 297 298 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 296 def supports_primary_key? true end |
#supports_ranges? ⇒ Boolean
Range data-types weren't introduced until PostgreSQL 9.2.
331 332 333 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 331 def supports_ranges? postgresql_version >= 90200 end |
#supports_savepoints? ⇒ Boolean
342 343 344 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 342 def supports_savepoints? true end |
#supports_standard_conforming_strings? ⇒ Boolean
Does PostgreSQL support standard conforming strings?
301 302 303 304 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 301 def supports_standard_conforming_strings? standard_conforming_strings? @standard_conforming_strings != :unsupported end |
#supports_transaction_isolation?(level = nil) ⇒ Boolean
318 319 320 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 318 def supports_transaction_isolation? true end |
#table_alias_length ⇒ Object
Returns the configured supported identifier length supported by PostgreSQL, or report the default of 63 on PostgreSQL 7.x.
401 402 403 404 405 406 407 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 401 def table_alias_length @table_alias_length ||= ( postgresql_version >= 80000 ? select_one('SHOW max_identifier_length')['max_identifier_length'].to_i : 63 ) end |
#table_exists?(name) ⇒ Boolean
1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 1081 def table_exists?(name) schema, table = extract_schema_and_table(name.to_s) return false unless table # abstract classes - nil table name binds = [[ nil, table.gsub(/(^"|"$)/,'') ]] binds << [ nil, schema ] if schema sql = " SELECT COUNT(*) as table_count\n FROM pg_tables\n WHERE tablename = ?\n AND schemaname = \#{schema ? \"?\" : \"ANY (current_schemas(false))\"}\n SQL\n\n log(sql, 'SCHEMA', binds) do\n @connection.execute_query_raw(sql, binds).first[\"table_count\"] > 0\n end\nend\n" |
#tables(name = nil) ⇒ Object
1073 1074 1075 1076 1077 1078 1079 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 1073 def tables(name = nil) select_values(" SELECT tablename\n FROM pg_tables\n WHERE schemaname = ANY (current_schemas(false))\n SQL\nend\n", 'SCHEMA') |
#type_cast(value, column, array_member = false) ⇒ Object
149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 149 def type_cast(value, column, array_member = false) return super unless column case value when String return super(value, column) unless 'bytea' == column.sql_type value # { :value => value, :format => 1 } when Array case column.sql_type when 'point' column_class = ::ActiveRecord::ConnectionAdapters::PostgreSQLColumn column_class.point_to_string(value) else return super(value, column) unless column.array? column_class = ::ActiveRecord::ConnectionAdapters::PostgreSQLColumn column_class.array_to_string(value, column, self) end when NilClass if column.array? && array_member 'NULL' elsif column.array? value else super(value, column) end when Hash case column.sql_type when 'hstore' column_class = ::ActiveRecord::ConnectionAdapters::PostgreSQLColumn column_class.hstore_to_string(value) when 'json' column_class = ::ActiveRecord::ConnectionAdapters::PostgreSQLColumn column_class.json_to_string(value) else super(value, column) end when IPAddr return super unless column.sql_type == 'inet' || column.sql_type == 'cidr' column_class = ::ActiveRecord::ConnectionAdapters::PostgreSQLColumn column_class.cidr_to_string(value) when Range return super(value, column) unless /range$/ =~ column.sql_type column_class = ::ActiveRecord::ConnectionAdapters::PostgreSQLColumn column_class.range_to_string(value) else super(value, column) end end |
#type_to_sql(type, limit = nil, precision = nil, scale = nil) ⇒ Object
Maps logical Rails types to PostgreSQL-specific data types.
112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 112 def type_to_sql(type, limit = nil, precision = nil, scale = nil) case type.to_sym when :'binary' # PostgreSQL doesn't support limits on binary (bytea) columns. # The hard limit is 1Gb, because of a 32-bit size field, and TOAST. case limit when nil, 0..0x3fffffff; super(type, nil, nil, nil) else raise(ActiveRecordError, "No binary type has byte size #{limit}.") end when :'text' # PostgreSQL doesn't support limits on text columns. # The hard limit is 1Gb, according to section 8.3 in the manual. case limit when nil, 0..0x3fffffff; super(type, nil, nil, nil) else raise(ActiveRecordError, "The limit on text can be at most 1GB - 1byte.") end when :'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 when :'datetime' return super unless precision case precision when 0..6; "timestamp(#{precision})" else raise(ActiveRecordError, "No timestamp type has precision of #{precision}. The allowed range of precision is from 0 to 6") end else super end end |
#use_insert_returning? ⇒ Boolean
60 61 62 63 64 65 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 60 def use_insert_returning? if ( @use_insert_returning ||= nil ).nil? @use_insert_returning = supports_insert_with_returning? end @use_insert_returning end |