2018-07-24 02:29:31 +00:00
**DO NOT READ THIS FILE ON GITHUB, GUIDES ARE PUBLISHED ON https://guides.rubyonrails.org.**
2014-12-23 22:32:50 +00:00
2014-05-06 11:20:32 +00:00
Active Record and PostgreSQL
2014-01-21 11:13:11 +00:00
============================
2014-05-06 11:20:32 +00:00
This guide covers PostgreSQL specific usage of Active Record.
2014-01-21 11:13:11 +00:00
2014-05-07 05:47:39 +00:00
After reading this guide, you will know:
* How to use PostgreSQL's datatypes.
2014-05-08 09:27:35 +00:00
* How to use UUID primary keys.
* How to implement full text search with PostgreSQL.
2014-06-14 09:20:58 +00:00
* How to back your Active Record models with database views.
2014-05-07 05:47:39 +00:00
--------------------------------------------------------------------------------
2018-09-23 04:45:19 +00:00
In order to use the PostgreSQL adapter you need to have at least version 9.3
2014-05-19 07:14:58 +00:00
installed. Older versions are not supported.
To get started with PostgreSQL have a look at the
[configuring Rails guide ](configuring.html#configuring-a-postgresql-database ).
2019-08-09 21:30:15 +00:00
It describes how to properly set up Active Record for PostgreSQL.
2014-05-19 07:14:58 +00:00
2014-01-21 11:13:11 +00:00
Datatypes
---------
PostgreSQL offers a number of specific datatypes. Following is a list of types,
that are supported by the PostgreSQL adapter.
### Bytea
2017-07-30 12:52:31 +00:00
* [type definition ](https://www.postgresql.org/docs/current/static/datatype-binary.html )
* [functions and operators ](https://www.postgresql.org/docs/current/static/functions-binarystring.html )
2014-01-21 11:13:11 +00:00
```ruby
# db/migrate/20140207133952_create_documents.rb
create_table :documents do |t|
t.binary 'payload'
end
2020-12-23 22:29:10 +00:00
```
2014-01-21 11:13:11 +00:00
2020-12-23 22:29:10 +00:00
```ruby
2014-01-21 11:13:11 +00:00
# app/models/document.rb
2015-12-12 13:25:00 +00:00
class Document < ApplicationRecord
2014-01-21 11:13:11 +00:00
end
2020-12-23 22:29:10 +00:00
```
2014-01-21 11:13:11 +00:00
2020-12-23 22:29:10 +00:00
```ruby
2014-01-21 11:13:11 +00:00
# Usage
data = File.read(Rails.root + "tmp/output.pdf")
Document.create payload: data
```
### Array
2017-07-30 12:52:31 +00:00
* [type definition ](https://www.postgresql.org/docs/current/static/arrays.html )
* [functions and operators ](https://www.postgresql.org/docs/current/static/functions-array.html )
2014-01-21 11:13:11 +00:00
```ruby
# db/migrate/20140207133952_create_books.rb
2014-06-09 10:58:36 +00:00
create_table :books do |t|
2014-01-21 11:13:11 +00:00
t.string 'title'
t.string 'tags', array: true
t.integer 'ratings', array: true
end
2014-06-09 10:58:36 +00:00
add_index :books, :tags, using: 'gin'
add_index :books, :ratings, using: 'gin'
2020-12-23 22:29:10 +00:00
```
2014-01-21 11:13:11 +00:00
2020-12-23 22:29:10 +00:00
```ruby
2014-01-21 11:13:11 +00:00
# app/models/book.rb
2015-12-12 13:25:00 +00:00
class Book < ApplicationRecord
2014-01-21 11:13:11 +00:00
end
2020-12-23 22:29:10 +00:00
```
2014-01-21 11:13:11 +00:00
2020-12-23 22:29:10 +00:00
```ruby
2014-01-21 11:13:11 +00:00
# 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")
```
### Hstore
2017-07-30 12:52:31 +00:00
* [type definition ](https://www.postgresql.org/docs/current/static/hstore.html )
2018-03-04 08:50:39 +00:00
* [functions and operators ](https://www.postgresql.org/docs/current/static/hstore.html#id-1.11.7.26.5 )
2014-01-21 11:13:11 +00:00
2015-10-13 20:50:19 +00:00
NOTE: You need to enable the `hstore` extension to use hstore.
2014-12-06 23:54:41 +00:00
2014-01-21 11:13:11 +00:00
```ruby
# db/migrate/20131009135255_create_profiles.rb
2022-01-28 22:00:32 +00:00
class CreateProfiles < ActiveRecord::Migration [ 7 . 0 ]
2014-12-06 23:54:41 +00:00
enable_extension 'hstore' unless extension_enabled?('hstore')
2014-01-21 11:13:11 +00:00
create_table :profiles do |t|
t.hstore 'settings'
end
end
2020-10-31 21:44:05 +00:00
```
2014-01-21 11:13:11 +00:00
2020-10-31 21:44:05 +00:00
```ruby
2014-01-21 11:13:11 +00:00
# app/models/profile.rb
2015-12-12 13:25:00 +00:00
class Profile < ApplicationRecord
2014-01-21 11:13:11 +00:00
end
2020-10-31 21:44:05 +00:00
```
2014-01-21 11:13:11 +00:00
2020-10-31 21:44:05 +00:00
```irb
irb> Profile.create(settings: { "color" => "blue", "resolution" => "800x600" })
2014-01-21 11:13:11 +00:00
2020-10-31 21:44:05 +00:00
irb> profile = Profile.first
irb> profile.settings
=> {"color"=>"blue", "resolution"=>"800x600"}
2014-01-21 11:13:11 +00:00
2020-10-31 21:44:05 +00:00
irb> profile.settings = {"color" => "yellow", "resolution" => "1280x1024"}
irb> profile.save!
2016-01-18 05:59:36 +00:00
2020-10-31 21:44:05 +00:00
irb> Profile.where("settings->'color' = ?", "yellow")
=> #< ActiveRecord::Relation [ # < Profile id: 1 , settings: { " color " = > "yellow", "resolution"=>"1280x1024"}>]>
2014-01-21 11:13:11 +00:00
```
2017-06-27 09:10:26 +00:00
### JSON and JSONB
2014-01-21 11:13:11 +00:00
2017-07-30 12:52:31 +00:00
* [type definition ](https://www.postgresql.org/docs/current/static/datatype-json.html )
* [functions and operators ](https://www.postgresql.org/docs/current/static/functions-json.html )
2014-01-21 11:13:11 +00:00
```ruby
# db/migrate/20131220144913_create_events.rb
2017-06-27 09:10:26 +00:00
# ... for json datatype:
2014-01-21 11:13:11 +00:00
create_table :events do |t|
t.json 'payload'
end
2017-06-27 09:10:26 +00:00
# ... or for jsonb datatype:
create_table :events do |t|
t.jsonb 'payload'
end
2020-10-31 21:44:05 +00:00
```
2014-01-21 11:13:11 +00:00
2020-10-31 21:44:05 +00:00
```ruby
2014-01-21 11:13:11 +00:00
# app/models/event.rb
2015-12-12 13:25:00 +00:00
class Event < ApplicationRecord
2014-01-21 11:13:11 +00:00
end
2020-10-31 21:44:05 +00:00
```
2014-01-21 11:13:11 +00:00
2020-10-31 21:44:05 +00:00
```irb
irb> Event.create(payload: { kind: "user_renamed", change: ["jack", "john"]})
2014-01-21 11:13:11 +00:00
2020-10-31 21:44:05 +00:00
irb> event = Event.first
irb> event.payload
=> {"kind"=>"user_renamed", "change"=>["jack", "john"]}
2014-01-21 11:13:11 +00:00
## Query based on JSON document
2014-09-02 21:01:00 +00:00
# The -> operator returns the original JSON type (which might be an object), whereas ->> returns text
2020-10-31 21:44:05 +00:00
irb> Event.where("payload->>'kind' = ?", "user_renamed")
2014-01-21 11:13:11 +00:00
```
### Range Types
2017-07-30 12:52:31 +00:00
* [type definition ](https://www.postgresql.org/docs/current/static/rangetypes.html )
* [functions and operators ](https://www.postgresql.org/docs/current/static/functions-range.html )
2014-01-21 11:13:11 +00:00
2021-02-04 16:34:53 +00:00
This type is mapped to Ruby [`Range` ](https://ruby-doc.org/core-2.7.0/Range.html ) objects.
2014-01-21 11:13:11 +00:00
```ruby
# db/migrate/20130923065404_create_events.rb
create_table :events do |t|
t.daterange 'duration'
end
2020-10-31 21:44:05 +00:00
```
2014-01-21 11:13:11 +00:00
2020-10-31 21:44:05 +00:00
```ruby
2014-01-21 11:13:11 +00:00
# app/models/event.rb
2015-12-12 13:25:00 +00:00
class Event < ApplicationRecord
2014-01-21 11:13:11 +00:00
end
2020-10-31 21:44:05 +00:00
```
2014-01-21 11:13:11 +00:00
2020-10-31 21:44:05 +00:00
```irb
irb> Event.create(duration: Date.new(2014, 2, 11)..Date.new(2014, 2, 12))
2014-01-21 11:13:11 +00:00
2020-10-31 21:44:05 +00:00
irb> event = Event.first
irb> event.duration
=> Tue, 11 Feb 2014...Thu, 13 Feb 2014
2014-01-21 11:13:11 +00:00
## All Events on a given date
2020-10-31 21:44:05 +00:00
irb> Event.where("duration @> ?::date", Date.new(2014, 2, 12))
2014-01-21 11:13:11 +00:00
## Working with range bounds
2020-10-31 21:44:05 +00:00
irb> event = Event.select("lower(duration) AS starts_at").select("upper(duration) AS ends_at").first
2014-01-21 11:13:11 +00:00
2020-10-31 21:44:05 +00:00
irb> event.starts_at
=> Tue, 11 Feb 2014
irb> event.ends_at
=> Thu, 13 Feb 2014
2014-01-21 11:13:11 +00:00
```
### Composite Types
2017-07-30 12:52:31 +00:00
* [type definition ](https://www.postgresql.org/docs/current/static/rowtypes.html )
2014-01-21 11:13:11 +00:00
2014-05-18 16:58:50 +00:00
Currently there is no special support for composite types. They are mapped to
2014-01-21 11:13:11 +00:00
normal text columns:
```sql
CREATE TYPE full_address AS
(
city VARCHAR(90),
street VARCHAR(90)
);
```
```ruby
# db/migrate/20140207133952_create_contacts.rb
execute < < -SQL
2020-12-25 17:17:01 +00:00
CREATE TYPE full_address AS
(
city VARCHAR(90),
street VARCHAR(90)
);
2014-01-21 11:13:11 +00:00
SQL
create_table :contacts do |t|
t.column :address, :full_address
end
2020-10-31 21:44:05 +00:00
```
2014-01-21 11:13:11 +00:00
2020-10-31 21:44:05 +00:00
```ruby
2014-01-21 11:13:11 +00:00
# app/models/contact.rb
2015-12-12 13:25:00 +00:00
class Contact < ApplicationRecord
2014-01-21 11:13:11 +00:00
end
2020-10-31 21:44:05 +00:00
```
2014-01-21 11:13:11 +00:00
2020-10-31 21:44:05 +00:00
```irb
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!
2014-01-21 11:13:11 +00:00
```
### Enumerated Types
2017-07-30 12:52:31 +00:00
* [type definition ](https://www.postgresql.org/docs/current/static/datatype-enum.html )
2014-01-21 11:13:11 +00:00
2022-01-03 15:40:52 +00:00
The type can be mapped as a normal text column, or to an [`ActiveRecord::Enum` ](https://api.rubyonrails.org/classes/ActiveRecord/Enum.html ).
2014-01-21 11:13:11 +00:00
```ruby
2014-11-22 07:13:33 +00:00
# db/migrate/20131220144913_create_articles.rb
2015-07-22 15:52:24 +00:00
def up
2022-01-03 15:40:52 +00:00
create_enum :article_status, ["draft", "published"]
2015-07-22 15:52:24 +00:00
create_table :articles do |t|
2022-01-03 15:40:52 +00:00
t.enum :status, enum_type: :article_status, default: "draft", null: false
2015-07-22 15:52:24 +00:00
end
end
2022-01-03 15:40:52 +00:00
# There's no built in support for dropping enums, but you can do it manually.
# You should first drop any table that depends on them.
2015-07-22 15:52:24 +00:00
def down
drop_table :articles
execute < < -SQL
DROP TYPE article_status;
SQL
2014-01-21 11:13:11 +00:00
end
2020-10-31 21:44:05 +00:00
```
2014-01-21 11:13:11 +00:00
2020-10-31 21:44:05 +00:00
```ruby
2014-01-21 11:13:11 +00:00
# app/models/article.rb
2015-12-12 13:25:00 +00:00
class Article < ApplicationRecord
2022-01-03 15:40:52 +00:00
enum status: {
draft: "draft", published: "published"
}, _prefix: true
2014-01-21 11:13:11 +00:00
end
2020-10-31 21:44:05 +00:00
```
2014-01-21 11:13:11 +00:00
2020-10-31 21:44:05 +00:00
```irb
irb> Article.create status: "draft"
irb> article = Article.first
2022-01-03 15:40:52 +00:00
irb> article.status_draft!
2020-10-31 21:44:05 +00:00
irb> article.status
=> "draft"
2014-01-21 11:13:11 +00:00
2022-01-03 15:40:52 +00:00
irb> article.status_published?
=> false
2014-01-21 11:13:11 +00:00
```
2017-07-30 12:52:31 +00:00
To add a new value before/after existing one you should use [ALTER TYPE ](https://www.postgresql.org/docs/current/static/sql-altertype.html ):
2015-10-13 20:50:19 +00:00
2015-07-22 15:52:24 +00:00
```ruby
# db/migrate/20150720144913_add_new_state_to_articles.rb
# NOTE: ALTER TYPE ... ADD VALUE cannot be executed inside of a transaction block so here we are using disable_ddl_transaction!
disable_ddl_transaction!
def up
execute < < -SQL
ALTER TYPE article_status ADD VALUE IF NOT EXISTS 'archived' AFTER 'published';
SQL
end
```
2022-01-03 15:40:52 +00:00
NOTE: Enum values can't be dropped. You can read why [here ](https://www.postgresql.org/message-id/29F36C7C98AB09499B1A209D48EAA615B7653DBC8A@mail2a.alliedtesting.com ).
2015-07-22 15:52:24 +00:00
2019-01-22 08:53:47 +00:00
Hint: to show all the values of the all enums you have, you should call this query in `bin/rails db` or `psql` console:
2015-10-13 20:50:19 +00:00
2015-07-22 15:52:24 +00:00
```sql
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
```
2014-01-21 11:13:11 +00:00
### UUID
2017-07-30 12:52:31 +00:00
* [type definition ](https://www.postgresql.org/docs/current/static/datatype-uuid.html )
2019-12-24 02:11:45 +00:00
* [pgcrypto generator function ](https://www.postgresql.org/docs/current/static/pgcrypto.html )
2017-07-30 12:52:31 +00:00
* [uuid-ossp generator functions ](https://www.postgresql.org/docs/current/static/uuid-ossp.html )
2014-01-21 11:13:11 +00:00
2015-10-13 20:50:19 +00:00
NOTE: You need to enable the `pgcrypto` (only PostgreSQL >= 9.4) or `uuid-ossp`
2015-04-23 03:39:07 +00:00
extension to use uuid.
2014-01-21 11:13:11 +00:00
```ruby
# db/migrate/20131220144913_create_revisions.rb
create_table :revisions do |t|
2015-08-08 09:37:22 +00:00
t.uuid :identifier
2014-01-21 11:13:11 +00:00
end
2020-10-31 21:44:05 +00:00
```
2014-01-21 11:13:11 +00:00
2020-10-31 21:44:05 +00:00
```ruby
2014-01-21 11:13:11 +00:00
# app/models/revision.rb
2015-12-12 13:25:00 +00:00
class Revision < ApplicationRecord
2014-01-21 11:13:11 +00:00
end
2020-10-31 21:44:05 +00:00
```
2014-01-21 11:13:11 +00:00
2020-10-31 21:44:05 +00:00
```irb
irb> Revision.create identifier: "A0EEBC99-9C0B-4EF8-BB6D-6BB9BD380A11"
2014-01-21 11:13:11 +00:00
2020-10-31 21:44:05 +00:00
irb> revision = Revision.first
irb> revision.identifier
=> "a0eebc99-9c0b-4ef8-bb6d-6bb9bd380a11"
2014-01-21 11:13:11 +00:00
```
2015-06-15 09:31:54 +00:00
You can use `uuid` type to define references in migrations:
2015-04-18 04:44:00 +00:00
```ruby
# db/migrate/20150418012400_create_blog.rb
2015-06-15 09:31:54 +00:00
enable_extension 'pgcrypto' unless extension_enabled?('pgcrypto')
2020-08-08 09:41:34 +00:00
create_table :posts, id: :uuid
2015-04-18 04:44:00 +00:00
2020-08-08 09:41:34 +00:00
create_table :comments, id: :uuid do |t|
2015-04-18 04:44:00 +00:00
# t.belongs_to :post, type: :uuid
t.references :post, type: :uuid
end
2020-12-23 22:29:10 +00:00
```
2015-04-18 04:44:00 +00:00
2020-12-23 22:29:10 +00:00
```ruby
2015-04-18 04:44:00 +00:00
# app/models/post.rb
2015-12-12 13:25:00 +00:00
class Post < ApplicationRecord
2015-04-18 04:44:00 +00:00
has_many :comments
end
2020-12-23 22:29:10 +00:00
```
2015-04-18 04:44:00 +00:00
2020-12-23 22:29:10 +00:00
```ruby
2015-04-18 04:44:00 +00:00
# app/models/comment.rb
2015-12-12 13:25:00 +00:00
class Comment < ApplicationRecord
2015-04-18 04:44:00 +00:00
belongs_to :post
end
```
2015-06-15 09:31:54 +00:00
See [this section ](#uuid-primary-keys ) for more details on using UUIDs as primary key.
2014-01-21 11:13:11 +00:00
### Bit String Types
2017-07-30 12:52:31 +00:00
* [type definition ](https://www.postgresql.org/docs/current/static/datatype-bit.html )
* [functions and operators ](https://www.postgresql.org/docs/current/static/functions-bitstring.html )
2014-01-21 11:13:11 +00:00
```ruby
# db/migrate/20131220144913_create_users.rb
create_table :users, force: true do |t|
t.column :settings, "bit(8)"
end
2020-10-31 21:44:05 +00:00
```
2014-01-21 11:13:11 +00:00
2020-10-31 21:44:05 +00:00
```ruby
2018-05-06 07:43:05 +00:00
# app/models/user.rb
2015-12-12 13:25:00 +00:00
class User < ApplicationRecord
2014-01-21 11:13:11 +00:00
end
2020-10-31 21:44:05 +00:00
```
2014-01-21 11:13:11 +00:00
2020-10-31 21:44:05 +00:00
```irb
irb> User.create settings: "01010011"
irb> user = User.first
irb> user.settings
=> "01010011"
irb> user.settings = "0xAF"
irb> user.settings
2021-12-02 21:46:11 +00:00
=> "10101111"
2020-10-31 21:44:05 +00:00
irb> user.save!
2014-01-21 11:13:11 +00:00
```
### Network Address Types
2017-07-30 12:52:31 +00:00
* [type definition ](https://www.postgresql.org/docs/current/static/datatype-net-types.html )
2014-01-21 11:13:11 +00:00
2014-05-18 16:58:50 +00:00
The types `inet` and `cidr` are mapped to Ruby
2021-02-04 16:34:53 +00:00
[`IPAddr` ](https://ruby-doc.org/stdlib-2.7.0/libdoc/ipaddr/rdoc/IPAddr.html )
2014-05-18 16:58:50 +00:00
objects. The `macaddr` type is mapped to normal text.
2014-01-21 11:13:11 +00:00
2014-05-08 09:27:35 +00:00
```ruby
# db/migrate/20140508144913_create_devices.rb
create_table(:devices, force: true) do |t|
t.inet 'ip'
t.cidr 'network'
t.macaddr 'address'
end
2020-10-31 21:44:05 +00:00
```
2014-05-08 09:27:35 +00:00
2020-10-31 21:44:05 +00:00
```ruby
2014-05-08 09:27:35 +00:00
# app/models/device.rb
2015-12-12 13:25:00 +00:00
class Device < ApplicationRecord
2014-05-08 09:27:35 +00:00
end
2020-10-31 21:44:05 +00:00
```
2014-05-08 09:27:35 +00:00
2020-10-31 21:44:05 +00:00
```irb
irb> macbook = Device.create(ip: "192.168.1.12", network: "192.168.2.0/24", address: "32:01:16:6d:05:ef")
2014-05-08 09:27:35 +00:00
2020-10-31 21:44:05 +00:00
irb> macbook.ip
=> #< IPAddr: IPv4:192 . 168 . 1 . 12 / 255 . 255 . 255 . 255 >
2014-05-08 09:27:35 +00:00
2020-10-31 21:44:05 +00:00
irb> macbook.network
=> #< IPAddr: IPv4:192 . 168 . 2 . 0 / 255 . 255 . 255 . 0 >
2014-05-08 09:27:35 +00:00
2020-10-31 21:44:05 +00:00
irb> macbook.address
=> "32:01:16:6d:05:ef"
2014-05-08 09:27:35 +00:00
```
2014-01-21 11:13:11 +00:00
### Geometric Types
2017-07-30 12:52:31 +00:00
* [type definition ](https://www.postgresql.org/docs/current/static/datatype-geometric.html )
2014-01-21 11:13:11 +00:00
2014-06-06 14:50:10 +00:00
All geometric types, with the exception of `points` are mapped to normal text.
A point is casted to an array containing `x` and `y` coordinates.
2014-01-21 11:13:11 +00:00
2020-01-20 16:26:41 +00:00
### Interval
2021-04-11 22:25:38 +00:00
* [type definition ](https://www.postgresql.org/docs/current/static/datatype-datetime.html#DATATYPE-INTERVAL-INPUT )
* [functions and operators ](https://www.postgresql.org/docs/current/static/functions-datetime.html )
2020-01-20 16:26:41 +00:00
2021-04-11 22:25:38 +00:00
This type is mapped to [`ActiveSupport::Duration` ](https://api.rubyonrails.org/classes/ActiveSupport/Duration.html ) objects.
2020-01-20 16:26:41 +00:00
```ruby
# db/migrate/20200120000000_create_events.rb
create_table :events do |t|
t.interval 'duration'
end
2020-10-31 21:44:05 +00:00
```
2020-01-20 16:26:41 +00:00
2020-10-31 21:44:05 +00:00
```ruby
2020-01-20 16:26:41 +00:00
# app/models/event.rb
class Event < ApplicationRecord
end
2020-10-31 21:44:05 +00:00
```
2020-01-20 16:26:41 +00:00
2020-10-31 21:44:05 +00:00
```irb
irb> Event.create(duration: 2.days)
2020-01-20 16:26:41 +00:00
2020-10-31 21:44:05 +00:00
irb> event = Event.first
irb> event.duration
=> 2 days
2020-01-20 16:26:41 +00:00
```
2014-02-24 18:25:15 +00:00
UUID Primary Keys
-----------------
2015-10-13 20:50:19 +00:00
NOTE: You need to enable the `pgcrypto` (only PostgreSQL >= 9.4) or `uuid-ossp`
2015-04-23 03:39:07 +00:00
extension to generate random UUIDs.
2014-02-24 18:25:15 +00:00
```ruby
# db/migrate/20131220144913_create_devices.rb
2015-04-23 03:39:07 +00:00
enable_extension 'pgcrypto' unless extension_enabled?('pgcrypto')
2020-08-08 09:41:34 +00:00
create_table :devices, id: :uuid do |t|
2014-02-24 18:25:15 +00:00
t.string :kind
end
2020-10-31 21:44:05 +00:00
```
2014-02-24 18:25:15 +00:00
2020-10-31 21:44:05 +00:00
```ruby
2014-02-24 18:25:15 +00:00
# app/models/device.rb
2015-12-12 13:25:00 +00:00
class Device < ApplicationRecord
2014-02-24 18:25:15 +00:00
end
2020-10-31 21:44:05 +00:00
```
2014-02-24 18:25:15 +00:00
2020-10-31 21:44:05 +00:00
```ruby
irb> device = Device.create
irb> device.id
=> "814865cd-5a1d-4771-9306-4268f188fe9e"
2014-02-24 18:25:15 +00:00
```
2016-11-24 09:42:45 +00:00
NOTE: `gen_random_uuid()` (from `pgcrypto` ) is assumed if no `:default` option was
2015-06-15 09:31:54 +00:00
passed to `create_table` .
2020-05-20 14:24:00 +00:00
Generated Columns
-----------------
NOTE: Generated columns are supported since version 12.0 of PostgreSQL.
```ruby
# db/migrate/20131220144913_create_users.rb
create_table :users do |t|
t.string :name
2021-04-06 17:04:50 +00:00
t.virtual :name_upcased, type: :string, as: 'upper(name)', stored: true
2020-05-20 14:24:00 +00:00
end
# app/models/user.rb
class User < ApplicationRecord
end
# Usage
user = User.create(name: 'John')
User.last.name_upcased # => "JOHN"
```
2014-02-24 18:25:15 +00:00
Full Text Search
----------------
```ruby
# db/migrate/20131220144913_create_documents.rb
create_table :documents do |t|
2020-05-20 14:24:00 +00:00
t.string :title
t.string :body
2014-02-24 18:25:15 +00:00
end
2016-05-28 05:26:04 +00:00
add_index :documents, "to_tsvector('english', title || ' ' || body)", using: :gin, name: 'documents_idx'
2020-12-23 22:29:10 +00:00
```
2014-02-24 18:25:15 +00:00
2020-12-23 22:29:10 +00:00
```ruby
2014-02-24 18:25:15 +00:00
# app/models/document.rb
2015-12-12 13:25:00 +00:00
class Document < ApplicationRecord
2014-02-24 18:25:15 +00:00
end
2020-12-23 22:29:10 +00:00
```
2014-02-24 18:25:15 +00:00
2020-12-23 22:29:10 +00:00
```ruby
2014-02-24 18:25:15 +00:00
# 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")
```
2020-05-20 14:24:00 +00:00
Optionally, you can store the vector as automatically generated column (from PostgreSQL 12.0):
```ruby
# db/migrate/20131220144913_create_documents.rb
create_table :documents do |t|
t.string :title
t.string :body
t.virtual :textsearchable_index_col,
2021-09-16 15:22:26 +00:00
type: :tsvector, as: "to_tsvector('english', title || ' ' || body)", stored: true
2020-05-20 14:24:00 +00:00
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")
```
2014-06-14 09:20:58 +00:00
Database Views
--------------
2014-05-11 11:47:30 +00:00
2017-07-30 12:52:31 +00:00
* [view creation ](https://www.postgresql.org/docs/current/static/sql-createview.html )
2014-05-11 11:47:30 +00:00
Imagine you need to work with a legacy database containing the following table:
```
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")
```
This table does not follow the Rails conventions at all.
Because simple PostgreSQL views are updateable by default,
we can wrap it as follows:
```ruby
# 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
2020-10-31 21:44:05 +00:00
```
2014-05-11 11:47:30 +00:00
2020-10-31 21:44:05 +00:00
```ruby
2014-05-11 11:47:30 +00:00
# app/models/article.rb
2015-12-12 13:25:00 +00:00
class Article < ApplicationRecord
2014-05-11 11:47:30 +00:00
self.primary_key = "id"
def archive!
update_attribute :archived, true
end
end
2020-10-31 21:44:05 +00:00
```
2014-05-11 11:47:30 +00:00
2020-10-31 21:44:05 +00:00
```irb
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
2014-05-11 11:47:30 +00:00
```
2014-05-29 09:23:59 +00:00
NOTE: This application only cares about non-archived `Articles` . A view also
2014-05-11 11:47:30 +00:00
allows for conditions so we can exclude the archived `Articles` directly.
2022-03-07 18:40:12 +00:00
Structure dumps
--------------
If your `config.active_record.schema_format` is `:sql` , Rails will call `pg_dump` to generate a
structure dump.
You can use `ActiveRecord::Tasks::DatabaseTasks.structure_dump_flags` to configure `pg_dump` .
For example, to exclude comments from your structure dump, add this to an initializer:
```ruby
ActiveRecord::Tasks::DatabaseTasks.structure_dump_flags = ['--no-comments']
```