Module: ArJdbc::PostgreSQL
- Included in:
- ActiveRecord::ConnectionAdapters::PostgreSQLAdapter
- Defined in:
- lib/arjdbc/postgresql/adapter.rb
Defined Under Namespace
Modules: Column
Constant Summary collapse
- ADAPTER_NAME =
constants taken from postgresql_adapter in rails project
'PostgreSQL'- NATIVE_DATABASE_TYPES =
{ :primary_key => "serial primary key", :string => { :name => "character varying", :limit => 255 }, :text => { :name => "text" }, :integer => { :name => "integer" }, :float => { :name => "float" }, :decimal => { :name => "decimal" }, :datetime => { :name => "timestamp" }, :timestamp => { :name => "timestamp" }, :time => { :name => "time" }, :date => { :name => "date" }, :binary => { :name => "bytea" }, :boolean => { :name => "boolean" }, :xml => { :name => "xml" }, :tsvector => { :name => "tsvector" } }
Class Method Summary collapse
- .arel2_visitors(config) ⇒ Object
- .column_selector ⇒ Object
- .extended(mod) ⇒ Object
- .jdbc_connection_class ⇒ Object
Instance Method Summary collapse
-
#adapter_name ⇒ Object
:nodoc:.
-
#add_column(table_name, column_name, type, options = {}) ⇒ Object
Adds a new column to the named table.
-
#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
- #create_database(name, options = {}) ⇒ Object
- #create_savepoint ⇒ Object
- #create_schema(schema_name, pg_username) ⇒ Object
-
#current_database ⇒ Object
current database name.
- #default_sequence_name(table_name, pk = nil) ⇒ Object
-
#disable_referential_integrity(&block) ⇒ Object
:nodoc:.
-
#distinct(columns, orders) ⇒ Object
SELECT DISTINCT clause for a given set of columns and a given ORDER BY clause.
- #drop_database(name) ⇒ Object
- #drop_schema(schema_name) ⇒ Object
-
#encoding ⇒ Object
current database encoding.
- #escape_bytea(s) ⇒ Object
-
#extract_schema_and_table(name) ⇒ Object
Extracts the table and schema name from
name. - #index_name_length ⇒ Object
-
#indexes(table_name, name = nil) ⇒ Object
Based on postgresql_adapter.rb.
-
#insert_sql(sql, name = nil, pk = nil, id_value = nil, sequence_name = nil, binds = []) ⇒ Object
Insert logic for pre-AR-3.1 adapters.
- #last_insert_id(table, sequence_name) ⇒ Object
-
#last_inserted_id(result) ⇒ Object
take id from result of insert query.
-
#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
- #pg_columns(table_name, name = nil) ⇒ Object
-
#pk_and_sequence_for(table) ⇒ Object
Find a table’s primary key and sequence.
- #postgresql_version ⇒ Object
- #primary_key(table) ⇒ Object
-
#quote(value, column = nil) ⇒ Object
from postgres_adapter.rb in rails project github.com/rails/rails/blob/3-1-stable/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb#L412 Quotes PostgreSQL-specific data types for SQL input.
- #quote_column_name(name) ⇒ Object
- #quote_table_name(name) ⇒ Object
-
#quoted_date(value) ⇒ Object
:nodoc:.
- #recreate_database(name) ⇒ Object
- #release_savepoint ⇒ Object
-
#remove_index!(table_name, index_name) ⇒ Object
:nodoc:.
-
#rename_column(table_name, column_name, new_column_name) ⇒ Object
:nodoc:.
- #rename_table(name, new_name) ⇒ Object
-
#reset_pk_sequence!(table, pk = nil, sequence = nil) ⇒ Object
Resets sequence to the max value of the table’s pk if present.
- #rollback_to_savepoint ⇒ Object
-
#sql_for_insert(sql, pk, id_value, sequence_name, binds) ⇒ Object
taken from rails postgresql adapter github.com/gfmurphy/rails/blob/master/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb#L611.
- #structure_dump ⇒ Object
- #supports_ddl_transactions? ⇒ Boolean
- #supports_insert_with_returning? ⇒ Boolean
-
#supports_migrations? ⇒ Boolean
Does PostgreSQL support migrations?.
- #supports_savepoints? ⇒ Boolean
-
#supports_standard_conforming_strings? ⇒ Boolean
Does PostgreSQL support standard conforming strings?.
-
#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_to_sql(type, limit = nil, precision = nil, scale = nil) ⇒ Object
Maps logical Rails types to PostgreSQL-specific data types.
Class Method Details
.arel2_visitors(config) ⇒ Object
185 186 187 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 185 def self.arel2_visitors(config) {}.tap {|v| %w(postgresql pg jdbcpostgresql).each {|a| v[a] = ::Arel::Visitors::PostgreSQL } } end |
.column_selector ⇒ Object
13 14 15 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 13 def self.column_selector [/postgre/i, lambda {|cfg,col| col.extend(::ArJdbc::PostgreSQL::Column)}] end |
.extended(mod) ⇒ Object
7 8 9 10 11 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 7 def self.extended(mod) (class << mod; self; end).class_eval do alias_chained_method :columns, :query_cache, :pg_columns end end |
.jdbc_connection_class ⇒ Object
17 18 19 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 17 def self.jdbc_connection_class ::ActiveRecord::ConnectionAdapters::PostgresJdbcConnection end |
Instance Method Details
#adapter_name ⇒ Object
:nodoc:
181 182 183 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 181 def adapter_name #:nodoc: 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.
630 631 632 633 634 635 636 637 638 639 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 630 def add_column(table_name, column_name, type, = {}) default = [:default] notnull = [:null] == false # Add the column. 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 () change_column_null(table_name, column_name, false, default) if notnull 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.
545 546 547 548 549 550 551 552 553 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 545 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
490 491 492 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 490 def all_schemas select('select nspname from pg_namespace').map {|r| r["nspname"] } end |
#change_column(table_name, column_name, type, options = {}) ⇒ Object
Changes the column of a table.
642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 642 def change_column(table_name, column_name, type, = {}) 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 # 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 #{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, [: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.
668 669 670 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 668 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
672 673 674 675 676 677 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 672 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 |
#create_database(name, options = {}) ⇒ Object
474 475 476 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 474 def create_database(name, = {}) execute "CREATE DATABASE \"#{name}\" ENCODING='#{options[:encoding] || 'utf8'}'" end |
#create_savepoint ⇒ Object
238 239 240 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 238 def create_savepoint execute("SAVEPOINT #{current_savepoint_name}") end |
#create_schema(schema_name, pg_username) ⇒ Object
482 483 484 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 482 def create_schema(schema_name, pg_username) execute("CREATE SCHEMA \"#{schema_name}\" AUTHORIZATION \"#{pg_username}\"") end |
#current_database ⇒ Object
current database name
392 393 394 395 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 392 def current_database exec_query("select current_database() as database"). first["database"] end |
#default_sequence_name(table_name, pk = nil) ⇒ Object
256 257 258 259 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 256 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_referential_integrity(&block) ⇒ Object
:nodoc:
617 618 619 620 621 622 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 617 def disable_referential_integrity(&block) #:nodoc: execute(tables.collect { |name| "ALTER TABLE #{quote_table_name(name)} DISABLE TRIGGER ALL" }.join(";")) yield ensure execute(tables.collect { |name| "ALTER TABLE #{quote_table_name(name)} ENABLE TRIGGER ALL" }.join(";")) end |
#distinct(columns, orders) ⇒ Object
SELECT DISTINCT clause for a given set of columns and a given ORDER BY clause.
PostgreSQL requires the ORDER BY columns in the select list for distinct queries, and requires that the ORDER BY include the distinct column.
distinct("posts.id", "posts.created_at desc")
528 529 530 531 532 533 534 535 536 537 538 539 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 528 def distinct(columns, orders) #:nodoc: return "DISTINCT #{columns}" if orders.empty? # Construct a clean list of column names from the ORDER BY clause, removing # any ASC/DESC modifiers order_columns = orders.collect { |s| s.gsub(/\s+(ASC|DESC)\s*/i, '') }. reject(&:blank?) order_columns = order_columns. zip((0...order_columns.size).to_a).map { |s,i| "#{s} AS alias_#{i}" } "DISTINCT #{columns}, #{order_columns * ', '}" end |
#drop_database(name) ⇒ Object
478 479 480 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 478 def drop_database(name) execute "DROP DATABASE IF EXISTS \"#{name}\"" end |
#drop_schema(schema_name) ⇒ Object
486 487 488 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 486 def drop_schema(schema_name) execute("DROP SCHEMA \"#{schema_name}\"") end |
#encoding ⇒ Object
current database encoding
398 399 400 401 402 403 404 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 398 def encoding exec_query(" SELECT pg_encoding_to_char(pg_database.encoding) as encoding\n FROM pg_database\n WHERE pg_database.datname LIKE '\#{current_database}'\n end_sql\nend\n").first["encoding"] |
#escape_bytea(s) ⇒ Object
586 587 588 589 590 591 592 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 586 def escape_bytea(s) if s result = '' s.each_byte { |c| result << sprintf('\\\\%03o', c) } result end end |
#extract_schema_and_table(name) ⇒ Object
Extracts the table and schema name from name
728 729 730 731 732 733 734 735 736 737 738 739 740 741 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 728 def extract_schema_and_table(name) schema, table = name.split('.', 2) unless table # A table was provided without a schema table = schema schema = nil end if name =~ /^"/ # Handle quoted table names table = name schema = nil end [schema, table] end |
#index_name_length ⇒ Object
687 688 689 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 687 def index_name_length 63 end |
#indexes(table_name, name = nil) ⇒ Object
Based on postgresql_adapter.rb
417 418 419 420 421 422 423 424 425 426 427 428 429 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 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 417 def indexes(table_name, name = nil) schema_search_path = @config[:schema_search_path] || select_rows('SHOW search_path')[0][0] schemas = schema_search_path.split(/,/).map { |p| quote(p) }.join(',') result = select_rows(" SELECT i.relname, d.indisunique, a.attname, a.attnum, d.indkey\n FROM pg_class t, pg_class i, pg_index d, pg_attribute a,\n generate_series(0,\#{multi_column_index_limit - 1}) AS s(i)\n WHERE i.relkind = 'i'\n AND d.indexrelid = i.oid\n AND d.indisprimary = 'f'\n AND t.oid = d.indrelid\n AND t.relname = '\#{table_name}'\n AND i.relnamespace IN (SELECT oid FROM pg_namespace WHERE nspname IN (\#{schemas}) )\n AND a.attrelid = t.oid\n AND d.indkey[s.i]=a.attnum\n ORDER BY i.relname\n SQL\n\n current_index = nil\n indexes = []\n\n insertion_order = []\n index_order = nil\n\n result.each do |row|\n if current_index != row[0]\n\n (index_order = row[4].split(' ')).each_with_index{ |v, i| index_order[i] = v.to_i }\n indexes << ::ActiveRecord::ConnectionAdapters::IndexDefinition.new(table_name, row[0], row[1] == \"t\", [])\n current_index = row[0]\n end\n insertion_order = row[3]\n ind = index_order.index(insertion_order)\n indexes.last.columns[ind] = row[2]\n end\n\n indexes\nend\n", name) |
#insert_sql(sql, name = nil, pk = nil, id_value = nil, sequence_name = nil, binds = []) ⇒ Object
Insert logic for pre-AR-3.1 adapters
330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 330 def insert_sql(sql, name = nil, pk = nil, id_value = nil, sequence_name = nil, binds = []) # Extract the table from the insert sql. Yuck. table = sql.split(" ", 4)[2].gsub('"', '') # Try an insert with 'returning id' if available (PG >= 8.2) if supports_insert_with_returning? && id_value.nil? pk, sequence_name = *pk_and_sequence_for(table) unless pk if pk sql = substitute_binds(sql, binds) id_value = select_value("#{sql} RETURNING #{quote_column_name(pk)}") clear_query_cache #FIXME: Why now? return id_value end end # Otherwise, plain insert execute(sql, name, binds) # Don't need to look up id_value if we already have it. # (and can't in case of non-sequence PK) unless id_value # If neither pk nor sequence name is given, look them up. unless pk || sequence_name pk, sequence_name = *pk_and_sequence_for(table) 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, pk) id_value = last_insert_id(table, sequence_name) end end id_value end |
#last_insert_id(table, sequence_name) ⇒ Object
465 466 467 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 465 def last_insert_id(table, sequence_name) Integer(select_value("SELECT currval('#{sequence_name}')")) end |
#last_inserted_id(result) ⇒ Object
take id from result of insert query
457 458 459 460 461 462 463 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 457 def last_inserted_id(result) if result.is_a? Fixnum result else result.first.first[1] end end |
#multi_column_index_limit ⇒ Object
Gets the maximum number columns postgres has, default 32
412 413 414 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 412 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
407 408 409 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 407 def multi_column_index_limit=(limit) @multi_column_index_limit = limit end |
#native_database_types ⇒ Object
201 202 203 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 201 def native_database_types NATIVE_DATABASE_TYPES end |
#pg_columns(table_name, name = nil) ⇒ Object
383 384 385 386 387 388 389 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 383 def pg_columns(table_name, name=nil) column_definitions(table_name).map do |row| ::ActiveRecord::ConnectionAdapters::PostgreSQLColumn.new( row["column_name"], row["column_default"], row["column_type"], row["column_not_null"] == "f") end end |
#pk_and_sequence_for(table) ⇒ Object
Find a table’s primary key and sequence.
282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 282 def pk_and_sequence_for(table) #:nodoc: # First try looking for a sequence with a dependency on the # given 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_namespace name,\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? or result.empty?\n # If that fails, try parsing the primary key's default value.\n # Support the 7.x and 8.0 nextval('foo'::text) as well as\n # the 8.1+ nextval('foo'::regclass).\n result = select(<<-end_sql, 'PK and custom sequence')[0]\n SELECT attr.attname,\n CASE\n WHEN split_part(def.adsrc, '''', 2) ~ '.' THEN\n substr(split_part(def.adsrc, '''', 2),\n strpos(split_part(def.adsrc, '''', 2), '.')+1)\n ELSE split_part(def.adsrc, '''', 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 def.adsrc ~* 'nextval'\n end_sql\n end\n\n [result[\"attname\"], result[\"relname\"]]\nrescue\n nil\nend\n", 'PK and serial sequence')[0] |
#postgresql_version ⇒ Object
189 190 191 192 193 194 195 196 197 198 199 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 189 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 |
#primary_key(table) ⇒ Object
365 366 367 368 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 365 def primary_key(table) pk_and_sequence = pk_and_sequence_for(table) pk_and_sequence && pk_and_sequence.first end |
#quote(value, column = nil) ⇒ Object
from postgres_adapter.rb in rails project github.com/rails/rails/blob/3-1-stable/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb#L412 Quotes PostgreSQL-specific data types for SQL input.
558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 558 def quote(value, column = nil) #:nodoc: return super unless column case value when Float return super unless value.infinite? && column.type == :datetime "'#{value.to_s.downcase}'" when Numeric return super unless column.sql_type == 'money' # Not truly string input, so doesn't require (or allow) escape string syntax. "'#{value}'" when String case column.sql_type when 'bytea' then "'#{escape_bytea(value)}'" when 'xml' then "xml '#{quote_string(value)}'" when /^bit/ case value when /^[01]*$/ then "B'#{value}'" # Bit-string notation when /^[0-9A-F]*$/i then "X'#{value}'" # Hexadecimal notation end else super end else super end end |
#quote_column_name(name) ⇒ Object
605 606 607 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 605 def quote_column_name(name) %("#{name.to_s.gsub("\"", "\"\"")}") end |
#quote_table_name(name) ⇒ Object
594 595 596 597 598 599 600 601 602 603 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 594 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 |
#quoted_date(value) ⇒ Object
:nodoc:
609 610 611 612 613 614 615 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 609 def quoted_date(value) #:nodoc: if value.acts_like?(:time) && value.respond_to?(:usec) "#{super}.#{sprintf("%06d", value.usec)}" else super end end |
#recreate_database(name) ⇒ Object
469 470 471 472 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 469 def recreate_database(name) drop_database(name) create_database(name) end |
#release_savepoint ⇒ Object
246 247 248 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 246 def release_savepoint execute("RELEASE SAVEPOINT #{current_savepoint_name}") end |
#remove_index!(table_name, index_name) ⇒ Object
:nodoc:
683 684 685 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 683 def remove_index!(table_name, index_name) #:nodoc: execute "DROP INDEX #{quote_table_name(index_name)}" end |
#rename_column(table_name, column_name, new_column_name) ⇒ Object
:nodoc:
679 680 681 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 679 def rename_column(table_name, column_name, new_column_name) #:nodoc: 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) ⇒ Object
624 625 626 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 624 def rename_table(name, new_name) execute "ALTER TABLE #{name} RENAME TO #{new_name}" end |
#reset_pk_sequence!(table, pk = nil, sequence = nil) ⇒ Object
Resets sequence to the max value of the table’s pk if present.
262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 262 def reset_pk_sequence!(table, pk = nil, sequence = nil) #:nodoc: unless pk and sequence default_pk, default_sequence = pk_and_sequence_for(table) pk ||= default_pk sequence ||= default_sequence end if pk if 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 else\n @logger.warn \"\#{table} has primary key \#{pk} with no default sequence\" if @logger\n end\n end\nend\n", 'Reset sequence' |
#rollback_to_savepoint ⇒ Object
242 243 244 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 242 def rollback_to_savepoint execute("ROLLBACK TO SAVEPOINT #{current_savepoint_name}") end |
#sql_for_insert(sql, pk, id_value, sequence_name, binds) ⇒ Object
taken from rails postgresql adapter github.com/gfmurphy/rails/blob/master/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb#L611
372 373 374 375 376 377 378 379 380 381 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 372 def sql_for_insert(sql, pk, id_value, sequence_name, binds) unless pk table_ref = extract_table_ref_from_insert_sql(sql) pk = primary_key(table_ref) if table_ref end sql = "#{sql} RETURNING #{quote_column_name(pk)}" if pk [sql, binds] end |
#structure_dump ⇒ Object
494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 494 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 = @config[:schema_search_path] search_path = "--schema=#{search_path}" if 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
230 231 232 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 230 def supports_ddl_transactions? true end |
#supports_insert_with_returning? ⇒ Boolean
226 227 228 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 226 def supports_insert_with_returning? postgresql_version >= 80200 end |
#supports_migrations? ⇒ Boolean
Does PostgreSQL support migrations?
206 207 208 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 206 def supports_migrations? true end |
#supports_savepoints? ⇒ Boolean
234 235 236 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 234 def supports_savepoints? true end |
#supports_standard_conforming_strings? ⇒ Boolean
Does PostgreSQL support standard conforming strings?
211 212 213 214 215 216 217 218 219 220 221 222 223 224 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 211 def supports_standard_conforming_strings? # Temporarily set the client message level above error to prevent unintentional # error messages in the logs when working on a PostgreSQL database server that # does not support standard conforming strings. = self. = 'panic' # postgres-pr does not raise an exception when client_min_messages is set higher # than error and "SHOW standard_conforming_strings" fails, but returns an empty # PGresult instead. has_support = select('SHOW standard_conforming_strings').to_a[0][0] rescue false self. = has_support end |
#table_alias_length ⇒ Object
Returns the configured supported identifier length supported by PostgreSQL, or report the default of 63 on PostgreSQL 7.x.
252 253 254 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 252 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
712 713 714 715 716 717 718 719 720 721 722 723 724 725 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 712 def table_exists?(name) schema, table = extract_schema_and_table(name.to_s) return false unless table # Abstract classes is having nil table name binds = [[nil, table.gsub(/(^"|"$)/,'')]] binds << [nil, schema] if schema exec_query(" SELECT COUNT(*) as table_count\n FROM pg_tables\n WHERE tablename = ?\n AND schemaname = \#{schema ? \"?\" : \"ANY (current_schemas(false))\"}\n SQL\nend\n", 'SCHEMA', binds).first["table_count"] > 0 |
#tables(name = nil) ⇒ Object
704 705 706 707 708 709 710 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 704 def tables(name = nil) exec_query(" SELECT tablename\n FROM pg_tables\n WHERE schemaname = ANY (current_schemas(false))\n SQL\nend\n", 'SCHEMA').map { |row| row["tablename"] } |
#type_to_sql(type, limit = nil, precision = nil, scale = nil) ⇒ Object
Maps logical Rails types to PostgreSQL-specific data types.
692 693 694 695 696 697 698 699 700 701 702 |
# File 'lib/arjdbc/postgresql/adapter.rb', line 692 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 |