v7.0.0
更多資訊請前往 rubyonrails.org: 更多在 Ruby on Rails

Active Record 和 PostgreSQL

本指南涵蓋了 Active Record 的 PostgreSQL 特定用法。

閱讀本指南後,您將瞭解:

為了使用 PostgreSQL 介面卡,您至少需要 9.3 版 安裝。不支援舊版本。

要開始使用 PostgreSQL,請檢視 配置 Rails 指南。 它描述瞭如何為 PostgreSQL 正確設定 Active Record。

1 資料型別

PostgreSQL 提供了許多特定的資料型別。以下是型別列表, PostgreSQL 介面卡支援的。

1.1 位元組

# db/migrate/20140207133952_create_documents.rb
create_table :documents do |t|
  t.binary 'payload'
end
# app/models/document.rb
class Document < ApplicationRecord
end
 用法
data = File.read(Rails.root + "tmp/output.pdf")
Document.create payload: data

1.2 陣列

# db/migrate/20140207133952_create_books.rb
create_table :books do |t|
  t.string 'title'
  t.string 'tags', array: true
  t.integer 'ratings', array: true
end
add_index :books, :tags, using: 'gin'
add_index :books, :ratings, using: 'gin'
# app/models/book.rb
class Book < ApplicationRecord
end
 用法
Book.create title: "Brave New World",
            tags: ["fantasy", "fiction"],
            ratings: [4, 5]

## 單個標籤的書籍
Book.where("'fantasy' = ANY (tags)")

## 多個標籤的書籍
Book.where("tags @> ARRAY[?]::varchar[]", ["fantasy", "fiction"])

## 3 個或更多評分的書籍
Book.where("array_length(ratings, 1) >= 3")

1.3 Hstore

您需要啟用 hstore 擴展才能使用 hstore。

# db/migrate/20131009135255_create_profiles.rb
ActiveRecord::Schema.define do
  enable_extension 'hstore' unless extension_enabled?('hstore')
  create_table :profiles do |t|
    t.hstore 'settings'
  end
end
# app/models/profile.rb
class Profile < ApplicationRecord
end
irb> Profile.create(settings: { "color" => "blue", "resolution" => "800x600" })

irb> profile = Profile.first
irb> profile.settings
=> {"color"=>"blue", "resolution"=>"800x600"}

irb> profile.settings = {"color" => "yellow", "resolution" => "1280x1024"}
irb> profile.save!

irb> Profile.where("settings->'color' = ?", "yellow")
=> #<ActiveRecord::Relation [#<Profile id: 1, settings: {"color"=>"yellow", "resolution"=>"1280x1024"}>]>

1.4 JSON 和 JSONB

# db/migrate/20131220144913_create_events.rb
# ... 對於 json 資料型別:
create_table :events do |t|
  t.json 'payload'
end
# ... 或者對於 jsonb 資料型別:
create_table :events do |t|
  t.jsonb 'payload'
end
# app/models/event.rb
class Event < ApplicationRecord
end
irb> Event.create(payload: { kind: "user_renamed", change: ["jack", "john"]})

irb> event = Event.first
irb> event.payload
=> {"kind"=>"user_renamed", "change"=>["jack", "john"]}

## 基於 JSON 文件的查詢
# -> 運算子返回原始 JSON 型別(可能是一個物件),而 ->> 返回文字
irb> Event.where("payload->>'kind' = ?", "user_renamed")

1.5 範圍型別

此型別對映到 Ruby Range 物件。

# db/migrate/2013092306540​​4_create_events.rb
create_table :events do |t|
  t.daterange 'duration'
end
# app/models/event.rb
class Event < ApplicationRecord
end
irb> Event.create(duration: Date.new(2014, 2, 11)..Date.new(2014, 2, 12))

irb> event = Event.first
irb> event.duration
=> Tue, 11 Feb 2014...Thu, 13 Feb 2014

## 給定日期的所有事件
irb> Event.where("duration @> ?::date", Date.new(2014, 2, 12))

## 使用範圍邊界
irb> event = Event.select("lower(duration) AS starts_at").select("upper(duration) AS ends_at").first

irb> event.starts_at
=> Tue, 11 Feb 2014
irb> event.ends_at
=> Thu, 13 Feb 2014

1.6 複合型別

目前沒有對複合型別的特殊支援。它們被對映到 普通文字列:

CREATE TYPE full_address AS
(
  city VARCHAR(90),
  street VARCHAR(90)
);
# db/migrate/20140207133952_create_contacts.rb
execute <<-SQL
  CREATE TYPE full_address AS
  (
    city VARCHAR(90),
    street VARCHAR(90)
  );
SQL
create_table :contacts do |t|
  t.column :address, :full_address
end
# app/models/contact.rb
class Contact < ApplicationRecord
end
irb> Contact.create address: "(Paris,Champs-Élysées)"
irb> contact = Contact.first
irb> contact.address
=> "(Paris,Champs-Élysées)"
irb> contact.address = "(Paris,Rue Basse)"
irb> contact.save!

1.7 列舉型別

目前沒有對列舉型別的特殊支援。它們被對映為 普通文字列:

# db/migrate/20131220144913_create_articles.rb
def up
  execute <<-SQL
    CREATE TYPE article_status AS ENUM ('draft', 'published');
  SQL
  create_table :articles do |t|
    t.column :status, :article_status
  end
end

# NOTE:在刪除列舉之前刪除表很重要。
def down
  drop_table :articles

  execute <<-SQL
    DROP TYPE article_status;
  SQL
end
# app/models/article.rb
class Article < ApplicationRecord
end
irb> Article.create status: "draft"
irb> article = Article.first
irb> article.status
=> "draft"

irb> article.status = "published"
irb> article.save!

要在現有的之前/之後新增新的 value,您應該使用 ALTER TYPE

# db/migrate/20150720144913_add_new_state_to_articles.rb
# NOTE:ALTER TYPE ... ADD VALUE 不能在 transaction 塊內執行,所以這裡我們使用 disable_ddl_transaction!
disable_ddl_transaction!

def up
  execute <<-SQL
    ALTER TYPE article_status ADD VALUE IF NOT EXISTS 'archived' AFTER 'published';
  SQL
end

當前無法刪除 ENUM values。您可以閱讀原因 此處

提示:要顯示您擁有的所有列舉的所有 values,您應該在 bin/rails dbpsql 控制檯中呼叫此查詢:

SELECT n.nspname AS enum_schema,
       t.typname AS enum_name,
       e.enumlabel AS enum_value
  FROM pg_type t
      JOIN pg_enum e ON t.oid = e.enumtypid
      JOIN pg_catalog.pg_namespace n ON n.oid = t.typnamespace

1.8 UUID

您需要啟用 pgcrypto(僅限 PostgreSQL >= 9.4)或 uuid-ossp 使用 uuid 的擴充套件。

# db/migrate/20131220144913_create_revisions.rb
create_table :revisions do |t|
  t.uuid :identifier
end
# app/models/revision.rb
class Revision < ApplicationRecord
end
irb> Revision.create identifier: "A0EEBC99-9C0B-4EF8-BB6D-6BB9BD380A11"

irb> revision = Revision.first
irb> revision.identifier
=> "a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11"

您可以使用 uuid 型別在 migrations 中定義引用:

# db/migrate/20150418012400_create_blog.rb
enable_extension 'pgcrypto' unless extension_enabled?('pgcrypto')
create_table :posts, id: :uuid

create_table :comments, id: :uuid do |t|
  # t.belongs_to :post, type: :uuid
  t.references :post, type: :uuid
end
# app/models/post.rb
class Post < ApplicationRecord
  has_many :comments
end
# app/models/comment.rb
class Comment < ApplicationRecord
  belongs_to :post
end

有關使用 UUID 作為主鍵的更多詳細資訊,請參閱 本節

1.9 位串型別

# db/migrate/20131220144913_create_users.rb
create_table :users, force: true do |t|
  t.column :settings, "bit(8)"
end
# app/models/user.rb
class User < ApplicationRecord
end
irb> User.create settings: "01010011"
irb> user = User.first
irb> user.settings
=> "01010011"
irb> user.settings = "0xAF"
irb> user.settings
=> 10101111
irb> user.save!

1.10 網路地址型別

型別 inetcidr 對映到 Ruby IPAddr 物件。 macaddr 型別對映到普通文字。

# db/migrate/20140508144913_create_devices.rb
create_table(:devices, force: true) do |t|
  t.inet 'ip'
  t.cidr 'network'
  t.macaddr 'address'
end
# app/models/device.rb
class Device < ApplicationRecord
end
irb> macbook = Device.create(ip: "192.168.1.12", network: "192.168.2.0/24", address: "32:01:16:6d:05:ef")

irb> macbook.ip
=> #<IPAddr: IPv4:192.168.1.12/255.255.255.255>

irb> macbook.network
=> #<IPAddr: IPv4:192.168.2.0/255.255.255.0>

irb> macbook.address
=> "32:01:16:6d:05:ef"

1.11 幾何型別

points 之外的所有幾何型別都對映到普通文字。 一個點被投射到一個包含 xy 座標的陣列。

1.12 間隔

此型別對映到 ActiveSupport::Duration 物件。

# db/migrate/20200120000000_create_events.rb
create_table :events do |t|
  t.interval 'duration'
end
# app/models/event.rb
class Event < ApplicationRecord
end
irb> Event.create(duration: 2.days)

irb> event = Event.first
irb> event.duration
=> 2 days

2 UUID 主 Keys

您需要啟用 pgcrypto(僅限 PostgreSQL >= 9.4)或 uuid-ossp 擴充套件以生成隨機 UUID。

# db/migrate/20131220144913_create_devices.rb
enable_extension 'pgcrypto' unless extension_enabled?('pgcrypto')
create_table :devices, id: :uuid do |t|
  t.string :kind
end
# app/models/device.rb
class Device < ApplicationRecord
end
irb> device = Device.create
irb> device.id
=> "814865cd-5a1d-4771-9306-4268f188fe9e"

如果沒有 :default 選項,則假定為 gen_random_uuid()(來自 pgcrypto) 傳遞給 create_table

3 全文檢索

# db/migrate/20131220144913_create_documents.rb
create_table :documents do |t|
  t.string 'title'
  t.string 'body'
end

add_index :documents, "to_tsvector('english', title || ' ' || body)", using: :gin, name: 'documents_idx'
# app/models/document.rb
class Document < ApplicationRecord
end
 用法
Document.create(title: "Cats and Dogs", body: "are nice!")

## 匹配“cat & dog”的所有文件
Document.where("to_tsvector('english', title || ' ' || body) @@ to_tsquery(?)",
                 "cat & dog")

4 資料庫 Views

想象一下,您需要使用包含下表的舊資料庫:

rails_pg_guide=# \d "TBL_ART"
                                        Table "public.TBL_ART"
   Column   |            Type             |                         Modifiers
------------+-----------------------------+------------------------------------------------------------
 INT_ID     | integer                     | not null default nextval('"TBL_ART_INT_ID_seq"'::regclass)
 STR_TITLE  | character varying           |
 STR_STAT   | character varying           | default 'draft'::character varying
 DT_PUBL_AT | timestamp without time zone |
 BL_ARCH    | boolean                     | default false
Indexes:
    "TBL_ART_pkey" PRIMARY KEY, btree ("INT_ID")

該表完全不遵循 Rails 約定。 因為簡單的 PostgreSQL views 預設是可更新的, 我們可以按如下方式包裝它:

# db/migrate/20131220144913_create_articles_view.rb
execute <<-SQL
CREATE VIEW articles AS
  SELECT "INT_ID" AS id,
         "STR_TITLE" AS title,
         "STR_STAT" AS status,
         "DT_PUBL_AT" AS published_at,
         "BL_ARCH" AS archived
  FROM "TBL_ART"
  WHERE "BL_ARCH" = 'f'
  SQL
# app/models/article.rb
class Article < ApplicationRecord
  self.primary_key = "id"
  def archive!
    update_attribute :archived, true
  end
end
irb> first = Article.create! title: "Winter is coming", status: "published", published_at: 1.year.ago
irb> second = Article.create! title: "Brace yourself", status: "draft", published_at: 1.month.ago

irb> Article.count
=> 2
irb> first.archive!
irb> Article.count
=> 1

此應用程式只關心未歸檔的 Articles。一個 view 也 允許條件,因此我們可以直接排除存檔的 Articles

回饋

我們鼓勵您幫助提高本指南的品質。

如果您發現任何拼寫錯誤或資訊錯誤,請提供回饋。 要開始回饋,您可以閱讀我們的 回饋 部分。

您還可能會發現不完整的內容或不是最新的內容。 請務必為 main 新增任何遺漏的文件。假設是 非穩定版指南(edge guides) 請先驗證問題是否已經在主分支上解決。 請前往 Ruby on Rails 指南寫作準則 查看寫作風格和慣例。

如果由於某種原因您發現要修復的內容但無法自行修補,請您 提出 issue

關於 Ruby on Rails 的任何類型的討論歡迎提供任何文件至 rubyonrails-docs 討論區