#3 SQLite 适用一切场景

2026-08-26

在 Dr. Raphael A. Bauer 发表《PostgreSQL for Everything》之后,JoeCode 发表了一篇《SQLite for Everything》调侃式回应(作者强调自己同样喜欢 PostgreSQL,但认为 SQLite 被严重低估)。
参考:PostgreSQL 适用一切场景

作者的核心观点:很多团队为了"看起来像生产系统"而引入的一整排基础设施(搜索、队列、缓存、向量库、图库、微服务……),在大多数项目里其实一个 SQLite 单文件就能顶替。
开发新项目的时候,先判断"它能跑在单机+单文件上吗"——能就先上 SQLite,真撞到写并发或分布式天花板再换重的。大多数业务比开发者以为的更晚才会撞墙,而期间你省掉的是大量运维工作。

SQLite 三大底层优势

  • 坚如磐石:2000 年发布,公有领域(public domain,不是普通开源),MC/DC 100% 分支覆盖、测试代码是库代码的约 500 倍,官方支持承诺到 2050 年;手机/浏览器/汽车/飞机里都在跑,部署量超过其他数据库总和。
  • 零运行成本:没有 daemon、没有端口、没有 Docker。已绑定在 Linux/Python/Go/Rust/.NET/Android/iOS 里;测试用 :memory: 微秒级拉起,和生产同库同二进制。
  • 极大简化 IT 拓扑:它不止是 RDBMS,还能当全文搜索引擎、文档库、队列、时序库、向量索引、缓存、文件格式、图存储——"少装一个服务"就是少一个要监控/升级/背锅的系统。

"SQLite 替代 X" 对照表

原本的组件 SQLite 怎么顶 关键机制
Solr / Elastic 全文搜索 FTS5(BM25、短语、NEAR、高亮),索引与数据同事务,不会"索引是旧的"
MongoDB JSON 文档存 jsonb、生成列、严格表
Kafka / RabbitMQ 任务队列 一张表 + BEGIN IMMEDIATE + UPDATE…RETURNING 抢单条作业,WAL 下读写不互锁
ClickHouse 时序数据 按时间分区单文件,中等体量够用
向量数据库 AI 检索 sqlite-vec 扩展做 embedding 相似度
Redis 非持久/高性能缓存 进程内点查 ~1µs,比 localhost 跑 Redis 的 ~100µs 快约 100 倍
文件系统 存小文件/BLOB 官方基准:<100KB blob 比裸文件系统更快、省空间
图数据库 关系遍历 递归 CTE
微服务 跨函数调用 直接同进程函数调用 + 本地事务
(彩蛋)PlayStation 5 — 纯玩笑章节

SQLite 的天花板

  • 不支持并发写入:高并发写入(每秒几万条以上)会卡在写锁;多机多写、跨机房分布式写不适合原生 SQLite。
  • 规模边界:超 TB 级数据、百万点/秒时序、需要用户/角色级 ACL 的多租户 SaaS,应换 Postgres/MySQL/ClickHouse 等。
  • 扩展方案:Litestream(WAL 流式备份到 S3)、LiteFS(分布式读)、Turso / Cloudflare D1 / rqlite(托管 SQLite)可缓解部分限制,但不改变单写本质。

#2 SQLite WAL 模式

2024-05-02

许多人对 SQLite 存在误解,认为“每次写入都会锁定整个数据库”。但实际上,只需一个简单的配置,就能让它轻松应对数千并发用户——这就是Write-Ahead Logging (WAL) 模式。

#1 SQLite

2013-07-12

简介

  1. 嵌入式数据库
  2. 第一版 2000 年发布
  3. 公有领域
  4. 实现了大多数 SQL-92 标准,包括事务(ACID)
  5. 使用最广泛的 DB 引擎

命令

.help
.databases
.tables
.shema <tableName> # show sql
.fullschema
.quit

.mode list      # 默认,没有头部,竖线隔开
.mode tabs      # tab 隔开
.mode column    # 可读性强些
.mode line      # 像 MySQL \G
sqlite> .show
        echo: off
         eqp: off
     explain: auto
     headers: off
        mode: list
   nullvalue: ""
      output: stdout
colseparator: "|"
rowseparator: "\n"
       stats: off
       width:
    filename: /tmp/history.db

sqlite> .dbinfo main
database page size:  4096
write format:        2
read format:         2
reserved bytes:      0
file change counter: 3110
database page count: 6669
freelist page count: 0
schema cookie:       7
schema format:       4
default cache size:  0
autovacuum top root: 0
incremental vacuum:  0
text encoding:       1 (utf8)
user version:        2
application id:      0
software version:    3033000
number of tables:    4
number of indexes:   6
number of triggers:  0
number of views:     0
schema size:         785
data version         2

常用操作

查看表结构

.schema tablename
pragma dbname.table_info(tablename)
pragma dbname.table_xinfo(tablename) # 包含虚拟表中的隐藏列
SELECT * FROM sqlite_master WHERE tbl_name = 'tablename';

工具

  1. SQLite Database Browser
  2. heidisql
  3. 浏览器拓展
  4. Navicat for SQLite

附:sqlite help

sqlite> .help
.archive ...             Manage SQL archives
.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.
.load FILE ?ENTRY?       Load an extension library
.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