LoginSignup
5
2

More than 1 year has passed since last update.

Cloud Spanner Emulatorをインストールしてspanner-cliでアクセスしてみる

Last updated at Posted at 2022-11-14

Spannerのエミューレータが出たのはいいのですが、標準ではgcloudやプログラミング言語からの操作になってしまい身近な感じがしないのでCLIツールであるspanner-cliを利用してアクセスしてみます。

本当はPostgreSQL Interfaceを利用したかったのですがEmulatorは対応してないそうです(本当はpsqlでアクセスしたかった)。

前提

  • Mac
  • gcloudがインストールされている
  • Dockerがインストールされている

Spanner Emulatorの起動と設定

起動

Dockerがインストールされていれば以下のコマンドで簡単に起動できるようです。

gcloud emulators spanner start

標準ではforgroundで起動するみたい(Emulatorはインメモリで終了後は全てのデータは揮発する仕様のようです)。

設定

gcloudコマンドがローカルのEmulatorを見るように設定を行います。

# Emulator用のconfiを作成
gcloud config configurations create emulator
# 認証をOFF
gcloud config set auth/disable_credentials true
# projectを指定(必須です)
gcloud config set project dev-test
# Endpointをローカルに
gcloud config set api_endpoint_overrides/spanner http://localhost:9020/

なお、configを切り替えるのは以下のコマンドできるみたいです。

gcloud config configurations activate [emulator | default]

gcloud config listで内容、現在Activeなconfigを確認できます。

Spannerを利用する

インスタンスの作成

まずはインスタンスを作成します。

gcloud spanner instances create test-instance --config=emulator-config --description="Test Instance" --nodes=1

インスタンスは以下のコマンドで確認できるみたいです。

gcloud spanner instances list

datbaseの作成

データベースを作っておきます。

spanner-cliではログイン時にDBの指定が必須になります。

gcloud spanner databases create testdb --instance=test-instance

なお、PostgreSQL Interfaceで操作可能なDBは以下のコマンドで作れるみたいですが、冒頭に記述した通り現時点ではEmulatorはPostgeSQL Interfaceに非対応とのこと。

gcloud spanner databases create testdb --instance=my-instance-id --database-dialect=POSTGRESQL

spanner-cliでアクセスしてみる

ではspanner-cliでアクセスしてみます。

準備

Goのインストール

spanner-cliはGoに依存しているのでGoをインストールします。Macなら以下でOK。

brew install go

ただし、正常に実行するには環境変数設定が必要みたいです。

(ずっと使うなら).zshrcに以下を追加。

export GOPATH=$HOME/go
export PATH=$PATH:$GOPATH/bin

また、spanner-cliを含めた言語経由でのアクセスのためには以下の環境変数設定が必要みたいです。

export SPANNER_EMULATOR_HOST=localhost:9010

.zshrcに書くかはお好みで。

spanner-cliのインストール

インストール。

go install github.com/cloudspannerecosystem/spanner-cli@latest

動作確認。バージョンコマンド見当たらないので-hで代用。

spanner-cli -h

アクセス

では、Spannerにアクセスしてみます。

spanner-cli -p dev-test -i test-instance -d testdb

DB一覧は gcloud spanner databases list --instance=test-instance で確認可能。

利用

ここからは基本SQLの世界(なので最低限)。

CREATE TABLE

create table members(
	id INT64 NOT NULL,
	name STRING(32),
	age INT64
) primary key (id);
show tables;

INSERT, SELECT

insert into members(id,name,age) values(1,"hoge",10);

select * from members;
+----+------+-----+
| id | name | age |
+----+------+-----+
| 1  | hoge | 10  |
+----+------+-----+
1 rows in set (262.052us)
exit;

後片付け

DBを消す

gcloud spanner databases delete testdb --instance=test-instance

Instanceを消す

gcloud spanner instances delete test-instance
5
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
2