diff --git a/.github/actions/setup-sqlite-version/action.yml b/.github/actions/setup-sqlite-version/action.yml
new file mode 100644
index 0000000..fdbc71c
--- /dev/null
+++ b/.github/actions/setup-sqlite-version/action.yml
@@ -0,0 +1,39 @@
+name: "Setup SQLite version"
+description: "Build and activate a specific SQLite version from its amalgamation archive"
+inputs:
+ version:
+ description: "The SQLite version to install"
+ required: true
+ cflags:
+ description: "CFLAGS to use when compiling SQLite"
+ required: false
+ default: ""
+ skip-activate:
+ description: "Set to true to skip modifying the library path"
+ required: false
+ default: "false"
+ fallback-urls:
+ description: "Whitespace-separated fallback download URLs to try after sqlite.org"
+ required: false
+ default: ""
+outputs:
+ sqlite-location:
+ description: "Directory containing the compiled SQLite library"
+ value: ${{ steps.build.outputs.sqlite-location }}
+runs:
+ using: "composite"
+ steps:
+ - shell: bash
+ run: mkdir -p "$RUNNER_TEMP/sqlite-versions/downloads"
+ - uses: actions/cache@v6
+ with:
+ path: ${{ runner.temp }}/sqlite-versions/downloads
+ key: setup-sqlite-version-${{ inputs.version }}-amalgamation-v1
+ - id: build
+ shell: bash
+ run: bash "$GITHUB_ACTION_PATH/setup-sqlite-version.sh"
+ env:
+ SQLITE_VERSION: ${{ inputs.version }}
+ SQLITE_CFLAGS: ${{ inputs.cflags }}
+ SQLITE_SKIP_ACTIVATE: ${{ inputs.skip-activate }}
+ SQLITE_EXTRA_FALLBACK_URLS: ${{ inputs.fallback-urls }}
diff --git a/.github/actions/setup-sqlite-version/setup-sqlite-version.sh b/.github/actions/setup-sqlite-version/setup-sqlite-version.sh
new file mode 100644
index 0000000..0df7290
--- /dev/null
+++ b/.github/actions/setup-sqlite-version/setup-sqlite-version.sh
@@ -0,0 +1,144 @@
+#!/usr/bin/env bash
+set -euo pipefail
+
+version_spec="${SQLITE_VERSION:?SQLITE_VERSION is required}"
+cflags="${SQLITE_CFLAGS:-}"
+skip_activate="${SQLITE_SKIP_ACTIVATE:-false}"
+extra_fallback_urls="${SQLITE_EXTRA_FALLBACK_URLS:-}"
+
+case "$version_spec" in
+ 3.46 | 3.46.0)
+ sqlite_version="3.46.0"
+ sqlite_year="2024"
+ amalgamation_id="3460000"
+ builtin_fallback_urls="https://static.simonwillison.net/static/2026/sqlite-amalgamation-3460000.zip"
+ ;;
+ 3.23.1)
+ sqlite_version="3.23.1"
+ sqlite_year="2018"
+ amalgamation_id="3230100"
+ builtin_fallback_urls="https://static.simonwillison.net/static/2026/sqlite-amalgamation-3230100.zip"
+ ;;
+ *)
+ echo "::error::Unsupported SQLite version '$version_spec'. Add its release year and amalgamation id to $GITHUB_ACTION_PATH/setup-sqlite-version.sh."
+ exit 1
+ ;;
+esac
+
+case "$(uname -s)" in
+ Linux)
+ library_name="libsqlite3.so.0"
+ library_path_var="LD_LIBRARY_PATH"
+ ;;
+ Darwin)
+ library_name="libsqlite3.dylib"
+ library_path_var="DYLD_LIBRARY_PATH"
+ ;;
+ *)
+ echo "::error::Unsupported platform $(uname -s)"
+ exit 1
+ ;;
+esac
+
+runner_temp="${RUNNER_TEMP:-}"
+if [ -z "$runner_temp" ]; then
+ runner_temp="$(mktemp -d)"
+fi
+
+filename="sqlite-amalgamation-${amalgamation_id}"
+official_url="https://www.sqlite.org/${sqlite_year}/${filename}.zip"
+download_dir="${runner_temp}/sqlite-versions/downloads"
+source_root="${runner_temp}/sqlite-versions/source"
+source_dir="${source_root}/${filename}"
+build_dir="${runner_temp}/sqlite-versions/build/${sqlite_version}"
+archive_path="${download_dir}/${filename}.zip"
+
+mkdir -p "$download_dir" "$source_root" "$build_dir"
+
+download_archive() {
+ local url
+ local candidate_path="${archive_path}.tmp"
+ local urls=("$official_url")
+
+ for url in $builtin_fallback_urls $extra_fallback_urls; do
+ urls+=("$url")
+ done
+
+ rm -f "$candidate_path"
+ for url in "${urls[@]}"; do
+ echo "Downloading SQLite ${sqlite_version} amalgamation from ${url}"
+ if curl \
+ --fail \
+ --location \
+ --show-error \
+ --retry 5 \
+ --retry-delay 2 \
+ --retry-max-time 180 \
+ --retry-all-errors \
+ --connect-timeout 20 \
+ --max-time 240 \
+ --output "$candidate_path" \
+ "$url"; then
+ mv "$candidate_path" "$archive_path"
+ return 0
+ fi
+
+ echo "::warning::Download failed from ${url}"
+ rm -f "$candidate_path"
+ done
+
+ echo "::error::Could not download SQLite ${sqlite_version} amalgamation"
+ return 1
+}
+
+if [ ! -f "${source_dir}/sqlite3.c" ]; then
+ if [ ! -f "$archive_path" ]; then
+ download_archive
+ fi
+
+ rm -rf "$source_dir"
+ unzip -q "$archive_path" -d "$source_root"
+fi
+
+if [ ! -f "${source_dir}/sqlite3.c" ]; then
+ echo "::error::Expected ${source_dir}/sqlite3.c after extracting ${archive_path}"
+ exit 1
+fi
+
+read -r -a cflag_args <<< "$cflags"
+
+echo "Compiling SQLite ${sqlite_version} to ${build_dir}/${library_name}"
+gcc \
+ -fPIC \
+ -shared \
+ "${cflag_args[@]}" \
+ "${source_dir}/sqlite3.c" \
+ "-I${source_dir}" \
+ -o "${build_dir}/${library_name}"
+
+if [ "$library_name" = "libsqlite3.so.0" ]; then
+ ln -sf "$library_name" "${build_dir}/libsqlite3.so"
+fi
+
+if [ -n "${GITHUB_OUTPUT:-}" ]; then
+ echo "sqlite-location=${build_dir}" >> "$GITHUB_OUTPUT"
+else
+ echo "sqlite-location=${build_dir}"
+fi
+
+case "$(printf '%s' "$skip_activate" | tr '[:upper:]' '[:lower:]')" in
+ true | 1 | yes)
+ echo "Skipping ${library_path_var} activation"
+ ;;
+ *)
+ existing_value="${!library_path_var:-}"
+ if [ -n "${GITHUB_ENV:-}" ]; then
+ if [ -n "$existing_value" ]; then
+ echo "${library_path_var}=${build_dir}:${existing_value}" >> "$GITHUB_ENV"
+ else
+ echo "${library_path_var}=${build_dir}" >> "$GITHUB_ENV"
+ fi
+ fi
+ echo "Added ${build_dir} to ${library_path_var}"
+ ;;
+esac
diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml
index a37907a..23b23bd 100644
--- a/.github/workflows/publish.yml
+++ b/.github/workflows/publish.yml
@@ -9,24 +9,19 @@ jobs:
runs-on: ${{ matrix.os }}
strategy:
matrix:
- python-version: ["3.7", "3.8", "3.9", "3.10", "3.11"]
+ python-version: ["3.10", "3.11", "3.12", "3.13", "3.14"]
os: [ubuntu-latest, windows-latest, macos-latest]
steps:
- - uses: actions/checkout@v3
+ - uses: actions/checkout@v7
- name: Set up Python ${{ matrix.python-version }}
- uses: actions/setup-python@v4
+ uses: actions/setup-python@v6
with:
python-version: ${{ matrix.python-version }}
- - uses: actions/cache@v3
- name: Configure pip caching
- with:
- path: ~/.cache/pip
- key: ${{ runner.os }}-pip-${{ hashFiles('**/setup.py') }}
- restore-keys: |
- ${{ runner.os }}-pip-
+ cache: pip
+ cache-dependency-path: pyproject.toml
- name: Install dependencies
run: |
- pip install -e '.[test]'
+ pip install . --group dev
- name: Run tests
run: |
pytest
@@ -34,25 +29,20 @@ jobs:
runs-on: ubuntu-latest
needs: [test]
steps:
- - uses: actions/checkout@v3
+ - uses: actions/checkout@v7
- name: Set up Python
- uses: actions/setup-python@v4
+ uses: actions/setup-python@v6
with:
- python-version: '3.11'
- - uses: actions/cache@v3
- name: Configure pip caching
- with:
- path: ~/.cache/pip
- key: ${{ runner.os }}-publish-pip-${{ hashFiles('**/setup.py') }}
- restore-keys: |
- ${{ runner.os }}-publish-pip-
+ python-version: '3.14'
+ cache: pip
+ cache-dependency-path: pyproject.toml
- name: Install dependencies
run: |
- pip install setuptools wheel twine
+ pip install build twine
- name: Publish
env:
TWINE_USERNAME: __token__
TWINE_PASSWORD: ${{ secrets.PYPI_TOKEN }}
run: |
- python setup.py sdist bdist_wheel
+ python -m build
twine upload dist/*
diff --git a/.github/workflows/spellcheck.yml b/.github/workflows/spellcheck.yml
index 8a86cd2..2afa7b7 100644
--- a/.github/workflows/spellcheck.yml
+++ b/.github/workflows/spellcheck.yml
@@ -6,21 +6,16 @@ jobs:
spellcheck:
runs-on: ubuntu-latest
steps:
- - uses: actions/checkout@v2
- - name: Set up Python ${{ matrix.python-version }}
- uses: actions/setup-python@v2
+ - uses: actions/checkout@v4
+ - name: Set up Python
+ uses: actions/setup-python@v5
with:
- python-version: 3.9
- - uses: actions/cache@v2
- name: Configure pip caching
- with:
- path: ~/.cache/pip
- key: ${{ runner.os }}-pip-${{ hashFiles('**/setup.py') }}
- restore-keys: |
- ${{ runner.os }}-pip-
+ python-version: "3.12"
+ cache: pip
+ cache-dependency-path: pyproject.toml
- name: Install dependencies
run: |
- pip install -e '.[docs]'
+ pip install . --group docs
- name: Check spelling
run: |
codespell docs/*.rst --ignore-words docs/codespell-ignore-words.txt
diff --git a/.github/workflows/test-coverage.yml b/.github/workflows/test-coverage.yml
index 0681f66..7668f1b 100644
--- a/.github/workflows/test-coverage.yml
+++ b/.github/workflows/test-coverage.yml
@@ -12,24 +12,19 @@ jobs:
runs-on: ubuntu-latest
steps:
- name: Check out repo
- uses: actions/checkout@v2
+ uses: actions/checkout@v7
- name: Set up Python
- uses: actions/setup-python@v2
+ uses: actions/setup-python@v6
with:
- python-version: 3.9
- - uses: actions/cache@v2
- name: Configure pip caching
- with:
- path: ~/.cache/pip
- key: ${{ runner.os }}-pip-${{ hashFiles('**/setup.py') }}
- restore-keys: |
- ${{ runner.os }}-pip-
+ python-version: "3.11"
+ cache: pip
+ cache-dependency-path: pyproject.toml
- name: Install SpatiaLite
run: sudo apt-get install libsqlite3-mod-spatialite
- name: Install Python dependencies
run: |
python -m pip install --upgrade pip
- python -m pip install -e .[test]
+ python -m pip install . --group dev
python -m pip install pytest-cov
- name: Run tests
run: |-
diff --git a/.github/workflows/test-sqlite-support.yml b/.github/workflows/test-sqlite-support.yml
new file mode 100644
index 0000000..f195cba
--- /dev/null
+++ b/.github/workflows/test-sqlite-support.yml
@@ -0,0 +1,41 @@
+name: Test SQLite versions
+
+on: [push, pull_request]
+
+permissions:
+ contents: read
+
+jobs:
+ test:
+ runs-on: ${{ matrix.platform }}
+ continue-on-error: true
+ strategy:
+ matrix:
+ platform: [ubuntu-latest]
+ python-version: ["3.10"]
+ sqlite-version: [
+ "3.46",
+ "3.23.1", # 2018-04-10, before UPSERT
+ ]
+ steps:
+ - uses: actions/checkout@v7
+ - name: Set up Python ${{ matrix.python-version }}
+ uses: actions/setup-python@v6
+ with:
+ python-version: ${{ matrix.python-version }}
+ allow-prereleases: true
+ cache: pip
+ cache-dependency-path: pyproject.toml
+ - name: Set up SQLite ${{ matrix.sqlite-version }}
+ uses: ./.github/actions/setup-sqlite-version
+ with:
+ version: ${{ matrix.sqlite-version }}
+ cflags: "-DSQLITE_ENABLE_DESERIALIZE -DSQLITE_ENABLE_FTS5 -DSQLITE_ENABLE_FTS4 -DSQLITE_ENABLE_FTS3_PARENTHESIS -DSQLITE_ENABLE_RTREE -DSQLITE_ENABLE_JSON1"
+ - run: python3 -c "import sqlite3; print(sqlite3.sqlite_version)"
+ - name: Install dependencies
+ run: |
+ pip install . --group dev
+ pip freeze
+ - name: Run tests
+ run: |
+ python -m pytest
diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml
index 2e706df..923de2e 100644
--- a/.github/workflows/test.yml
+++ b/.github/workflows/test.yml
@@ -10,25 +10,21 @@ jobs:
runs-on: ${{ matrix.os }}
strategy:
matrix:
- python-version: ["3.7", "3.8", "3.9", "3.10", "3.11"]
+ python-version: ["3.10", "3.11", "3.12", "3.13", "3.14", "3.15-dev"]
numpy: [0, 1]
- os: [ubuntu-latest, macos-latest, windows-latest]
+ os: [ubuntu-latest, macos-latest, windows-latest, macos-14]
steps:
- - uses: actions/checkout@v3
+ - uses: actions/checkout@v7
- name: Set up Python ${{ matrix.python-version }}
- uses: actions/setup-python@v4
+ uses: actions/setup-python@v6
with:
python-version: ${{ matrix.python-version }}
- - uses: actions/cache@v3
- name: Configure pip caching
- with:
- path: ~/.cache/pip
- key: ${{ runner.os }}-pip-${{ hashFiles('**/setup.py') }}
- restore-keys: |
- ${{ runner.os }}-pip-
+ allow-prereleases: true
+ cache: pip
+ cache-dependency-path: pyproject.toml
- name: Install dependencies
run: |
- pip install -e '.[test,mypy,flake8]'
+ pip install . --group dev
- name: Optionally install numpy
if: matrix.numpy == 1
run: pip install numpy
@@ -42,12 +38,20 @@ jobs:
- name: Run tests
run: |
pytest -v
+ - name: Run autocommit tests just on 3.14/Ubuntu
+ if: matrix.os == 'ubuntu-latest' && matrix.python-version == '3.14'
+ run: pytest --sqlite-autocommit
- name: run mypy
run: mypy sqlite_utils tests
- name: run flake8
run: flake8
+ - name: run ty
+ if: matrix.os != 'windows-latest' && matrix.python-version == '3.14'
+ run: |
+ pip install uv
+ uv run ty check sqlite_utils
- name: Check formatting
run: black . --check
- name: Check if cog needs to be run
run: |
- cog --check README.md docs/*.rst
+ cog --check --diff README.md docs/*.rst
diff --git a/.gitignore b/.gitignore
index 7947f33..5b5d2c6 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,4 +1,5 @@
.venv
+dist
build
*.db
__pycache__/
@@ -14,9 +15,10 @@ venv
.schema
.vscode
.hypothesis
+.claude/
Pipfile
Pipfile.lock
-pyproject.toml
+uv.lock
tests/*.dylib
tests/*.so
tests/*.dll
diff --git a/.gitpod.yml b/.gitpod.yml
deleted file mode 100644
index fe8ba1e..0000000
--- a/.gitpod.yml
+++ /dev/null
@@ -1,2 +0,0 @@
-tasks:
-- init: pip install '.[test]'
\ No newline at end of file
diff --git a/.readthedocs.yaml b/.readthedocs.yaml
index ce66cbe..08c2f81 100644
--- a/.readthedocs.yaml
+++ b/.readthedocs.yaml
@@ -3,10 +3,15 @@ version: 2
sphinx:
configuration: docs/conf.py
-python:
- version: "3.8"
- install:
- - method: pip
- path: .
- extra_requirements:
- - docs
+build:
+ os: ubuntu-24.04
+ tools:
+ python: "3.13"
+ jobs:
+ install:
+ - pip install --upgrade pip
+ - pip install . --group docs
+
+formats:
+- pdf
+- epub
diff --git a/Justfile b/Justfile
index 66863f6..be41523 100644
--- a/Justfile
+++ b/Justfile
@@ -1,29 +1,34 @@
# Run tests and linters
@default: test lint
-# Setup project
-@init:
- pipenv run pip install -e '.[test,docs,mypy,flake8]'
-
# Run pytest with supplied options
@test *options:
- pipenv run pytest {{options}}
+ uv run pytest {{options}}
-# Run linters: black, flake8, mypy, cog
+@run *options:
+ uv run -- {{options}}
+
+# Run linters: black, flake8, mypy, ty, cog
@lint:
- pipenv run black . --check
- pipenv run flake8
- pipenv run mypy sqlite_utils tests
- pipenv run cog --check README.md docs/*.rst
+ just run black . --check
+ uv run flake8
+ uv run mypy sqlite_utils tests
+ uv run ty check sqlite_utils
+ uv run cog --check README.md docs/*.rst
+ uv run --group docs codespell docs/*.rst --ignore-words docs/codespell-ignore-words.txt
+ uv run --group docs codespell sqlite_utils --ignore-words docs/codespell-ignore-words.txt
# Rebuild docs with cog
@cog:
- pipenv run cog -r README.md docs/*.rst
+ uv run --group docs cog -r README.md docs/*.rst
# Serve live docs on localhost:8000
@docs: cog
- cd docs && pipenv run make livehtml
+ #!/usr/bin/env bash
+ cd docs
+ uv run --group docs make livehtml
+
# Apply Black
@black:
- pipenv run black .
+ uv run black .
diff --git a/README.md b/README.md
index 49a26ed..c444c64 100644
--- a/README.md
+++ b/README.md
@@ -18,8 +18,12 @@ Python CLI utility and library for manipulating SQLite databases.
- [Configure SQLite full-text search](https://sqlite-utils.datasette.io/en/stable/cli.html#configuring-full-text-search) against your database tables and run search queries against them, ordered by relevance
- Run [transformations against your tables](https://sqlite-utils.datasette.io/en/stable/cli.html#transforming-tables) to make schema changes that SQLite `ALTER TABLE` does not directly support, such as changing the type of a column
- [Extract columns](https://sqlite-utils.datasette.io/en/stable/cli.html#extracting-columns-into-a-separate-table) into separate tables to better normalize your existing data
+- [Manage database migrations](https://sqlite-utils.datasette.io/en/stable/migrations.html) using Python migration files and the `sqlite-utils migrate` command
+- [Install plugins](https://sqlite-utils.datasette.io/en/stable/plugins.html) to add custom SQL functions and additional features
-Read more on my blog, in this series of posts on [New features in sqlite-utils](https://simonwillison.net/series/sqlite-utils-features/) and other [entries tagged sqliteutils](https://simonwillison.net/tags/sqliteutils/).
+Upgrading from sqlite-utils 3.x? See the [4.0 upgrade guide](https://sqlite-utils.datasette.io/en/stable/upgrading.html#upgrading-from-3-x-to-4-0).
+
+Read more on my blog, in this series of posts on [New features in sqlite-utils](https://simonwillison.net/series/sqlite-utils-features/) and other [entries tagged sqlite-utils](https://simonwillison.net/tags/sqlite-utils/).
## Installation
diff --git a/docs/_templates/base.html b/docs/_templates/base.html
index a9e670e..a253a46 100644
--- a/docs/_templates/base.html
+++ b/docs/_templates/base.html
@@ -3,4 +3,40 @@
{% block site_meta %}
{{ super() }}
-{% endblock %}
\ No newline at end of file
+{% endblock %}
+
+{% block scripts %}
+{{ super() }}
+
+
+{% endblock %}
diff --git a/docs/changelog.rst b/docs/changelog.rst
index c3c12f2..a853aa2 100644
--- a/docs/changelog.rst
+++ b/docs/changelog.rst
@@ -4,6 +4,350 @@
Changelog
===========
+.. _v3_39_1:
+
+3.39.1 (2026-07-25)
+-------------------
+
+- Fixed a bug where ``table.delete_where()`` left the connection in an open transaction, causing deleted rows to be silently restored when the connection was closed. (:issue:`815`)
+
+.. _v4_1_1:
+
+4.1.1 (2026-07-12)
+------------------
+
+- ``table.transform()`` now raises a ``TransactionError`` if called while a transaction is open with ``PRAGMA foreign_keys`` enabled and the table is referenced by foreign keys with destructive ``ON DELETE`` actions - ``CASCADE``, ``SET NULL`` or ``SET DEFAULT``. The pragma cannot be changed inside a transaction, so previously dropping the old table as part of the transform could fire those actions and silently delete or modify referencing rows. See :ref:`python_api_transform_foreign_keys_transactions` for details and workarounds. (:issue:`794`)
+- The :ref:`CLI ` and :ref:`Python API ` documentation now cross-reference each other: CLI sections link to the equivalent Python API functionality and Python API sections link back to the corresponding CLI command. (:issue:`791`)
+.. _v4_1:
+
+4.1 (2026-07-11)
+----------------
+
+- ``sqlite-utils insert`` and ``sqlite-utils upsert`` now accept a ``--code`` option for :ref:`providing a block of Python code ` (or a path to a ``.py`` file) that defines a ``rows()`` function or ``rows`` iterable of rows to insert, as an alternative to importing from a file. (:issue:`684`)
+- ``sqlite-utils insert`` and ``sqlite-utils upsert`` now accept ``--type column-name type`` to :ref:`override the type automatically chosen when the table is created `. This is useful for CSV or TSV columns such as ZIP codes that look like integers but should be stored as ``TEXT`` to preserve leading zeros. (:issue:`131`)
+- New ``table.drop_index(name)`` method and ``sqlite-utils drop-index`` command for dropping an index by name. Both accept ``ignore=True``/``--ignore`` to ignore a missing index. (:issue:`626`)
+- ``sqlite-utils query`` can now read the SQL query from standard input by passing ``-`` in place of the query, for example ``echo "select * from dogs" | sqlite-utils query dogs.db -``. (:issue:`765`)
+- ``sqlite-utils upsert`` can now infer the primary key of an existing table, so ``--pk`` can be omitted when upserting into a table that already has a primary key.
+- ``table.transform()`` and ``table.transform_sql()`` now accept ``strict=True`` or ``strict=False`` to change a table's `SQLite strict mode `__. Omitting the option preserves the existing mode. (:issue:`787`)
+- The ``sqlite-utils transform`` command now accepts ``--strict`` and ``--no-strict`` to change a table's strict mode. (:issue:`787`)
+
+.. _v4_0:
+
+4.0 (2026-07-07)
+----------------
+
+The 4.0 release includes some minor backwards-incompatible fixes (hence the major version number bump) and introduces three major new features:
+
+- :ref:`Database migrations `, providing a structured mechanism for evolving a project's schema over time. (:issue:`752`)
+- :ref:`Nested transaction support ` via ``db.atomic()``, plus numerous improvements to how transactions work across the library. (:issue:`755`)
+- Support for :ref:`compound foreign keys `, including creation, transformation and introspection through :ref:`table.foreign_keys `. (:issue:`594`)
+
+Other notable changes include:
+
+- Upserts now use SQLite's ``INSERT ... ON CONFLICT ... DO UPDATE SET`` syntax, detect existing table primary keys automatically and reject records that are missing required primary key values. (:issue:`652`)
+- ``db.query()`` now executes immediately and rejects statements that do not return rows; use ``db.execute()`` for writes and DDL.
+- CSV and TSV imports now detect column types by default, while inserts into existing tables preserve those tables' column types. (:issue:`679`)
+- Foreign key handling now preserves ``ON DELETE``/``ON UPDATE`` actions during transforms and resolves referenced primary keys more accurately. (:issue:`530`)
+- Column names passed to Python API methods are now matched case-insensitively, mirroring SQLite's own identifier behavior. (:issue:`760`)
+- The command-line tool now emits UTF-8 JSON output by default, with ``--ascii`` available to restore escaped output. (:issue:`625`)
+- ``table.extract()`` and ``extracts=`` no longer create lookup table records for all-``null`` values. (:issue:`186`)
+
+See :ref:`upgrading_3_to_4` for details on backwards-incompatible changes.
+
+The detailed release notes for the features and fixes shipped during the 4.0 pre-release cycle are available in :ref:`4.0a0 `, :ref:`4.0a1 `, :ref:`4.0rc1 `, :ref:`4.0rc2 `, :ref:`4.0rc3 ` and :ref:`4.0rc4 `.
+
+Bug fixes since 4.0rc4
+~~~~~~~~~~~~~~~~~~~~~~
+
+- Fixed 4.0 regressions in ``insert``/``upsert`` against tables that use SQLite's implicit ``rowid`` primary key. Passing ``pk="rowid"``, ``pk="_rowid_"`` or ``pk="oid"`` now works again for rowid tables, and ``last_pk`` is set correctly. (:issue:`781`)
+- Fixed ``insert(..., ignore=True)`` and ``insert_all(..., ignore=True)`` so an ignored insert that conflicts with an existing primary key row now reports that existing row in ``last_rowid`` and ``last_pk`` where possible. This also works for compound primary keys and list-mode inserts. (:issue:`783`)
+
+.. _v4_0rc4:
+
+4.0rc4 (2026-07-06)
+-------------------
+
+- **Breaking change**: ``table.extract()`` - and the ``sqlite-utils extract`` command - no longer extract rows where every extracted column is ``null``. Those rows now keep a ``null`` value in the new foreign key column instead of pointing at an all-``null`` record in the lookup table. When extracting multiple columns, rows are still extracted if at least one of the columns has a value. (:issue:`186`)
+- The ``extracts=`` option to ``table.insert()`` and friends no longer creates a lookup table record for ``None`` values - the column value stays ``null``. Previously every batch of inserted rows containing a ``None`` value would add a duplicate ``null`` record to the lookup table.
+- Fixed a bug where ``table.lookup()`` inserted a duplicate row on every call if any of the lookup values were ``None``. Lookup values are now compared using ``IS`` so that ``None`` values match existing rows correctly.
+- JSON output from the command-line tool no longer escapes non-ASCII characters, so ``sqlite-utils data.db "select '日本語' as text"`` now outputs ``[{"text": "日本語"}]``. This matches how values were already stored by ``insert`` and how CSV/TSV output already behaved. A new ``--ascii`` option restores the previous behavior of escaping non-ASCII characters, for output destinations that cannot handle UTF-8 - see :ref:`cli_query_json_ascii`. The option is available on the ``query``, ``rows``, ``search``, ``tables``, ``views``, ``triggers``, ``indexes`` and ``memory`` commands. The ``convert --multi --dry-run`` preview and ``plugins`` output also no longer escape non-ASCII characters. (:issue:`625`)
+- ``--no-headers`` now omits the header row from ``--fmt`` and ``--table`` output, not just CSV and TSV output. (:issue:`566`)
+- ``table.insert_all(..., pk=...)`` now raises ``InvalidColumns`` if ``pk=`` names columns that do not exist in an existing table. Previously this behaved inconsistently, with single-row inserts raising a ``KeyError`` while other row counts succeeded. (:issue:`732`)
+- Fixed an ``IndexError`` from ``table.insert(..., pk=..., ignore=True)`` when an ignored insert followed writes to another table on the same connection. ``last_pk`` is now populated from the explicit primary key value instead of looking up a stale ``lastrowid``. (:issue:`554`)
+- Fixed a bug where a failed write statement executed with ``db.execute()`` left the driver's implicit transaction open. Every subsequent write then joined that phantom transaction, which nothing committed, so their work was silently rolled back when the connection was closed. The implicit transaction opened by a failed statement is now rolled back before the exception is raised. A failed write inside a transaction opened with ``db.begin()`` or ``db.atomic()`` leaves that transaction open and untouched, as before.
+- Fixed a bug where transaction-control statements prefixed with an empty statement - ``db.query("; COMMIT")`` - or a UTF-8 byte order mark slipped past the check that rejects them, committing the caller's open transaction before raising a confusing ``OperationalError``. The keyword scanner used by ``db.query()`` and ``db.execute()`` now skips leading ``;`` and byte order marks, matching what the ``sqlite3`` driver tolerates before the first token, so these statements are rejected with a ``ValueError`` without being executed. The same fix means ``db.execute("; BEGIN")`` no longer auto-commits the transaction it just opened.
+- Documented a limitation of ``db.query()``: a ``PRAGMA`` statement that returns no rows raises a ``ValueError`` but still takes effect, because PRAGMA statements run outside the savepoint guard used to roll back other rejected statements. Use ``db.execute()`` for row-less PRAGMA statements.
+- Fixed exception masking when a statement destroys the enclosing transaction. An error such as a ``RAISE(ROLLBACK)`` trigger or ``INSERT OR ROLLBACK`` conflict rolls back the whole transaction, destroying every savepoint - the cleanup in ``db.atomic()`` and ``db.query()`` then failed with ``OperationalError: no such savepoint`` (or ``cannot rollback - no transaction is active``), hiding the original ``IntegrityError`` from code that tried to catch it. Cleanup now checks whether a transaction is still open first, so the original exception propagates.
+- ``sqlite-utils migrate --list`` is now read-only even when the migrations file uses the legacy ``sqlite_migrate.Migrations`` class, whose listing methods create the ``_sqlite_migrations`` table as a side effect. The listing now runs inside a transaction that is rolled back.
+- ``sqlite-utils insert ... --pk `` and ``sqlite-utils extract `` now show a clean ``Error:`` message instead of a raw Python traceback. The ``extract`` command also shows a clean error when pointed at a view.
+- Fixed a bug where running ``table.extract()`` more than once against the same lookup table inserted duplicate rows for values containing ``null`` - SQLite unique indexes treat ``NULL`` values as distinct, so ``INSERT OR IGNORE`` alone could not dedupe them. Each repeat extract added another copy that nothing referenced. The insert now uses an ``IS``-based ``NOT EXISTS`` guard so ``null``-containing rows match existing lookup rows.
+- ``db.add_foreign_keys()`` no longer silently ignores requested ``ON DELETE``/``ON UPDATE`` actions when a foreign key with the same columns already exists - it raises ``AlterError`` suggesting ``table.transform()``, since the actions of an existing foreign key cannot be changed in place. Exact duplicates, including actions, are still skipped so repeated calls stay idempotent. The method also now validates that compound foreign keys have the same number of columns on both sides, instead of silently discarding the extra columns.
+- ``db.ensure_autocommit_on()`` now raises ``TransactionError`` if called while a transaction is open. Assigning ``isolation_level`` commits any pending transaction as a side effect, so entering the block silently committed the caller's open transaction and made a later ``rollback()`` a no-op.
+- ``sqlite-utils migrate --stop-before`` now exits with an error if the named migration has already been applied. Previously the name passed validation but was only checked against pending migrations, so every migration after it was silently applied - the exact outcome ``--stop-before`` exists to prevent. ``Migrations.apply(db, stop_before=...)`` raises ``ValueError`` in the same situation, before applying anything.
+- Fixed a regression where ``table.insert(..., pk=..., alter=True)`` raised ``InvalidColumns`` if the primary key column did not exist in the table yet. With ``alter=True`` the check now waits until the record keys are known, so a pk column supplied by the records is added by the alter as it was in 3.x. A pk column found in neither the table nor the records still raises ``InvalidColumns``.
+- Fixed a bug where inserting CSV or TSV data into an existing table rewrote that table's column types to match the incoming file. Type detection is the default in 4.0, so ``sqlite-utils insert data.db places places.csv --csv`` against a table with a ``TEXT`` zip code column would convert the column to ``INTEGER`` and corrupt values with leading zeros - ``"01234"`` became ``1234``. Detected types are now only applied when the ``insert`` or ``upsert`` command creates the table.
+- Fixed ``pks_and_rows_where()`` raising ``AttributeError`` when called on a view, and no longer double-quotes the synthesized ``rowid`` column in its generated SQL - SQLite turns a double-quoted identifier that does not resolve into a string literal, which on a view produced a confusing ``KeyError`` instead of the ``OperationalError`` raised in 3.x. Compound primary keys returned by this method now follow ``PRIMARY KEY`` declaration order.
+- The ``foreign_keys=`` argument to ``create()`` and ``insert()`` accepts a mixed list of ``ForeignKey`` objects, tuples and column name strings again. In 4.0 pre-releases mixing ``ForeignKey`` objects with tuples raised a ``ValueError`` - a regression from 3.x, where ``ForeignKey`` was a ``namedtuple`` and passed the tuple checks.
+- ``ForeignKey`` objects are hashable again. The 4.0 change from ``namedtuple`` to dataclass accidentally made them unhashable, breaking patterns like ``set(table.foreign_keys)`` that worked in 3.x. ``ForeignKey`` is now a frozen dataclass - immutable and hashable, like the namedtuple was.
+- Fixed a bug where compound primary key columns were returned in table column order instead of ``PRIMARY KEY`` declaration order. For a table declared as ``CREATE TABLE other (b TEXT, a TEXT, PRIMARY KEY (a, b))`` an implicit ``FOREIGN KEY (x, y) REFERENCES other`` was introspected as referencing ``(b, a)`` when SQLite resolves it as ``(a, b)`` - running ``transform()`` on such a table then rewrote the schema with the inverted column order, silently reversing the meaning of the constraint and causing foreign key errors on valid data. ``table.pks``, compound foreign key guessing and ``transform()`` now all use the primary key declaration order, and ``transform()`` no longer reorders a compound ``PRIMARY KEY (b, a)`` into table column order.
+
+.. _v4_0rc3:
+
+4.0rc3 (2026-07-05)
+-------------------
+
+Breaking changes
+~~~~~~~~~~~~~~~~
+
+- :ref:`table.foreign_keys ` now returns ``ForeignKey`` objects that are dataclasses rather than ``namedtuple`` instances, so they can no longer be unpacked or indexed as ``(table, column, other_table, other_column)`` tuples - access their fields by name instead. Compound (multi-column) foreign keys are now represented as a single ``ForeignKey`` with ``is_compound=True`` and populated ``columns``/``other_columns`` tuples, where ``column`` and ``other_column`` are ``None``. Previously they were returned as one ``ForeignKey`` per column, misleadingly suggesting several independent foreign keys. See :ref:`upgrading_3_to_4` for details. (:issue:`594`)
+- Removed support for using ``sqlean.py`` as a drop-in replacement for the Python standard library ``sqlite3`` module. ``sqlite-utils`` will now use ``pysqlite3`` if it is installed, otherwise it will use ``sqlite3`` from the standard library.
+- The ``db.ensure_autocommit_off()`` context manager has been renamed to ``db.ensure_autocommit_on()``, because the old name described the opposite of what it did. The method temporarily puts the connection into driver-level autocommit mode - by setting ``isolation_level = None`` - so that statements such as ``PRAGMA journal_mode=wal`` can run outside of an implicit transaction. (:issue:`705`)
+
+Compound foreign key support
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+- Tables can now be created with :ref:`compound foreign keys `, by passing tuples of column names in ``foreign_keys=``: ``foreign_keys=[(("campus_name", "dept_code"), "departments")]``. The referenced columns default to the compound primary key of the other table. Compound keys are rendered as table-level ``FOREIGN KEY`` constraints in the generated schema.
+- ``table.transform()`` now preserves compound foreign keys, applying any column renames to them. Dropping a column that is part of a compound foreign key drops the whole constraint, matching the existing single-column behavior. ``drop_foreign_keys=`` accepts a bare column name - dropping any foreign key that column participates in - or a tuple of columns to target a compound key precisely.
+- ``table.add_foreign_key()`` and ``db.add_foreign_keys()`` accept tuples of column names to add a compound foreign key to an existing table.
+- ``db.index_foreign_keys()`` creates a single composite index for a compound foreign key.
+
+Other foreign key improvements
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+- ``ForeignKey`` now exposes ``on_delete`` and ``on_update`` fields reflecting the foreign key's ``ON DELETE``/``ON UPDATE`` actions, and ``table.transform()`` preserves those actions. Previously a transform silently stripped clauses such as ``ON DELETE CASCADE`` from the table schema.
+- ``table.add_foreign_key()`` accepts new ``on_delete=`` and ``on_update=`` parameters for creating foreign keys with actions, e.g. ``table.add_foreign_key("author_id", "authors", "id", on_delete="CASCADE")``. (:issue:`530`)
+- Foreign keys declared as ``REFERENCES other_table`` with no explicit column are now resolved to the other table's primary key by ``table.foreign_keys``, instead of reporting ``other_column=None``.
+- Fixed a ``TypeError`` when sorting ``ForeignKey`` objects where some were compound.
+
+Case-insensitive column matching
+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+Column names passed to Python API methods are now matched against the table schema case-insensitively, mirroring how SQLite itself treats identifiers. Previously many methods accepted mixed-case identifiers in the SQL they generated but then failed - or silently did nothing - when performing Python-side comparisons against the schema. (:issue:`760`) Fixes include:
+
+- ``table.insert()`` and ``table.upsert()`` now populate ``table.last_pk`` correctly when the ``pk=`` argument uses different casing to the table schema or the record keys - previously this raised a ``KeyError`` after the row had already been written.
+- Upserts no longer raise or misbehave when the casing of ``pk=`` differs from the casing of the record keys. The primary key columns are correctly excluded from the generated ``DO UPDATE SET`` clause.
+- ``table.transform()`` arguments ``types=``, ``rename=``, ``drop=``, ``pk=``, ``not_null=``, ``defaults=``, ``column_order=`` and ``drop_foreign_keys=`` all resolve column names case-insensitively. Previously options like ``rename={"name": "title"}`` against a column called ``Name`` were silently ignored.
+- ``db.create_table(..., transform=True)`` now recognizes existing columns that differ only by case, instead of attempting to add them again and failing with ``duplicate column name``. The casing used in the existing schema is preserved.
+- ``table.lookup()`` returns the primary key value even if ``pk=`` casing differs from the schema, and recognizes existing unique indexes case-insensitively instead of creating redundant ones.
+- ``table.extract()`` and ``table.convert()`` - including ``multi=True`` and ``output=`` - accept column names in any casing.
+- Foreign key columns are validated and recorded using the casing of the actual schema columns, in ``foreign_keys=`` when creating tables, ``db.add_foreign_keys()``, ``table.add_foreign_key()`` and ``table.add_column(fk_col=...)``. Duplicate foreign key detection is also case-insensitive.
+- ``table.create()`` with ``pk=``, ``not_null=``, ``defaults=`` or ``column_order=`` referencing columns using different casing no longer creates an unwanted extra primary key column or raises a ``ValueError``.
+
+Everything else
+~~~~~~~~~~~~~~~
+
+- Fixed a bug where ``table.transform()`` could convert ``DEFAULT TRUE``, ``DEFAULT FALSE`` and ``DEFAULT NULL`` column defaults into quoted string defaults when rebuilding a table. Thanks, `Vincent Gao `__. (`#764 `__)
+
+.. _v4_0rc2:
+
+4.0rc2 (2026-07-04)
+-------------------
+
+Breaking changes:
+
+- Write statements executed with ``db.execute()`` are now committed automatically, unless a transaction is already open in which case they join it. Previously they opened an implicit transaction that stayed open until something committed it - writes appeared to work when read on the same connection but were silently rolled back when the connection closed. Code that relied on rolling back uncommitted ``db.execute()`` writes should use the new ``db.begin()`` method to open an explicit transaction first. The transaction model is documented in full at :ref:`python_api_transactions`.
+- ``db.query()`` now executes its SQL as soon as it is called, rather than waiting until the returned generator is first iterated. Rows are still fetched lazily during iteration. SQL errors are now raised at the call site, statements such as ``INSERT ... RETURNING`` are executed and committed immediately without needing to iterate over their results, and passing a statement that returns no rows - previously a silent no-op - now raises a ``ValueError`` recommending ``db.execute()`` instead. A statement rejected this way is rolled back before the error is raised, so it has no effect on the database.
+- Python API validation errors now raise ``ValueError`` instead of ``AssertionError``. Previously invalid arguments - such as ``create_table()`` with no columns, ``transform()`` on a table that does not exist, or passing both ``ignore=True`` and ``replace=True`` - were rejected using bare ``assert`` statements, which are silently skipped when Python runs with the ``-O`` flag. Code that caught ``AssertionError`` for these cases should catch ``ValueError`` instead.
+- ``table.upsert()`` and ``table.upsert_all()`` now raise ``PrimaryKeyRequired`` if a record is missing a value for any primary key column, or has a value of ``None`` for one. Previously such records - which can never match an existing row - were quietly inserted as brand new rows, or triggered a confusing ``KeyError`` after the insert had already taken place.
+- ``db.enable_wal()`` and ``db.disable_wal()`` now raise a ``sqlite_utils.db.TransactionError`` if called while a transaction is open. Previously they would silently commit the open transaction as a side effect of changing the journal mode, breaking the rollback guarantee of ``db.atomic()`` and of user-managed transactions.
+- The ``View`` class no longer has an ``enable_fts()`` method. It existed only to raise ``NotImplementedError``, since full-text search is not supported for views - calling it now raises ``AttributeError`` instead, and the method no longer appears in the API reference. The ``sqlite-utils enable-fts`` command shows a clean error when pointed at a view.
+- The no-op ``-d/--detect-types`` flag has been removed from the ``insert`` and ``upsert`` commands. Type detection has been the default for CSV/TSV data since 4.0a1, so the flag did nothing - invocations using it should simply drop it. ``--no-detect-types`` remains available to disable detection.
+- ``Database()`` now raises a ``sqlite_utils.db.TransactionError`` if passed a connection created with the Python 3.12+ ``sqlite3.connect(..., autocommit=True)`` or ``autocommit=False`` options. ``commit()`` and ``rollback()`` behave differently on those connections, which previously caused every write made by the library to be silently discarded when the connection closed.
+
+Everything else:
+
+- Fixed a bug where ``table.delete_where()``, ``table.optimize()`` and ``table.rebuild_fts()`` did not commit their changes, leaving the connection inside an open transaction. Their work - and any subsequent writes - could then be silently rolled back when the connection was closed. All three now use ``db.atomic()``, consistent with the other write methods.
+- The ``sqlite-utils drop-table`` command now refuses to drop a view, and ``drop-view`` refuses to drop a table. Previously each would silently drop the wrong type of object if the name matched. Both now exit with an error suggesting the correct command to use.
+- Migrations applied by the new :ref:`migrations system ` now run inside a transaction, together with the record of the migration having been applied. If a migration raises an exception its changes are rolled back and it stays pending, so it can be safely re-applied after the error is fixed. Migrations that cannot run inside a transaction, such as those executing ``VACUUM``, can opt out using ``@migrations(transactional=False)`` - see :ref:`migrations_transactions`.
+- ``table.upsert()`` and ``table.upsert_all()`` now detect the primary key or compound primary key of an existing table, so the ``pk=`` argument is no longer required when upserting into a table that already has a primary key.
+- ``db.table(table_name).insert({})`` can now be used to insert a row consisting entirely of default values into an existing table, using ``INSERT INTO ... DEFAULT VALUES``. (:issue:`759`)
+- Improvements to the ``sqlite-utils migrate`` command: ``--stop-before`` values that do not match any known migration are now an error instead of being silently ignored, ``--stop-before`` now works correctly with migration files that still use the older ``sqlite_migrate.Migrations`` class, and ``--list`` is now a read-only operation that no longer creates the database file or the migrations tracking table. ``migrations.applied()`` now returns migrations in the order they were applied.
+- New ``db.begin()``, ``db.commit()`` and ``db.rollback()`` methods for taking manual control of transactions, as an alternative to the ``db.atomic()`` context manager.
+- New documentation: :ref:`python_api_transactions` describes how transactions work and when changes are committed, and a new :ref:`upgrading` page details the changes needed to move between major versions.
+
+.. _v4_0rc1:
+
+4.0rc1 (2026-06-21)
+-------------------
+
+- New :ref:`database migrations system `, incorporating functionality that was previously provided by the separate `sqlite-migrate `__ plugin. Define migration sets using the new :class:`sqlite_utils.Migrations` class and apply them using the ``sqlite-utils migrate`` command or the :ref:`migrations Python API `. (:issue:`752`)
+- New ``db.atomic()`` :ref:`context manager providing nested transaction support ` using SQLite transactions and savepoints. Internal multi-step operations such as ``table.transform()`` now use this mechanism to avoid unexpectedly committing an existing transaction. (:issue:`755`)
+- ``Database`` objects can now be :ref:`used as context managers `, automatically closing the connection when the ``with`` block exits. The CLI also now closes database and file handles more reliably, resolving a number of ``ResourceWarning`` warnings. (:issue:`692`)
+- The ``sqlite-utils convert`` command can now accept a direct callable reference such as ``r.parsedate`` or ``json.loads --import json`` as the conversion code, as an alternative to calling it explicitly with ``r.parsedate(value)``. (:issue:`686`)
+- Fixed a bug where CSV or TSV files with only a header row could crash ``sqlite-utils insert`` and ``sqlite-utils memory`` when type detection was enabled. Thanks, `Rami Abdelrazzaq `__. (:issue:`702`, `#707 `__)
+- Fixed a bug where installed plugins could be loaded while running the test suite, despite the test-mode safeguard that disables plugin loading. Thanks, `Rami Abdelrazzaq `__. (:issue:`713`, `#719 `__)
+- ``table.detect_fts()`` now recognizes legacy FTS virtual tables that quote the ``content=`` table name using square brackets, allowing ``table.enable_fts(..., replace=True)`` to replace them correctly. (:issue:`694`)
+- Now depends on Click 8.3.1 or later, removing compatibility workarounds for Click's ``Sentinel`` default values. (:issue:`666`)
+- Improved type annotations throughout the package, with ``ty`` now run in CI. (:issue:`697`)
+- Development tooling now uses ``uv`` dependency groups, with separate ``dev`` and ``docs`` groups. (:issue:`691`)
+- The test suite now runs against Python 3.15-dev. (:issue:`738`)
+
+.. _v3_39:
+
+3.39 (2025-11-24)
+-----------------
+
+- Fixed a bug with ``sqlite-utils install`` when the tool had been installed using ``uv``. (:issue:`687`)
+- The ``--functions`` argument now optionally accepts a path to a Python file as an alternative to a string full of code, and can be specified multiple times - see :ref:`cli_query_functions`. (:issue:`659`)
+- ``sqlite-utils`` now requires Python 3.10 or higher.
+
+.. _v4_0a1:
+
+4.0a1 (2025-11-23)
+------------------
+
+- **Breaking change**: The ``db.table(table_name)`` method now only works with tables. To access a SQL view use ``db.view(view_name)`` instead. (:issue:`657`)
+- The ``table.insert_all()`` and ``table.upsert_all()`` methods can now accept an iterator of lists or tuples as an alternative to dictionaries. The first item should be a list/tuple of column names. See :ref:`python_api_insert_lists` for details. (:issue:`672`)
+- **Breaking change**: The default floating point column type has been changed from ``FLOAT`` to ``REAL``, which is the correct SQLite type for floating point values. This affects auto-detected columns when inserting data. (:issue:`645`)
+- Now uses ``pyproject.toml`` in place of ``setup.py`` for packaging. (:issue:`675`)
+- Tables in the Python API now do a much better job of remembering the primary key and other schema details from when they were first created. (:issue:`655`)
+- **Breaking change**: The ``table.convert()`` and ``sqlite-utils convert`` mechanisms no longer skip values that evaluate to ``False``. Previously the ``--skip-false`` option was needed, this has been removed. (:issue:`542`)
+- **Breaking change**: Tables created by this library now wrap table and column names in ``"double-quotes"`` in the schema. Previously they would use ``[square-braces]``. (:issue:`677`)
+- The ``--functions`` CLI argument now accepts a path to a Python file in addition to accepting a string full of Python code. It can also now be specified multiple times. (:issue:`659`)
+- **Breaking change:** Type detection is now the default behavior for the ``insert`` and ``upsert`` CLI commands when importing CSV or TSV data. Previously all columns were treated as ``TEXT`` unless the ``--detect-types`` flag was passed. Use the new ``--no-detect-types`` flag to restore the old behavior. The ``SQLITE_UTILS_DETECT_TYPES`` environment variable has been removed. (:issue:`679`)
+
+.. _v4_0a0:
+
+4.0a0 (2025-05-08)
+------------------
+
+- Upsert operations now use SQLite's ``INSERT ... ON CONFLICT SET`` syntax on all SQLite versions later than 3.23.1. This is a very slight breaking change for apps that depend on the previous ``INSERT OR IGNORE`` followed by ``UPDATE`` behavior. (:issue:`652`)
+- Python library users can opt-in to the previous implementation by passing ``use_old_upsert=True`` to the ``Database()`` constructor, see :ref:`python_api_old_upsert`.
+- Dropped support for Python 3.8, added support for Python 3.13. (:issue:`646`)
+- ``sqlite-utils tui`` is now provided by the `sqlite-utils-tui `__ plugin. (:issue:`648`)
+- Test suite now also runs against SQLite 3.23.1, the last version (from 2018-04-10) before the new ``INSERT ... ON CONFLICT SET`` syntax was added. (:issue:`654`)
+
+.. _v3_38:
+
+3.38 (2024-11-23)
+-----------------
+
+- Plugins can now reuse the implementation of the ``sqlite-utils memory`` CLI command with the new ``return_db=True`` parameter. (:issue:`643`)
+- ``table.transform()`` now recreates indexes after transforming a table. A new ``sqlite_utils.db.TransformError`` exception is raised if these indexes cannot be recreated due to conflicting changes to the table such as a column rename. Thanks, `Mat Miller `__. (:issue:`633`)
+- ``table.search()`` now accepts a ``include_rank=True`` parameter, causing the resulting rows to have a ``rank`` column showing the calculated relevance score. Thanks, `liunux4odoo `__. (`#628 `__)
+- Fixed an error that occurred when creating a strict table with at least one floating point column. These ``FLOAT`` columns are now correctly created as ``REAL`` as well, but only for strict tables. (:issue:`644`)
+
+.. _v3_37:
+
+3.37 (2024-07-18)
+-----------------
+
+- The ``create-table`` and ``insert-files`` commands all now accept multiple ``--pk`` options for compound primary keys. (:issue:`620`)
+- Now tested against Python 3.13 pre-release. (`#619 `__)
+- Fixed a crash that can occur in environments with a broken ``numpy`` installation, producing a ``module 'numpy' has no attribute 'int8'``. (:issue:`632`)
+
+.. _v3_36:
+
+3.36 (2023-12-07)
+-----------------
+
+- Support for creating tables in `SQLite STRICT mode `__. Thanks, `Taj Khattra `__. (:issue:`344`)
+ - CLI commands ``create-table``, ``insert`` and ``upsert`` all now accept a ``--strict`` option.
+ - Python methods that can create a table - ``table.create()`` and ``insert/upsert/insert_all/upsert_all`` all now accept an optional ``strict=True`` parameter.
+ - The ``transform`` command and ``table.transform()`` method preserve strict mode when transforming a table.
+- The ``sqlite-utils create-table`` command now accepts ``str``, ``int`` and ``bytes`` as aliases for ``text``, ``integer`` and ``blob`` respectively. (:issue:`606`)
+
+.. _v3_35_2:
+
+3.35.2 (2023-11-03)
+-------------------
+
+- The ``--load-extension=spatialite`` option and :ref:`find_spatialite() ` utility function now both work correctly on ``arm64`` Linux. Thanks, `Mike Coats `__. (:issue:`599`)
+- Fix for bug where ``sqlite-utils insert`` could cause your terminal cursor to disappear. Thanks, `Luke Plant `__. (:issue:`433`)
+- ``datetime.timedelta`` values are now stored as ``TEXT`` columns. Thanks, `Harald Nezbeda `__. (:issue:`522`)
+- Test suite is now also run against Python 3.12.
+
+.. _v3_35_1:
+
+3.35.1 (2023-09-08)
+-------------------
+
+- Fixed a bug where :ref:`table.transform() ` would sometimes re-assign the ``rowid`` values for a table rather than keeping them consistent across the operation. (:issue:`592`)
+
+.. _v3_35:
+
+3.35 (2023-08-17)
+-----------------
+
+Adding foreign keys to a table no longer uses ``PRAGMA writable_schema = 1`` to directly manipulate the ``sqlite_master`` table. This was resulting in errors in some Python installations where the SQLite library was compiled in a way that prevented this from working, in particular on macOS. Foreign keys are now added using the :ref:`table transformation ` mechanism instead. (:issue:`577`)
+
+This new mechanism creates a full copy of the table, so it is likely to be significantly slower for large tables, but will no longer trigger ``table sqlite_master may not be modified`` errors on platforms that do not support ``PRAGMA writable_schema = 1``.
+
+A new plugin, `sqlite-utils-fast-fks `__, is now available for developers who still want to use that faster but riskier implementation.
+
+Other changes:
+
+- The :ref:`table.transform() method ` has two new parameters: ``foreign_keys=`` allows you to replace the foreign key constraints defined on a table, and ``add_foreign_keys=`` lets you specify new foreign keys to add. These complement the existing ``drop_foreign_keys=`` parameter. (:issue:`577`)
+- The :ref:`sqlite-utils transform ` command has a new ``--add-foreign-key`` option which can be called multiple times to add foreign keys to a table that is being transformed. (:issue:`585`)
+- :ref:`sqlite-utils convert ` now has a ``--pdb`` option for opening a debugger on the first encountered error in your conversion script. (:issue:`581`)
+- Fixed a bug where ``sqlite-utils install -e '.[test]'`` option did not work correctly.
+
+.. _v3_34:
+
+3.34 (2023-07-22)
+-----------------
+
+This release introduces a new :ref:`plugin system `. Read more about this in `sqlite-utils now supports plugins `__. (:issue:`567`)
+
+- Documentation describing :ref:`how to build a plugin `.
+- Plugin hook: :ref:`plugins_hooks_register_commands`, for plugins to add extra commands to ``sqlite-utils``. (:issue:`569`)
+- Plugin hook: :ref:`plugins_hooks_prepare_connection`. Plugins can use this to help prepare the SQLite connection to do things like registering custom SQL functions. Thanks, `Alex Garcia `__. (:issue:`574`)
+- ``sqlite_utils.Database(..., execute_plugins=False)`` option for disabling plugin execution. (:issue:`575`)
+- ``sqlite-utils install -e path-to-directory`` option for installing editable code. This option is useful during the development of a plugin. (:issue:`570`)
+- ``table.create(...)`` method now accepts ``replace=True`` to drop and replace an existing table with the same name, or ``ignore=True`` to silently do nothing if a table already exists with the same name. (:issue:`568`)
+- ``sqlite-utils insert ... --stop-after 10`` option for stopping the insert after a specified number of records. Works for the ``upsert`` command as well. (:issue:`561`)
+- The ``--csv`` and ``--tsv`` modes for ``insert`` now accept a ``--empty-null`` option, which causes empty strings in the CSV file to be stored as ``null`` in the database. (:issue:`563`)
+- New ``db.rename_table(table_name, new_name)`` method for renaming tables. (:issue:`565`)
+- ``sqlite-utils rename-table my.db table_name new_name`` command for renaming tables. (:issue:`565`)
+- The ``table.transform(...)`` method now takes an optional ``keep_table=new_table_name`` parameter, which will cause the original table to be renamed to ``new_table_name`` rather than being dropped at the end of the transformation. (:issue:`571`)
+- Documentation now notes that calling ``table.transform()`` without any arguments will reformat the SQL schema stored by SQLite to be more aesthetically pleasing. (:issue:`564`)
+
+.. _v3_33:
+
+3.33 (2023-06-25)
+-----------------
+
+- ``sqlite-utils`` will now use `sqlean.py `__ in place of ``sqlite3`` if it is installed in the same virtual environment. This is useful for Python environments with either an outdated version of SQLite or with restrictions on SQLite such as disabled extension loading or restrictions resulting in the ``sqlite3.OperationalError: table sqlite_master may not be modified`` error. (:issue:`559`)
+- New ``with db.ensure_autocommit_off()`` context manager, which ensures that the database is in autocommit mode for the duration of a block of code. This is used by ``db.enable_wal()`` and ``db.disable_wal()`` to ensure they work correctly with ``pysqlite3`` and ``sqlean.py``.
+- New ``db.iterdump()`` method, providing an iterator over SQL strings representing a dump of the database. This uses ``sqlite-dump`` if it is available, otherwise falling back on the ``conn.iterdump()`` method from ``sqlite3``. Both ``pysqlite3`` and ``sqlean.py`` omit support for ``iterdump()`` - this method helps paper over that difference.
+
+.. _v3_32_1:
+
+3.32.1 (2023-05-21)
+-------------------
+
+- Examples in the :ref:`CLI documentation ` can now all be copied and pasted without needing to remove a leading ``$``. (:issue:`551`)
+- Documentation now covers :ref:`installation_completion` for ``bash`` and ``zsh``. (:issue:`552`)
+
+.. _v3_32:
+
+3.32 (2023-05-21)
+-----------------
+
+- New experimental ``sqlite-utils tui`` interface for interactively building command-line invocations, powered by `Trogon `__. This requires an optional dependency, installed using ``sqlite-utils install trogon``. (:issue:`545`)
+- ``sqlite-utils analyze-tables`` command (:ref:`documentation `) now has a ``--common-limit 20`` option for changing the number of common/least-common values shown for each column. (:issue:`544`)
+- ``sqlite-utils analyze-tables --no-most`` and ``--no-least`` options for disabling calculation of most-common and least-common values.
+- If a column contains only ``null`` values, ``analyze-tables`` will no longer attempt to calculate the most common and least common values for that column. (:issue:`547`)
+- Calling ``sqlite-utils analyze-tables`` with non-existent columns in the ``-c/--column`` option now results in an error message. (:issue:`548`)
+- The ``table.analyze_column()`` method (:ref:`documented here `) now accepts ``most_common=False`` and ``least_common=False`` options for disabling calculation of those values.
+
+.. _v3_31:
+
+3.31 (2023-05-08)
+-----------------
+
+- Dropped support for Python 3.6. Tests now ensure compatibility with Python 3.11. (:issue:`517`)
+- Automatically locates the SpatiaLite extension on Apple Silicon. Thanks, Chris Amico. (`#536 `__)
+- New ``--raw-lines`` option for the ``sqlite-utils query`` and ``sqlite-utils memory`` commands, which outputs just the raw value of the first column of every row. (:issue:`539`)
+- Fixed a bug where ``table.upsert_all()`` failed if the ``not_null=`` option was passed. (:issue:`538`)
+- Fixed a ``ResourceWarning`` when using ``sqlite-utils insert``. (:issue:`534`)
+- Now shows a more detailed error message when ``sqlite-utils insert`` is called with invalid JSON. (:issue:`532`)
+- ``table.convert(..., skip_false=False)`` and ``sqlite-utils convert --no-skip-false`` options, for avoiding a misfeature where the :ref:`convert() ` mechanism skips rows in the database with a falsey value for the specified column. Fixing this by default would be a backwards-incompatible change and is under consideration for a 4.0 release in the future. (:issue:`527`)
+- Tables can now be created with self-referential foreign keys. Thanks, Scott Perry. (`#537 `__)
+- ``sqlite-utils transform`` no longer breaks if a table defines default values for columns. Thanks, Kenny Song. (:issue:`509`)
+- Fixed a bug where repeated calls to ``table.transform()`` did not work correctly. Thanks, Martin Carpenter. (:issue:`525`)
+- Improved error message if ``rows_from_file()`` is passed a non-binary-mode file-like object. (:issue:`520`)
+
.. _v3_30:
3.30 (2022-10-25)
@@ -16,7 +360,7 @@
- Conversion functions passed to :ref:`table.convert(...) ` can now return lists or dictionaries, which will be inserted into the database as JSON strings. (:issue:`495`)
- ``sqlite-utils install`` and ``sqlite-utils uninstall`` commands for installing packages into the same virtual environment as ``sqlite-utils``, :ref:`described here `. (:issue:`483`)
- New :ref:`sqlite_utils.utils.flatten() ` utility function. (:issue:`500`)
-- Documentation on :ref:`using Just ` to run tests, linters and build documentation.
+- Documentation on :ref:`using Just ` to run tests, linters and build documentation.
- Documentation now covers the :ref:`release_process` for this package.
.. _v3_29:
@@ -1202,3 +1546,19 @@ A few other changes:
----------------
- ``enable_fts()``, ``populate_fts()`` and ``search()`` table methods
+
+0.3.1 (2018-07-31)
+------------------
+
+- Documented related projects
+- Added badges to the documentation
+
+0.3 (2018-07-31)
+----------------
+
+- New ``Table`` class representing a table in the SQLite database
+
+0.2 (2018-07-28)
+----------------
+
+- Initial release to PyPI
diff --git a/docs/cli-reference.rst b/docs/cli-reference.rst
index 153e5f9..a4ec402 100644
--- a/docs/cli-reference.rst
+++ b/docs/cli-reference.rst
@@ -11,14 +11,16 @@ This page lists the ``--help`` for every ``sqlite-utils`` CLI sub-command.
.. [[[cog
from sqlite_utils import cli
+ import sys
+ sys._called_from_test = True
from click.testing import CliRunner
import textwrap
commands = list(cli.cli.commands.keys())
go_first = [
"query", "memory", "insert", "upsert", "bulk", "search", "transform", "extract",
"schema", "insert-files", "analyze-tables", "convert", "tables", "views", "rows",
- "triggers", "indexes", "create-database", "create-table", "create-index",
- "enable-fts", "populate-fts", "rebuild-fts", "disable-fts"
+ "triggers", "indexes", "create-database", "create-table", "create-index", "drop-index",
+ "migrate", "enable-fts", "populate-fts", "rebuild-fts", "disable-fts"
]
refs = {
"query": "cli_query",
@@ -38,13 +40,17 @@ This page lists the ``--help`` for every ``sqlite-utils`` CLI sub-command.
"vacuum": "cli_vacuum",
"dump": "cli_dump",
"add-column": "cli_add_column",
+ "rename-table": "cli_renaming_tables",
+ "duplicate": "cli_duplicate_table",
"add-foreign-key": "cli_add_foreign_key",
"add-foreign-keys": "cli_add_foreign_keys",
"index-foreign-keys": "cli_index_foreign_keys",
"create-index": "cli_create_index",
+ "drop-index": "cli_drop_index",
"enable-wal": "cli_wal",
"enable-counts": "cli_enable_counts",
"bulk": "cli_bulk",
+ "migrate": "cli_migrate",
"create-database": "cli_create_database",
"create-table": "cli_create_table",
"drop-table": "cli_drop_table",
@@ -80,6 +86,7 @@ This page lists the ``--help`` for every ``sqlite-utils`` CLI sub-command.
cog.out("::\n\n")
result = CliRunner().invoke(cli.cli, [command, "--help"])
output = result.output.replace("Usage: cli ", "Usage: sqlite-utils ")
+ output = output.replace('\b', '')
cog.out(textwrap.indent(output, ' '))
cog.out("\n\n")
.. ]]]
@@ -103,6 +110,10 @@ See :ref:`cli_query`.
"select * from chickens where age > :age" \
-p age 1
+ Pass "-" as the SQL to read the query from standard input:
+
+ echo "select * from chickens" | sqlite-utils data.db -
+
Options:
--attach ... Additional databases to attach - specify alias and
filepath
@@ -110,23 +121,26 @@ See :ref:`cli_query`.
--arrays Output rows as arrays instead of objects
--csv Output CSV
--tsv Output TSV
- --no-headers Omit CSV headers
+ --no-headers Omit headers from CSV/TSV and table/--fmt output
-t, --table Output as a formatted table
- --fmt TEXT Table format - one of asciidoc, double_grid,
- double_outline, fancy_grid, fancy_outline, github,
- grid, heavy_grid, heavy_outline, html, jira,
- latex, latex_booktabs, latex_longtable, latex_raw,
- mediawiki, mixed_grid, mixed_outline, moinmoin,
- orgtbl, outline, pipe, plain, presto, pretty,
- psql, rounded_grid, rounded_outline, rst, simple,
- simple_grid, simple_outline, textile, tsv,
- unsafehtml, youtrack
+ --fmt TEXT Table format - one of asciidoc, colon_grid,
+ double_grid, double_outline, fancy_grid,
+ fancy_outline, github, grid, heavy_grid,
+ heavy_outline, html, jira, latex, latex_booktabs,
+ latex_longtable, latex_raw, mediawiki, mixed_grid,
+ mixed_outline, moinmoin, orgtbl, outline, pipe,
+ plain, presto, pretty, psql, rounded_grid,
+ rounded_outline, rst, simple, simple_grid,
+ simple_outline, textile, tsv, unsafehtml, youtrack
--json-cols Detect JSON cols and output them as JSON, not
escaped strings
+ --ascii Escape non-ASCII characters in JSON output as
+ \uXXXX
-r, --raw Raw output, first column of first row
+ --raw-lines Raw output, first column of each row
-p, --param ... Named :parameters for SQL query
- --functions TEXT Python code defining one or more custom SQL
- functions
+ --functions TEXT Python code or a file path defining custom SQL
+ functions; can be used multiple times
--load-extension TEXT Path to SQLite extension, with optional
:entrypoint
-h, --help Show this message and exit.
@@ -168,8 +182,8 @@ See :ref:`cli_memory`.
sqlite-utils memory animals.csv --schema
Options:
- --functions TEXT Python code defining one or more custom SQL
- functions
+ --functions TEXT Python code or a file path defining custom SQL
+ functions; can be used multiple times
--attach ... Additional databases to attach - specify alias and
filepath
--flatten Flatten nested JSON objects, so {"foo": {"bar":
@@ -178,20 +192,23 @@ See :ref:`cli_memory`.
--arrays Output rows as arrays instead of objects
--csv Output CSV
--tsv Output TSV
- --no-headers Omit CSV headers
+ --no-headers Omit headers from CSV/TSV and table/--fmt output
-t, --table Output as a formatted table
- --fmt TEXT Table format - one of asciidoc, double_grid,
- double_outline, fancy_grid, fancy_outline, github,
- grid, heavy_grid, heavy_outline, html, jira,
- latex, latex_booktabs, latex_longtable, latex_raw,
- mediawiki, mixed_grid, mixed_outline, moinmoin,
- orgtbl, outline, pipe, plain, presto, pretty,
- psql, rounded_grid, rounded_outline, rst, simple,
- simple_grid, simple_outline, textile, tsv,
- unsafehtml, youtrack
+ --fmt TEXT Table format - one of asciidoc, colon_grid,
+ double_grid, double_outline, fancy_grid,
+ fancy_outline, github, grid, heavy_grid,
+ heavy_outline, html, jira, latex, latex_booktabs,
+ latex_longtable, latex_raw, mediawiki, mixed_grid,
+ mixed_outline, moinmoin, orgtbl, outline, pipe,
+ plain, presto, pretty, psql, rounded_grid,
+ rounded_outline, rst, simple, simple_grid,
+ simple_outline, textile, tsv, unsafehtml, youtrack
--json-cols Detect JSON cols and output them as JSON, not
escaped strings
+ --ascii Escape non-ASCII characters in JSON output as
+ \uXXXX
-r, --raw Raw output, first column of first row
+ --raw-lines Raw output, first column of each row
-p, --param ... Named :parameters for SQL query
--encoding TEXT Character encoding for CSV input, defaults to
utf-8
@@ -214,7 +231,7 @@ See :ref:`cli_inserting_data`, :ref:`cli_insert_csv_tsv`, :ref:`cli_insert_unstr
::
- Usage: sqlite-utils insert [OPTIONS] PATH TABLE FILE
+ Usage: sqlite-utils insert [OPTIONS] PATH TABLE [FILE]
Insert records from FILE into a table, creating the table if it does not
already exist.
@@ -230,6 +247,9 @@ See :ref:`cli_inserting_data`, :ref:`cli_insert_csv_tsv`, :ref:`cli_insert_unstr
- Use --lines to write each incoming line to a column called "line"
- Use --text to write the entire input to a column called "text"
+ Use --type column-name type to override the type automatically chosen when the
+ table is created.
+
You can also use --convert to pass a fragment of Python code that will be used
to convert each input.
@@ -256,13 +276,26 @@ See :ref:`cli_inserting_data`, :ref:`cli_insert_csv_tsv`, :ref:`cli_insert_unstr
echo 'A bunch of words' | sqlite-utils insert words.db words - \
--text --convert '({"word": w} for w in text.split())'
+ Instead of a FILE you can use --code to provide a block of Python code that
+ defines the rows to insert, as either a rows() function that yields
+ dictionaries or a "rows" iterable. --code can also be a path to a .py file:
+
+ sqlite-utils insert data.db creatures --code '
+ def rows():
+ yield {"id": 1, "name": "Cleo"}
+ yield {"id": 2, "name": "Suna"}
+ ' --pk id
+
Options:
--pk TEXT Columns to use as the primary key, e.g. id
+ --code TEXT Python code defining a rows() function or iterable
+ of rows to insert
--flatten Flatten nested JSON objects, so {"a": {"b": 1}}
becomes {"a_b": 1}
--nl Expect newline-delimited JSON
-c, --csv Expect CSV input
--tsv Expect TSV input
+ --empty-null Treat empty strings as NULL
--lines Treat each line as a single value called 'line'
--text Treat input as a single value called 'text'
--convert TEXT Python code to convert each item
@@ -273,13 +306,16 @@ See :ref:`cli_inserting_data`, :ref:`cli_insert_csv_tsv`, :ref:`cli_insert_unstr
--no-headers CSV file has no header row
--encoding TEXT Character encoding for input, defaults to utf-8
--batch-size INTEGER Commit every X records
+ --stop-after INTEGER Stop after X records
--alter Alter existing table to add any missing columns
--not-null TEXT Columns that should be created as NOT NULL
--default ... Default value that should be set for a column
- -d, --detect-types Detect types for columns in CSV/TSV data
+ --type ... Column types to use when creating the table
+ --no-detect-types Treat all CSV/TSV columns as TEXT
--analyze Run ANALYZE at the end of this operation
--load-extension TEXT Path to SQLite extension, with optional :entrypoint
--silent Do not show progress bar
+ --strict Apply STRICT mode to created table
--ignore Ignore records if pk already exists
--replace Replace records if pk already exists
--truncate Truncate table before inserting records, if table
@@ -296,12 +332,17 @@ See :ref:`cli_upsert`.
::
- Usage: sqlite-utils upsert [OPTIONS] PATH TABLE FILE
+ Usage: sqlite-utils upsert [OPTIONS] PATH TABLE [FILE]
Upsert records based on their primary key. Works like 'insert' but if an
incoming record has a primary key that matches an existing record the existing
record will be updated.
+ If the table already exists and has a primary key, --pk can be omitted.
+
+ Use --type column-name type to override the type automatically chosen when the
+ table is created.
+
Example:
echo '[
@@ -311,12 +352,14 @@ See :ref:`cli_upsert`.
Options:
--pk TEXT Columns to use as the primary key, e.g. id
- [required]
+ --code TEXT Python code defining a rows() function or iterable
+ of rows to insert
--flatten Flatten nested JSON objects, so {"a": {"b": 1}}
becomes {"a_b": 1}
--nl Expect newline-delimited JSON
-c, --csv Expect CSV input
--tsv Expect TSV input
+ --empty-null Treat empty strings as NULL
--lines Treat each line as a single value called 'line'
--text Treat input as a single value called 'text'
--convert TEXT Python code to convert each item
@@ -327,13 +370,16 @@ See :ref:`cli_upsert`.
--no-headers CSV file has no header row
--encoding TEXT Character encoding for input, defaults to utf-8
--batch-size INTEGER Commit every X records
+ --stop-after INTEGER Stop after X records
--alter Alter existing table to add any missing columns
--not-null TEXT Columns that should be created as NOT NULL
--default ... Default value that should be set for a column
- -d, --detect-types Detect types for columns in CSV/TSV data
+ --type ... Column types to use when creating the table
+ --no-detect-types Treat all CSV/TSV columns as TEXT
--analyze Run ANALYZE at the end of this operation
--load-extension TEXT Path to SQLite extension, with optional :entrypoint
--silent Do not show progress bar
+ --strict Apply STRICT mode to created table
-h, --help Show this message and exit.
@@ -361,12 +407,14 @@ See :ref:`cli_bulk`.
Options:
--batch-size INTEGER Commit every X records
- --functions TEXT Python code defining one or more custom SQL functions
+ --functions TEXT Python code or a file path defining custom SQL
+ functions; can be used multiple times
--flatten Flatten nested JSON objects, so {"a": {"b": 1}} becomes
{"a_b": 1}
--nl Expect newline-delimited JSON
-c, --csv Expect CSV input
--tsv Expect TSV input
+ --empty-null Treat empty strings as NULL
--lines Treat each line as a single value called 'line'
--text Treat input as a single value called 'text'
--convert TEXT Python code to convert each item
@@ -407,18 +455,20 @@ See :ref:`cli_search`.
--arrays Output rows as arrays instead of objects
--csv Output CSV
--tsv Output TSV
- --no-headers Omit CSV headers
+ --no-headers Omit headers from CSV/TSV and table/--fmt output
-t, --table Output as a formatted table
- --fmt TEXT Table format - one of asciidoc, double_grid,
- double_outline, fancy_grid, fancy_outline, github,
- grid, heavy_grid, heavy_outline, html, jira, latex,
- latex_booktabs, latex_longtable, latex_raw, mediawiki,
- mixed_grid, mixed_outline, moinmoin, orgtbl, outline,
- pipe, plain, presto, pretty, psql, rounded_grid,
- rounded_outline, rst, simple, simple_grid,
- simple_outline, textile, tsv, unsafehtml, youtrack
+ --fmt TEXT Table format - one of asciidoc, colon_grid,
+ double_grid, double_outline, fancy_grid, fancy_outline,
+ github, grid, heavy_grid, heavy_outline, html, jira,
+ latex, latex_booktabs, latex_longtable, latex_raw,
+ mediawiki, mixed_grid, mixed_outline, moinmoin, orgtbl,
+ outline, pipe, plain, presto, pretty, psql,
+ rounded_grid, rounded_outline, rst, simple,
+ simple_grid, simple_outline, textile, tsv, unsafehtml,
+ youtrack
--json-cols Detect JSON cols and output them as JSON, not escaped
strings
+ --ascii Escape non-ASCII characters in JSON output as \uXXXX
--load-extension TEXT Path to SQLite extension, with optional :entrypoint
-h, --help Show this message and exit.
@@ -443,20 +493,27 @@ See :ref:`cli_transform_table`.
--rename column2 column_renamed
Options:
- --type ... Change column type to INTEGER, TEXT, FLOAT or BLOB
- --drop TEXT Drop this column
- --rename ... Rename this column to X
- -o, --column-order TEXT Reorder columns
- --not-null TEXT Set this column to NOT NULL
- --not-null-false TEXT Remove NOT NULL from this column
- --pk TEXT Make this column the primary key
- --pk-none Remove primary key (convert to rowid table)
- --default ... Set default value for this column
- --default-none TEXT Remove default from this column
- --drop-foreign-key TEXT Drop foreign key constraint for this column
- --sql Output SQL without executing it
- --load-extension TEXT Path to SQLite extension, with optional :entrypoint
- -h, --help Show this message and exit.
+ --type ... Change column type to INTEGER, TEXT, FLOAT,
+ REAL or BLOB
+ --drop TEXT Drop this column
+ --rename ... Rename this column to X
+ -o, --column-order TEXT Reorder columns
+ --not-null TEXT Set this column to NOT NULL
+ --not-null-false TEXT Remove NOT NULL from this column
+ --pk TEXT Make this column the primary key
+ --pk-none Remove primary key (convert to rowid table)
+ --default ... Set default value for this column
+ --default-none TEXT Remove default from this column
+ --add-foreign-key ...
+ Add a foreign key constraint from a column to
+ another table with another column
+ --drop-foreign-key TEXT Drop foreign key constraint for this column
+ --strict / --no-strict Enable or disable STRICT mode (default:
+ preserve current mode)
+ --sql Output SQL without executing it
+ --load-extension TEXT Path to SQLite extension, with optional
+ :entrypoint
+ -h, --help Show this message and exit.
.. _cli_ref_extract:
@@ -562,10 +619,13 @@ See :ref:`cli_analyze_tables`.
sqlite-utils analyze-tables data.db trees
Options:
- -c, --column TEXT Specific columns to analyze
- --save Save results to _analyze_tables table
- --load-extension TEXT Path to SQLite extension, with optional :entrypoint
- -h, --help Show this message and exit.
+ -c, --column TEXT Specific columns to analyze
+ --save Save results to _analyze_tables table
+ --common-limit INTEGER How many common values
+ --no-most Skip most common values
+ --no-least Skip least common values
+ --load-extension TEXT Path to SQLite extension, with optional :entrypoint
+ -h, --help Show this message and exit.
.. _cli_ref_convert:
@@ -581,42 +641,48 @@ See :ref:`cli_convert`.
Convert columns using Python code you supply. For example:
- sqlite-utils convert my.db mytable mycolumn \
- '"\n".join(textwrap.wrap(value, 10))' \
- --import=textwrap
+ sqlite-utils convert my.db mytable mycolumn \
+ '"\n".join(textwrap.wrap(value, 10))' \
+ --import=textwrap
"value" is a variable with the column value to be converted.
+ CODE can also be a reference to a callable that takes the value, for example:
+
+ sqlite-utils convert my.db mytable date r.parsedate
+ sqlite-utils convert my.db mytable data json.loads --import json
+
Use "-" for CODE to read Python code from standard input.
The following common operations are available as recipe functions:
- r.jsonsplit(value, delimiter=',', type=)
+ r.jsonsplit(value: 'str', delimiter: 'str' = ',', type: 'Callable[[str],
+ object]' = ) -> 'str'
- Convert a string like a,b,c into a JSON array ["a", "b", "c"]
+ Convert a string like a,b,c into a JSON array ["a", "b", "c"]
- r.parsedate(value, dayfirst=False, yearfirst=False, errors=None)
+ r.parsedate(value: 'str', dayfirst: 'bool' = False, yearfirst: 'bool' = False,
+ errors: 'object | None' = None) -> 'str | None'
- Parse a date and convert it to ISO date format: yyyy-mm-dd
-
- - dayfirst=True: treat xx as the day in xx/yy/zz
- - yearfirst=True: treat xx as the year in xx/yy/zz
- - errors=r.IGNORE to ignore values that cannot be parsed
- - errors=r.SET_NULL to set values that cannot be parsed to null
+ Parse a date and convert it to ISO date format: yyyy-mm-dd
+ - dayfirst=True: treat xx as the day in xx/yy/zz
+ - yearfirst=True: treat xx as the year in xx/yy/zz
+ - errors=r.IGNORE to ignore values that cannot be parsed
+ - errors=r.SET_NULL to set values that cannot be parsed to null
- r.parsedatetime(value, dayfirst=False, yearfirst=False, errors=None)
+ r.parsedatetime(value: 'str', dayfirst: 'bool' = False, yearfirst: 'bool' =
+ False, errors: 'object | None' = None) -> 'str | None'
- Parse a datetime and convert it to ISO datetime format: yyyy-mm-ddTHH:MM:SS
-
- - dayfirst=True: treat xx as the day in xx/yy/zz
- - yearfirst=True: treat xx as the year in xx/yy/zz
- - errors=r.IGNORE to ignore values that cannot be parsed
- - errors=r.SET_NULL to set values that cannot be parsed to null
+ Parse a datetime and convert it to ISO datetime format: yyyy-mm-ddTHH:MM:SS
+ - dayfirst=True: treat xx as the day in xx/yy/zz
+ - yearfirst=True: treat xx as the year in xx/yy/zz
+ - errors=r.IGNORE to ignore values that cannot be parsed
+ - errors=r.SET_NULL to set values that cannot be parsed to null
You can use these recipes like so:
- sqlite-utils convert my.db mytable mycolumn \
- 'r.jsonsplit(value, delimiter=":")'
+ sqlite-utils convert my.db mytable mycolumn \
+ 'r.jsonsplit(value, delimiter=":")'
Options:
--import TEXT Python modules to import
@@ -632,6 +698,7 @@ See :ref:`cli_convert`.
Column type to use for the output column
--drop Drop original column afterwards
-s, --silent Don't show a progress bar
+ --pdb Open pdb debugger on first error
-h, --help Show this message and exit.
@@ -660,18 +727,20 @@ See :ref:`cli_tables`.
--arrays Output rows as arrays instead of objects
--csv Output CSV
--tsv Output TSV
- --no-headers Omit CSV headers
+ --no-headers Omit headers from CSV/TSV and table/--fmt output
-t, --table Output as a formatted table
- --fmt TEXT Table format - one of asciidoc, double_grid,
- double_outline, fancy_grid, fancy_outline, github,
- grid, heavy_grid, heavy_outline, html, jira, latex,
- latex_booktabs, latex_longtable, latex_raw, mediawiki,
- mixed_grid, mixed_outline, moinmoin, orgtbl, outline,
- pipe, plain, presto, pretty, psql, rounded_grid,
- rounded_outline, rst, simple, simple_grid,
- simple_outline, textile, tsv, unsafehtml, youtrack
+ --fmt TEXT Table format - one of asciidoc, colon_grid,
+ double_grid, double_outline, fancy_grid, fancy_outline,
+ github, grid, heavy_grid, heavy_outline, html, jira,
+ latex, latex_booktabs, latex_longtable, latex_raw,
+ mediawiki, mixed_grid, mixed_outline, moinmoin, orgtbl,
+ outline, pipe, plain, presto, pretty, psql,
+ rounded_grid, rounded_outline, rst, simple,
+ simple_grid, simple_outline, textile, tsv, unsafehtml,
+ youtrack
--json-cols Detect JSON cols and output them as JSON, not escaped
strings
+ --ascii Escape non-ASCII characters in JSON output as \uXXXX
--columns Include list of columns for each table
--schema Include schema for each table
--load-extension TEXT Path to SQLite extension, with optional :entrypoint
@@ -701,18 +770,20 @@ See :ref:`cli_views`.
--arrays Output rows as arrays instead of objects
--csv Output CSV
--tsv Output TSV
- --no-headers Omit CSV headers
+ --no-headers Omit headers from CSV/TSV and table/--fmt output
-t, --table Output as a formatted table
- --fmt TEXT Table format - one of asciidoc, double_grid,
- double_outline, fancy_grid, fancy_outline, github,
- grid, heavy_grid, heavy_outline, html, jira, latex,
- latex_booktabs, latex_longtable, latex_raw, mediawiki,
- mixed_grid, mixed_outline, moinmoin, orgtbl, outline,
- pipe, plain, presto, pretty, psql, rounded_grid,
- rounded_outline, rst, simple, simple_grid,
- simple_outline, textile, tsv, unsafehtml, youtrack
+ --fmt TEXT Table format - one of asciidoc, colon_grid,
+ double_grid, double_outline, fancy_grid, fancy_outline,
+ github, grid, heavy_grid, heavy_outline, html, jira,
+ latex, latex_booktabs, latex_longtable, latex_raw,
+ mediawiki, mixed_grid, mixed_outline, moinmoin, orgtbl,
+ outline, pipe, plain, presto, pretty, psql,
+ rounded_grid, rounded_outline, rst, simple,
+ simple_grid, simple_outline, textile, tsv, unsafehtml,
+ youtrack
--json-cols Detect JSON cols and output them as JSON, not escaped
strings
+ --ascii Escape non-ASCII characters in JSON output as \uXXXX
--columns Include list of columns for each view
--schema Include schema for each view
--load-extension TEXT Path to SQLite extension, with optional :entrypoint
@@ -747,19 +818,21 @@ See :ref:`cli_rows`.
--arrays Output rows as arrays instead of objects
--csv Output CSV
--tsv Output TSV
- --no-headers Omit CSV headers
+ --no-headers Omit headers from CSV/TSV and table/--fmt output
-t, --table Output as a formatted table
- --fmt TEXT Table format - one of asciidoc, double_grid,
- double_outline, fancy_grid, fancy_outline, github,
- grid, heavy_grid, heavy_outline, html, jira,
- latex, latex_booktabs, latex_longtable, latex_raw,
- mediawiki, mixed_grid, mixed_outline, moinmoin,
- orgtbl, outline, pipe, plain, presto, pretty,
- psql, rounded_grid, rounded_outline, rst, simple,
- simple_grid, simple_outline, textile, tsv,
- unsafehtml, youtrack
+ --fmt TEXT Table format - one of asciidoc, colon_grid,
+ double_grid, double_outline, fancy_grid,
+ fancy_outline, github, grid, heavy_grid,
+ heavy_outline, html, jira, latex, latex_booktabs,
+ latex_longtable, latex_raw, mediawiki, mixed_grid,
+ mixed_outline, moinmoin, orgtbl, outline, pipe,
+ plain, presto, pretty, psql, rounded_grid,
+ rounded_outline, rst, simple, simple_grid,
+ simple_outline, textile, tsv, unsafehtml, youtrack
--json-cols Detect JSON cols and output them as JSON, not
escaped strings
+ --ascii Escape non-ASCII characters in JSON output as
+ \uXXXX
--load-extension TEXT Path to SQLite extension, with optional
:entrypoint
-h, --help Show this message and exit.
@@ -787,18 +860,20 @@ See :ref:`cli_triggers`.
--arrays Output rows as arrays instead of objects
--csv Output CSV
--tsv Output TSV
- --no-headers Omit CSV headers
+ --no-headers Omit headers from CSV/TSV and table/--fmt output
-t, --table Output as a formatted table
- --fmt TEXT Table format - one of asciidoc, double_grid,
- double_outline, fancy_grid, fancy_outline, github,
- grid, heavy_grid, heavy_outline, html, jira, latex,
- latex_booktabs, latex_longtable, latex_raw, mediawiki,
- mixed_grid, mixed_outline, moinmoin, orgtbl, outline,
- pipe, plain, presto, pretty, psql, rounded_grid,
- rounded_outline, rst, simple, simple_grid,
- simple_outline, textile, tsv, unsafehtml, youtrack
+ --fmt TEXT Table format - one of asciidoc, colon_grid,
+ double_grid, double_outline, fancy_grid, fancy_outline,
+ github, grid, heavy_grid, heavy_outline, html, jira,
+ latex, latex_booktabs, latex_longtable, latex_raw,
+ mediawiki, mixed_grid, mixed_outline, moinmoin, orgtbl,
+ outline, pipe, plain, presto, pretty, psql,
+ rounded_grid, rounded_outline, rst, simple,
+ simple_grid, simple_outline, textile, tsv, unsafehtml,
+ youtrack
--json-cols Detect JSON cols and output them as JSON, not escaped
strings
+ --ascii Escape non-ASCII characters in JSON output as \uXXXX
--load-extension TEXT Path to SQLite extension, with optional :entrypoint
-h, --help Show this message and exit.
@@ -826,18 +901,20 @@ See :ref:`cli_indexes`.
--arrays Output rows as arrays instead of objects
--csv Output CSV
--tsv Output TSV
- --no-headers Omit CSV headers
+ --no-headers Omit headers from CSV/TSV and table/--fmt output
-t, --table Output as a formatted table
- --fmt TEXT Table format - one of asciidoc, double_grid,
- double_outline, fancy_grid, fancy_outline, github,
- grid, heavy_grid, heavy_outline, html, jira, latex,
- latex_booktabs, latex_longtable, latex_raw, mediawiki,
- mixed_grid, mixed_outline, moinmoin, orgtbl, outline,
- pipe, plain, presto, pretty, psql, rounded_grid,
- rounded_outline, rst, simple, simple_grid,
- simple_outline, textile, tsv, unsafehtml, youtrack
+ --fmt TEXT Table format - one of asciidoc, colon_grid,
+ double_grid, double_outline, fancy_grid, fancy_outline,
+ github, grid, heavy_grid, heavy_outline, html, jira,
+ latex, latex_booktabs, latex_longtable, latex_raw,
+ mediawiki, mixed_grid, mixed_outline, moinmoin, orgtbl,
+ outline, pipe, plain, presto, pretty, psql,
+ rounded_grid, rounded_outline, rst, simple,
+ simple_grid, simple_outline, textile, tsv, unsafehtml,
+ youtrack
--json-cols Detect JSON cols and output them as JSON, not escaped
strings
+ --ascii Escape non-ASCII characters in JSON output as \uXXXX
--load-extension TEXT Path to SQLite extension, with optional :entrypoint
-h, --help Show this message and exit.
@@ -883,10 +960,10 @@ See :ref:`cli_create_table`.
sqlite-utils create-table my.db people \
id integer \
name text \
- height float \
+ height real \
photo blob --pk id
- Valid column types are text, integer, float and blob.
+ Valid column types are text, integer, real, float and blob.
Options:
--pk TEXT Column to use as primary key
@@ -898,6 +975,7 @@ See :ref:`cli_create_table`.
--replace If table already exists, replace it
--transform If table already exists, try to transform the schema
--load-extension TEXT Path to SQLite extension, with optional :entrypoint
+ --strict Apply STRICT mode to created table
-h, --help Show this message and exit.
@@ -931,6 +1009,67 @@ See :ref:`cli_create_index`.
-h, --help Show this message and exit.
+.. _cli_ref_drop_index:
+
+drop-index
+==========
+
+See :ref:`cli_drop_index`.
+
+::
+
+ Usage: sqlite-utils drop-index [OPTIONS] PATH TABLE INDEX
+
+ Drop an index by index name from the specified table
+
+ Example:
+
+ sqlite-utils drop-index chickens.db chickens idx_chickens_name
+
+ Options:
+ --ignore Ignore if index does not exist
+ --load-extension TEXT Path to SQLite extension, with optional :entrypoint
+ -h, --help Show this message and exit.
+
+
+.. _cli_ref_migrate:
+
+migrate
+=======
+
+See :ref:`cli_migrate`.
+
+::
+
+ Usage: sqlite-utils migrate [OPTIONS] DB_PATH [MIGRATIONS]...
+
+ Apply pending database migrations.
+
+ Usage:
+
+ sqlite-utils migrate database.db
+
+ This will find the migrations.py file in the current directory or
+ subdirectories and apply any pending migrations.
+
+ Or pass paths to one or more migrations.py files directly:
+
+ sqlite-utils migrate database.db path/to/migrations.py
+
+ Pass --list to see a list of applied and pending migrations without applying
+ them.
+
+ Use --stop-before migration_set:name to stop before a migration. This option
+ can be used multiple times.
+
+ Options:
+ --stop-before TEXT Stop before applying this migration. Use set:name to
+ target a migration set.
+ --list List migrations without running them
+ -v, --verbose Show verbose output
+ -h, --help Show this message and exit.
+
+
.. _cli_ref_enable_fts:
enable-fts
@@ -942,7 +1081,7 @@ See :ref:`cli_fts`.
Usage: sqlite-utils enable-fts [OPTIONS] PATH TABLE COLUMN...
- Enable full-text search for specific table and columns"
+ Enable full-text search for specific table and columns
Example:
@@ -1118,7 +1257,7 @@ See :ref:`cli_add_column`.
::
Usage: sqlite-utils add-column [OPTIONS] PATH TABLE COL_NAME
- [[integer|float|blob|text|INTEGER|FLOAT|BLOB|TEXT]]
+ [integer|int|float|real|text|str|blob|bytes]
Add a column to the specified table
@@ -1154,8 +1293,6 @@ See :ref:`cli_add_foreign_key`.
sqlite-utils add-foreign-key my.db books author_id authors id
- WARNING: Could corrupt your database! Back up your database file first.
-
Options:
--ignore If foreign key already exists, do nothing
--load-extension TEXT Path to SQLite extension, with optional :entrypoint
@@ -1297,6 +1434,8 @@ reset-counts
duplicate
=========
+See :ref:`cli_duplicate_table`.
+
::
Usage: sqlite-utils duplicate [OPTIONS] PATH TABLE NEW_TABLE
@@ -1309,6 +1448,25 @@ duplicate
-h, --help Show this message and exit.
+.. _cli_ref_rename_table:
+
+rename-table
+============
+
+See :ref:`cli_renaming_tables`.
+
+::
+
+ Usage: sqlite-utils rename-table [OPTIONS] PATH TABLE NEW_NAME
+
+ Rename this table.
+
+ Options:
+ --ignore If table does not exist, do nothing
+ --load-extension TEXT Path to SQLite extension, with optional :entrypoint
+ -h, --help Show this message and exit.
+
+
.. _cli_ref_drop_table:
drop-table
@@ -1389,13 +1547,14 @@ See :ref:`cli_install`.
::
- Usage: sqlite-utils install [OPTIONS] PACKAGES...
+ Usage: sqlite-utils install [OPTIONS] [PACKAGES]...
Install packages from PyPI into the same environment as sqlite-utils
Options:
- -U, --upgrade Upgrade packages to latest version
- -h, --help Show this message and exit.
+ -U, --upgrade Upgrade packages to latest version
+ -e, --editable TEXT Install a project in editable mode from this path
+ -h, --help Show this message and exit.
.. _cli_ref_uninstall:
@@ -1434,7 +1593,7 @@ See :ref:`cli_spatialite`.
paths. To load it from a specific path, use --load-extension.
Options:
- -t, --type [POINT|LINESTRING|POLYGON|MULTIPOINT|MULTILINESTRING|MULTIPOLYGON|GEOMETRYCOLLECTION|GEOMETRY]
+ -t, --type [point|linestring|polygon|multipoint|multilinestring|multipolygon|geometrycollection|geometry]
Specify a geometry type for this column.
[default: GEOMETRY]
--srid INTEGER Spatial Reference ID. See
@@ -1470,4 +1629,19 @@ See :ref:`cli_spatialite_indexes`.
-h, --help Show this message and exit.
+.. _cli_ref_plugins:
+
+plugins
+=======
+
+::
+
+ Usage: sqlite-utils plugins [OPTIONS]
+
+ List installed plugins
+
+ Options:
+ -h, --help Show this message and exit.
+
+
.. [[[end]]]
diff --git a/docs/cli.rst b/docs/cli.rst
index 1d67e88..2e506dd 100644
--- a/docs/cli.rst
+++ b/docs/cli.rst
@@ -16,33 +16,60 @@ Once :ref:`installed ` the tool should be available as ``sqlite-ut
Running SQL queries
===================
-The ``sqlite-utils query`` command lets you run queries directly against a SQLite database file. This is the default subcommand, so the following two examples work the same way::
+The ``sqlite-utils query`` command lets you run queries directly against a SQLite database file. This is the default subcommand, so the following two examples work the same way:
- $ sqlite-utils query dogs.db "select * from dogs"
- $ sqlite-utils dogs.db "select * from dogs"
+.. code-block:: bash
+
+ sqlite-utils query dogs.db "select * from dogs"
+
+.. code-block:: bash
+
+ sqlite-utils dogs.db "select * from dogs"
.. note::
In Python: :ref:`db.query() ` CLI reference: :ref:`sqlite-utils query `
+Pass ``-`` as the SQL query to read the query from standard input. This is useful for longer queries that would otherwise require careful shell escaping, or for piping in SQL generated by another tool:
+
+.. code-block:: bash
+
+ echo "select * from dogs" | sqlite-utils query dogs.db -
+
+.. code-block:: bash
+
+ sqlite-utils query dogs.db - < query.sql
+
.. _cli_query_json:
Returning JSON
--------------
-The default format returned for queries is JSON::
+The default format returned for queries is JSON:
+
+.. code-block:: bash
+
+ sqlite-utils dogs.db "select * from dogs"
+
+.. code-block:: output
- $ sqlite-utils dogs.db "select * from dogs"
[{"id": 1, "age": 4, "name": "Cleo"},
{"id": 2, "age": 2, "name": "Pancakes"}]
+If the query returns more than one column with the same name, later occurrences are renamed with a numeric suffix - ``select 1 as id, 2 as id`` returns ``[{"id": 1, "id_2": 2}]``. This only applies to JSON output: :ref:`CSV and TSV ` and :ref:`table ` output keep the duplicate column headers unchanged.
+
.. _cli_query_nl:
Newline-delimited JSON
~~~~~~~~~~~~~~~~~~~~~~
-Use ``--nl`` to get back newline-delimited JSON objects::
+Use ``--nl`` to get back newline-delimited JSON objects:
+
+.. code-block:: bash
+
+ sqlite-utils dogs.db "select * from dogs" --nl
+
+.. code-block:: output
- $ sqlite-utils dogs.db "select * from dogs" --nl
{"id": 1, "age": 4, "name": "Cleo"}
{"id": 2, "age": 2, "name": "Pancakes"}
@@ -51,21 +78,36 @@ Use ``--nl`` to get back newline-delimited JSON objects::
JSON arrays
~~~~~~~~~~~
-You can use ``--arrays`` to request arrays instead of objects::
+You can use ``--arrays`` to request arrays instead of objects:
+
+.. code-block:: bash
+
+ sqlite-utils dogs.db "select * from dogs" --arrays
+
+.. code-block:: output
- $ sqlite-utils dogs.db "select * from dogs" --arrays
[[1, 4, "Cleo"],
[2, 2, "Pancakes"]]
-You can also combine ``--arrays`` and ``--nl``::
+You can also combine ``--arrays`` and ``--nl``:
+
+.. code-block:: bash
+
+ sqlite-utils dogs.db "select * from dogs" --arrays --nl
+
+.. code-block:: output
- $ sqlite-utils dogs.db "select * from dogs" --arrays --nl
[1, 4, "Cleo"]
[2, 2, "Pancakes"]
-If you want to pretty-print the output further, you can pipe it through ``python -mjson.tool``::
+If you want to pretty-print the output further, you can pipe it through ``python -mjson.tool``:
+
+.. code-block:: bash
+
+ sqlite-utils dogs.db "select * from dogs" | python -mjson.tool
+
+.. code-block:: output
- $ sqlite-utils dogs.db "select * from dogs" | python -mjson.tool
[
{
"id": 1,
@@ -79,14 +121,46 @@ If you want to pretty-print the output further, you can pipe it through ``python
}
]
+.. _cli_query_json_ascii:
+
+Unicode characters in JSON
+~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+JSON output includes unicode characters directly, without escaping them:
+
+.. code-block:: bash
+
+ sqlite-utils dogs.db "select '日本語' as text"
+
+.. code-block:: output
+
+ [{"text": "日本語"}]
+
+Use ``--ascii`` to escape non-ASCII characters as ``\uXXXX`` sequences instead:
+
+.. code-block:: bash
+
+ sqlite-utils dogs.db "select '日本語' as text" --ascii
+
+.. code-block:: output
+
+ [{"text": "\u65e5\u672c\u8a9e"}]
+
+The ``--ascii`` option can help on systems that cannot display or process UTF-8, such as Windows consoles using a legacy code page. On Windows, setting the ``PYTHONUTF8=1`` environment variable is an alternative fix for ``UnicodeEncodeError`` crashes when redirecting output to a file.
+
.. _cli_query_binary_json:
Binary data in JSON
~~~~~~~~~~~~~~~~~~~
-Binary strings are not valid JSON, so BLOB columns containing binary data will be returned as a JSON object containing base64 encoded data, that looks like this::
+Binary strings are not valid JSON, so BLOB columns containing binary data will be returned as a JSON object containing base64 encoded data, that looks like this:
+
+.. code-block:: bash
+
+ sqlite-utils dogs.db "select name, content from images" | python -mjson.tool
+
+.. code-block:: output
- $ sqlite-utils dogs.db "select name, content from images" | python -mjson.tool
[
{
"name": "transparent.gif",
@@ -97,15 +171,19 @@ Binary strings are not valid JSON, so BLOB columns containing binary data will b
}
]
-
.. _cli_json_values:
Nested JSON values
~~~~~~~~~~~~~~~~~~
-If one of your columns contains JSON, by default it will be returned as an escaped string::
+If one of your columns contains JSON, by default it will be returned as an escaped string:
+
+.. code-block:: bash
+
+ sqlite-utils dogs.db "select * from dogs" | python -mjson.tool
+
+.. code-block:: output
- $ sqlite-utils dogs.db "select * from dogs" | python -mjson.tool
[
{
"id": 1,
@@ -114,9 +192,14 @@ If one of your columns contains JSON, by default it will be returned as an escap
}
]
-You can use the ``--json-cols`` option to automatically detect these JSON columns and output them as nested JSON data::
+You can use the ``--json-cols`` option to automatically detect these JSON columns and output them as nested JSON data:
+
+.. code-block:: bash
+
+ sqlite-utils dogs.db "select * from dogs" --json-cols | python -mjson.tool
+
+.. code-block:: output
- $ sqlite-utils dogs.db "select * from dogs" --json-cols | python -mjson.tool
[
{
"id": 1,
@@ -137,22 +220,37 @@ You can use the ``--json-cols`` option to automatically detect these JSON column
Returning CSV or TSV
--------------------
-You can use the ``--csv`` option to return results as CSV::
+You can use the ``--csv`` option to return results as CSV:
+
+.. code-block:: bash
+
+ sqlite-utils dogs.db "select * from dogs" --csv
+
+.. code-block:: output
- $ sqlite-utils dogs.db "select * from dogs" --csv
id,age,name
1,4,Cleo
2,2,Pancakes
-This will default to including the column names as a header row. To exclude the headers, use ``--no-headers``::
+This will default to including the column names as a header row. To exclude the headers, use ``--no-headers``:
+
+.. code-block:: bash
+
+ sqlite-utils dogs.db "select * from dogs" --csv --no-headers
+
+.. code-block:: output
- $ sqlite-utils dogs.db "select * from dogs" --csv --no-headers
1,4,Cleo
2,2,Pancakes
-Use ``--tsv`` instead of ``--csv`` to get back tab-separated values::
+Use ``--tsv`` instead of ``--csv`` to get back tab-separated values:
+
+.. code-block:: bash
+
+ sqlite-utils dogs.db "select * from dogs" --tsv
+
+.. code-block:: output
- $ sqlite-utils dogs.db "select * from dogs" --tsv
id age name
1 4 Cleo
2 2 Pancakes
@@ -162,17 +260,27 @@ Use ``--tsv`` instead of ``--csv`` to get back tab-separated values::
Table-formatted output
----------------------
-You can use the ``--table`` option (or ``-t`` shortcut) to output query results as a table::
+You can use the ``--table`` option (or ``-t`` shortcut) to output query results as a table:
+
+.. code-block:: bash
+
+ sqlite-utils dogs.db "select * from dogs" --table
+
+.. code-block:: output
- $ sqlite-utils dogs.db "select * from dogs" --table
id age name
---- ----- --------
1 4 Cleo
2 2 Pancakes
-You can use the ``--fmt`` option to specify different table formats, for example ``rst`` for reStructuredText::
+You can use the ``--fmt`` option to specify different table formats, for example ``rst`` for reStructuredText:
+
+.. code-block:: bash
+
+ sqlite-utils dogs.db "select * from dogs" --fmt rst
+
+.. code-block:: output
- $ sqlite-utils dogs.db "select * from dogs" --fmt rst
==== ===== ========
id age name
==== ===== ========
@@ -188,6 +296,7 @@ Available ``--fmt`` options are:
.. ]]]
- ``asciidoc``
+- ``colon_grid``
- ``double_grid``
- ``double_outline``
- ``fancy_grid``
@@ -235,19 +344,31 @@ Returning raw data, such as binary content
If your table contains binary data in a ``BLOB`` you can use the ``--raw`` option to output specific columns directly to standard out.
-For example, to retrieve a binary image from a ``BLOB`` column and store it in a file you can use the following::
+For example, to retrieve a binary image from a ``BLOB`` column and store it in a file you can use the following:
- $ sqlite-utils photos.db "select contents from photos where id=1" --raw > myphoto.jpg
+.. code-block:: bash
+ sqlite-utils photos.db "select contents from photos where id=1" --raw > myphoto.jpg
+
+To return the first column of each result as raw data, separated by newlines, use ``--raw-lines``:
+
+.. code-block:: bash
+
+ sqlite-utils photos.db "select caption from photos" --raw-lines > captions.txt
.. _cli_query_parameters:
Using named parameters
----------------------
-You can pass named parameters to the query using ``-p``::
+You can pass named parameters to the query using ``-p name value``:
+
+.. code-block:: bash
+
+ sqlite-utils query dogs.db "select :num * :num2" -p num 5 -p num2 6
+
+.. code-block:: output
- $ sqlite-utils query dogs.db "select :num * :num2" -p num 5 -p num2 6
[{":num * :num2": 30}]
These will be correctly quoted and escaped in the SQL query, providing a safe way to combine other values with SQL.
@@ -257,9 +378,14 @@ These will be correctly quoted and escaped in the SQL query, providing a safe wa
UPDATE, INSERT and DELETE
-------------------------
-If you execute an ``UPDATE``, ``INSERT`` or ``DELETE`` query the command will return the number of affected rows::
+If you execute an ``UPDATE``, ``INSERT`` or ``DELETE`` query the command will return the number of affected rows:
+
+.. code-block:: bash
+
+ sqlite-utils dogs.db "update dogs set age = 5 where name = 'Cleo'"
+
+.. code-block:: output
- $ sqlite-utils dogs.db "update dogs set age = 5 where name = 'Cleo'"
[{"rows_affected": 1}]
.. _cli_query_functions:
@@ -269,9 +395,11 @@ Defining custom SQL functions
You can use the ``--functions`` option to pass a block of Python code that defines additional functions which can then be called by your SQL query.
-This example defines a function which extracts the domain from a URL::
+This example defines a function which extracts the domain from a URL:
- $ sqlite-utils query sites.db "select url, domain(url) from urls" --functions '
+.. code-block:: bash
+
+ sqlite-utils query sites.db "select url, domain(url) from urls" --functions '
from urllib.parse import urlparse
def domain(url):
@@ -280,6 +408,25 @@ This example defines a function which extracts the domain from a URL::
Every callable object defined in the block will be registered as a SQL function with the same name, with the exception of functions with names that begin with an underscore.
+You can also pass the path to a Python file containing function definitions:
+
+.. code-block:: bash
+
+ sqlite-utils query sites.db "select url, domain(url) from urls" --functions functions.py
+
+The ``--functions`` option can be used multiple times to load functions from multiple sources:
+
+.. code-block:: bash
+
+ sqlite-utils query sites.db "select url, domain(url), extract_path(url) from urls" \
+ --functions domain_funcs.py \
+ --functions 'def extract_path(url):
+ from urllib.parse import urlparse
+ return urlparse(url).path'
+
+.. note::
+ In Python: :ref:`db.register_function() `
+
.. _cli_query_extensions:
SQLite extensions
@@ -287,12 +434,14 @@ SQLite extensions
You can load SQLite extension modules using the ``--load-extension`` option, see :ref:`cli_load_extension`.
-::
+.. code-block:: bash
+
+ sqlite-utils dogs.db "select spatialite_version()" --load-extension=spatialite
+
+.. code-block:: output
- $ sqlite-utils dogs.db "select spatialite_version()" --load-extension=spatialite
[{"spatialite_version()": "4.3.0a"}]
-
.. _cli_query_attach:
Attaching additional databases
@@ -302,7 +451,9 @@ SQLite supports cross-database SQL queries, which can join data from tables in m
You can attach one or more additional databases using the ``--attach`` option, providing an alias to use for that database and the path to the SQLite file on disk.
-This example attaches the ``books.db`` database under the alias ``books`` and then runs a query that combines data from that database with the default ``dogs.db`` database::
+This example attaches the ``books.db`` database under the alias ``books`` and then runs a query that combines data from that database with the default ``dogs.db`` database:
+
+.. code-block:: bash
sqlite-utils dogs.db --attach books books.db \
'select * from sqlite_master union all select * from books.sqlite_master'
@@ -319,17 +470,33 @@ The ``sqlite-utils memory`` command works similar to ``sqlite-utils query``, but
You can also pass this command CSV or JSON files which will be loaded into a temporary in-memory table, allowing you to execute SQL against that data without a separate step to first convert it to SQLite.
-Without any extra arguments, this command executes SQL against the in-memory database directly::
+Without any extra arguments, this command executes SQL against the in-memory database directly:
+
+.. code-block:: bash
+
+ sqlite-utils memory 'select sqlite_version()'
+
+.. code-block:: output
- $ sqlite-utils memory 'select sqlite_version()'
[{"sqlite_version()": "3.35.5"}]
-It takes all of the same output formatting options as :ref:`sqlite-utils query `: ``--csv`` and ``--csv`` and ``--table`` and ``--nl``::
+It takes all of the same output formatting options as :ref:`sqlite-utils query `: ``--csv`` and ``--csv`` and ``--table`` and ``--nl``:
+
+.. code-block:: bash
+
+ sqlite-utils memory 'select sqlite_version()' --csv
+
+.. code-block:: output
- $ sqlite-utils memory 'select sqlite_version()' --csv
sqlite_version()
3.35.5
- $ sqlite-utils memory 'select sqlite_version()' --fmt grid
+
+.. code-block:: bash
+
+ sqlite-utils memory 'select sqlite_version()' --fmt grid
+
+.. code-block:: output
+
+--------------------+
| sqlite_version() |
+====================+
@@ -341,37 +508,50 @@ It takes all of the same output formatting options as :ref:`sqlite-utils query <
Running queries directly against CSV or JSON
--------------------------------------------
-If you have data in CSV or JSON format you can load it into an in-memory SQLite database and run queries against it directly in a single command using ``sqlite-utils memory`` like this::
+If you have data in CSV or JSON format you can load it into an in-memory SQLite database and run queries against it directly in a single command using ``sqlite-utils memory`` like this:
- $ sqlite-utils memory data.csv "select * from data"
+.. code-block:: bash
-You can pass multiple files to the command if you want to run joins between data from different files::
+ sqlite-utils memory data.csv "select * from data"
- $ sqlite-utils memory one.csv two.json "select * from one join two on one.id = two.other_id"
+You can pass multiple files to the command if you want to run joins between data from different files:
+
+.. code-block:: bash
+
+ sqlite-utils memory one.csv two.json \
+ "select * from one join two on one.id = two.other_id"
If your data is JSON it should be the same format supported by the :ref:`sqlite-utils insert command ` - so either a single JSON object (treated as a single row) or a list of JSON objects.
CSV data can be comma- or tab- delimited.
-The in-memory tables will be named after the files without their extensions. The tool also sets up aliases for those tables (using SQL views) as ``t1``, ``t2`` and so on, or you can use the alias ``t`` to refer to the first table::
+The in-memory tables will be named after the files without their extensions. The tool also sets up aliases for those tables (using SQL views) as ``t1``, ``t2`` and so on, or you can use the alias ``t`` to refer to the first table:
- $ sqlite-utils memory example.csv "select * from t"
+.. code-block:: bash
-If two files have the same name they will be assigned a numeric suffix::
+ sqlite-utils memory example.csv "select * from t"
- $ sqlite-utils memory foo/data.csv bar/data.csv "select * from data_2"
+If two files have the same name they will be assigned a numeric suffix:
-To read from standard input, use either ``-`` or ``stdin`` as the filename - then use ``stdin`` or ``t`` or ``t1`` as the table name::
+.. code-block:: bash
- $ cat example.csv | sqlite-utils memory - "select * from stdin"
+ sqlite-utils memory foo/data.csv bar/data.csv "select * from data_2"
-Incoming CSV data will be assumed to use ``utf-8``. If your data uses a different character encoding you can specify that with ``--encoding``::
+To read from standard input, use either ``-`` or ``stdin`` as the filename - then use ``stdin`` or ``t`` or ``t1`` as the table name:
- $ cat example.csv | sqlite-utils memory - "select * from stdin" --encoding=latin-1
+.. code-block:: bash
+
+ cat example.csv | sqlite-utils memory - "select * from stdin"
+
+Incoming CSV data will be assumed to use ``utf-8``. If your data uses a different character encoding you can specify that with ``--encoding``:
+
+.. code-block:: bash
+
+ cat example.csv | sqlite-utils memory - "select * from stdin" --encoding=latin-1
If you are joining across multiple CSV files they must all use the same encoding.
-Column types will be automatically detected in CSV or TSV data, using the same mechanism as ``--detect-types`` described in :ref:`cli_insert_csv_tsv`. You can pass the ``--no-detect-types`` option to disable this automatic type detection and treat all CSV and TSV columns as ``TEXT``.
+Column types will be automatically detected in CSV or TSV data, as described in :ref:`cli_insert_csv_tsv`. You can pass the ``--no-detect-types`` option to disable this automatic type detection and treat all CSV and TSV columns as ``TEXT``.
.. _cli_memory_explicit:
@@ -380,24 +560,31 @@ Explicitly specifying the format
By default, ``sqlite-utils memory`` will attempt to detect the incoming data format (JSON, TSV or CSV) automatically.
-You can instead specify an explicit format by adding a ``:csv``, ``:tsv``, ``:json`` or ``:nl`` (for newline-delimited JSON) suffix to the filename. For example::
+You can instead specify an explicit format by adding a ``:csv``, ``:tsv``, ``:json`` or ``:nl`` (for newline-delimited JSON) suffix to the filename. For example:
- $ sqlite-utils memory one.dat:csv two.dat:nl "select * from one union select * from two"
+.. code-block:: bash
+
+ sqlite-utils memory one.dat:csv two.dat:nl \
+ "select * from one union select * from two"
Here the contents of ``one.dat`` will be treated as CSV and the contents of ``two.dat`` will be treated as newline-delimited JSON.
-To explicitly specify the format for data piped into the tool on standard input, use ``stdin:format`` - for example::
+To explicitly specify the format for data piped into the tool on standard input, use ``stdin:format`` - for example:
- $ cat one.dat | sqlite-utils memory stdin:csv "select * from stdin"
+.. code-block:: bash
+
+ cat one.dat | sqlite-utils memory stdin:csv "select * from stdin"
.. _cli_memory_attach:
Joining in-memory data against existing databases using \-\-attach
------------------------------------------------------------------
-The :ref:`attach option ` can be used to attach database files to the in-memory connection, enabling joins between in-memory data loaded from a file and tables in existing SQLite database files. An example::
+The :ref:`attach option ` can be used to attach database files to the in-memory connection, enabling joins between in-memory data loaded from a file and tables in existing SQLite database files. An example:
- $ echo "id\n1\n3\n5" | sqlite-utils memory - --attach trees trees.db \
+.. code-block:: bash
+
+ echo "id\n1\n3\n5" | sqlite-utils memory - --attach trees trees.db \
"select * from trees.trees where rowid in (select id from stdin)"
Here the ``--attach trees trees.db`` option makes the ``trees.db`` database available with an alias of ``trees``.
@@ -411,20 +598,30 @@ The CSV data that was piped into the script is available in the ``stdin`` table,
\-\-schema, \-\-analyze, \-\-dump and \-\-save
----------------------------------------------
-To see the in-memory database schema that would be used for a file or for multiple files, use ``--schema``::
+To see the in-memory database schema that would be used for a file or for multiple files, use ``--schema``:
- % sqlite-utils memory dogs.csv --schema
- CREATE TABLE [dogs] (
- [id] INTEGER,
- [age] INTEGER,
- [name] TEXT
+.. code-block:: bash
+
+ sqlite-utils memory dogs.csv --schema
+
+.. code-block:: output
+
+ CREATE TABLE "dogs" (
+ "id" INTEGER,
+ "age" INTEGER,
+ "name" TEXT
);
- CREATE VIEW t1 AS select * from [dogs];
- CREATE VIEW t AS select * from [dogs];
+ CREATE VIEW "t1" AS select * from "dogs";
+ CREATE VIEW "t" AS select * from "dogs";
-You can run the equivalent of the :ref:`analyze-tables ` command using ``--analyze``::
+You can run the equivalent of the :ref:`analyze-tables ` command using ``--analyze``:
+
+.. code-block:: bash
+
+ sqlite-utils memory dogs.csv --analyze
+
+.. code-block:: output
- % sqlite-utils memory dogs.csv --analyze
dogs.id: (1/3)
Total rows: 2
@@ -449,24 +646,31 @@ You can run the equivalent of the :ref:`analyze-tables ` com
Distinct values: 2
-You can output SQL that will both create the tables and insert the full data used to populate the in-memory database using ``--dump``::
+You can output SQL that will both create the tables and insert the full data used to populate the in-memory database using ``--dump``:
+
+.. code-block:: bash
+
+ sqlite-utils memory dogs.csv --dump
+
+.. code-block:: output
- % sqlite-utils memory dogs.csv --dump
BEGIN TRANSACTION;
- CREATE TABLE [dogs] (
- [id] INTEGER,
- [age] INTEGER,
- [name] TEXT
+ CREATE TABLE "dogs" (
+ "id" INTEGER,
+ "age" INTEGER,
+ "name" TEXT
);
INSERT INTO "dogs" VALUES('1','4','Cleo');
INSERT INTO "dogs" VALUES('2','2','Pancakes');
- CREATE VIEW t1 AS select * from [dogs];
- CREATE VIEW t AS select * from [dogs];
+ CREATE VIEW "t1" AS select * from "dogs";
+ CREATE VIEW "t" AS select * from "dogs";
COMMIT;
-Passing ``--save other.db`` will instead use that SQL to populate a new database file::
+Passing ``--save other.db`` will instead use that SQL to populate a new database file:
- % sqlite-utils memory dogs.csv --save dogs.db
+.. code-block:: bash
+
+ sqlite-utils memory dogs.csv --save dogs.db
These features are mainly intended as debugging tools - for much more finely grained control over how data is inserted into a SQLite database file see :ref:`cli_inserting_data` and :ref:`cli_insert_csv_tsv`.
@@ -475,28 +679,48 @@ These features are mainly intended as debugging tools - for much more finely gra
Returning all rows in a table
=============================
-You can return every row in a specified table using the ``rows`` command::
+You can return every row in a specified table using the ``rows`` command:
+
+.. code-block:: bash
+
+ sqlite-utils rows dogs.db dogs
+
+.. code-block:: output
- $ sqlite-utils rows dogs.db dogs
[{"id": 1, "age": 4, "name": "Cleo"},
{"id": 2, "age": 2, "name": "Pancakes"}]
This command accepts the same output options as ``query`` - so you can pass ``--nl``, ``--csv``, ``--tsv``, ``--no-headers``, ``--table`` and ``--fmt``.
-You can use the ``-c`` option to specify a subset of columns to return::
+You can use the ``-c`` option to specify a subset of columns to return:
+
+.. code-block:: bash
+
+ sqlite-utils rows dogs.db dogs -c age -c name
+
+.. code-block:: output
- $ sqlite-utils rows dogs.db dogs -c age -c name
[{"age": 4, "name": "Cleo"},
{"age": 2, "name": "Pancakes"}]
-You can filter rows using a where clause with the ``--where`` option::
+You can filter rows using a where clause with the ``--where`` option:
+
+.. code-block:: bash
+
+ sqlite-utils rows dogs.db dogs -c name --where 'name = "Cleo"'
+
+.. code-block:: output
- $ sqlite-utils rows dogs.db dogs -c name --where 'name = "Cleo"'
[{"name": "Cleo"}]
-Or pass named parameters using ``--where`` in combination with ``-p``::
+Or pass named parameters using ``--where`` in combination with ``-p``:
+
+.. code-block:: bash
+
+ sqlite-utils rows dogs.db dogs -c name --where 'name = :name' -p name Cleo
+
+.. code-block:: output
- $ sqlite-utils rows dogs.db dogs -c name --where 'name = :name' -p name Cleo
[{"name": "Cleo"}]
You can define a sort order using ``--order column`` or ``--order 'column desc'``.
@@ -511,50 +735,80 @@ Use ``--limit N`` to only return the first ``N`` rows. Use ``--offset N`` to ret
Listing tables
==============
-You can list the names of tables in a database using the ``tables`` command::
+You can list the names of tables in a database using the ``tables`` command:
+
+.. code-block:: bash
+
+ sqlite-utils tables mydb.db
+
+.. code-block:: output
- $ sqlite-utils tables mydb.db
[{"table": "dogs"},
{"table": "cats"},
{"table": "chickens"}]
-You can output this list in CSV using the ``--csv`` or ``--tsv`` options::
+You can output this list in CSV using the ``--csv`` or ``--tsv`` options:
+
+.. code-block:: bash
+
+ sqlite-utils tables mydb.db --csv --no-headers
+
+.. code-block:: output
- $ sqlite-utils tables mydb.db --csv --no-headers
dogs
cats
chickens
-If you just want to see the FTS4 tables, you can use ``--fts4`` (or ``--fts5`` for FTS5 tables)::
+If you just want to see the FTS4 tables, you can use ``--fts4`` (or ``--fts5`` for FTS5 tables):
+
+.. code-block:: bash
+
+ sqlite-utils tables docs.db --fts4
+
+.. code-block:: output
- $ sqlite-utils tables docs.db --fts4
[{"table": "docs_fts"}]
-Use ``--counts`` to include a count of the number of rows in each table::
+Use ``--counts`` to include a count of the number of rows in each table:
+
+.. code-block:: bash
+
+ sqlite-utils tables mydb.db --counts
+
+.. code-block:: output
- $ sqlite-utils tables mydb.db --counts
[{"table": "dogs", "count": 12},
{"table": "cats", "count": 332},
{"table": "chickens", "count": 9}]
-Use ``--columns`` to include a list of columns in each table::
+Use ``--columns`` to include a list of columns in each table:
+
+.. code-block:: bash
+
+ sqlite-utils tables dogs.db --counts --columns
+
+.. code-block:: output
- $ sqlite-utils tables dogs.db --counts --columns
[{"table": "Gosh", "count": 0, "columns": ["c1", "c2", "c3"]},
{"table": "Gosh2", "count": 0, "columns": ["c1", "c2", "c3"]},
{"table": "dogs", "count": 2, "columns": ["id", "age", "name"]}]
-Use ``--schema`` to include the schema of each table::
+Use ``--schema`` to include the schema of each table:
+
+.. code-block:: bash
+
+ sqlite-utils tables dogs.db --schema --table
+
+.. code-block:: output
- $ sqlite-utils tables dogs.db --schema --table
table schema
------- -----------------------------------------------
Gosh CREATE TABLE Gosh (c1 text, c2 text, c3 text)
Gosh2 CREATE TABLE Gosh2 (c1 text, c2 text, c3 text)
- dogs CREATE TABLE [dogs] (
- [id] INTEGER,
- [age] INTEGER,
- [name] TEXT)
+ dogs CREATE TABLE "dogs" (
+ "id" INTEGER,
+ "age" INTEGER,
+ "name" TEXT)
The ``--nl``, ``--csv``, ``--tsv``, ``--table`` and ``--fmt`` options are also available.
@@ -566,9 +820,14 @@ The ``--nl``, ``--csv``, ``--tsv``, ``--table`` and ``--fmt`` options are also a
Listing views
=============
-The ``views`` command shows any views defined in the database::
+The ``views`` command shows any views defined in the database:
+
+.. code-block:: bash
+
+ sqlite-utils views sf-trees.db --table --counts --columns --schema
+
+.. code-block:: output
- $ sqlite-utils views sf-trees.db --table --counts --columns --schema
view count columns schema
--------- ------- -------------------- --------------------------------------------------------------
demo_view 189144 ['qSpecies'] CREATE VIEW demo_view AS select qSpecies from Street_Tree_List
@@ -592,9 +851,14 @@ It takes the same options as the ``tables`` command:
Listing indexes
===============
-The ``indexes`` command lists any indexes configured for the database::
+The ``indexes`` command lists any indexes configured for the database:
+
+.. code-block:: bash
+
+ sqlite-utils indexes covid.db --table
+
+.. code-block:: output
- $ sqlite-utils indexes covid.db --table
table index_name seqno cid name desc coll key
-------------------------------- ------------------------------------------------------ ------- ----- ----------------- ------ ------ -----
johns_hopkins_csse_daily_reports idx_johns_hopkins_csse_daily_reports_combined_key 0 12 combined_key 0 BINARY 1
@@ -606,9 +870,11 @@ The ``indexes`` command lists any indexes configured for the database::
ny_times_us_counties idx_ny_times_us_counties_county 0 1 county 0 BINARY 1
ny_times_us_counties idx_ny_times_us_counties_state 0 2 state 0 BINARY 1
-It shows indexes across all tables. To see indexes for specific tables, list those after the database::
+It shows indexes across all tables. To see indexes for specific tables, list those after the database:
- $ sqlite-utils indexes covid.db johns_hopkins_csse_daily_reports --table
+.. code-block:: bash
+
+ sqlite-utils indexes covid.db johns_hopkins_csse_daily_reports --table
The command defaults to only showing the columns that are explicitly part of the index. To also include auxiliary columns use the ``--aux`` option - these columns will be listed with a ``key`` of ``0``.
@@ -622,26 +888,33 @@ The command takes the same format options as the ``tables`` and ``views`` comman
Listing triggers
================
-The ``triggers`` command shows any triggers configured for the database::
+The ``triggers`` command shows any triggers configured for the database:
+
+.. code-block:: bash
+
+ sqlite-utils triggers global-power-plants.db --table
+
+.. code-block:: output
- $ sqlite-utils triggers global-power-plants.db --table
name table sql
--------------- --------- -----------------------------------------------------------------
- plants_insert plants CREATE TRIGGER [plants_insert] AFTER INSERT ON [plants]
+ plants_insert plants CREATE TRIGGER "plants_insert" AFTER INSERT ON "plants"
BEGIN
- INSERT OR REPLACE INTO [_counts]
+ INSERT OR REPLACE INTO "_counts"
VALUES (
'plants',
COALESCE(
- (SELECT count FROM [_counts] WHERE [table] = 'plants'),
+ (SELECT count FROM "_counts" WHERE "table" = 'plants'),
0
) + 1
);
END
-It defaults to showing triggers for all tables. To see triggers for one or more specific tables pass their names as arguments::
+It defaults to showing triggers for all tables. To see triggers for one or more specific tables pass their names as arguments:
- $ sqlite-utils triggers global-power-plants.db plants
+.. code-block:: bash
+
+ sqlite-utils triggers global-power-plants.db plants
The command takes the same format options as the ``tables`` and ``views`` commands.
@@ -653,18 +926,24 @@ The command takes the same format options as the ``tables`` and ``views`` comman
Showing the schema
==================
-The ``sqlite-utils schema`` command shows the full SQL schema for the database::
+The ``sqlite-utils schema`` command shows the full SQL schema for the database:
+
+.. code-block:: bash
+
+ sqlite-utils schema dogs.db
+
+.. code-block:: output
- $ sqlite-utils schema dogs.db
CREATE TABLE "dogs" (
- [id] INTEGER PRIMARY KEY,
- [name] TEXT
+ "id" INTEGER PRIMARY KEY,
+ "name" TEXT
);
-This will show the schema for every table and index in the database. To view the schema just for a specified subset of tables pass those as additional arguments::
+This will show the schema for every table and index in the database. To view the schema just for a specified subset of tables pass those as additional arguments:
- $ sqlite-utils schema dogs.db dogs chickens
- ...
+.. code-block:: bash
+
+ sqlite-utils schema dogs.db dogs chickens
.. note::
In Python: :ref:`table.schema ` or :ref:`db.schema ` CLI reference: :ref:`sqlite-utils schema `
@@ -676,9 +955,14 @@ Analyzing tables
When working with a new database it can be useful to get an idea of the shape of the data. The ``sqlite-utils analyze-tables`` command inspects specified tables (or all tables) and calculates some useful details about each of the columns in those tables.
-To inspect the ``tags`` table in the ``github.db`` database, run the following::
+To inspect the ``tags`` table in the ``github.db`` database, run the following:
+
+.. code-block:: bash
+
+ sqlite-utils analyze-tables github.db tags
+
+.. code-block:: output
- $ sqlite-utils analyze-tables github.db tags
tags.repo: (1/3)
Total rows: 261
@@ -725,38 +1009,57 @@ To inspect the ``tags`` table in the ``github.db`` database, run the following::
For each column this tool displays the number of null rows, the number of blank rows (rows that contain an empty string), the number of distinct values and, for columns that are not entirely distinct, the most common and least common values.
-If you do not specify any tables every table in the database will be analyzed::
+If you do not specify any tables every table in the database will be analyzed:
- $ sqlite-utils analyze-tables github.db
+.. code-block:: bash
-If you wish to analyze one or more specific columns, use the ``-c`` option::
+ sqlite-utils analyze-tables github.db
- $ sqlite-utils analyze-tables github.db tags -c sha
+If you wish to analyze one or more specific columns, use the ``-c`` option:
+
+.. code-block:: bash
+
+ sqlite-utils analyze-tables github.db tags -c sha
+
+To show more than 10 common values, use ``--common-limit 20``. To skip the most common or least common value analysis, use ``--no-most`` or ``--no-least``:
+
+.. code-block:: bash
+
+ sqlite-utils analyze-tables github.db tags --common-limit 20 --no-least
+
+.. note::
+ In Python: :ref:`table.analyze_column() ` CLI reference: :ref:`sqlite-utils analyze-tables `
.. _cli_analyze_tables_save:
Saving the analyzed table details
---------------------------------
-``analyze-tables`` can take quite a while to run for large database files. You can save the results of the analysis to a database table called ``_analyze_tables_`` using the ``--save`` option::
+``analyze-tables`` can take quite a while to run for large database files. You can save the results of the analysis to a database table called ``_analyze_tables_`` using the ``--save`` option:
- $ sqlite-utils analyze-tables github.db --save
+.. code-block:: bash
-The ``_analyze_tables_`` table has the following schema::
+ sqlite-utils analyze-tables github.db --save
- CREATE TABLE [_analyze_tables_] (
- [table] TEXT,
- [column] TEXT,
- [total_rows] INTEGER,
- [num_null] INTEGER,
- [num_blank] INTEGER,
- [num_distinct] INTEGER,
- [most_common] TEXT,
- [least_common] TEXT,
- PRIMARY KEY ([table], [column])
+The ``_analyze_tables_`` table has the following schema:
+
+.. code-block:: sql
+
+ CREATE TABLE "_analyze_tables_" (
+ "table" TEXT,
+ "column" TEXT,
+ "total_rows" INTEGER,
+ "num_null" INTEGER,
+ "num_blank" INTEGER,
+ "num_distinct" INTEGER,
+ "most_common" TEXT,
+ "least_common" TEXT,
+ PRIMARY KEY ("table", "column")
);
-The ``most_common`` and ``least_common`` columns will contain nested JSON arrays of the most common and least common values that look like this::
+The ``most_common`` and ``least_common`` columns will contain nested JSON arrays of the most common and least common values that look like this:
+
+.. code-block:: json
[
["Del Libertador, Av", 5068],
@@ -776,21 +1079,60 @@ The ``most_common`` and ``least_common`` columns will contain nested JSON arrays
Creating an empty database
==========================
-You can create a new empty database file using the ``create-database`` command::
+You can create a new empty database file using the ``create-database`` command:
- $ sqlite-utils create-database empty.db
+.. code-block:: bash
-To enable :ref:`cli_wal` on the newly created database add the ``--enable-wal`` option::
+ sqlite-utils create-database empty.db
- $ sqlite-utils create-database empty.db --enable-wal
+To enable :ref:`cli_wal` on the newly created database add the ``--enable-wal`` option:
-To enable SpatiaLite metadata on a newly created database, add the ``--init-spatialite`` flag::
+.. code-block:: bash
- $ sqlite-utils create-database empty.db --init-spatialite
+ sqlite-utils create-database empty.db --enable-wal
-That will look for SpatiaLite in a set of predictable locations. To load it from somewhere else, use the ``--load-extension`` option::
+To enable SpatiaLite metadata on a newly created database, add the ``--init-spatialite`` flag:
- $ sqlite-utils create-database empty.db --init-spatialite --load-extension /path/to/spatialite.so
+.. code-block:: bash
+
+ sqlite-utils create-database empty.db --init-spatialite
+
+That will look for SpatiaLite in a set of predictable locations. To load it from somewhere else, use the ``--load-extension`` option:
+
+.. code-block:: bash
+
+ sqlite-utils create-database empty.db --init-spatialite --load-extension /path/to/spatialite.so
+
+.. _cli_migrate:
+
+Running migrations
+==================
+
+The ``migrate`` command applies pending Python migrations to a database. For the full migration file format and Python API, see :ref:`migrations`.
+
+.. code-block:: bash
+
+ sqlite-utils migrate creatures.db path/to/migrations.py
+
+If you omit the migration path it will search the current directory and subdirectories for files called ``migrations.py``:
+
+.. code-block:: bash
+
+ sqlite-utils migrate creatures.db
+
+Use ``--list`` to list applied and pending migrations without running them:
+
+.. code-block:: bash
+
+ sqlite-utils migrate creatures.db --list
+
+Use ``--stop-before`` to stop before a named migration. The option can be passed more than once, and can target a specific migration set using ``migration_set:migration_name``:
+
+.. code-block:: bash
+
+ sqlite-utils migrate creatures.db path/to/migrations.py \
+ --stop-before creatures:add_weight \
+ --stop-before sales:drop_index
.. _cli_inserting_data:
@@ -801,15 +1143,19 @@ If you have data as JSON, you can use ``sqlite-utils insert tablename`` to inser
You can pass in a single JSON object or a list of JSON objects, either as a filename or piped directly to standard-in (by using ``-`` as the filename).
-Here's the simplest possible example::
+Here's the simplest possible example:
- $ echo '{"name": "Cleo", "age": 4}' | sqlite-utils insert dogs.db dogs -
+.. code-block:: bash
+
+ echo '{"name": "Cleo", "age": 4}' | sqlite-utils insert dogs.db dogs -
To specify a column as the primary key, use ``--pk=column_name``.
To create a compound primary key across more than one column, use ``--pk`` multiple times.
-If you feed it a JSON list it will insert multiple records. For example, if ``dogs.json`` looks like this::
+If you feed it a JSON list it will insert multiple records. For example, if ``dogs.json`` looks like this:
+
+.. code-block:: json
[
{
@@ -829,26 +1175,39 @@ If you feed it a JSON list it will insert multiple records. For example, if ``do
}
]
-You can import all three records into an automatically created ``dogs`` table and set the ``id`` column as the primary key like so::
+You can import all three records into an automatically created ``dogs`` table and set the ``id`` column as the primary key like so:
- $ sqlite-utils insert dogs.db dogs dogs.json --pk=id
+.. code-block:: bash
-You can skip inserting any records that have a primary key that already exists using ``--ignore``::
+ sqlite-utils insert dogs.db dogs dogs.json --pk=id
- $ sqlite-utils insert dogs.db dogs dogs.json --ignore
+Pass ``--pk`` multiple times to define a compound primary key.
-You can delete all the existing rows in the table before inserting the new records using ``--truncate``::
+You can skip inserting any records that have a primary key that already exists using ``--ignore``:
- $ sqlite-utils insert dogs.db dogs dogs.json --truncate
+.. code-block:: bash
+
+ sqlite-utils insert dogs.db dogs dogs.json --pk=id --ignore
+
+You can delete all the existing rows in the table before inserting the new records using ``--truncate``:
+
+.. code-block:: bash
+
+ sqlite-utils insert dogs.db dogs dogs.json --truncate
You can add the ``--analyze`` option to run ``ANALYZE`` against the table after the rows have been inserted.
+.. note::
+ In Python: :ref:`table.insert_all() ` CLI reference: :ref:`sqlite-utils insert `
+
.. _cli_inserting_data_binary:
Inserting binary data
---------------------
-You can insert binary data into a BLOB column by first encoding it using base64 and then structuring it like this::
+You can insert binary data into a BLOB column by first encoding it using base64 and then structuring it like this:
+
+.. code-block:: json
[
{
@@ -865,27 +1224,38 @@ You can insert binary data into a BLOB column by first encoding it using base64
Inserting newline-delimited JSON
--------------------------------
-You can also import `newline-delimited JSON `__ using the ``--nl`` option::
+You can also import newline-delimited JSON (see `JSON Lines `__) using the ``--nl`` option:
- $ echo '{"id": 1, "name": "Cleo"}
+.. code-block:: bash
+
+ echo '{"id": 1, "name": "Cleo"}
{"id": 2, "name": "Suna"}' | sqlite-utils insert creatures.db creatures - --nl
Newline-delimited JSON consists of full JSON objects separated by newlines.
If you are processing data using ``jq`` you can use the ``jq -c`` option to output valid newline-delimited JSON.
-Since `Datasette `__ can export newline-delimited JSON, you can combine the Datasette and ``sqlite-utils`` like so::
+Since `Datasette `__ can export newline-delimited JSON, you can combine the Datasette and ``sqlite-utils`` like so:
- $ curl -L "https://latest.datasette.io/fixtures/facetable.json?_shape=array&_nl=on" \
+.. code-block:: bash
+
+ curl -L "https://latest.datasette.io/fixtures/facetable.json?_shape=array&_nl=on" \
| sqlite-utils insert nl-demo.db facetable - --pk=id --nl
-You can also pipe ``sqlite-utils`` together to create a new SQLite database file containing the results of a SQL query against another database::
+You can also pipe ``sqlite-utils`` together to create a new SQLite database file containing the results of a SQL query against another database:
- $ sqlite-utils sf-trees.db \
+.. code-block:: bash
+
+ sqlite-utils sf-trees.db \
"select TreeID, qAddress, Latitude, Longitude from Street_Tree_List" --nl \
| sqlite-utils insert saved.db trees - --nl
- # This creates saved.db with a single table called trees:
- $ sqlite-utils saved.db "select * from trees limit 5" --csv
+
+.. code-block:: bash
+
+ sqlite-utils saved.db "select * from trees limit 5" --csv
+
+.. code-block:: output
+
TreeID,qAddress,Latitude,Longitude
141565,501X Baker St,37.7759676911831,-122.441396661871
232565,940 Elizabeth St,37.7517102172731,-122.441498017841
@@ -902,7 +1272,9 @@ Flattening nested JSON objects
If your data is nested you can use the ``--flatten`` option to create columns that are derived from the nested data.
-Consider this example document, in a file called ``log.json``::
+Consider this example document, in a file called ``log.json``:
+
+.. code-block:: json
{
"httpRequest": {
@@ -917,23 +1289,27 @@ Consider this example document, in a file called ``log.json``::
}
}
-Inserting this into a table using ``sqlite-utils insert logs.db logs log.json`` will create a table with the following schema::
+Inserting this into a table using ``sqlite-utils insert logs.db logs log.json`` will create a table with the following schema:
- CREATE TABLE [logs] (
- [httpRequest] TEXT,
- [insertId] TEXT,
- [labels] TEXT
+.. code-block:: sql
+
+ CREATE TABLE "logs" (
+ "httpRequest" TEXT,
+ "insertId" TEXT,
+ "labels" TEXT
);
-With the ``--flatten`` option columns will be created using ``topkey_nextkey`` column names - so running ``sqlite-utils insert logs.db logs log.json --flatten`` will create the following schema instead::
+With the ``--flatten`` option columns will be created using ``topkey_nextkey`` column names - so running ``sqlite-utils insert logs.db logs log.json --flatten`` will create the following schema instead:
- CREATE TABLE [logs] (
- [httpRequest_latency] TEXT,
- [httpRequest_requestMethod] TEXT,
- [httpRequest_requestSize] TEXT,
- [httpRequest_status] INTEGER,
- [insertId] TEXT,
- [labels_service] TEXT
+.. code-block:: sql
+
+ CREATE TABLE "logs" (
+ "httpRequest_latency" TEXT,
+ "httpRequest_requestMethod" TEXT,
+ "httpRequest_requestSize" TEXT,
+ "httpRequest_status" INTEGER,
+ "insertId" TEXT,
+ "labels_service" TEXT
);
.. _cli_insert_csv_tsv:
@@ -941,44 +1317,104 @@ With the ``--flatten`` option columns will be created using ``topkey_nextkey`` c
Inserting CSV or TSV data
=========================
-If your data is in CSV format, you can insert it using the ``--csv`` option::
+If your data is in CSV format, you can insert it using the ``--csv`` option:
- $ sqlite-utils insert dogs.db dogs dogs.csv --csv
+.. code-block:: bash
-For tab-delimited data, use ``--tsv``::
+ sqlite-utils insert dogs.db dogs dogs.csv --csv
- $ sqlite-utils insert dogs.db dogs dogs.tsv --tsv
+For tab-delimited data, use ``--tsv``:
-Data is expected to be encoded as Unicode UTF-8. If your data is an another character encoding you can specify it using the ``--encoding`` option::
+.. code-block:: bash
- $ sqlite-utils insert dogs.db dogs dogs.tsv --tsv --encoding=latin-1
+ sqlite-utils insert dogs.db dogs dogs.tsv --tsv
+
+Data is expected to be encoded as Unicode UTF-8. If your data is an another character encoding you can specify it using the ``--encoding`` option:
+
+.. code-block:: bash
+
+ sqlite-utils insert dogs.db dogs dogs.tsv --tsv --encoding=latin-1
+
+To stop inserting after a specified number of records - useful for getting a faster preview of a large file - use the ``--stop-after`` option:
+
+.. code-block:: bash
+
+ sqlite-utils insert dogs.db dogs dogs.csv --csv --stop-after=10
A progress bar is displayed when inserting data from a file. You can hide the progress bar using the ``--silent`` option.
-By default every column inserted from a CSV or TSV file will be of type ``TEXT``. To automatically detect column types - resulting in a mix of ``TEXT``, ``INTEGER`` and ``FLOAT`` columns, use the ``--detect-types`` option (or its shortcut ``-d``).
+By default, column types are automatically detected for CSV or TSV files - resulting in a mix of ``TEXT``, ``INTEGER`` and ``REAL`` columns. To disable type detection and treat all columns as ``TEXT``, use the ``--no-detect-types`` option.
-For example, given a ``creatures.csv`` file containing this::
+Detected types are only applied when the table is created by the command. Inserting CSV or TSV data into a table that already exists leaves the existing column types unchanged - values are inserted using the table's existing schema.
+
+For example, given a ``creatures.csv`` file containing this:
+
+.. code-block::
name,age,weight
Cleo,6,45.5
Dori,1,3.5
-The following command::
+The following command:
- $ sqlite-utils insert creatures.db creatures creatures.csv --csv --detect-types
+.. code-block:: bash
-Will produce this schema::
+ sqlite-utils insert creatures.db creatures creatures.csv --csv
+
+Will produce this schema with automatically detected types:
+
+.. code-block:: bash
+
+ sqlite-utils schema creatures.db
+
+.. code-block:: output
- $ sqlite-utils schema creatures.db
CREATE TABLE "creatures" (
- [name] TEXT,
- [age] INTEGER,
- [weight] FLOAT
+ "name" TEXT,
+ "age" INTEGER,
+ "weight" REAL
);
-You can set the ``SQLITE_UTILS_DETECT_TYPES`` environment variable if you want ``--detect-types`` to be the default behavior::
+.. _cli_insert_csv_tsv_column_types:
- $ export SQLITE_UTILS_DETECT_TYPES=1
+Overriding column types
+-----------------------
+
+Use ``--type column-name type`` to override the type automatically chosen when the table is created. This option can be used more than once, and works with both ``insert`` and ``upsert``:
+
+.. code-block:: bash
+
+ sqlite-utils insert places.db places places.csv --csv \
+ --type zipcode text \
+ --type score real
+
+This is useful for values such as ZIP codes, which may look like integers but should be stored as ``TEXT`` to preserve leading zeros.
+
+The column type should be one of ``TEXT``, ``INTEGER``, ``FLOAT``, ``REAL`` or ``BLOB``. Column types are matched case-insensitively.
+
+As with detected column types, ``--type`` only affects tables created by the command. If the table already exists, its existing column types are left unchanged.
+
+To disable type detection and treat all columns as TEXT, use ``--no-detect-types``:
+
+.. code-block:: bash
+
+ sqlite-utils insert creatures.db creatures creatures.csv --csv --no-detect-types
+
+If a CSV or TSV file includes empty cells, like this one:
+
+::
+
+ name,age,weight
+ Cleo,6,
+ Dori,,3.5
+
+They will be imported into SQLite as empty string values, ``""``.
+
+To import them as ``NULL`` values instead, use the ``--empty-null`` option:
+
+.. code-block:: bash
+
+ sqlite-utils insert creatures.db creatures creatures.csv --csv --empty-null
.. _cli_insert_csv_tsv_delimiter:
@@ -987,7 +1423,9 @@ Alternative delimiters and quote characters
If your file uses a delimiter other than ``,`` or a quote character other than ``"`` you can attempt to detect delimiters or you can specify them explicitly.
-The ``--sniff`` option can be used to attempt to detect the delimiters::
+The ``--sniff`` option can be used to attempt to detect the delimiters:
+
+.. code-block:: bash
sqlite-utils insert dogs.db dogs dogs.csv --sniff
@@ -999,9 +1437,11 @@ Here's a CSV file that uses ``;`` for delimiters and the ``|`` symbol for quote
Cleo;|Very fine; a friendly dog|
Pancakes;A local corgi
-You can import that using::
+You can import that using:
- $ sqlite-utils insert dogs.db dogs dogs.csv --delimiter=";" --quotechar="|"
+.. code-block:: bash
+
+ sqlite-utils insert dogs.db dogs dogs.csv --delimiter=";" --quotechar="|"
Passing ``--delimiter``, ``--quotechar`` or ``--sniff`` implies ``--csv``, so you can omit the ``--csv`` option.
@@ -1021,28 +1461,32 @@ If you do this, the table will be created with column names called ``untitled_1`
Inserting unstructured data with \-\-lines and \-\-text
=======================================================
-If you have an unstructured file you can insert its contents into a table with a single ``line`` column containing each line from the file using ``--lines``. This can be useful if you intend to further analyze those lines using SQL string functions or :ref:`sqlite-utils convert `::
+If you have an unstructured file you can insert its contents into a table with a single ``line`` column containing each line from the file using ``--lines``. This can be useful if you intend to further analyze those lines using SQL string functions or :ref:`sqlite-utils convert `:
- $ sqlite-utils insert logs.db loglines logfile.log --lines
+.. code-block:: bash
+
+ sqlite-utils insert logs.db loglines logfile.log --lines
This will produce the following schema:
.. code-block:: sql
- CREATE TABLE [loglines] (
- [line] TEXT
+ CREATE TABLE "loglines" (
+ "line" TEXT
);
-You can also insert the entire contents of the file into a single column called ``text`` using ``--text``::
+You can also insert the entire contents of the file into a single column called ``text`` using ``--text``:
- $ sqlite-utils insert content.db content file.txt --text
+.. code-block:: bash
+
+ sqlite-utils insert content.db content file.txt --text
The schema here will be:
.. code-block:: sql
- CREATE TABLE [content] (
- [text] TEXT
+ CREATE TABLE "content" (
+ "text" TEXT
);
.. _cli_insert_convert:
@@ -1063,9 +1507,11 @@ Given a JSON file called ``dogs.json`` containing this:
{"id": 2, "name": "Pancakes"}
]
-The following command will insert that data and add an ``is_good`` column set to ``1`` for each dog::
+The following command will insert that data and add an ``is_good`` column set to ``1`` for each dog:
- $ sqlite-utils insert dogs.db dogs dogs.json --convert 'row["is_good"] = 1'
+.. code-block:: bash
+
+ sqlite-utils insert dogs.db dogs dogs.json --convert 'row["is_good"] = 1'
The ``--convert`` option also works with the ``--csv``, ``--tsv`` and ``--nl`` insert options.
@@ -1085,9 +1531,11 @@ With ``--lines``, instead of being passed a ``row`` dictionary your function wil
INFO: 127.0.0.1:60581 - GET / HTTP/1.1 200 OK
INFO: 127.0.0.1:60581 - GET /foo/-/static/app.css?cead5a HTTP/1.1 200 OK
-You could convert it into structured data like so::
+You could convert it into structured data like so:
- $ sqlite-utils insert logs.db loglines access.log --convert '
+.. code-block:: bash
+
+ sqlite-utils insert logs.db loglines access.log --convert '
type, source, _, verb, path, _, status, _ = line.split()
return {
"type": type,
@@ -1115,17 +1563,24 @@ With ``--text`` the entire input to the command will be made available to the fu
The function can return a single dictionary which will be inserted as a single row, or it can return a list or iterator of dictionaries, each of which will be inserted.
-Here's how to use ``--convert`` and ``--text`` to insert one record per word in the input::
+Here's how to use ``--convert`` and ``--text`` to insert one record per word in the input:
- $ echo 'A bunch of words' | sqlite-utils insert words.db words - \
+.. code-block:: bash
+
+ echo 'A bunch of words' | sqlite-utils insert words.db words - \
--text --convert '({"word": w} for w in text.split())'
-The result looks like this::
+The result looks like this:
+
+.. code-block:: bash
+
+ sqlite-utils dump words.db
+
+.. code-block:: output
- $ sqlite-utils dump words.db
BEGIN TRANSACTION;
- CREATE TABLE [words] (
- [word] TEXT
+ CREATE TABLE "words" (
+ "word" TEXT
);
INSERT INTO "words" VALUES('A');
INSERT INTO "words" VALUES('bunch');
@@ -1134,6 +1589,27 @@ The result looks like this::
COMMIT;
+.. _cli_insert_code:
+
+Inserting rows generated by Python code
+=======================================
+
+Instead of providing a ``FILE`` to import, you can use the ``--code`` option to pass a block of Python code that generates the rows to insert. This is the command-line equivalent of calling ``db["creatures"].insert_all(rows())`` from the :ref:`Python API `.
+
+Your code should define either a ``rows()`` function that returns or yields dictionaries, or a ``rows`` iterable such as a list of dictionaries:
+
+.. code-block:: bash
+
+ sqlite-utils insert data.db creatures --code '
+ def rows():
+ yield {"id": 1, "name": "Cleo"}
+ yield {"id": 2, "name": "Suna"}
+ ' --pk id
+
+``--code`` can also be given a path to a Python ``.py`` file.
+
+The ``--code`` option works with both ``sqlite-utils insert`` and ``sqlite-utils upsert``, and composes with table options such as ``--pk``, ``--replace``, ``--alter``, ``--not-null`` and ``--default``. It cannot be combined with a ``FILE`` argument or with input format options such as ``--csv`` or ``--convert``.
+
.. _cli_insert_replace:
Insert-replacing data
@@ -1141,11 +1617,16 @@ Insert-replacing data
The ``--replace`` option to ``insert`` causes any existing records with the same primary key to be replaced entirely by the new records.
-To replace a dog with in ID of 2 with a new record, run the following::
+To replace a dog with in ID of 2 with a new record, run the following:
- $ echo '{"id": 2, "name": "Pancakes", "age": 3}' | \
+.. code-block:: bash
+
+ echo '{"id": 2, "name": "Pancakes", "age": 3}' | \
sqlite-utils insert dogs.db dogs - --pk=id --replace
+.. note::
+ In Python: :ref:`table.insert(..., replace=True) ` CLI reference: :ref:`sqlite-utils insert `
+
.. _cli_upsert:
Upserting data
@@ -1155,19 +1636,26 @@ Upserting is update-or-insert. If a row exists with the specified primary key th
Unlike ``insert --replace``, an upsert will ignore any column values that exist but are not present in the upsert document.
-For example::
+For example:
- $ echo '{"id": 2, "age": 4}' | \
+.. code-block:: bash
+
+ echo '{"id": 2, "age": 4}' | \
sqlite-utils upsert dogs.db dogs - --pk=id
This will update the dog with an ID of 2 to have an age of 4, creating a new record (with a null name) if one does not exist. If a row DOES exist the name will be left as-is.
+If the table already exists and has a primary key, you can omit the ``--pk`` option and ``sqlite-utils`` will use that existing primary key.
+
The command will fail if you reference columns that do not exist on the table. To automatically create missing columns, use the ``--alter`` option.
.. note::
``upsert`` in sqlite-utils 1.x worked like ``insert ... --replace`` does in 2.x. See `issue #66 `__ for details of this change.
+.. note::
+ In Python: :ref:`table.upsert() ` CLI reference: :ref:`sqlite-utils upsert `
+
.. _cli_bulk:
Executing SQL in bulk
@@ -1179,7 +1667,9 @@ The command takes the database file, the SQL to be executed and the file contain
The SQL query should include ``:named`` parameters that match the keys in the records.
-For example, given a ``chickens.csv`` CSV file containing the following::
+For example, given a ``chickens.csv`` CSV file containing the following:
+
+.. code-block::
id,name
1,Blue
@@ -1189,9 +1679,11 @@ For example, given a ``chickens.csv`` CSV file containing the following::
5,Suna
6,Cardi
-You could insert those rows into a pre-created ``chickens`` table like so::
+You could insert those rows into a pre-created ``chickens`` table like so:
- $ sqlite-utils bulk chickens.db \
+.. code-block:: bash
+
+ sqlite-utils bulk chickens.db \
'insert into chickens (id, name) values (:id, :name)' \
chickens.csv --csv
@@ -1206,41 +1698,53 @@ Inserting data from files
The ``insert-files`` command can be used to insert the content of files, along with their metadata, into a SQLite table.
-Here's an example that inserts all of the GIF files in the current directory into a ``gifs.db`` database, placing the file contents in an ``images`` table::
+Here's an example that inserts all of the GIF files in the current directory into a ``gifs.db`` database, placing the file contents in an ``images`` table:
- $ sqlite-utils insert-files gifs.db images *.gif
+.. code-block:: bash
-You can also pass one or more directories, in which case every file in those directories will be added recursively::
+ sqlite-utils insert-files gifs.db images *.gif
- $ sqlite-utils insert-files gifs.db images path/to/my-gifs
+You can also pass one or more directories, in which case every file in those directories will be added recursively:
-By default this command will create a table with the following schema::
+.. code-block:: bash
- CREATE TABLE [images] (
- [path] TEXT PRIMARY KEY,
- [content] BLOB,
- [size] INTEGER
+ sqlite-utils insert-files gifs.db images path/to/my-gifs
+
+By default this command will create a table with the following schema:
+
+.. code-block:: sql
+
+ CREATE TABLE "images" (
+ "path" TEXT PRIMARY KEY,
+ "content" BLOB,
+ "size" INTEGER
);
Content will be treated as binary by default and stored in a ``BLOB`` column. You can use the ``--text`` option to store that content in a ``TEXT`` column instead.
-You can customize the schema using one or more ``-c`` options. For a table schema that includes just the path, MD5 hash and last modification time of the file, you would use this::
+You can customize the schema using one or more ``-c`` options. For a table schema that includes just the path, MD5 hash and last modification time of the file, you would use this:
- $ sqlite-utils insert-files gifs.db images *.gif -c path -c md5 -c mtime --pk=path
+.. code-block:: bash
-This will result in the following schema::
+ sqlite-utils insert-files gifs.db images *.gif -c path -c md5 -c mtime --pk=path
- CREATE TABLE [images] (
- [path] TEXT PRIMARY KEY,
- [md5] TEXT,
- [mtime] FLOAT
+This will result in the following schema:
+
+.. code-block:: sql
+
+ CREATE TABLE "images" (
+ "path" TEXT PRIMARY KEY,
+ "md5" TEXT,
+ "mtime" REAL
);
Note that there's no ``content`` column here at all - if you specify custom columns using ``-c`` you need to include ``-c content`` to create that column.
-You can change the name of one of these columns using a ``-c colname:coldef`` parameter. To rename the ``mtime`` column to ``last_modified`` you would use this::
+You can change the name of one of these columns using a ``-c colname:coldef`` parameter. To rename the ``mtime`` column to ``last_modified`` you would use this:
- $ sqlite-utils insert-files gifs.db images *.gif \
+.. code-block:: bash
+
+ sqlite-utils insert-files gifs.db images *.gif \
-c path -c md5 -c last_modified:mtime --pk=path
You can pass ``--replace`` or ``--upsert`` to indicate what should happen if you try to insert a file with an existing primary key. Pass ``--alter`` to cause any missing columns to be added to the table.
@@ -1282,7 +1786,9 @@ The full list of column definitions you can use is as follows:
``suffix``
The file extension - for ``file.txt.gz`` this would be ``.gz``
-You can insert data piped from standard input like this::
+You can insert data piped from standard input like this:
+
+.. code-block:: bash
cat dog.jpg | sqlite-utils insert-files dogs.db pics - --name=dog.jpg
@@ -1297,27 +1803,35 @@ Converting data in columns
The ``convert`` command can be used to transform the data in a specified column - for example to parse a date string into an ISO timestamp, or to split a string of tags into a JSON array.
-The command accepts a database, table, one or more columns and a string of Python code to be executed against the values from those columns. The following example would replace the values in the ``headline`` column in the ``articles`` table with an upper-case version::
+The command accepts a database, table, one or more columns and a string of Python code to be executed against the values from those columns. The following example would replace the values in the ``headline`` column in the ``articles`` table with an upper-case version:
- $ sqlite-utils convert content.db articles headline 'value.upper()'
+.. code-block:: bash
+
+ sqlite-utils convert content.db articles headline 'value.upper()'
The Python code is passed as a string. Within that Python code the ``value`` variable will be the value of the current column.
-The code you provide will be compiled into a function that takes ``value`` as a single argument. If you break your function body into multiple lines the last line should be a ``return`` statement::
+The code you provide will be compiled into a function that takes ``value`` as a single argument. If you break your function body into multiple lines the last line should be a ``return`` statement:
- $ sqlite-utils convert content.db articles headline '
+.. code-block:: bash
+
+ sqlite-utils convert content.db articles headline '
value = str(value)
return value.upper()'
-Your code will be automatically wrapped in a function, but you can also define a function called ``convert(value)`` which will be called, if available::
+Your code will be automatically wrapped in a function, but you can also define a function called ``convert(value)`` which will be called, if available:
- $ sqlite-utils convert content.db articles headline '
+.. code-block:: bash
+
+ sqlite-utils convert content.db articles headline '
def convert(value):
return value.upper()'
-Use a ``CODE`` value of ``-`` to read from standard input::
+Use a ``CODE`` value of ``-`` to read from standard input:
- $ cat mycode.py | sqlite-utils convert content.db articles headline -
+.. code-block:: bash
+
+ cat mycode.py | sqlite-utils convert content.db articles headline -
Where ``mycode.py`` contains a fragment of Python code that looks like this:
@@ -1326,47 +1840,100 @@ Where ``mycode.py`` contains a fragment of Python code that looks like this:
def convert(value):
return value.upper()
-The conversion will be applied to every row in the specified table. You can limit that to just rows that match a ``WHERE`` clause using ``--where``::
+The conversion will be applied to every row in the specified table. You can limit that to just rows that match a ``WHERE`` clause using ``--where``:
- $ sqlite-utils convert content.db articles headline 'value.upper()' \
+.. code-block:: bash
+
+ sqlite-utils convert content.db articles headline 'value.upper()' \
--where "headline like '%cat%'"
-You can include named parameters in your where clause and populate them using one or more ``--param`` options::
+You can include named parameters in your where clause and populate them using one or more ``--param`` options:
- $ sqlite-utils convert content.db articles headline 'value.upper()' \
+.. code-block:: bash
+
+ sqlite-utils convert content.db articles headline 'value.upper()' \
--where "headline like :query" \
--param query '%cat%'
The ``--dry-run`` option will output a preview of the conversion against the first ten rows, without modifying the database.
+.. note::
+ In Python: :ref:`table.convert() ` CLI reference: :ref:`sqlite-utils convert `
+
.. _cli_convert_import:
Importing additional modules
----------------------------
-You can specify Python modules that should be imported and made available to your code using one or more ``--import`` options. This example uses the ``textwrap`` module to wrap the ``content`` column at 100 characters::
+You can specify Python modules that should be imported and made available to your code using one or more ``--import`` options. This example uses the ``textwrap`` module to wrap the ``content`` column at 100 characters:
- $ sqlite-utils convert content.db articles content \
+.. code-block:: bash
+
+ sqlite-utils convert content.db articles content \
'"\n".join(textwrap.wrap(value, 100))' \
--import=textwrap
-This supports nested imports as well, for example to use `ElementTree `__::
+This supports nested imports as well, for example to use `ElementTree `__:
- $ sqlite-utils convert content.db articles content \
+.. code-block:: bash
+
+ sqlite-utils convert content.db articles content \
'xml.etree.ElementTree.fromstring(value).attrib["title"]' \
--import=xml.etree.ElementTree
+.. _cli_convert_debugger:
+
+Using the debugger
+------------------
+
+If an error occurs while running your conversion operation you may see a message like this::
+
+ user-defined function raised exception
+
+Add the ``--pdb`` option to catch the error and open the Python debugger at that point. The conversion operation will exit after you type ``q`` in the debugger.
+
+Here's an example debugging session. First, create a ``articles`` table with invalid XML in the ``content`` column:
+
+.. code-block:: bash
+
+ echo '{"content": "This is not XML"}' | sqlite-utils insert content.db articles -
+
+Now run the conversion with the ``--pdb`` option:
+
+.. code-block:: bash
+
+ sqlite-utils convert content.db articles content \
+ 'xml.etree.ElementTree.fromstring(value).attrib["title"]' \
+ --import=xml.etree.ElementTree \
+ --pdb
+
+When the error occurs the debugger will open::
+
+ Exception raised, dropping into pdb...: syntax error: line 1, column 0
+ > .../python3.11/xml/etree/ElementTree.py(1338)XML()
+ -> parser.feed(text)
+ (Pdb) args
+ text = 'This is not XML'
+ parser =
+ (Pdb) q
+
+``args`` here shows the arguments to the current function in the stack. The Python `pdb documentation `__ has full details on the other available commands.
+
.. _cli_convert_complex:
-Using a convert() function to execute initialization
-----------------------------------------------------
+Defining a convert() function
+-----------------------------
-In some cases you may need to execute one-off initialization code at the start of the run. You can do that by providing code that runs before defining your ``convert(value)`` function.
+Instead of providing a single line of code to be executed against each value, you can define a function called ``convert(value)``.
-The following example adds a new ``score`` column, then updates it to list a random number - after first seeding the random number generator to ensure that multiple runs produce the same results::
+This mechanism can be used to execute one-off initialization code that runs once at the start of the conversion run.
- $ sqlite-utils add-column content.db articles score float --not-null-default 1.0
- $ sqlite-utils convert content.db articles score '
+The following example adds a new ``score`` column, then updates it to list a random number - after first seeding the random number generator to ensure that multiple runs produce the same results:
+
+.. code-block:: bash
+
+ sqlite-utils add-column content.db articles score float --not-null-default 1.0
+ sqlite-utils convert content.db articles score '
import random
random.seed(10)
@@ -1408,14 +1975,30 @@ Various built-in recipe functions are available for common operations. These are
``r.parsedatetime(value, dayfirst=False, yearfirst=False, errors=None)``
Parse a datetime and convert it to ISO datetime format: ``yyyy-mm-ddTHH:MM:SS``
-These recipes can be used in the code passed to ``sqlite-utils convert`` like this::
+These recipes can be used in the code passed to ``sqlite-utils convert`` like this:
- $ sqlite-utils convert my.db mytable mycolumn \
+.. code-block:: bash
+
+ sqlite-utils convert my.db mytable mycolumn \
'r.jsonsplit(value)'
-To use any of the documented parameters, do this::
+You can also pass the recipe function directly without the ``(value)`` part - sqlite-utils will detect that it is a callable and use it automatically:
- $ sqlite-utils convert my.db mytable mycolumn \
+.. code-block:: bash
+
+ sqlite-utils convert my.db mytable mycolumn r.parsedate
+
+This shorter syntax works for any callable, including functions from imported modules:
+
+.. code-block:: bash
+
+ sqlite-utils convert my.db mytable mycolumn json.loads --import json
+
+To use any of the documented parameters, use the full function call syntax:
+
+.. code-block:: bash
+
+ sqlite-utils convert my.db mytable mycolumn \
'r.jsonsplit(value, delimiter=":")'
.. _cli_convert_output:
@@ -1423,14 +2006,18 @@ To use any of the documented parameters, do this::
Saving the result to a different column
---------------------------------------
-The ``--output`` and ``--output-type`` options can be used to save the result of the conversion to a separate column, which will be created if that column does not already exist::
+The ``--output`` and ``--output-type`` options can be used to save the result of the conversion to a separate column, which will be created if that column does not already exist:
- $ sqlite-utils convert content.db articles headline 'value.upper()' \
+.. code-block:: bash
+
+ sqlite-utils convert content.db articles headline 'value.upper()' \
--output headline_upper
-The type of the created column defaults to ``text``, but a different column type can be specified using ``--output-type``. This example will create a new floating point column called ``id_as_a_float`` with a copy of each item's ID increased by 0.5::
+The type of the created column defaults to ``text``, but a different column type can be specified using ``--output-type``. This example will create a new floating point column called ``id_as_a_float`` with a copy of each item's ID increased by 0.5:
- $ sqlite-utils convert content.db articles id 'float(value) + 0.5' \
+.. code-block:: bash
+
+ sqlite-utils convert content.db articles id 'float(value) + 0.5' \
--output id_as_a_float \
--output-type float
@@ -1445,9 +2032,11 @@ Sometimes you may wish to convert a single column into multiple derived columns.
You can achieve this using the ``--multi`` option to ``sqlite-utils convert``. This option expects your Python code to return a Python dictionary: new columns well be created and populated for each of the keys in that dictionary.
-For the ``latitude,longitude`` example you would use the following::
+For the ``latitude,longitude`` example you would use the following:
- $ sqlite-utils convert demo.db places location \
+.. code-block:: bash
+
+ sqlite-utils convert demo.db places location \
'bits = value.split(",")
return {
"latitude": float(bits[0]),
@@ -1458,10 +2047,10 @@ The type of the returned values will be taken into account when creating the new
.. code-block:: sql
- CREATE TABLE [places] (
- [location] TEXT,
- [latitude] FLOAT,
- [longitude] FLOAT
+ CREATE TABLE "places" (
+ "location" TEXT,
+ "latitude" REAL,
+ "longitude" REAL
);
The code function can also return ``None``, in which case its output will be ignored. You can drop the original column at the end of the operation by adding ``--drop``.
@@ -1471,19 +2060,23 @@ The code function can also return ``None``, in which case its output will be ign
Creating tables
===============
-Most of the time creating tables by inserting example data is the quickest approach. If you need to create an empty table in advance of inserting data you can do so using the ``create-table`` command::
+Most of the time creating tables by inserting example data is the quickest approach. If you need to create an empty table in advance of inserting data you can do so using the ``create-table`` command:
- $ sqlite-utils create-table mydb.db mytable id integer name text --pk=id
+.. code-block:: bash
+
+ sqlite-utils create-table mydb.db mytable id integer name text --pk=id
This will create a table called ``mytable`` with two columns - an integer ``id`` column and a text ``name`` column. It will set the ``id`` column to be the primary key.
You can pass as many column-name column-type pairs as you like. Valid types are ``integer``, ``text``, ``float`` and ``blob``.
+Pass ``--pk`` more than once for a compound primary key that covers multiple columns.
+
You can specify columns that should be NOT NULL using ``--not-null colname``. You can specify default values for columns using ``--default colname defaultvalue``.
-::
+.. code-block:: bash
- $ sqlite-utils create-table mydb.db mytable \
+ sqlite-utils create-table mydb.db mytable \
id integer \
name text \
age integer \
@@ -1493,77 +2086,137 @@ You can specify columns that should be NOT NULL using ``--not-null colname``. Yo
--default is_good 1 \
--pk=id
- $ sqlite-utils tables mydb.db --schema -t
+.. code-block:: bash
+
+ sqlite-utils tables mydb.db --schema -t
+
+.. code-block:: output
+
table schema
------- --------------------------------
- mytable CREATE TABLE [mytable] (
- [id] INTEGER PRIMARY KEY,
- [name] TEXT NOT NULL,
- [age] INTEGER NOT NULL,
- [is_good] INTEGER DEFAULT '1'
+ mytable CREATE TABLE "mytable" (
+ "id" INTEGER PRIMARY KEY,
+ "name" TEXT NOT NULL,
+ "age" INTEGER NOT NULL,
+ "is_good" INTEGER DEFAULT '1'
)
-You can specify foreign key relationships between the tables you are creating using ``--fk colname othertable othercolumn``::
+You can specify foreign key relationships between the tables you are creating using ``--fk colname othertable othercolumn``:
- $ sqlite-utils create-table books.db authors \
+.. code-block:: bash
+
+ sqlite-utils create-table books.db authors \
id integer \
name text \
--pk=id
- $ sqlite-utils create-table books.db books \
+ sqlite-utils create-table books.db books \
id integer \
title text \
author_id integer \
--pk=id \
--fk author_id authors id
- $ sqlite-utils tables books.db --schema -t
+.. code-block:: bash
+
+ sqlite-utils tables books.db --schema -t
+
+.. code-block:: output
+
table schema
------- -------------------------------------------------
- authors CREATE TABLE [authors] (
- [id] INTEGER PRIMARY KEY,
- [name] TEXT
+ authors CREATE TABLE "authors" (
+ "id" INTEGER PRIMARY KEY,
+ "name" TEXT
)
- books CREATE TABLE [books] (
- [id] INTEGER PRIMARY KEY,
- [title] TEXT,
- [author_id] INTEGER REFERENCES [authors]([id])
+ books CREATE TABLE "books" (
+ "id" INTEGER PRIMARY KEY,
+ "title" TEXT,
+ "author_id" INTEGER REFERENCES "authors"("id")
)
+You can create a table in `SQLite STRICT mode `__ using ``--strict``:
+
+.. code-block:: bash
+
+ sqlite-utils create-table mydb.db mytable id integer name text --strict
+
+.. code-block:: bash
+
+ sqlite-utils tables mydb.db --schema -t
+
+.. code-block:: output
+
+ table schema
+ ------- ------------------------
+ mytable CREATE TABLE "mytable" (
+ "id" INTEGER,
+ "name" TEXT
+ ) STRICT
+
If a table with the same name already exists, you will get an error. You can choose to silently ignore this error with ``--ignore``, or you can replace the existing table with a new, empty table using ``--replace``.
You can also pass ``--transform`` to transform the existing table to match the new schema. See :ref:`python_api_explicit_create` in the Python library documentation for details of how this option works.
+.. note::
+ In Python: :ref:`table.create() ` CLI reference: :ref:`sqlite-utils create-table `
+
+.. _cli_renaming_tables:
+
+Renaming a table
+================
+
+Yo ucan rename a table using the ``rename-table`` command:
+
+.. code-block:: bash
+
+ sqlite-utils rename-table mydb.db oldname newname
+
+Pass ``--ignore`` to ignore any errors caused by the table not existing, or the new name already being in use.
+
+.. note::
+ In Python: :ref:`db.rename_table() ` CLI reference: :ref:`sqlite-utils rename-table `
+
.. _cli_duplicate_table:
Duplicating tables
==================
-The ``duplicate`` command duplicates a table - creating a new table with the same schema and a copy of all of the rows::
+The ``duplicate`` command duplicates a table - creating a new table with the same schema and a copy of all of the rows:
- $ sqlite-utils duplicate books.db authors authors_copy
+.. code-block:: bash
+
+ sqlite-utils duplicate books.db authors authors_copy
+
+.. note::
+ In Python: :ref:`table.duplicate() ` CLI reference: :ref:`sqlite-utils duplicate `
.. _cli_drop_table:
Dropping tables
===============
-You can drop a table using the ``drop-table`` command::
+You can drop a table using the ``drop-table`` command:
- $ sqlite-utils drop-table mydb.db mytable
+.. code-block:: bash
+
+ sqlite-utils drop-table mydb.db mytable
Use ``--ignore`` to ignore the error if the table does not exist.
+.. note::
+ In Python: :ref:`table.drop() ` CLI reference: :ref:`sqlite-utils drop-table `
+
.. _cli_transform_table:
Transforming tables
===================
-The ``transform`` command allows you to apply complex transformations to a table that cannot be implemented using a regular SQLite ``ALTER TABLE`` command. See :ref:`python_api_transform` for details of how this works.
+The ``transform`` command allows you to apply complex transformations to a table that cannot be implemented using a regular SQLite ``ALTER TABLE`` command. See :ref:`python_api_transform` for details of how this works. By default, the ``transform`` command preserves a table's ``STRICT`` mode.
-::
+.. code-block:: bash
- $ sqlite-utils transform mydb.db mytable \
+ sqlite-utils transform mydb.db mytable \
--drop column1 \
--rename column2 column_renamed
@@ -1602,9 +2255,20 @@ Every option for this table (with the exception of ``--pk-none``) can be specifi
``--drop-foreign-key column``
Drop the specified foreign key.
-If you want to see the SQL that will be executed to make the change without actually executing it, add the ``--sql`` flag. For example::
+``--add-foreign-key column other_table other_column``
+ Add a foreign key constraint to ``column`` pointing to ``other_table.other_column``.
- $ sqlite-utils transform fixtures.db roadside_attractions \
+``--strict``
+ Convert the table to a `SQLite STRICT table `__. The command fails if the available SQLite version does not support strict tables. If existing rows contain values that are incompatible with their declared column types the transformation fails and the original table is left unchanged.
+
+``--no-strict``
+ Convert a strict table back to a regular non-strict table.
+
+If you want to see the SQL that will be executed to make the change without actually executing it, add the ``--sql`` flag. For example:
+
+.. code-block:: bash
+
+ sqlite-utils transform fixtures.db roadside_attractions \
--rename pk id \
--default name Untitled \
--column-order id \
@@ -1612,50 +2276,96 @@ If you want to see the SQL that will be executed to make the change without actu
--column-order latitude \
--drop address \
--sql
- CREATE TABLE [roadside_attractions_new_4033a60276b9] (
- [id] INTEGER PRIMARY KEY,
- [longitude] FLOAT,
- [latitude] FLOAT,
- [name] TEXT DEFAULT 'Untitled'
+
+.. code-block:: output
+
+ CREATE TABLE "roadside_attractions_new_4033a60276b9" (
+ "id" INTEGER PRIMARY KEY,
+ "longitude" FLOAT,
+ "latitude" FLOAT,
+ "name" TEXT DEFAULT 'Untitled'
);
- INSERT INTO [roadside_attractions_new_4033a60276b9] ([longitude], [latitude], [id], [name])
- SELECT [longitude], [latitude], [pk], [name] FROM [roadside_attractions];
- DROP TABLE [roadside_attractions];
- ALTER TABLE [roadside_attractions_new_4033a60276b9] RENAME TO [roadside_attractions];
+ INSERT INTO "roadside_attractions_new_4033a60276b9" ("longitude", "latitude", "id", "name")
+ SELECT "longitude", "latitude", "pk", "name" FROM "roadside_attractions";
+ DROP TABLE "roadside_attractions";
+ ALTER TABLE "roadside_attractions_new_4033a60276b9" RENAME TO "roadside_attractions";
+
+.. note::
+ In Python: :ref:`table.transform() ` CLI reference: :ref:`sqlite-utils transform `
.. _cli_transform_table_add_primary_key_to_rowid:
Adding a primary key to a rowid table
-------------------------------------
-SQLite tables that are created without an explicit primary key are created as `rowid tables `__. They still have a numeric primary key which is available in the ``rowid`` column, but that column is not included in the output of ``select *``. Here's an example::
+SQLite tables that are created without an explicit primary key are created as `rowid tables `__. They still have a numeric primary key which is available in the ``rowid`` column, but that column is not included in the output of ``select *``. Here's an example:
- % echo '[{"name": "Azi"}, {"name": "Suna"}]' | \
+.. code-block:: bash
+
+ echo '[{"name": "Azi"}, {"name": "Suna"}]' | \
sqlite-utils insert chickens.db chickens -
- % sqlite-utils schema chickens.db
- CREATE TABLE [chickens] (
- [name] TEXT
+ sqlite-utils schema chickens.db
+
+.. code-block:: output
+
+ CREATE TABLE "chickens" (
+ "name" TEXT
);
- % sqlite-utils chickens.db 'select * from chickens'
+
+.. code-block:: bash
+
+ sqlite-utils chickens.db 'select * from chickens'
+
+.. code-block:: output
+
[{"name": "Azi"},
{"name": "Suna"}]
- % sqlite-utils chickens.db 'select rowid, * from chickens'
+
+.. code-block:: bash
+
+ sqlite-utils chickens.db 'select rowid, * from chickens'
+
+.. code-block:: output
+
[{"rowid": 1, "name": "Azi"},
{"rowid": 2, "name": "Suna"}]
-You can use ``sqlite-utils transform ... --pk id`` to add a primary key column called ``id`` to the table. The primary key will be created as an ``INTEGER PRIMARY KEY`` and the existing ``rowid`` values will be copied across to it. It will automatically increment as new rows are added to the table::
+You can use ``sqlite-utils transform ... --pk id`` to add a primary key column called ``id`` to the table. The primary key will be created as an ``INTEGER PRIMARY KEY`` and the existing ``rowid`` values will be copied across to it. It will automatically increment as new rows are added to the table:
+
+.. code-block:: bash
+
+ sqlite-utils transform chickens.db chickens --pk id
+
+.. code-block:: bash
+
+ sqlite-utils schema chickens.db
+
+.. code-block:: output
- % sqlite-utils transform chickens.db chickens --pk id
- % sqlite-utils schema chickens.db
CREATE TABLE "chickens" (
- [id] INTEGER PRIMARY KEY,
- [name] TEXT
+ "id" INTEGER PRIMARY KEY,
+ "name" TEXT
);
- % sqlite-utils chickens.db 'select * from chickens'
+
+.. code-block:: bash
+
+ sqlite-utils chickens.db 'select * from chickens'
+
+.. code-block:: output
+
[{"id": 1, "name": "Azi"},
{"id": 2, "name": "Suna"}]
- % echo '{"name": "Cardi"}' | sqlite-utils insert chickens.db chickens -
- % sqlite-utils chickens.db 'select * from chickens'
+
+.. code-block:: bash
+
+ echo '{"name": "Cardi"}' | sqlite-utils insert chickens.db chickens -
+
+.. code-block:: bash
+
+ sqlite-utils chickens.db 'select * from chickens'
+
+.. code-block:: output
+
[{"id": 1, "name": "Azi"},
{"id": 2, "name": "Suna"},
{"id": 3, "name": "Cardi"}]
@@ -1669,26 +2379,30 @@ The ``sqlite-utils extract`` command can be used to extract specified columns in
Take a look at the Python API documentation for :ref:`python_api_extract` for a detailed description of how this works, including examples of table schemas before and after running an extraction operation.
-The command takes a database, table and one or more columns that should be extracted. To extract the ``species`` column from the ``trees`` table you would run::
+Rows where every extracted column is ``null`` are not extracted - those rows get a ``null`` value in their new foreign key column and no record is created for them in the lookup table.
- $ sqlite-utils extract my.db trees species
+The command takes a database, table and one or more columns that should be extracted. To extract the ``species`` column from the ``trees`` table you would run:
+
+.. code-block:: bash
+
+ sqlite-utils extract my.db trees species
This would produce the following schema:
.. code-block:: sql
CREATE TABLE "trees" (
- [id] INTEGER PRIMARY KEY,
- [TreeAddress] TEXT,
- [species_id] INTEGER,
+ "id" INTEGER PRIMARY KEY,
+ "TreeAddress" TEXT,
+ "species_id" INTEGER,
FOREIGN KEY(species_id) REFERENCES species(id)
);
- CREATE TABLE [species] (
- [id] INTEGER PRIMARY KEY,
- [species] TEXT
+ CREATE TABLE "species" (
+ "id" INTEGER PRIMARY KEY,
+ "species" TEXT
);
- CREATE UNIQUE INDEX [idx_species_species]
- ON [species] ([species]);
+ CREATE UNIQUE INDEX "idx_species_species"
+ ON "species" ("species");
The command takes the following options:
@@ -1704,7 +2418,9 @@ The command takes the following options:
``--silent``
Don't display the progress bar.
-Here's a more complex example that makes use of these options. It converts `this CSV file `__ full of global power plants into SQLite, then extracts the ``country`` and ``country_long`` columns into a separate ``countries`` table::
+Here's a more complex example that makes use of these options. It converts `this CSV file `__ full of global power plants into SQLite, then extracts the ``country`` and ``country_long`` columns into a separate ``countries`` table:
+
+.. code-block:: bash
wget 'https://github.com/wri/global-power-plant-database/blob/232a6666/output_database/global_power_plant_database.csv?raw=true'
sqlite-utils insert global.db power_plants \
@@ -1719,99 +2435,140 @@ After running the above, the command ``sqlite-utils schema global.db`` reveals t
.. code-block:: sql
- CREATE TABLE [countries] (
- [id] INTEGER PRIMARY KEY,
- [country] TEXT,
- [name] TEXT
+ CREATE TABLE "countries" (
+ "id" INTEGER PRIMARY KEY,
+ "country" TEXT,
+ "name" TEXT
);
CREATE TABLE "power_plants" (
- [country_id] INTEGER,
- [name] TEXT,
- [gppd_idnr] TEXT,
- [capacity_mw] TEXT,
- [latitude] TEXT,
- [longitude] TEXT,
- [primary_fuel] TEXT,
- [other_fuel1] TEXT,
- [other_fuel2] TEXT,
- [other_fuel3] TEXT,
- [commissioning_year] TEXT,
- [owner] TEXT,
- [source] TEXT,
- [url] TEXT,
- [geolocation_source] TEXT,
- [wepp_id] TEXT,
- [year_of_capacity_data] TEXT,
- [generation_gwh_2013] TEXT,
- [generation_gwh_2014] TEXT,
- [generation_gwh_2015] TEXT,
- [generation_gwh_2016] TEXT,
- [generation_gwh_2017] TEXT,
- [generation_data_source] TEXT,
- [estimated_generation_gwh] TEXT,
- FOREIGN KEY([country_id]) REFERENCES [countries]([id])
+ "country_id" INTEGER,
+ "name" TEXT,
+ "gppd_idnr" TEXT,
+ "capacity_mw" TEXT,
+ "latitude" TEXT,
+ "longitude" TEXT,
+ "primary_fuel" TEXT,
+ "other_fuel1" TEXT,
+ "other_fuel2" TEXT,
+ "other_fuel3" TEXT,
+ "commissioning_year" TEXT,
+ "owner" TEXT,
+ "source" TEXT,
+ "url" TEXT,
+ "geolocation_source" TEXT,
+ "wepp_id" TEXT,
+ "year_of_capacity_data" TEXT,
+ "generation_gwh_2013" TEXT,
+ "generation_gwh_2014" TEXT,
+ "generation_gwh_2015" TEXT,
+ "generation_gwh_2016" TEXT,
+ "generation_gwh_2017" TEXT,
+ "generation_data_source" TEXT,
+ "estimated_generation_gwh" TEXT,
+ FOREIGN KEY("country_id") REFERENCES "countries"("id")
);
- CREATE UNIQUE INDEX [idx_countries_country_name]
- ON [countries] ([country], [name]);
+ CREATE UNIQUE INDEX "idx_countries_country_name"
+ ON "countries" ("country", "name");
+
+.. note::
+ In Python: :ref:`table.extract() ` CLI reference: :ref:`sqlite-utils extract `
.. _cli_create_view:
Creating views
==============
-You can create a view using the ``create-view`` command::
+You can create a view using the ``create-view`` command:
- $ sqlite-utils create-view mydb.db version "select sqlite_version()"
+.. code-block:: bash
+
+ sqlite-utils create-view mydb.db version "select sqlite_version()"
+
+.. code-block:: bash
+
+ sqlite-utils mydb.db "select * from version"
+
+.. code-block:: output
- $ sqlite-utils mydb.db "select * from version"
[{"sqlite_version()": "3.31.1"}]
Use ``--replace`` to replace an existing view of the same name, and ``--ignore`` to do nothing if a view already exists.
+.. note::
+ In Python: :ref:`db.create_view() ` CLI reference: :ref:`sqlite-utils create-view `
+
.. _cli_drop_view:
Dropping views
==============
-You can drop a view using the ``drop-view`` command::
+You can drop a view using the ``drop-view`` command:
- $ sqlite-utils drop-view myview
+.. code-block:: bash
+
+ sqlite-utils drop-view myview
Use ``--ignore`` to ignore the error if the view does not exist.
+.. note::
+ In Python: :ref:`view.drop() ` CLI reference: :ref:`sqlite-utils drop-view `
+
.. _cli_add_column:
Adding columns
==============
-You can add a column using the ``add-column`` command::
+You can add a column using the ``add-column`` command:
- $ sqlite-utils add-column mydb.db mytable nameofcolumn text
+.. code-block:: bash
-The last argument here is the type of the column to be created. You can use one of ``text``, ``integer``, ``float`` or ``blob``. If you leave it off, ``text`` will be used.
+ sqlite-utils add-column mydb.db mytable nameofcolumn text
-You can add a column that is a foreign key reference to another table using the ``--fk`` option::
+The last argument here is the type of the column to be created. This can be one of:
- $ sqlite-utils add-column mydb.db dogs species_id --fk species
+- ``text`` or ``str``
+- ``integer`` or ``int``
+- ``float``
+- ``blob`` or ``bytes``
+
+This argument is optional and defaults to ``text``.
+
+You can add a column that is a foreign key reference to another table using the ``--fk`` option:
+
+.. code-block:: bash
+
+ sqlite-utils add-column mydb.db dogs species_id --fk species
This will automatically detect the name of the primary key on the species table and use that (and its type) for the new column.
-You can explicitly specify the column you wish to reference using ``--fk-col``::
+You can explicitly specify the column you wish to reference using ``--fk-col``:
- $ sqlite-utils add-column mydb.db dogs species_id --fk species --fk-col ref
+.. code-block:: bash
-You can set a ``NOT NULL DEFAULT 'x'`` constraint on the new column using ``--not-null-default``::
+ sqlite-utils add-column mydb.db dogs species_id --fk species --fk-col ref
- $ sqlite-utils add-column mydb.db dogs friends_count integer --not-null-default 0
+You can set a ``NOT NULL DEFAULT 'x'`` constraint on the new column using ``--not-null-default``:
+
+.. code-block:: bash
+
+ sqlite-utils add-column mydb.db dogs friends_count integer --not-null-default 0
+
+.. note::
+ In Python: :ref:`table.add_column() ` CLI reference: :ref:`sqlite-utils add-column `
.. _cli_add_column_alter:
Adding columns automatically on insert/update
=============================================
-You can use the ``--alter`` option to automatically add new columns if the data you are inserting or upserting is of a different shape::
+You can use the ``--alter`` option to automatically add new columns if the data you are inserting or upserting is of a different shape:
- $ sqlite-utils insert dogs.db dogs new-dogs.json --pk=id --alter
+.. code-block:: bash
+
+ sqlite-utils insert dogs.db dogs new-dogs.json --pk=id --alter
+
+.. note::
+ In Python: :ref:`table.insert(..., alter=True) `
.. _cli_add_foreign_key:
@@ -1820,63 +2577,89 @@ Adding foreign key constraints
The ``add-foreign-key`` command can be used to add new foreign key references to an existing table - something which SQLite's ``ALTER TABLE`` command does not support.
-To add a foreign key constraint pointing the ``books.author_id`` column to ``authors.id`` in another table, do this::
+To add a foreign key constraint pointing the ``books.author_id`` column to ``authors.id`` in another table, do this:
- $ sqlite-utils add-foreign-key books.db books author_id authors id
+.. code-block:: bash
-If you omit the other table and other column references ``sqlite-utils`` will attempt to guess them - so the above example could instead look like this::
+ sqlite-utils add-foreign-key books.db books author_id authors id
- $ sqlite-utils add-foreign-key books.db books author_id
+If you omit the other table and other column references ``sqlite-utils`` will attempt to guess them - so the above example could instead look like this:
-Add ``--ignore`` to ignore an existing foreign key (as opposed to returning an error)::
+.. code-block:: bash
- $ sqlite-utils add-foreign-key books.db books author_id --ignore
+ sqlite-utils add-foreign-key books.db books author_id
+
+Add ``--ignore`` to ignore an existing foreign key (as opposed to returning an error):
+
+.. code-block:: bash
+
+ sqlite-utils add-foreign-key books.db books author_id --ignore
See :ref:`python_api_add_foreign_key` in the Python API documentation for further details, including how the automatic table guessing mechanism works.
+.. note::
+ In Python: :ref:`table.add_foreign_key() ` CLI reference: :ref:`sqlite-utils add-foreign-key `
+
.. _cli_add_foreign_keys:
Adding multiple foreign keys at once
------------------------------------
-Adding a foreign key requires a ``VACUUM``. On large databases this can be an expensive operation, so if you are adding multiple foreign keys you can combine them into one operation (and hence one ``VACUUM``) using ``add-foreign-keys``::
+Adding a foreign key requires a ``VACUUM``. On large databases this can be an expensive operation, so if you are adding multiple foreign keys you can combine them into one operation (and hence one ``VACUUM``) using ``add-foreign-keys``:
- $ sqlite-utils add-foreign-keys books.db \
+.. code-block:: bash
+
+ sqlite-utils add-foreign-keys books.db \
books author_id authors id \
authors country_id countries id
When you are using this command each foreign key needs to be defined in full, as four arguments - the table, column, other table and other column.
+.. note::
+ In Python: :ref:`db.add_foreign_keys() ` CLI reference: :ref:`sqlite-utils add-foreign-keys `
+
.. _cli_index_foreign_keys:
Adding indexes for all foreign keys
-----------------------------------
-If you want to ensure that every foreign key column in your database has a corresponding index, you can do so like this::
+If you want to ensure that every foreign key column in your database has a corresponding index, you can do so like this:
- $ sqlite-utils index-foreign-keys books.db
+.. code-block:: bash
+
+ sqlite-utils index-foreign-keys books.db
+
+.. note::
+ In Python: :ref:`db.index_foreign_keys() ` CLI reference: :ref:`sqlite-utils index-foreign-keys `
.. _cli_defaults_not_null:
Setting defaults and not null constraints
=========================================
-You can use the ``--not-null`` and ``--default`` options (to both ``insert`` and ``upsert``) to specify columns that should be ``NOT NULL`` or to set database defaults for one or more specific columns::
+You can use the ``--not-null`` and ``--default`` options (to both ``insert`` and ``upsert``) to specify columns that should be ``NOT NULL`` or to set database defaults for one or more specific columns:
- $ sqlite-utils insert dogs.db dogs_with_scores dogs-with-scores.json \
+.. code-block:: bash
+
+ sqlite-utils insert dogs.db dogs_with_scores dogs-with-scores.json \
--not-null=age \
--not-null=name \
--default age 2 \
--default score 5
+.. note::
+ In Python: :ref:`not_null= and defaults= arguments `
+
.. _cli_create_index:
Creating indexes
================
-You can add an index to an existing table using the ``create-index`` command::
+You can add an index to an existing table using the ``create-index`` command:
- $ sqlite-utils create-index mydb.db mytable col1 [col2...]
+.. code-block:: bash
+
+ sqlite-utils create-index mydb.db mytable col1 [col2...]
This can be used to create indexes against a single column or multiple columns.
@@ -1886,9 +2669,11 @@ Use the ``--unique`` option to create a unique index.
Use ``--if-not-exists`` to avoid attempting to create the index if one with that name already exists.
-To add an index on a column in descending order, prefix the column with a hyphen. Since this can be confused for a command-line option you need to construct that like this::
+To add an index on a column in descending order, prefix the column with a hyphen. Since this can be confused for a command-line option you need to construct that like this:
- $ sqlite-utils create-index mydb.db mytable -- col1 -col2 col3
+.. code-block:: bash
+
+ sqlite-utils create-index mydb.db mytable -- col1 -col2 col3
This will create an index on that table on ``(col1, col2 desc, col3)``.
@@ -1896,87 +2681,139 @@ If your column names are already prefixed with a hyphen you'll need to manually
Add the ``--analyze`` option to run ``ANALYZE`` against the index after it has been created.
+.. note::
+ In Python: :ref:`table.create_index() ` CLI reference: :ref:`sqlite-utils create-index `
+
+.. _cli_drop_index:
+
+Dropping indexes
+================
+
+You can drop an index from an existing table using the ``drop-index`` command:
+
+.. code-block:: bash
+
+ sqlite-utils drop-index mydb.db mytable idx_mytable_col1
+
+Use ``--ignore`` to ignore the error if the index does not exist on that table.
+
+.. note::
+ In Python: :ref:`table.drop_index() ` CLI reference: :ref:`sqlite-utils drop-index `
+
.. _cli_fts:
Configuring full-text search
============================
-You can enable SQLite full-text search on a table and a set of columns like this::
+You can enable SQLite full-text search on a table and a set of columns like this:
- $ sqlite-utils enable-fts mydb.db documents title summary
+.. code-block:: bash
-This will use SQLite's FTS5 module by default. Use ``--fts4`` if you want to use FTS4::
+ sqlite-utils enable-fts mydb.db documents title summary
- $ sqlite-utils enable-fts mydb.db documents title summary --fts4
+This will use SQLite's FTS5 module by default. Use ``--fts4`` if you want to use FTS4:
-The ``enable-fts`` command will populate the new index with all existing documents. If you later add more documents you will need to use ``populate-fts`` to cause them to be indexed as well::
+.. code-block:: bash
- $ sqlite-utils populate-fts mydb.db documents title summary
+ sqlite-utils enable-fts mydb.db documents title summary --fts4
-A better solution here is to use database triggers. You can set up database triggers to automatically update the full-text index using the ``--create-triggers`` option when you first run ``enable-fts``::
+The ``enable-fts`` command will populate the new index with all existing documents. If you later add more documents you will need to use ``populate-fts`` to cause them to be indexed as well:
- $ sqlite-utils enable-fts mydb.db documents title summary --create-triggers
+.. code-block:: bash
-To set a custom FTS tokenizer, e.g. to enable Porter stemming, use ``--tokenize=``::
+ sqlite-utils populate-fts mydb.db documents title summary
- $ sqlite-utils populate-fts mydb.db documents title summary --tokenize=porter
+A better solution here is to use database triggers. You can set up database triggers to automatically update the full-text index using the ``--create-triggers`` option when you first run ``enable-fts``:
-To remove the FTS tables and triggers you created, use ``disable-fts``::
+.. code-block:: bash
- $ sqlite-utils disable-fts mydb.db documents
+ sqlite-utils enable-fts mydb.db documents title summary --create-triggers
-To rebuild one or more FTS tables (see :ref:`python_api_fts_rebuild`), use ``rebuild-fts``::
+To set a custom FTS tokenizer, e.g. to enable Porter stemming, use ``--tokenize=``:
- $ sqlite-utils rebuild-fts mydb.db documents
+.. code-block:: bash
-You can rebuild every FTS table by running ``rebuild-fts`` without passing any table names::
+ sqlite-utils populate-fts mydb.db documents title summary --tokenize=porter
- $ sqlite-utils rebuild-fts mydb.db
+To remove the FTS tables and triggers you created, use ``disable-fts``:
+
+.. code-block:: bash
+
+ sqlite-utils disable-fts mydb.db documents
+
+To rebuild one or more FTS tables (see :ref:`python_api_fts_rebuild`), use ``rebuild-fts``:
+
+.. code-block:: bash
+
+ sqlite-utils rebuild-fts mydb.db documents
+
+You can rebuild every FTS table by running ``rebuild-fts`` without passing any table names:
+
+.. code-block:: bash
+
+ sqlite-utils rebuild-fts mydb.db
+
+.. note::
+ In Python: :ref:`table.enable_fts() ` CLI reference: :ref:`sqlite-utils enable-fts `
.. _cli_search:
Executing searches
==================
-Once you have configured full-text search for a table, you can search it using ``sqlite-utils search``::
+Once you have configured full-text search for a table, you can search it using ``sqlite-utils search``:
- $ sqlite-utils search mydb.db documents searchterm
+.. code-block:: bash
+
+ sqlite-utils search mydb.db documents searchterm
This command accepts the same output options as ``sqlite-utils query``: ``--table``, ``--csv``, ``--tsv``, ``--nl`` etc.
-By default it shows the most relevant matches first. You can specify a different sort order using the ``-o`` option, which can take a column or a column followed by ``desc``::
+By default it shows the most relevant matches first. You can specify a different sort order using the ``-o`` option, which can take a column or a column followed by ``desc``:
+
+.. code-block:: bash
# Sort by rowid
- $ sqlite-utils search mydb.db documents searchterm -o rowid
+ sqlite-utils search mydb.db documents searchterm -o rowid
# Sort by created in descending order
- $ sqlite-utils search mydb.db documents searchterm -o 'created desc'
+ sqlite-utils search mydb.db documents searchterm -o 'created desc'
SQLite `advanced search syntax `__ is enabled by default. To run a search with automatic quoting applied to the terms to avoid them being potentially interpreted as advanced search syntax use the ``--quote`` option.
-You can specify a subset of columns to be returned using the ``-c`` option one or more times::
+You can specify a subset of columns to be returned using the ``-c`` option one or more times:
- $ sqlite-utils search mydb.db documents searchterm -c title -c created
+.. code-block:: bash
+
+ sqlite-utils search mydb.db documents searchterm -c title -c created
By default all search results will be returned. You can use ``--limit 20`` to return just the first 20 results.
-Use the ``--sql`` option to output the SQL that would be executed, rather than running the query::
+Use the ``--sql`` option to output the SQL that would be executed, rather than running the query:
+
+.. code-block:: bash
+
+ sqlite-utils search mydb.db documents searchterm --sql
+
+.. code-block:: output
- $ sqlite-utils search mydb.db documents searchterm --sql
with original as (
select
rowid,
*
- from [documents]
+ from "documents"
)
select
- [original].*
+ "original".*
from
- [original]
- join [documents_fts] on [original].rowid = [documents_fts].rowid
+ "original"
+ join "documents_fts" on "original".rowid = "documents_fts".rowid
where
- [documents_fts] match :query
+ "documents_fts" match :query
order by
- [documents_fts].rank
+ "documents_fts".rank
+
+.. note::
+ In Python: :ref:`table.search() ` CLI reference: :ref:`sqlite-utils search `
.. _cli_enable_counts:
@@ -1987,17 +2824,22 @@ Enabling cached counts
The ``sqlite-utils enable-counts`` command can be used to configure these triggers, either for every table in the database or for specific tables.
-::
+.. code-block:: bash
# Configure triggers for every table in the database
- $ sqlite-utils enable-counts mydb.db
+ sqlite-utils enable-counts mydb.db
# Configure triggers just for specific tables
- $ sqlite-utils enable-counts mydb.db table1 table2
+ sqlite-utils enable-counts mydb.db table1 table2
-If the ``_counts`` table ever becomes out-of-sync with the actual table counts you can repair it using the ``reset-counts`` command::
+If the ``_counts`` table ever becomes out-of-sync with the actual table counts you can repair it using the ``reset-counts`` command:
- $ sqlite-utils reset-counts mydb.db
+.. code-block:: bash
+
+ sqlite-utils reset-counts mydb.db
+
+.. note::
+ In Python: :ref:`table.enable_counts() ` CLI reference: :ref:`sqlite-utils enable-counts `
.. _cli_analyze:
@@ -2008,24 +2850,36 @@ The `SQLite ANALYZE command `__ builds
You should run ``ANALYZE`` if your database is large and you do not think your indexes are being efficiently used.
-To run ``ANALYZE`` against every index in a database, use this::
+To run ``ANALYZE`` against every index in a database, use this:
- $ sqlite-utils analyze mydb.db
+.. code-block:: bash
-You can run it against specific tables, or against specific named indexes, by passing them as optional arguments::
+ sqlite-utils analyze mydb.db
- $ sqlite-utils analyze mydb.db mytable idx_mytable_name
+You can run it against specific tables, or against specific named indexes, by passing them as optional arguments:
+
+.. code-block:: bash
+
+ sqlite-utils analyze mydb.db mytable idx_mytable_name
You can also run ``ANALYZE`` as part of another command using the ``--analyze`` option. This is supported by the ``create-index``, ``insert`` and ``upsert`` commands.
+.. note::
+ In Python: :ref:`db.analyze() ` CLI reference: :ref:`sqlite-utils analyze `
+
.. _cli_vacuum:
Vacuum
======
-You can run VACUUM to optimize your database like so::
+You can run VACUUM to optimize your database like so:
- $ sqlite-utils vacuum mydb.db
+.. code-block:: bash
+
+ sqlite-utils vacuum mydb.db
+
+.. note::
+ In Python: :ref:`db.vacuum() ` CLI reference: :ref:`sqlite-utils vacuum `
.. _cli_optimize:
@@ -2036,48 +2890,63 @@ The optimize command can dramatically reduce the size of your database if you ar
If you just want to run OPTIMIZE without the VACUUM, use the ``--no-vacuum`` flag.
-::
+.. code-block:: bash
# Optimize all FTS tables and then VACUUM
- $ sqlite-utils optimize mydb.db
+ sqlite-utils optimize mydb.db
# Optimize but skip the VACUUM
- $ sqlite-utils optimize --no-vacuum mydb.db
+ sqlite-utils optimize --no-vacuum mydb.db
To optimize specific tables rather than every FTS table, pass those tables as extra arguments:
-::
+.. code-block:: bash
- $ sqlite-utils optimize mydb.db table_1 table_2
+ sqlite-utils optimize mydb.db table_1 table_2
+
+.. note::
+ In Python: :ref:`table.optimize() ` CLI reference: :ref:`sqlite-utils optimize `
.. _cli_wal:
WAL mode
========
-You can enable `Write-Ahead Logging `__ for a database file using the ``enable-wal`` command::
+You can enable `Write-Ahead Logging `__ for a database file using the ``enable-wal`` command:
- $ sqlite-utils enable-wal mydb.db
+.. code-block:: bash
-You can disable WAL mode using ``disable-wal``::
+ sqlite-utils enable-wal mydb.db
- $ sqlite-utils disable-wal mydb.db
+You can disable WAL mode using ``disable-wal``:
+
+.. code-block:: bash
+
+ sqlite-utils disable-wal mydb.db
Both of these commands accept one or more database files as arguments.
+.. note::
+ In Python: :ref:`db.enable_wal() and db.disable_wal() ` CLI reference: :ref:`sqlite-utils enable-wal `
+
.. _cli_dump:
Dumping the database to SQL
===========================
-The ``dump`` command outputs a SQL dump of the schema and full contents of the specified database file::
+The ``dump`` command outputs a SQL dump of the schema and full contents of the specified database file:
- $ sqlite-utils dump mydb.db
+.. code-block:: bash
+
+ sqlite-utils dump mydb.db
BEGIN TRANSACTION;
CREATE TABLE ...
...
COMMIT;
+.. note::
+ In Python: :ref:`db.iterdump() ` CLI reference: :ref:`sqlite-utils dump `
+
.. _cli_load_extension:
Loading SQLite extensions
@@ -2087,9 +2956,14 @@ Many of these commands have the ability to load additional SQLite extensions usi
This option can be applied multiple times to load multiple extensions.
-Since `SpatiaLite `__ is commonly used with SQLite, the value ``spatialite`` is special: it will search for SpatiaLite in the most common installation locations, saving you from needing to remember exactly where that module is located::
+Since `SpatiaLite `__ is commonly used with SQLite, the value ``spatialite`` is special: it will search for SpatiaLite in the most common installation locations, saving you from needing to remember exactly where that module is located:
+
+.. code-block:: bash
+
+ sqlite-utils memory "select spatialite_version()" --load-extension=spatialite
+
+.. code-block:: output
- $ sqlite-utils memory "select spatialite_version()" --load-extension=spatialite
[{"spatialite_version()": "4.3.0a"}]
.. _cli_spatialite:
@@ -2099,9 +2973,11 @@ SpatiaLite helpers
`SpatiaLite `_ adds geographic capability to SQLite (similar to how PostGIS builds on PostgreSQL). The `SpatiaLite cookbook `__ is a good resource for learning what's possible with it.
-You can convert an existing table to a geographic table by adding a geometry column, use the ``sqlite-utils add-geometry-column`` command::
+You can convert an existing table to a geographic table by adding a geometry column, use the ``sqlite-utils add-geometry-column`` command:
- $ sqlite-utils add-geometry-column spatial.db locations geometry --type POLYGON --srid 4326
+.. code-block:: bash
+
+ sqlite-utils add-geometry-column spatial.db locations geometry --type POLYGON --srid 4326
The table (``locations`` in the example above) must already exist before adding a geometry column. Use ``sqlite-utils create-table`` first, then ``add-geometry-column``.
@@ -2118,17 +2994,25 @@ Eight (case-insensitive) types are allowed:
* GEOMETRYCOLLECTION
* GEOMETRY
+.. note::
+ In Python: :ref:`table.add_geometry_column() ` CLI reference: :ref:`sqlite-utils add-geometry-column `
+
.. _cli_spatialite_indexes:
Adding spatial indexes
----------------------
-Once you have a geometry column, you can speed up bounding box queries by adding a spatial index::
+Once you have a geometry column, you can speed up bounding box queries by adding a spatial index:
- $ sqlite-utils create-spatial-index spatial.db locations geometry
+.. code-block:: bash
+
+ sqlite-utils create-spatial-index spatial.db locations geometry
See this `SpatiaLite Cookbook recipe `__ for examples of how to use a spatial index.
+.. note::
+ In Python: :ref:`table.create_spatial_index() ` CLI reference: :ref:`sqlite-utils create-spatial-index `
+
.. _cli_install:
Installing packages
@@ -2138,9 +3022,9 @@ The :ref:`convert command ` and the :ref:`insert -\\-convert ``. This is a wrapper around ``pip install``.
-::
+.. code-block:: bash
- $ sqlite-utils install beautifulsoup4
+ sqlite-utils install beautifulsoup4
Use ``-U`` to upgrade an existing package.
@@ -2149,8 +3033,10 @@ Use ``-U`` to upgrade an existing package.
Uninstalling packages
=====================
-You can uninstall packages that were installed using ``sqlite-utils install`` with ``sqlite-utils uninstall ``::
+You can uninstall packages that were installed using ``sqlite-utils install`` with ``sqlite-utils uninstall ``:
- $ sqlite-utils uninstall beautifulsoup4
+.. code-block:: bash
+
+ sqlite-utils uninstall beautifulsoup4
Use ``-y`` to skip the request for confirmation.
diff --git a/docs/conf.py b/docs/conf.py
index 8d49b81..62d4642 100644
--- a/docs/conf.py
+++ b/docs/conf.py
@@ -1,8 +1,7 @@
-#!/usr/bin/env python3
-# -*- coding: utf-8 -*-
-
-from subprocess import Popen, PIPE
-from beanbag_docutils.sphinx.ext.github import github_linkcode_resolve
+import inspect
+import sys
+from pathlib import Path
+from subprocess import PIPE, CalledProcessError, Popen, check_output
# This file is execfile()d with the current directory set to its
# containing dir.
@@ -41,18 +40,56 @@ autodoc_member_order = "bysource"
autodoc_typehints = "description"
extlinks = {
- "issue": ("https://github.com/simonw/sqlite-utils/issues/%s", "#"),
+ "issue": ("https://github.com/simonw/sqlite-utils/issues/%s", "#%s"),
}
+def _linkcode_git_ref():
+ try:
+ return check_output(["git", "rev-parse", "HEAD"]).decode("utf8").strip()
+ except (CalledProcessError, OSError):
+ return "main"
+
+
def linkcode_resolve(domain, info):
- return github_linkcode_resolve(
- domain=domain,
- info=info,
- allowed_module_names=["sqlite_utils"],
- github_org_id="simonw",
- github_repo_id="sqlite-utils",
- branch="main",
+ if domain != "py":
+ return None
+
+ module_name = info.get("module")
+ if not module_name or module_name.split(".")[0] != "sqlite_utils":
+ return None
+
+ module = sys.modules.get(module_name)
+ if module is None:
+ return None
+
+ obj = module
+ for part in info.get("fullname", "").split("."):
+ obj = getattr(obj, part, None)
+ if obj is None:
+ return None
+
+ if isinstance(obj, property):
+ obj = obj.fget
+
+ try:
+ obj = inspect.unwrap(obj)
+ source_file = inspect.getsourcefile(obj)
+ _, line_number = inspect.getsourcelines(obj)
+ except (OSError, TypeError, ValueError):
+ return None
+
+ if source_file is None:
+ return None
+
+ try:
+ filename = Path(source_file).resolve().relative_to(Path(__file__).parent.parent)
+ except ValueError:
+ return None
+
+ return (
+ "https://github.com/simonw/sqlite-utils/blob/"
+ f"{_linkcode_git_ref()}/{filename}#L{line_number}"
)
@@ -79,7 +116,7 @@ author = "Simon Willison"
#
# The short X.Y version.
pipe = Popen("git describe --tags --always", stdout=PIPE, shell=True)
-git_version = pipe.stdout.read().decode("utf8")
+git_version = pipe.stdout.read().decode("utf8") if pipe.stdout else ""
if git_version:
version = git_version.rsplit("-", 1)[0]
diff --git a/docs/contributing.rst b/docs/contributing.rst
index 2e883ee..f10b02a 100644
--- a/docs/contributing.rst
+++ b/docs/contributing.rst
@@ -13,83 +13,61 @@ All improvements to the software should start with an issue. Read `How I build a
Obtaining the code
==================
-To work on this library locally, first checkout the code. Then create a new virtual environment::
+To work on this library locally, first checkout the code::
git clone git@github.com:simonw/sqlite-utils
cd sqlite-utils
- python3 -mvenv venv
- source venv/bin/activate
-Or if you are using ``pipenv``::
+Use ``uv run`` to run the development version of the tool::
- pipenv shell
-
-Within the virtual environment running ``sqlite-utils`` should run your locally editable version of the tool. You can use ``which sqlite-utils`` to confirm that you are running the version that lives in your virtual environment.
+ uv run sqlite-utils --help
.. _contributing_tests:
Running the tests
=================
-To install the dependencies and test dependencies::
+Use ``uv run`` to run the tests::
- pip install -e '.[test]'
-
-To run the tests::
-
- pytest
+ uv run pytest
.. _contributing_docs:
Building the documentation
==========================
-To build the documentation, first install the documentation dependencies::
+To build the documentation run this command::
- pip install -e '.[docs]'
+ uv run make livehtml --directory docs
-Then run ``make livehtml`` from the ``docs/`` directory to start a server on port 8000 that will serve the documentation and live-reload any time you make an edit to a ``.rst`` file::
-
- cd docs
- make livehtml
+This will start a server on port 8000 that will serve the documentation and live-reload any time you make an edit to a ``.rst`` file.
The `cog `__ tool is used to maintain portions of the documentation. You can run it like so::
- cog -r docs/*.rst
+ uv run cog -r docs/*.rst
.. _contributing_linting:
Linting and formatting
======================
-``sqlite-utils`` uses `Black `__ for code formatting, and `flake8 `__ and `mypy `__ for linting and type checking.
+``sqlite-utils`` uses `Black `__ for code formatting, and `flake8 `__ and `mypy `__ for linting and type checking::
-Black is installed as part of ``pip install -e '.[test]'`` - you can then format your code by running it in the root of the project::
+ uv run black .
- black .
+Linting tools can be run like this::
-To install ``mypy`` and ``flake8`` run the following::
-
- pip install -e '.[flake8,mypy]'
-
-Both commands can then be run in the root of the project like this::
-
- flake8
- mypy sqlite_utils
+ uv run flake8
+ uv run mypy sqlite_utils
All three of these tools are run by our CI mechanism against every commit and pull request.
.. _contributing_just:
-Using Just and pipenv
-=====================
+Using Just
+==========
-If you install `Just `__ and `pipenv `__ you can use them to manage your local development environment.
-
-To create a virtual environment and install all development dependencies, run::
-
- cd sqlite-utils
- just init
+If you install `Just `__ you can use it to manage your local development environment.
To run all of the tests and linters::
@@ -144,7 +122,7 @@ We increment ``minor`` for new features.
We increment ``patch`` for bugfix releass.
-To release a new version, first create a commit that updates the version number in ``setup.py`` and the :ref:`the changelog ` with highlights of the new version. An example `commit can be seen here `__::
+To release a new version, first create a commit that updates the version number in ``pyproject.toml`` and the :ref:`the changelog ` with highlights of the new version. An example `commit can be seen here `__::
# Update changelog
git commit -m " Release 3.29
diff --git a/docs/index.rst b/docs/index.rst
index 2bca2c8..f190d47 100644
--- a/docs/index.rst
+++ b/docs/index.rst
@@ -36,7 +36,10 @@ Contents
installation
cli
python-api
+ migrations
+ plugins
reference
cli-reference
+ upgrading
contributing
changelog
diff --git a/docs/installation.rst b/docs/installation.rst
index f4f132e..1333f5d 100644
--- a/docs/installation.rst
+++ b/docs/installation.rst
@@ -38,3 +38,53 @@ Using pipx
`pipx `__ is a tool for installing Python command-line applications in their own isolated environments. You can use ``pipx`` to install the ``sqlite-utils`` command-line tool like this::
pipx install sqlite-utils
+
+.. _installation_sqlite3_alternatives:
+
+Alternatives to sqlite3
+=======================
+
+By default, ``sqlite-utils`` uses the ``sqlite3`` package bundled with the Python standard library.
+
+Depending on your operating system, this may come with some limitations.
+
+On some platforms the ability to load additional extensions (via ``conn.load_extension(...)`` or ``--load-extension=/path/to/extension``) may be disabled.
+
+You may also see the error ``sqlite3.OperationalError: table sqlite_master may not be modified`` when trying to alter an existing table.
+
+You can work around these limitations by installing the `pysqlite3 `__ package, which provides a drop-in replacement for the standard library ``sqlite3`` module but with a recent version of SQLite and full support for loading extensions.
+
+To install ``pysqlite3`` run the following:
+
+.. code-block:: bash
+
+ sqlite-utils install pysqlite3
+
+``pysqlite3`` does not provide an implementation of the ``.iterdump()`` method. To use that method (see :ref:`python_api_itedump`) or the ``sqlite-utils dump`` command you should also install the ``sqlite-dump`` package:
+
+.. code-block:: bash
+
+ sqlite-utils install sqlite-dump
+
+.. _installation_completion:
+
+Setting up shell completion
+===========================
+
+You can configure shell tab completion for the ``sqlite-utils`` command using these commands.
+
+For ``bash``:
+
+.. code-block:: bash
+
+ eval "$(_SQLITE_UTILS_COMPLETE=bash_source sqlite-utils)"
+
+For ``zsh``:
+
+.. code-block:: zsh
+
+ eval "$(_SQLITE_UTILS_COMPLETE=zsh_source sqlite-utils)"
+
+Add this code to ``~/.zshrc`` or ``~/.bashrc`` to automatically run it when you start a new shell.
+
+See `the Click documentation `__ for more details.
diff --git a/docs/migrations.rst b/docs/migrations.rst
new file mode 100644
index 0000000..23aa9d8
--- /dev/null
+++ b/docs/migrations.rst
@@ -0,0 +1,194 @@
+.. _migrations:
+
+=====================
+ Database migrations
+=====================
+
+``sqlite-utils`` includes a migration system for applying repeatable changes to SQLite database files.
+
+A migration is a Python function that receives a :class:`sqlite_utils.Database` instance and then executes Python code to modify that database - creating or transforming tables, adding indexes, inserting rows, or any other operation supported by SQLite.
+
+Migrations are grouped into named sets using the :class:`sqlite_utils.Migrations` class, and each applied migration is recorded in the ``_sqlite_migrations`` table in that database.
+
+This means you can run the migrate operation multiple times and it will only apply migrations that have not previously been recorded.
+
+.. _migrations_define:
+
+Defining migrations
+===================
+
+Ordered migration sets are defined by first creating a :class:`sqlite_utils.Migrations` object.
+
+Individual migrations are Python functions that are then registered with that migration set. Each migration function is passed a single argument that is a :ref:`sqlite_utils.Database ` instance.
+
+The name passed to ``Migrations("creatures")`` identifies that set of migrations. Use a name that is unique for your project, since multiple migration sets can be applied to the same database.
+
+Here is a simple example of a ``migrations.py`` file which creates a table, then adds an extra column to that table in a second migration:
+
+.. code-block:: python
+
+ from sqlite_utils import Migrations
+
+ migrations = Migrations("creatures")
+
+ @migrations()
+ def create_table(db):
+ db["creatures"].create(
+ {"id": int, "name": str, "species": str},
+ pk="id",
+ )
+
+ @migrations()
+ def add_weight(db):
+ db["creatures"].add_column("weight", float)
+
+.. _migrations_python:
+
+Applying migrations in Python
+=============================
+
+Once you have a ``Migrations(name)`` collection with one or more migrations registered to it, you can execute them in Python code like this:
+
+.. code-block:: python
+
+ from sqlite_utils import Database
+
+ db = Database("creatures.db")
+ migrations.apply(db)
+
+Running ``migrations.apply(db)`` repeatedly is safe. Migrations that already have a matching ``migration_set`` and ``name`` row in ``_sqlite_migrations`` will be skipped.
+
+Migration functions are applied in the order that they were registered. The function name is used as the migration name unless you pass one explicitly:
+
+.. code-block:: python
+
+ @migrations(name="001_create_table")
+ def create_table(db):
+ db["creatures"].create({"id": int, "name": str}, pk="id")
+
+When you apply a set of migrations you can stop part way through by specifying a ``stop_before=`` migration name:
+
+.. code-block:: python
+
+ migrations.apply(db, stop_before="add_weight")
+
+.. _migrations_transactions:
+
+Migrations and transactions
+===========================
+
+Each migration runs inside a transaction, together with the ``_sqlite_migrations`` record of it having been applied. If a migration function raises an exception, everything it did is rolled back, no record is written and the migration stays pending - so fixing the error and re-applying will run that migration again from a clean state. Migrations that completed earlier in the same ``apply()`` run stay applied.
+
+Some operations cannot run inside a transaction, for example ``VACUUM`` or changing the journal mode with ``db.enable_wal()``. Register migrations like these with ``transactional=False``:
+
+.. code-block:: python
+
+ @migrations(transactional=False)
+ def compact(db):
+ db.execute("VACUUM")
+
+A migration registered with ``transactional=False`` runs without a wrapping transaction, so if it fails part way through any changes it already made will not be rolled back, and re-applying will run the whole function again.
+
+Avoid calling ``db.commit()`` or otherwise managing transactions manually inside a transactional migration - register the migration with ``transactional=False`` if it needs to control its own transactions. Using ``with db.atomic():`` blocks inside a migration is fine: they nest as savepoints within the migration's transaction, so the migration as a whole still commits or rolls back as a single unit. See :ref:`python_api_transactions`.
+
+Applying migrations using the CLI
+=================================
+
+Run migrations using the ``sqlite-utils migrate`` command:
+
+.. code-block:: bash
+
+ sqlite-utils migrate creatures.db path/to/migrations.py
+
+The first argument is the database file. The remaining arguments can be paths to migration files or directories containing migration files.
+
+If you omit migration paths, ``sqlite-utils`` searches the current directory and subdirectories for files called ``migrations.py``:
+
+.. code-block:: bash
+
+ sqlite-utils migrate creatures.db
+
+You can also pass a directory. Every ``migrations.py`` file in that directory tree will be considered:
+
+.. code-block:: bash
+
+ sqlite-utils migrate creatures.db path/to/project/
+
+Running the command repeatedly is safe. Migrations that already have a matching ``migration_set`` and ``name`` row in ``_sqlite_migrations`` will be skipped.
+
+Listing migrations
+==================
+
+Use ``--list`` to show applied and pending migrations without running them. This is a read-only operation - it will not create the database file or the ``_sqlite_migrations`` table:
+
+.. code-block:: bash
+
+ sqlite-utils migrate creatures.db --list
+
+Example output:
+
+.. code-block:: output
+
+ Migrations for: creatures
+
+ Applied:
+ create_table - 2026-06-09 17:23:12.048092+00:00
+ add_weight - 2026-06-09 17:23:12.051249+00:00
+
+ Pending:
+ add_age
+
+Stopping before a migration
+===========================
+
+When applying migrations using the CLI, you can stop before a named migration:
+
+.. code-block:: bash
+
+ sqlite-utils migrate creatures.db path/to/migrations.py --stop-before add_weight
+
+This applies any pending migrations before ``add_weight`` and leaves ``add_weight`` and later migrations pending. An unqualified migration name matches in any migration set.
+
+You can also target a specific migration set using ``migration_set:migration_name``. This is useful if a migrations file contains more than one migration set, or if multiple sets use the same migration name:
+
+.. code-block:: bash
+
+ sqlite-utils migrate creatures.db path/to/migrations.py \
+ --stop-before creatures:add_weight \
+ --stop-before sales:drop_index
+
+The ``--stop-before`` option can be passed more than once.
+
+If a ``--stop-before`` value does not match any known migration the command exits with an error, rather than silently applying everything. Naming a migration that has already been applied is also an error - stopping before it is impossible to honor - and no pending migrations are applied.
+
+Verbose output
+==============
+
+Use ``--verbose`` or ``-v`` to show the schema before and after migrations are applied, plus a unified diff when the schema changes:
+
+.. code-block:: bash
+
+ sqlite-utils migrate creatures.db --verbose
+
+Migrating from sqlite-migrate
+=============================
+
+This system uses the same migration table format as the older `sqlite-migrate `__ package. To use existing migration files directly with ``sqlite-utils``, update their import from ``sqlite_migrate`` to ``sqlite_utils``:
+
+.. code-block:: python
+
+ from sqlite_utils import Migrations
+
+ migration = Migrations("creatures")
+
+ @migration()
+ def create_table(db):
+ db["creatures"].create({"id": int, "name": str}, pk="id")
+
+Python API
+==========
+
+.. autoclass:: sqlite_utils.migrations.Migrations
+ :members:
+ :undoc-members:
+ :exclude-members: _Migration, _AppliedMigration
diff --git a/docs/plugins.rst b/docs/plugins.rst
new file mode 100644
index 0000000..99588ee
--- /dev/null
+++ b/docs/plugins.rst
@@ -0,0 +1,159 @@
+.. _plugins:
+
+=========
+ Plugins
+=========
+
+``sqlite-utils`` supports plugins, which can be used to add extra features to the software.
+
+Plugins can add new commands, for example ``sqlite-utils some-command ...``
+
+Plugins can be installed using the ``sqlite-utils install`` command:
+
+.. code-block:: bash
+
+ sqlite-utils install sqlite-utils-name-of-plugin
+
+You can see a JSON list of plugins that have been installed by running this:
+
+.. code-block:: bash
+
+ sqlite-utils plugins
+
+Plugin hooks such as :ref:`plugins_hooks_prepare_connection` affect each instance of the ``Database`` class. You can opt-out of these plugins by creating that class instance like so:
+
+.. code-block:: python
+
+ db = Database(memory=True, execute_plugins=False)
+
+.. _plugins_building:
+
+Building a plugin
+-----------------
+
+Plugins are created in a directory named after the plugin. To create a "hello world" plugin, first create a ``hello-world`` directory:
+
+.. code-block:: bash
+
+ mkdir hello-world
+ cd hello-world
+
+In that folder create two files. The first is a ``pyproject.toml`` file describing the plugin:
+
+.. code-block:: toml
+
+ [project]
+ name = "sqlite-utils-hello-world"
+ version = "0.1"
+
+ [project.entry-points.sqlite_utils]
+ hello_world = "sqlite_utils_hello_world"
+
+The ``[project.entry-points.sqlite_utils]`` section tells ``sqlite-utils`` which module to load when executing the plugin.
+
+Then create ``sqlite_utils_hello_world.py`` with the following content:
+
+.. code-block:: python
+
+ import click
+ import sqlite_utils
+
+ @sqlite_utils.hookimpl
+ def register_commands(cli):
+ @cli.command()
+ def hello_world():
+ "Say hello world"
+ click.echo("Hello world!")
+
+Install the plugin in "editable" mode - so you can make changes to the code and have them picked up instantly by ``sqlite-utils`` - like this:
+
+.. code-block:: bash
+
+ sqlite-utils install -e .
+
+Or pass the path to your plugin directory:
+
+.. code-block:: bash
+
+ sqlite-utils install -e /dev/sqlite-utils-hello-world
+
+Now, running this should execute your new command:
+
+.. code-block:: bash
+
+ sqlite-utils hello-world
+
+Your command will also be listed in the output of ``sqlite-utils --help``.
+
+See the `LLM plugin documentation `__ for tips on distributing your plugin.
+
+.. _plugins_hooks:
+
+Plugin hooks
+------------
+
+Plugin hooks allow ``sqlite-utils`` to be customized.
+
+.. _plugins_hooks_register_commands:
+
+register_commands(cli)
+~~~~~~~~~~~~~~~~~~~~~~
+
+This hook can be used to register additional commands with the ``sqlite-utils`` CLI. It is called with the ``cli`` object, which is a ``click.Group`` instance.
+
+Example implementation:
+
+.. code-block:: python
+
+ import click
+ import sqlite_utils
+
+ @sqlite_utils.hookimpl
+ def register_commands(cli):
+ @cli.command()
+ def hello_world():
+ "Say hello world"
+ click.echo("Hello world!")
+
+New commands implemented by plugins can invoke existing commands using the `context.invoke `__ mechanism.
+
+As a special niche feature, if your plugin needs to import some files and then act against an in-memory database containing those files you can forward to the :ref:`sqlite-utils memory command ` and pass it ``return_db=True``:
+
+.. code-block:: python
+
+ @cli.command()
+ @click.pass_context
+ @click.argument(
+ "paths",
+ type=click.Path(file_okay=True, dir_okay=False, allow_dash=True),
+ required=False,
+ nargs=-1,
+ )
+ def show_schema_for_files(ctx, paths):
+ from sqlite_utils.cli import memory
+ db = ctx.invoke(memory, paths=paths, return_db=True)
+ # Now do something with that database
+ click.echo(db.schema)
+
+.. _plugins_hooks_prepare_connection:
+
+prepare_connection(conn)
+~~~~~~~~~~~~~~~~~~~~~~~~
+
+This hook is called when a new SQLite database connection is created. You can use it to `register custom SQL functions `_, aggregates and collations. For example:
+
+.. code-block:: python
+
+ import sqlite_utils
+
+ @sqlite_utils.hookimpl
+ def prepare_connection(conn):
+ conn.create_function(
+ "hello", 1, lambda name: f"Hello, {name}!"
+ )
+
+This registers a SQL function called ``hello`` which takes a single argument and can be called like this:
+
+.. code-block:: sql
+
+ select hello("world"); -- "Hello, world!"
diff --git a/docs/python-api.rst b/docs/python-api.rst
index 206e5e6..43b734d 100644
--- a/docs/python-api.rst
+++ b/docs/python-api.rst
@@ -19,7 +19,7 @@ Here's how to create a new SQLite database file containing a new ``chickens`` ta
from sqlite_utils import Database
db = Database("chickens.db")
- db["chickens"].insert_all([{
+ db.table("chickens").insert_all([{
"name": "Azi",
"color": "blue",
}, {
@@ -33,11 +33,13 @@ Here's how to create a new SQLite database file containing a new ``chickens`` ta
"color": "black",
}])
+The inserted rows are saved to the database file straight away - methods like ``insert_all()`` commit their own changes, so no ``commit()`` call is needed. See :ref:`python_api_transactions` for how this works.
+
You can loop through those rows like this:
.. code-block:: python
- for row in db["chickens"].rows:
+ for row in db.table("chickens").rows:
print(row)
Which outputs the following::
@@ -93,6 +95,8 @@ Instead of a file path you can pass in an existing SQLite connection:
db = Database(sqlite3.connect("my_database.db"))
+The connection must use Python's default transaction handling. Connections created with the Python 3.12+ ``sqlite3.connect(..., autocommit=True)`` or ``autocommit=False`` options are rejected with a ``sqlite_utils.db.TransactionError`` - see :ref:`python_api_transactions_modes`.
+
If you want to create an in-memory database, you can do so like this:
.. code-block:: python
@@ -105,12 +109,59 @@ You can also create a named in-memory database. Unlike regular memory databases
db = Database(memory_name="my_shared_database")
+After creating a ``Database`` you can use ``db.memory`` and ``db.memory_name`` to tell whether it is backed by an in-memory database and to read the shared cache name. ``db.memory`` is ``True`` for any in-memory database and ``db.memory_name`` holds the name passed to ``memory_name=``, or ``None`` otherwise.
+
+.. code-block:: python
+
+ db = Database(memory_name="shared")
+ db.memory # True
+ db.memory_name # "shared"
+
Connections use ``PRAGMA recursive_triggers=on`` by default. If you don't want to use `recursive triggers `__ you can turn them off using:
.. code-block:: python
db = Database(memory=True, recursive_triggers=False)
+By default, any :ref:`sqlite-utils plugins ` that implement the :ref:`plugins_hooks_prepare_connection` hook will be executed against the connection when you create the ``Database`` object. You can opt out of executing plugins using ``execute_plugins=False`` like this:
+
+.. code-block:: python
+
+ db = Database(memory=True, execute_plugins=False)
+
+You can pass ``strict=True`` to enable `SQLite STRICT mode `__ for all tables created using this database object:
+
+.. code-block:: python
+
+ db = Database("my_database.db", strict=True)
+
+.. _python_api_close:
+
+Closing a database
+------------------
+
+Database objects maintain a connection to the underlying SQLite database. You can explicitly close this connection using the ``.close()`` method:
+
+.. code-block:: python
+
+ db = Database("my_database.db")
+ # ... use the database ...
+ db.close()
+
+The ``Database`` object also works as a context manager, which will automatically close the connection when the ``with`` block exits:
+
+.. code-block:: python
+
+ with Database("my_database.db") as db:
+ db["my_table"].insert({"name": "Example"})
+ # Connection is automatically closed here
+
+Exiting the block is equivalent to calling ``db.close()``: the connection is closed and any transaction still open at that point is rolled back. This matches SQLite's own behavior when a connection closes.
+
+This rarely matters in practice. Everything that writes to the database - including raw ``db.execute()`` statements - commits automatically, so a transaction can only be open here if you explicitly started one with ``db.begin()`` and have not yet committed it. In that case the decision to commit stays with you: committing automatically on exit could silently persist half-finished work, for example if your code returned early from the block. Call ``db.commit()`` when the work is complete.
+
+Note this differs from the ``sqlite3.Connection`` context manager in the standard library, which commits on success but does not close the connection. See :ref:`python_api_transactions` for the full transaction model.
+
.. _python_api_attach:
Attaching additional databases
@@ -133,6 +184,9 @@ You can attach an additional database using the ``.attach()`` method, providing
You can reference tables in the attached database using the alias value you passed to ``db.attach(alias, filepath)`` as a prefix, for example the ``second.table_in_second`` reference in the SQL query above.
+.. note::
+ In the CLI: :ref:`sqlite-utils --attach `
+
.. _python_api_tracing:
Tracing queries
@@ -158,7 +212,7 @@ You can also turn on a tracer function temporarily for a block of code using the
db = Database(memory=True)
# ... later
with db.tracer(print):
- db["dogs"].insert({"name": "Cleo"})
+ db.table("dogs").insert({"name": "Cleo"})
This example will print queries only for the duration of the ``with`` block.
@@ -179,13 +233,33 @@ The ``db.query(sql)`` function executes a SQL query and returns an iterator over
.. code-block:: python
db = Database(memory=True)
- db["dogs"].insert_all([{"name": "Cleo"}, {"name": "Pancakes"}])
+ db.table("dogs").insert_all([{"name": "Cleo"}, {"name": "Pancakes"}])
for row in db.query("select * from dogs"):
print(row)
# Outputs:
# {'name': 'Cleo'}
# {'name': 'Pancakes'}
+The SQL query is executed as soon as ``db.query()`` is called. The resulting rows are fetched lazily as you iterate, so large result sets are not loaded into memory all at once. Because execution is immediate, an error in your SQL will raise an exception straight away, and a statement such as ``INSERT ... RETURNING`` will take effect - and be committed, unless a transaction is open - even if you do not iterate over its results.
+
+``db.query()`` can only be used with SQL that returns rows. Passing a statement that returns no rows - an ``INSERT`` or ``UPDATE`` without a ``RETURNING`` clause, for example - will raise a ``ValueError``. The rejected statement is rolled back, so it has no effect on the database. Use :ref:`db.execute() ` for those statements instead.
+
+There is one exception to the rolled-back guarantee: a ``PRAGMA`` statement that returns no rows, such as ``PRAGMA user_version = 5``, still raises a ``ValueError`` but will already have taken effect. Some PRAGMA statements refuse to run inside a transaction, so PRAGMAs are executed outside the savepoint that is used to roll back other rejected statements. Use ``db.execute()`` for PRAGMA statements that do not return rows.
+
+If a query returns more than one column with the same name - a join between two tables that share column names, for example - later occurrences are renamed with a numeric suffix, so every value is included in the dictionary:
+
+.. code-block:: python
+
+ row = next(db.query("select 1 as id, 2 as id, 3 as id"))
+ print(row)
+ # Outputs:
+ # {'id': 1, 'id_2': 2, 'id_3': 3}
+
+A suffix that would collide with another column in the query is skipped - ``select 1 as id, 2 as id, 3 as id_2`` returns ``{'id': 1, 'id_3': 2, 'id_2': 3}``. The same renaming is applied by ``table.rows_where()`` and ``table.search()``.
+
+.. note::
+ In the CLI: :ref:`sqlite-utils query `
+
.. _python_api_execute:
db.execute(sql, params)
@@ -198,7 +272,7 @@ The ``db.execute()`` and ``db.executescript()`` methods provide wrappers around
.. code-block:: python
db = Database(memory=True)
- db["dogs"].insert({"name": "Cleo"})
+ db.table("dogs").insert({"name": "Cleo"})
cursor = db.execute("update dogs set name = 'Cleopaws'")
print(cursor.rowcount)
# Outputs the number of rows affected by the update
@@ -206,6 +280,9 @@ The ``db.execute()`` and ``db.executescript()`` methods provide wrappers around
Other cursor methods such as ``.fetchone()`` and ``.fetchall()`` are also available, see the `standard library documentation `__.
+.. note::
+ Write statements executed this way are committed automatically, unless a transaction is already open in which case they become part of it - see :ref:`python_api_transactions_execute`.
+
.. _python_api_parameters:
Passing parameters
@@ -234,26 +311,181 @@ Named parameters using ``:name`` can be filled using a dictionary:
In this example ``next()`` is used to retrieve the first result in the iterator returned by the ``db.query()`` method.
+.. _python_api_transactions:
+
+Transactions and saving your changes
+====================================
+
+Every method in this library that writes to the database - ``insert()``, ``upsert()``, ``update()``, ``delete()``, ``delete_where()``, ``transform()``, ``create_table()``, ``create_index()``, ``enable_fts()`` and the rest - runs inside its own transaction and commits it before returning. Your changes are saved to disk as soon as the method call finishes:
+
+.. code-block:: python
+
+ db = Database("data.db")
+ db.table("news").insert({"headline": "Dog wins award"})
+ # The new row is already saved - no commit() required
+
+The same applies to raw SQL executed with :ref:`db.execute() ` - a write statement is committed as soon as it has run.
+
+Another way to think about this is that each sqlite-utils method call is its own unit of work. If several method calls must either all succeed or all fail, use ``db.atomic()`` to turn them into a single unit of work.
+
+You never need to call ``commit()``, and you do not need to close the database to persist your changes. There are exactly two situations where you need to think about transactions:
+
+1. You want to group several write operations together, so they either all succeed or all fail - use :ref:`db.atomic() `.
+2. You are :ref:`managing a transaction yourself ` with ``db.begin()``, in which case nothing is committed until you commit - the library will never commit a transaction you opened.
+
+``with Database(...) as db:`` is not a transaction block. It manages the lifetime of the database connection and closes it on exit. Use ``with db.atomic():`` for a transaction.
+
+.. _python_api_atomic:
+
+Grouping changes with db.atomic()
+---------------------------------
+
+Use ``db.atomic()`` to group multiple operations in a single transaction:
+
+.. code-block:: python
+
+ with db.atomic():
+ db.table("dogs").insert({"id": 1, "name": "Cleo"}, pk="id")
+ db.table("dogs").insert({"id": 2, "name": "Pancakes"})
+
+The transaction commits when the block exits. If an exception is raised, changes made inside the block will be rolled back.
+
+This matters when several operations represent a single logical change. Without ``db.atomic()``, an earlier method call remains committed if a later one fails:
+
+.. code-block:: python
+
+ # These are two separate transactions
+ db.table("accounts").update(1, {"balance": 90})
+ db.table("accounts").update(2, {"balance": 110})
+
+ # These updates either both succeed or both fail
+ with db.atomic():
+ db.table("accounts").update(1, {"balance": 90})
+ db.table("accounts").update(2, {"balance": 110})
+
+Transactions can also improve performance. Calling ``insert()`` repeatedly outside ``db.atomic()`` creates and commits a separate transaction for every call. For bulk inserts, prefer :ref:`insert_all() `. If you need to call several different methods in a loop, wrap the loop in ``db.atomic()``:
+
+.. code-block:: python
+
+ with db.atomic():
+ for row in rows:
+ db.table("events").insert(row)
+
+``db.atomic()`` can be nested. Nested blocks use SQLite savepoints, so an exception in an inner block can roll back to that savepoint without rolling back the entire outer transaction:
+
+.. code-block:: python
+
+ with db.atomic():
+ db.table("dogs").insert({"id": 1, "name": "Cleo"}, pk="id")
+ try:
+ with db.atomic():
+ db.table("dogs").insert({"id": 2, "name": "Pancakes"})
+ raise ValueError("skip this one")
+ except ValueError:
+ pass
+ db.table("dogs").insert({"id": 3, "name": "Marnie"})
+
+The transaction is opened with a deferred ``BEGIN`` - SQLite takes the necessary locks when the first statement inside the block runs.
+
+.. _python_api_transactions_execute:
+
+Raw SQL writes with db.execute()
+--------------------------------
+
+Write statements executed with :ref:`db.execute() ` follow the same rule as everything else: they are committed automatically as soon as they have run.
+
+.. code-block:: python
+
+ db.execute("insert into news (headline) values (?)", ["Dog wins award"])
+ # Already committed
+
+``db.execute()`` participates in sqlite-utils transaction handling. Calling ``db.conn.execute()`` directly bypasses that policy and leaves transaction handling to Python's underlying ``sqlite3.Connection``. Prefer ``db.execute()`` unless you deliberately need the lower-level API.
+
+If a transaction is open - because the call happens inside a ``db.atomic()`` block, or after ``db.begin()`` - the statement becomes part of that transaction instead, and commits when the transaction commits:
+
+.. code-block:: python
+
+ with db.atomic():
+ db.execute("insert into news (headline) values (?)", ["Dog wins award"])
+ db.execute("insert into news (headline) values (?)", ["Cat unimpressed"])
+ # Both rows committed together
+
+One corner case: a row-returning write such as ``INSERT ... RETURNING`` executed through ``db.execute()`` cannot be auto-committed, because its rows have not been read yet - call ``db.commit()`` after fetching them, or use :ref:`db.query() ` for those statements, which executes the write and commits it immediately.
+
+.. _python_api_transactions_manual:
+
+Managing transactions yourself
+------------------------------
+
+You can take full manual control using the ``db.begin()``, ``db.commit()`` and ``db.rollback()`` methods:
+
+.. code-block:: python
+
+ db.begin()
+ db.table("news").insert({"headline": "Dog wins award"})
+ if all_looks_good:
+ db.commit()
+ else:
+ db.rollback()
+
+``db.begin()`` raises ``sqlite3.OperationalError`` if a transaction is already open. ``db.commit()`` and ``db.rollback()`` do nothing if there is no open transaction.
+
+The library will never commit a transaction you opened. If you call write methods such as ``insert()`` - or use ``db.atomic()`` - while your transaction is open, they participate in it using SQLite savepoints instead of committing: exiting an ``atomic()`` block releases its savepoint, but nothing is saved to disk until you commit the outer transaction yourself. If you roll back, their changes are rolled back too.
+
+Prefer ``db.atomic()`` or ``db.begin()``, ``db.commit()`` and ``db.rollback()`` over mixing sqlite-utils transaction methods with calls to ``db.conn.commit()``, ``db.conn.rollback()`` or raw transaction-control SQL. Mixing the two layers makes it much harder to tell which layer owns the current transaction.
+
+Some related safeguards to be aware of:
+
+- ``db.enable_wal()`` and ``db.disable_wal()`` raise a ``sqlite_utils.db.TransactionError`` if called while a transaction is open, because changing the journal mode would commit it as a side effect.
+- ``table.transform()`` raises a ``sqlite_utils.db.TransactionError`` if called while a transaction is open with ``PRAGMA foreign_keys`` enabled and the table is referenced by foreign keys with destructive ``ON DELETE`` actions, because the pragma cannot be turned off mid-transaction to protect those referencing rows - see :ref:`python_api_transform_foreign_keys_transactions`.
+- Closing the database - explicitly with ``db.close()``, or by exiting a ``with Database(...) as db:`` block - rolls back any transaction that is still open, see :ref:`python_api_close`.
+
+.. _python_api_transactions_modes:
+
+Supported connection modes
+--------------------------
+
+``db.atomic()`` and the automatic per-method transactions currently require a connection using Python's legacy transaction control mode (``sqlite3.LEGACY_TRANSACTION_CONTROL`` on Python 3.12 and later). Passing a connection created with the Python 3.12+ ``sqlite3.connect(..., autocommit=True)`` or ``autocommit=False`` options to ``Database()`` raises a ``sqlite_utils.db.TransactionError``.
+
+Connections using ``autocommit=False`` are not supported because Python keeps a transaction open continuously. sqlite-utils uses ``Connection.in_transaction`` to distinguish its own transactions from transactions opened by its caller, and that distinction is not available in this mode.
+
+Connections using ``autocommit=True`` are also currently rejected because sqlite-utils has not formally exposed that as a supported configuration.
+
.. _python_api_table:
Accessing tables
================
-Tables are accessed using the indexing operator, like so:
-
-.. code-block:: python
-
- table = db["my_table"]
-
-If the table does not yet exist, it will be created the first time you attempt to insert or upsert data into it.
-
-You can also access tables using the ``.table()`` method like so:
+Tables are accessed using the ``db.table()`` method, like so:
.. code-block:: python
table = db.table("my_table")
-Using this factory function allows you to set :ref:`python_api_table_configuration`.
+Using this factory function allows you to set :ref:`python_api_table_configuration`. Additional keyword arguments to ``db.table()`` will be used if a further method call causes the table to be created.
+
+The ``db.table()`` method will always return a :ref:`reference_db_table` instance, or raise a ``sqlite_utils.db.NoTable`` exception if the table name is actually a SQL view.
+
+You can also access tables or views using dictionary-style syntax, like this:
+
+.. code-block:: python
+
+ table_or_view = db["my_table_or_view_name"]
+
+If a table accessed using either of these methods does not yet exist, it will be created the first time you attempt to insert or upsert data into it.
+
+.. _python_api_view:
+
+Accessing views
+===============
+
+SQL views can be accessed using the ``db.view()`` method, like so:
+
+.. code-block:: python
+
+ view = db.view("my_view")
+
+This will return a :ref:`reference_db_view` instance, or raise a ``sqlite_utils.db.NoView`` exception if the view does not exist.
.. _python_api_tables:
@@ -272,6 +504,9 @@ You can also iterate through the table objects themselves using the ``.tables``
>>> db.tables
[]
+.. note::
+ In the CLI: :ref:`sqlite-utils tables `
+
.. _python_api_views:
Listing views
@@ -297,6 +532,9 @@ View objects are similar to Table objects, except that any attempts to insert or
* ``rows_where(where, where_args, order_by, select)``
* ``drop()``
+.. note::
+ In the CLI: :ref:`sqlite-utils views `
+
.. _python_api_rows:
Listing rows
@@ -305,7 +543,7 @@ Listing rows
To iterate through dictionaries for each of the rows in a table, use ``.rows``::
>>> db = sqlite_utils.Database("dogs.db")
- >>> for row in db["dogs"].rows:
+ >>> for row in db.table("dogs").rows:
... print(row)
{'id': 1, 'age': 4, 'name': 'Cleo'}
{'id': 2, 'age': 2, 'name': 'Pancakes'}
@@ -313,26 +551,26 @@ To iterate through dictionaries for each of the rows in a table, use ``.rows``::
You can filter rows by a WHERE clause using ``.rows_where(where, where_args)``::
>>> db = sqlite_utils.Database("dogs.db")
- >>> for row in db["dogs"].rows_where("age > ?", [3]):
+ >>> for row in db.table("dogs").rows_where("age > ?", [3]):
... print(row)
{'id': 1, 'age': 4, 'name': 'Cleo'}
The first argument is a fragment of SQL. The second, optional argument is values to be passed to that fragment - you can use ``?`` placeholders and pass an array, or you can use ``:named`` parameters and pass a dictionary, like this::
- >>> for row in db["dogs"].rows_where("age > :age", {"age": 3}):
+ >>> for row in db.table("dogs").rows_where("age > :age", {"age": 3}):
... print(row)
{'id': 1, 'age': 4, 'name': 'Cleo'}
To return custom columns (instead of the default that uses ``select *``) pass ``select="column1, column2"``::
>>> db = sqlite_utils.Database("dogs.db")
- >>> for row in db["dogs"].rows_where(select='name, age'):
+ >>> for row in db.table("dogs").rows_where(select='name, age'):
... print(row)
{'name': 'Cleo', 'age': 4}
To specify an order, use the ``order_by=`` argument::
- >>> for row in db["dogs"].rows_where("age > 1", order_by="age"):
+ >>> for row in db.table("dogs").rows_where("age > 1", order_by="age"):
... print(row)
{'id': 2, 'age': 2, 'name': 'Pancakes'}
{'id': 1, 'age': 4, 'name': 'Cleo'}
@@ -341,17 +579,20 @@ You can use ``order_by="age desc"`` for descending order.
You can order all records in the table by excluding the ``where`` argument::
- >>> for row in db["dogs"].rows_where(order_by="age desc"):
+ >>> for row in db.table("dogs").rows_where(order_by="age desc"):
... print(row)
{'id': 1, 'age': 4, 'name': 'Cleo'}
{'id': 2, 'age': 2, 'name': 'Pancakes'}
This method also accepts ``offset=`` and ``limit=`` arguments, for specifying an OFFSET and a LIMIT for the SQL query::
- >>> for row in db["dogs"].rows_where(order_by="age desc", limit=1):
+ >>> for row in db.table("dogs").rows_where(order_by="age desc", limit=1):
... print(row)
{'id': 1, 'age': 4, 'name': 'Cleo'}
+.. note::
+ In the CLI: :ref:`sqlite-utils rows `
+
.. _python_api_rows_count_where:
Counting rows
@@ -359,7 +600,7 @@ Counting rows
To count the number of rows that would be returned by a where filter, use ``.count_where(where, where_args)``:
- >>> db["dogs"].count_where("age > ?", [1])
+ >>> db.table("dogs").count_where("age > ?", [1])
2
.. _python_api_pks_and_rows_where:
@@ -378,21 +619,21 @@ If the table is a ``rowid`` table (with no explicit primary key column) then tha
::
>>> db = sqlite_utils.Database(memory=True)
- >>> db["dogs"].insert({"name": "Cleo"})
- >>> for pk, row in db["dogs"].pks_and_rows_where():
+ >>> db.table("dogs").insert({"name": "Cleo"})
+ >>> for pk, row in db.table("dogs").pks_and_rows_where():
... print(pk, row)
1 {'rowid': 1, 'name': 'Cleo'}
- >>> db["dogs_with_pk"].insert({"id": 5, "name": "Cleo"}, pk="id")
- >>> for pk, row in db["dogs_with_pk"].pks_and_rows_where():
+ >>> db.table("dogs_with_pk").insert({"id": 5, "name": "Cleo"}, pk="id")
+ >>> for pk, row in db.table("dogs_with_pk").pks_and_rows_where():
... print(pk, row)
5 {'id': 5, 'name': 'Cleo'}
- >>> db["dogs_with_compound_pk"].insert(
+ >>> db.table("dogs_with_compound_pk").insert(
... {"species": "dog", "id": 3, "name": "Cleo"},
... pk=("species", "id")
... )
- >>> for pk, row in db["dogs_with_compound_pk"].pks_and_rows_where():
+ >>> for pk, row in db.table("dogs_with_compound_pk").pks_and_rows_where():
... print(pk, row)
('dog', 3) {'species': 'dog', 'id': 3, 'name': 'Cleo'}
@@ -404,12 +645,12 @@ Retrieving a specific record
You can retrieve a record by its primary key using ``table.get()``::
>>> db = sqlite_utils.Database("dogs.db")
- >>> print(db["dogs"].get(1))
+ >>> print(db.table("dogs").get(1))
{'id': 1, 'age': 4, 'name': 'Cleo'}
If the table has a compound primary key you can pass in the primary key values as a tuple::
- >>> db["compound_dogs"].get(("mixed", 3))
+ >>> db.table("compound_dogs").get(("mixed", 3))
If the record does not exist a ``NotFoundError`` will be raised:
@@ -418,7 +659,7 @@ If the record does not exist a ``NotFoundError`` will be raised:
from sqlite_utils.db import NotFoundError
try:
- row = db["dogs"].get(5)
+ row = db.table("dogs").get(5)
except NotFoundError:
print("Dog not found")
@@ -432,10 +673,13 @@ The ``db.schema`` property returns the full SQL schema for the database as a str
>>> db = sqlite_utils.Database("dogs.db")
>>> print(db.schema)
CREATE TABLE "dogs" (
- [id] INTEGER PRIMARY KEY,
- [name] TEXT
+ "id" INTEGER PRIMARY KEY,
+ "name" TEXT
);
+.. note::
+ In the CLI: :ref:`sqlite-utils schema `
+
.. _python_api_creating_tables:
Creating tables
@@ -449,7 +693,7 @@ The easiest way to create a new table is to insert a record into it:
import sqlite3
db = Database("dogs.db")
- dogs = db["dogs"]
+ dogs = db.table("dogs")
dogs.insert({
"name": "Cleo",
"twitter": "cleopaws",
@@ -493,7 +737,7 @@ If you want to explicitly set the order of the columns you can do so using the `
.. code-block:: python
- db["dogs"].insert({
+ db.table("dogs").insert({
"id": 1,
"name": "Cleo",
"twitter": "cleopaws",
@@ -507,7 +751,7 @@ Column types are detected based on the example data provided. Sometimes you may
.. code-block:: python
- db["dogs"].insert({
+ db.table("dogs").insert({
"id": 1,
"name": "Cleo",
"age": "5",
@@ -517,11 +761,11 @@ This will create a table with the following schema:
.. code-block:: sql
- CREATE TABLE [dogs] (
- [id] INTEGER PRIMARY KEY,
- [name] TEXT,
- [age] INTEGER,
- [weight] FLOAT
+ CREATE TABLE "dogs" (
+ "id" INTEGER PRIMARY KEY,
+ "name" TEXT,
+ "age" INTEGER,
+ "weight" REAL
)
.. _python_api_explicit_create:
@@ -533,7 +777,7 @@ You can directly create a new table without inserting any data into it using the
.. code-block:: python
- db["cats"].create({
+ db.table("cats").create({
"id": int,
"name": str,
"weight": float,
@@ -545,20 +789,22 @@ This method takes optional arguments ``pk=``, ``column_order=``, ``foreign_keys=
A ``sqlite_utils.utils.sqlite3.OperationalError`` will be raised if a table of that name already exists.
-To do nothing if the table already exists, add ``if_not_exists=True``:
+You can pass ``ignore=True`` to ignore that error. You can also use ``if_not_exists=True`` to use the SQL ``CREATE TABLE IF NOT EXISTS`` pattern to achieve the same effect:
.. code-block:: python
- db["cats"].create({
+ db.table("cats").create({
"id": int,
"name": str,
}, pk="id", if_not_exists=True)
+To drop and replace any existing table of that name, pass ``replace=True``. This is a **dangerous operation** that will result in loss of existing data in the table.
+
You can also pass ``transform=True`` to have any existing tables :ref:`transformed ` to match your new table specification. This is a **dangerous operation** as it will drop columns that are no longer listed in your call to ``.create()``, so be careful when running this.
.. code-block:: python
- db["cats"].create({
+ db.table("cats").create({
"id": int,
"name": str,
"weight": float,
@@ -573,6 +819,18 @@ The ``transform=True`` option will update the table schema if any of the followi
Changes to ``foreign_keys=`` are not currently detected and applied by ``transform=True``.
+You can pass ``strict=True`` to create a table in ``STRICT`` mode:
+
+.. code-block:: python
+
+ db.table("cats").create({
+ "id": int,
+ "name": str,
+ }, strict=True)
+
+.. note::
+ In the CLI: :ref:`sqlite-utils create-table `
+
.. _python_api_compound_primary_keys:
Compound primary keys
@@ -582,7 +840,7 @@ If you want to create a table with a compound primary key that spans multiple co
.. code-block:: python
- db["cats"].create({
+ db.table("cats").create({
"id": int,
"breed": str,
"name": str,
@@ -622,25 +880,80 @@ You can leave off the third item in the tuple to have the referenced column auto
.. code-block:: python
- db["authors"].insert_all([
+ db.table("authors").insert_all([
{"id": 1, "name": "Sally"},
{"id": 2, "name": "Asheesh"}
], pk="id")
- db["books"].insert_all([
+ db.table("books").insert_all([
{"title": "Hedgehogs of the world", "author_id": 1},
{"title": "How to train your wolf", "author_id": 2},
], foreign_keys=[
("author_id", "authors")
])
+.. _python_api_compound_foreign_keys:
+
+Compound foreign keys
+~~~~~~~~~~~~~~~~~~~~~
+
+To create a compound (multi-column) foreign key, use tuples of column names in place of the single column names:
+
+.. code-block:: python
+
+ db.table("courses").create({
+ "course_code": str,
+ "campus_name": str,
+ "dept_code": str,
+ }, pk="course_code", foreign_keys=[
+ (("campus_name", "dept_code"), "departments", ("campus_name", "dept_code"))
+ ])
+
+This creates a table-level constraint:
+
+.. code-block:: sql
+
+ CREATE TABLE "courses" (
+ "course_code" TEXT PRIMARY KEY,
+ "campus_name" TEXT,
+ "dept_code" TEXT,
+ FOREIGN KEY ("campus_name", "dept_code") REFERENCES "departments"("campus_name", "dept_code")
+ )
+
+As with single columns, you can leave off the tuple of other columns to reference the compound primary key of the other table:
+
+.. code-block:: python
+
+ foreign_keys=[
+ (("campus_name", "dept_code"), "departments")
+ ]
+
+To specify ``ON DELETE`` or ``ON UPDATE`` actions, pass ``ForeignKey`` objects instead:
+
+.. code-block:: python
+
+ from sqlite_utils.db import ForeignKey
+
+ db.table("books").create({
+ "id": int,
+ "author_id": int,
+ }, pk="id", foreign_keys=[
+ ForeignKey(
+ table="books", column="author_id",
+ other_table="authors", other_column="id",
+ on_delete="CASCADE",
+ )
+ ])
+
+Foreign key actions are preserved by :ref:`table.transform() ` - prior to sqlite-utils 4.0 they were silently dropped when a table was transformed.
+
.. _python_api_table_configuration:
Table configuration options
-===========================
+---------------------------
The ``.insert()``, ``.upsert()``, ``.insert_all()`` and ``.upsert_all()`` methods each take a number of keyword arguments, some of which influence what happens should they cause a table to be created and some of which affect the behavior of those methods.
-You can set default values for these methods by accessing the table through the ``db.table(...)`` method (instead of using ``db["table_name"]``), like so:
+You can set default values for these methods by accessing the table through the ``db.table(...)`` method (instead of using ``db.table("table_name")``), like so:
.. code-block:: python
@@ -653,12 +966,12 @@ You can set default values for these methods by accessing the table through the
# Now you can call .insert() like so:
table.insert({"id": 1, "name": "Tracy", "score": 5})
-The configuration options that can be specified in this way are ``pk``, ``foreign_keys``, ``column_order``, ``not_null``, ``defaults``, ``batch_size``, ``hash_id``, ``hash_id_columns``, ``alter``, ``ignore``, ``replace``, ``extracts``, ``conversions``, ``columns``. These are all documented below.
+The configuration options that can be specified in this way are ``pk``, ``foreign_keys``, ``column_order``, ``not_null``, ``defaults``, ``batch_size``, ``hash_id``, ``hash_id_columns``, ``alter``, ``ignore``, ``replace``, ``extracts``, ``conversions``, ``columns``, ``strict``. These are all documented below.
.. _python_api_defaults_not_null:
Setting defaults and not null constraints
-=========================================
+-----------------------------------------
Each of the methods that can cause a table to be created take optional arguments ``not_null=set()`` and ``defaults=dict()``. The methods that take these optional arguments are:
@@ -677,26 +990,50 @@ Here's an example that uses these features:
.. code-block:: python
- db["authors"].insert_all(
+ db.table("authors").insert_all(
[{"id": 1, "name": "Sally", "score": 2}],
pk="id",
not_null={"name", "score"},
defaults={"score": 1},
)
- db["authors"].insert({"name": "Dharma"})
+ db.table("authors").insert({"name": "Dharma"})
- list(db["authors"].rows)
+ list(db.table("authors").rows)
# Outputs:
# [{'id': 1, 'name': 'Sally', 'score': 2},
# {'id': 3, 'name': 'Dharma', 'score': 1}]
- print(db["authors"].schema)
+ print(db.table("authors").schema)
# Outputs:
- # CREATE TABLE [authors] (
- # [id] INTEGER PRIMARY KEY,
- # [name] TEXT NOT NULL,
- # [score] INTEGER NOT NULL DEFAULT 1
+ # CREATE TABLE "authors" (
+ # "id" INTEGER PRIMARY KEY,
+ # "name" TEXT NOT NULL,
+ # "score" INTEGER NOT NULL DEFAULT 1
# )
+
+.. note::
+ In the CLI: :ref:`sqlite-utils insert --not-null and --default `
+
+.. _python_api_rename_table:
+
+Renaming a table
+================
+
+The ``db.rename_table(old_name, new_name)`` method can be used to rename a table:
+
+.. code-block:: python
+
+ db.rename_table("my_table", "new_name_for_my_table")
+
+This executes the following SQL:
+
+.. code-block:: sql
+
+ ALTER TABLE [my_table] RENAME TO [new_name_for_my_table]
+
+.. note::
+ In the CLI: :ref:`sqlite-utils rename-table `
+
.. _python_api_duplicate:
Duplicating tables
@@ -706,12 +1043,15 @@ The ``table.duplicate()`` method creates a copy of the table, copying both the t
.. code-block:: python
- db["authors"].duplicate("authors_copy")
+ db.table("authors").duplicate("authors_copy")
The new ``authors_copy`` table will now contain a duplicate copy of the data from ``authors``.
This method raises ``sqlite_utils.db.NoTable`` if the table does not exist.
+.. note::
+ In the CLI: :ref:`sqlite-utils duplicate `
+
.. _python_api_bulk_inserts:
Bulk inserts
@@ -723,7 +1063,7 @@ Use it like this:
.. code-block:: python
- db["dogs"].insert_all([{
+ db.table("dogs").insert_all([{
"id": 1,
"name": "Cleo",
"twitter": "cleopaws",
@@ -743,7 +1083,7 @@ The function can accept an iterator or generator of rows and will commit them ac
.. code-block:: python
- db["big_table"].insert_all(({
+ db.table("big_table").insert_all(({
"id": 1,
"name": "Name {}".format(i),
} for i in range(10000)), batch_size=1000)
@@ -754,6 +1094,38 @@ You can delete all the existing rows in the table before inserting the new recor
Pass ``analyze=True`` to run ``ANALYZE`` against the table after inserting the new records.
+.. note::
+ In the CLI: :ref:`sqlite-utils insert `
+
+.. _python_api_insert_lists:
+
+Inserting data from a list or tuple iterator
+--------------------------------------------
+
+As an alternative to passing an iterator of dictionaries, you can pass an iterator of lists or tuples. The first item yielded by the iterator must be a list or tuple of string column names, and subsequent items should be lists or tuples of values:
+
+.. code-block:: python
+
+ db["creatures"].insert_all([
+ ["name", "species"],
+ ["Cleo", "dog"],
+ ["Lila", "chicken"],
+ ["Bants", "chicken"],
+ ])
+
+This also works with generators:
+
+.. code-block:: python
+
+ def creatures():
+ yield "id", "name", "city"
+ yield 1, "Cleo", "San Francisco"
+ yield 2, "Lila", "Los Angeles"
+
+ db["creatures"].insert_all(creatures())
+
+Tuples and lists are both supported.
+
.. _python_api_insert_replace:
Insert-replacing data
@@ -768,7 +1140,7 @@ This example that catches that exception:
from sqlite_utils.utils import sqlite3
try:
- db["dogs"].insert({"id": 1, "name": "Cleo"}, pk="id")
+ db.table("dogs").insert({"id": 1, "name": "Cleo"}, pk="id")
except sqlite3.IntegrityError:
print("Record already exists with that primary key")
@@ -779,13 +1151,13 @@ Use the ``ignore=True`` parameter to ignore this error:
.. code-block:: python
# This fails silently if a record with id=1 already exists
- db["dogs"].insert({"id": 1, "name": "Cleo"}, pk="id", ignore=True)
+ db.table("dogs").insert({"id": 1, "name": "Cleo"}, pk="id", ignore=True)
To replace any existing records that have a matching primary key, use the ``replace=True`` parameter to ``.insert()`` or ``.insert_all()``:
.. code-block:: python
- db["dogs"].insert_all([{
+ db.table("dogs").insert_all([{
"id": 1,
"name": "Cleo",
"twitter": "cleopaws",
@@ -802,6 +1174,9 @@ To replace any existing records that have a matching primary key, use the ``repl
.. note::
Prior to sqlite-utils 2.0 the ``.upsert()`` and ``.upsert_all()`` methods worked the same way as ``.insert(replace=True)`` does today. See :ref:`python_api_upsert` for the new behaviour of those methods introduced in 2.0.
+.. note::
+ In the CLI: :ref:`sqlite-utils insert --replace `
+
.. _python_api_update:
Updating a specific record
@@ -810,21 +1185,21 @@ Updating a specific record
You can update a record by its primary key using ``table.update()``::
>>> db = sqlite_utils.Database("dogs.db")
- >>> print(db["dogs"].get(1))
+ >>> print(db.table("dogs").get(1))
{'id': 1, 'age': 4, 'name': 'Cleo'}
- >>> db["dogs"].update(1, {"age": 5})
- >>> print(db["dogs"].get(1))
+ >>> db.table("dogs").update(1, {"age": 5})
+ >>> print(db.table("dogs").get(1))
{'id': 1, 'age': 5, 'name': 'Cleo'}
The first argument to ``update()`` is the primary key. This can be a single value, or a tuple if that table has a compound primary key::
- >>> db["compound_dogs"].update((5, 3), {"name": "Updated"})
+ >>> db.table("compound_dogs").update((5, 3), {"name": "Updated"})
The second argument is a dictionary of columns that should be updated, along with their new values.
You can cause any missing columns to be added automatically using ``alter=True``::
- >>> db["dogs"].update(1, {"breed": "Mutt"}, alter=True)
+ >>> db.table("dogs").update(1, {"breed": "Mutt"}, alter=True)
.. _python_api_delete:
@@ -834,11 +1209,11 @@ Deleting a specific record
You can delete a record using ``table.delete()``::
>>> db = sqlite_utils.Database("dogs.db")
- >>> db["dogs"].delete(1)
+ >>> db.table("dogs").delete(1)
The ``delete()`` method takes the primary key of the record. This can be a tuple of values if the row has a compound primary key::
- >>> db["compound_dogs"].delete((5, 3))
+ >>> db.table("compound_dogs").delete((5, 3))
.. _python_api_delete_where:
@@ -849,7 +1224,7 @@ You can delete all records in a table that match a specific WHERE statement usin
>>> db = sqlite_utils.Database("dogs.db")
>>> # Delete every dog with age less than 3
- >>> db["dogs"].delete_where("age < ?", [3])
+ >>> db.table("dogs").delete_where("age < ?", [3])
Calling ``table.delete_where()`` with no other arguments will delete every row in the table.
@@ -866,7 +1241,7 @@ For example, given the dogs database you could upsert the record for Cleo like s
.. code-block:: python
- db["dogs"].upsert({
+ db.table("dogs").upsert({
"id": 1,
"name": "Cleo",
"twitter": "cleopaws",
@@ -882,9 +1257,21 @@ Note that the ``pk`` and ``column_order`` parameters here are optional if you ar
An ``upsert_all()`` method is also available, which behaves like ``insert_all()`` but performs upserts instead.
+Every record passed to ``upsert()`` or ``upsert_all()`` must include a value for each primary key column - a record without one could never match an existing row, so a ``sqlite_utils.db.PrimaryKeyRequired`` exception is raised instead of quietly inserting a new row.
+
.. note::
``.upsert()`` and ``.upsert_all()`` in sqlite-utils 1.x worked like ``.insert(..., replace=True)`` and ``.insert_all(..., replace=True)`` do in 2.x. See `issue #66 `__ for details of this change.
+.. note::
+ In the CLI: :ref:`sqlite-utils upsert `
+
+.. _python_api_old_upsert:
+
+Alternative upserts using INSERT OR IGNORE
+------------------------------------------
+
+Upserts use ``INSERT INTO ... ON CONFLICT SET``. Prior to ``sqlite-utils 4.0`` these used a sequence of ``INSERT OR IGNORE`` followed by an ``UPDATE``. This older method is still used for SQLite 3.23.1 and earlier. You can force the older implementation by passing ``use_old_upsert=True`` to the ``Database()`` constructor.
+
.. _python_api_convert:
Converting data in columns
@@ -898,19 +1285,19 @@ To transform a specific column to uppercase, you would use the following:
.. code-block:: python
- db["dogs"].convert("name", lambda value: value.upper())
+ db.table("dogs").convert("name", lambda value: value.upper())
You can pass a list of columns, in which case the transformation will be applied to each one:
.. code-block:: python
- db["dogs"].convert(["name", "twitter"], lambda value: value.upper())
+ db.table("dogs").convert(["name", "twitter"], lambda value: value.upper())
To save the output to of the transformation to a different column, use the ``output=`` parameter:
.. code-block:: python
- db["dogs"].convert("name", lambda value: value.upper(), output="name_upper")
+ db.table("dogs").convert("name", lambda value: value.upper(), output="name_upper")
This will add the new column, if it does not already exist. You can pass ``output_type=int`` or some other type to control the type of the new column - otherwise it will default to text.
@@ -944,7 +1331,7 @@ A useful pattern when populating large tables in to break common values out into
Creating lookup tables explicitly
---------------------------------
-Calling ``db["Species"].lookup({"name": "Palm"})`` creates a table called ``Species`` (if one does not already exist) with two columns: ``id`` and ``name``. It sets up a unique constraint on the ``name`` column to guarantee it will not contain duplicate rows. It then inserts a new row with the ``name`` set to ``Palm`` and returns the new integer primary key value.
+Calling ``db.table("Species").lookup({"name": "Palm"})`` creates a table called ``Species`` (if one does not already exist) with two columns: ``id`` and ``name``. It sets up a unique constraint on the ``name`` column to guarantee it will not contain duplicate rows. It then inserts a new row with the ``name`` set to ``Palm`` and returns the new integer primary key value.
If the ``Species`` table already exists, it will insert the new row and return the primary key. If a row with that ``name`` already exists, it will return the corresponding primary key value directly.
@@ -954,10 +1341,10 @@ If you pass in a dictionary with multiple values, both values will be used to in
.. code-block:: python
- db["Trees"].insert({
+ db.table("Trees").insert({
"latitude": 49.1265976,
"longitude": 2.5496218,
- "species": db["Species"].lookup({
+ "species": db.table("Species").lookup({
"common_name": "Common Juniper",
"latin_name": "Juniperus communis"
})
@@ -969,10 +1356,12 @@ To create a species record with a note on when it was first seen, you can use th
.. code-block:: python
- db["Species"].lookup({"name": "Palm"}, {"first_seen": "2021-03-04"})
+ db.table("Species").lookup({"name": "Palm"}, {"first_seen": "2021-03-04"})
The first time this is called the record will be created for ``name="Palm"``. Any subsequent calls with that name will ignore the second argument, even if it includes different values.
+``None`` values are matched correctly: calling ``.lookup()`` a second time with the same values will return the primary key of the existing row even if some of those values are ``None``.
+
``.lookup()`` also accepts keyword arguments, which are passed through to the :ref:`insert() method ` and can be used to influence the shape of the created table. Supported parameters are:
- ``pk`` - which defaults to ``id``
@@ -983,6 +1372,7 @@ The first time this is called the record will be created for ``name="Palm"``. An
- ``extracts``
- ``conversions``
- ``columns``
+- ``strict``
.. _python_api_extracts:
@@ -1011,12 +1401,14 @@ To extract the ``species`` column out to a separate ``Species`` table, you can d
trees = db.table("Trees", extracts=["species"])
# Using .insert() directly
- db["Trees"].insert({
+ db.table("Trees").insert({
"latitude": 49.1265976,
"longitude": 2.5496218,
"species": "Common Juniper"
}, extracts={"species": "Species"})
+``None`` values are not extracted: no record is created for them in the lookup table and the column value stays ``null``.
+
.. _python_api_m2m:
Working with many-to-many relationships
@@ -1028,7 +1420,7 @@ Here's how to create two new records and connect them via a many-to-many table i
.. code-block:: python
- db["dogs"].insert({"id": 1, "name": "Cleo"}, pk="id").m2m(
+ db.table("dogs").insert({"id": 1, "name": "Cleo"}, pk="id").m2m(
"humans", {"id": 1, "name": "Natalie"}, pk="id"
)
@@ -1038,7 +1430,7 @@ The ``.m2m()`` method executes against the last record that was affected by ``.i
.. code-block:: python
- db["dogs"].update(1).m2m(
+ db.table("dogs").update(1).m2m(
"humans", {"id": 2, "name": "Simon"}, pk="id"
)
@@ -1095,17 +1487,17 @@ You can inspect the database to see the results like this::
>>> db.table_names()
['dogs', 'characteristics', 'characteristics_dogs']
- >>> list(db["dogs"].rows)
+ >>> list(db.table("dogs").rows)
[{'id': 1, 'name': 'Cleo'}]
- >>> list(db["characteristics"].rows)
+ >>> list(db.table("characteristics").rows)
[{'id': 1, 'name': 'Playful'}, {'id': 2, 'name': 'Opinionated'}]
- >>> list(db["characteristics_dogs"].rows)
+ >>> list(db.table("characteristics_dogs").rows)
[{'characteristics_id': 1, 'dogs_id': 1}, {'characteristics_id': 2, 'dogs_id': 1}]
- >>> print(db["characteristics_dogs"].schema)
- CREATE TABLE [characteristics_dogs] (
- [characteristics_id] INTEGER REFERENCES [characteristics]([id]),
- [dogs_id] INTEGER REFERENCES [dogs]([id]),
- PRIMARY KEY ([characteristics_id], [dogs_id])
+ >>> print(db.table("characteristics_dogs").schema)
+ CREATE TABLE "characteristics_dogs" (
+ "characteristics_id" INTEGER REFERENCES "characteristics"("id"),
+ "dogs_id" INTEGER REFERENCES "dogs"("id"),
+ PRIMARY KEY ("characteristics_id", "dogs_id")
)
.. _python_api_analyze_column:
@@ -1113,7 +1505,26 @@ You can inspect the database to see the results like this::
Analyzing a column
==================
-The ``table.analyze_column(column, common_limit=10, value_truncate=None)`` method is used by the :ref:`analyze-tables ` CLI command. It returns a ``ColumnDetails`` named tuple with the following fields:
+The ``table.analyze_column(column)`` method is used by the :ref:`analyze-tables ` CLI command.
+
+It takes the following arguments and options:
+
+``column`` - required
+ The name of the column to analyze
+
+``common_limit``
+ The number of most common values to return. Defaults to 10.
+
+``value_truncate``
+ If set to an integer, values longer than this will be truncated to this length. Defaults to None.
+
+``most_common``
+ If set to False, the ``most_common`` field of the returned ``ColumnDetails`` will be set to None. Defaults to True.
+
+``least_common``
+ If set to False, the ``least_common`` field of the returned ``ColumnDetails`` will be set to None. Defaults to True.
+
+And returns a ``ColumnDetails`` named tuple with the following fields:
``table``
The name of the table
@@ -1139,10 +1550,6 @@ The ``table.analyze_column(column, common_limit=10, value_truncate=None)`` metho
``least_common``
The ``N`` least common values as a list of ``(value, count)`` tuples`, or ``None`` if the table is entirely distinct or if the number of distinct values is less than N (since they will already have been returned in ``most_common``)
-``N`` defaults to 10, or you can pass a custom ``N`` using the ``common_limit`` parameter.
-
-You can use the ``value_truncate`` parameter to truncate values in the ``most_common`` and ``least_common`` lists to a specified number of characters.
-
.. _python_api_add_column:
Adding columns
@@ -1152,21 +1559,21 @@ You can add a new column to a table using the ``.add_column(col_name, col_type)`
.. code-block:: python
- db["dogs"].add_column("instagram", str)
- db["dogs"].add_column("weight", float)
- db["dogs"].add_column("dob", datetime.date)
- db["dogs"].add_column("image", "BLOB")
- db["dogs"].add_column("website") # str by default
+ db.table("dogs").add_column("instagram", str)
+ db.table("dogs").add_column("weight", float)
+ db.table("dogs").add_column("dob", datetime.date)
+ db.table("dogs").add_column("image", "BLOB")
+ db.table("dogs").add_column("website") # str by default
You can specify the ``col_type`` argument either using a SQLite type as a string, or by directly passing a Python type e.g. ``str`` or ``float``.
The ``col_type`` is optional - if you omit it the type of ``TEXT`` will be used.
-SQLite types you can specify are ``"TEXT"``, ``"INTEGER"``, ``"FLOAT"`` or ``"BLOB"``.
+SQLite types you can specify are ``"TEXT"``, ``"INTEGER"``, ``"FLOAT"``, ``"REAL"`` or ``"BLOB"``.
If you pass a Python type, it will be mapped to SQLite types as shown here::
- float: "FLOAT"
+ float: "REAL"
int: "INTEGER"
bool: "INTEGER"
str: "TEXT"
@@ -1174,6 +1581,7 @@ If you pass a Python type, it will be mapped to SQLite types as shown here::
datetime.datetime: "TEXT"
datetime.date: "TEXT"
datetime.time: "TEXT"
+ datetime.timedelta: "TEXT"
# If numpy is installed
np.int8: "INTEGER"
@@ -1184,15 +1592,15 @@ If you pass a Python type, it will be mapped to SQLite types as shown here::
np.uint16: "INTEGER"
np.uint32: "INTEGER"
np.uint64: "INTEGER"
- np.float16: "FLOAT"
- np.float32: "FLOAT"
- np.float64: "FLOAT"
+ np.float16: "REAL"
+ np.float32: "REAL"
+ np.float64: "REAL"
You can also add a column that is a foreign key reference to another table using the ``fk`` parameter:
.. code-block:: python
- db["dogs"].add_column("species_id", fk="species")
+ db.table("dogs").add_column("species_id", fk="species")
This will automatically detect the name of the primary key on the species table and use that (and its type) for the new column.
@@ -1200,13 +1608,16 @@ You can explicitly specify the column you wish to reference using ``fk_col``:
.. code-block:: python
- db["dogs"].add_column("species_id", fk="species", fk_col="ref")
+ db.table("dogs").add_column("species_id", fk="species", fk_col="ref")
You can set a ``NOT NULL DEFAULT 'x'`` constraint on the new column using ``not_null_default``:
.. code-block:: python
- db["dogs"].add_column("friends_count", int, not_null_default=0)
+ db.table("dogs").add_column("friends_count", int, not_null_default=0)
+
+.. note::
+ In the CLI: :ref:`sqlite-utils add-column `
.. _python_api_add_column_alter:
@@ -1217,13 +1628,13 @@ You can insert or update data that includes new columns and have the table autom
.. code-block:: python
- db["new_table"].insert({"name": "Gareth"})
+ db.table("new_table").insert({"name": "Gareth"})
# This will throw an exception:
- db["new_table"].insert({"name": "Gareth", "age": 32})
+ db.table("new_table").insert({"name": "Gareth", "age": 32})
# This will succeed and add a new "age" integer column:
- db["new_table"].insert({"name": "Gareth", "age": 32}, alter=True)
+ db.table("new_table").insert({"name": "Gareth", "age": 32}, alter=True)
# You can see confirm the new column like so:
- print(db["new_table"].columns_dict)
+ print(db.table("new_table").columns_dict)
# Outputs this:
# {'name': , 'age': }
@@ -1231,6 +1642,9 @@ You can insert or update data that includes new columns and have the table autom
new_table = db.table("new_table", alter=True)
new_table.insert({"name": "Gareth", "age": 32, "shoe_size": 11})
+.. note::
+ In the CLI: :ref:`sqlite-utils insert --alter `
+
.. _python_api_add_foreign_key:
Adding foreign key constraints
@@ -1238,23 +1652,23 @@ Adding foreign key constraints
The SQLite ``ALTER TABLE`` statement doesn't have the ability to add foreign key references to an existing column.
-It's possible to add these references through very careful manipulation of SQLite's ``sqlite_master`` table, using ``PRAGMA writable_schema``.
+The ``add_foreign_key()`` method here is a convenient wrapper around :ref:`table.transform() `.
-``sqlite-utils`` can do this for you, though there is a significant risk of data corruption if something goes wrong so it is advisable to create a fresh copy of your database file before attempting this.
+It's also possible to add foreign keys by directly updating the `sqlite_master` table. The `sqlite-utils-fast-fks `__ plugin implements this pattern, using code that was included with ``sqlite-utils`` prior to version 3.35.
Here's an example of this mechanism in action:
.. code-block:: python
- db["authors"].insert_all([
+ db.table("authors").insert_all([
{"id": 1, "name": "Sally"},
{"id": 2, "name": "Asheesh"}
], pk="id")
- db["books"].insert_all([
+ db.table("books").insert_all([
{"title": "Hedgehogs of the world", "author_id": 1},
{"title": "How to train your wolf", "author_id": 2},
])
- db["books"].add_foreign_key("author_id", "authors", "id")
+ db.table("books").add_foreign_key("author_id", "authors", "id")
The ``table.add_foreign_key(column, other_table, other_column)`` method takes the name of the column, the table that is being referenced and the key column within that other table. If you omit the ``other_column`` argument the primary key from that table will be used automatically. If you omit the ``other_table`` argument the table will be guessed based on some simple rules:
@@ -1267,18 +1681,37 @@ To ignore the case where the key already exists, use ``ignore=True``:
.. code-block:: python
- db["books"].add_foreign_key("author_id", "authors", "id", ignore=True)
+ db.table("books").add_foreign_key("author_id", "authors", "id", ignore=True)
+
+To add a compound foreign key, pass tuples of columns:
+
+.. code-block:: python
+
+ db.table("courses").add_foreign_key(
+ ("campus_name", "dept_code"), "departments", ("campus_name", "dept_code")
+ )
+
+As with single columns, omitting the other columns will use the compound primary key of the other table. ``other_table`` must always be specified for a compound foreign key.
+
+Use ``on_delete=`` and ``on_update=`` to specify ``ON DELETE`` and ``ON UPDATE`` actions for the foreign key:
+
+.. code-block:: python
+
+ db.table("books").add_foreign_key(
+ "author_id", "authors", "id", on_delete="CASCADE"
+ )
+
+This creates a foreign key with an ``ON DELETE CASCADE`` clause, so deleting an author will also delete their books (provided foreign key enforcement is enabled with ``PRAGMA foreign_keys = ON``). Valid actions are ``"SET NULL"``, ``"SET DEFAULT"``, ``"CASCADE"``, ``"RESTRICT"`` and the default ``"NO ACTION"``.
+
+.. note::
+ In the CLI: :ref:`sqlite-utils add-foreign-key `
.. _python_api_add_foreign_keys:
Adding multiple foreign key constraints at once
-----------------------------------------------
-The final step in adding a new foreign key to a SQLite database is to run ``VACUUM``, to ensure the new foreign key is available in future introspection queries.
-
-``VACUUM`` against a large (multi-GB) database can take several minutes or longer. If you are adding multiple foreign keys using ``table.add_foreign_key(...)`` these can quickly add up.
-
-Instead, you can use ``db.add_foreign_keys(...)`` to add multiple foreign keys within a single transaction. This method takes a list of four-tuples, each one specifying a ``table``, ``column``, ``other_table`` and ``other_column``.
+You can use ``db.add_foreign_keys(...)`` to add multiple foreign keys in one go. This method takes a list of four-tuples, each one specifying a ``table``, ``column``, ``other_table`` and ``other_column``.
Here's an example adding two foreign keys at once:
@@ -1291,6 +1724,11 @@ Here's an example adding two foreign keys at once:
This method runs the same checks as ``.add_foreign_keys()`` and will raise ``sqlite_utils.db.AlterError`` if those checks fail.
+Foreign keys that already exist are silently skipped, so repeated calls are idempotent - but only if they match exactly. Requesting a foreign key that exists with different ``ON DELETE``/``ON UPDATE`` actions raises ``AlterError``: use ``table.transform()`` to change the actions of an existing foreign key.
+
+.. note::
+ In the CLI: :ref:`sqlite-utils add-foreign-keys `
+
.. _python_api_index_foreign_keys:
Adding indexes for all foreign keys
@@ -1302,6 +1740,11 @@ If you want to ensure that every foreign key column in your database has a corre
db.index_foreign_keys()
+Compound foreign keys get a single composite index across their columns.
+
+.. note::
+ In the CLI: :ref:`sqlite-utils index-foreign-keys `
+
.. _python_api_drop:
Dropping a table or view
@@ -1311,13 +1754,20 @@ You can drop a table or view using the ``.drop()`` method:
.. code-block:: python
- db["my_table"].drop()
+ db.table("my_table").drop()
+ # Or for a view:
+ db.view("my_view").drop()
+ # Or for either:
+ db["table_or_view_name"].drop()
Pass ``ignore=True`` if you want to ignore the error caused by the table or view not existing.
.. code-block:: python
- db["my_table"].drop(ignore=True)
+ db.table("my_table").drop(ignore=True)
+
+.. note::
+ In the CLI: :ref:`sqlite-utils drop-table ` and :ref:`sqlite-utils drop-view `
.. _python_api_transform:
@@ -1337,6 +1787,21 @@ The ``table.transform()`` method can do all of these things, by implementing a m
The ``.transform()`` method takes a number of parameters, all of which are optional.
+As a bonus, calling ``.transform()`` will reformat the schema for the table that is stored in SQLite to make it more readable. This works even if you call it without any arguments.
+
+To keep the original table around instead of dropping it, pass the ``keep_table=`` option and specify the name of the table you would like it to be renamed to:
+
+.. code-block:: python
+
+ table.transform(types={"age": int}, keep_table="original_table")
+
+This method raises a ``sqlite_utils.db.TransformError`` exception if the table cannot be transformed, usually because there are existing constraints or indexes that are incompatible with modifications to the columns.
+
+.. note::
+ In the CLI: :ref:`sqlite-utils transform `
+
+.. _python_api_transform_alter_column_types:
+
Altering column types
---------------------
@@ -1349,6 +1814,31 @@ To alter the type of a column, use the ``types=`` argument:
See :ref:`python_api_add_column` for a list of available types.
+.. _python_api_transform_strict:
+
+Changing strict mode
+--------------------
+
+The optional ``strict=`` parameter can change whether a table uses `SQLite STRICT mode `__. Pass ``strict=True`` to convert a regular table to a strict table:
+
+.. code-block:: python
+
+ table.transform(strict=True)
+
+Pass ``strict=False`` to convert a strict table back to a regular non-strict table:
+
+.. code-block:: python
+
+ table.transform(strict=False)
+
+The default is ``strict=None``, which preserves the table's existing strict mode.
+
+Passing ``strict=True`` raises ``sqlite_utils.db.TransformError`` if the available SQLite version does not support strict tables.
+
+Converting to a strict table validates all existing rows as they are copied into the replacement table. If a value is incompatible with its declared column type, SQLite raises ``sqlite3.IntegrityError`` and the transformation is rolled back, leaving the original table and its data unchanged.
+
+.. _python_api_transform_rename_columns:
+
Renaming columns
----------------
@@ -1359,6 +1849,8 @@ The ``rename=`` parameter can rename columns:
# Rename 'age' to 'initial_age':
table.transform(rename={"age": "initial_age"})
+.. _python_api_transform_drop_columns:
+
Dropping columns
----------------
@@ -1369,6 +1861,8 @@ To drop columns, pass them in the ``drop=`` set:
# Drop the 'age' column:
table.transform(drop={"age"})
+.. _python_api_transform_change_primary_keys:
+
Changing primary keys
---------------------
@@ -1379,6 +1873,8 @@ To change the primary key for a table, use ``pk=``. This can be passed a single
# Make `user_id` the new primary key
table.transform(pk="user_id")
+.. _python_api_transform_change_not_null:
+
Changing not null status
------------------------
@@ -1399,6 +1895,8 @@ If you want to take existing ``NOT NULL`` columns and change them to allow null
# Make age allow NULL and switch weight to being NOT NULL:
table.transform(not_null={"age": False, "weight": True})
+.. _python_api_transform_alter_column_defaults:
+
Altering column defaults
------------------------
@@ -1412,6 +1910,8 @@ The ``defaults=`` parameter can be used to set or change the defaults for differ
# Now remove the default from that column:
table.transform(defaults={"age": None})
+.. _python_api_transform_change_column_order:
+
Changing column order
---------------------
@@ -1422,6 +1922,47 @@ The ``column_order=`` parameter can be used to change the order of the columns.
# Change column order
table.transform(column_order=("name", "age", "id")
+.. _python_api_transform_add_foreign_key_constraints:
+
+Adding foreign key constraints
+------------------------------
+
+You can add one or more foreign key constraints to a table using the ``add_foreign_keys=`` parameter:
+
+.. code-block:: python
+
+ db.table("places").transform(
+ add_foreign_keys=(
+ ("country", "country", "id"),
+ ("continent", "continent", "id")
+ )
+ )
+
+This accepts the same arguments described in :ref:`specifying foreign keys ` - so you can specify them as a full tuple of ``(column, other_table, other_column)``, or you can take a shortcut and pass just the name of the column, provided the table can be automatically derived from the column name:
+
+.. code-block:: python
+
+ db.table("places").transform(
+ add_foreign_keys=(("country", "continent"))
+ )
+
+.. _python_api_transform_replace_foreign_key_constraints:
+
+Replacing foreign key constraints
+---------------------------------
+
+The ``foreign_keys=`` parameter is similar to to ``add_foreign_keys=`` but can be be used to replace all foreign key constraints on a table, dropping any that are not explicitly mentioned:
+
+.. code-block:: python
+
+ db.table("places").transform(
+ foreign_keys=(
+ ("continent", "continent", "id"),
+ )
+ )
+
+.. _python_api_transform_drop_foreign_key_constraints:
+
Dropping foreign key constraints
--------------------------------
@@ -1431,10 +1972,20 @@ This example drops two foreign keys - the one from ``places.country`` to ``count
.. code-block:: python
- db["places"].transform(
+ db.table("places").transform(
drop_foreign_keys=("country", "continent")
)
+A bare column name drops any foreign key that column participates in, including compound foreign keys. To target a compound foreign key precisely, pass a tuple of its columns:
+
+.. code-block:: python
+
+ db.table("courses").transform(
+ drop_foreign_keys=[("campus_name", "dept_code")]
+ )
+
+Renaming a column with ``rename=`` updates any foreign keys that use it, and dropping a column with ``drop=`` also drops any foreign keys it participates in - for a compound foreign key this removes the whole constraint.
+
.. _python_api_transform_sql:
Custom transformations with .transform_sql()
@@ -1446,6 +1997,36 @@ If you want to do something more advanced, you can call the ``table.transform_sq
This method will return a list of SQL statements that should be executed to implement the change. You can then make modifications to that SQL - or add additional SQL statements - before executing it yourself.
+.. _python_api_transform_foreign_keys_transactions:
+
+Foreign keys and transactions
+-----------------------------
+
+Because ``.transform()`` drops the old table, running it with ``PRAGMA foreign_keys`` enabled could fire ``ON DELETE`` actions on any tables that reference it - an inbound ``ON DELETE CASCADE`` foreign key would silently delete those referencing rows. To prevent this, ``.transform()`` turns ``PRAGMA foreign_keys`` off for the duration of the operation and restores it afterwards, running ``PRAGMA foreign_key_check`` before committing.
+
+``PRAGMA foreign_keys`` cannot be changed inside a transaction, so this protection is impossible if you call ``.transform()`` while a transaction is already open - for example inside a ``with db.atomic():`` block or after ``db.begin()``. If ``PRAGMA foreign_keys`` is on and another table references the table being transformed with a destructive ``ON DELETE`` action - ``CASCADE``, ``SET NULL`` or ``SET DEFAULT`` - the method will refuse to run and raise a ``sqlite_utils.db.TransactionError``:
+
+.. code-block:: python
+
+ from sqlite_utils.db import TransactionError
+
+ try:
+ with db.atomic():
+ db["authors"].transform(types={"id": str})
+ except TransactionError as ex:
+ print("Could not transform in transaction:", ex)
+
+To transform such a table either call ``.transform()`` outside of the transaction, or execute ``PRAGMA foreign_keys = off`` before opening it:
+
+.. code-block:: python
+
+ db.execute("PRAGMA foreign_keys = off")
+ with db.atomic():
+ db["authors"].transform(types={"id": str})
+ db.execute("PRAGMA foreign_keys = on")
+
+Tables referenced by foreign keys without a destructive action (the default ``NO ACTION``, or ``RESTRICT``) can still be transformed inside a transaction - sqlite-utils uses ``PRAGMA defer_foreign_keys`` to postpone the foreign key checks until the transaction commits.
+
.. _python_api_extract:
Extracting columns into a separate table
@@ -1470,26 +2051,26 @@ The schema of the above table is:
.. code-block:: sql
- CREATE TABLE [Trees] (
- [id] INTEGER PRIMARY KEY,
- [TreeAddress] TEXT,
- [Species] TEXT
+ CREATE TABLE "Trees" (
+ "id" INTEGER PRIMARY KEY,
+ "TreeAddress" TEXT,
+ "Species" TEXT
)
Here's how to extract the ``Species`` column using ``.extract()``:
.. code-block:: python
- db["Trees"].extract("Species")
+ db.table("Trees").extract("Species")
After running this code the table schema now looks like this:
.. code-block:: sql
CREATE TABLE "Trees" (
- [id] INTEGER PRIMARY KEY,
- [TreeAddress] TEXT,
- [Species_id] INTEGER,
+ "id" INTEGER PRIMARY KEY,
+ "TreeAddress" TEXT,
+ "Species_id" INTEGER,
FOREIGN KEY(Species_id) REFERENCES Species(id)
)
@@ -1497,9 +2078,9 @@ A new ``Species`` table will have been created with the following schema:
.. code-block:: sql
- CREATE TABLE [Species] (
- [id] INTEGER PRIMARY KEY,
- [Species] TEXT
+ CREATE TABLE "Species" (
+ "id" INTEGER PRIMARY KEY,
+ "Species" TEXT
)
The ``.extract()`` method defaults to creating a table with the same name as the column that was extracted, and adding a foreign key column called ``tablename_id``.
@@ -1508,22 +2089,22 @@ You can specify a custom table name using ``table=``, and a custom foreign key n
.. code-block:: python
- db["Trees"].extract("Species", table="tree_species", fk_column="tree_species_id")
+ db.table("Trees").extract("Species", table="tree_species", fk_column="tree_species_id")
The resulting schema looks like this:
.. code-block:: sql
CREATE TABLE "Trees" (
- [id] INTEGER PRIMARY KEY,
- [TreeAddress] TEXT,
- [tree_species_id] INTEGER,
+ "id" INTEGER PRIMARY KEY,
+ "TreeAddress" TEXT,
+ "tree_species_id" INTEGER,
FOREIGN KEY(tree_species_id) REFERENCES tree_species(id)
)
- CREATE TABLE [tree_species] (
- [id] INTEGER PRIMARY KEY,
- [Species] TEXT
+ CREATE TABLE "tree_species" (
+ "id" INTEGER PRIMARY KEY,
+ "Species" TEXT
)
You can also extract multiple columns into the same external table. Say for example you have a table like this:
@@ -1541,51 +2122,51 @@ You can pass ``["CommonName", "LatinName"]`` to ``.extract()`` to extract both o
.. code-block:: python
- db["Trees"].extract(["CommonName", "LatinName"])
+ db.table("Trees").extract(["CommonName", "LatinName"])
This produces the following schema:
.. code-block:: sql
CREATE TABLE "Trees" (
- [id] INTEGER PRIMARY KEY,
- [TreeAddress] TEXT,
- [CommonName_LatinName_id] INTEGER,
+ "id" INTEGER PRIMARY KEY,
+ "TreeAddress" TEXT,
+ "CommonName_LatinName_id" INTEGER,
FOREIGN KEY(CommonName_LatinName_id) REFERENCES CommonName_LatinName(id)
)
- CREATE TABLE [CommonName_LatinName] (
- [id] INTEGER PRIMARY KEY,
- [CommonName] TEXT,
- [LatinName] TEXT
+ CREATE TABLE "CommonName_LatinName" (
+ "id" INTEGER PRIMARY KEY,
+ "CommonName" TEXT,
+ "LatinName" TEXT
)
The table name ``CommonName_LatinName`` is derived from the extract columns. You can use ``table=`` and ``fk_column=`` to specify custom names like this:
.. code-block:: python
- db["Trees"].extract(["CommonName", "LatinName"], table="Species", fk_column="species_id")
+ db.table("Trees").extract(["CommonName", "LatinName"], table="Species", fk_column="species_id")
This produces the following schema:
.. code-block:: sql
CREATE TABLE "Trees" (
- [id] INTEGER PRIMARY KEY,
- [TreeAddress] TEXT,
- [species_id] INTEGER,
+ "id" INTEGER PRIMARY KEY,
+ "TreeAddress" TEXT,
+ "species_id" INTEGER,
FOREIGN KEY(species_id) REFERENCES Species(id)
)
- CREATE TABLE [Species] (
- [id] INTEGER PRIMARY KEY,
- [CommonName] TEXT,
- [LatinName] TEXT
+ CREATE TABLE "Species" (
+ "id" INTEGER PRIMARY KEY,
+ "CommonName" TEXT,
+ "LatinName" TEXT
)
You can use the ``rename=`` argument to rename columns in the lookup table. To create a ``Species`` table with columns called ``name`` and ``latin`` you can do this:
.. code-block:: python
- db["Trees"].extract(
+ db.table("Trees").extract(
["CommonName", "LatinName"],
table="Species",
fk_column="species_id",
@@ -1596,12 +2177,17 @@ This produces a lookup table like so:
.. code-block:: sql
- CREATE TABLE [Species] (
- [id] INTEGER PRIMARY KEY,
- [name] TEXT,
- [latin] TEXT
+ CREATE TABLE "Species" (
+ "id" INTEGER PRIMARY KEY,
+ "name" TEXT,
+ "latin" TEXT
)
+Rows where every extracted column is ``null`` are not extracted: no record is created for them in the lookup table and their foreign key column is left as ``null``. When extracting multiple columns, rows where at least one of the extracted columns has a value will be extracted as usual.
+
+.. note::
+ In the CLI: :ref:`sqlite-utils extract `
+
.. _python_api_hash:
Setting an ID based on the hash of the row contents
@@ -1614,7 +2200,7 @@ In these cases, a useful technique is to create an ID that is derived from the s
``sqlite-utils`` can do this for you using the ``hash_id=`` option. For example::
db = sqlite_utils.Database("dogs.db")
- db["dogs"].upsert({"name": "Cleo", "twitter": "cleopaws"}, hash_id="id")
+ db.table("dogs").upsert({"name": "Cleo", "twitter": "cleopaws"}, hash_id="id")
print(list(db["dogs]))
Outputs::
@@ -1623,7 +2209,7 @@ Outputs::
If you are going to use that ID straight away, you can access it using ``last_pk``::
- dog_id = db["dogs"].upsert({
+ dog_id = db.table("dogs").upsert({
"name": "Cleo",
"twitter": "cleopaws"
}, hash_id="id").last_pk
@@ -1631,7 +2217,7 @@ If you are going to use that ID straight away, you can access it using ``last_pk
The hash will be created using all of the column values. To create a hash using a subset of the columns, pass the ``hash_id_columns=`` parameter::
- db["dogs"].upsert(
+ db.table("dogs").upsert(
{"name": "Cleo", "twitter": "cleopaws", "age": 7},
hash_id_columns=("name", "twitter")
)
@@ -1663,6 +2249,9 @@ You can pass ``ignore=True`` to silently ignore an existing view and do nothing,
select * from dogs where is_good_dog = 1
""", replace=True)
+.. note::
+ In the CLI: :ref:`sqlite-utils create-view `
+
Storing JSON
============
@@ -1672,7 +2261,7 @@ For example:
.. code-block:: python
- db["niche_museums"].insert({
+ db.table("niche_museums").insert({
"name": "The Bigfoot Discovery Museum",
"url": "http://bigfootdiscoveryproject.com/"
"hours": {
@@ -1708,11 +2297,11 @@ You can specify an upper case conversion for a specific column like so:
.. code-block:: python
- db["example"].insert({
+ db.table("example").insert({
"name": "The Bigfoot Discovery Museum"
}, conversions={"name": "upper(?)"})
- # list(db["example"].rows) now returns:
+ # list(db.table("example").rows) now returns:
# [{'name': 'THE BIGFOOT DISCOVERY MUSEUM'}]
The dictionary key is the column name to be converted. The value is the SQL fragment to use, with a ``?`` placeholder for the original value.
@@ -1730,7 +2319,7 @@ A more useful example: if you are working with `SpatiaLite `__ and depends on the `Shapely `__ and `HTTPX `__ Python libraries.
.. _python_api_sqlite_version:
@@ -1762,6 +2351,28 @@ The ``db.sqlite_version`` property returns a tuple of integers representing the
>>> db.sqlite_version
(3, 36, 0)
+.. _python_api_itedump:
+
+Dumping the database to SQL
+===========================
+
+The ``db.iterdump()`` method returns a sequence of SQL strings representing a complete dump of the database. Use it like this:
+
+.. code-block:: python
+
+ full_sql = "".join(db.iterdump())
+
+This uses the `sqlite3.Connection.iterdump() `__ method.
+
+If you are using ``pysqlite3`` the underlying method may be missing. If you install the `sqlite-dump `__ package then the ``db.iterdump()`` method will use that implementation instead:
+
+.. code-block:: bash
+
+ pip install sqlite-dump
+
+.. note::
+ In the CLI: :ref:`sqlite-utils dump `
+
.. _python_api_introspection:
Introspecting tables and views
@@ -1769,8 +2380,10 @@ Introspecting tables and views
If you have loaded an existing table or view, you can use introspection to find out more about it::
- >>> db["PlantType"]
+ >>> db.table("PlantType")
+ ### db.view("NameOfView")
+
.. _python_api_introspection_exists:
@@ -1779,9 +2392,11 @@ If you have loaded an existing table or view, you can use introspection to find
The ``.exists()`` method can be used to find out if a table exists or not::
- >>> db["PlantType"].exists()
+ >>> db.table("PlantType").exists()
True
- >>> db["PlantType2"].exists()
+ >>> db.table("PlantType2").exists()
+ False
+ >>> db["table_or_view_name"].exists()
False
.. _python_api_introspection_count:
@@ -1791,9 +2406,9 @@ The ``.exists()`` method can be used to find out if a table exists or not::
The ``.count`` property shows the current number of rows (``select count(*) from table``)::
- >>> db["PlantType"].count
+ >>> db.table("PlantType").count
3
- >>> db["Street_Tree_List"].count
+ >>> db.table("Street_Tree_List").count
189144
This property will take advantage of :ref:`python_api_cached_table_counts` if the ``use_counts_table`` property is set on the database. You can avoid that optimization entirely by calling ``table.count_where()`` instead of accessing the property.
@@ -1807,7 +2422,7 @@ The ``.columns`` property shows the columns in the table or view. It returns a l
::
- >>> db["PlantType"].columns
+ >>> db.table("PlantType").columns
[Column(cid=0, name='id', type='INTEGER', notnull=0, default_value=None, is_pk=1),
Column(cid=1, name='value', type='TEXT', notnull=0, default_value=None, is_pk=0)]
@@ -1818,7 +2433,7 @@ The ``.columns`` property shows the columns in the table or view. It returns a l
The ``.columns_dict`` property returns a dictionary version of the columns with just the names and Python types::
- >>> db["PlantType"].columns_dict
+ >>> db.table("PlantType").columns_dict
{'id': , 'value': }
.. _python_api_introspection_default_values:
@@ -1828,7 +2443,7 @@ The ``.columns_dict`` property returns a dictionary version of the columns with
The ``.default_values`` property returns a dictionary of default values for each column that has a default::
- >>> db["table_with_defaults"].default_values
+ >>> db.table("table_with_defaults").default_values
{'score': 5}
.. _python_api_introspection_pks:
@@ -1838,7 +2453,7 @@ The ``.default_values`` property returns a dictionary of default values for each
The ``.pks`` property returns a list of strings naming the primary key columns for the table::
- >>> db["PlantType"].pks
+ >>> db.table("PlantType").pks
['id']
If a table has no primary keys but is a `rowid table `__, this property will return ``['rowid']``.
@@ -1850,7 +2465,7 @@ If a table has no primary keys but is a `rowid table >> db["PlantType"].use_rowid
+ >>> db.table("PlantType").use_rowid
False
@@ -1859,17 +2474,39 @@ Almost all SQLite tables have a ``rowid`` column, but a table with no explicitly
.foreign_keys
-------------
-The ``.foreign_keys`` property returns any foreign key relationships for the table, as a list of ``ForeignKey(table, column, other_table, other_column)`` named tuples. It is not available on views.
+The ``.foreign_keys`` property returns any foreign key relationships for the table, as a list of ``ForeignKey`` objects. It is not available on views.
+
+Each ``ForeignKey`` has the following attributes:
+
+``table``
+ The table the foreign key is defined on.
+``column``
+ The column on this table, or ``None`` for a compound foreign key.
+``other_table``
+ The table being referenced.
+``other_column``
+ The referenced column, or ``None`` for a compound foreign key.
+``columns``
+ A tuple of the columns on this table, always populated (a one-item tuple for single-column foreign keys).
+``other_columns``
+ A tuple of the referenced columns.
+``is_compound``
+ ``True`` if this is a compound (multi-column) foreign key.
+``on_delete``
+ The ``ON DELETE`` action, e.g. ``"CASCADE"`` - ``"NO ACTION"`` if not set.
+``on_update``
+ The ``ON UPDATE`` action - ``"NO ACTION"`` if not set.
+
+``ForeignKey`` was a ``namedtuple`` prior to sqlite-utils 4.0. It is now a dataclass and can no longer be unpacked or indexed as a tuple - access its fields by name instead. See :ref:`upgrading_3_to_4` for details.
::
- >>> db["Street_Tree_List"].foreign_keys
- [ForeignKey(table='Street_Tree_List', column='qLegalStatus', other_table='qLegalStatus', other_column='id'),
- ForeignKey(table='Street_Tree_List', column='qCareAssistant', other_table='qCareAssistant', other_column='id'),
- ForeignKey(table='Street_Tree_List', column='qSiteInfo', other_table='qSiteInfo', other_column='id'),
- ForeignKey(table='Street_Tree_List', column='qSpecies', other_table='qSpecies', other_column='id'),
- ForeignKey(table='Street_Tree_List', column='qCaretaker', other_table='qCaretaker', other_column='id'),
- ForeignKey(table='Street_Tree_List', column='PlantType', other_table='PlantType', other_column='id')]
+ >>> db.table("Street_Tree_List").foreign_keys
+ [ForeignKey(table='Street_Tree_List', column='qLegalStatus', other_table='qLegalStatus', other_column='id', columns=('qLegalStatus',), other_columns=('id',), is_compound=False, on_delete='NO ACTION', on_update='NO ACTION'),
+ ForeignKey(table='Street_Tree_List', column='qCareAssistant', other_table='qCareAssistant', other_column='id', columns=('qCareAssistant',), other_columns=('id',), is_compound=False, on_delete='NO ACTION', on_update='NO ACTION'),
+ ...]
+
+Compound foreign keys - defined with ``FOREIGN KEY (col_a, col_b) REFERENCES other(col_a, col_b)`` - are returned as a single ``ForeignKey`` with ``is_compound=True``, ``column`` and ``other_column`` set to ``None``, and the participating columns available in the ``columns`` and ``other_columns`` tuples.
.. _python_api_introspection_schema:
@@ -1878,7 +2515,7 @@ The ``.foreign_keys`` property returns any foreign key relationships for the tab
The ``.schema`` property outputs the table's schema as a SQL string::
- >>> print(db["Street_Tree_List"].schema)
+ >>> print(db.table("Street_Tree_List").schema)
CREATE TABLE "Street_Tree_List" (
"TreeID" INTEGER,
"qLegalStatus" INTEGER,
@@ -1899,12 +2536,12 @@ The ``.schema`` property outputs the table's schema as a SQL string::
"Longitude" REAL,
"Location" TEXT
,
- FOREIGN KEY ("PlantType") REFERENCES [PlantType](id),
- FOREIGN KEY ("qCaretaker") REFERENCES [qCaretaker](id),
- FOREIGN KEY ("qSpecies") REFERENCES [qSpecies](id),
- FOREIGN KEY ("qSiteInfo") REFERENCES [qSiteInfo](id),
- FOREIGN KEY ("qCareAssistant") REFERENCES [qCareAssistant](id),
- FOREIGN KEY ("qLegalStatus") REFERENCES [qLegalStatus](id))
+ FOREIGN KEY ("PlantType") REFERENCES "PlantType"(id),
+ FOREIGN KEY ("qCaretaker") REFERENCES "qCaretaker"(id),
+ FOREIGN KEY ("qSpecies") REFERENCES "qSpecies"(id),
+ FOREIGN KEY ("qSiteInfo") REFERENCES "qSiteInfo"(id),
+ FOREIGN KEY ("qCareAssistant") REFERENCES "qCareAssistant"(id),
+ FOREIGN KEY ("qLegalStatus") REFERENCES "qLegalStatus"(id))
.. _python_api_introspection_strict:
@@ -1915,7 +2552,7 @@ The ``.strict`` property identifies if the table is a `SQLite STRICT table