要使用 PostgreSQL 适配器,您需要安装至少 9.3 版本的 PostgreSQL。不支持旧版本。
要开始使用 PostgreSQL,请查看 配置 Rails 指南。它描述了如何为 PostgreSQL 正确设置 Active Record。
1 数据类型
PostgreSQL 提供了许多特定数据类型。以下是 PostgreSQL 适配器支持的类型列表。
1.1 Bytea
# db/migrate/20140207133952_create_documents.rb
create_table :documents do |t|
t.binary "payload"
end
# app/models/document.rb
class Document < ApplicationRecord
end
# Usage
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
# Usage
Book.create title: "Brave New World",
tags: ["fantasy", "fiction"],
ratings: [4, 5]
## Books for a single tag
Book.where("'fantasy' = ANY (tags)")
## Books for multiple tags
Book.where("tags @> ARRAY[?]::varchar[]", ["fantasy", "fiction"])
## Books with 3 or more ratings
Book.where("array_length(ratings, 1) >= 3")
1.3 Hstore
您需要启用 hstore
扩展才能使用 hstore。
# db/migrate/20131009135255_create_profiles.rb
class CreateProfiles < ActiveRecord::Migration[8.0]
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
# ... for json datatype:
create_table :events do |t|
t.json "payload"
end
# ... or for jsonb datatype:
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"]}
## Query based on JSON document
# The -> operator returns the original JSON type (which might be an object), whereas ->> returns text
irb> Event.where("payload->>'kind' = ?", "user_renamed")
1.5 范围类型
此类型映射到 Ruby Range
对象。
# db/migrate/20130923065404_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
## All Events on a given date
irb> Event.where("duration @> ?::date", Date.new(2014, 2, 12))
## Working with range bounds
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 枚举类型
该类型可以被映射为普通文本列,也可以映射为 ActiveRecord::Enum
。
# db/migrate/20131220144913_create_articles.rb
def change
create_enum :article_status, ["draft", "published", "archived"]
create_table :articles do |t|
t.enum :status, enum_type: :article_status, default: "draft", null: false
end
end
您还可以创建枚举类型并将枚举列添加到现有表中
# db/migrate/20230113024409_add_status_to_articles.rb
def change
create_enum :article_status, ["draft", "published", "archived"]
add_column :articles, :status, :enum, enum_type: :article_status, default: "draft", null: false
end
以上迁移都是可逆的,但如果需要,您可以定义单独的 #up
和 #down
方法。在删除枚举类型之前,确保您删除了任何依赖枚举类型的列或表
def down
drop_table :articles
# OR: remove_column :articles, :status
drop_enum :article_status
end
在模型中声明枚举属性会添加辅助方法,并防止将无效值分配给类的实例
# app/models/article.rb
class Article < ApplicationRecord
enum :status, {
draft: "draft", published: "published", archived: "archived"
}, prefix: true
end
irb> article = Article.create
irb> article.status
=> "draft" # default status from PostgreSQL, as defined in migration above
irb> article.status_published!
irb> article.status
=> "published"
irb> article.status_archived?
=> false
irb> article.status = "deleted"
ArgumentError: 'deleted' is not a valid status
要重命名枚举,您可以使用 rename_enum
,并同时更新模型中所有使用该枚举的地方
# db/migrate/20150718144917_rename_article_status.rb
def change
rename_enum :article_status, :article_state
end
要添加新值,您可以使用 add_enum_value
# db/migrate/20150720144913_add_new_state_to_articles.rb
def up
add_enum_value :article_state, "archived" # will be at the end after published
add_enum_value :article_state, "in review", before: "published"
add_enum_value :article_state, "approved", after: "in review"
add_enum_value :article_state, "rejected", if_not_exists: true # won't raise an error if the value already exists
end
无法删除枚举值,这也意味着 add_enum_value
不可逆。您可以阅读 此处了解原因。
要重命名值,您可以使用 rename_enum_value
# db/migrate/20150722144915_rename_article_state.rb
def change
rename_enum_value :article_state, from: "archived", to: "deleted"
end
提示:要显示所有枚举的所有值,您可以在 bin/rails db
或 psql
控制台中调用此查询
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
如果您使用的是 13.0 之前的 PostgreSQL 版本,则可能需要启用特殊扩展才能使用 UUID。启用 pgcrypto
扩展(PostgreSQL >= 9.4)或 uuid-ossp
扩展(适用于更早的版本)。
# 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
类型在迁移中定义引用
# 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 网络地址类型
类型 inet
和 cidr
被映射到 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
外的所有几何类型都被映射到普通文本。一个点被转换为包含 x
和 y
坐标的数组。
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 主键
您需要启用 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
选项传递给 create_table
,则假定使用 gen_random_uuid()
(来自 pgcrypto
)。
要为使用 UUID 作为主键的表使用 Rails 模型生成器,请将 --primary-key-type=uuid
传递给模型生成器。
例如
$ rails generate model Device --primary-key-type=uuid kind:string
在构建具有引用此 UUID 的外键的模型时,将 uuid
视为本机字段类型,例如
$ rails generate model Case device_id:uuid
3 索引
PostgreSQL 包含各种索引选项。除了 常见索引选项之外,PostgreSQL 适配器还支持以下选项
3.1 包含
在创建新索引时,可以使用 :include
选项包含非主键列。这些键不用于索引扫描以进行搜索,但可以在索引扫描期间读取,而无需访问关联的表。
# db/migrate/20131220144913_add_index_users_on_email_include_id.rb
add_index :users, :email, include: :id
支持多个列
# db/migrate/20131220144913_add_index_users_on_email_include_id_and_created_at.rb
add_index :users, :email, include: [:id, :created_at]
4 生成列
从 PostgreSQL 12.0 版本开始支持生成列。
# db/migrate/20131220144913_create_users.rb
create_table :users do |t|
t.string :name
t.virtual :name_upcased, type: :string, as: "upper(name)", stored: true
end
# app/models/user.rb
class User < ApplicationRecord
end
# Usage
user = User.create(name: "John")
User.last.name_upcased # => "JOHN"
5 可延迟外键
默认情况下,PostgreSQL 中的表约束会在每个语句执行后立即检查。它有意不允许创建引用记录尚未存在的表的记录。但是,可以通过在 foreign key 定义中添加 DEFERRABLE
来在事务提交时运行此完整性检查。要默认延迟所有检查,可以将其设置为 DEFERRABLE INITIALLY DEFERRED
。Rails 通过在 add_reference
和 add_foreign_key
方法中将 :deferrable
键添加到 foreign_key
选项来公开此 PostgreSQL 功能。
一个例子是在事务中创建循环依赖,即使您已经创建了外键
add_reference :person, :alias, foreign_key: { deferrable: :deferred }
add_reference :alias, :person, foreign_key: { deferrable: :deferred }
如果引用是使用 foreign_key: true
选项创建的,则以下事务将在执行第一个 INSERT
语句时失败。但是,如果设置了 deferrable: :deferred
选项,则不会失败。
ActiveRecord::Base.lease_connection.transaction do
person = Person.create(id: SecureRandom.uuid, alias_id: SecureRandom.uuid, name: "John Doe")
Alias.create(id: person.alias_id, person_id: person.id, name: "jaydee")
end
当 :deferrable
选项设置为 :immediate
时,让外键保持默认行为,即立即检查约束,但允许在事务中使用 set_constraints
手动延迟检查。这将导致外键在事务提交时进行检查
ActiveRecord::Base.lease_connection.transaction do
ActiveRecord::Base.lease_connection.set_constraints(:deferred)
person = Person.create(alias_id: SecureRandom.uuid, name: "John Doe")
Alias.create(id: person.alias_id, person_id: person.id, name: "jaydee")
end
默认情况下,:deferrable
为 false
,并且约束始终立即检查。
6 唯一约束
# db/migrate/20230422225213_create_items.rb
create_table :items do |t|
t.integer :position, null: false
t.unique_constraint [:position], deferrable: :immediate
end
如果您要将现有的唯一索引更改为可延迟的,您可以使用 :using_index
来创建可延迟的唯一约束。
add_unique_constraint :items, deferrable: :deferred, using_index: "index_items_on_position"
与外键一样,可以通过将 :deferrable
设置为 :immediate
或 :deferred
来延迟唯一约束。默认情况下,:deferrable
为 false
,并且约束始终立即检查。
7 排除约束
# db/migrate/20131220144913_create_products.rb
create_table :products do |t|
t.integer :price, null: false
t.daterange :availability_range, null: false
t.exclusion_constraint "price WITH =, availability_range WITH &&", using: :gist, name: "price_check"
end
与外键一样,可以通过将 :deferrable
设置为 :immediate
或 :deferred
来延迟排除约束。默认情况下,:deferrable
为 false
,并且约束始终立即检查。
8 全文搜索
# 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
# Usage
Document.create(title: "Cats and Dogs", body: "are nice!")
## all documents matching 'cat & dog'
Document.where("to_tsvector('english', title || ' ' || body) @@ to_tsquery(?)",
"cat & dog")
可以选择将向量存储为自动生成的列(来自 PostgreSQL 12.0)
# db/migrate/20131220144913_create_documents.rb
create_table :documents do |t|
t.string :title
t.string :body
t.virtual :textsearchable_index_col,
type: :tsvector, as: "to_tsvector('english', title || ' ' || body)", stored: true
end
add_index :documents, :textsearchable_index_col, using: :gin, name: "documents_idx"
# Usage
Document.create(title: "Cats and Dogs", body: "are nice!")
## all documents matching 'cat & dog'
Document.where("textsearchable_index_col @@ to_tsquery(?)", "cat & dog")
9 数据库视图
假设您需要使用包含以下表的旧数据库
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 视图默认情况下是可更新的,因此我们可以按如下方式对其进行包装
# 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
。视图也允许使用条件,因此我们可以直接排除已归档的 Articles
。
10 结构转储
如果您的 config.active_record.schema_format
为 :sql
,Rails 将调用 pg_dump
来生成结构转储。
您可以使用ActiveRecord::Tasks::DatabaseTasks.structure_dump_flags
配置pg_dump
。 例如,要从结构转储中排除注释,请将其添加到初始化程序中
ActiveRecord::Tasks::DatabaseTasks.structure_dump_flags = ["--no-comments"]