diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml
deleted file mode 100644
index f0bcdbe..0000000
--- a/.github/FUNDING.yml
+++ /dev/null
@@ -1 +0,0 @@
-github: [simonw]
diff --git a/.github/actions/setup-sqlite-version/action.yml b/.github/actions/setup-sqlite-version/action.yml
deleted file mode 100644
index fdbc71c..0000000
--- a/.github/actions/setup-sqlite-version/action.yml
+++ /dev/null
@@ -1,39 +0,0 @@
-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
deleted file mode 100644
index 0df7290..0000000
--- a/.github/actions/setup-sqlite-version/setup-sqlite-version.sh
+++ /dev/null
@@ -1,144 +0,0 @@
-#!/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/codeql-analysis.yml b/.github/workflows/codeql-analysis.yml
deleted file mode 100644
index 713f81e..0000000
--- a/.github/workflows/codeql-analysis.yml
+++ /dev/null
@@ -1,63 +0,0 @@
-name: "CodeQL"
-
-on:
- push:
- branches: [main]
- schedule:
- - cron: '0 4 * * 5'
-
-jobs:
- analyze:
- name: Analyze
- runs-on: ubuntu-latest
-
- strategy:
- fail-fast: false
- matrix:
- # Override automatic language detection by changing the below list
- # Supported options are ['csharp', 'cpp', 'go', 'java', 'javascript', 'python']
- language: ['python']
- # Learn more...
- # https://docs.github.com/en/github/finding-security-vulnerabilities-and-errors-in-your-code/configuring-code-scanning#overriding-automatic-language-detection
-
- steps:
- - name: Checkout repository
- uses: actions/checkout@v2
- with:
- # We must fetch at least the immediate parents so that if this is
- # a pull request then we can checkout the head.
- fetch-depth: 2
-
- # If this run was triggered by a pull request event, then checkout
- # the head of the pull request instead of the merge commit.
- - run: git checkout HEAD^2
- if: ${{ github.event_name == 'pull_request' }}
-
- # Initializes the CodeQL tools for scanning.
- - name: Initialize CodeQL
- uses: github/codeql-action/init@v1
- with:
- languages: ${{ matrix.language }}
- # If you wish to specify custom queries, you can do so here or in a config file.
- # By default, queries listed here will override any specified in a config file.
- # Prefix the list here with "+" to use these queries and those in the config file.
- # queries: ./path/to/local/query, your-org/your-repo/queries@main
-
- # Autobuild attempts to build any compiled languages (C/C++, C#, or Java).
- # If this step fails, then you should remove it and run the build manually (see below)
- - name: Autobuild
- uses: github/codeql-action/autobuild@v1
-
- # ℹ️ Command-line programs to run using the OS shell.
- # 📚 https://git.io/JvXDl
-
- # ✏️ If the Autobuild fails above, remove it and uncomment the following three lines
- # and modify them (or add more) to build your code if your project
- # uses a compiled language
-
- #- run: |
- # make bootstrap
- # make release
-
- - name: Perform CodeQL Analysis
- uses: github/codeql-action/analyze@v1
diff --git a/.github/workflows/documentation-links.yml b/.github/workflows/documentation-links.yml
deleted file mode 100644
index 1aab04e..0000000
--- a/.github/workflows/documentation-links.yml
+++ /dev/null
@@ -1,16 +0,0 @@
-name: Read the Docs Pull Request Preview
-on:
- pull_request_target:
- types:
- - opened
-
-permissions:
- pull-requests: write
-
-jobs:
- documentation-links:
- runs-on: ubuntu-latest
- steps:
- - uses: readthedocs/actions/preview@v1
- with:
- project-slug: "sqlite-utils"
diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml
deleted file mode 100644
index 23b23bd..0000000
--- a/.github/workflows/publish.yml
+++ /dev/null
@@ -1,48 +0,0 @@
-name: Publish Python Package
-
-on:
- release:
- types: [created]
-
-jobs:
- test:
- runs-on: ${{ matrix.os }}
- strategy:
- matrix:
- python-version: ["3.10", "3.11", "3.12", "3.13", "3.14"]
- os: [ubuntu-latest, windows-latest, macos-latest]
- steps:
- - uses: actions/checkout@v7
- - name: Set up Python ${{ matrix.python-version }}
- uses: actions/setup-python@v6
- with:
- python-version: ${{ matrix.python-version }}
- cache: pip
- cache-dependency-path: pyproject.toml
- - name: Install dependencies
- run: |
- pip install . --group dev
- - name: Run tests
- run: |
- pytest
- deploy:
- runs-on: ubuntu-latest
- needs: [test]
- steps:
- - uses: actions/checkout@v7
- - name: Set up Python
- uses: actions/setup-python@v6
- with:
- python-version: '3.14'
- cache: pip
- cache-dependency-path: pyproject.toml
- - name: Install dependencies
- run: |
- pip install build twine
- - name: Publish
- env:
- TWINE_USERNAME: __token__
- TWINE_PASSWORD: ${{ secrets.PYPI_TOKEN }}
- run: |
- python -m build
- twine upload dist/*
diff --git a/.github/workflows/spellcheck.yml b/.github/workflows/spellcheck.yml
deleted file mode 100644
index 2afa7b7..0000000
--- a/.github/workflows/spellcheck.yml
+++ /dev/null
@@ -1,22 +0,0 @@
-name: Check spelling in documentation
-
-on: [push, pull_request]
-
-jobs:
- spellcheck:
- runs-on: ubuntu-latest
- steps:
- - uses: actions/checkout@v4
- - name: Set up Python
- uses: actions/setup-python@v5
- with:
- python-version: "3.12"
- cache: pip
- cache-dependency-path: pyproject.toml
- - name: Install dependencies
- run: |
- pip install . --group docs
- - name: Check spelling
- run: |
- codespell docs/*.rst --ignore-words docs/codespell-ignore-words.txt
- codespell sqlite_utils --ignore-words docs/codespell-ignore-words.txt
diff --git a/.github/workflows/test-coverage.yml b/.github/workflows/test-coverage.yml
deleted file mode 100644
index 7668f1b..0000000
--- a/.github/workflows/test-coverage.yml
+++ /dev/null
@@ -1,38 +0,0 @@
-name: Calculate test coverage
-
-on:
- push:
- branches:
- - main
- pull_request:
- branches:
- - main
-jobs:
- test:
- runs-on: ubuntu-latest
- steps:
- - name: Check out repo
- uses: actions/checkout@v7
- - name: Set up Python
- uses: actions/setup-python@v6
- with:
- 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 . --group dev
- python -m pip install pytest-cov
- - name: Run tests
- run: |-
- ls -lah
- pytest --cov=sqlite_utils --cov-report xml:coverage.xml --cov-report term
- ls -lah
- - name: Upload coverage report
- uses: codecov/codecov-action@v1
- with:
- token: ${{ secrets.CODECOV_TOKEN }}
- file: coverage.xml
diff --git a/.github/workflows/test-sqlite-support.yml b/.github/workflows/test-sqlite-support.yml
deleted file mode 100644
index f195cba..0000000
--- a/.github/workflows/test-sqlite-support.yml
+++ /dev/null
@@ -1,41 +0,0 @@
-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
deleted file mode 100644
index 923de2e..0000000
--- a/.github/workflows/test.yml
+++ /dev/null
@@ -1,57 +0,0 @@
-name: Test
-
-on: [push, pull_request]
-
-env:
- FORCE_COLOR: 1
-
-jobs:
- test:
- runs-on: ${{ matrix.os }}
- strategy:
- matrix:
- 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, macos-14]
- 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: Install dependencies
- run: |
- pip install . --group dev
- - name: Optionally install numpy
- if: matrix.numpy == 1
- run: pip install numpy
- - name: Install SpatiaLite
- if: matrix.os == 'ubuntu-latest'
- run: sudo apt-get install libsqlite3-mod-spatialite
- - name: Build extension for --load-extension test
- if: matrix.os == 'ubuntu-latest'
- run: |-
- (cd tests && gcc ext.c -fPIC -shared -o ext.so && ls -lah)
- - 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 --diff README.md docs/*.rst
diff --git a/.gitignore b/.gitignore
index 5b5d2c6..53605b7 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,7 +1,4 @@
.venv
-dist
-build
-*.db
__pycache__/
*.py[cod]
*$py.class
@@ -10,15 +7,3 @@ venv
.pytest_cache
*.egg-info
.DS_Store
-.mypy_cache
-.coverage
-.schema
-.vscode
-.hypothesis
-.claude/
-Pipfile
-Pipfile.lock
-uv.lock
-tests/*.dylib
-tests/*.so
-tests/*.dll
diff --git a/.readthedocs.yaml b/.readthedocs.yaml
deleted file mode 100644
index 08c2f81..0000000
--- a/.readthedocs.yaml
+++ /dev/null
@@ -1,17 +0,0 @@
-version: 2
-
-sphinx:
- configuration: docs/conf.py
-
-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/.travis.yml b/.travis.yml
new file mode 100644
index 0000000..3af29a6
--- /dev/null
+++ b/.travis.yml
@@ -0,0 +1,39 @@
+language: python
+dist: xenial
+
+# 3.6 is listed first so it gets used for the later build stages
+python:
+ - "3.6"
+ - "3.7-dev"
+ - "3.8-dev"
+
+script:
+ - sudo add-apt-repository ppa:jonathonf/backports -y
+ - sudo apt-get update && sudo apt-get install sqlite3
+ - pip install -U pip wheel
+ - pip install .[test]
+ # Only run the numpy/pandas tests on Python 3.7:
+ - python -c "import sys; print(sys.version_info.minor == 7)" | grep True > /dev/null && pip install pandas || true
+ - pytest
+
+cache:
+ directories:
+ - $HOME/.cache/pip
+
+jobs:
+ include:
+ - stage: release tagged version
+ if: tag IS present
+ language: python
+ python: 3.6
+ script:
+ - pip install -U pip wheel
+ deploy:
+ - provider: pypi
+ user: simonw
+ distributions: bdist_wheel
+ password: ${PYPI_PASSWORD}
+ on:
+ branch: master
+ tags: true
+ repo: simonw/sqlite-utils
diff --git a/Justfile b/Justfile
deleted file mode 100644
index be41523..0000000
--- a/Justfile
+++ /dev/null
@@ -1,34 +0,0 @@
-# Run tests and linters
-@default: test lint
-
-# Run pytest with supplied options
-@test *options:
- uv run pytest {{options}}
-
-@run *options:
- uv run -- {{options}}
-
-# Run linters: black, flake8, mypy, ty, cog
-@lint:
- 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:
- uv run --group docs cog -r README.md docs/*.rst
-
-# Serve live docs on localhost:8000
-@docs: cog
- #!/usr/bin/env bash
- cd docs
- uv run --group docs make livehtml
-
-
-# Apply Black
-@black:
- uv run black .
diff --git a/MANIFEST.in b/MANIFEST.in
deleted file mode 100644
index e3c9212..0000000
--- a/MANIFEST.in
+++ /dev/null
@@ -1,4 +0,0 @@
-include LICENSE
-include README.md
-recursive-include docs *.rst
-recursive-include tests *.py
diff --git a/README.md b/README.md
index c444c64..1e41cfb 100644
--- a/README.md
+++ b/README.md
@@ -1,55 +1,27 @@
# sqlite-utils
[](https://pypi.org/project/sqlite-utils/)
-[](https://sqlite-utils.datasette.io/en/stable/changelog.html)
-[](https://pypi.org/project/sqlite-utils/)
-[](https://github.com/simonw/sqlite-utils/actions?query=workflow%3ATest)
-[](http://sqlite-utils.datasette.io/en/stable/?badge=stable)
-[](https://codecov.io/gh/simonw/sqlite-utils)
-[](https://github.com/simonw/sqlite-utils/blob/main/LICENSE)
-[](https://discord.gg/Ass7bCAMDw)
+[](https://travis-ci.com/simonw/sqlite-utils)
+[](http://sqlite-utils.readthedocs.io/en/latest/?badge=latest)
+[](https://github.com/simonw/sqlite-utils/blob/master/LICENSE)
Python CLI utility and library for manipulating SQLite databases.
-## Some feature highlights
+Read more on my blog: [
+sqlite-utils: a Python library and CLI tool for building SQLite databases](https://simonwillison.net/2019/Feb/25/sqlite-utils/)
-- [Pipe JSON](https://sqlite-utils.datasette.io/en/stable/cli.html#inserting-json-data) (or [CSV or TSV](https://sqlite-utils.datasette.io/en/stable/cli.html#inserting-csv-or-tsv-data)) directly into a new SQLite database file, automatically creating a table with the appropriate schema
-- [Run in-memory SQL queries](https://sqlite-utils.datasette.io/en/stable/cli.html#querying-data-directly-using-an-in-memory-database), including joins, directly against data in CSV, TSV or JSON files and view the results
-- [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
+Install it like this:
-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
-
- pip install sqlite-utils
-
-Or if you use [Homebrew](https://brew.sh/) for macOS:
-
- brew install sqlite-utils
-
-## Using as a CLI tool
+ pip3 install sqlite-utils
Now you can do things with the CLI utility like this:
- $ sqlite-utils memory dogs.csv "select * from t"
- [{"id": 1, "age": 4, "name": "Cleo"},
- {"id": 2, "age": 2, "name": "Pancakes"}]
-
- $ sqlite-utils insert dogs.db dogs dogs.csv --csv
- [####################################] 100%
-
$ sqlite-utils tables dogs.db --counts
[{"table": "dogs", "count": 2}]
- $ sqlite-utils dogs.db "select id, name from dogs"
- [{"id": 1, "name": "Cleo"},
- {"id": 2, "name": "Pancakes"}]
+ $ sqlite-utils dogs.db "select * from dogs"
+ [{"id": 1, "age": 4, "name": "Cleo"},
+ {"id": 2, "age": 2, "name": "Pancakes"}]
$ sqlite-utils dogs.db "select * from dogs" --csv
id,age,name
@@ -62,24 +34,7 @@ Now you can do things with the CLI utility like this:
1 4 Cleo
2 2 Pancakes
-You can import JSON data into a new database table like this:
-
- $ curl https://api.github.com/repos/simonw/sqlite-utils/releases \
- | sqlite-utils insert releases.db releases - --pk id
-
-Or for data in a CSV file:
-
- $ sqlite-utils insert dogs.db dogs dogs.csv --csv
-
-`sqlite-utils memory` lets you import CSV or JSON data into an in-memory database and run SQL queries against it in a single command:
-
- $ cat dogs.csv | sqlite-utils memory - "select name, age from stdin"
-
-See the [full CLI documentation](https://sqlite-utils.datasette.io/en/stable/cli.html) for comprehensive coverage of many more commands.
-
-## Using as a library
-
-You can also `import sqlite_utils` and use it as a Python library like this:
+Or you can import it and use it as a Python library like this:
```python
import sqlite_utils
@@ -91,11 +46,10 @@ db["dogs"].insert_all([
], pk="id")
```
-Check out the [full library documentation](https://sqlite-utils.datasette.io/en/stable/python-api.html) for everything else you can do with the Python library.
+Full documentation: https://sqlite-utils.readthedocs.io/
-## Related projects
+Related projects:
-* [Datasette](https://datasette.io/): A tool for exploring and publishing data
+* [Datasette](https://github.com/simonw/datasette): A tool for exploring and publishing data
* [csvs-to-sqlite](https://github.com/simonw/csvs-to-sqlite): Convert CSV files into a SQLite database
* [db-to-sqlite](https://github.com/simonw/db-to-sqlite): CLI tool for exporting a MySQL or PostgreSQL database as a SQLite file
-* [dogsheep](https://dogsheep.github.io/): A family of tools for personal analytics, built on top of `sqlite-utils`
diff --git a/codecov.yml b/codecov.yml
deleted file mode 100644
index bfdc987..0000000
--- a/codecov.yml
+++ /dev/null
@@ -1,8 +0,0 @@
-coverage:
- status:
- project:
- default:
- informational: true
- patch:
- default:
- informational: true
diff --git a/docs/Makefile b/docs/Makefile
index 5578ae3..a279768 100644
--- a/docs/Makefile
+++ b/docs/Makefile
@@ -20,4 +20,4 @@ help:
@$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
livehtml:
- sphinx-autobuild -a -b html "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(0) --watch ../sqlite_utils
+ sphinx-autobuild -b html "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(0)
diff --git a/docs/_static/js/custom.js b/docs/_static/js/custom.js
deleted file mode 100644
index 8786865..0000000
--- a/docs/_static/js/custom.js
+++ /dev/null
@@ -1,23 +0,0 @@
-jQuery(function ($) {
- // Show banner linking to /stable/ if this is a /latest/ page
- if (!/\/latest\//.test(location.pathname)) {
- return;
- }
- var stableUrl = location.pathname.replace("/latest/", "/stable/");
- // Check it's not a 404
- fetch(stableUrl, { method: "HEAD" }).then((response) => {
- if (response.status == 200) {
- var warning = $(
- `
-
Note
-
- This documentation covers the development version of sqlite-utils.
-
See this page for the current stable release.
-
-
`
- );
- warning.find("a").attr("href", stableUrl);
- $("article[role=main]").prepend(warning);
- }
- });
-});
diff --git a/docs/_templates/base.html b/docs/_templates/base.html
deleted file mode 100644
index a253a46..0000000
--- a/docs/_templates/base.html
+++ /dev/null
@@ -1,42 +0,0 @@
-{%- extends "!base.html" %}
-
-{% block site_meta %}
-{{ super() }}
-
-{% endblock %}
-
-{% block scripts %}
-{{ super() }}
-
-
-{% endblock %}
diff --git a/docs/changelog.rst b/docs/changelog.rst
index 4c868f4..95252c2 100644
--- a/docs/changelog.rst
+++ b/docs/changelog.rst
@@ -1,1231 +1,20 @@
-.. _changelog:
-
===========
Changelog
===========
-.. _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)
------------------
-
-- Now tested against Python 3.11. (:issue:`502`)
-- New ``table.search_sql(include_rank=True)`` option, which adds a ``rank`` column to the generated SQL. Thanks, Jacob Chapman. (`#480 `__)
-- Progress bars now display for newline-delimited JSON files using the ``--nl`` option. Thanks, Mischa Untaga. (:issue:`485`)
-- New ``db.close()`` method. (:issue:`504`)
-- 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 now covers the :ref:`release_process` for this package.
-
-.. _v3_29:
-
-3.29 (2022-08-27)
------------------
-
-- The ``sqlite-utils query``, ``memory`` and ``bulk`` commands now all accept a new ``--functions`` option. This can be passed a string of Python code, and any callable objects defined in that code will be made available to SQL queries as custom SQL functions. See :ref:`cli_query_functions` for details. (:issue:`471`)
-- ``db[table].create(...)`` method now accepts a new ``transform=True`` parameter. If the table already exists it will be :ref:`transformed ` to match the schema configuration options passed to the function. This may result in columns being added or dropped, column types being changed, column order being updated or not null and default values for columns being set. (:issue:`467`)
-- Related to the above, the ``sqlite-utils create-table`` command now accepts a ``--transform`` option.
-- New introspection property: ``table.default_values`` returns a dictionary mapping each column name with a default value to the configured default value. (:issue:`475`)
-- The ``--load-extension`` option can now be provided a path to a compiled SQLite extension module accompanied by the name of an entrypoint, separated by a colon - for example ``--load-extension ./lines0:sqlite3_lines0_noread_init``. This feature is modelled on code first `contributed to Datasette `__ by Alex Garcia. (:issue:`470`)
-- Functions registered using the :ref:`db.register_function() ` method can now have a custom name specified using the new ``db.register_function(fn, name=...)`` parameter. (:issue:`458`)
-- :ref:`sqlite-utils rows ` has a new ``--order`` option for specifying the sort order for the returned rows. (:issue:`469`)
-- All of the CLI options that accept Python code blocks can now all be used to define functions that can access modules imported in that same block of code without needing to use the ``global`` keyword. (:issue:`472`)
-- Fixed bug where ``table.extract()`` would not behave correctly for columns containing null values. Thanks, Forest Gregg. (:issue:`423`)
-- New tutorial: `Cleaning data with sqlite-utils and Datasette `__ shows how to use ``sqlite-utils`` to import and clean an example CSV file.
-- Datasette and ``sqlite-utils`` now have a Discord community. `Join the Discord here `__.
-
-.. _v3_28:
-
-3.28 (2022-07-15)
------------------
-
-- New :ref:`table.duplicate(new_name) ` method for creating a copy of a table with a matching schema and row contents. Thanks, `David `__. (:issue:`449`)
-- New ``sqlite-utils duplicate data.db table_name new_name`` CLI command for :ref:`cli_duplicate_table`. (:issue:`454`)
-- ``sqlite_utils.utils.rows_from_file()`` is now a :ref:`documented API `. It can be used to read a sequence of dictionaries from a file-like object containing CSV, TSV, JSON or newline-delimited JSON. It can be passed an explicit format or can attempt to detect the format automatically. (:issue:`443`)
-- ``sqlite_utils.utils.TypeTracker`` is now a documented API for detecting the likely column types for a sequence of string rows, see :ref:`python_api_typetracker`. (:issue:`445`)
-- ``sqlite_utils.utils.chunks()`` is now a documented API for :ref:`splitting an iterator into chunks `. (:issue:`451`)
-- ``sqlite-utils enable-fts`` now has a ``--replace`` option for replacing the existing FTS configuration for a table. (:issue:`450`)
-- The ``create-index``, ``add-column`` and ``duplicate`` commands all now take a ``--ignore`` option for ignoring errors should the database not be in the right state for them to operate. (:issue:`450`)
-
-.. _v3_27:
-
-3.27 (2022-06-14)
------------------
-
-See also `the annotated release notes `__ for this release.
-
-- Documentation now uses the `Furo `__ Sphinx theme. (:issue:`435`)
-- Code examples in documentation now have a "copy to clipboard" button. (:issue:`436`)
-- ``sqlite_utils.utils.utils.rows_from_file()`` is now a documented API, see :ref:`python_api_rows_from_file`. (:issue:`443`)
-- ``rows_from_file()`` has two new parameters to help handle CSV files with rows that contain more values than are listed in that CSV file's headings: ``ignore_extras=True`` and ``extras_key="name-of-key"``. (:issue:`440`)
-- ``sqlite_utils.utils.maximize_csv_field_size_limit()`` helper function for increasing the field size limit for reading CSV files to its maximum, see :ref:`python_api_maximize_csv_field_size_limit`. (:issue:`442`)
-- ``table.search(where=, where_args=)`` parameters for adding additional ``WHERE`` clauses to a search query. The ``where=`` parameter is available on ``table.search_sql(...)`` as well. See :ref:`python_api_fts_search`. (:issue:`441`)
-- Fixed bug where ``table.detect_fts()`` and other search-related functions could fail if two FTS-enabled tables had names that were prefixes of each other. (:issue:`434`)
-
-.. _v3_26_1:
-
-3.26.1 (2022-05-02)
--------------------
-
-- Now depends on `click-default-group-wheel `__, a pure Python wheel package. This means you can install and use this package with `Pyodide `__, which can run Python entirely in your browser using WebAssembly. (`#429 `__)
-
- Try that out using the `Pyodide REPL `__:
-
- .. code-block:: python
-
- >>> import micropip
- >>> await micropip.install("sqlite-utils")
- >>> import sqlite_utils
- >>> db = sqlite_utils.Database(memory=True)
- >>> list(db.query("select 3 * 5"))
- [{'3 * 5': 15}]
-
-.. _v3_26:
-
-3.26 (2022-04-13)
------------------
-
-- New ``errors=r.IGNORE/r.SET_NULL`` parameter for the ``r.parsedatetime()`` and ``r.parsedate()`` :ref:`convert recipes `. (:issue:`416`)
-- Fixed a bug where ``--multi`` could not be used in combination with ``--dry-run`` for the :ref:`convert ` command. (:issue:`415`)
-- New documentation: :ref:`cli_convert_complex`. (:issue:`420`)
-- More robust detection for whether or not ``deterministic=True`` is supported. (:issue:`425`)
-
-.. _v3_25_1:
-
-3.25.1 (2022-03-11)
--------------------
-
-- Improved display of type information and parameters in the :ref:`API reference documentation `. (:issue:`413`)
-
-.. _v3_25:
-
-3.25 (2022-03-01)
------------------
-
-- New ``hash_id_columns=`` parameter for creating a primary key that's a hash of the content of specific columns - see :ref:`python_api_hash` for details. (:issue:`343`)
-- New :ref:`db.sqlite_version ` property, returning a tuple of integers representing the version of SQLite, for example ``(3, 38, 0)``.
-- Fixed a bug where :ref:`register_function(deterministic=True) ` caused errors on versions of SQLite prior to 3.8.3. (:issue:`408`)
-- New documented :ref:`hash_record(record, keys=...) ` function.
-
-.. _v3_24:
-
-3.24 (2022-02-15)
------------------
-
-- SpatiaLite helpers for the ``sqlite-utils`` command-line tool - thanks, Chris Amico. (:issue:`398`)
-
- - :ref:`sqlite-utils create-database ` ``--init-spatialite`` option for initializing SpatiaLite on a newly created database.
- - :ref:`sqlite-utils add-geometry-column ` command for adding geometry columns.
- - :ref:`sqlite-utils create-spatial-index ` command for adding spatial indexes.
-
-- ``db[table].create(..., if_not_exists=True)`` option for :ref:`creating a table ` only if it does not already exist. (:issue:`397`)
-- ``Database(memory_name="my_shared_database")`` parameter for creating a :ref:`named in-memory database ` that can be shared between multiple connections. (:issue:`405`)
-- Documentation now describes :ref:`how to add a primary key to a rowid table ` using ``sqlite-utils transform``. (:issue:`403`)
-
-.. _v3_23:
-
-3.23 (2022-02-03)
------------------
-
-This release introduces four new utility methods for working with `SpatiaLite `__. Thanks, Chris Amico. (`#385 `__)
-
-- ``sqlite_utils.utils.find_spatialite()`` :ref:`finds the location of the SpatiaLite module ` on disk.
-- ``db.init_spatialite()`` :ref:`initializes SpatiaLite ` for the given database.
-- ``table.add_geometry_column(...)`` :ref:`adds a geometry column ` to an existing table.
-- ``table.create_spatial_index(...)`` :ref:`creates a spatial index ` for a column.
-- ``sqlite-utils batch`` now accepts a ``--batch-size`` option. (:issue:`392`)
-
-.. _v3_22_1:
-
-3.22.1 (2022-01-25)
--------------------
-
-- All commands now include example usage in their ``--help`` - see :ref:`cli_reference`. (:issue:`384`)
-- Python library documentation has a new :ref:`python_api_getting_started` section. (:issue:`387`)
-- Documentation now uses `Plausible analytics `__. (:issue:`389`)
-
-.. _v3_22:
-
-3.22 (2022-01-11)
------------------
-
-- New :ref:`cli_reference` documentation page, listing the output of ``--help`` for every one of the CLI commands. (:issue:`383`)
-- ``sqlite-utils rows`` now has ``--limit`` and ``--offset`` options for paginating through data. (:issue:`381`)
-- ``sqlite-utils rows`` now has ``--where`` and ``-p`` options for filtering the table using a ``WHERE`` query, see :ref:`cli_rows`. (:issue:`382`)
-
-.. _v3_21:
-
-3.21 (2022-01-10)
------------------
-
-CLI and Python library improvements to help run `ANALYZE `__ after creating indexes or inserting rows, to gain better performance from the SQLite query planner when it runs against indexes.
-
-Three new CLI commands: ``create-database``, ``analyze`` and ``bulk``.
-
-More details and examples can be found in `the annotated release notes `__.
-
-- New ``sqlite-utils create-database`` command for creating new empty database files. (:issue:`348`)
-- New Python methods for running ``ANALYZE`` against a database, table or index: ``db.analyze()`` and ``table.analyze()``, see :ref:`python_api_analyze`. (:issue:`366`)
-- New :ref:`sqlite-utils analyze command ` for running ``ANALYZE`` using the CLI. (:issue:`379`)
-- The ``create-index``, ``insert`` and ``upsert`` commands now have a new ``--analyze`` option for running ``ANALYZE`` after the command has completed. (:issue:`379`)
-- New :ref:`sqlite-utils bulk command ` which can import records in the same way as ``sqlite-utils insert`` (from JSON, CSV or TSV) and use them to bulk execute a parametrized SQL query. (:issue:`375`)
-- The CLI tool can now also be run using ``python -m sqlite_utils``. (:issue:`368`)
-- Using ``--fmt`` now implies ``--table``, so you don't need to pass both options. (:issue:`374`)
-- The ``--convert`` function applied to rows can now modify the row in place. (:issue:`371`)
-- The :ref:`insert-files command ` supports two new columns: ``stem`` and ``suffix``. (:issue:`372`)
-- The ``--nl`` import option now ignores blank lines in the input. (:issue:`376`)
-- Fixed bug where streaming input to the ``insert`` command with ``--batch-size 1`` would appear to only commit after several rows had been ingested, due to unnecessary input buffering. (:issue:`364`)
-
-.. _v3_20:
-
-3.20 (2022-01-05)
------------------
-
-- ``sqlite-utils insert ... --lines`` to insert the lines from a file into a table with a single ``line`` column, see :ref:`cli_insert_unstructured`.
-- ``sqlite-utils insert ... --text`` to insert the contents of the file into a table with a single ``text`` column and a single row.
-- ``sqlite-utils insert ... --convert`` allows a Python function to be provided that will be used to convert each row that is being inserted into the database. See :ref:`cli_insert_convert`, including details on special behavior when combined with ``--lines`` and ``--text``. (:issue:`356`)
-- ``sqlite-utils convert`` now accepts a code value of ``-`` to read code from standard input. (:issue:`353`)
-- ``sqlite-utils convert`` also now accepts code that defines a named ``convert(value)`` function, see :ref:`cli_convert`.
-- ``db.supports_strict`` property showing if the database connection supports `SQLite strict tables `__.
-- ``table.strict`` property (see :ref:`python_api_introspection_strict`) indicating if the table uses strict mode. (:issue:`344`)
-- Fixed bug where ``sqlite-utils upsert ... --detect-types`` ignored the ``--detect-types`` option. (:issue:`362`)
-
-.. _v3_19:
-
-3.19 (2021-11-20)
------------------
-
-- The :ref:`table.lookup() method ` now accepts keyword arguments that match those on the underlying ``table.insert()`` method: ``foreign_keys=``, ``column_order=``, ``not_null=``, ``defaults=``, ``extracts=``, ``conversions=`` and ``columns=``. You can also now pass ``pk=`` to specify a different column name to use for the primary key. (:issue:`342`)
-
-.. _v3_18:
-
-3.18 (2021-11-14)
------------------
-
-- The ``table.lookup()`` method now has an optional second argument which can be used to populate columns only the first time the record is created, see :ref:`python_api_lookup_tables`. (:issue:`339`)
-- ``sqlite-utils memory`` now has a ``--flatten`` option for :ref:`flattening nested JSON objects ` into separate columns, consistent with ``sqlite-utils insert``. (:issue:`332`)
-- ``table.create_index(..., find_unique_name=True)`` parameter, which finds an available name for the created index even if the default name has already been taken. This means that ``index-foreign-keys`` will work even if one of the indexes it tries to create clashes with an existing index name. (:issue:`335`)
-- Added ``py.typed`` to the module, so `mypy `__ should now correctly pick up the type annotations. Thanks, Andreas Longo. (:issue:`331`)
-- Now depends on ``python-dateutil`` instead of depending on ``dateutils``. Thanks, Denys Pavlov. (:issue:`324`)
-- ``table.create()`` (see :ref:`python_api_explicit_create`) now handles ``dict``, ``list`` and ``tuple`` types, mapping them to ``TEXT`` columns in SQLite so that they can be stored encoded as JSON. (:issue:`338`)
-- Inserted data with square braces in the column names (for example a CSV file containing a ``item[price]``) column now have the braces converted to underscores: ``item_price_``. Previously such columns would be rejected with an error. (:issue:`329`)
-- Now also tested against Python 3.10. (`#330 `__)
-
-.. _v3_17.1:
-
-3.17.1 (2021-09-22)
--------------------
-
-- :ref:`sqlite-utils memory ` now works if files passed to it share the same file name. (:issue:`325`)
-- :ref:`sqlite-utils query ` now returns ``[]`` in JSON mode if no rows are returned. (:issue:`328`)
-
-.. _v3_17:
-
-3.17 (2021-08-24)
------------------
-
-- The :ref:`sqlite-utils memory ` command has a new ``--analyze`` option, which runs the equivalent of the :ref:`analyze-tables ` command directly against the in-memory database created from the incoming CSV or JSON data. (:issue:`320`)
-- :ref:`sqlite-utils insert-files ` now has the ability to insert file contents in to ``TEXT`` columns in addition to the default ``BLOB``. Pass the ``--text`` option or use ``content_text`` as a column specifier. (:issue:`319`)
-
-.. _v3_16:
-
-3.16 (2021-08-18)
------------------
-
-- Type signatures added to more methods, including ``table.resolve_foreign_keys()``, ``db.create_table_sql()``, ``db.create_table()`` and ``table.create()``. (:issue:`314`)
-- New ``db.quote_fts(value)`` method, see :ref:`python_api_quote_fts` - thanks, Mark Neumann. (:issue:`246`)
-- ``table.search()`` now accepts an optional ``quote=True`` parameter. (:issue:`296`)
-- CLI command ``sqlite-utils search`` now accepts a ``--quote`` option. (:issue:`296`)
-- Fixed bug where ``--no-headers`` and ``--tsv`` options to :ref:`sqlite-utils insert ` could not be used together. (:issue:`295`)
-- Various small improvements to :ref:`reference` documentation.
-
-.. _v3_15.1:
-
-3.15.1 (2021-08-10)
--------------------
-
-- Python library now includes type annotations on almost all of the methods, plus detailed docstrings describing each one. (:issue:`311`)
-- New :ref:`reference` documentation page, powered by those docstrings.
-- Fixed bug where ``.add_foreign_keys()`` failed to raise an error if called against a ``View``. (:issue:`313`)
-- Fixed bug where ``.delete_where()`` returned a ``[]`` instead of returning ``self`` if called against a non-existent table. (:issue:`315`)
-
-.. _v3_15:
-
-3.15 (2021-08-09)
------------------
-
-- ``sqlite-utils insert --flatten`` option for :ref:`flattening nested JSON objects ` to create tables with column names like ``topkey_nestedkey``. (:issue:`310`)
-- Fixed several spelling mistakes in the documentation, spotted `using codespell `__.
-- Errors that occur while using the ``sqlite-utils`` CLI tool now show the responsible SQL and query parameters, if possible. (:issue:`309`)
-
-.. _v3_14:
-
-3.14 (2021-08-02)
------------------
-
-This release introduces the new :ref:`sqlite-utils convert command ` (:issue:`251`) and corresponding :ref:`table.convert(...) ` Python method (:issue:`302`). These tools can be used to apply a Python conversion function to one or more columns of a table, either updating the column in place or using transformed data from that column to populate one or more other columns.
-
-This command-line example uses the Python standard library `textwrap module `__ to wrap the content of the ``content`` column in the ``articles`` table to 100 characters::
-
- $ sqlite-utils convert content.db articles content \
- '"\n".join(textwrap.wrap(value, 100))' \
- --import=textwrap
-
-The same operation in Python code looks like this:
-
-.. code-block:: python
-
- import sqlite_utils, textwrap
-
- db = sqlite_utils.Database("content.db")
- db["articles"].convert("content", lambda v: "\n".join(textwrap.wrap(v, 100)))
-
-See the full documentation for the :ref:`sqlite-utils convert command ` and the :ref:`table.convert(...) ` Python method for more details.
-
-Also in this release:
-
-- The new ``table.count_where(...)`` method, for counting rows in a table that match a specific SQL ``WHERE`` clause. (:issue:`305`)
-- New ``--silent`` option for the :ref:`sqlite-utils insert-files command ` to hide the terminal progress bar, consistent with the ``--silent`` option for ``sqlite-utils convert``. (:issue:`301`)
-
-.. _v3_13:
-
-3.13 (2021-07-24)
------------------
-
-- ``sqlite-utils schema my.db table1 table2`` command now accepts optional table names. (:issue:`299`)
-- ``sqlite-utils memory --help`` now describes the ``--schema`` option.
-
-.. _v3_12:
-
-3.12 (2021-06-25)
------------------
-
-- New :ref:`db.query(sql, params) ` method, which executes a SQL query and returns the results as an iterator over Python dictionaries. (:issue:`290`)
-- This project now uses ``flake8`` and has started to use ``mypy``. (:issue:`291`)
-- New documentation on :ref:`contributing ` to this project. (:issue:`292`)
-
-.. _v3_11:
-
-3.11 (2021-06-20)
------------------
-
-- New ``sqlite-utils memory data.csv --schema`` option, for outputting the schema of the in-memory database generated from one or more files. See :ref:`cli_memory_schema_dump_save`. (:issue:`288`)
-- Added :ref:`installation instructions `. (:issue:`286`)
-
-.. _v3_10:
-
-3.10 (2021-06-19)
------------------
-
-This release introduces the ``sqlite-utils memory`` command, which can be used to load CSV or JSON data into a temporary in-memory database and run SQL queries (including joins across multiple files) directly against that data.
-
-Also new: ``sqlite-utils insert --detect-types``, ``sqlite-utils dump``, ``table.use_rowid`` plus some smaller fixes.
-
-sqlite-utils memory
-~~~~~~~~~~~~~~~~~~~
-
-This example of ``sqlite-utils memory`` retrieves information about the all of the repositories in the `Dogsheep `__ organization on GitHub using `this JSON API `__, sorts them by their number of stars and outputs a table of the top five (using ``-t``)::
-
- $ curl -s 'https://api.github.com/users/dogsheep/repos' \
- | sqlite-utils memory - '
- select full_name, forks_count, stargazers_count
- from stdin order by stargazers_count desc limit 5
- ' -t
- full_name forks_count stargazers_count
- --------------------------------- ------------- ------------------
- dogsheep/twitter-to-sqlite 12 225
- dogsheep/github-to-sqlite 14 139
- dogsheep/dogsheep-photos 5 116
- dogsheep/dogsheep.github.io 7 90
- dogsheep/healthkit-to-sqlite 4 85
-
-The tool works against files on disk as well. This example joins data from two CSV files::
-
- $ cat creatures.csv
- species_id,name
- 1,Cleo
- 2,Bants
- 2,Dori
- 2,Azi
- $ cat species.csv
- id,species_name
- 1,Dog
- 2,Chicken
- $ sqlite-utils memory species.csv creatures.csv '
- select * from creatures join species on creatures.species_id = species.id
- '
- [{"species_id": 1, "name": "Cleo", "id": 1, "species_name": "Dog"},
- {"species_id": 2, "name": "Bants", "id": 2, "species_name": "Chicken"},
- {"species_id": 2, "name": "Dori", "id": 2, "species_name": "Chicken"},
- {"species_id": 2, "name": "Azi", "id": 2, "species_name": "Chicken"}]
-
-Here the ``species.csv`` file becomes the ``species`` table, the ``creatures.csv`` file becomes the ``creatures`` table and the output is JSON, the default output format.
-
-You can also use the ``--attach`` option to attach existing SQLite database files to the in-memory database, in order to join data from CSV or JSON directly against your existing tables.
-
-Full documentation of this new feature is available in :ref:`cli_memory`. (:issue:`272`)
-
-sqlite-utils insert \-\-detect-types
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
-The :ref:`sqlite-utils insert ` command can be used to insert data from JSON, CSV or TSV files into a SQLite database file. The new ``--detect-types`` option (shortcut ``-d``), when used in conjunction with a CSV or TSV import, will automatically detect if columns in the file are integers or floating point numbers as opposed to treating everything as a text column and create the new table with the corresponding schema. See :ref:`cli_insert_csv_tsv` for details. (:issue:`282`)
-
-Other changes
-~~~~~~~~~~~~~
-
-- **Bug fix**: ``table.transform()``, when run against a table without explicit primary keys, would incorrectly create a new version of the table with an explicit primary key column called ``rowid``. (:issue:`284`)
-- New ``table.use_rowid`` introspection property, see :ref:`python_api_introspection_use_rowid`. (:issue:`285`)
-- The new ``sqlite-utils dump file.db`` command outputs a SQL dump that can be used to recreate a database. (:issue:`274`)
-- ``-h`` now works as a shortcut for ``--help``, thanks Loren McIntyre. (:issue:`276`)
-- Now using `pytest-cov `__ and `Codecov `__ to track test coverage - currently at 96%. (:issue:`275`)
-- SQL errors that occur when using ``sqlite-utils query`` are now displayed as CLI errors.
-
-.. _v3_9_1:
-
-3.9.1 (2021-06-12)
-------------------
-
-- Fixed bug when using ``table.upsert_all()`` to create a table with only a single column that is treated as the primary key. (:issue:`271`)
-
-.. _v3_9:
-
-3.9 (2021-06-11)
-----------------
-
-- New ``sqlite-utils schema`` command showing the full SQL schema for a database, see :ref:`Showing the schema (CLI)`. (:issue:`268`)
-- ``db.schema`` introspection property exposing the same feature to the Python library, see :ref:`Showing the schema (Python library) `.
-
-.. _v3_8:
-
-3.8 (2021-06-02)
-----------------
-
-- New ``sqlite-utils indexes`` command to list indexes in a database, see :ref:`cli_indexes`. (:issue:`263`)
-- ``table.xindexes`` introspection property returning more details about that table's indexes, see :ref:`python_api_introspection_xindexes`. (:issue:`261`)
-
-.. _v3_7:
-
-3.7 (2021-05-28)
-----------------
-
-- New ``table.pks_and_rows_where()`` method returning ``(primary_key, row_dictionary)`` tuples - see :ref:`python_api_pks_and_rows_where`. (:issue:`240`)
-- Fixed bug with ``table.add_foreign_key()`` against columns containing spaces. (:issue:`238`)
-- ``table_or_view.drop(ignore=True)`` option for avoiding errors if the table or view does not exist. (:issue:`237`)
-- ``sqlite-utils drop-view --ignore`` and ``sqlite-utils drop-table --ignore`` options. (:issue:`237`)
-- Fixed a bug with inserts of nested JSON containing non-ascii strings - thanks, Dylan Wu. (:issue:`257`)
-- Suggest ``--alter`` if an error occurs caused by a missing column. (:issue:`259`)
-- Support creating indexes with columns in descending order, see :ref:`API documentation ` and :ref:`CLI documentation `. (:issue:`260`)
-- Correctly handle CSV files that start with a UTF-8 BOM. (:issue:`250`)
-
-.. _v3_6:
-
-3.6 (2021-02-18)
-----------------
-
-This release adds the ability to execute queries joining data from more than one database file - similar to the cross database querying feature introduced in `Datasette 0.55 `__.
-
-- The ``db.attach(alias, filepath)`` Python method can be used to attach extra databases to the same connection, see :ref:`db.attach() in the Python API documentation `. (:issue:`113`)
-- The ``--attach`` option attaches extra aliased databases to run SQL queries against directly on the command-line, see :ref:`attaching additional databases in the CLI documentation `. (:issue:`236`)
-
-.. _v3_5:
-
-3.5 (2021-02-14)
-----------------
-
-- ``sqlite-utils insert --sniff`` option for detecting the delimiter and quote character used by a CSV file, see :ref:`cli_insert_csv_tsv_delimiter`. (:issue:`230`)
-- The ``table.rows_where()``, ``table.search()`` and ``table.search_sql()`` methods all now take optional ``offset=`` and ``limit=`` arguments. (:issue:`231`)
-- New ``--no-headers`` option for ``sqlite-utils insert --csv`` to handle CSV files that are missing the header row, see :ref:`cli_insert_csv_tsv_no_header`. (:issue:`228`)
-- Fixed bug where inserting data with extra columns in subsequent chunks would throw an error. Thanks `@nieuwenhoven `__ for the fix. (:issue:`234`)
-- Fixed bug importing CSV files with columns containing more than 128KB of data. (:issue:`229`)
-- Test suite now runs in CI against Ubuntu, macOS and Windows. Thanks `@nieuwenhoven `__ for the Windows test fixes. (:issue:`232`)
-
-.. _v3_4_1:
-
-3.4.1 (2021-02-05)
-------------------
-
-- Fixed a code import bug that slipped in to 3.4. (:issue:`226`)
-
-.. _v3_4:
-
-3.4 (2021-02-05)
-----------------
-
-- ``sqlite-utils insert --csv`` now accepts optional ``--delimiter`` and ``--quotechar`` options. See :ref:`cli_insert_csv_tsv_delimiter`. (:issue:`223`)
-
-.. _v3_3:
-
-3.3 (2021-01-17)
-----------------
-
-- The ``table.m2m()`` method now accepts an optional ``alter=True`` argument to specify that any missing columns should be added to the referenced table. See :ref:`python_api_m2m`. (:issue:`222`)
-
-.. _v3_2_1:
-
-3.2.1 (2021-01-12)
-------------------
-
-- Fixed a bug where ``.add_missing_columns()`` failed to take case insensitive column names into account. (:issue:`221`)
-
-.. _v3_2:
-
-3.2 (2021-01-03)
-----------------
-
-This release introduces a new mechanism for speeding up ``count(*)`` queries using cached table counts, stored in a ``_counts`` table and updated by triggers. This mechanism is described in :ref:`python_api_cached_table_counts`, and can be enabled using Python API methods or the new ``enable-counts`` CLI command. (:issue:`212`)
-
-- ``table.enable_counts()`` method for enabling these triggers on a specific table.
-- ``db.enable_counts()`` method for enabling triggers on every table in the database. (:issue:`213`)
-- New ``sqlite-utils enable-counts my.db`` command for enabling counts on all or specific tables, see :ref:`cli_enable_counts`. (:issue:`214`)
-- New ``sqlite-utils triggers`` command for listing the triggers defined for a database or specific tables, see :ref:`cli_triggers`. (:issue:`218`)
-- New ``db.use_counts_table`` property which, if ``True``, causes ``table.count`` to read from the ``_counts`` table. (:issue:`215`)
-- ``table.has_counts_triggers`` property revealing if a table has been configured with the new ``_counts`` database triggers.
-- ``db.reset_counts()`` method and ``sqlite-utils reset-counts`` command for resetting the values in the ``_counts`` table. (:issue:`219`)
-- The previously undocumented ``db.escape()`` method has been renamed to ``db.quote()`` and is now covered by the documentation: :ref:`python_api_quote`. (:issue:`217`)
-- New ``table.triggers_dict`` and ``db.triggers_dict`` introspection properties. (:issue:`211`, :issue:`216`)
-- ``sqlite-utils insert`` now shows a more useful error message for invalid JSON. (:issue:`206`)
-
-.. _v3_1_1:
-
-3.1.1 (2021-01-01)
-------------------
-
-- Fixed failing test caused by ``optimize`` sometimes creating larger database files. (:issue:`209`)
-- Documentation now lives on https://sqlite-utils.datasette.io/
-- README now includes ``brew install sqlite-utils`` installation method.
-
-.. _v3_1:
-
-3.1 (2020-12-12)
-----------------
-
-- New command: ``sqlite-utils analyze-tables my.db`` outputs useful information about the table columns in the database, such as the number of distinct values and how many rows are null. See :ref:`cli_analyze_tables` for documentation. (:issue:`207`)
-- New ``table.analyze_column(column)`` Python method used by the ``analyze-tables`` command - see :ref:`python_api_analyze_column`.
-- The ``table.update()`` method now correctly handles values that should be stored as JSON. Thanks, Andreas Madsack. (`#204 `__)
-
-.. _v3_0:
-
-3.0 (2020-11-08)
-----------------
-
-This release introduces a new ``sqlite-utils search`` command for searching tables, see :ref:`cli_search`. (:issue:`192`)
-
-The ``table.search()`` method has been redesigned, see :ref:`python_api_fts_search`. (:issue:`197`)
-
-The release includes minor backwards-incompatible changes, hence the version bump to 3.0. Those changes, which should not affect most users, are:
-
-- The ``-c`` shortcut option for outputting CSV is no longer available. The full ``--csv`` option is required instead.
-- The ``-f`` shortcut for ``--fmt`` has also been removed - use ``--fmt``.
-- The ``table.search()`` method now defaults to sorting by relevance, not sorting by ``rowid``. (:issue:`198`)
-- The ``table.search()`` method now returns a generator over a list of Python dictionaries. It previously returned a list of tuples.
-
-Also in this release:
-
-- The ``query``, ``tables``, ``rows`` and ``search`` CLI commands now accept a new ``--tsv`` option which outputs the results in TSV. (:issue:`193`)
-- A new ``table.virtual_table_using`` property reveals if a table is a virtual table, and returns the upper case type of virtual table (e.g. ``FTS4`` or ``FTS5``) if it is. It returns ``None`` if the table is not a virtual table. (:issue:`196`)
-- The new ``table.search_sql()`` method returns the SQL for searching a table, see :ref:`python_api_fts_search_sql`.
-- ``sqlite-utils rows`` now accepts multiple optional ``-c`` parameters specifying the columns to return. (:issue:`200`)
-
-Changes since the 3.0a0 alpha release:
-
-- The ``sqlite-utils search`` command now defaults to returning every result, unless you add a ``--limit 20`` option.
-- The ``sqlite-utils search -c`` and ``table.search(columns=[])`` options are now fully respected. (:issue:`201`)
-
-.. _v2_23:
-
-2.23 (2020-10-28)
------------------
-
-- ``table.m2m(other_table, records)`` method now takes any iterable, not just a list or tuple. Thanks, Adam Wolf. (`#189 `__)
-- ``sqlite-utils insert`` now displays a progress bar for CSV or TSV imports. (:issue:`173`)
-- New ``@db.register_function(deterministic=True)`` option for registering deterministic SQLite functions in Python 3.8 or higher. (:issue:`191`)
-
-.. _v2_22:
-
-2.22 (2020-10-16)
------------------
-
-- New ``--encoding`` option for processing CSV and TSV files that use a non-utf-8 encoding, for both the ``insert`` and ``update`` commands. (:issue:`182`)
-- The ``--load-extension`` option is now available to many more commands. (:issue:`137`)
-- ``--load-extension=spatialite`` can be used to load SpatiaLite from common installation locations, if it is available. (:issue:`136`)
-- Tests now also run against Python 3.9. (:issue:`184`)
-- Passing ``pk=["id"]`` now has the same effect as passing ``pk="id"``. (:issue:`181`)
-
-.. _v2_21:
-
-2.21 (2020-09-24)
------------------
-
-- ``table.extract()`` and ``sqlite-utils extract`` now apply much, much faster - one example operation reduced from twelve minutes to just four seconds! (:issue:`172`)
-- ``sqlite-utils extract`` no longer shows a progress bar, because it's fast enough not to need one.
-- New ``column_order=`` option for ``table.transform()`` which can be used to alter the order of columns in a table. (:issue:`175`)
-- ``sqlite-utils transform --column-order=`` option (with a ``-o`` shortcut) for changing column order. (:issue:`176`)
-- The ``table.transform(drop_foreign_keys=)`` parameter and the ``sqlite-utils transform --drop-foreign-key`` option have changed. They now accept just the name of the column rather than requiring all three of the column, other table and other column. This is technically a backwards-incompatible change but I chose not to bump the major version number because the transform feature is so new. (:issue:`177`)
-- The table ``.disable_fts()``, ``.rebuild_fts()``, ``.delete()``, ``.delete_where()`` and ``.add_missing_columns()`` methods all now ``return self``, which means they can be chained together with other table operations.
-
-.. _v2_20:
-
-2.20 (2020-09-22)
------------------
-
-This release introduces two key new capabilities: **transform** (:issue:`114`) and **extract** (:issue:`42`).
-
-Transform
-~~~~~~~~~
-
-SQLite's ALTER TABLE has `several documented limitations `__. The ``table.transform()`` Python method and ``sqlite-utils transform`` CLI command work around these limitations using a pattern where a new table with the desired structure is created, data is copied over to it and the old table is then dropped and replaced by the new one.
-
-You can use these tools to change column types, rename columns, drop columns, add and remove ``NOT NULL`` and defaults, remove foreign key constraints and more. See the :ref:`transforming tables (CLI) ` and :ref:`transforming tables (Python library) ` documentation for full details of how to use them.
-
-Extract
-~~~~~~~
-
-Sometimes a database table - especially one imported from a CSV file - will contain duplicate data. A ``Trees`` table may include a ``Species`` column with only a few dozen unique values, when the table itself contains thousands of rows.
-
-The ``table.extract()`` method and ``sqlite-utils extract`` commands can extract a column - or multiple columns - out into a separate lookup table, and set up a foreign key relationship from the original table.
-
-The Python library :ref:`extract() documentation ` describes how extraction works in detail, and :ref:`cli_extract` in the CLI documentation includes a detailed example.
-
-Other changes
-~~~~~~~~~~~~~
-
-- The ``@db.register_function`` decorator can be used to quickly register Python functions as custom SQL functions, see :ref:`python_api_register_function`. (:issue:`162`)
-- The ``table.rows_where()`` method now accepts an optional ``select=`` argument for specifying which columns should be selected, see :ref:`python_api_rows`.
-
-.. _v2_19:
-
-2.19 (2020-09-20)
------------------
-
-- New ``sqlite-utils add-foreign-keys`` command for :ref:`cli_add_foreign_keys`. (:issue:`157`)
-- New ``table.enable_fts(..., replace=True)`` argument for replacing an existing FTS table with a new configuration. (:issue:`160`)
-- New ``table.add_foreign_key(..., ignore=True)`` argument for ignoring a foreign key if it already exists. (:issue:`112`)
-
-.. _v2_18:
-
-2.18 (2020-09-08)
------------------
-
-- ``table.rebuild_fts()`` method for rebuilding a FTS index, see :ref:`python_api_fts_rebuild`. (:issue:`155`)
-- ``sqlite-utils rebuild-fts data.db`` command for rebuilding FTS indexes across all tables, or just specific tables. (:issue:`155`)
-- ``table.optimize()`` method no longer deletes junk rows from the ``*_fts_docsize`` table. This was added in 2.17 but it turns out running ``table.rebuild_fts()`` is a better solution to this problem.
-- Fixed a bug where rows with additional columns that are inserted after the first batch of records could cause an error due to breaking SQLite's maximum number of parameters. Thanks, Simon Wiles. (:issue:`145`)
-
-.. _v2_17:
-
-2.17 (2020-09-07)
------------------
-
-This release handles a bug where replacing rows in FTS tables could result in growing numbers of unnecessary rows in the associated ``*_fts_docsize`` table. (:issue:`149`)
-
-- ``PRAGMA recursive_triggers=on`` by default for all connections. You can turn it off with ``Database(recursive_triggers=False)``. (:issue:`152`)
-- ``table.optimize()`` method now deletes unnecessary rows from the ``*_fts_docsize`` table. (:issue:`153`)
-- New tracer method for tracking underlying SQL queries, see :ref:`python_api_tracing`. (:issue:`150`)
-- Neater indentation for schema SQL. (:issue:`148`)
-- Documentation for ``sqlite_utils.AlterError`` exception thrown by in ``add_foreign_keys()``.
-
-.. _v2_16_1:
-
-2.16.1 (2020-08-28)
--------------------
-
-- ``insert_all(..., alter=True)`` now works for columns introduced after the first 100 records. Thanks, Simon Wiles! (:issue:`139`)
-- Continuous Integration is now powered by GitHub Actions. (:issue:`143`)
-
-.. _v2_16:
-
-2.16 (2020-08-21)
------------------
-
-- ``--load-extension`` option for ``sqlite-utils query`` for loading SQLite extensions. (:issue:`134`)
-- New ``sqlite_utils.utils.find_spatialite()`` function for finding SpatiaLite in common locations. (:issue:`135`)
-
-.. _v2_15_1:
-
-2.15.1 (2020-08-12)
--------------------
-
-- Now available as a ``sdist`` package on PyPI in addition to a wheel. (:issue:`133`)
-
-.. _v2_15:
-
-2.15 (2020-08-10)
------------------
-
-- New ``db.enable_wal()`` and ``db.disable_wal()`` methods for enabling and disabling `Write-Ahead Logging `__ for a database file - see :ref:`python_api_wal` in the Python API documentation.
-- Also ``sqlite-utils enable-wal file.db`` and ``sqlite-utils disable-wal file.db`` commands for doing the same thing on the command-line, see :ref:`WAL mode (CLI) `. (:issue:`132`)
-
-.. _v2_14_1:
-
-2.14.1 (2020-08-05)
--------------------
-
-- Documentation improvements.
-
-.. _v2_14:
-
-2.14 (2020-08-01)
------------------
-
-- The :ref:`insert-files command ` can now read from standard input: ``cat dog.jpg | sqlite-utils insert-files dogs.db pics - --name=dog.jpg``. (:issue:`127`)
-- You can now specify a full-text search tokenizer using the new ``tokenize=`` parameter to :ref:`enable_fts() `. This means you can enable Porter stemming on a table by running ``db["articles"].enable_fts(["headline", "body"], tokenize="porter")``. (:issue:`130`)
-- You can also set a custom tokenizer using the :ref:`sqlite-utils enable-fts ` CLI command, via the new ``--tokenize`` option.
-
-.. _v2_13:
-
-2.13 (2020-07-29)
------------------
-
-- ``memoryview`` and ``uuid.UUID`` objects are now supported. ``memoryview`` objects will be stored using ``BLOB`` and ``uuid.UUID`` objects will be stored using ``TEXT``. (:issue:`128`)
-
-.. _v2_12:
-
-2.12 (2020-07-27)
------------------
-
-The theme of this release is better tools for working with binary data. The new ``insert-files`` command can be used to insert binary files directly into a database table, and other commands have been improved with better support for BLOB columns.
-
-- ``sqlite-utils insert-files my.db gifs *.gif`` can now insert the contents of files into a specified table. The columns in the table can be customized to include different pieces of metadata derived from the files. See :ref:`cli_insert_files`. (:issue:`122`)
-- ``--raw`` option to ``sqlite-utils query`` - for outputting just a single raw column value - see :ref:`cli_query_raw`. (:issue:`123`)
-- JSON output now encodes BLOB values as special base64 objects - see :ref:`cli_query_json`. (:issue:`125`)
-- The same format of JSON base64 objects can now be used to insert binary data - see :ref:`cli_inserting_data`. (:issue:`126`)
-- The ``sqlite-utils query`` command can now accept named parameters, e.g. ``sqlite-utils :memory: "select :num * :num2" -p num 5 -p num2 6`` - see :ref:`cli_query_json`. (:issue:`124`)
-
-.. _v2_11:
-
-2.11 (2020-07-08)
------------------
-
-- New ``--truncate`` option to ``sqlite-utils insert``, and ``truncate=True`` argument to ``.insert_all()``. Thanks, Thomas Sibley. (`#118 `__)
-- The ``sqlite-utils query`` command now runs updates in a transaction. Thanks, Thomas Sibley. (`#120 `__)
-
-.. _v2_10_1:
-
-2.10.1 (2020-06-23)
--------------------
-
-- Added documentation for the ``table.pks`` introspection property. (:issue:`116`)
-
-.. _v2_10:
-
-2.10 (2020-06-12)
------------------
-
-- The ``sqlite-utils`` command now supports UPDATE/INSERT/DELETE in addition to SELECT. (:issue:`115`)
-
-.. _v2_9_1:
-
-2.9.1 (2020-05-11)
-------------------
-
-- Added custom project links to the `PyPI listing `__.
-
-.. _v2_9:
-
-2.9 (2020-05-10)
-----------------
-
-- New ``sqlite-utils drop-table`` command, see :ref:`cli_drop_table`. (:issue:`111`)
-- New ``sqlite-utils drop-view`` command, see :ref:`cli_drop_view`.
-- Python ``decimal.Decimal`` objects are now stored as ``FLOAT``. (:issue:`110`)
-
-.. _v2_8:
-
-2.8 (2020-05-03)
-----------------
-
-- New ``sqlite-utils create-table`` command, see :ref:`cli_create_table`. (:issue:`27`)
-- New ``sqlite-utils create-view`` command, see :ref:`cli_create_view`. (:issue:`107`)
-
-.. _v2_7.2:
-
-2.7.2 (2020-05-02)
-------------------
-
-- ``db.create_view(...)`` now has additional parameters ``ignore=True`` or ``replace=True``, see :ref:`python_api_create_view`. (:issue:`106`)
-
-.. _v2_7.1:
-
-2.7.1 (2020-05-01)
-------------------
-
-- New ``sqlite-utils views my.db`` command for listing views in a database, see :ref:`cli_views`. (:issue:`105`)
-- ``sqlite-utils tables`` (and ``views``) has a new ``--schema`` option which outputs the table/view schema, see :ref:`cli_tables`. (:issue:`104`)
-- Nested structures containing invalid JSON values (e.g. Python bytestrings) are now serialized using ``repr()`` instead of throwing an error. (:issue:`102`)
-
-.. _v2_7:
-
-2.7 (2020-04-17)
-----------------
-
-- New ``columns=`` argument for the ``.insert()``, ``.insert_all()``, ``.upsert()`` and ``.upsert_all()`` methods, for over-riding the auto-detected types for columns and specifying additional columns that should be added when the table is created. See :ref:`python_api_custom_columns`. (:issue:`100`)
-
-.. _v2_6:
-
-2.6 (2020-04-15)
-----------------
-
-- New ``table.rows_where(..., order_by="age desc")`` argument, see :ref:`python_api_rows`. (:issue:`76`)
-
-.. _v2_5:
-
-2.5 (2020-04-12)
-----------------
-
-- Panda's Timestamp is now stored as a SQLite TEXT column. Thanks, b0b5h4rp13! (:issue:`96`)
-- ``table.last_pk`` is now only available for inserts or upserts of a single record. (:issue:`98`)
-- New ``Database(filepath, recreate=True)`` parameter for deleting and recreating the database. (:issue:`97`)
-
-.. _v2_4_4:
-
-2.4.4 (2020-03-23)
-------------------
-
-- Fixed bug where columns with only null values were not correctly created. (:issue:`95`)
-
-.. _v2_4_3:
-
-2.4.3 (2020-03-23)
-------------------
-
-- Column type suggestion code is no longer confused by null values. (:issue:`94`)
-
-.. _v2_4_2:
-
-2.4.2 (2020-03-14)
-------------------
-
-- ``table.column_dicts`` now works with all column types - previously it would throw errors on types other than ``TEXT``, ``BLOB``, ``INTEGER`` or ``FLOAT``. (:issue:`92`)
-- Documentation for ``NotFoundError`` thrown by ``table.get(pk)`` - see :ref:`python_api_get`.
-
-.. _v2_4_1:
-
-2.4.1 (2020-03-01)
-------------------
-
-- ``table.enable_fts()`` now works with columns that contain spaces. (:issue:`90`)
-
-.. _v2_4:
-
-2.4 (2020-02-26)
-----------------
-
-- ``table.disable_fts()`` can now be used to remove FTS tables and triggers that were created using ``table.enable_fts(...)``. (:issue:`88`)
-- The ``sqlite-utils disable-fts`` command can be used to remove FTS tables and triggers from the command-line. (:issue:`88`)
-- Trying to create table columns with square braces ([ or ]) in the name now raises an error. (:issue:`86`)
-- Subclasses of ``dict``, ``list`` and ``tuple`` are now detected as needing a JSON column. (:issue:`87`)
-
-.. _v2_3_1:
-
-2.3.1 (2020-02-10)
-------------------
-
-``table.create_index()`` now works for columns that contain spaces. (:issue:`85`)
-
-.. _v2_3:
-
-2.3 (2020-02-08)
-----------------
-
-``table.exists()`` is now a method, not a property. This was not a documented part of the API before so I'm considering this a non-breaking change. (:issue:`83`)
-
-.. _v2_2_1:
-
-2.2.1 (2020-02-06)
-------------------
-
-Fixed a bug where ``.upsert(..., hash_id="pk")`` threw an error (:issue:`84`).
-
-.. _v2_2:
-
-2.2 (2020-02-01)
-----------------
-
-New feature: ``sqlite_utils.suggest_column_types([records])`` returns the suggested column types for a list of records. See :ref:`python_api_suggest_column_types`. (:issue:`81`).
-
-This replaces the undocumented ``table.detect_column_types()`` method.
-
-.. _v2_1:
-
-2.1 (2020-01-30)
-----------------
-
-New feature: ``conversions={...}`` can be passed to the ``.insert()`` family of functions to specify SQL conversions that should be applied to values that are being inserted or updated. See :ref:`python_api_conversions` . (`#77 `__).
-
-.. _v2_0_1:
-
-2.0.1 (2020-01-05)
-------------------
-
-The ``.upsert()`` and ``.upsert_all()`` methods now raise a ``sqlite_utils.db.PrimaryKeyRequired`` exception if you call them without specifying the primary key column using ``pk=`` (:issue:`73`).
-
-.. _v2:
-
-2.0 (2019-12-29)
-----------------
-
-This release changes the behaviour of ``upsert``. It's a breaking change, hence ``2.0``.
-
-The ``upsert`` command-line utility and the ``.upsert()`` and ``.upsert_all()`` Python API methods have had their behaviour altered. They used to completely replace the affected records: now, they update the specified values on existing records but leave other columns unaffected.
-
-See :ref:`Upserting data using the Python API ` and :ref:`Upserting data using the CLI ` for full details.
-
-If you want the old behaviour - where records were completely replaced - you can use ``$ sqlite-utils insert ... --replace`` on the command-line and ``.insert(..., replace=True)`` and ``.insert_all(..., replace=True)`` in the Python API. See :ref:`Insert-replacing data using the Python API ` and :ref:`Insert-replacing data using the CLI ` for more.
-
-For full background on this change, see `issue #66 `__.
-
.. _v1_12_1:
1.12.1 (2019-11-06)
-------------------
-- Fixed error thrown when ``.insert_all()`` and ``.upsert_all()`` were called with empty lists (:issue:`52`)
+- Fixed error thrown when ``.insert_all()`` and ``.upsert_all()`` were called with empty lists (`#52 `__)
.. _v1_12:
1.12 (2019-11-04)
-----------------
-Python library utilities for deleting records (:issue:`62`)
+Python library utilities for deleting records (`#62 `__)
- ``db["tablename"].delete(4)`` to delete by primary key, see :ref:`python_api_delete`
- ``db["tablename"].delete_where("id > ?", [3])`` to delete by a where clause, see :ref:`python_api_delete_where`
@@ -1239,14 +28,14 @@ Option to create triggers to automatically keep FTS tables up-to-date with newly
- ``sqlite-utils enable-fts ... --create-triggers`` - see :ref:`Configuring full-text search using the CLI `
- ``db["tablename"].enable_fts(..., create_triggers=True)`` - see :ref:`Configuring full-text search using the Python library `
-- Support for introspecting triggers for a database or table - see :ref:`python_api_introspection` (:issue:`59`)
+- Support for introspecting triggers for a database or table - see :ref:`python_api_introspection` (`#59 `__)
.. _v1_10:
1.10 (2019-08-23)
-----------------
-Ability to introspect and run queries against views (:issue:`54`)
+Ability to introspect and run queries against views (`#54 `__)
- ``db.view_names()`` method and and ``db.views`` property
- Separate ``View`` and ``Table`` classes, both subclassing new ``Queryable`` class
@@ -1259,21 +48,21 @@ See :ref:`python_api_views`.
1.9 (2019-08-04)
----------------
-- ``table.m2m(...)`` method for creating many-to-many relationships: :ref:`python_api_m2m` (:issue:`23`)
+- ``table.m2m(...)`` method for creating many-to-many relationships: :ref:`python_api_m2m` (`#23 `__)
.. _v1_8:
1.8 (2019-07-28)
----------------
-- ``table.update(pk, values)`` method: :ref:`python_api_update` (:issue:`35`)
+- ``table.update(pk, values)`` method: :ref:`python_api_update` (`#35 `__)
.. _v1_7_1:
1.7.1 (2019-07-28)
------------------
-- Fixed bug where inserting records with 11 columns in a batch of 100 triggered a "too many SQL variables" error (:issue:`50`)
+- Fixed bug where inserting records with 11 columns in a batch of 100 triggered a "too many SQL variables" error (`#50 `__)
- Documentation and tests for ``table.drop()`` method: :ref:`python_api_drop`
.. _v1_7:
@@ -1283,8 +72,8 @@ See :ref:`python_api_views`.
Support for lookup tables.
-- New ``table.lookup({...})`` utility method for building and querying lookup tables - see :ref:`python_api_lookup_tables` (:issue:`44`)
-- New ``extracts=`` table configuration option, see :ref:`python_api_extracts` (:issue:`46`)
+- New ``table.lookup({...})`` utility method for building and querying lookup tables - see :ref:`python_api_lookup_tables` (`#44 `__)
+- New ``extracts=`` table configuration option, see :ref:`python_api_extracts` (`#46 `__)
- Use `pysqlite3 `__ if it is available, otherwise use ``sqlite3`` from the standard library
- Table options can now be passed to the new ``db.table(name, **options)`` factory function in addition to being passed to ``insert_all(records, **options)`` and friends - see :ref:`python_api_table_configuration`
- In-memory databases can now be created using ``db = Database(memory=True)``
@@ -1294,19 +83,19 @@ Support for lookup tables.
1.6 (2019-07-18)
----------------
-- ``sqlite-utils insert`` can now accept TSV data via the new ``--tsv`` option (:issue:`41`)
+- ``sqlite-utils insert`` can now accept TSV data via the new ``--tsv`` option (`#41 `__)
.. _v1_5:
1.5 (2019-07-14)
----------------
-- Support for compound primary keys (:issue:`36`)
+- Support for compound primary keys (`#36 `__)
- Configure these using the CLI tool by passing ``--pk`` multiple times
- In Python, pass a tuple of columns to the ``pk=(..., ...)`` argument: :ref:`python_api_compound_primary_keys`
-- New ``table.get()`` method for retrieving a record by its primary key: :ref:`python_api_get` (:issue:`39`)
+- New ``table.get()`` method for retrieving a record by its primary key: :ref:`python_api_get` (`#39 `__)
.. _v1_4_1:
@@ -1320,14 +109,14 @@ Support for lookup tables.
1.4 (2019-06-30)
----------------
-- Added ``sqlite-utils index-foreign-keys`` command (:ref:`docs `) and ``db.index_foreign_keys()`` method (:ref:`docs `) (:issue:`33`)
+- Added ``sqlite-utils index-foreign-keys`` command (:ref:`docs `) and ``db.index_foreign_keys()`` method (:ref:`docs `) (`#33 `__)
.. _v1_3:
1.3 (2019-06-28)
----------------
-- New mechanism for adding multiple foreign key constraints at once: :ref:`db.add_foreign_keys() documentation ` (:issue:`31`)
+- New mechanism for adding multiple foreign key constraints at once: :ref:`db.add_foreign_keys() documentation ` (`#31 `__)
.. _v1_2_2:
@@ -1341,15 +130,15 @@ Support for lookup tables.
1.2.1 (2019-06-20)
------------------
-- Check the column exists before attempting to add a foreign key (:issue:`29`)
+- Check the column exists before attempting to add a foreign key (`#29 `__)
.. _v1_2:
1.2 (2019-06-12)
----------------
-- Improved foreign key definitions: you no longer need to specify the ``column``, ``other_table`` AND ``other_column`` to define a foreign key - if you omit the ``other_table`` or ``other_column`` the script will attempt to guess the correct values by introspecting the database. See :ref:`python_api_add_foreign_key` for details. (:issue:`25`)
-- Ability to set ``NOT NULL`` constraints and ``DEFAULT`` values when creating tables (:issue:`24`). Documentation: :ref:`Setting defaults and not null constraints (Python API) `, :ref:`Setting defaults and not null constraints (CLI) `
+- Improved foreign key definitions: you no longer need to specify the ``column``, ``other_table`` AND ``other_column`` to define a foreign key - if you omit the ``other_table`` or ``other_column`` the script will attempt to guess the correct values by instrospecting the database. See :ref:`python_api_add_foreign_key` for details. (`#25 `__)
+- Ability to set ``NOT NULL`` constraints and ``DEFAULT`` values when creating tables (`#24 `__). Documentation: :ref:`Setting defaults and not null constraints (Python API) `, :ref:`Setting defaults and not null constraints (CLI) `
- Support for ``not_null_default=X`` / ``--not-null-default`` for setting a ``NOT NULL DEFAULT 'x'`` when adding a new column. Documentation: :ref:`Adding columns (Python API) `, :ref:`Adding columns (CLI) `
.. _v1_1:
@@ -1357,8 +146,8 @@ Support for lookup tables.
1.1 (2019-05-28)
----------------
-- Support for ``ignore=True`` / ``--ignore`` for ignoring inserted records if the primary key already exists (:issue:`21`) - documentation: :ref:`Inserting data (Python API) `, :ref:`Inserting data (CLI) `
-- Ability to add a column that is a foreign key reference using ``fk=...`` / ``--fk`` (:issue:`16`) - documentation: :ref:`Adding columns (Python API) `, :ref:`Adding columns (CLI) `
+- Support for ``ignore=True`` / ``--ignore`` for ignoring inserted records if the primary key alread exists (`#21 `__) - documentation: :ref:`Inserting data (Python API) `, :ref:`Inserting data (CLI) `
+- Ability to add a column that is a foreign key reference using ``fk=...`` / ``--fk`` (`#16 `__) - documentation: :ref:`Adding columns (Python API) `, :ref:`Adding columns (CLI) `
.. _v1_0_1:
@@ -1539,19 +328,3 @@ 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
deleted file mode 100644
index a4ec402..0000000
--- a/docs/cli-reference.rst
+++ /dev/null
@@ -1,1647 +0,0 @@
-.. _cli_reference:
-
-===============
- CLI reference
-===============
-
-This page lists the ``--help`` for every ``sqlite-utils`` CLI sub-command.
-
-.. contents:: :local:
- :class: this-will-duplicate-information-and-it-is-still-useful-here
-
-.. [[[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", "drop-index",
- "migrate", "enable-fts", "populate-fts", "rebuild-fts", "disable-fts"
- ]
- refs = {
- "query": "cli_query",
- "memory": "cli_memory",
- "insert": [
- "cli_inserting_data", "cli_insert_csv_tsv", "cli_insert_unstructured", "cli_insert_convert"
- ],
- "upsert": "cli_upsert",
- "tables": "cli_tables",
- "views": "cli_views",
- "optimize": "cli_optimize",
- "rows": "cli_rows",
- "triggers": "cli_triggers",
- "indexes": "cli_indexes",
- "enable-fts": "cli_fts",
- "analyze": "cli_analyze",
- "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",
- "create-view": "cli_create_view",
- "drop-view": "cli_drop_view",
- "search": "cli_search",
- "transform": "cli_transform_table",
- "extract": "cli_extract",
- "schema": "cli_schema",
- "insert-files": "cli_insert_files",
- "analyze-tables": "cli_analyze_tables",
- "convert": "cli_convert",
- "add-geometry-column": "cli_spatialite",
- "create-spatial-index": "cli_spatialite_indexes",
- "install": "cli_install",
- "uninstall": "cli_uninstall",
- }
- commands.sort(key = lambda command: go_first.index(command) if command in go_first else 999)
- cog.out("\n")
- for command in commands:
- cog.out(".. _cli_ref_" + command.replace("-", "_") + ":\n\n")
- cog.out(command + "\n")
- cog.out(("=" * len(command)) + "\n\n")
- if command in refs:
- command_refs = refs[command]
- if isinstance(command_refs, str):
- command_refs = [command_refs]
- cog.out(
- "See {}.\n\n".format(
- ", ".join(":ref:`{}`".format(c) for c in command_refs)
- )
- )
- 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")
-.. ]]]
-
-.. _cli_ref_query:
-
-query
-=====
-
-See :ref:`cli_query`.
-
-::
-
- Usage: sqlite-utils query [OPTIONS] PATH SQL
-
- Execute SQL query and return the results as JSON
-
- Example:
-
- sqlite-utils data.db \
- "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
- --nl Output newline-delimited JSON
- --arrays Output rows as arrays instead of objects
- --csv Output CSV
- --tsv Output TSV
- --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, 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 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.
-
-
-.. _cli_ref_memory:
-
-memory
-======
-
-See :ref:`cli_memory`.
-
-::
-
- Usage: sqlite-utils memory [OPTIONS] [PATHS]... SQL
-
- Execute SQL query against an in-memory database, optionally populated by
- imported data
-
- To import data from CSV, TSV or JSON files pass them on the command-line:
-
- sqlite-utils memory one.csv two.json \
- "select * from one join two on one.two_id = two.id"
-
- For data piped into the tool from standard input, use "-" or "stdin":
-
- cat animals.csv | sqlite-utils memory - \
- "select * from stdin where species = 'dog'"
-
- The format of the data will be automatically detected. You can specify the
- format explicitly using :json, :csv, :tsv or :nl (for newline-delimited JSON)
- - for example:
-
- cat animals.csv | sqlite-utils memory stdin:csv places.dat:nl \
- "select * from stdin where place_id in (select id from places)"
-
- Use --schema to view the SQL schema of any imported files:
-
- sqlite-utils memory animals.csv --schema
-
- Options:
- --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":
- 1}} becomes {"foo_bar": 1}
- --nl Output newline-delimited JSON
- --arrays Output rows as arrays instead of objects
- --csv Output CSV
- --tsv Output TSV
- --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, 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
- -n, --no-detect-types Treat all CSV/TSV columns as TEXT
- --schema Show SQL schema for in-memory database
- --dump Dump SQL for in-memory database
- --save FILE Save in-memory database to this file
- --analyze Analyze resulting tables and output results
- --load-extension TEXT Path to SQLite extension, with optional
- :entrypoint
- -h, --help Show this message and exit.
-
-
-.. _cli_ref_insert:
-
-insert
-======
-
-See :ref:`cli_inserting_data`, :ref:`cli_insert_csv_tsv`, :ref:`cli_insert_unstructured`, :ref:`cli_insert_convert`.
-
-::
-
- Usage: sqlite-utils insert [OPTIONS] PATH TABLE [FILE]
-
- Insert records from FILE into a table, creating the table if it does not
- already exist.
-
- Example:
-
- echo '{"name": "Lila"}' | sqlite-utils insert data.db chickens -
-
- By default the input is expected to be a JSON object or array of objects.
-
- - Use --nl for newline-delimited JSON objects
- - Use --csv or --tsv for comma-separated or tab-separated input
- - 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.
-
- Your Python code will be passed a "row" variable representing the imported
- row, and can return a modified row.
-
- This example uses just the name, latitude and longitude columns from a CSV
- file, converting name to upper case and latitude and longitude to floating
- point numbers:
-
- sqlite-utils insert plants.db plants plants.csv --csv --convert '
- return {
- "name": row["name"].upper(),
- "latitude": float(row["latitude"]),
- "longitude": float(row["longitude"]),
- }'
-
- If you are using --lines your code will be passed a "line" variable, and for
- --text a "text" variable.
-
- When using --text your function can return an iterator of rows to insert. This
- example inserts one record per word in the input:
-
- 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
- --import TEXT Python modules to import
- --delimiter TEXT Delimiter to use for CSV files
- --quotechar TEXT Quote character to use for CSV/TSV
- --sniff Detect delimiter and quote character
- --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
- --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
- already exists
- -h, --help Show this message and exit.
-
-
-.. _cli_ref_upsert:
-
-upsert
-======
-
-See :ref:`cli_upsert`.
-
-::
-
- 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 '[
- {"id": 1, "name": "Lila"},
- {"id": 2, "name": "Suna"}
- ]' | sqlite-utils upsert data.db chickens - --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
- --import TEXT Python modules to import
- --delimiter TEXT Delimiter to use for CSV files
- --quotechar TEXT Quote character to use for CSV/TSV
- --sniff Detect delimiter and quote character
- --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
- --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.
-
-
-.. _cli_ref_bulk:
-
-bulk
-====
-
-See :ref:`cli_bulk`.
-
-::
-
- Usage: sqlite-utils bulk [OPTIONS] PATH SQL FILE
-
- Execute parameterized SQL against the provided list of documents.
-
- Example:
-
- echo '[
- {"id": 1, "name": "Lila2"},
- {"id": 2, "name": "Suna2"}
- ]' | sqlite-utils bulk data.db '
- update chickens set name = :name where id = :id
- ' -
-
- Options:
- --batch-size INTEGER Commit every X records
- --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
- --import TEXT Python modules to import
- --delimiter TEXT Delimiter to use for CSV files
- --quotechar TEXT Quote character to use for CSV/TSV
- --sniff Detect delimiter and quote character
- --no-headers CSV file has no header row
- --encoding TEXT Character encoding for input, defaults to utf-8
- --load-extension TEXT Path to SQLite extension, with optional :entrypoint
- -h, --help Show this message and exit.
-
-
-.. _cli_ref_search:
-
-search
-======
-
-See :ref:`cli_search`.
-
-::
-
- Usage: sqlite-utils search [OPTIONS] PATH DBTABLE Q
-
- Execute a full-text search against this table
-
- Example:
-
- sqlite-utils search data.db chickens lila
-
- Options:
- -o, --order TEXT Order by ('column' or 'column desc')
- -c, --column TEXT Columns to return
- --limit INTEGER Number of rows to return - defaults to everything
- --sql Show SQL query that would be run
- --quote Apply FTS quoting rules to search term
- --nl Output newline-delimited JSON
- --arrays Output rows as arrays instead of objects
- --csv Output CSV
- --tsv Output TSV
- --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, 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.
-
-
-.. _cli_ref_transform:
-
-transform
-=========
-
-See :ref:`cli_transform_table`.
-
-::
-
- Usage: sqlite-utils transform [OPTIONS] PATH TABLE
-
- Transform a table beyond the capabilities of ALTER TABLE
-
- Example:
-
- sqlite-utils transform mydb.db mytable \
- --drop column1 \
- --rename column2 column_renamed
-
- Options:
- --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:
-
-extract
-=======
-
-See :ref:`cli_extract`.
-
-::
-
- Usage: sqlite-utils extract [OPTIONS] PATH TABLE COLUMNS...
-
- Extract one or more columns into a separate table
-
- Example:
-
- sqlite-utils extract trees.db Street_Trees species
-
- Options:
- --table TEXT Name of the other table to extract columns to
- --fk-column TEXT Name of the foreign key column to add to the table
- --rename ... Rename this column in extracted table
- --load-extension TEXT Path to SQLite extension, with optional :entrypoint
- -h, --help Show this message and exit.
-
-
-.. _cli_ref_schema:
-
-schema
-======
-
-See :ref:`cli_schema`.
-
-::
-
- Usage: sqlite-utils schema [OPTIONS] PATH [TABLES]...
-
- Show full schema for this database or for specified tables
-
- Example:
-
- sqlite-utils schema trees.db
-
- Options:
- --load-extension TEXT Path to SQLite extension, with optional :entrypoint
- -h, --help Show this message and exit.
-
-
-.. _cli_ref_insert_files:
-
-insert-files
-============
-
-See :ref:`cli_insert_files`.
-
-::
-
- Usage: sqlite-utils insert-files [OPTIONS] PATH TABLE FILE_OR_DIR...
-
- Insert one or more files using BLOB columns in the specified table
-
- Example:
-
- sqlite-utils insert-files pics.db images *.gif \
- -c name:name \
- -c content:content \
- -c content_hash:sha256 \
- -c created:ctime_iso \
- -c modified:mtime_iso \
- -c size:size \
- --pk name
-
- Options:
- -c, --column TEXT Column definitions for the table
- --pk TEXT Column to use as primary key
- --alter Alter table to add missing columns
- --replace Replace files with matching primary key
- --upsert Upsert files with matching primary key
- --name TEXT File name to use
- --text Store file content as TEXT, not BLOB
- --encoding TEXT Character encoding for input, defaults to utf-8
- -s, --silent Don't show a progress bar
- --load-extension TEXT Path to SQLite extension, with optional :entrypoint
- -h, --help Show this message and exit.
-
-
-.. _cli_ref_analyze_tables:
-
-analyze-tables
-==============
-
-See :ref:`cli_analyze_tables`.
-
-::
-
- Usage: sqlite-utils analyze-tables [OPTIONS] PATH [TABLES]...
-
- Analyze the columns in one or more tables
-
- Example:
-
- sqlite-utils analyze-tables data.db trees
-
- Options:
- -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:
-
-convert
-=======
-
-See :ref:`cli_convert`.
-
-::
-
- Usage: sqlite-utils convert [OPTIONS] DB_PATH TABLE COLUMNS... CODE
-
- Convert columns using Python code you supply. For example:
-
- 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: 'str', delimiter: 'str' = ',', type: 'Callable[[str],
- object]' = ) -> 'str'
-
- Convert a string like a,b,c into a JSON array ["a", "b", "c"]
-
- 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
-
- 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
-
- You can use these recipes like so:
-
- sqlite-utils convert my.db mytable mycolumn \
- 'r.jsonsplit(value, delimiter=":")'
-
- Options:
- --import TEXT Python modules to import
- --dry-run Show results of running this against first 10
- rows
- --multi Populate columns for keys in returned
- dictionary
- --where TEXT Optional where clause
- -p, --param ... Named :parameters for where clause
- --output TEXT Optional separate column to populate with the
- output
- --output-type [integer|float|blob|text]
- 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.
-
-
-.. _cli_ref_tables:
-
-tables
-======
-
-See :ref:`cli_tables`.
-
-::
-
- Usage: sqlite-utils tables [OPTIONS] PATH
-
- List the tables in the database
-
- Example:
-
- sqlite-utils tables trees.db
-
- Options:
- --fts4 Just show FTS4 enabled tables
- --fts5 Just show FTS5 enabled tables
- --counts Include row counts per table
- --nl Output newline-delimited JSON
- --arrays Output rows as arrays instead of objects
- --csv Output CSV
- --tsv Output TSV
- --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, 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
- -h, --help Show this message and exit.
-
-
-.. _cli_ref_views:
-
-views
-=====
-
-See :ref:`cli_views`.
-
-::
-
- Usage: sqlite-utils views [OPTIONS] PATH
-
- List the views in the database
-
- Example:
-
- sqlite-utils views trees.db
-
- Options:
- --counts Include row counts per view
- --nl Output newline-delimited JSON
- --arrays Output rows as arrays instead of objects
- --csv Output CSV
- --tsv Output TSV
- --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, 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
- -h, --help Show this message and exit.
-
-
-.. _cli_ref_rows:
-
-rows
-====
-
-See :ref:`cli_rows`.
-
-::
-
- Usage: sqlite-utils rows [OPTIONS] PATH DBTABLE
-
- Output all rows in the specified table
-
- Example:
-
- sqlite-utils rows trees.db Trees
-
- Options:
- -c, --column TEXT Columns to return
- --where TEXT Optional where clause
- -o, --order TEXT Order by ('column' or 'column desc')
- -p, --param ... Named :parameters for where clause
- --limit INTEGER Number of rows to return - defaults to everything
- --offset INTEGER SQL offset to use
- --nl Output newline-delimited JSON
- --arrays Output rows as arrays instead of objects
- --csv Output CSV
- --tsv Output TSV
- --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, 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.
-
-
-.. _cli_ref_triggers:
-
-triggers
-========
-
-See :ref:`cli_triggers`.
-
-::
-
- Usage: sqlite-utils triggers [OPTIONS] PATH [TABLES]...
-
- Show triggers configured in this database
-
- Example:
-
- sqlite-utils triggers trees.db
-
- Options:
- --nl Output newline-delimited JSON
- --arrays Output rows as arrays instead of objects
- --csv Output CSV
- --tsv Output TSV
- --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, 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.
-
-
-.. _cli_ref_indexes:
-
-indexes
-=======
-
-See :ref:`cli_indexes`.
-
-::
-
- Usage: sqlite-utils indexes [OPTIONS] PATH [TABLES]...
-
- Show indexes for the whole database or specific tables
-
- Example:
-
- sqlite-utils indexes trees.db Trees
-
- Options:
- --aux Include auxiliary columns
- --nl Output newline-delimited JSON
- --arrays Output rows as arrays instead of objects
- --csv Output CSV
- --tsv Output TSV
- --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, 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.
-
-
-.. _cli_ref_create_database:
-
-create-database
-===============
-
-See :ref:`cli_create_database`.
-
-::
-
- Usage: sqlite-utils create-database [OPTIONS] PATH
-
- Create a new empty database file
-
- Example:
-
- sqlite-utils create-database trees.db
-
- Options:
- --enable-wal Enable WAL mode on the created database
- --init-spatialite Enable SpatiaLite on the created database
- --load-extension TEXT Path to SQLite extension, with optional :entrypoint
- -h, --help Show this message and exit.
-
-
-.. _cli_ref_create_table:
-
-create-table
-============
-
-See :ref:`cli_create_table`.
-
-::
-
- Usage: sqlite-utils create-table [OPTIONS] PATH TABLE COLUMNS...
-
- Add a table with the specified columns. Columns should be specified using
- name, type pairs, for example:
-
- sqlite-utils create-table my.db people \
- id integer \
- name text \
- height real \
- photo blob --pk id
-
- Valid column types are text, integer, real, float and blob.
-
- Options:
- --pk TEXT Column to use as primary key
- --not-null TEXT Columns that should be created as NOT NULL
- --default ... Default value that should be set for a column
- --fk ... Column, other table, other column to set as a
- foreign key
- --ignore If table already exists, do nothing
- --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.
-
-
-.. _cli_ref_create_index:
-
-create-index
-============
-
-See :ref:`cli_create_index`.
-
-::
-
- Usage: sqlite-utils create-index [OPTIONS] PATH TABLE COLUMN...
-
- Add an index to the specified table for the specified columns
-
- Example:
-
- sqlite-utils create-index chickens.db chickens name
-
- To create an index in descending order:
-
- sqlite-utils create-index chickens.db chickens -- -name
-
- Options:
- --name TEXT Explicit name for the new index
- --unique Make this a unique index
- --if-not-exists, --ignore Ignore if index already exists
- --analyze Run ANALYZE after creating the index
- --load-extension TEXT Path to SQLite extension, with optional :entrypoint
- -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
-==========
-
-See :ref:`cli_fts`.
-
-::
-
- Usage: sqlite-utils enable-fts [OPTIONS] PATH TABLE COLUMN...
-
- Enable full-text search for specific table and columns
-
- Example:
-
- sqlite-utils enable-fts chickens.db chickens name
-
- Options:
- --fts4 Use FTS4
- --fts5 Use FTS5
- --tokenize TEXT Tokenizer to use, e.g. porter
- --create-triggers Create triggers to update the FTS tables when the
- parent table changes.
- --replace Replace existing FTS configuration if it exists
- --load-extension TEXT Path to SQLite extension, with optional :entrypoint
- -h, --help Show this message and exit.
-
-
-.. _cli_ref_populate_fts:
-
-populate-fts
-============
-
-::
-
- Usage: sqlite-utils populate-fts [OPTIONS] PATH TABLE COLUMN...
-
- Re-populate full-text search for specific table and columns
-
- Example:
-
- sqlite-utils populate-fts chickens.db chickens name
-
- Options:
- --load-extension TEXT Path to SQLite extension, with optional :entrypoint
- -h, --help Show this message and exit.
-
-
-.. _cli_ref_rebuild_fts:
-
-rebuild-fts
-===========
-
-::
-
- Usage: sqlite-utils rebuild-fts [OPTIONS] PATH [TABLES]...
-
- Rebuild all or specific full-text search tables
-
- Example:
-
- sqlite-utils rebuild-fts chickens.db chickens
-
- Options:
- --load-extension TEXT Path to SQLite extension, with optional :entrypoint
- -h, --help Show this message and exit.
-
-
-.. _cli_ref_disable_fts:
-
-disable-fts
-===========
-
-::
-
- Usage: sqlite-utils disable-fts [OPTIONS] PATH TABLE
-
- Disable full-text search for specific table
-
- Example:
-
- sqlite-utils disable-fts chickens.db chickens
-
- Options:
- --load-extension TEXT Path to SQLite extension, with optional :entrypoint
- -h, --help Show this message and exit.
-
-
-.. _cli_ref_optimize:
-
-optimize
-========
-
-See :ref:`cli_optimize`.
-
-::
-
- Usage: sqlite-utils optimize [OPTIONS] PATH [TABLES]...
-
- Optimize all full-text search tables and then run VACUUM - should shrink the
- database file
-
- Example:
-
- sqlite-utils optimize chickens.db
-
- Options:
- --no-vacuum Don't run VACUUM
- --load-extension TEXT Path to SQLite extension, with optional :entrypoint
- -h, --help Show this message and exit.
-
-
-.. _cli_ref_analyze:
-
-analyze
-=======
-
-See :ref:`cli_analyze`.
-
-::
-
- Usage: sqlite-utils analyze [OPTIONS] PATH [NAMES]...
-
- Run ANALYZE against the whole database, or against specific named indexes and
- tables
-
- Example:
-
- sqlite-utils analyze chickens.db
-
- Options:
- -h, --help Show this message and exit.
-
-
-.. _cli_ref_vacuum:
-
-vacuum
-======
-
-See :ref:`cli_vacuum`.
-
-::
-
- Usage: sqlite-utils vacuum [OPTIONS] PATH
-
- Run VACUUM against the database
-
- Example:
-
- sqlite-utils vacuum chickens.db
-
- Options:
- -h, --help Show this message and exit.
-
-
-.. _cli_ref_dump:
-
-dump
-====
-
-See :ref:`cli_dump`.
-
-::
-
- Usage: sqlite-utils dump [OPTIONS] PATH
-
- Output a SQL dump of the schema and full contents of the database
-
- Example:
-
- sqlite-utils dump chickens.db
-
- Options:
- --load-extension TEXT Path to SQLite extension, with optional :entrypoint
- -h, --help Show this message and exit.
-
-
-.. _cli_ref_add_column:
-
-add-column
-==========
-
-See :ref:`cli_add_column`.
-
-::
-
- Usage: sqlite-utils add-column [OPTIONS] PATH TABLE COL_NAME
- [integer|int|float|real|text|str|blob|bytes]
-
- Add a column to the specified table
-
- Example:
-
- sqlite-utils add-column chickens.db chickens weight float
-
- Options:
- --fk TEXT Table to reference as a foreign key
- --fk-col TEXT Referenced column on that foreign key table - if
- omitted will automatically use the primary key
- --not-null-default TEXT Add NOT NULL DEFAULT 'TEXT' constraint
- --ignore If column already exists, do nothing
- --load-extension TEXT Path to SQLite extension, with optional :entrypoint
- -h, --help Show this message and exit.
-
-
-.. _cli_ref_add_foreign_key:
-
-add-foreign-key
-===============
-
-See :ref:`cli_add_foreign_key`.
-
-::
-
- Usage: sqlite-utils add-foreign-key [OPTIONS] PATH TABLE COLUMN [OTHER_TABLE]
- [OTHER_COLUMN]
-
- Add a new foreign key constraint to an existing table
-
- Example:
-
- sqlite-utils add-foreign-key my.db books author_id authors id
-
- Options:
- --ignore If foreign key already exists, do nothing
- --load-extension TEXT Path to SQLite extension, with optional :entrypoint
- -h, --help Show this message and exit.
-
-
-.. _cli_ref_add_foreign_keys:
-
-add-foreign-keys
-================
-
-See :ref:`cli_add_foreign_keys`.
-
-::
-
- Usage: sqlite-utils add-foreign-keys [OPTIONS] PATH [FOREIGN_KEY]...
-
- Add multiple new foreign key constraints to a database
-
- Example:
-
- sqlite-utils add-foreign-keys my.db \
- books author_id authors id \
- authors country_id countries id
-
- Options:
- --load-extension TEXT Path to SQLite extension, with optional :entrypoint
- -h, --help Show this message and exit.
-
-
-.. _cli_ref_index_foreign_keys:
-
-index-foreign-keys
-==================
-
-See :ref:`cli_index_foreign_keys`.
-
-::
-
- Usage: sqlite-utils index-foreign-keys [OPTIONS] PATH
-
- Ensure every foreign key column has an index on it
-
- Example:
-
- sqlite-utils index-foreign-keys chickens.db
-
- Options:
- --load-extension TEXT Path to SQLite extension, with optional :entrypoint
- -h, --help Show this message and exit.
-
-
-.. _cli_ref_enable_wal:
-
-enable-wal
-==========
-
-See :ref:`cli_wal`.
-
-::
-
- Usage: sqlite-utils enable-wal [OPTIONS] PATH...
-
- Enable WAL for database files
-
- Example:
-
- sqlite-utils enable-wal chickens.db
-
- Options:
- --load-extension TEXT Path to SQLite extension, with optional :entrypoint
- -h, --help Show this message and exit.
-
-
-.. _cli_ref_disable_wal:
-
-disable-wal
-===========
-
-::
-
- Usage: sqlite-utils disable-wal [OPTIONS] PATH...
-
- Disable WAL for database files
-
- Example:
-
- sqlite-utils disable-wal chickens.db
-
- Options:
- --load-extension TEXT Path to SQLite extension, with optional :entrypoint
- -h, --help Show this message and exit.
-
-
-.. _cli_ref_enable_counts:
-
-enable-counts
-=============
-
-See :ref:`cli_enable_counts`.
-
-::
-
- Usage: sqlite-utils enable-counts [OPTIONS] PATH [TABLES]...
-
- Configure triggers to update a _counts table with row counts
-
- Example:
-
- sqlite-utils enable-counts chickens.db
-
- Options:
- --load-extension TEXT Path to SQLite extension, with optional :entrypoint
- -h, --help Show this message and exit.
-
-
-.. _cli_ref_reset_counts:
-
-reset-counts
-============
-
-::
-
- Usage: sqlite-utils reset-counts [OPTIONS] PATH
-
- Reset calculated counts in the _counts table
-
- Example:
-
- sqlite-utils reset-counts chickens.db
-
- Options:
- --load-extension TEXT Path to SQLite extension, with optional :entrypoint
- -h, --help Show this message and exit.
-
-
-.. _cli_ref_duplicate:
-
-duplicate
-=========
-
-See :ref:`cli_duplicate_table`.
-
-::
-
- Usage: sqlite-utils duplicate [OPTIONS] PATH TABLE NEW_TABLE
-
- Create a duplicate of this table, copying across the schema and all row data.
-
- 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_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
-==========
-
-See :ref:`cli_drop_table`.
-
-::
-
- Usage: sqlite-utils drop-table [OPTIONS] PATH TABLE
-
- Drop the specified table
-
- Example:
-
- sqlite-utils drop-table chickens.db chickens
-
- 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_create_view:
-
-create-view
-===========
-
-See :ref:`cli_create_view`.
-
-::
-
- Usage: sqlite-utils create-view [OPTIONS] PATH VIEW SELECT
-
- Create a view for the provided SELECT query
-
- Example:
-
- sqlite-utils create-view chickens.db heavy_chickens \
- 'select * from chickens where weight > 3'
-
- Options:
- --ignore If view already exists, do nothing
- --replace If view already exists, replace it
- --load-extension TEXT Path to SQLite extension, with optional :entrypoint
- -h, --help Show this message and exit.
-
-
-.. _cli_ref_drop_view:
-
-drop-view
-=========
-
-See :ref:`cli_drop_view`.
-
-::
-
- Usage: sqlite-utils drop-view [OPTIONS] PATH VIEW
-
- Drop the specified view
-
- Example:
-
- sqlite-utils drop-view chickens.db heavy_chickens
-
- Options:
- --ignore If view does not exist, do nothing
- --load-extension TEXT Path to SQLite extension, with optional :entrypoint
- -h, --help Show this message and exit.
-
-
-.. _cli_ref_install:
-
-install
-=======
-
-See :ref:`cli_install`.
-
-::
-
- 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
- -e, --editable TEXT Install a project in editable mode from this path
- -h, --help Show this message and exit.
-
-
-.. _cli_ref_uninstall:
-
-uninstall
-=========
-
-See :ref:`cli_uninstall`.
-
-::
-
- Usage: sqlite-utils uninstall [OPTIONS] PACKAGES...
-
- Uninstall Python packages from the sqlite-utils environment
-
- Options:
- -y, --yes Don't ask for confirmation
- -h, --help Show this message and exit.
-
-
-.. _cli_ref_add_geometry_column:
-
-add-geometry-column
-===================
-
-See :ref:`cli_spatialite`.
-
-::
-
- Usage: sqlite-utils add-geometry-column [OPTIONS] DB_PATH TABLE COLUMN_NAME
-
- Add a SpatiaLite geometry column to an existing table. Requires SpatiaLite
- extension.
-
- By default, this command will try to load the SpatiaLite extension from usual
- paths. To load it from a specific path, use --load-extension.
-
- Options:
- -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
- https://spatialreference.org for details on
- specific projections. [default: 4326]
- --dimensions TEXT Coordinate dimensions. Use XYZ for three-
- dimensional geometries.
- --not-null Add a NOT NULL constraint.
- --load-extension TEXT Path to SQLite extension, with optional
- :entrypoint
- -h, --help Show this message and exit.
-
-
-.. _cli_ref_create_spatial_index:
-
-create-spatial-index
-====================
-
-See :ref:`cli_spatialite_indexes`.
-
-::
-
- Usage: sqlite-utils create-spatial-index [OPTIONS] DB_PATH TABLE COLUMN_NAME
-
- Create a spatial index on a SpatiaLite geometry column. The table and geometry
- column must already exist before trying to add a spatial index.
-
- By default, this command will try to load the SpatiaLite extension from usual
- paths. To load it from a specific path, use --load-extension.
-
- Options:
- --load-extension TEXT Path to SQLite extension, with optional :entrypoint
- -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 2e506dd..10c3345 100644
--- a/docs/cli.rst
+++ b/docs/cli.rst
@@ -6,108 +6,42 @@
The ``sqlite-utils`` command-line tool can be used to manipulate SQLite databases in a number of different ways.
-Once :ref:`installed ` the tool should be available as ``sqlite-utils``. It can also be run using ``python -m sqlite_utils``.
-
-.. contents:: :local:
- :class: this-will-duplicate-information-and-it-is-still-useful-here
-
-.. _cli_query:
-
-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:
-
-.. 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
---------------
+Running queries and returning JSON
+==================================
-The default format returned for queries is JSON:
-
-.. code-block:: bash
-
- sqlite-utils dogs.db "select * from dogs"
-
-.. code-block:: output
+You can execute a SQL query against a database and get the results back as JSON like this::
+ $ sqlite-utils query 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.
+This is the default subcommand for ``sqlite-utils``, so you can instead use this::
-.. _cli_query_nl:
+ $ sqlite-utils dogs.db "select * from dogs"
-Newline-delimited JSON
-~~~~~~~~~~~~~~~~~~~~~~
-
-Use ``--nl`` to get back newline-delimited JSON objects:
-
-.. code-block:: bash
-
- sqlite-utils dogs.db "select * from dogs" --nl
-
-.. code-block:: output
+Use ``--nl`` to get back newline-delimited JSON objects::
+ $ sqlite-utils dogs.db "select * from dogs" --nl
{"id": 1, "age": 4, "name": "Cleo"}
{"id": 2, "age": 2, "name": "Pancakes"}
-.. _cli_query_arrays:
-
-JSON arrays
-~~~~~~~~~~~
-
-You can use ``--arrays`` to request arrays instead of objects:
-
-.. code-block:: bash
-
- sqlite-utils dogs.db "select * from dogs" --arrays
-
-.. code-block:: output
+You can use ``--arrays`` to request ararys instead of objects::
+ $ sqlite-utils dogs.db "select * from dogs" --arrays
[[1, 4, "Cleo"],
[2, 2, "Pancakes"]]
-You can also combine ``--arrays`` and ``--nl``:
-
-.. code-block:: bash
-
- sqlite-utils dogs.db "select * from dogs" --arrays --nl
-
-.. code-block:: output
+You can also combine ``--arrays`` and ``--nl``::
+ $ 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``:
-
-.. code-block:: bash
-
- sqlite-utils dogs.db "select * from dogs" | python -mjson.tool
-
-.. code-block:: output
+If you want to pretty-print the output further, you can pipe it through ``python -mjson.tool``::
+ $ sqlite-utils dogs.db "select * from dogs" | python -mjson.tool
[
{
"id": 1,
@@ -121,69 +55,19 @@ If you want to pretty-print the output further, you can pipe it through ``python
}
]
-.. _cli_query_json_ascii:
+You can run queries against a temporary in-memory database by passing ``:memory:`` as the filename::
-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:
-
-.. code-block:: bash
-
- sqlite-utils dogs.db "select name, content from images" | python -mjson.tool
-
-.. code-block:: output
-
- [
- {
- "name": "transparent.gif",
- "content": {
- "$base64": true,
- "encoded": "R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7"
- }
- }
- ]
+ $ sqlite-utils :memory: "select sqlite_version()"
+ [{"sqlite_version()": "3.29.0"}]
.. _cli_json_values:
Nested JSON values
-~~~~~~~~~~~~~~~~~~
+------------------
-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
+If one of your columns contains JSON, by default it will be returned as an escaped string::
+ $ sqlite-utils dogs.db "select * from dogs" | python -mjson.tool
[
{
"id": 1,
@@ -192,14 +76,9 @@ 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:
-
-.. code-block:: bash
-
- sqlite-utils dogs.db "select * from dogs" --json-cols | python -mjson.tool
-
-.. code-block:: output
+You can use the ``--json-cols`` option to automatically detect these JSON columns and output them as nested JSON data::
+ $ sqlite-utils dogs.db "select * from dogs" --json-cols | python -mjson.tool
[
{
"id": 1,
@@ -217,70 +96,38 @@ You can use the ``--json-cols`` option to automatically detect these JSON column
.. _cli_query_csv:
-Returning CSV or TSV
---------------------
+Running queries and returning 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
+You can use the ``--csv`` option (or ``-c`` shortcut) to return results as CSV::
+ $ 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``:
-
-.. code-block:: bash
-
- sqlite-utils dogs.db "select * from dogs" --csv --no-headers
-
-.. code-block:: output
+This will default to including the column names as a header row. To exclude the headers, use ``--no-headers``::
+ $ 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:
-
-.. code-block:: bash
-
- sqlite-utils dogs.db "select * from dogs" --tsv
-
-.. code-block:: output
-
- id age name
- 1 4 Cleo
- 2 2 Pancakes
-
.. _cli_query_table:
-Table-formatted output
-----------------------
+Running queries and outputting 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
+You can use the ``--table`` option (or ``-t`` shortcut) to output query results as a table::
+ $ 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:
-
-.. code-block:: bash
-
- sqlite-utils dogs.db "select * from dogs" --fmt rst
-
-.. code-block:: output
+You can use the ``--fmt`` (or ``-f``) option to specify different table formats, for example ``rst`` for reStructuredText::
+ $ sqlite-utils dogs.db "select * from dogs" --table --fmt rst
==== ===== ========
id age name
==== ===== ========
@@ -288,851 +135,60 @@ You can use the ``--fmt`` option to specify different table formats, for example
2 2 Pancakes
==== ===== ========
-Available ``--fmt`` options are:
-
-.. [[[cog
- import tabulate
- cog.out("\n" + "\n".join('- ``{}``'.format(t) for t in tabulate.tabulate_formats) + "\n\n")
-.. ]]]
-
-- ``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``
-
-.. [[[end]]]
-
-This list can also be found by running ``sqlite-utils query --help``.
-
-.. _cli_query_raw:
-
-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:
-
-.. 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 name value``:
-
-.. code-block:: bash
-
- sqlite-utils query dogs.db "select :num * :num2" -p num 5 -p num2 6
-
-.. code-block:: output
-
- [{":num * :num2": 30}]
-
-These will be correctly quoted and escaped in the SQL query, providing a safe way to combine other values with SQL.
-
-.. _cli_query_update_insert_delete:
-
-UPDATE, INSERT and DELETE
--------------------------
-
-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
-
- [{"rows_affected": 1}]
-
-.. _cli_query_functions:
-
-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:
-
-.. code-block:: bash
-
- sqlite-utils query sites.db "select url, domain(url) from urls" --functions '
- from urllib.parse import urlparse
-
- def domain(url):
- return urlparse(url).netloc
- '
-
-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
------------------
-
-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
-
- [{"spatialite_version()": "4.3.0a"}]
-
-.. _cli_query_attach:
-
-Attaching additional databases
-------------------------------
-
-SQLite supports cross-database SQL queries, which can join data from tables in more than one database file.
-
-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:
-
-.. code-block:: bash
-
- sqlite-utils dogs.db --attach books books.db \
- 'select * from sqlite_master union all select * from books.sqlite_master'
-
-.. note::
- In Python: :ref:`db.attach() `
-
-.. _cli_memory:
-
-Querying data directly using an in-memory database
-==================================================
-
-The ``sqlite-utils memory`` command works similar to ``sqlite-utils query``, but allows you to execute queries against an in-memory database.
-
-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:
-
-.. code-block:: bash
-
- sqlite-utils memory 'select sqlite_version()'
-
-.. code-block:: output
-
- [{"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``:
-
-.. code-block:: bash
-
- sqlite-utils memory 'select sqlite_version()' --csv
-
-.. code-block:: output
-
- sqlite_version()
- 3.35.5
-
-.. code-block:: bash
-
- sqlite-utils memory 'select sqlite_version()' --fmt grid
-
-.. code-block:: output
-
- +--------------------+
- | sqlite_version() |
- +====================+
- | 3.35.5 |
- +--------------------+
-
-.. _cli_memory_csv_json:
-
-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:
-
-.. code-block:: bash
-
- sqlite-utils memory data.csv "select * from data"
-
-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:
-
-.. code-block:: bash
-
- sqlite-utils memory example.csv "select * from t"
-
-If two files have the same name they will be assigned a numeric suffix:
-
-.. code-block:: bash
-
- sqlite-utils memory foo/data.csv bar/data.csv "select * from data_2"
-
-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"
-
-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, 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:
-
-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:
-
-.. 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:
-
-.. 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:
-
-.. 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``.
-
-``select * from trees.trees where ...`` can then query the ``trees`` table in that database.
-
-The CSV data that was piped into the script is available in the ``stdin`` table, so ``... where rowid in (select id from stdin)`` can be used to return rows from the ``trees`` table that match IDs that were piped in as CSV content.
-
-.. _cli_memory_schema_dump_save:
-
-\-\-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``:
-
-.. 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";
-
-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
-
- dogs.id: (1/3)
-
- Total rows: 2
- Null rows: 0
- Blank rows: 0
-
- Distinct values: 2
-
- dogs.name: (2/3)
-
- Total rows: 2
- Null rows: 0
- Blank rows: 0
-
- Distinct values: 2
-
- dogs.age: (3/3)
-
- Total rows: 2
- Null rows: 0
- Blank rows: 0
-
- 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``:
-
-.. code-block:: bash
-
- sqlite-utils memory dogs.csv --dump
-
-.. code-block:: output
-
- BEGIN TRANSACTION;
- 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";
- COMMIT;
-
-Passing ``--save other.db`` will instead use that SQL to populate a new database file:
-
-.. 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`.
+For a full list of table format options, run ``sqlite-utils query --help``.
.. _cli_rows:
Returning all rows in a table
=============================
-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
+You can return every row in a specified table using the ``rows`` subcommand::
+ $ 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:
-
-.. code-block:: bash
-
- sqlite-utils rows dogs.db dogs -c age -c name
-
-.. code-block:: output
-
- [{"age": 4, "name": "Cleo"},
- {"age": 2, "name": "Pancakes"}]
-
-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
-
- [{"name": "Cleo"}]
-
-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
-
- [{"name": "Cleo"}]
-
-You can define a sort order using ``--order column`` or ``--order 'column desc'``.
-
-Use ``--limit N`` to only return the first ``N`` rows. Use ``--offset N`` to return rows starting from the specified offset.
-
-.. note::
- In Python: :ref:`table.rows ` CLI reference: :ref:`sqlite-utils rows `
+This command accepts the same output options as ``query`` - so you can pass ``--nl``, ``--csv``, ``--no-headers``, ``--table`` and ``--fmt``.
.. _cli_tables:
Listing tables
==============
-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
+You can list the names of tables in a database using the ``tables`` subcommand::
+ $ sqlite-utils tables mydb.db
[{"table": "dogs"},
{"table": "cats"},
{"table": "chickens"}]
-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
+You can output this list in CSV using the ``-csv`` option::
+ $ 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):
-
-.. code-block:: bash
-
- sqlite-utils tables docs.db --fts4
-
-.. code-block:: output
+If you just want to see the FTS4 tables, you can use ``--fts4`` (or ``--fts5`` for FTS5 tables)::
+ $ sqlite-utils tables docs.db --fts4
[{"table": "docs_fts"}]
-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
+Use ``--counts`` to include a count of the number of rows in each table::
+ $ 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:
-
-.. code-block:: bash
-
- sqlite-utils tables dogs.db --counts --columns
-
-.. code-block:: output
+Use ``--columns`` to include a list of columns in each table::
+ $ 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:
-
-.. code-block:: bash
-
- sqlite-utils tables dogs.db --schema --table
-
-.. code-block:: output
-
- 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)
-
-The ``--nl``, ``--csv``, ``--tsv``, ``--table`` and ``--fmt`` options are also available.
-
-.. note::
- In Python: :ref:`db.tables or db.table_names() ` CLI reference: :ref:`sqlite-utils tables `
-
-.. _cli_views:
-
-Listing views
-=============
-
-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
-
- view count columns schema
- --------- ------- -------------------- --------------------------------------------------------------
- demo_view 189144 ['qSpecies'] CREATE VIEW demo_view AS select qSpecies from Street_Tree_List
- hello 1 ['sqlite_version()'] CREATE VIEW hello as select sqlite_version()
-
-It takes the same options as the ``tables`` command:
-
-* ``--columns``
-* ``--schema``
-* ``--counts``
-* ``--nl``
-* ``--csv``
-* ``--tsv``
-* ``--table``
-
-.. note::
- In Python: :ref:`db.views or db.view_names() ` CLI reference: :ref:`sqlite-utils views `
-
-.. _cli_indexes:
-
-Listing indexes
-===============
-
-The ``indexes`` command lists any indexes configured for the database:
-
-.. code-block:: bash
-
- sqlite-utils indexes covid.db --table
-
-.. code-block:: output
-
- 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
- johns_hopkins_csse_daily_reports idx_johns_hopkins_csse_daily_reports_country_or_region 0 1 country_or_region 0 BINARY 1
- johns_hopkins_csse_daily_reports idx_johns_hopkins_csse_daily_reports_province_or_state 0 2 province_or_state 0 BINARY 1
- johns_hopkins_csse_daily_reports idx_johns_hopkins_csse_daily_reports_day 0 0 day 0 BINARY 1
- ny_times_us_counties idx_ny_times_us_counties_date 0 0 date 1 BINARY 1
- ny_times_us_counties idx_ny_times_us_counties_fips 0 3 fips 0 BINARY 1
- 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:
-
-.. 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``.
-
-The command takes the same format options as the ``tables`` and ``views`` commands.
-
-.. note::
- In Python: :ref:`table.indexes ` CLI reference: :ref:`sqlite-utils indexes `
-
-.. _cli_triggers:
-
-Listing triggers
-================
-
-The ``triggers`` command shows any triggers configured for the database:
-
-.. code-block:: bash
-
- sqlite-utils triggers global-power-plants.db --table
-
-.. code-block:: output
-
- name table sql
- --------------- --------- -----------------------------------------------------------------
- plants_insert plants CREATE TRIGGER "plants_insert" AFTER INSERT ON "plants"
- BEGIN
- INSERT OR REPLACE INTO "_counts"
- VALUES (
- 'plants',
- COALESCE(
- (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:
-
-.. code-block:: bash
-
- sqlite-utils triggers global-power-plants.db plants
-
-The command takes the same format options as the ``tables`` and ``views`` commands.
-
-.. note::
- In Python: :ref:`table.triggers or db.triggers ` CLI reference: :ref:`sqlite-utils triggers `
-
-.. _cli_schema:
-
-Showing the schema
-==================
-
-The ``sqlite-utils schema`` command shows the full SQL schema for the database:
-
-.. code-block:: bash
-
- sqlite-utils schema dogs.db
-
-.. code-block:: output
-
- CREATE TABLE "dogs" (
- "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:
-
-.. 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 `
-
-.. _cli_analyze_tables:
-
-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:
-
-.. code-block:: bash
-
- sqlite-utils analyze-tables github.db tags
-
-.. code-block:: output
-
- tags.repo: (1/3)
-
- Total rows: 261
- Null rows: 0
- Blank rows: 0
-
- Distinct values: 14
-
- Most common:
- 88: 107914493
- 75: 140912432
- 27: 206156866
-
- Least common:
- 1: 209590345
- 2: 206649770
- 2: 303218369
-
- tags.name: (2/3)
-
- Total rows: 261
- Null rows: 0
- Blank rows: 0
-
- Distinct values: 175
-
- Most common:
- 10: 0.2
- 9: 0.1
- 7: 0.3
-
- Least common:
- 1: 0.1.1
- 1: 0.11.1
- 1: 0.1a2
-
- tags.sha: (3/3)
-
- Total rows: 261
- Null rows: 0
- Blank rows: 0
-
- Distinct values: 261
-
-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:
-
-.. code-block:: bash
-
- sqlite-utils analyze-tables github.db
-
-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:
-
-.. code-block:: bash
-
- sqlite-utils analyze-tables github.db --save
-
-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:
-
-.. code-block:: json
-
- [
- ["Del Libertador, Av", 5068],
- ["Alberdi Juan Bautista Av.", 4612],
- ["Directorio Av.", 4552],
- ["Rivadavia, Av", 4532],
- ["Yerbal", 4512],
- ["Cosquín", 4472],
- ["Estado Plurinacional de Bolivia", 4440],
- ["Gordillo Timoteo", 4424],
- ["Montiel", 4360],
- ["Condarco", 4288]
- ]
-
-.. _cli_create_database:
-
-Creating an empty database
-==========================
-
-You can create a new empty database file using the ``create-database`` command:
-
-.. code-block:: bash
-
- sqlite-utils create-database empty.db
-
-To enable :ref:`cli_wal` on the newly created database add the ``--enable-wal`` option:
-
-.. code-block:: bash
-
- sqlite-utils create-database empty.db --enable-wal
-
-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
-
-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
+The ``--nl``, ``--csv`` and ``--table`` options are all available.
.. _cli_inserting_data:
@@ -1143,19 +199,15 @@ 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::
-.. code-block:: bash
-
- echo '{"name": "Cleo", "age": 4}' | sqlite-utils insert dogs.db dogs -
+ $ 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:
-
-.. code-block:: json
+If you feed it a JSON list it will insert multiple records. For example, if ``dogs.json`` looks like this::
[
{
@@ -1175,87 +227,26 @@ 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::
-.. code-block:: bash
+ $ sqlite-utils insert dogs.db dogs dogs.json --pk=id
- sqlite-utils insert dogs.db dogs dogs.json --pk=id
+You can skip inserting any records that have a primary key that already exists using ``--ignore``::
-Pass ``--pk`` multiple times to define a compound primary key.
+ $ sqlite-utils insert dogs.db dogs dogs.json --ignore
-You can skip inserting any records that have a primary key that already exists using ``--ignore``:
+You can also import newline-delimited JSON using the ``--nl`` option. Since `Datasette `__ can export newline-delimited JSON, you can combine the two tools like so::
-.. 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:
-
-.. code-block:: json
-
- [
- {
- "name": "transparent.gif",
- "content": {
- "$base64": true,
- "encoded": "R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7"
- }
- }
- ]
-
-.. _cli_inserting_data_nl_json:
-
-Inserting newline-delimited JSON
---------------------------------
-
-You can also import newline-delimited JSON (see `JSON Lines `__) using the ``--nl`` option:
-
-.. 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:
-
-.. code-block:: bash
-
- curl -L "https://latest.datasette.io/fixtures/facetable.json?_shape=array&_nl=on" \
+ $ 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:
+This also means you pipe ``sqlite-utils`` together to easily create a new SQLite database file containing the results of a SQL query against another database::
-.. code-block:: bash
-
- sqlite-utils sf-trees.db \
+ $ sqlite-utils json sf-trees.db \
"select TreeID, qAddress, Latitude, Longitude from Street_Tree_List" --nl \
| sqlite-utils insert saved.db trees - --nl
-
-.. code-block:: bash
-
- sqlite-utils saved.db "select * from trees limit 5" --csv
-
-.. code-block:: output
-
+ # This creates saved.db with a single table called trees:
+ $ sqlite-utils csv saved.db "select * from trees limit 5"
TreeID,qAddress,Latitude,Longitude
141565,501X Baker St,37.7759676911831,-122.441396661871
232565,940 Elizabeth St,37.7517102172731,-122.441498017841
@@ -1263,1312 +254,62 @@ You can also pipe ``sqlite-utils`` together to create a new SQLite database file
207368,920 Kirkham St,37.760210314285,-122.47073935813
188702,1501 Evans Ave,37.7422086702947,-122.387293152263
-.. _cli_inserting_data_flatten:
-
-Flattening nested JSON objects
-------------------------------
-
-``sqlite-utils insert`` and ``sqlite-utils memory`` both expect incoming JSON data to consist of an array of JSON objects, where the top-level keys of each object will become columns in the created database table.
-
-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``:
-
-.. code-block:: json
-
- {
- "httpRequest": {
- "latency": "0.112114537s",
- "requestMethod": "GET",
- "requestSize": "534",
- "status": 200
- },
- "insertId": "6111722f000b5b4c4d4071e2",
- "labels": {
- "service": "datasette-io"
- }
- }
-
-Inserting this into a table using ``sqlite-utils insert logs.db logs log.json`` will create a table with the following schema:
-
-.. 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:
-
-.. 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:
-
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::
-.. code-block:: bash
+ $ sqlite-utils insert dogs.db dogs docs.csv --csv
- sqlite-utils insert dogs.db dogs dogs.csv --csv
+For tab-delimited data, use ``--tsv``::
-For tab-delimited data, use ``--tsv``:
-
-.. code-block:: bash
-
- 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, 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.
-
-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:
-
-.. code-block:: bash
-
- 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
-
- CREATE TABLE "creatures" (
- "name" TEXT,
- "age" INTEGER,
- "weight" REAL
- );
-
-.. _cli_insert_csv_tsv_column_types:
-
-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:
-
-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:
-
-.. code-block:: bash
-
- sqlite-utils insert dogs.db dogs dogs.csv --sniff
-
-Alternatively, you can specify them using the ``--delimiter`` and ``--quotechar`` options.
-
-Here's a CSV file that uses ``;`` for delimiters and the ``|`` symbol for quote characters::
-
- name;description
- Cleo;|Very fine; a friendly dog|
- Pancakes;A local corgi
-
-You can import that using:
-
-.. 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.
-
-.. _cli_insert_csv_tsv_no_header:
-
-CSV files without a header row
-------------------------------
-
-The first row of any CSV or TSV file is expected to contain the names of the columns in that file.
-
-If your file does not include this row, you can use the ``--no-headers`` option to specify that the tool should not use that fist row as headers.
-
-If you do this, the table will be created with column names called ``untitled_1`` and ``untitled_2`` and so on. You can then rename them using the ``sqlite-utils transform ... --rename`` command, see :ref:`cli_transform_table`.
-
-.. _cli_insert_unstructured:
-
-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 `:
-
-.. 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
- );
-
-You can also insert the entire contents of the file into a single column called ``text`` using ``--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
- );
-
-.. _cli_insert_convert:
-
-Applying conversions while inserting data
-=========================================
-
-The ``--convert`` option can be used to apply a Python conversion function to imported data before it is inserted into the database. It works in a similar way to :ref:`sqlite-utils convert `.
-
-Your Python function will be passed a dictionary called ``row`` for each item that is being imported. You can modify that dictionary and return it - or return a fresh dictionary - to change the data that will be inserted.
-
-Given a JSON file called ``dogs.json`` containing this:
-
-.. code-block:: json
-
- [
- {"id": 1, "name": "Cleo"},
- {"id": 2, "name": "Pancakes"}
- ]
-
-The following command will insert that data and add an ``is_good`` column set to ``1`` for each dog:
-
-.. 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.
-
-As with ``sqlite-utils convert`` you can use ``--import`` to import additional Python modules, see :ref:`cli_convert_import` for details.
-
-You can also pass code that runs some initialization steps and defines a ``convert(value)`` function, see :ref:`cli_convert_complex`.
-
-.. _cli_insert_convert_lines:
-
-\-\-convert with \-\-lines
---------------------------
-
-Things work slightly differently when combined with the ``--lines`` or ``--text`` options.
-
-With ``--lines``, instead of being passed a ``row`` dictionary your function will be passed a ``line`` string representing each line of the input. Given a file called ``access.log`` containing the following::
-
- 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:
-
-.. code-block:: bash
-
- sqlite-utils insert logs.db loglines access.log --convert '
- type, source, _, verb, path, _, status, _ = line.split()
- return {
- "type": type,
- "source": source,
- "verb": verb,
- "path": path,
- "status": status,
- }' --lines
-
-The resulting table would look like this:
-
-====== =============== ====== ============================ ========
-type source verb path status
-====== =============== ====== ============================ ========
-INFO: 127.0.0.1:60581 GET / 200
-INFO: 127.0.0.1:60581 GET /foo/-/static/app.css?cead5a 200
-====== =============== ====== ============================ ========
-
-.. _cli_insert_convert_text:
-
-\-\-convert with \-\-text
--------------------------
-
-With ``--text`` the entire input to the command will be made available to the function as a variable called ``text``.
-
-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:
-
-.. 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:
-
-.. code-block:: bash
-
- sqlite-utils dump words.db
-
-.. code-block:: output
-
- BEGIN TRANSACTION;
- CREATE TABLE "words" (
- "word" TEXT
- );
- INSERT INTO "words" VALUES('A');
- INSERT INTO "words" VALUES('bunch');
- INSERT INTO "words" VALUES('of');
- INSERT INTO "words" VALUES('words');
- 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
-=====================
-
-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:
-
-.. 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:
+ $ sqlite-utils insert dogs.db dogs docs.tsv --tsv
Upserting data
==============
-Upserting is update-or-insert. If a row exists with the specified primary key the provided columns will be updated. If no row exists that row will be created.
+Upserting works exactly like inserting, with the exception that if your data has a primary key that matches an already exsting record that record will be replaced with the new data.
-Unlike ``insert --replace``, an upsert will ignore any column values that exist but are not present in the upsert document.
+After running the above ``dogs.json`` example, try running this::
-For example:
-
-.. code-block:: bash
-
- echo '{"id": 2, "age": 4}' | \
+ $ echo '{"id": 2, "name": "Pancakes", "age": 3}' | \
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
-=====================
-
-If you have a JSON, newline-delimited JSON, CSV or TSV file you can execute a bulk SQL query using each of the records in that file using the ``sqlite-utils bulk`` command.
-
-The command takes the database file, the SQL to be executed and the file containing records to be used when evaluating the SQL query.
-
-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:
-
-.. code-block::
-
- id,name
- 1,Blue
- 2,Snowy
- 3,Azi
- 4,Lila
- 5,Suna
- 6,Cardi
-
-You could insert those rows into a pre-created ``chickens`` table like so:
-
-.. code-block:: bash
-
- sqlite-utils bulk chickens.db \
- 'insert into chickens (id, name) values (:id, :name)' \
- chickens.csv --csv
-
-This command takes the same options as the ``sqlite-utils insert`` command - so it defaults to expecting JSON but can accept other formats using ``--csv`` or ``--tsv`` or ``--nl`` or other options described above.
-
-By default all of the SQL queries will be executed in a single transaction. To commit every 20 records, use ``--batch-size 20``.
-
-.. _cli_insert_files:
-
-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:
-
-.. code-block:: bash
-
- sqlite-utils insert-files gifs.db images *.gif
-
-You can also pass one or more directories, in which case every file in those directories will be added recursively:
-
-.. code-block:: bash
-
- 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:
-
-.. code-block:: bash
-
- sqlite-utils insert-files gifs.db images *.gif -c path -c md5 -c mtime --pk=path
-
-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:
-
-.. 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.
-
-The full list of column definitions you can use is as follows:
-
-``name``
- The name of the file, e.g. ``cleo.jpg``
-``path``
- The path to the file relative to the root folder, e.g. ``pictures/cleo.jpg``
-``fullpath``
- The fully resolved path to the image, e.g. ``/home/simonw/pictures/cleo.jpg``
-``sha256``
- The SHA256 hash of the file contents
-``md5``
- The MD5 hash of the file contents
-``mode``
- The permission bits of the file, as an integer - you may want to convert this to octal
-``content``
- The binary file contents, which will be stored as a BLOB
-``content_text``
- The text file contents, which will be stored as TEXT
-``mtime``
- The modification time of the file, as floating point seconds since the Unix epoch
-``ctime``
- The creation time of the file, as floating point seconds since the Unix epoch
-``mtime_int``
- The modification time as an integer rather than a float
-``ctime_int``
- The creation time as an integer rather than a float
-``mtime_iso``
- The modification time as an ISO timestamp, e.g. ``2020-07-27T04:24:06.654246``
-``ctime_iso``
- The creation time is an ISO timestamp
-``size``
- The integer size of the file in bytes
-``stem``
- The filename without the extension - for ``file.txt.gz`` this would be ``file.txt``
-``suffix``
- The file extension - for ``file.txt.gz`` this would be ``.gz``
-
-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
-
-The ``-`` argument indicates data should be read from standard input. The string passed using the ``--name`` option will be used for the file name and path values.
-
-When inserting data from standard input only the following column definitions are supported: ``name``, ``path``, ``content``, ``content_text``, ``sha256``, ``md5`` and ``size``.
-
-.. _cli_convert:
-
-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:
-
-.. 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:
-
-.. 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:
-
-.. 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:
-
-.. 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:
-
-.. code-block:: python
-
- 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``:
-
-.. 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:
-
-.. 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:
-
-.. 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 `__:
-
-.. 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