dshimizu/blog

アルファ版

SQLite がどんなものかを少し調べながら sqlite3 コマンドでの基本操作を確認してみた

はじめに

ISUCON 12 で SQLite が登場してちょっと話題になった*1。 だいぶ月日が経ったけど SQLite をそれほどきちんと触ったことがなかったので、少し調べたり触ってみたりした。

SQLite とその特徴

軽量なデータベース、くらいの認識しかなかったので改めて少し調べた。

ざっくり箇条書きまとめ

  • SQLite は C ライブラリであり、ソースコードコンパイルして利用する。
  • データベースは xxxx.db といった形式のファイルとして保存される。
  • 何らかのアプリケーションから、SQLite ライブラリを利用して、直接 xxx.db 形式のデータベースファイルを読み書きするといった形になる。
    • sqlite3 コマンドが提供されているので、これを利用してシェルから CLI で対話的に操作/SQL実行できる
  • 設定ファイルはない。
  • 一般的な RDB と違い、クライアント/サーバ構成をとっていない。
    • サーバープロセス(PostgreSQL なら postgres プロセス, MySQL なら mysql プロセス)といったものは存在しない
    • TCPUnix ソケットなどを使用してデータベースサーバーに接続する形ではない。
    • そのため、ネットワーク的に分離した別サーバー等にある SQLite のデータベースファイルにアクセスするのは難しい(ユースケースとしてもやらないほうが良い)
  • SQLite のすべてのトランザクションは、ACID に完全に準拠している。

簡単な概念図

動かしてみる

環境

% sw_vers
ProductName:    macOS
ProductVersion: 12.6.1
BuildVersion:   21G217
 % sqlite3 -version
3.37.0 2021-12-09 01:34:53 9ff244ce0739f8ee52a3e9671adb4ee54c83c640b02e3f9d185fd2f9a179aapl

サンプルを使った動作と操作の確認

SQLite Tutorial というサイトがある。

適当なディレクトリを作成し、そのサイトからサンプルのデータベースを取得して配置する。

% mkdir sqlite-tutorial

% cd sqlite-tutorial

% curl -OL https://www.sqlitetutorial.net/wp-content/uploads/2018/03/chinook.zip

展開する。

% unzip chinook.zip
Archive:  chinook.zip
  inflating: chinook.db

データベースにアクセスする。

% sqlite3 chinook.db
SQLite version 3.37.0 2021-12-09 01:34:53
Enter ".help" for usage hints.
sqlite>

.help はこんな感じの出力だった。

sqlite> .help
.auth ON|OFF             Show authorizer callbacks
.backup ?DB? FILE        Backup DB (default "main") to FILE
.bail on|off             Stop after hitting an error.  Default OFF
.binary on|off           Turn binary output on or off.  Default OFF
.cd DIRECTORY            Change the working directory to DIRECTORY
.changes on|off          Show number of rows changed by SQL
.check GLOB              Fail if output since .testcase does not match
.clone NEWDB             Clone data into NEWDB from the existing database
.connection [close] [#]  Open or close an auxiliary database connection
.databases               List names and files of attached databases
.dbconfig ?op? ?val?     List or change sqlite3_db_config() options
.dbinfo ?DB?             Show status information about the database
.dump ?OBJECTS?          Render database content as SQL
.echo on|off             Turn command echo on or off
.eqp on|off|full|...     Enable or disable automatic EXPLAIN QUERY PLAN
.excel                   Display the output of next command in spreadsheet
.exit ?CODE?             Exit this program with return-code CODE
.expert                  EXPERIMENTAL. Suggest indexes for queries
.explain ?on|off|auto?   Change the EXPLAIN formatting mode.  Default: auto
.filectrl CMD ...        Run various sqlite3_file_control() operations
.fullschema ?--indent?   Show schema and the content of sqlite_stat tables
.headers on|off          Turn display of headers on or off
.help ?-all? ?PATTERN?   Show help text for PATTERN
.import FILE TABLE       Import data from FILE into TABLE
.imposter INDEX TABLE    Create imposter table TABLE on index INDEX
.indexes ?TABLE?         Show names of indexes
.limit ?LIMIT? ?VAL?     Display or change the value of an SQLITE_LIMIT
.lint OPTIONS            Report potential schema issues.
.log FILE|off            Turn logging on or off.  FILE can be stderr/stdout
.mode MODE ?TABLE?       Set output mode
.nonce STRING            Disable safe mode for one command if the nonce matches
.nullvalue STRING        Use STRING in place of NULL values
.once ?OPTIONS? ?FILE?   Output for the next SQL command only to FILE
.open ?OPTIONS? ?FILE?   Close existing database and reopen FILE
.output ?FILE?           Send output to FILE or stdout if FILE is omitted
.parameter CMD ...       Manage SQL parameter bindings
.print STRING...         Print literal STRING
.progress N              Invoke progress handler after every N opcodes
.prompt MAIN CONTINUE    Replace the standard prompts
.quit                    Exit this program
.read FILE               Read input from FILE
.recover                 Recover as much data as possible from corrupt db.
.restore ?DB? FILE       Restore content of DB (default "main") from FILE
.save FILE               Write in-memory database into FILE
.scanstats on|off        Turn sqlite3_stmt_scanstatus() metrics on or off
.schema ?PATTERN?        Show the CREATE statements matching PATTERN
.selftest ?OPTIONS?      Run tests defined in the SELFTEST table
.separator COL ?ROW?     Change the column and row separators
.session ?NAME? CMD ...  Create or control sessions
.sha3sum ...             Compute a SHA3 hash of database content
.shell CMD ARGS...       Run CMD ARGS... in a system shell
.show                    Show the current values for various settings
.stats ?ARG?             Show stats or turn stats on or off
.system CMD ARGS...      Run CMD ARGS... in a system shell
.tables ?TABLE?          List names of tables matching LIKE pattern TABLE
.testcase NAME           Begin redirecting output to 'testcase-out.txt'
.testctrl CMD ...        Run various sqlite3_test_control() operations
.timeout MS              Try opening locked tables for MS milliseconds
.timer on|off            Turn SQL timer on or off
.trace ?OPTIONS?         Output each SQL statement as it is run
.vfsinfo ?AUX?           Information about the top-level VFS
.vfslist                 List all available VFSes
.vfsname ?AUX?           Print the name of the VFS stack
.width NUM1 NUM2 ...     Set minimum column widths for columnar output

テーブル一覧を見てみる。

sqlite> .table
albums          employees       invoices        playlists
artists         genres          media_types     tracks
customers       invoice_items   playlist_track

.database で、現在の接続しているデータベースを表示できる。 main という名前のデータベースを少なくとも 1 つ表示される。

たとえば、次のコマンドは、現在の接続のすべてのデータベースを表示します。

sqlite> .database
main: /path/to/sqlite-tutorial/chinook.db r/w

どこにも接続してない場合は下記のようになる。

% sqlite3
SQLite version 3.37.0 2021-12-09 01:34:53
Enter ".help" for usage hints.
Connected to a transient in-memory database.
Use ".open FILENAME" to reopen on a persistent database.

sqlite> .database
main: "" r/w

sqliteCLI を起動中に他のデータベースに接続する場合は下記のように attach database コマンドを使う。

sqlite> attach database "/path/to/sqlite-tutorial/test.db" as testdb;

データベース一覧に追加される。

sqlite> .database
main: /Users/daisuke.shimizu/workspace/sqlite3/db/chinook.db r/w
testdb: /Users/daisuke.shimizu/workspace/go-clean-arch-study/test.db r/w

まとめ

SQLite をそんなにちゃんと触ったことがなかったので、ネットの記事等をざっと見つつ、手元で操作してみた。 面倒なインストール作業が不要で、データはファイルベースで管理しつつ、データベースとしての機能は普通に使えるので、少し試すには簡単だと改めて実感した。

参考