テーブル
テーブルとはデータを格納する場所です。
テーブルはExcelのスプレッドシートに似ています。データの列と行を含んでいます。
例えば、このテーブルには3つの「列」(id
, name
, description
)と4つの「行」のデータがあります。
id | name | description |
---|---|---|
1 | The Phantom Menace | Two Jedi escape a hostile blockade to find allies and come across a young boy who may bring balance to the Force. |
2 | Attack of the Clones | Ten years after the invasion of Naboo, the Galactic Republic is facing a Separatist movement. |
3 | Revenge of the Sith | As Obi-Wan pursues a new threat, Anakin acts as a double agent between the Jedi Council and Palpatine and is lured into a sinister plan to rule the galaxy. |
4 | Star Wars | Luke Skywalker 結合s forces with a Jedi Knight, a cocky pilot, a Wookiee and two droids to save the galaxy from the Empire's world-destroying battle station. |
表計算ソフトとの重要な違いがいくつかありますが、リレーショナル・データベースに初めて触れる方には良い出発点になります。
テーブルの作成
テーブルを作成する際には、同時にカラムを追加するのがベストプラクティスです。
各カラムの「データ型」は、作成時に定義する必要があります。カラムの追加や削除は、テーブルを作成した後いつでも行うことができます。
Supabaseには、テーブルを作成するためのいくつかの選択肢があります。テーブル・エディターを使用するか、SQLを直接使用して作成できます。 ダッシュボードにはSQLエディターが用意されていますが、データベースに接続して、SQLクエリを実行できます。
- Dashboard
- SQL
1. 「Table editor」のセクションに移動します。
2. 「New Table」をクリックします。
3. 「todos」というテーブル名を入力します。
4. 「Save」をクリックします。
5. 「New Column」をクリックします。
6. 「task」というカラム名を入力して、タイプを「text」にします。
7. 「Save」をクリックします。
create table movies (
id bigint generated by default as identity primary key,
name text,
description text
);
テーブル名を付ける際には、小文字とアンダースコアを使用するのがベストプラクティスです。例えば、Table Name
ではなく、table_name
とします。
カラム
カラムを作成する際に、「データ型」を定義します。
データ型
全ての列は定義済みの型です。PostgreSQLは多くのデフォルト型を提供していますが、デフォルト型がニーズに合わない場合は、独自に設計できます(または拡張機能を使用きます)。
表示/非表示 デフォルトのデータ型
名称 | エイリアス | 説明 |
---|---|---|
bigint | int8 | 符号付き8バイト整数 |
bigserial | serial8 | オートインクリメントの8バイト整数 |
bit | 固定長のビット列 | |
bit varying | varbit | 可変長のビット列 |
boolean | bool | 論理ブーリアン(true/false) |
box | 平面上の長方形の短形 | |
bytea | バイナリーデータ(バイトの配列) | |
character | char | 固定長の文字列 |
character varying | varchar | 可変長文字列 |
cidr | IPv4またはIPv6のネットワークアドレス | |
circle | 平面上の円 | |
date | カレンダーの日付(年、月、日) | |
double precision | float8 | 倍精度の浮動小数点数(8バイト) |
inet | IPv4またはIPv6のホストアドレス | |
integer | int, int4 | 符号付き4バイト整数 |
interval [ fields ] | タイムスパン | |
json | テキスト形式のJSONデータ | |
jsonb | JSONのバイナリーデータを分解したもの | |
line | 平面上の無限の線 | |
lseg | 平面上の線分 | |
macaddr | MAC(Media Access Control)アドレス | |
macaddr8 | MAC(Media Access Control)アドレス(EUI-64形式) | |
money | 通貨量 | |
numeric | decimal | 選択可能な精度の正確な数値 |
path | 平面上の幾何学的なパス | |
pg_lsn | PostgreSQLログのシーケンス番号 | |
pg_snapshot | ユーザーレベルのトランザクションIDのスナップショット | |
point | 平面上の幾何学的な点 | |
polygon | 平面上の閉じた幾何学的経路 | |
real | float4 | 単精度の浮動小数点数(4バイト) |
smallint | int2 | 符号付き2バイト整数 |
smallserial | serial2 | オートインクリメントの2バイト整数 |
serial | serial4 | オートインクリメントの4バイト整数 |
text | 可変長文字列 | |
time [ without time zone ] | 時間帯(タイムゾーンなし) | |
time with time zone | timetz | タイムゾーンを含む時刻 |
timestamp [ without time zone ] | 日付と時刻(タイムゾーンなし) | |
timestamp with time zone | timestamptz | タイムゾーンを含む日付と時刻 |
tsquery | テキスト検索クエリ | |
tsvector | テキスト検索ドキュメント | |
txid_snapshot | ユーザレベルのトランザクションIDのスナップショット(非推奨、pg_snapshot参照) | |
uuid | 一意に識別するための識別子 - universally unique identifier | |
xml | XMLデータ |
ある型のカラムを別の型に「キャスト」できますが、型の間にいくつかの非互換性が存在します。
例えば、timestamp
をdate
にキャストすると、それまで保存されていた時刻の情報がすべて失われます。
プライマリー・キー
テーブルには「プライマリー・キー」、つまりすべてのデータ行に一意な識別子を設定できます。プライマリー・キーに関するいくつかのヒントを紹介します。
- データベース内のすべてのテーブルにプライマリー・キーを作成することを推奨します。
- 各行で一意であれば、どのようなカラムでもプライマリー・キーとして使用できます。
- プライマリー・キーとして
uuid
型または番号付きのidentity
カラムを使用するのが一般的です。
create table movies (
id bigint generated always as identity primary key
);
上の例では、次のようになります。
id
という名前のカラムを作成しました。- データ型に
bigint
を割り当てました。 - このカラムが
generated always as identity
であること、つまりPostgresがこのカラムに自動的に一意な番号を割り当てることをデータベースに指示します。 - 一意であるため、
primary key
(プライマリー・キー)として使用できます。
また、generated by default as identity
を使用することで、独自の値を挿入できます。
create table movies (
id bigint generated by default as identity primary key
);
データの読み込み
Supabaseにデータを読み込むには、いくつかの方法があります。データベースに直接データを読み込む方法と、APIを使用して読み込みする方法があります。 大きなデータ・セットを読み込む場合は、「バルクでの読み込み」の手順を使用してください。
基本的なデータの読み込み
- SQL
- JavaScript
- Dart
insert into movies
(name, description)
values
('The Empire Strikes Back', 'After the Rebels are brutally overpowered by the Empire on the ice planet Hoth, Luke Skywalker begins Jedi training with Yoda.'),
('Return of the Jedi', 'After a daring mission to rescue Han Solo from Jabba the Hutt, the Rebels dispatch to Endor to destroy the second Death Star.');
const { data, error } = await supabase
.from('movies')
.insert([{
name: 'The Empire Strikes Back',
description: 'After the Rebels are brutally overpowered by the Empire on the ice planet Hoth, Luke Skywalker begins Jedi training with Yoda.'
}, {
name: 'Return of the Jedi',
description: 'After a daring mission to rescue Han Solo from Jabba the Hutt, the Rebels dispatch to Endor to destroy the second Death Star.'
}])
final res = await supabase
.from('movies')
.insert([{
name: 'The Empire Strikes Back',
description: 'After the Rebels are brutally overpowered by the Empire on the ice planet Hoth, Luke Skywalker begins Jedi training with Yoda.'
}, {
name: 'Return of the Jedi',
description: 'After a daring mission to rescue Han Solo from Jabba the Hutt, the Rebels dispatch to Endor to destroy the second Death Star.'
}]).execute();
バルクでのデータ読み込み
大きなデータのセットを挿入する場合、PostgreSQLのCOPYコマンドを使用することが最善です。 これは、データをファイルからテーブルに直接ロードします。データのコピーに使用できるファイル形式は、テキスト、csv、バイナリー、JSONなど、いくつかあります。
例えば、次のCSVファイルをmoviesテーブルに読み込みます。
"The Empire Strikes Back", "After the Rebels are brutally overpowered by the Empire on the ice planet Hoth, Luke Skywalker begins Jedi training with Yoda."
"Return of the Jedi", "After a daring mission to rescue Han Solo from Jabba the Hutt, the Rebels dispatch to Endor to destroy the second Death Star."
データベースに直接接続して、COPYコマンドでファイルを読み込みます。
psql -h DATABASE_URL -p 5432 postgres -U postgres \
-c "COPY movies FROM './movies.csv';"
外部キーでテーブル結合
テーブルは、外部キーを使って「結合(結合)」できます。
これは、データが通常ある種の関係を形成していることから、「リレーショナル(関連)」という名称が付けられました。
上記の「movies(映画)」の例では、各映画に「カテゴリー」を追加したいとします(例えば、「アクション」や「ドキュメンタリー」など)。
そこで、categories
という新しいテーブルを作成して、movies
テーブルに「リンク」してみましょう。
create table categories (
id bigint generated always as identity primary key,
name text -- category name
);
alter table movies
add column category_id bigint references categories;
また、「結合」テーブルを作成することで、「多対多」の関係を作ることができます。 例えば、次のような状況があったとします。
movies
(映画)のリストがあります。- 映画には複数の
actors
(俳優)が登場します。 actor
は複数の映画に出演できます。
- SQL
- Dashboard
create table movies (
id bigint generated by default as identity primary key,
name text,
description text
);
create table actors (
id bigint generated by default as identity primary key,
name text
);
create table performances (
id bigint generated by default as identity primary key,
movie_id bigint not null references movies,
actor_id bigint not null references actors
);
スキーマ
テーブルはschemas
に属します。スキーマはテーブルを組織化する方法であり、多くの場合、セキュリティー上の理由からです。
テーブルを作成する際にスキーマを明示的に渡さない場合、Postgresはpublic
スキーマでテーブルを作成するものとみなします。
テーブルを整理するためのスキーマを作成できます。例えば、APIからは見えないプライベートなスキーマが必要な場合は次のように作成します。
create schema private;
これでprivate
スキーマの中にテーブルを作成できるようになりました。
create table salaries (
id bigint generated by default as identity primary key,
salary bigint not null,
actor_id bigint not null references public.actors
);