2017/3/21

rails db & postgresql cli 使用方法

postgresql 相關指令

查看有哪些資料庫

\l

連線到資料庫

\c db_name

查看有哪些表格

\dt

查看有哪些欄位

\d+ table_name

查看執行過的資料庫遷移

select * from schema_migrations;

rails db 相關指令

開啟含有 rails 環境的 irb

rails console

連線到資料庫

rails dbconsole

建立資料庫,如果資料庫已經存在則不做事

rails db:create

刪除資料庫

rails db:drop

根據 db/schema.rb 檔產生對應的資料表(此動作會將資料庫內的資料清空)

rails db:schema:load

根據資料庫狀態更新 db/schema.rb 檔 (但只要叫 db:migrate 就會自動執行這個了)

rails db:schema:dump

執行db/seeds.rb

rails db:seed

快速功能

setup

rails db:setup

等於以下指令

rails db:create
rails db:schema:load
rails db:seed

reset

rails db:reset

等於以下指令

rails db:drop
rails db:setup

在這裡要注意的是setup跟reset指令不是重新執行migrate,所以如果你的schema檔是壞的,你下這兩個指令完還是壞的。 如果想要根據migration檔重新建立一個資料庫應該下的指令是

migrate:reset

rails db:migrate:reset 

等於以下指令

rails db:drop 
rails db:create 
rails db:migrate

這裡要注意的是, db:migrate:reset 指令並不會執行 db:seed

執行資料庫遷移,會把所有還沒執行過的都執行完,然後自動更新 db/schema.rb 檔

rails db:migrate

查看資料庫遷移結果

rails db:migrate:status

還原上一筆資料庫遷移

rails db:rollback

執行下一筆資料庫遷移

rails db:forward

參考資料

RailsGuide Migrations(資料庫遷移)

schema 相關 psql 指令

列出所有 schema

\dn
#  List of schemas
#  Name  |  Owner   
#--------+----------
# public | postgres
# abc    | etrex
# (2 rows)

顯示目前所在的 schema

SHOW search_path;
#   search_path   
#-----------------
# "$user", public
# (1 row)

切換 schema

SET search_path TO abc;
# SET
SET search_path TO 'abc';
# SET

字串要不要加引號都可以,當 search_path 的值不在 schema 的列表上時不會跳 error,可以想像成連接到一個空的 schema,而這樣並不代表新增了一個 schema。

在 select 的當下使用 schema

SELECT * FROM schema_name.table_name;

參考資料

https://stackoverflow.com/questions/34098326/how-to-select-a-schema-in-postgres-when-using-psql

沒有留言: