Skip to content

DuckDB CLI API

CLI 就是命令行界面程序,DuckDB 提供了一个单一的、跨平台的、无依赖的可执行二进制文件。他是基于 SQLite 命令行 Shell 改写而来的,因此整个使用方式非常类似于 SQLite。最大的区别可能就是 SQL 语法遵循 PostgreSQL,并且了一些特有的过程函数。

安装

DuckDB release释出了各个平台的二进制文件,只需要放置到 PATH 路径下就可以了。

Note

这些释出的版本都是正式版,如果想要使用开发版甚至 nightly 版可以自行编译

基本用法

Bash
# FILENAME: DuckDB 数据库文件,如果没有指定则使用内存数据库
# OPTIONS: 设置
# 比较重要的设置如下
# -readonly : 以只读模式打开数据库,DuckDB 并发模型控制
# -c COMMAND : 运行 COMMAND 后退出
duckdb [OPTIONS] [FILENAME]

Tips

可用选项查看完整选项列表

非交互式使用

CLI 程序提供了几种非交互使用的方式,他们读取文件或输入并得到结果后立即退出:

  • 通过将文件内容以管道的方式传递给 duckdb:
Bash
duckdb < example/init.sql

    ┌─────────┐
      name        varchar     ├─────────┤
     0 rows      └─────────┘
  • 直接从命令行传入的 SQL 字符串来执行命令,如果是内存数据库需要指定 :memory::
Bash
duckdb :memory: "SELECT 42 AS the_answer"

    ┌────────────┐
     the_answer        int32        ├────────────┤
             42     └────────────┘
  • -c COMMAND 来执行,他不需要指定 :memory::
Bash
duckdb -c "SELECT 42 AS the_answer"

    ┌────────────┐
     the_answer        int32        ├────────────┤
             42     └────────────┘

-init init.sql: 指定初始化文件

通过 -init xxx.sql 来指定初始化文件,其中甚至可以包括Dot Commands命令。他的使用场景:

  • 设置一些 .mode 等不同于默认设置的常规设置
  • 通过 ATTACH 来引入其他数据库作为附加数据库

Tips

我们可用通过 alias 来实现一些固定的 init 脚本

Tips

一些不是经常使用的更推荐通过.read file来引入脚本

执行 SQL

运行 CLI 后会进入交互模式,其中就可以执行 SQL 语句了,结果默认会输出到 stdout 上。

Note

DuckDB 的 SQL 语法兼容 PostgreSQL,而且几乎支持所有主流的 SQL 语法

CLI Dot Commands

就像 SQLite 中能够使用以点开头的命令一样, DuckDB 同样支持:

Bash
duckdb -c .help

    .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
    .columns                 Column-wise rendering of query results
    .constant ?COLOR?        Sets the syntax highlighting color used for constant values
    .constantcode ?CODE?     Sets the syntax highlighting terminal code used for constant values
    .databases               List names and files of attached databases
    .dump ?TABLE?            Render database content as SQL
    .echo on|off             Turn command echo on or off
    .excel                   Display the output of next command in spreadsheet
    .edit                    Opens an external text editor to edit a query.
    .exit ?CODE?             Exit this program with return-code CODE
    .explain ?on|off|auto?   Change the EXPLAIN formatting mode.  Default: auto
    .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
    .highlight [on|off]      Toggle syntax highlighting in the shell on/off
    .import FILE TABLE       Import data from FILE into TABLE
    .indexes ?TABLE?         Show names of indexes
    .keyword ?COLOR?         Sets the syntax highlighting color used for keywords
    .keywordcode ?CODE?      Sets the syntax highlighting terminal code used for keywords
    .lint OPTIONS            Report potential schema issues.
    .log FILE|off            Turn logging on or off.  FILE can be stderr/stdout
    .maxrows COUNT           Sets the maximum number of rows for display (default: 40). Only for duckbox mode.
    .maxwidth COUNT          Sets the maximum width in characters. 0 defaults to terminal width. Only for duckbox mode.
    .mode MODE ?TABLE?       Set output mode
    .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
    .prompt MAIN CONTINUE    Replace the standard prompts
    .quit                    Exit this program
    .read FILE               Read input from FILE
    .rows                    Row-wise rendering of query results (default)
    .schema ?PATTERN?        Show the CREATE statements matching PATTERN
    .separator COL ?ROW?     Change the column and row separators
    .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
    .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'
    .timer on|off            Turn SQL timer on or off
    .width NUM1 NUM2 ...     Set minimum column widths for columnar output

.mode 和 .output 来输出特定格式的文件

.output 能够指定文件来输出结果,它可以配合 .mode 中指定的输出格式来实现导出结果到文件。其中 .mode 指定输出的格式,其中比较常见的包括:

模式 描述
csv 逗号分隔符
duckbox 默认的模式
insert SQL INSERT 语句
json JSON数组
jsonlines 一行输出的 json 格式

首先设置 .mode 然后设置 .output 到文件,之后就可以实现导出数据到文件了:

SQL
.mode csv
.output my_results.md
SELECT 'taking flight' from output_table;
-- 重新切换输出到 stdout
.output
SELECT 'back to the terminal' from displayed_column;

.exit 退出

退出 CLI 官方的方法是执行.exit,当然直接使用Ctrl + C命令也可以。

如果指定了 FILENAME 即使用了持久性数据库文件,退出操作会执行一系列工作:

  1. 自动 checkpoint 并将最新的编辑保存到磁盘中然
  2. 删除.wal预写日志文件
  3. 将所有的 temp 文件合并到单个数据库文件中
  4. 关闭 duckdb 释放内存