diff --git a/.github/actions/setup-sqlite-version/action.yml b/.github/actions/setup-sqlite-version/action.yml new file mode 100644 index 0000000..fdbc71c --- /dev/null +++ b/.github/actions/setup-sqlite-version/action.yml @@ -0,0 +1,39 @@ +name: "Setup SQLite version" +description: "Build and activate a specific SQLite version from its amalgamation archive" +inputs: + version: + description: "The SQLite version to install" + required: true + cflags: + description: "CFLAGS to use when compiling SQLite" + required: false + default: "" + skip-activate: + description: "Set to true to skip modifying the library path" + required: false + default: "false" + fallback-urls: + description: "Whitespace-separated fallback download URLs to try after sqlite.org" + required: false + default: "" +outputs: + sqlite-location: + description: "Directory containing the compiled SQLite library" + value: ${{ steps.build.outputs.sqlite-location }} +runs: + using: "composite" + steps: + - shell: bash + run: mkdir -p "$RUNNER_TEMP/sqlite-versions/downloads" + - uses: actions/cache@v6 + with: + path: ${{ runner.temp }}/sqlite-versions/downloads + key: setup-sqlite-version-${{ inputs.version }}-amalgamation-v1 + - id: build + shell: bash + run: bash "$GITHUB_ACTION_PATH/setup-sqlite-version.sh" + env: + SQLITE_VERSION: ${{ inputs.version }} + SQLITE_CFLAGS: ${{ inputs.cflags }} + SQLITE_SKIP_ACTIVATE: ${{ inputs.skip-activate }} + SQLITE_EXTRA_FALLBACK_URLS: ${{ inputs.fallback-urls }} diff --git a/.github/actions/setup-sqlite-version/setup-sqlite-version.sh b/.github/actions/setup-sqlite-version/setup-sqlite-version.sh new file mode 100644 index 0000000..0df7290 --- /dev/null +++ b/.github/actions/setup-sqlite-version/setup-sqlite-version.sh @@ -0,0 +1,144 @@ +#!/usr/bin/env bash +set -euo pipefail + +version_spec="${SQLITE_VERSION:?SQLITE_VERSION is required}" +cflags="${SQLITE_CFLAGS:-}" +skip_activate="${SQLITE_SKIP_ACTIVATE:-false}" +extra_fallback_urls="${SQLITE_EXTRA_FALLBACK_URLS:-}" + +case "$version_spec" in + 3.46 | 3.46.0) + sqlite_version="3.46.0" + sqlite_year="2024" + amalgamation_id="3460000" + builtin_fallback_urls="https://static.simonwillison.net/static/2026/sqlite-amalgamation-3460000.zip" + ;; + 3.23.1) + sqlite_version="3.23.1" + sqlite_year="2018" + amalgamation_id="3230100" + builtin_fallback_urls="https://static.simonwillison.net/static/2026/sqlite-amalgamation-3230100.zip" + ;; + *) + echo "::error::Unsupported SQLite version '$version_spec'. Add its release year and amalgamation id to $GITHUB_ACTION_PATH/setup-sqlite-version.sh." + exit 1 + ;; +esac + +case "$(uname -s)" in + Linux) + library_name="libsqlite3.so.0" + library_path_var="LD_LIBRARY_PATH" + ;; + Darwin) + library_name="libsqlite3.dylib" + library_path_var="DYLD_LIBRARY_PATH" + ;; + *) + echo "::error::Unsupported platform $(uname -s)" + exit 1 + ;; +esac + +runner_temp="${RUNNER_TEMP:-}" +if [ -z "$runner_temp" ]; then + runner_temp="$(mktemp -d)" +fi + +filename="sqlite-amalgamation-${amalgamation_id}" +official_url="https://www.sqlite.org/${sqlite_year}/${filename}.zip" +download_dir="${runner_temp}/sqlite-versions/downloads" +source_root="${runner_temp}/sqlite-versions/source" +source_dir="${source_root}/${filename}" +build_dir="${runner_temp}/sqlite-versions/build/${sqlite_version}" +archive_path="${download_dir}/${filename}.zip" + +mkdir -p "$download_dir" "$source_root" "$build_dir" + +download_archive() { + local url + local candidate_path="${archive_path}.tmp" + local urls=("$official_url") + + for url in $builtin_fallback_urls $extra_fallback_urls; do + urls+=("$url") + done + + rm -f "$candidate_path" + for url in "${urls[@]}"; do + echo "Downloading SQLite ${sqlite_version} amalgamation from ${url}" + if curl \ + --fail \ + --location \ + --show-error \ + --retry 5 \ + --retry-delay 2 \ + --retry-max-time 180 \ + --retry-all-errors \ + --connect-timeout 20 \ + --max-time 240 \ + --output "$candidate_path" \ + "$url"; then + mv "$candidate_path" "$archive_path" + return 0 + fi + + echo "::warning::Download failed from ${url}" + rm -f "$candidate_path" + done + + echo "::error::Could not download SQLite ${sqlite_version} amalgamation" + return 1 +} + +if [ ! -f "${source_dir}/sqlite3.c" ]; then + if [ ! -f "$archive_path" ]; then + download_archive + fi + + rm -rf "$source_dir" + unzip -q "$archive_path" -d "$source_root" +fi + +if [ ! -f "${source_dir}/sqlite3.c" ]; then + echo "::error::Expected ${source_dir}/sqlite3.c after extracting ${archive_path}" + exit 1 +fi + +read -r -a cflag_args <<< "$cflags" + +echo "Compiling SQLite ${sqlite_version} to ${build_dir}/${library_name}" +gcc \ + -fPIC \ + -shared \ + "${cflag_args[@]}" \ + "${source_dir}/sqlite3.c" \ + "-I${source_dir}" \ + -o "${build_dir}/${library_name}" + +if [ "$library_name" = "libsqlite3.so.0" ]; then + ln -sf "$library_name" "${build_dir}/libsqlite3.so" +fi + +if [ -n "${GITHUB_OUTPUT:-}" ]; then + echo "sqlite-location=${build_dir}" >> "$GITHUB_OUTPUT" +else + echo "sqlite-location=${build_dir}" +fi + +case "$(printf '%s' "$skip_activate" | tr '[:upper:]' '[:lower:]')" in + true | 1 | yes) + echo "Skipping ${library_path_var} activation" + ;; + *) + existing_value="${!library_path_var:-}" + if [ -n "${GITHUB_ENV:-}" ]; then + if [ -n "$existing_value" ]; then + echo "${library_path_var}=${build_dir}:${existing_value}" >> "$GITHUB_ENV" + else + echo "${library_path_var}=${build_dir}" >> "$GITHUB_ENV" + fi + fi + echo "Added ${build_dir} to ${library_path_var}" + ;; +esac diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 5df57a0..23b23bd 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -9,24 +9,19 @@ jobs: runs-on: ${{ matrix.os }} strategy: matrix: - python-version: ["3.7", "3.8", "3.9", "3.10", "3.11", "3.12"] + python-version: ["3.10", "3.11", "3.12", "3.13", "3.14"] os: [ubuntu-latest, windows-latest, macos-latest] steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v7 - name: Set up Python ${{ matrix.python-version }} - uses: actions/setup-python@v4 + uses: actions/setup-python@v6 with: python-version: ${{ matrix.python-version }} - - uses: actions/cache@v3 - name: Configure pip caching - with: - path: ~/.cache/pip - key: ${{ runner.os }}-pip-${{ hashFiles('**/setup.py') }} - restore-keys: | - ${{ runner.os }}-pip- + cache: pip + cache-dependency-path: pyproject.toml - name: Install dependencies run: | - pip install -e '.[test]' + pip install . --group dev - name: Run tests run: | pytest @@ -34,25 +29,20 @@ jobs: runs-on: ubuntu-latest needs: [test] steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v7 - name: Set up Python - uses: actions/setup-python@v4 + uses: actions/setup-python@v6 with: - python-version: '3.12' - - uses: actions/cache@v3 - name: Configure pip caching - with: - path: ~/.cache/pip - key: ${{ runner.os }}-publish-pip-${{ hashFiles('**/setup.py') }} - restore-keys: | - ${{ runner.os }}-publish-pip- + python-version: '3.14' + cache: pip + cache-dependency-path: pyproject.toml - name: Install dependencies run: | - pip install setuptools wheel twine + pip install build twine - name: Publish env: TWINE_USERNAME: __token__ TWINE_PASSWORD: ${{ secrets.PYPI_TOKEN }} run: | - python setup.py sdist bdist_wheel + python -m build twine upload dist/* diff --git a/.github/workflows/spellcheck.yml b/.github/workflows/spellcheck.yml index 8a86cd2..2afa7b7 100644 --- a/.github/workflows/spellcheck.yml +++ b/.github/workflows/spellcheck.yml @@ -6,21 +6,16 @@ jobs: spellcheck: runs-on: ubuntu-latest steps: - - uses: actions/checkout@v2 - - name: Set up Python ${{ matrix.python-version }} - uses: actions/setup-python@v2 + - uses: actions/checkout@v4 + - name: Set up Python + uses: actions/setup-python@v5 with: - python-version: 3.9 - - uses: actions/cache@v2 - name: Configure pip caching - with: - path: ~/.cache/pip - key: ${{ runner.os }}-pip-${{ hashFiles('**/setup.py') }} - restore-keys: | - ${{ runner.os }}-pip- + python-version: "3.12" + cache: pip + cache-dependency-path: pyproject.toml - name: Install dependencies run: | - pip install -e '.[docs]' + pip install . --group docs - name: Check spelling run: | codespell docs/*.rst --ignore-words docs/codespell-ignore-words.txt diff --git a/.github/workflows/test-coverage.yml b/.github/workflows/test-coverage.yml index 0681f66..7668f1b 100644 --- a/.github/workflows/test-coverage.yml +++ b/.github/workflows/test-coverage.yml @@ -12,24 +12,19 @@ jobs: runs-on: ubuntu-latest steps: - name: Check out repo - uses: actions/checkout@v2 + uses: actions/checkout@v7 - name: Set up Python - uses: actions/setup-python@v2 + uses: actions/setup-python@v6 with: - python-version: 3.9 - - uses: actions/cache@v2 - name: Configure pip caching - with: - path: ~/.cache/pip - key: ${{ runner.os }}-pip-${{ hashFiles('**/setup.py') }} - restore-keys: | - ${{ runner.os }}-pip- + python-version: "3.11" + cache: pip + cache-dependency-path: pyproject.toml - name: Install SpatiaLite run: sudo apt-get install libsqlite3-mod-spatialite - name: Install Python dependencies run: | python -m pip install --upgrade pip - python -m pip install -e .[test] + python -m pip install . --group dev python -m pip install pytest-cov - name: Run tests run: |- diff --git a/.github/workflows/test-sqlite-support.yml b/.github/workflows/test-sqlite-support.yml new file mode 100644 index 0000000..f195cba --- /dev/null +++ b/.github/workflows/test-sqlite-support.yml @@ -0,0 +1,41 @@ +name: Test SQLite versions + +on: [push, pull_request] + +permissions: + contents: read + +jobs: + test: + runs-on: ${{ matrix.platform }} + continue-on-error: true + strategy: + matrix: + platform: [ubuntu-latest] + python-version: ["3.10"] + sqlite-version: [ + "3.46", + "3.23.1", # 2018-04-10, before UPSERT + ] + steps: + - uses: actions/checkout@v7 + - name: Set up Python ${{ matrix.python-version }} + uses: actions/setup-python@v6 + with: + python-version: ${{ matrix.python-version }} + allow-prereleases: true + cache: pip + cache-dependency-path: pyproject.toml + - name: Set up SQLite ${{ matrix.sqlite-version }} + uses: ./.github/actions/setup-sqlite-version + with: + version: ${{ matrix.sqlite-version }} + cflags: "-DSQLITE_ENABLE_DESERIALIZE -DSQLITE_ENABLE_FTS5 -DSQLITE_ENABLE_FTS4 -DSQLITE_ENABLE_FTS3_PARENTHESIS -DSQLITE_ENABLE_RTREE -DSQLITE_ENABLE_JSON1" + - run: python3 -c "import sqlite3; print(sqlite3.sqlite_version)" + - name: Install dependencies + run: | + pip install . --group dev + pip freeze + - name: Run tests + run: | + python -m pytest diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 1832262..923de2e 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -10,37 +10,27 @@ jobs: runs-on: ${{ matrix.os }} strategy: matrix: - python-version: ["3.7", "3.8", "3.9", "3.10", "3.11", "3.12"] + python-version: ["3.10", "3.11", "3.12", "3.13", "3.14", "3.15-dev"] numpy: [0, 1] - os: [ubuntu-latest, macos-latest, windows-latest] + os: [ubuntu-latest, macos-latest, windows-latest, macos-14] steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v7 - name: Set up Python ${{ matrix.python-version }} - uses: actions/setup-python@v4 + uses: actions/setup-python@v6 with: python-version: ${{ matrix.python-version }} - - uses: actions/cache@v3 - name: Configure pip caching - with: - path: ~/.cache/pip - key: ${{ runner.os }}-pip-${{ hashFiles('**/setup.py') }} - restore-keys: | - ${{ runner.os }}-pip- + allow-prereleases: true + cache: pip + cache-dependency-path: pyproject.toml - name: Install dependencies run: | - pip install -e '.[test,mypy,flake8]' - - name: Optionally install tui dependencies (not 3.7) - if: matrix.python-version != '3.7' - run: pip install -e '.[tui]' + 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: On macOS with Python 3.10 test with sqlean.py - if: matrix.os == 'macos-latest' && matrix.python-version == '3.10' - run: pip install sqlean.py sqlite-dump - name: Build extension for --load-extension test if: matrix.os == 'ubuntu-latest' run: |- @@ -48,14 +38,20 @@ jobs: - name: Run tests run: | pytest -v + - name: Run autocommit tests just on 3.14/Ubuntu + if: matrix.os == 'ubuntu-latest' && matrix.python-version == '3.14' + run: pytest --sqlite-autocommit - name: run mypy run: mypy sqlite_utils tests - - name: run flake8 if Python 3.8 or higher - if: matrix.python-version >= 3.8 + - 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 - if: matrix.python-version != '3.7' run: | - cog --check README.md docs/*.rst + cog --check --diff README.md docs/*.rst diff --git a/.gitignore b/.gitignore index 7947f33..6743708 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,5 @@ .venv +dist build *.db __pycache__/ @@ -16,7 +17,7 @@ venv .hypothesis Pipfile Pipfile.lock -pyproject.toml +uv.lock tests/*.dylib tests/*.so tests/*.dll diff --git a/.gitpod.yml b/.gitpod.yml deleted file mode 100644 index fe8ba1e..0000000 --- a/.gitpod.yml +++ /dev/null @@ -1,2 +0,0 @@ -tasks: -- init: pip install '.[test]' \ No newline at end of file diff --git a/.readthedocs.yaml b/.readthedocs.yaml index aa15c7c..08c2f81 100644 --- a/.readthedocs.yaml +++ b/.readthedocs.yaml @@ -4,13 +4,14 @@ sphinx: configuration: docs/conf.py build: - os: ubuntu-22.04 + os: ubuntu-24.04 tools: - python: "3.11" + python: "3.13" + jobs: + install: + - pip install --upgrade pip + - pip install . --group docs -python: - install: - - method: pip - path: . - extra_requirements: - - docs +formats: +- pdf +- epub diff --git a/Justfile b/Justfile index 7571ec3..5caa120 100644 --- a/Justfile +++ b/Justfile @@ -1,30 +1,33 @@ # Run tests and linters @default: test lint -# Setup project -@init: - pipenv run pip install -e '.[test,docs,mypy,flake8]' - # Run pytest with supplied options @test *options: - pipenv run pytest {{options}} + uv run pytest {{options}} -# Run linters: black, flake8, mypy, cog +@run *options: + uv run -- {{options}} + +# Run linters: black, flake8, mypy, ty, cog @lint: - pipenv run black . --check - pipenv run flake8 - pipenv run mypy sqlite_utils tests - pipenv run cog --check README.md docs/*.rst - pipenv run codespell docs/*.rst --ignore-words docs/codespell-ignore-words.txt + 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 # Rebuild docs with cog @cog: - pipenv run cog -r README.md docs/*.rst + uv run --group docs cog -r README.md docs/*.rst # Serve live docs on localhost:8000 @docs: cog - cd docs && pipenv run make livehtml + #!/usr/bin/env bash + cd docs + uv run --group docs make livehtml + # Apply Black @black: - pipenv run black . + uv run black . diff --git a/README.md b/README.md index e425461..c444c64 100644 --- a/README.md +++ b/README.md @@ -18,9 +18,12 @@ Python CLI utility and library for manipulating SQLite databases. - [Configure SQLite full-text search](https://sqlite-utils.datasette.io/en/stable/cli.html#configuring-full-text-search) against your database tables and run search queries against them, ordered by relevance - Run [transformations against your tables](https://sqlite-utils.datasette.io/en/stable/cli.html#transforming-tables) to make schema changes that SQLite `ALTER TABLE` does not directly support, such as changing the type of a column - [Extract columns](https://sqlite-utils.datasette.io/en/stable/cli.html#extracting-columns-into-a-separate-table) into separate tables to better normalize your existing data +- [Manage database migrations](https://sqlite-utils.datasette.io/en/stable/migrations.html) using Python migration files and the `sqlite-utils migrate` command - [Install plugins](https://sqlite-utils.datasette.io/en/stable/plugins.html) to add custom SQL functions and additional features -Read more on my blog, in this series of posts on [New features in sqlite-utils](https://simonwillison.net/series/sqlite-utils-features/) and other [entries tagged sqliteutils](https://simonwillison.net/tags/sqliteutils/). +Upgrading from sqlite-utils 3.x? See the [4.0 upgrade guide](https://sqlite-utils.datasette.io/en/stable/upgrading.html#upgrading-from-3-x-to-4-0). + +Read more on my blog, in this series of posts on [New features in sqlite-utils](https://simonwillison.net/series/sqlite-utils-features/) and other [entries tagged sqlite-utils](https://simonwillison.net/tags/sqlite-utils/). ## Installation diff --git a/docs/_static/img/tui.png b/docs/_static/img/tui.png deleted file mode 100644 index 04cbeb1..0000000 Binary files a/docs/_static/img/tui.png and /dev/null differ diff --git a/docs/changelog.rst b/docs/changelog.rst index 72b3d50..4c868f4 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -4,6 +4,242 @@ 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) @@ -81,7 +317,7 @@ This release introduces a new :ref:`plugin system `. Read more about th 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``. There is a screenshot :ref:`in the documentation `. (:issue:`545`) +- 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`) @@ -117,7 +353,7 @@ This release introduces a new :ref:`plugin system `. Read more about th - Conversion functions passed to :ref:`table.convert(...) ` can now return lists or dictionaries, which will be inserted into the database as JSON strings. (:issue:`495`) - ``sqlite-utils install`` and ``sqlite-utils uninstall`` commands for installing packages into the same virtual environment as ``sqlite-utils``, :ref:`described here `. (:issue:`483`) - New :ref:`sqlite_utils.utils.flatten() ` utility function. (:issue:`500`) -- Documentation on :ref:`using Just ` to run tests, linters and build documentation. +- Documentation on :ref:`using Just ` to run tests, linters and build documentation. - Documentation now covers the :ref:`release_process` for this package. .. _v3_29: diff --git a/docs/cli-reference.rst b/docs/cli-reference.rst index 02f66cd..9fafe28 100644 --- a/docs/cli-reference.rst +++ b/docs/cli-reference.rst @@ -19,8 +19,8 @@ This page lists the ``--help`` for every ``sqlite-utils`` CLI sub-command. go_first = [ "query", "memory", "insert", "upsert", "bulk", "search", "transform", "extract", "schema", "insert-files", "analyze-tables", "convert", "tables", "views", "rows", - "triggers", "indexes", "create-database", "create-table", "create-index", - "enable-fts", "populate-fts", "rebuild-fts", "disable-fts" + "triggers", "indexes", "create-database", "create-table", "create-index", "drop-index", + "migrate", "enable-fts", "populate-fts", "rebuild-fts", "disable-fts" ] refs = { "query": "cli_query", @@ -46,9 +46,11 @@ This page lists the ``--help`` for every ``sqlite-utils`` CLI sub-command. "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", @@ -65,7 +67,6 @@ This page lists the ``--help`` for every ``sqlite-utils`` CLI sub-command. "create-spatial-index": "cli_spatialite_indexes", "install": "cli_install", "uninstall": "cli_uninstall", - "tui": "cli_tui", } commands.sort(key = lambda command: go_first.index(command) if command in go_first else 999) cog.out("\n") @@ -85,6 +86,7 @@ This page lists the ``--help`` for every ``sqlite-utils`` CLI sub-command. cog.out("::\n\n") result = CliRunner().invoke(cli.cli, [command, "--help"]) output = result.output.replace("Usage: cli ", "Usage: sqlite-utils ") + output = output.replace('\b', '') cog.out(textwrap.indent(output, ' ')) cog.out("\n\n") .. ]]] @@ -108,6 +110,10 @@ See :ref:`cli_query`. "select * from chickens where age > :age" \ -p age 1 + Pass "-" as the SQL to read the query from standard input: + + echo "select * from chickens" | sqlite-utils data.db - + Options: --attach ... Additional databases to attach - specify alias and filepath @@ -115,24 +121,26 @@ See :ref:`cli_query`. --arrays Output rows as arrays instead of objects --csv Output CSV --tsv Output TSV - --no-headers Omit CSV headers + --no-headers Omit headers from CSV/TSV and table/--fmt output -t, --table Output as a formatted table - --fmt TEXT Table format - one of asciidoc, double_grid, - double_outline, fancy_grid, fancy_outline, github, - grid, heavy_grid, heavy_outline, html, jira, - latex, latex_booktabs, latex_longtable, latex_raw, - mediawiki, mixed_grid, mixed_outline, moinmoin, - orgtbl, outline, pipe, plain, presto, pretty, - psql, rounded_grid, rounded_outline, rst, simple, - simple_grid, simple_outline, textile, tsv, - unsafehtml, youtrack + --fmt TEXT Table format - one of asciidoc, colon_grid, + double_grid, double_outline, fancy_grid, + fancy_outline, github, grid, heavy_grid, + heavy_outline, html, jira, latex, latex_booktabs, + latex_longtable, latex_raw, mediawiki, mixed_grid, + mixed_outline, moinmoin, orgtbl, outline, pipe, + plain, presto, pretty, psql, rounded_grid, + rounded_outline, rst, simple, simple_grid, + simple_outline, textile, tsv, unsafehtml, youtrack --json-cols Detect JSON cols and output them as JSON, not escaped strings + --ascii Escape non-ASCII characters in JSON output as + \uXXXX -r, --raw Raw output, first column of first row --raw-lines Raw output, first column of each row -p, --param ... Named :parameters for SQL query - --functions TEXT Python code defining one or more custom SQL - functions + --functions TEXT Python code or a file path defining custom SQL + functions; can be used multiple times --load-extension TEXT Path to SQLite extension, with optional :entrypoint -h, --help Show this message and exit. @@ -174,8 +182,8 @@ See :ref:`cli_memory`. sqlite-utils memory animals.csv --schema Options: - --functions TEXT Python code defining one or more custom SQL - functions + --functions TEXT Python code or a file path defining custom SQL + functions; can be used multiple times --attach ... Additional databases to attach - specify alias and filepath --flatten Flatten nested JSON objects, so {"foo": {"bar": @@ -184,19 +192,21 @@ See :ref:`cli_memory`. --arrays Output rows as arrays instead of objects --csv Output CSV --tsv Output TSV - --no-headers Omit CSV headers + --no-headers Omit headers from CSV/TSV and table/--fmt output -t, --table Output as a formatted table - --fmt TEXT Table format - one of asciidoc, double_grid, - double_outline, fancy_grid, fancy_outline, github, - grid, heavy_grid, heavy_outline, html, jira, - latex, latex_booktabs, latex_longtable, latex_raw, - mediawiki, mixed_grid, mixed_outline, moinmoin, - orgtbl, outline, pipe, plain, presto, pretty, - psql, rounded_grid, rounded_outline, rst, simple, - simple_grid, simple_outline, textile, tsv, - unsafehtml, youtrack + --fmt TEXT Table format - one of asciidoc, colon_grid, + double_grid, double_outline, fancy_grid, + fancy_outline, github, grid, heavy_grid, + heavy_outline, html, jira, latex, latex_booktabs, + latex_longtable, latex_raw, mediawiki, mixed_grid, + mixed_outline, moinmoin, orgtbl, outline, pipe, + plain, presto, pretty, psql, rounded_grid, + rounded_outline, rst, simple, simple_grid, + simple_outline, textile, tsv, unsafehtml, youtrack --json-cols Detect JSON cols and output them as JSON, not escaped strings + --ascii Escape non-ASCII characters in JSON output as + \uXXXX -r, --raw Raw output, first column of first row --raw-lines Raw output, first column of each row -p, --param ... Named :parameters for SQL query @@ -221,7 +231,7 @@ See :ref:`cli_inserting_data`, :ref:`cli_insert_csv_tsv`, :ref:`cli_insert_unstr :: - Usage: sqlite-utils insert [OPTIONS] PATH TABLE FILE + Usage: sqlite-utils insert [OPTIONS] PATH TABLE [FILE] Insert records from FILE into a table, creating the table if it does not already exist. @@ -237,6 +247,9 @@ See :ref:`cli_inserting_data`, :ref:`cli_insert_csv_tsv`, :ref:`cli_insert_unstr - Use --lines to write each incoming line to a column called "line" - Use --text to write the entire input to a column called "text" + Use --type column-name type to override the type automatically chosen when the + table is created. + You can also use --convert to pass a fragment of Python code that will be used to convert each input. @@ -263,8 +276,20 @@ See :ref:`cli_inserting_data`, :ref:`cli_insert_csv_tsv`, :ref:`cli_insert_unstr echo 'A bunch of words' | sqlite-utils insert words.db words - \ --text --convert '({"word": w} for w in text.split())' + Instead of a FILE you can use --code to provide a block of Python code that + defines the rows to insert, as either a rows() function that yields + dictionaries or a "rows" iterable. --code can also be a path to a .py file: + + sqlite-utils insert data.db creatures --code ' + def rows(): + yield {"id": 1, "name": "Cleo"} + yield {"id": 2, "name": "Suna"} + ' --pk id + Options: --pk TEXT Columns to use as the primary key, e.g. id + --code TEXT Python code defining a rows() function or iterable + of rows to insert --flatten Flatten nested JSON objects, so {"a": {"b": 1}} becomes {"a_b": 1} --nl Expect newline-delimited JSON @@ -285,10 +310,12 @@ See :ref:`cli_inserting_data`, :ref:`cli_insert_csv_tsv`, :ref:`cli_insert_unstr --alter Alter existing table to add any missing columns --not-null TEXT Columns that should be created as NOT NULL --default ... Default value that should be set for a column - -d, --detect-types Detect types for columns in CSV/TSV data + --type ... Column types to use when creating the table + --no-detect-types Treat all CSV/TSV columns as TEXT --analyze Run ANALYZE at the end of this operation --load-extension TEXT Path to SQLite extension, with optional :entrypoint --silent Do not show progress bar + --strict Apply STRICT mode to created table --ignore Ignore records if pk already exists --replace Replace records if pk already exists --truncate Truncate table before inserting records, if table @@ -305,12 +332,17 @@ See :ref:`cli_upsert`. :: - Usage: sqlite-utils upsert [OPTIONS] PATH TABLE FILE + Usage: sqlite-utils upsert [OPTIONS] PATH TABLE [FILE] Upsert records based on their primary key. Works like 'insert' but if an incoming record has a primary key that matches an existing record the existing record will be updated. + If the table already exists and has a primary key, --pk can be omitted. + + Use --type column-name type to override the type automatically chosen when the + table is created. + Example: echo '[ @@ -320,7 +352,8 @@ See :ref:`cli_upsert`. Options: --pk TEXT Columns to use as the primary key, e.g. id - [required] + --code TEXT Python code defining a rows() function or iterable + of rows to insert --flatten Flatten nested JSON objects, so {"a": {"b": 1}} becomes {"a_b": 1} --nl Expect newline-delimited JSON @@ -341,10 +374,12 @@ See :ref:`cli_upsert`. --alter Alter existing table to add any missing columns --not-null TEXT Columns that should be created as NOT NULL --default ... Default value that should be set for a column - -d, --detect-types Detect types for columns in CSV/TSV data + --type ... Column types to use when creating the table + --no-detect-types Treat all CSV/TSV columns as TEXT --analyze Run ANALYZE at the end of this operation --load-extension TEXT Path to SQLite extension, with optional :entrypoint --silent Do not show progress bar + --strict Apply STRICT mode to created table -h, --help Show this message and exit. @@ -372,7 +407,8 @@ See :ref:`cli_bulk`. Options: --batch-size INTEGER Commit every X records - --functions TEXT Python code defining one or more custom SQL functions + --functions TEXT Python code or a file path defining custom SQL + functions; can be used multiple times --flatten Flatten nested JSON objects, so {"a": {"b": 1}} becomes {"a_b": 1} --nl Expect newline-delimited JSON @@ -419,18 +455,20 @@ See :ref:`cli_search`. --arrays Output rows as arrays instead of objects --csv Output CSV --tsv Output TSV - --no-headers Omit CSV headers + --no-headers Omit headers from CSV/TSV and table/--fmt output -t, --table Output as a formatted table - --fmt TEXT Table format - one of asciidoc, double_grid, - double_outline, fancy_grid, fancy_outline, github, - grid, heavy_grid, heavy_outline, html, jira, latex, - latex_booktabs, latex_longtable, latex_raw, mediawiki, - mixed_grid, mixed_outline, moinmoin, orgtbl, outline, - pipe, plain, presto, pretty, psql, rounded_grid, - rounded_outline, rst, simple, simple_grid, - simple_outline, textile, tsv, unsafehtml, youtrack + --fmt TEXT Table format - one of asciidoc, colon_grid, + double_grid, double_outline, fancy_grid, fancy_outline, + github, grid, heavy_grid, heavy_outline, html, jira, + latex, latex_booktabs, latex_longtable, latex_raw, + mediawiki, mixed_grid, mixed_outline, moinmoin, orgtbl, + outline, pipe, plain, presto, pretty, psql, + rounded_grid, rounded_outline, rst, simple, + simple_grid, simple_outline, textile, tsv, unsafehtml, + youtrack --json-cols Detect JSON cols and output them as JSON, not escaped strings + --ascii Escape non-ASCII characters in JSON output as \uXXXX --load-extension TEXT Path to SQLite extension, with optional :entrypoint -h, --help Show this message and exit. @@ -455,8 +493,8 @@ See :ref:`cli_transform_table`. --rename column2 column_renamed Options: - --type ... Change column type to INTEGER, TEXT, FLOAT or - BLOB + --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 @@ -470,6 +508,8 @@ See :ref:`cli_transform_table`. 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 @@ -601,42 +641,48 @@ See :ref:`cli_convert`. Convert columns using Python code you supply. For example: - sqlite-utils convert my.db mytable mycolumn \ - '"\n".join(textwrap.wrap(value, 10))' \ - --import=textwrap + sqlite-utils convert my.db mytable mycolumn \ + '"\n".join(textwrap.wrap(value, 10))' \ + --import=textwrap "value" is a variable with the column value to be converted. + CODE can also be a reference to a callable that takes the value, for example: + + sqlite-utils convert my.db mytable date r.parsedate + sqlite-utils convert my.db mytable data json.loads --import json + Use "-" for CODE to read Python code from standard input. The following common operations are available as recipe functions: - r.jsonsplit(value, delimiter=',', type=) + r.jsonsplit(value: 'str', delimiter: 'str' = ',', type: 'Callable[[str], + object]' = ) -> 'str' - Convert a string like a,b,c into a JSON array ["a", "b", "c"] + Convert a string like a,b,c into a JSON array ["a", "b", "c"] - r.parsedate(value, dayfirst=False, yearfirst=False, errors=None) + r.parsedate(value: 'str', dayfirst: 'bool' = False, yearfirst: 'bool' = False, + errors: 'Optional[object]' = None) -> 'Optional[str]' - Parse a date and convert it to ISO date format: yyyy-mm-dd -  - - dayfirst=True: treat xx as the day in xx/yy/zz - - yearfirst=True: treat xx as the year in xx/yy/zz - - errors=r.IGNORE to ignore values that cannot be parsed - - errors=r.SET_NULL to set values that cannot be parsed to null + Parse a date and convert it to ISO date format: yyyy-mm-dd + - dayfirst=True: treat xx as the day in xx/yy/zz + - yearfirst=True: treat xx as the year in xx/yy/zz + - errors=r.IGNORE to ignore values that cannot be parsed + - errors=r.SET_NULL to set values that cannot be parsed to null - r.parsedatetime(value, dayfirst=False, yearfirst=False, errors=None) + r.parsedatetime(value: 'str', dayfirst: 'bool' = False, yearfirst: 'bool' = + False, errors: 'Optional[object]' = None) -> 'Optional[str]' - Parse a datetime and convert it to ISO datetime format: yyyy-mm-ddTHH:MM:SS -  - - dayfirst=True: treat xx as the day in xx/yy/zz - - yearfirst=True: treat xx as the year in xx/yy/zz - - errors=r.IGNORE to ignore values that cannot be parsed - - errors=r.SET_NULL to set values that cannot be parsed to null + Parse a datetime and convert it to ISO datetime format: yyyy-mm-ddTHH:MM:SS + - dayfirst=True: treat xx as the day in xx/yy/zz + - yearfirst=True: treat xx as the year in xx/yy/zz + - errors=r.IGNORE to ignore values that cannot be parsed + - errors=r.SET_NULL to set values that cannot be parsed to null You can use these recipes like so: - sqlite-utils convert my.db mytable mycolumn \ - 'r.jsonsplit(value, delimiter=":")' + sqlite-utils convert my.db mytable mycolumn \ + 'r.jsonsplit(value, delimiter=":")' Options: --import TEXT Python modules to import @@ -651,7 +697,6 @@ See :ref:`cli_convert`. --output-type [integer|float|blob|text] Column type to use for the output column --drop Drop original column afterwards - --no-skip-false Don't skip falsey values -s, --silent Don't show a progress bar --pdb Open pdb debugger on first error -h, --help Show this message and exit. @@ -682,18 +727,20 @@ See :ref:`cli_tables`. --arrays Output rows as arrays instead of objects --csv Output CSV --tsv Output TSV - --no-headers Omit CSV headers + --no-headers Omit headers from CSV/TSV and table/--fmt output -t, --table Output as a formatted table - --fmt TEXT Table format - one of asciidoc, double_grid, - double_outline, fancy_grid, fancy_outline, github, - grid, heavy_grid, heavy_outline, html, jira, latex, - latex_booktabs, latex_longtable, latex_raw, mediawiki, - mixed_grid, mixed_outline, moinmoin, orgtbl, outline, - pipe, plain, presto, pretty, psql, rounded_grid, - rounded_outline, rst, simple, simple_grid, - simple_outline, textile, tsv, unsafehtml, youtrack + --fmt TEXT Table format - one of asciidoc, colon_grid, + double_grid, double_outline, fancy_grid, fancy_outline, + github, grid, heavy_grid, heavy_outline, html, jira, + latex, latex_booktabs, latex_longtable, latex_raw, + mediawiki, mixed_grid, mixed_outline, moinmoin, orgtbl, + outline, pipe, plain, presto, pretty, psql, + rounded_grid, rounded_outline, rst, simple, + simple_grid, simple_outline, textile, tsv, unsafehtml, + youtrack --json-cols Detect JSON cols and output them as JSON, not escaped strings + --ascii Escape non-ASCII characters in JSON output as \uXXXX --columns Include list of columns for each table --schema Include schema for each table --load-extension TEXT Path to SQLite extension, with optional :entrypoint @@ -723,18 +770,20 @@ See :ref:`cli_views`. --arrays Output rows as arrays instead of objects --csv Output CSV --tsv Output TSV - --no-headers Omit CSV headers + --no-headers Omit headers from CSV/TSV and table/--fmt output -t, --table Output as a formatted table - --fmt TEXT Table format - one of asciidoc, double_grid, - double_outline, fancy_grid, fancy_outline, github, - grid, heavy_grid, heavy_outline, html, jira, latex, - latex_booktabs, latex_longtable, latex_raw, mediawiki, - mixed_grid, mixed_outline, moinmoin, orgtbl, outline, - pipe, plain, presto, pretty, psql, rounded_grid, - rounded_outline, rst, simple, simple_grid, - simple_outline, textile, tsv, unsafehtml, youtrack + --fmt TEXT Table format - one of asciidoc, colon_grid, + double_grid, double_outline, fancy_grid, fancy_outline, + github, grid, heavy_grid, heavy_outline, html, jira, + latex, latex_booktabs, latex_longtable, latex_raw, + mediawiki, mixed_grid, mixed_outline, moinmoin, orgtbl, + outline, pipe, plain, presto, pretty, psql, + rounded_grid, rounded_outline, rst, simple, + simple_grid, simple_outline, textile, tsv, unsafehtml, + youtrack --json-cols Detect JSON cols and output them as JSON, not escaped strings + --ascii Escape non-ASCII characters in JSON output as \uXXXX --columns Include list of columns for each view --schema Include schema for each view --load-extension TEXT Path to SQLite extension, with optional :entrypoint @@ -769,19 +818,21 @@ See :ref:`cli_rows`. --arrays Output rows as arrays instead of objects --csv Output CSV --tsv Output TSV - --no-headers Omit CSV headers + --no-headers Omit headers from CSV/TSV and table/--fmt output -t, --table Output as a formatted table - --fmt TEXT Table format - one of asciidoc, double_grid, - double_outline, fancy_grid, fancy_outline, github, - grid, heavy_grid, heavy_outline, html, jira, - latex, latex_booktabs, latex_longtable, latex_raw, - mediawiki, mixed_grid, mixed_outline, moinmoin, - orgtbl, outline, pipe, plain, presto, pretty, - psql, rounded_grid, rounded_outline, rst, simple, - simple_grid, simple_outline, textile, tsv, - unsafehtml, youtrack + --fmt TEXT Table format - one of asciidoc, colon_grid, + double_grid, double_outline, fancy_grid, + fancy_outline, github, grid, heavy_grid, + heavy_outline, html, jira, latex, latex_booktabs, + latex_longtable, latex_raw, mediawiki, mixed_grid, + mixed_outline, moinmoin, orgtbl, outline, pipe, + plain, presto, pretty, psql, rounded_grid, + rounded_outline, rst, simple, simple_grid, + simple_outline, textile, tsv, unsafehtml, youtrack --json-cols Detect JSON cols and output them as JSON, not escaped strings + --ascii Escape non-ASCII characters in JSON output as + \uXXXX --load-extension TEXT Path to SQLite extension, with optional :entrypoint -h, --help Show this message and exit. @@ -809,18 +860,20 @@ See :ref:`cli_triggers`. --arrays Output rows as arrays instead of objects --csv Output CSV --tsv Output TSV - --no-headers Omit CSV headers + --no-headers Omit headers from CSV/TSV and table/--fmt output -t, --table Output as a formatted table - --fmt TEXT Table format - one of asciidoc, double_grid, - double_outline, fancy_grid, fancy_outline, github, - grid, heavy_grid, heavy_outline, html, jira, latex, - latex_booktabs, latex_longtable, latex_raw, mediawiki, - mixed_grid, mixed_outline, moinmoin, orgtbl, outline, - pipe, plain, presto, pretty, psql, rounded_grid, - rounded_outline, rst, simple, simple_grid, - simple_outline, textile, tsv, unsafehtml, youtrack + --fmt TEXT Table format - one of asciidoc, colon_grid, + double_grid, double_outline, fancy_grid, fancy_outline, + github, grid, heavy_grid, heavy_outline, html, jira, + latex, latex_booktabs, latex_longtable, latex_raw, + mediawiki, mixed_grid, mixed_outline, moinmoin, orgtbl, + outline, pipe, plain, presto, pretty, psql, + rounded_grid, rounded_outline, rst, simple, + simple_grid, simple_outline, textile, tsv, unsafehtml, + youtrack --json-cols Detect JSON cols and output them as JSON, not escaped strings + --ascii Escape non-ASCII characters in JSON output as \uXXXX --load-extension TEXT Path to SQLite extension, with optional :entrypoint -h, --help Show this message and exit. @@ -848,18 +901,20 @@ See :ref:`cli_indexes`. --arrays Output rows as arrays instead of objects --csv Output CSV --tsv Output TSV - --no-headers Omit CSV headers + --no-headers Omit headers from CSV/TSV and table/--fmt output -t, --table Output as a formatted table - --fmt TEXT Table format - one of asciidoc, double_grid, - double_outline, fancy_grid, fancy_outline, github, - grid, heavy_grid, heavy_outline, html, jira, latex, - latex_booktabs, latex_longtable, latex_raw, mediawiki, - mixed_grid, mixed_outline, moinmoin, orgtbl, outline, - pipe, plain, presto, pretty, psql, rounded_grid, - rounded_outline, rst, simple, simple_grid, - simple_outline, textile, tsv, unsafehtml, youtrack + --fmt TEXT Table format - one of asciidoc, colon_grid, + double_grid, double_outline, fancy_grid, fancy_outline, + github, grid, heavy_grid, heavy_outline, html, jira, + latex, latex_booktabs, latex_longtable, latex_raw, + mediawiki, mixed_grid, mixed_outline, moinmoin, orgtbl, + outline, pipe, plain, presto, pretty, psql, + rounded_grid, rounded_outline, rst, simple, + simple_grid, simple_outline, textile, tsv, unsafehtml, + youtrack --json-cols Detect JSON cols and output them as JSON, not escaped strings + --ascii Escape non-ASCII characters in JSON output as \uXXXX --load-extension TEXT Path to SQLite extension, with optional :entrypoint -h, --help Show this message and exit. @@ -905,10 +960,10 @@ See :ref:`cli_create_table`. sqlite-utils create-table my.db people \ id integer \ name text \ - height float \ + height real \ photo blob --pk id - Valid column types are text, integer, float and blob. + Valid column types are text, integer, real, float and blob. Options: --pk TEXT Column to use as primary key @@ -920,6 +975,7 @@ See :ref:`cli_create_table`. --replace If table already exists, replace it --transform If table already exists, try to transform the schema --load-extension TEXT Path to SQLite extension, with optional :entrypoint + --strict Apply STRICT mode to created table -h, --help Show this message and exit. @@ -953,6 +1009,67 @@ See :ref:`cli_create_index`. -h, --help Show this message and exit. +.. _cli_ref_drop_index: + +drop-index +========== + +See :ref:`cli_drop_index`. + +:: + + Usage: sqlite-utils drop-index [OPTIONS] PATH TABLE INDEX + + Drop an index by index name from the specified table + + Example: + + sqlite-utils drop-index chickens.db chickens idx_chickens_name + + Options: + --ignore Ignore if index does not exist + --load-extension TEXT Path to SQLite extension, with optional :entrypoint + -h, --help Show this message and exit. + + +.. _cli_ref_migrate: + +migrate +======= + +See :ref:`cli_migrate`. + +:: + + Usage: sqlite-utils migrate [OPTIONS] DB_PATH [MIGRATIONS]... + + Apply pending database migrations. + + Usage: + + sqlite-utils migrate database.db + + This will find the migrations.py file in the current directory or + subdirectories and apply any pending migrations. + + Or pass paths to one or more migrations.py files directly: + + sqlite-utils migrate database.db path/to/migrations.py + + Pass --list to see a list of applied and pending migrations without applying + them. + + Use --stop-before migration_set:name to stop before a migration. This option + can be used multiple times. + + Options: + --stop-before TEXT Stop before applying this migration. Use set:name to + target a migration set. + --list List migrations without running them + -v, --verbose Show verbose output + -h, --help Show this message and exit. + + .. _cli_ref_enable_fts: enable-fts @@ -964,7 +1081,7 @@ See :ref:`cli_fts`. Usage: sqlite-utils enable-fts [OPTIONS] PATH TABLE COLUMN... - Enable full-text search for specific table and columns" + Enable full-text search for specific table and columns Example: @@ -1041,23 +1158,6 @@ disable-fts -h, --help Show this message and exit. -.. _cli_ref_tui: - -tui -=== - -See :ref:`cli_tui`. - -:: - - Usage: sqlite-utils tui [OPTIONS] - - Open Textual TUI. - - Options: - -h, --help Show this message and exit. - - .. _cli_ref_optimize: optimize @@ -1157,7 +1257,7 @@ See :ref:`cli_add_column`. :: Usage: sqlite-utils add-column [OPTIONS] PATH TABLE COL_NAME - [[integer|float|blob|text|INTEGER|FLOAT|BLOB|TEXT]] + [integer|int|float|real|text|str|blob|bytes] Add a column to the specified table @@ -1493,7 +1593,7 @@ See :ref:`cli_spatialite`. paths. To load it from a specific path, use --load-extension. Options: - -t, --type [POINT|LINESTRING|POLYGON|MULTIPOINT|MULTILINESTRING|MULTIPOLYGON|GEOMETRYCOLLECTION|GEOMETRY] + -t, --type [point|linestring|polygon|multipoint|multilinestring|multipolygon|geometrycollection|geometry] Specify a geometry type for this column. [default: GEOMETRY] --srid INTEGER Spatial Reference ID. See diff --git a/docs/cli.rst b/docs/cli.rst index 5d9deb0..2e506dd 100644 --- a/docs/cli.rst +++ b/docs/cli.rst @@ -29,6 +29,16 @@ The ``sqlite-utils query`` command lets you run queries directly against a SQLit .. 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 @@ -45,6 +55,8 @@ The default format returned for queries is JSON: [{"id": 1, "age": 4, "name": "Cleo"}, {"id": 2, "age": 2, "name": "Pancakes"}] +If the query returns more than one column with the same name, later occurrences are renamed with a numeric suffix - ``select 1 as id, 2 as id`` returns ``[{"id": 1, "id_2": 2}]``. This only applies to JSON output: :ref:`CSV and TSV ` and :ref:`table ` output keep the duplicate column headers unchanged. + .. _cli_query_nl: Newline-delimited JSON @@ -109,6 +121,33 @@ If you want to pretty-print the output further, you can pipe it through ``python } ] +.. _cli_query_json_ascii: + +Unicode characters in JSON +~~~~~~~~~~~~~~~~~~~~~~~~~~ + +JSON output includes unicode characters directly, without escaping them: + +.. code-block:: bash + + sqlite-utils dogs.db "select '日本語' as text" + +.. code-block:: output + + [{"text": "日本語"}] + +Use ``--ascii`` to escape non-ASCII characters as ``\uXXXX`` sequences instead: + +.. code-block:: bash + + sqlite-utils dogs.db "select '日本語' as text" --ascii + +.. code-block:: output + + [{"text": "\u65e5\u672c\u8a9e"}] + +The ``--ascii`` option can help on systems that cannot display or process UTF-8, such as Windows consoles using a legacy code page. On Windows, setting the ``PYTHONUTF8=1`` environment variable is an alternative fix for ``UnicodeEncodeError`` crashes when redirecting output to a file. + .. _cli_query_binary_json: Binary data in JSON @@ -257,6 +296,7 @@ Available ``--fmt`` options are: .. ]]] - ``asciidoc`` +- ``colon_grid`` - ``double_grid`` - ``double_outline`` - ``fancy_grid`` @@ -321,7 +361,7 @@ To return the first column of each result as raw data, separated by newlines, us Using named parameters ---------------------- -You can pass named parameters to the query using ``-p``: +You can pass named parameters to the query using ``-p name value``: .. code-block:: bash @@ -368,6 +408,25 @@ This example defines a function which extracts the domain from a URL: Every callable object defined in the block will be registered as a SQL function with the same name, with the exception of functions with names that begin with an underscore. +You can also pass the path to a Python file containing function definitions: + +.. code-block:: bash + + sqlite-utils query sites.db "select url, domain(url) from urls" --functions functions.py + +The ``--functions`` option can be used multiple times to load functions from multiple sources: + +.. code-block:: bash + + sqlite-utils query sites.db "select url, domain(url), extract_path(url) from urls" \ + --functions domain_funcs.py \ + --functions 'def extract_path(url): + from urllib.parse import urlparse + return urlparse(url).path' + +.. note:: + In Python: :ref:`db.register_function() ` + .. _cli_query_extensions: SQLite extensions @@ -492,7 +551,7 @@ Incoming CSV data will be assumed to use ``utf-8``. If your data uses a differen If you are joining across multiple CSV files they must all use the same encoding. -Column types will be automatically detected in CSV or TSV data, using the same mechanism as ``--detect-types`` described in :ref:`cli_insert_csv_tsv`. You can pass the ``--no-detect-types`` option to disable this automatic type detection and treat all CSV and TSV columns as ``TEXT``. +Column types will be automatically detected in CSV or TSV data, as described in :ref:`cli_insert_csv_tsv`. You can pass the ``--no-detect-types`` option to disable this automatic type detection and treat all CSV and TSV columns as ``TEXT``. .. _cli_memory_explicit: @@ -547,13 +606,13 @@ To see the in-memory database schema that would be used for a file or for multip .. code-block:: output - CREATE TABLE [dogs] ( - [id] INTEGER, - [age] INTEGER, - [name] TEXT + CREATE TABLE "dogs" ( + "id" INTEGER, + "age" INTEGER, + "name" TEXT ); - CREATE VIEW t1 AS select * from [dogs]; - CREATE VIEW t AS select * from [dogs]; + CREATE VIEW "t1" AS select * from "dogs"; + CREATE VIEW "t" AS select * from "dogs"; You can run the equivalent of the :ref:`analyze-tables ` command using ``--analyze``: @@ -596,15 +655,15 @@ You can output SQL that will both create the tables and insert the full data use .. code-block:: output BEGIN TRANSACTION; - CREATE TABLE [dogs] ( - [id] INTEGER, - [age] INTEGER, - [name] TEXT + CREATE TABLE "dogs" ( + "id" INTEGER, + "age" INTEGER, + "name" TEXT ); INSERT INTO "dogs" VALUES('1','4','Cleo'); INSERT INTO "dogs" VALUES('2','2','Pancakes'); - CREATE VIEW t1 AS select * from [dogs]; - CREATE VIEW t AS select * from [dogs]; + CREATE VIEW "t1" AS select * from "dogs"; + CREATE VIEW "t" AS select * from "dogs"; COMMIT; Passing ``--save other.db`` will instead use that SQL to populate a new database file: @@ -746,10 +805,10 @@ Use ``--schema`` to include the schema of each table: ------- ----------------------------------------------- Gosh CREATE TABLE Gosh (c1 text, c2 text, c3 text) Gosh2 CREATE TABLE Gosh2 (c1 text, c2 text, c3 text) - dogs CREATE TABLE [dogs] ( - [id] INTEGER, - [age] INTEGER, - [name] TEXT) + dogs CREATE TABLE "dogs" ( + "id" INTEGER, + "age" INTEGER, + "name" TEXT) The ``--nl``, ``--csv``, ``--tsv``, ``--table`` and ``--fmt`` options are also available. @@ -839,13 +898,13 @@ The ``triggers`` command shows any triggers configured for the database: name table sql --------------- --------- ----------------------------------------------------------------- - plants_insert plants CREATE TRIGGER [plants_insert] AFTER INSERT ON [plants] + plants_insert plants CREATE TRIGGER "plants_insert" AFTER INSERT ON "plants" BEGIN - INSERT OR REPLACE INTO [_counts] + INSERT OR REPLACE INTO "_counts" VALUES ( 'plants', COALESCE( - (SELECT count FROM [_counts] WHERE [table] = 'plants'), + (SELECT count FROM "_counts" WHERE "table" = 'plants'), 0 ) + 1 ); @@ -876,8 +935,8 @@ The ``sqlite-utils schema`` command shows the full SQL schema for the database: .. code-block:: output CREATE TABLE "dogs" ( - [id] INTEGER PRIMARY KEY, - [name] TEXT + "id" INTEGER PRIMARY KEY, + "name" TEXT ); This will show the schema for every table and index in the database. To view the schema just for a specified subset of tables pass those as additional arguments: @@ -968,6 +1027,9 @@ To show more than 10 common values, use ``--common-limit 20``. To skip the most 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 @@ -983,16 +1045,16 @@ 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]) + 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: @@ -1041,6 +1103,37 @@ That will look for SpatiaLite in a set of predictable locations. To load it from sqlite-utils create-database empty.db --init-spatialite --load-extension /path/to/spatialite.so +.. _cli_migrate: + +Running migrations +================== + +The ``migrate`` command applies pending Python migrations to a database. For the full migration file format and Python API, see :ref:`migrations`. + +.. code-block:: bash + + sqlite-utils migrate creatures.db path/to/migrations.py + +If you omit the migration path it will search the current directory and subdirectories for files called ``migrations.py``: + +.. code-block:: bash + + sqlite-utils migrate creatures.db + +Use ``--list`` to list applied and pending migrations without running them: + +.. code-block:: bash + + sqlite-utils migrate creatures.db --list + +Use ``--stop-before`` to stop before a named migration. The option can be passed more than once, and can target a specific migration set using ``migration_set:migration_name``: + +.. code-block:: bash + + sqlite-utils migrate creatures.db path/to/migrations.py \ + --stop-before creatures:add_weight \ + --stop-before sales:drop_index + .. _cli_inserting_data: Inserting JSON data @@ -1088,11 +1181,13 @@ You can import all three records into an automatically created ``dogs`` table an sqlite-utils insert dogs.db dogs dogs.json --pk=id +Pass ``--pk`` multiple times to define a compound primary key. + You can skip inserting any records that have a primary key that already exists using ``--ignore``: .. code-block:: bash - sqlite-utils insert dogs.db dogs dogs.json --ignore + 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``: @@ -1102,6 +1197,9 @@ You can delete all the existing rows in the table before inserting the new recor 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 @@ -1126,7 +1224,7 @@ You can insert binary data into a BLOB column by first encoding it using base64 Inserting newline-delimited JSON -------------------------------- -You can also import `newline-delimited JSON `__ using the ``--nl`` option: +You can also import newline-delimited JSON (see `JSON Lines `__) using the ``--nl`` option: .. code-block:: bash @@ -1195,23 +1293,23 @@ Inserting this into a table using ``sqlite-utils insert logs.db logs log.json`` .. code-block:: sql - CREATE TABLE [logs] ( - [httpRequest] TEXT, - [insertId] TEXT, - [labels] TEXT + 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 + CREATE TABLE "logs" ( + "httpRequest_latency" TEXT, + "httpRequest_requestMethod" TEXT, + "httpRequest_requestSize" TEXT, + "httpRequest_status" INTEGER, + "insertId" TEXT, + "labels_service" TEXT ); .. _cli_insert_csv_tsv: @@ -1245,7 +1343,9 @@ To stop inserting after a specified number of records - useful for getting a fas A progress bar is displayed when inserting data from a file. You can hide the progress bar using the ``--silent`` option. -By default every column inserted from a CSV or TSV file will be of type ``TEXT``. To automatically detect column types - resulting in a mix of ``TEXT``, ``INTEGER`` and ``FLOAT`` columns, use the ``--detect-types`` option (or its shortcut ``-d``). +By default, column types are automatically detected for CSV or TSV files - resulting in a mix of ``TEXT``, ``INTEGER`` and ``REAL`` columns. To disable type detection and treat all columns as ``TEXT``, use the ``--no-detect-types`` option. + +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: @@ -1259,9 +1359,9 @@ The following command: .. code-block:: bash - sqlite-utils insert creatures.db creatures creatures.csv --csv --detect-types + sqlite-utils insert creatures.db creatures creatures.csv --csv -Will produce this schema: +Will produce this schema with automatically detected types: .. code-block:: bash @@ -1270,20 +1370,39 @@ Will produce this schema: .. code-block:: output CREATE TABLE "creatures" ( - [name] TEXT, - [age] INTEGER, - [weight] FLOAT + "name" TEXT, + "age" INTEGER, + "weight" REAL ); -You can set the ``SQLITE_UTILS_DETECT_TYPES`` environment variable if you want ``--detect-types`` to be the default behavior: +.. _cli_insert_csv_tsv_column_types: + +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 - export SQLITE_UTILS_DETECT_TYPES=1 + 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: -.. code-block:: csv +:: name,age,weight Cleo,6, @@ -1352,8 +1471,8 @@ This will produce the following schema: .. code-block:: sql - CREATE TABLE [loglines] ( - [line] TEXT + CREATE TABLE "loglines" ( + "line" TEXT ); You can also insert the entire contents of the file into a single column called ``text`` using ``--text``: @@ -1366,8 +1485,8 @@ The schema here will be: .. code-block:: sql - CREATE TABLE [content] ( - [text] TEXT + CREATE TABLE "content" ( + "text" TEXT ); .. _cli_insert_convert: @@ -1460,8 +1579,8 @@ The result looks like this: .. code-block:: output BEGIN TRANSACTION; - CREATE TABLE [words] ( - [word] TEXT + CREATE TABLE "words" ( + "word" TEXT ); INSERT INTO "words" VALUES('A'); INSERT INTO "words" VALUES('bunch'); @@ -1470,6 +1589,27 @@ The result looks like this: COMMIT; +.. _cli_insert_code: + +Inserting rows generated by Python code +======================================= + +Instead of providing a ``FILE`` to import, you can use the ``--code`` option to pass a block of Python code that generates the rows to insert. This is the command-line equivalent of calling ``db["creatures"].insert_all(rows())`` from the :ref:`Python API `. + +Your code should define either a ``rows()`` function that returns or yields dictionaries, or a ``rows`` iterable such as a list of dictionaries: + +.. code-block:: bash + + sqlite-utils insert data.db creatures --code ' + def rows(): + yield {"id": 1, "name": "Cleo"} + yield {"id": 2, "name": "Suna"} + ' --pk id + +``--code`` can also be given a path to a Python ``.py`` file. + +The ``--code`` option works with both ``sqlite-utils insert`` and ``sqlite-utils upsert``, and composes with table options such as ``--pk``, ``--replace``, ``--alter``, ``--not-null`` and ``--default``. It cannot be combined with a ``FILE`` argument or with input format options such as ``--csv`` or ``--convert``. + .. _cli_insert_replace: Insert-replacing data @@ -1484,6 +1624,9 @@ To replace a dog with in ID of 2 with a new record, run the following: echo '{"id": 2, "name": "Pancakes", "age": 3}' | \ sqlite-utils insert dogs.db dogs - --pk=id --replace +.. note:: + In Python: :ref:`table.insert(..., replace=True) ` CLI reference: :ref:`sqlite-utils insert ` + .. _cli_upsert: Upserting data @@ -1502,12 +1645,17 @@ For example: 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 @@ -1566,10 +1714,10 @@ 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 + 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. @@ -1584,10 +1732,10 @@ This will result in the following schema: .. code-block:: sql - CREATE TABLE [images] ( - [path] TEXT PRIMARY KEY, - [md5] TEXT, - [mtime] FLOAT + 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. @@ -1709,7 +1857,8 @@ You can include named parameters in your where clause and populate them using on The ``--dry-run`` option will output a preview of the conversion against the first ten rows, without modifying the database. -By default any rows with a falsey value for the column - such as ``0`` or ``null`` - will be skipped. Use the ``--no-skip-false`` option to disable this behaviour. +.. note:: + In Python: :ref:`table.convert() ` CLI reference: :ref:`sqlite-utils convert ` .. _cli_convert_import: @@ -1833,7 +1982,19 @@ These recipes can be used in the code passed to ``sqlite-utils convert`` like th sqlite-utils convert my.db mytable mycolumn \ 'r.jsonsplit(value)' -To use any of the documented parameters, do this: +You can also pass the recipe function directly without the ``(value)`` part - sqlite-utils will detect that it is a callable and use it automatically: + +.. code-block:: bash + + sqlite-utils convert my.db mytable mycolumn r.parsedate + +This shorter syntax works for any callable, including functions from imported modules: + +.. code-block:: bash + + sqlite-utils convert my.db mytable mycolumn json.loads --import json + +To use any of the documented parameters, use the full function call syntax: .. code-block:: bash @@ -1886,10 +2047,10 @@ The type of the returned values will be taken into account when creating the new .. code-block:: sql - CREATE TABLE [places] ( - [location] TEXT, - [latitude] FLOAT, - [longitude] FLOAT + CREATE TABLE "places" ( + "location" TEXT, + "latitude" REAL, + "longitude" REAL ); The code function can also return ``None``, in which case its output will be ignored. You can drop the original column at the end of the operation by adding ``--drop``. @@ -1909,6 +2070,8 @@ This will create a table called ``mytable`` with two columns - an integer ``id`` You can pass as many column-name column-type pairs as you like. Valid types are ``integer``, ``text``, ``float`` and ``blob``. +Pass ``--pk`` more than once for a compound primary key that covers multiple columns. + You can specify columns that should be NOT NULL using ``--not-null colname``. You can specify default values for columns using ``--default colname defaultvalue``. .. code-block:: bash @@ -1931,11 +2094,11 @@ You can specify columns that should be NOT NULL using ``--not-null colname``. Yo table schema ------- -------------------------------- - mytable CREATE TABLE [mytable] ( - [id] INTEGER PRIMARY KEY, - [name] TEXT NOT NULL, - [age] INTEGER NOT NULL, - [is_good] INTEGER DEFAULT '1' + mytable CREATE TABLE "mytable" ( + "id" INTEGER PRIMARY KEY, + "name" TEXT NOT NULL, + "age" INTEGER NOT NULL, + "is_good" INTEGER DEFAULT '1' ) You can specify foreign key relationships between the tables you are creating using ``--fk colname othertable othercolumn``: @@ -1962,20 +2125,42 @@ You can specify foreign key relationships between the tables you are creating us table schema ------- ------------------------------------------------- - authors CREATE TABLE [authors] ( - [id] INTEGER PRIMARY KEY, - [name] TEXT + authors CREATE TABLE "authors" ( + "id" INTEGER PRIMARY KEY, + "name" TEXT ) - books CREATE TABLE [books] ( - [id] INTEGER PRIMARY KEY, - [title] TEXT, - [author_id] INTEGER REFERENCES [authors]([id]) + books CREATE TABLE "books" ( + "id" INTEGER PRIMARY KEY, + "title" TEXT, + "author_id" INTEGER REFERENCES "authors"("id") ) +You can create a table in `SQLite STRICT mode `__ using ``--strict``: + +.. code-block:: bash + + sqlite-utils create-table mydb.db mytable id integer name text --strict + +.. code-block:: bash + + sqlite-utils tables mydb.db --schema -t + +.. code-block:: output + + table schema + ------- ------------------------ + mytable CREATE TABLE "mytable" ( + "id" INTEGER, + "name" TEXT + ) STRICT + If a table with the same name already exists, you will get an error. You can choose to silently ignore this error with ``--ignore``, or you can replace the existing table with a new, empty table using ``--replace``. You can also pass ``--transform`` to transform the existing table to match the new schema. See :ref:`python_api_explicit_create` in the Python library documentation for details of how this option works. +.. note:: + In Python: :ref:`table.create() ` CLI reference: :ref:`sqlite-utils create-table ` + .. _cli_renaming_tables: Renaming a table @@ -1989,6 +2174,9 @@ Yo ucan rename a table using the ``rename-table`` command: Pass ``--ignore`` to ignore any errors caused by the table not existing, or the new name already being in use. +.. note:: + In Python: :ref:`db.rename_table() ` CLI reference: :ref:`sqlite-utils rename-table ` + .. _cli_duplicate_table: Duplicating tables @@ -2000,6 +2188,9 @@ The ``duplicate`` command duplicates a table - creating a new table with the sam sqlite-utils duplicate books.db authors authors_copy +.. note:: + In Python: :ref:`table.duplicate() ` CLI reference: :ref:`sqlite-utils duplicate ` + .. _cli_drop_table: Dropping tables @@ -2013,12 +2204,15 @@ You can drop a table using the ``drop-table`` command: Use ``--ignore`` to ignore the error if the table does not exist. +.. note:: + In Python: :ref:`table.drop() ` CLI reference: :ref:`sqlite-utils drop-table ` + .. _cli_transform_table: Transforming tables =================== -The ``transform`` command allows you to apply complex transformations to a table that cannot be implemented using a regular SQLite ``ALTER TABLE`` command. See :ref:`python_api_transform` for details of how this works. +The ``transform`` command allows you to apply complex transformations to a table that cannot be implemented using a regular SQLite ``ALTER TABLE`` command. See :ref:`python_api_transform` for details of how this works. By default, the ``transform`` command preserves a table's ``STRICT`` mode. .. code-block:: bash @@ -2061,9 +2255,15 @@ Every option for this table (with the exception of ``--pk-none``) can be specifi ``--drop-foreign-key column`` Drop the specified foreign key. -``--add-foregn-key column other_table other_column`` +``--add-foreign-key column other_table other_column`` Add a foreign key constraint to ``column`` pointing to ``other_table.other_column``. +``--strict`` + Convert the table to a `SQLite STRICT table `__. The command fails if the available SQLite version does not support strict tables. If existing rows contain values that are incompatible with their declared column types the transformation fails and the original table is left unchanged. + +``--no-strict`` + Convert a strict table back to a regular non-strict table. + If you want to see the SQL that will be executed to make the change without actually executing it, add the ``--sql`` flag. For example: .. code-block:: bash @@ -2079,16 +2279,19 @@ If you want to see the SQL that will be executed to make the change without actu .. code-block:: output - CREATE TABLE [roadside_attractions_new_4033a60276b9] ( - [id] INTEGER PRIMARY KEY, - [longitude] FLOAT, - [latitude] FLOAT, - [name] TEXT DEFAULT 'Untitled' + CREATE TABLE "roadside_attractions_new_4033a60276b9" ( + "id" INTEGER PRIMARY KEY, + "longitude" FLOAT, + "latitude" FLOAT, + "name" TEXT DEFAULT 'Untitled' ); - INSERT INTO [roadside_attractions_new_4033a60276b9] ([longitude], [latitude], [id], [name]) - SELECT [longitude], [latitude], [pk], [name] FROM [roadside_attractions]; - DROP TABLE [roadside_attractions]; - ALTER TABLE [roadside_attractions_new_4033a60276b9] RENAME TO [roadside_attractions]; + INSERT INTO "roadside_attractions_new_4033a60276b9" ("longitude", "latitude", "id", "name") + SELECT "longitude", "latitude", "pk", "name" FROM "roadside_attractions"; + DROP TABLE "roadside_attractions"; + ALTER TABLE "roadside_attractions_new_4033a60276b9" RENAME TO "roadside_attractions"; + +.. note:: + In Python: :ref:`table.transform() ` CLI reference: :ref:`sqlite-utils transform ` .. _cli_transform_table_add_primary_key_to_rowid: @@ -2105,8 +2308,8 @@ SQLite tables that are created without an explicit primary key are created as `r .. code-block:: output - CREATE TABLE [chickens] ( - [name] TEXT + CREATE TABLE "chickens" ( + "name" TEXT ); .. code-block:: bash @@ -2140,8 +2343,8 @@ You can use ``sqlite-utils transform ... --pk id`` to add a primary key column c .. code-block:: output CREATE TABLE "chickens" ( - [id] INTEGER PRIMARY KEY, - [name] TEXT + "id" INTEGER PRIMARY KEY, + "name" TEXT ); .. code-block:: bash @@ -2176,6 +2379,8 @@ The ``sqlite-utils extract`` command can be used to extract specified columns in Take a look at the Python API documentation for :ref:`python_api_extract` for a detailed description of how this works, including examples of table schemas before and after running an extraction operation. +Rows where every extracted column is ``null`` are not extracted - those rows get a ``null`` value in their new foreign key column and no record is created for them in the lookup table. + The command takes a database, table and one or more columns that should be extracted. To extract the ``species`` column from the ``trees`` table you would run: .. code-block:: bash @@ -2187,17 +2392,17 @@ This would produce the following schema: .. code-block:: sql CREATE TABLE "trees" ( - [id] INTEGER PRIMARY KEY, - [TreeAddress] TEXT, - [species_id] INTEGER, + "id" INTEGER PRIMARY KEY, + "TreeAddress" TEXT, + "species_id" INTEGER, FOREIGN KEY(species_id) REFERENCES species(id) ); - CREATE TABLE [species] ( - [id] INTEGER PRIMARY KEY, - [species] TEXT + CREATE TABLE "species" ( + "id" INTEGER PRIMARY KEY, + "species" TEXT ); - CREATE UNIQUE INDEX [idx_species_species] - ON [species] ([species]); + CREATE UNIQUE INDEX "idx_species_species" + ON "species" ("species"); The command takes the following options: @@ -2230,40 +2435,43 @@ After running the above, the command ``sqlite-utils schema global.db`` reveals t .. code-block:: sql - CREATE TABLE [countries] ( - [id] INTEGER PRIMARY KEY, - [country] TEXT, - [name] TEXT + CREATE TABLE "countries" ( + "id" INTEGER PRIMARY KEY, + "country" TEXT, + "name" TEXT ); CREATE TABLE "power_plants" ( - [country_id] INTEGER, - [name] TEXT, - [gppd_idnr] TEXT, - [capacity_mw] TEXT, - [latitude] TEXT, - [longitude] TEXT, - [primary_fuel] TEXT, - [other_fuel1] TEXT, - [other_fuel2] TEXT, - [other_fuel3] TEXT, - [commissioning_year] TEXT, - [owner] TEXT, - [source] TEXT, - [url] TEXT, - [geolocation_source] TEXT, - [wepp_id] TEXT, - [year_of_capacity_data] TEXT, - [generation_gwh_2013] TEXT, - [generation_gwh_2014] TEXT, - [generation_gwh_2015] TEXT, - [generation_gwh_2016] TEXT, - [generation_gwh_2017] TEXT, - [generation_data_source] TEXT, - [estimated_generation_gwh] TEXT, - FOREIGN KEY([country_id]) REFERENCES [countries]([id]) + "country_id" INTEGER, + "name" TEXT, + "gppd_idnr" TEXT, + "capacity_mw" TEXT, + "latitude" TEXT, + "longitude" TEXT, + "primary_fuel" TEXT, + "other_fuel1" TEXT, + "other_fuel2" TEXT, + "other_fuel3" TEXT, + "commissioning_year" TEXT, + "owner" TEXT, + "source" TEXT, + "url" TEXT, + "geolocation_source" TEXT, + "wepp_id" TEXT, + "year_of_capacity_data" TEXT, + "generation_gwh_2013" TEXT, + "generation_gwh_2014" TEXT, + "generation_gwh_2015" TEXT, + "generation_gwh_2016" TEXT, + "generation_gwh_2017" TEXT, + "generation_data_source" TEXT, + "estimated_generation_gwh" TEXT, + FOREIGN KEY("country_id") REFERENCES "countries"("id") ); - CREATE UNIQUE INDEX [idx_countries_country_name] - ON [countries] ([country], [name]); + CREATE UNIQUE INDEX "idx_countries_country_name" + ON "countries" ("country", "name"); + +.. note:: + In Python: :ref:`table.extract() ` CLI reference: :ref:`sqlite-utils extract ` .. _cli_create_view: @@ -2286,6 +2494,9 @@ You can create a view using the ``create-view`` command: Use ``--replace`` to replace an existing view of the same name, and ``--ignore`` to do nothing if a view already exists. +.. note:: + In Python: :ref:`db.create_view() ` CLI reference: :ref:`sqlite-utils create-view ` + .. _cli_drop_view: Dropping views @@ -2299,6 +2510,9 @@ You can drop a view using the ``drop-view`` command: Use ``--ignore`` to ignore the error if the view does not exist. +.. note:: + In Python: :ref:`view.drop() ` CLI reference: :ref:`sqlite-utils drop-view ` + .. _cli_add_column: Adding columns @@ -2310,7 +2524,14 @@ You can add a column using the ``add-column`` command: sqlite-utils add-column mydb.db mytable nameofcolumn text -The last argument here is the type of the column to be created. You can use one of ``text``, ``integer``, ``float`` or ``blob``. If you leave it off, ``text`` will be used. +The last argument here is the type of the column to be created. This can be one of: + +- ``text`` or ``str`` +- ``integer`` or ``int`` +- ``float`` +- ``blob`` or ``bytes`` + +This argument is optional and defaults to ``text``. You can add a column that is a foreign key reference to another table using the ``--fk`` option: @@ -2332,6 +2553,9 @@ You can set a ``NOT NULL DEFAULT 'x'`` constraint on the new column using ``--no sqlite-utils add-column mydb.db dogs friends_count integer --not-null-default 0 +.. note:: + In Python: :ref:`table.add_column() ` CLI reference: :ref:`sqlite-utils add-column ` + .. _cli_add_column_alter: Adding columns automatically on insert/update @@ -2343,6 +2567,9 @@ You can use the ``--alter`` option to automatically add new columns if the data sqlite-utils insert dogs.db dogs new-dogs.json --pk=id --alter +.. note:: + In Python: :ref:`table.insert(..., alter=True) ` + .. _cli_add_foreign_key: Adding foreign key constraints @@ -2370,6 +2597,9 @@ Add ``--ignore`` to ignore an existing foreign key (as opposed to returning an e See :ref:`python_api_add_foreign_key` in the Python API documentation for further details, including how the automatic table guessing mechanism works. +.. note:: + In Python: :ref:`table.add_foreign_key() ` CLI reference: :ref:`sqlite-utils add-foreign-key ` + .. _cli_add_foreign_keys: Adding multiple foreign keys at once @@ -2385,6 +2615,9 @@ Adding a foreign key requires a ``VACUUM``. On large databases this can be an ex When you are using this command each foreign key needs to be defined in full, as four arguments - the table, column, other table and other column. +.. note:: + In Python: :ref:`db.add_foreign_keys() ` CLI reference: :ref:`sqlite-utils add-foreign-keys ` + .. _cli_index_foreign_keys: Adding indexes for all foreign keys @@ -2396,6 +2629,9 @@ If you want to ensure that every foreign key column in your database has a corre sqlite-utils index-foreign-keys books.db +.. note:: + In Python: :ref:`db.index_foreign_keys() ` CLI reference: :ref:`sqlite-utils index-foreign-keys ` + .. _cli_defaults_not_null: Setting defaults and not null constraints @@ -2411,6 +2647,9 @@ You can use the ``--not-null`` and ``--default`` options (to both ``insert`` and --default age 2 \ --default score 5 +.. note:: + In Python: :ref:`not_null= and defaults= arguments ` + .. _cli_create_index: Creating indexes @@ -2442,6 +2681,25 @@ If your column names are already prefixed with a hyphen you'll need to manually Add the ``--analyze`` option to run ``ANALYZE`` against the index after it has been created. +.. note:: + In Python: :ref:`table.create_index() ` CLI reference: :ref:`sqlite-utils create-index ` + +.. _cli_drop_index: + +Dropping indexes +================ + +You can drop an index from an existing table using the ``drop-index`` command: + +.. code-block:: bash + + sqlite-utils drop-index mydb.db mytable idx_mytable_col1 + +Use ``--ignore`` to ignore the error if the index does not exist on that table. + +.. note:: + In Python: :ref:`table.drop_index() ` CLI reference: :ref:`sqlite-utils drop-index ` + .. _cli_fts: Configuring full-text search @@ -2495,6 +2753,9 @@ You can rebuild every FTS table by running ``rebuild-fts`` without passing any t sqlite-utils rebuild-fts mydb.db +.. note:: + In Python: :ref:`table.enable_fts() ` CLI reference: :ref:`sqlite-utils enable-fts ` + .. _cli_search: Executing searches @@ -2539,17 +2800,20 @@ Use the ``--sql`` option to output the SQL that would be executed, rather than r select rowid, * - from [documents] + from "documents" ) select - [original].* + "original".* from - [original] - join [documents_fts] on [original].rowid = [documents_fts].rowid + "original" + join "documents_fts" on "original".rowid = "documents_fts".rowid where - [documents_fts] match :query + "documents_fts" match :query order by - [documents_fts].rank + "documents_fts".rank + +.. note:: + In Python: :ref:`table.search() ` CLI reference: :ref:`sqlite-utils search ` .. _cli_enable_counts: @@ -2574,6 +2838,9 @@ If the ``_counts`` table ever becomes out-of-sync with the actual table counts y sqlite-utils reset-counts mydb.db +.. note:: + In Python: :ref:`table.enable_counts() ` CLI reference: :ref:`sqlite-utils enable-counts ` + .. _cli_analyze: Optimizing index usage with ANALYZE @@ -2597,6 +2864,9 @@ You can run it against specific tables, or against specific named indexes, by pa You can also run ``ANALYZE`` as part of another command using the ``--analyze`` option. This is supported by the ``create-index``, ``insert`` and ``upsert`` commands. +.. note:: + In Python: :ref:`db.analyze() ` CLI reference: :ref:`sqlite-utils analyze ` + .. _cli_vacuum: Vacuum @@ -2608,6 +2878,9 @@ You can run VACUUM to optimize your database like so: sqlite-utils vacuum mydb.db +.. note:: + In Python: :ref:`db.vacuum() ` CLI reference: :ref:`sqlite-utils vacuum ` + .. _cli_optimize: Optimize @@ -2631,6 +2904,9 @@ To optimize specific tables rather than every FTS table, pass those tables as ex sqlite-utils optimize mydb.db table_1 table_2 +.. note:: + In Python: :ref:`table.optimize() ` CLI reference: :ref:`sqlite-utils optimize ` + .. _cli_wal: WAL mode @@ -2650,6 +2926,9 @@ You can disable WAL mode using ``disable-wal``: Both of these commands accept one or more database files as arguments. +.. note:: + In Python: :ref:`db.enable_wal() and db.disable_wal() ` CLI reference: :ref:`sqlite-utils enable-wal ` + .. _cli_dump: Dumping the database to SQL @@ -2665,6 +2944,9 @@ The ``dump`` command outputs a SQL dump of the schema and full contents of the s ... COMMIT; +.. note:: + In Python: :ref:`db.iterdump() ` CLI reference: :ref:`sqlite-utils dump ` + .. _cli_load_extension: Loading SQLite extensions @@ -2712,6 +2994,9 @@ Eight (case-insensitive) types are allowed: * GEOMETRYCOLLECTION * GEOMETRY +.. note:: + In Python: :ref:`table.add_geometry_column() ` CLI reference: :ref:`sqlite-utils add-geometry-column ` + .. _cli_spatialite_indexes: Adding spatial indexes @@ -2725,6 +3010,9 @@ Once you have a geometry column, you can speed up bounding box queries by adding See this `SpatiaLite Cookbook recipe `__ for examples of how to use a spatial index. +.. note:: + In Python: :ref:`table.create_spatial_index() ` CLI reference: :ref:`sqlite-utils create-spatial-index ` + .. _cli_install: Installing packages @@ -2752,29 +3040,3 @@ You can uninstall packages that were installed using ``sqlite-utils install`` wi sqlite-utils uninstall beautifulsoup4 Use ``-y`` to skip the request for confirmation. - -.. _cli_tui: - -Experimental TUI -================ - -A TUI is a "text user interface" (or "terminal user interface") - a keyboard and mouse driven graphical interface running in your terminal. - -``sqlite-utils`` has experimental support for a TUI for building command-line invocations, built on top of the `Trogon `__ TUI library. - -To enable this feature you will need to install the ``trogon`` dependency. You can do that like so: - -.. code-block:: bash - - sqite-utils install trogon - -Once installed, running the ``sqlite-utils tui`` command will launch the TUI interface: - -.. code-block:: bash - - sqlite-utils tui - -You can then construct a command by selecting options from the menus, and execute it using ``Ctrl+R``. - -.. image:: _static/img/tui.png - :alt: A TUI interface for sqlite-utils - the left column shows a list of commands, while the right panel has a form for constructing arguments to the add-column command. diff --git a/docs/conf.py b/docs/conf.py index 859c6b9..4f29b39 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -1,8 +1,10 @@ #!/usr/bin/env python3 # -*- coding: utf-8 -*- -from subprocess import Popen, PIPE -from beanbag_docutils.sphinx.ext.github import github_linkcode_resolve +import inspect +from pathlib import Path +from subprocess import Popen, PIPE, check_output +import sys # This file is execfile()d with the current directory set to its # containing dir. @@ -45,14 +47,52 @@ extlinks = { } +def _linkcode_git_ref(): + try: + return check_output(["git", "rev-parse", "HEAD"]).decode("utf8").strip() + except Exception: + return "main" + + def linkcode_resolve(domain, info): - return github_linkcode_resolve( - domain=domain, - info=info, - allowed_module_names=["sqlite_utils"], - github_org_id="simonw", - github_repo_id="sqlite-utils", - branch="main", + if domain != "py": + return None + + module_name = info.get("module") + if not module_name or module_name.split(".")[0] != "sqlite_utils": + return None + + module = sys.modules.get(module_name) + if module is None: + return None + + obj = module + for part in info.get("fullname", "").split("."): + obj = getattr(obj, part, None) + if obj is None: + return None + + if isinstance(obj, property): + obj = obj.fget + + try: + obj = inspect.unwrap(obj) + source_file = inspect.getsourcefile(obj) + _, line_number = inspect.getsourcelines(obj) + except Exception: + return None + + if source_file is None: + return None + + try: + filename = Path(source_file).resolve().relative_to(Path(__file__).parent.parent) + except ValueError: + return None + + return ( + "https://github.com/simonw/sqlite-utils/blob/" + f"{_linkcode_git_ref()}/{filename}#L{line_number}" ) @@ -79,7 +119,7 @@ author = "Simon Willison" # # The short X.Y version. pipe = Popen("git describe --tags --always", stdout=PIPE, shell=True) -git_version = pipe.stdout.read().decode("utf8") +git_version = pipe.stdout.read().decode("utf8") if pipe.stdout else "" if git_version: version = git_version.rsplit("-", 1)[0] diff --git a/docs/contributing.rst b/docs/contributing.rst index 2e883ee..f10b02a 100644 --- a/docs/contributing.rst +++ b/docs/contributing.rst @@ -13,83 +13,61 @@ All improvements to the software should start with an issue. Read `How I build a Obtaining the code ================== -To work on this library locally, first checkout the code. Then create a new virtual environment:: +To work on this library locally, first checkout the code:: git clone git@github.com:simonw/sqlite-utils cd sqlite-utils - python3 -mvenv venv - source venv/bin/activate -Or if you are using ``pipenv``:: +Use ``uv run`` to run the development version of the tool:: - pipenv shell - -Within the virtual environment running ``sqlite-utils`` should run your locally editable version of the tool. You can use ``which sqlite-utils`` to confirm that you are running the version that lives in your virtual environment. + uv run sqlite-utils --help .. _contributing_tests: Running the tests ================= -To install the dependencies and test dependencies:: +Use ``uv run`` to run the tests:: - pip install -e '.[test]' - -To run the tests:: - - pytest + uv run pytest .. _contributing_docs: Building the documentation ========================== -To build the documentation, first install the documentation dependencies:: +To build the documentation run this command:: - pip install -e '.[docs]' + uv run make livehtml --directory docs -Then run ``make livehtml`` from the ``docs/`` directory to start a server on port 8000 that will serve the documentation and live-reload any time you make an edit to a ``.rst`` file:: - - cd docs - make livehtml +This will start a server on port 8000 that will serve the documentation and live-reload any time you make an edit to a ``.rst`` file. The `cog `__ tool is used to maintain portions of the documentation. You can run it like so:: - cog -r docs/*.rst + uv run cog -r docs/*.rst .. _contributing_linting: Linting and formatting ====================== -``sqlite-utils`` uses `Black `__ for code formatting, and `flake8 `__ and `mypy `__ for linting and type checking. +``sqlite-utils`` uses `Black `__ for code formatting, and `flake8 `__ and `mypy `__ for linting and type checking:: -Black is installed as part of ``pip install -e '.[test]'`` - you can then format your code by running it in the root of the project:: + uv run black . - black . +Linting tools can be run like this:: -To install ``mypy`` and ``flake8`` run the following:: - - pip install -e '.[flake8,mypy]' - -Both commands can then be run in the root of the project like this:: - - flake8 - mypy sqlite_utils + uv run flake8 + uv run mypy sqlite_utils All three of these tools are run by our CI mechanism against every commit and pull request. .. _contributing_just: -Using Just and pipenv -===================== +Using Just +========== -If you install `Just `__ and `pipenv `__ you can use them to manage your local development environment. - -To create a virtual environment and install all development dependencies, run:: - - cd sqlite-utils - just init +If you install `Just `__ you can use it to manage your local development environment. To run all of the tests and linters:: @@ -144,7 +122,7 @@ We increment ``minor`` for new features. We increment ``patch`` for bugfix releass. -To release a new version, first create a commit that updates the version number in ``setup.py`` and the :ref:`the changelog ` with highlights of the new version. An example `commit can be seen here `__:: +To release a new version, first create a commit that updates the version number in ``pyproject.toml`` and the :ref:`the changelog ` with highlights of the new version. An example `commit can be seen here `__:: # Update changelog git commit -m " Release 3.29 diff --git a/docs/index.rst b/docs/index.rst index 27a22c3..f190d47 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -36,8 +36,10 @@ Contents installation cli python-api + migrations plugins reference cli-reference + upgrading contributing changelog diff --git a/docs/installation.rst b/docs/installation.rst index beb6d4a..1333f5d 100644 --- a/docs/installation.rst +++ b/docs/installation.rst @@ -52,15 +52,15 @@ On some platforms the ability to load additional extensions (via ``conn.load_ext You may also see the error ``sqlite3.OperationalError: table sqlite_master may not be modified`` when trying to alter an existing table. -You can work around these limitations by installing either the `pysqlite3 `__ package or the `sqlean.py `__ package, both of which provide drop-in replacements for the standard library ``sqlite3`` module but with a recent version of SQLite and full support for loading extensions. +You can work around these limitations by installing the `pysqlite3 `__ package, which provides a drop-in replacement for the standard library ``sqlite3`` module but with a recent version of SQLite and full support for loading extensions. -To install ``sqlean.py`` (which has compiled binary wheels available for all major platforms) run the following: +To install ``pysqlite3`` run the following: .. code-block:: bash - sqlite-utils install sqlean.py + sqlite-utils install pysqlite3 -``pysqlite3`` and ``sqlean.py`` do not provide implementations of the ``.iterdump()`` method. To use that method (see :ref:`python_api_itedump`) or the ``sqlite-utils dump`` command you should also install the ``sqlite-dump`` package: +``pysqlite3`` does not provide an implementation of the ``.iterdump()`` method. To use that method (see :ref:`python_api_itedump`) or the ``sqlite-utils dump`` command you should also install the ``sqlite-dump`` package: .. code-block:: bash @@ -87,4 +87,4 @@ For ``zsh``: Add this code to ``~/.zshrc`` or ``~/.bashrc`` to automatically run it when you start a new shell. -See `the Click documentation `__ for more details. \ No newline at end of file +See `the Click documentation `__ for more details. diff --git a/docs/migrations.rst b/docs/migrations.rst new file mode 100644 index 0000000..23aa9d8 --- /dev/null +++ b/docs/migrations.rst @@ -0,0 +1,194 @@ +.. _migrations: + +===================== + Database migrations +===================== + +``sqlite-utils`` includes a migration system for applying repeatable changes to SQLite database files. + +A migration is a Python function that receives a :class:`sqlite_utils.Database` instance and then executes Python code to modify that database - creating or transforming tables, adding indexes, inserting rows, or any other operation supported by SQLite. + +Migrations are grouped into named sets using the :class:`sqlite_utils.Migrations` class, and each applied migration is recorded in the ``_sqlite_migrations`` table in that database. + +This means you can run the migrate operation multiple times and it will only apply migrations that have not previously been recorded. + +.. _migrations_define: + +Defining migrations +=================== + +Ordered migration sets are defined by first creating a :class:`sqlite_utils.Migrations` object. + +Individual migrations are Python functions that are then registered with that migration set. Each migration function is passed a single argument that is a :ref:`sqlite_utils.Database ` instance. + +The name passed to ``Migrations("creatures")`` identifies that set of migrations. Use a name that is unique for your project, since multiple migration sets can be applied to the same database. + +Here is a simple example of a ``migrations.py`` file which creates a table, then adds an extra column to that table in a second migration: + +.. code-block:: python + + from sqlite_utils import Migrations + + migrations = Migrations("creatures") + + @migrations() + def create_table(db): + db["creatures"].create( + {"id": int, "name": str, "species": str}, + pk="id", + ) + + @migrations() + def add_weight(db): + db["creatures"].add_column("weight", float) + +.. _migrations_python: + +Applying migrations in Python +============================= + +Once you have a ``Migrations(name)`` collection with one or more migrations registered to it, you can execute them in Python code like this: + +.. code-block:: python + + from sqlite_utils import Database + + db = Database("creatures.db") + migrations.apply(db) + +Running ``migrations.apply(db)`` repeatedly is safe. Migrations that already have a matching ``migration_set`` and ``name`` row in ``_sqlite_migrations`` will be skipped. + +Migration functions are applied in the order that they were registered. The function name is used as the migration name unless you pass one explicitly: + +.. code-block:: python + + @migrations(name="001_create_table") + def create_table(db): + db["creatures"].create({"id": int, "name": str}, pk="id") + +When you apply a set of migrations you can stop part way through by specifying a ``stop_before=`` migration name: + +.. code-block:: python + + migrations.apply(db, stop_before="add_weight") + +.. _migrations_transactions: + +Migrations and transactions +=========================== + +Each migration runs inside a transaction, together with the ``_sqlite_migrations`` record of it having been applied. If a migration function raises an exception, everything it did is rolled back, no record is written and the migration stays pending - so fixing the error and re-applying will run that migration again from a clean state. Migrations that completed earlier in the same ``apply()`` run stay applied. + +Some operations cannot run inside a transaction, for example ``VACUUM`` or changing the journal mode with ``db.enable_wal()``. Register migrations like these with ``transactional=False``: + +.. code-block:: python + + @migrations(transactional=False) + def compact(db): + db.execute("VACUUM") + +A migration registered with ``transactional=False`` runs without a wrapping transaction, so if it fails part way through any changes it already made will not be rolled back, and re-applying will run the whole function again. + +Avoid calling ``db.commit()`` or otherwise managing transactions manually inside a transactional migration - register the migration with ``transactional=False`` if it needs to control its own transactions. Using ``with db.atomic():`` blocks inside a migration is fine: they nest as savepoints within the migration's transaction, so the migration as a whole still commits or rolls back as a single unit. See :ref:`python_api_transactions`. + +Applying migrations using the CLI +================================= + +Run migrations using the ``sqlite-utils migrate`` command: + +.. code-block:: bash + + sqlite-utils migrate creatures.db path/to/migrations.py + +The first argument is the database file. The remaining arguments can be paths to migration files or directories containing migration files. + +If you omit migration paths, ``sqlite-utils`` searches the current directory and subdirectories for files called ``migrations.py``: + +.. code-block:: bash + + sqlite-utils migrate creatures.db + +You can also pass a directory. Every ``migrations.py`` file in that directory tree will be considered: + +.. code-block:: bash + + sqlite-utils migrate creatures.db path/to/project/ + +Running the command repeatedly is safe. Migrations that already have a matching ``migration_set`` and ``name`` row in ``_sqlite_migrations`` will be skipped. + +Listing migrations +================== + +Use ``--list`` to show applied and pending migrations without running them. This is a read-only operation - it will not create the database file or the ``_sqlite_migrations`` table: + +.. code-block:: bash + + sqlite-utils migrate creatures.db --list + +Example output: + +.. code-block:: output + + Migrations for: creatures + + Applied: + create_table - 2026-06-09 17:23:12.048092+00:00 + add_weight - 2026-06-09 17:23:12.051249+00:00 + + Pending: + add_age + +Stopping before a migration +=========================== + +When applying migrations using the CLI, you can stop before a named migration: + +.. code-block:: bash + + sqlite-utils migrate creatures.db path/to/migrations.py --stop-before add_weight + +This applies any pending migrations before ``add_weight`` and leaves ``add_weight`` and later migrations pending. An unqualified migration name matches in any migration set. + +You can also target a specific migration set using ``migration_set:migration_name``. This is useful if a migrations file contains more than one migration set, or if multiple sets use the same migration name: + +.. code-block:: bash + + sqlite-utils migrate creatures.db path/to/migrations.py \ + --stop-before creatures:add_weight \ + --stop-before sales:drop_index + +The ``--stop-before`` option can be passed more than once. + +If a ``--stop-before`` value does not match any known migration the command exits with an error, rather than silently applying everything. Naming a migration that has already been applied is also an error - stopping before it is impossible to honor - and no pending migrations are applied. + +Verbose output +============== + +Use ``--verbose`` or ``-v`` to show the schema before and after migrations are applied, plus a unified diff when the schema changes: + +.. code-block:: bash + + sqlite-utils migrate creatures.db --verbose + +Migrating from sqlite-migrate +============================= + +This system uses the same migration table format as the older `sqlite-migrate `__ package. To use existing migration files directly with ``sqlite-utils``, update their import from ``sqlite_migrate`` to ``sqlite_utils``: + +.. code-block:: python + + from sqlite_utils import Migrations + + migration = Migrations("creatures") + + @migration() + def create_table(db): + db["creatures"].create({"id": int, "name": str}, pk="id") + +Python API +========== + +.. autoclass:: sqlite_utils.migrations.Migrations + :members: + :undoc-members: + :exclude-members: _Migration, _AppliedMigration diff --git a/docs/plugins.rst b/docs/plugins.rst index 8e1a37a..99588ee 100644 --- a/docs/plugins.rst +++ b/docs/plugins.rst @@ -49,7 +49,7 @@ In that folder create two files. The first is a ``pyproject.toml`` file describi [project.entry-points.sqlite_utils] hello_world = "sqlite_utils_hello_world" -The ```[project.entry-points.sqlite_utils]`` section tells ``sqlite-tils`` which module to load when executing the plugin. +The ``[project.entry-points.sqlite_utils]`` section tells ``sqlite-utils`` which module to load when executing the plugin. Then create ``sqlite_utils_hello_world.py`` with the following content: @@ -75,7 +75,7 @@ Or pass the path to your plugin directory: .. code-block:: bash - sqlite-utils install -e `/dev/sqlite-utils-hello-world + sqlite-utils install -e /dev/sqlite-utils-hello-world Now, running this should execute your new command: @@ -115,14 +115,32 @@ Example implementation: "Say hello world" click.echo("Hello world!") +New commands implemented by plugins can invoke existing commands using the `context.invoke `__ mechanism. + +As a special niche feature, if your plugin needs to import some files and then act against an in-memory database containing those files you can forward to the :ref:`sqlite-utils memory command ` and pass it ``return_db=True``: + +.. code-block:: python + + @cli.command() + @click.pass_context + @click.argument( + "paths", + type=click.Path(file_okay=True, dir_okay=False, allow_dash=True), + required=False, + nargs=-1, + ) + def show_schema_for_files(ctx, paths): + from sqlite_utils.cli import memory + db = ctx.invoke(memory, paths=paths, return_db=True) + # Now do something with that database + click.echo(db.schema) + .. _plugins_hooks_prepare_connection: prepare_connection(conn) ~~~~~~~~~~~~~~~~~~~~~~~~ -This hook is called when a new SQLite database connection is created. You can -use it to `register custom SQL functions `_, -aggregates and collations. For example: +This hook is called when a new SQLite database connection is created. You can use it to `register custom SQL functions `_, aggregates and collations. For example: .. code-block:: python @@ -134,8 +152,7 @@ aggregates and collations. For example: "hello", 1, lambda name: f"Hello, {name}!" ) -This registers a SQL function called ``hello`` which takes a single -argument and can be called like this: +This registers a SQL function called ``hello`` which takes a single argument and can be called like this: .. code-block:: sql diff --git a/docs/python-api.rst b/docs/python-api.rst index 9d396c6..43b734d 100644 --- a/docs/python-api.rst +++ b/docs/python-api.rst @@ -19,7 +19,7 @@ Here's how to create a new SQLite database file containing a new ``chickens`` ta from sqlite_utils import Database db = Database("chickens.db") - db["chickens"].insert_all([{ + db.table("chickens").insert_all([{ "name": "Azi", "color": "blue", }, { @@ -33,11 +33,13 @@ Here's how to create a new SQLite database file containing a new ``chickens`` ta "color": "black", }]) +The inserted rows are saved to the database file straight away - methods like ``insert_all()`` commit their own changes, so no ``commit()`` call is needed. See :ref:`python_api_transactions` for how this works. + You can loop through those rows like this: .. code-block:: python - for row in db["chickens"].rows: + for row in db.table("chickens").rows: print(row) Which outputs the following:: @@ -93,6 +95,8 @@ Instead of a file path you can pass in an existing SQLite connection: db = Database(sqlite3.connect("my_database.db")) +The connection must use Python's default transaction handling. Connections created with the Python 3.12+ ``sqlite3.connect(..., autocommit=True)`` or ``autocommit=False`` options are rejected with a ``sqlite_utils.db.TransactionError`` - see :ref:`python_api_transactions_modes`. + If you want to create an in-memory database, you can do so like this: .. code-block:: python @@ -105,6 +109,14 @@ You can also create a named in-memory database. Unlike regular memory databases db = Database(memory_name="my_shared_database") +After creating a ``Database`` you can use ``db.memory`` and ``db.memory_name`` to tell whether it is backed by an in-memory database and to read the shared cache name. ``db.memory`` is ``True`` for any in-memory database and ``db.memory_name`` holds the name passed to ``memory_name=``, or ``None`` otherwise. + +.. code-block:: python + + db = Database(memory_name="shared") + db.memory # True + db.memory_name # "shared" + Connections use ``PRAGMA recursive_triggers=on`` by default. If you don't want to use `recursive triggers `__ you can turn them off using: .. code-block:: python @@ -117,6 +129,39 @@ By default, any :ref:`sqlite-utils plugins ` that implement the :ref:`p db = Database(memory=True, execute_plugins=False) +You can pass ``strict=True`` to enable `SQLite STRICT mode `__ for all tables created using this database object: + +.. code-block:: python + + db = Database("my_database.db", strict=True) + +.. _python_api_close: + +Closing a database +------------------ + +Database objects maintain a connection to the underlying SQLite database. You can explicitly close this connection using the ``.close()`` method: + +.. code-block:: python + + db = Database("my_database.db") + # ... use the database ... + db.close() + +The ``Database`` object also works as a context manager, which will automatically close the connection when the ``with`` block exits: + +.. code-block:: python + + with Database("my_database.db") as db: + db["my_table"].insert({"name": "Example"}) + # Connection is automatically closed here + +Exiting the block is equivalent to calling ``db.close()``: the connection is closed and any transaction still open at that point is rolled back. This matches SQLite's own behavior when a connection closes. + +This rarely matters in practice. Everything that writes to the database - including raw ``db.execute()`` statements - commits automatically, so a transaction can only be open here if you explicitly started one with ``db.begin()`` and have not yet committed it. In that case the decision to commit stays with you: committing automatically on exit could silently persist half-finished work, for example if your code returned early from the block. Call ``db.commit()`` when the work is complete. + +Note this differs from the ``sqlite3.Connection`` context manager in the standard library, which commits on success but does not close the connection. See :ref:`python_api_transactions` for the full transaction model. + .. _python_api_attach: Attaching additional databases @@ -139,6 +184,9 @@ You can attach an additional database using the ``.attach()`` method, providing You can reference tables in the attached database using the alias value you passed to ``db.attach(alias, filepath)`` as a prefix, for example the ``second.table_in_second`` reference in the SQL query above. +.. note:: + In the CLI: :ref:`sqlite-utils --attach ` + .. _python_api_tracing: Tracing queries @@ -164,7 +212,7 @@ You can also turn on a tracer function temporarily for a block of code using the db = Database(memory=True) # ... later with db.tracer(print): - db["dogs"].insert({"name": "Cleo"}) + db.table("dogs").insert({"name": "Cleo"}) This example will print queries only for the duration of the ``with`` block. @@ -185,13 +233,33 @@ The ``db.query(sql)`` function executes a SQL query and returns an iterator over .. code-block:: python db = Database(memory=True) - db["dogs"].insert_all([{"name": "Cleo"}, {"name": "Pancakes"}]) + db.table("dogs").insert_all([{"name": "Cleo"}, {"name": "Pancakes"}]) for row in db.query("select * from dogs"): print(row) # Outputs: # {'name': 'Cleo'} # {'name': 'Pancakes'} +The SQL query is executed as soon as ``db.query()`` is called. The resulting rows are fetched lazily as you iterate, so large result sets are not loaded into memory all at once. Because execution is immediate, an error in your SQL will raise an exception straight away, and a statement such as ``INSERT ... RETURNING`` will take effect - and be committed, unless a transaction is open - even if you do not iterate over its results. + +``db.query()`` can only be used with SQL that returns rows. Passing a statement that returns no rows - an ``INSERT`` or ``UPDATE`` without a ``RETURNING`` clause, for example - will raise a ``ValueError``. The rejected statement is rolled back, so it has no effect on the database. Use :ref:`db.execute() ` for those statements instead. + +There is one exception to the rolled-back guarantee: a ``PRAGMA`` statement that returns no rows, such as ``PRAGMA user_version = 5``, still raises a ``ValueError`` but will already have taken effect. Some PRAGMA statements refuse to run inside a transaction, so PRAGMAs are executed outside the savepoint that is used to roll back other rejected statements. Use ``db.execute()`` for PRAGMA statements that do not return rows. + +If a query returns more than one column with the same name - a join between two tables that share column names, for example - later occurrences are renamed with a numeric suffix, so every value is included in the dictionary: + +.. code-block:: python + + row = next(db.query("select 1 as id, 2 as id, 3 as id")) + print(row) + # Outputs: + # {'id': 1, 'id_2': 2, 'id_3': 3} + +A suffix that would collide with another column in the query is skipped - ``select 1 as id, 2 as id, 3 as id_2`` returns ``{'id': 1, 'id_3': 2, 'id_2': 3}``. The same renaming is applied by ``table.rows_where()`` and ``table.search()``. + +.. note:: + In the CLI: :ref:`sqlite-utils query ` + .. _python_api_execute: db.execute(sql, params) @@ -204,7 +272,7 @@ The ``db.execute()`` and ``db.executescript()`` methods provide wrappers around .. code-block:: python db = Database(memory=True) - db["dogs"].insert({"name": "Cleo"}) + db.table("dogs").insert({"name": "Cleo"}) cursor = db.execute("update dogs set name = 'Cleopaws'") print(cursor.rowcount) # Outputs the number of rows affected by the update @@ -212,6 +280,9 @@ The ``db.execute()`` and ``db.executescript()`` methods provide wrappers around Other cursor methods such as ``.fetchone()`` and ``.fetchall()`` are also available, see the `standard library documentation `__. +.. note:: + Write statements executed this way are committed automatically, unless a transaction is already open in which case they become part of it - see :ref:`python_api_transactions_execute`. + .. _python_api_parameters: Passing parameters @@ -240,26 +311,181 @@ Named parameters using ``:name`` can be filled using a dictionary: In this example ``next()`` is used to retrieve the first result in the iterator returned by the ``db.query()`` method. +.. _python_api_transactions: + +Transactions and saving your changes +==================================== + +Every method in this library that writes to the database - ``insert()``, ``upsert()``, ``update()``, ``delete()``, ``delete_where()``, ``transform()``, ``create_table()``, ``create_index()``, ``enable_fts()`` and the rest - runs inside its own transaction and commits it before returning. Your changes are saved to disk as soon as the method call finishes: + +.. code-block:: python + + db = Database("data.db") + db.table("news").insert({"headline": "Dog wins award"}) + # The new row is already saved - no commit() required + +The same applies to raw SQL executed with :ref:`db.execute() ` - a write statement is committed as soon as it has run. + +Another way to think about this is that each sqlite-utils method call is its own unit of work. If several method calls must either all succeed or all fail, use ``db.atomic()`` to turn them into a single unit of work. + +You never need to call ``commit()``, and you do not need to close the database to persist your changes. There are exactly two situations where you need to think about transactions: + +1. You want to group several write operations together, so they either all succeed or all fail - use :ref:`db.atomic() `. +2. You are :ref:`managing a transaction yourself ` with ``db.begin()``, in which case nothing is committed until you commit - the library will never commit a transaction you opened. + +``with Database(...) as db:`` is not a transaction block. It manages the lifetime of the database connection and closes it on exit. Use ``with db.atomic():`` for a transaction. + +.. _python_api_atomic: + +Grouping changes with db.atomic() +--------------------------------- + +Use ``db.atomic()`` to group multiple operations in a single transaction: + +.. code-block:: python + + with db.atomic(): + db.table("dogs").insert({"id": 1, "name": "Cleo"}, pk="id") + db.table("dogs").insert({"id": 2, "name": "Pancakes"}) + +The transaction commits when the block exits. If an exception is raised, changes made inside the block will be rolled back. + +This matters when several operations represent a single logical change. Without ``db.atomic()``, an earlier method call remains committed if a later one fails: + +.. code-block:: python + + # These are two separate transactions + db.table("accounts").update(1, {"balance": 90}) + db.table("accounts").update(2, {"balance": 110}) + + # These updates either both succeed or both fail + with db.atomic(): + db.table("accounts").update(1, {"balance": 90}) + db.table("accounts").update(2, {"balance": 110}) + +Transactions can also improve performance. Calling ``insert()`` repeatedly outside ``db.atomic()`` creates and commits a separate transaction for every call. For bulk inserts, prefer :ref:`insert_all() `. If you need to call several different methods in a loop, wrap the loop in ``db.atomic()``: + +.. code-block:: python + + with db.atomic(): + for row in rows: + db.table("events").insert(row) + +``db.atomic()`` can be nested. Nested blocks use SQLite savepoints, so an exception in an inner block can roll back to that savepoint without rolling back the entire outer transaction: + +.. code-block:: python + + with db.atomic(): + db.table("dogs").insert({"id": 1, "name": "Cleo"}, pk="id") + try: + with db.atomic(): + db.table("dogs").insert({"id": 2, "name": "Pancakes"}) + raise ValueError("skip this one") + except ValueError: + pass + db.table("dogs").insert({"id": 3, "name": "Marnie"}) + +The transaction is opened with a deferred ``BEGIN`` - SQLite takes the necessary locks when the first statement inside the block runs. + +.. _python_api_transactions_execute: + +Raw SQL writes with db.execute() +-------------------------------- + +Write statements executed with :ref:`db.execute() ` follow the same rule as everything else: they are committed automatically as soon as they have run. + +.. code-block:: python + + db.execute("insert into news (headline) values (?)", ["Dog wins award"]) + # Already committed + +``db.execute()`` participates in sqlite-utils transaction handling. Calling ``db.conn.execute()`` directly bypasses that policy and leaves transaction handling to Python's underlying ``sqlite3.Connection``. Prefer ``db.execute()`` unless you deliberately need the lower-level API. + +If a transaction is open - because the call happens inside a ``db.atomic()`` block, or after ``db.begin()`` - the statement becomes part of that transaction instead, and commits when the transaction commits: + +.. code-block:: python + + with db.atomic(): + db.execute("insert into news (headline) values (?)", ["Dog wins award"]) + db.execute("insert into news (headline) values (?)", ["Cat unimpressed"]) + # Both rows committed together + +One corner case: a row-returning write such as ``INSERT ... RETURNING`` executed through ``db.execute()`` cannot be auto-committed, because its rows have not been read yet - call ``db.commit()`` after fetching them, or use :ref:`db.query() ` for those statements, which executes the write and commits it immediately. + +.. _python_api_transactions_manual: + +Managing transactions yourself +------------------------------ + +You can take full manual control using the ``db.begin()``, ``db.commit()`` and ``db.rollback()`` methods: + +.. code-block:: python + + db.begin() + db.table("news").insert({"headline": "Dog wins award"}) + if all_looks_good: + db.commit() + else: + db.rollback() + +``db.begin()`` raises ``sqlite3.OperationalError`` if a transaction is already open. ``db.commit()`` and ``db.rollback()`` do nothing if there is no open transaction. + +The library will never commit a transaction you opened. If you call write methods such as ``insert()`` - or use ``db.atomic()`` - while your transaction is open, they participate in it using SQLite savepoints instead of committing: exiting an ``atomic()`` block releases its savepoint, but nothing is saved to disk until you commit the outer transaction yourself. If you roll back, their changes are rolled back too. + +Prefer ``db.atomic()`` or ``db.begin()``, ``db.commit()`` and ``db.rollback()`` over mixing sqlite-utils transaction methods with calls to ``db.conn.commit()``, ``db.conn.rollback()`` or raw transaction-control SQL. Mixing the two layers makes it much harder to tell which layer owns the current transaction. + +Some related safeguards to be aware of: + +- ``db.enable_wal()`` and ``db.disable_wal()`` raise a ``sqlite_utils.db.TransactionError`` if called while a transaction is open, because changing the journal mode would commit it as a side effect. +- ``table.transform()`` raises a ``sqlite_utils.db.TransactionError`` if called while a transaction is open with ``PRAGMA foreign_keys`` enabled and the table is referenced by foreign keys with destructive ``ON DELETE`` actions, because the pragma cannot be turned off mid-transaction to protect those referencing rows - see :ref:`python_api_transform_foreign_keys_transactions`. +- Closing the database - explicitly with ``db.close()``, or by exiting a ``with Database(...) as db:`` block - rolls back any transaction that is still open, see :ref:`python_api_close`. + +.. _python_api_transactions_modes: + +Supported connection modes +-------------------------- + +``db.atomic()`` and the automatic per-method transactions currently require a connection using Python's legacy transaction control mode (``sqlite3.LEGACY_TRANSACTION_CONTROL`` on Python 3.12 and later). Passing a connection created with the Python 3.12+ ``sqlite3.connect(..., autocommit=True)`` or ``autocommit=False`` options to ``Database()`` raises a ``sqlite_utils.db.TransactionError``. + +Connections using ``autocommit=False`` are not supported because Python keeps a transaction open continuously. sqlite-utils uses ``Connection.in_transaction`` to distinguish its own transactions from transactions opened by its caller, and that distinction is not available in this mode. + +Connections using ``autocommit=True`` are also currently rejected because sqlite-utils has not formally exposed that as a supported configuration. + .. _python_api_table: Accessing tables ================ -Tables are accessed using the indexing operator, like so: - -.. code-block:: python - - table = db["my_table"] - -If the table does not yet exist, it will be created the first time you attempt to insert or upsert data into it. - -You can also access tables using the ``.table()`` method like so: +Tables are accessed using the ``db.table()`` method, like so: .. code-block:: python table = db.table("my_table") -Using this factory function allows you to set :ref:`python_api_table_configuration`. +Using this factory function allows you to set :ref:`python_api_table_configuration`. Additional keyword arguments to ``db.table()`` will be used if a further method call causes the table to be created. + +The ``db.table()`` method will always return a :ref:`reference_db_table` instance, or raise a ``sqlite_utils.db.NoTable`` exception if the table name is actually a SQL view. + +You can also access tables or views using dictionary-style syntax, like this: + +.. code-block:: python + + table_or_view = db["my_table_or_view_name"] + +If a table accessed using either of these methods does not yet exist, it will be created the first time you attempt to insert or upsert data into it. + +.. _python_api_view: + +Accessing views +=============== + +SQL views can be accessed using the ``db.view()`` method, like so: + +.. code-block:: python + + view = db.view("my_view") + +This will return a :ref:`reference_db_view` instance, or raise a ``sqlite_utils.db.NoView`` exception if the view does not exist. .. _python_api_tables: @@ -278,6 +504,9 @@ You can also iterate through the table objects themselves using the ``.tables`` >>> db.tables [] +.. note:: + In the CLI: :ref:`sqlite-utils tables ` + .. _python_api_views: Listing views @@ -303,6 +532,9 @@ View objects are similar to Table objects, except that any attempts to insert or * ``rows_where(where, where_args, order_by, select)`` * ``drop()`` +.. note:: + In the CLI: :ref:`sqlite-utils views ` + .. _python_api_rows: Listing rows @@ -311,7 +543,7 @@ Listing rows To iterate through dictionaries for each of the rows in a table, use ``.rows``:: >>> db = sqlite_utils.Database("dogs.db") - >>> for row in db["dogs"].rows: + >>> for row in db.table("dogs").rows: ... print(row) {'id': 1, 'age': 4, 'name': 'Cleo'} {'id': 2, 'age': 2, 'name': 'Pancakes'} @@ -319,26 +551,26 @@ To iterate through dictionaries for each of the rows in a table, use ``.rows``:: You can filter rows by a WHERE clause using ``.rows_where(where, where_args)``:: >>> db = sqlite_utils.Database("dogs.db") - >>> for row in db["dogs"].rows_where("age > ?", [3]): + >>> for row in db.table("dogs").rows_where("age > ?", [3]): ... print(row) {'id': 1, 'age': 4, 'name': 'Cleo'} The first argument is a fragment of SQL. The second, optional argument is values to be passed to that fragment - you can use ``?`` placeholders and pass an array, or you can use ``:named`` parameters and pass a dictionary, like this:: - >>> for row in db["dogs"].rows_where("age > :age", {"age": 3}): + >>> for row in db.table("dogs").rows_where("age > :age", {"age": 3}): ... print(row) {'id': 1, 'age': 4, 'name': 'Cleo'} To return custom columns (instead of the default that uses ``select *``) pass ``select="column1, column2"``:: >>> db = sqlite_utils.Database("dogs.db") - >>> for row in db["dogs"].rows_where(select='name, age'): + >>> for row in db.table("dogs").rows_where(select='name, age'): ... print(row) {'name': 'Cleo', 'age': 4} To specify an order, use the ``order_by=`` argument:: - >>> for row in db["dogs"].rows_where("age > 1", order_by="age"): + >>> for row in db.table("dogs").rows_where("age > 1", order_by="age"): ... print(row) {'id': 2, 'age': 2, 'name': 'Pancakes'} {'id': 1, 'age': 4, 'name': 'Cleo'} @@ -347,17 +579,20 @@ You can use ``order_by="age desc"`` for descending order. You can order all records in the table by excluding the ``where`` argument:: - >>> for row in db["dogs"].rows_where(order_by="age desc"): + >>> for row in db.table("dogs").rows_where(order_by="age desc"): ... print(row) {'id': 1, 'age': 4, 'name': 'Cleo'} {'id': 2, 'age': 2, 'name': 'Pancakes'} This method also accepts ``offset=`` and ``limit=`` arguments, for specifying an OFFSET and a LIMIT for the SQL query:: - >>> for row in db["dogs"].rows_where(order_by="age desc", limit=1): + >>> for row in db.table("dogs").rows_where(order_by="age desc", limit=1): ... print(row) {'id': 1, 'age': 4, 'name': 'Cleo'} +.. note:: + In the CLI: :ref:`sqlite-utils rows ` + .. _python_api_rows_count_where: Counting rows @@ -365,7 +600,7 @@ Counting rows To count the number of rows that would be returned by a where filter, use ``.count_where(where, where_args)``: - >>> db["dogs"].count_where("age > ?", [1]) + >>> db.table("dogs").count_where("age > ?", [1]) 2 .. _python_api_pks_and_rows_where: @@ -384,21 +619,21 @@ If the table is a ``rowid`` table (with no explicit primary key column) then tha :: >>> db = sqlite_utils.Database(memory=True) - >>> db["dogs"].insert({"name": "Cleo"}) - >>> for pk, row in db["dogs"].pks_and_rows_where(): + >>> db.table("dogs").insert({"name": "Cleo"}) + >>> for pk, row in db.table("dogs").pks_and_rows_where(): ... print(pk, row) 1 {'rowid': 1, 'name': 'Cleo'} - >>> db["dogs_with_pk"].insert({"id": 5, "name": "Cleo"}, pk="id") - >>> for pk, row in db["dogs_with_pk"].pks_and_rows_where(): + >>> db.table("dogs_with_pk").insert({"id": 5, "name": "Cleo"}, pk="id") + >>> for pk, row in db.table("dogs_with_pk").pks_and_rows_where(): ... print(pk, row) 5 {'id': 5, 'name': 'Cleo'} - >>> db["dogs_with_compound_pk"].insert( + >>> db.table("dogs_with_compound_pk").insert( ... {"species": "dog", "id": 3, "name": "Cleo"}, ... pk=("species", "id") ... ) - >>> for pk, row in db["dogs_with_compound_pk"].pks_and_rows_where(): + >>> for pk, row in db.table("dogs_with_compound_pk").pks_and_rows_where(): ... print(pk, row) ('dog', 3) {'species': 'dog', 'id': 3, 'name': 'Cleo'} @@ -410,12 +645,12 @@ Retrieving a specific record You can retrieve a record by its primary key using ``table.get()``:: >>> db = sqlite_utils.Database("dogs.db") - >>> print(db["dogs"].get(1)) + >>> print(db.table("dogs").get(1)) {'id': 1, 'age': 4, 'name': 'Cleo'} If the table has a compound primary key you can pass in the primary key values as a tuple:: - >>> db["compound_dogs"].get(("mixed", 3)) + >>> db.table("compound_dogs").get(("mixed", 3)) If the record does not exist a ``NotFoundError`` will be raised: @@ -424,7 +659,7 @@ If the record does not exist a ``NotFoundError`` will be raised: from sqlite_utils.db import NotFoundError try: - row = db["dogs"].get(5) + row = db.table("dogs").get(5) except NotFoundError: print("Dog not found") @@ -438,10 +673,13 @@ The ``db.schema`` property returns the full SQL schema for the database as a str >>> db = sqlite_utils.Database("dogs.db") >>> print(db.schema) CREATE TABLE "dogs" ( - [id] INTEGER PRIMARY KEY, - [name] TEXT + "id" INTEGER PRIMARY KEY, + "name" TEXT ); +.. note:: + In the CLI: :ref:`sqlite-utils schema ` + .. _python_api_creating_tables: Creating tables @@ -455,7 +693,7 @@ The easiest way to create a new table is to insert a record into it: import sqlite3 db = Database("dogs.db") - dogs = db["dogs"] + dogs = db.table("dogs") dogs.insert({ "name": "Cleo", "twitter": "cleopaws", @@ -499,7 +737,7 @@ If you want to explicitly set the order of the columns you can do so using the ` .. code-block:: python - db["dogs"].insert({ + db.table("dogs").insert({ "id": 1, "name": "Cleo", "twitter": "cleopaws", @@ -513,7 +751,7 @@ Column types are detected based on the example data provided. Sometimes you may .. code-block:: python - db["dogs"].insert({ + db.table("dogs").insert({ "id": 1, "name": "Cleo", "age": "5", @@ -523,11 +761,11 @@ This will create a table with the following schema: .. code-block:: sql - CREATE TABLE [dogs] ( - [id] INTEGER PRIMARY KEY, - [name] TEXT, - [age] INTEGER, - [weight] FLOAT + CREATE TABLE "dogs" ( + "id" INTEGER PRIMARY KEY, + "name" TEXT, + "age" INTEGER, + "weight" REAL ) .. _python_api_explicit_create: @@ -539,7 +777,7 @@ You can directly create a new table without inserting any data into it using the .. code-block:: python - db["cats"].create({ + db.table("cats").create({ "id": int, "name": str, "weight": float, @@ -555,7 +793,7 @@ You can pass ``ignore=True`` to ignore that error. You can also use ``if_not_exi .. code-block:: python - db["cats"].create({ + db.table("cats").create({ "id": int, "name": str, }, pk="id", if_not_exists=True) @@ -566,7 +804,7 @@ You can also pass ``transform=True`` to have any existing tables :ref:`transform .. code-block:: python - db["cats"].create({ + db.table("cats").create({ "id": int, "name": str, "weight": float, @@ -581,6 +819,18 @@ The ``transform=True`` option will update the table schema if any of the followi Changes to ``foreign_keys=`` are not currently detected and applied by ``transform=True``. +You can pass ``strict=True`` to create a table in ``STRICT`` mode: + +.. code-block:: python + + db.table("cats").create({ + "id": int, + "name": str, + }, strict=True) + +.. note:: + In the CLI: :ref:`sqlite-utils create-table ` + .. _python_api_compound_primary_keys: Compound primary keys @@ -590,7 +840,7 @@ If you want to create a table with a compound primary key that spans multiple co .. code-block:: python - db["cats"].create({ + db.table("cats").create({ "id": int, "breed": str, "name": str, @@ -630,17 +880,72 @@ You can leave off the third item in the tuple to have the referenced column auto .. code-block:: python - db["authors"].insert_all([ + db.table("authors").insert_all([ {"id": 1, "name": "Sally"}, {"id": 2, "name": "Asheesh"} ], pk="id") - db["books"].insert_all([ + db.table("books").insert_all([ {"title": "Hedgehogs of the world", "author_id": 1}, {"title": "How to train your wolf", "author_id": 2}, ], foreign_keys=[ ("author_id", "authors") ]) +.. _python_api_compound_foreign_keys: + +Compound foreign keys +~~~~~~~~~~~~~~~~~~~~~ + +To create a compound (multi-column) foreign key, use tuples of column names in place of the single column names: + +.. code-block:: python + + db.table("courses").create({ + "course_code": str, + "campus_name": str, + "dept_code": str, + }, pk="course_code", foreign_keys=[ + (("campus_name", "dept_code"), "departments", ("campus_name", "dept_code")) + ]) + +This creates a table-level constraint: + +.. code-block:: sql + + CREATE TABLE "courses" ( + "course_code" TEXT PRIMARY KEY, + "campus_name" TEXT, + "dept_code" TEXT, + FOREIGN KEY ("campus_name", "dept_code") REFERENCES "departments"("campus_name", "dept_code") + ) + +As with single columns, you can leave off the tuple of other columns to reference the compound primary key of the other table: + +.. code-block:: python + + foreign_keys=[ + (("campus_name", "dept_code"), "departments") + ] + +To specify ``ON DELETE`` or ``ON UPDATE`` actions, pass ``ForeignKey`` objects instead: + +.. code-block:: python + + from sqlite_utils.db import ForeignKey + + db.table("books").create({ + "id": int, + "author_id": int, + }, pk="id", foreign_keys=[ + ForeignKey( + table="books", column="author_id", + other_table="authors", other_column="id", + on_delete="CASCADE", + ) + ]) + +Foreign key actions are preserved by :ref:`table.transform() ` - prior to sqlite-utils 4.0 they were silently dropped when a table was transformed. + .. _python_api_table_configuration: Table configuration options @@ -648,7 +953,7 @@ Table configuration options The ``.insert()``, ``.upsert()``, ``.insert_all()`` and ``.upsert_all()`` methods each take a number of keyword arguments, some of which influence what happens should they cause a table to be created and some of which affect the behavior of those methods. -You can set default values for these methods by accessing the table through the ``db.table(...)`` method (instead of using ``db["table_name"]``), like so: +You can set default values for these methods by accessing the table through the ``db.table(...)`` method (instead of using ``db.table("table_name")``), like so: .. code-block:: python @@ -661,7 +966,7 @@ You can set default values for these methods by accessing the table through the # Now you can call .insert() like so: table.insert({"id": 1, "name": "Tracy", "score": 5}) -The configuration options that can be specified in this way are ``pk``, ``foreign_keys``, ``column_order``, ``not_null``, ``defaults``, ``batch_size``, ``hash_id``, ``hash_id_columns``, ``alter``, ``ignore``, ``replace``, ``extracts``, ``conversions``, ``columns``. These are all documented below. +The configuration options that can be specified in this way are ``pk``, ``foreign_keys``, ``column_order``, ``not_null``, ``defaults``, ``batch_size``, ``hash_id``, ``hash_id_columns``, ``alter``, ``ignore``, ``replace``, ``extracts``, ``conversions``, ``columns``, ``strict``. These are all documented below. .. _python_api_defaults_not_null: @@ -685,27 +990,30 @@ Here's an example that uses these features: .. code-block:: python - db["authors"].insert_all( + db.table("authors").insert_all( [{"id": 1, "name": "Sally", "score": 2}], pk="id", not_null={"name", "score"}, defaults={"score": 1}, ) - db["authors"].insert({"name": "Dharma"}) + db.table("authors").insert({"name": "Dharma"}) - list(db["authors"].rows) + list(db.table("authors").rows) # Outputs: # [{'id': 1, 'name': 'Sally', 'score': 2}, # {'id': 3, 'name': 'Dharma', 'score': 1}] - print(db["authors"].schema) + print(db.table("authors").schema) # Outputs: - # CREATE TABLE [authors] ( - # [id] INTEGER PRIMARY KEY, - # [name] TEXT NOT NULL, - # [score] INTEGER NOT NULL DEFAULT 1 + # CREATE TABLE "authors" ( + # "id" INTEGER PRIMARY KEY, + # "name" TEXT NOT NULL, + # "score" INTEGER NOT NULL DEFAULT 1 # ) +.. note:: + In the CLI: :ref:`sqlite-utils insert --not-null and --default ` + .. _python_api_rename_table: Renaming a table @@ -723,6 +1031,9 @@ This executes the following SQL: ALTER TABLE [my_table] RENAME TO [new_name_for_my_table] +.. note:: + In the CLI: :ref:`sqlite-utils rename-table ` + .. _python_api_duplicate: Duplicating tables @@ -732,12 +1043,15 @@ The ``table.duplicate()`` method creates a copy of the table, copying both the t .. code-block:: python - db["authors"].duplicate("authors_copy") + db.table("authors").duplicate("authors_copy") The new ``authors_copy`` table will now contain a duplicate copy of the data from ``authors``. This method raises ``sqlite_utils.db.NoTable`` if the table does not exist. +.. note:: + In the CLI: :ref:`sqlite-utils duplicate ` + .. _python_api_bulk_inserts: Bulk inserts @@ -749,7 +1063,7 @@ Use it like this: .. code-block:: python - db["dogs"].insert_all([{ + db.table("dogs").insert_all([{ "id": 1, "name": "Cleo", "twitter": "cleopaws", @@ -769,7 +1083,7 @@ The function can accept an iterator or generator of rows and will commit them ac .. code-block:: python - db["big_table"].insert_all(({ + db.table("big_table").insert_all(({ "id": 1, "name": "Name {}".format(i), } for i in range(10000)), batch_size=1000) @@ -780,6 +1094,38 @@ You can delete all the existing rows in the table before inserting the new recor Pass ``analyze=True`` to run ``ANALYZE`` against the table after inserting the new records. +.. note:: + In the CLI: :ref:`sqlite-utils insert ` + +.. _python_api_insert_lists: + +Inserting data from a list or tuple iterator +-------------------------------------------- + +As an alternative to passing an iterator of dictionaries, you can pass an iterator of lists or tuples. The first item yielded by the iterator must be a list or tuple of string column names, and subsequent items should be lists or tuples of values: + +.. code-block:: python + + db["creatures"].insert_all([ + ["name", "species"], + ["Cleo", "dog"], + ["Lila", "chicken"], + ["Bants", "chicken"], + ]) + +This also works with generators: + +.. code-block:: python + + def creatures(): + yield "id", "name", "city" + yield 1, "Cleo", "San Francisco" + yield 2, "Lila", "Los Angeles" + + db["creatures"].insert_all(creatures()) + +Tuples and lists are both supported. + .. _python_api_insert_replace: Insert-replacing data @@ -794,7 +1140,7 @@ This example that catches that exception: from sqlite_utils.utils import sqlite3 try: - db["dogs"].insert({"id": 1, "name": "Cleo"}, pk="id") + db.table("dogs").insert({"id": 1, "name": "Cleo"}, pk="id") except sqlite3.IntegrityError: print("Record already exists with that primary key") @@ -805,13 +1151,13 @@ Use the ``ignore=True`` parameter to ignore this error: .. code-block:: python # This fails silently if a record with id=1 already exists - db["dogs"].insert({"id": 1, "name": "Cleo"}, pk="id", ignore=True) + db.table("dogs").insert({"id": 1, "name": "Cleo"}, pk="id", ignore=True) To replace any existing records that have a matching primary key, use the ``replace=True`` parameter to ``.insert()`` or ``.insert_all()``: .. code-block:: python - db["dogs"].insert_all([{ + db.table("dogs").insert_all([{ "id": 1, "name": "Cleo", "twitter": "cleopaws", @@ -828,6 +1174,9 @@ To replace any existing records that have a matching primary key, use the ``repl .. note:: Prior to sqlite-utils 2.0 the ``.upsert()`` and ``.upsert_all()`` methods worked the same way as ``.insert(replace=True)`` does today. See :ref:`python_api_upsert` for the new behaviour of those methods introduced in 2.0. +.. note:: + In the CLI: :ref:`sqlite-utils insert --replace ` + .. _python_api_update: Updating a specific record @@ -836,21 +1185,21 @@ Updating a specific record You can update a record by its primary key using ``table.update()``:: >>> db = sqlite_utils.Database("dogs.db") - >>> print(db["dogs"].get(1)) + >>> print(db.table("dogs").get(1)) {'id': 1, 'age': 4, 'name': 'Cleo'} - >>> db["dogs"].update(1, {"age": 5}) - >>> print(db["dogs"].get(1)) + >>> db.table("dogs").update(1, {"age": 5}) + >>> print(db.table("dogs").get(1)) {'id': 1, 'age': 5, 'name': 'Cleo'} The first argument to ``update()`` is the primary key. This can be a single value, or a tuple if that table has a compound primary key:: - >>> db["compound_dogs"].update((5, 3), {"name": "Updated"}) + >>> db.table("compound_dogs").update((5, 3), {"name": "Updated"}) The second argument is a dictionary of columns that should be updated, along with their new values. You can cause any missing columns to be added automatically using ``alter=True``:: - >>> db["dogs"].update(1, {"breed": "Mutt"}, alter=True) + >>> db.table("dogs").update(1, {"breed": "Mutt"}, alter=True) .. _python_api_delete: @@ -860,11 +1209,11 @@ Deleting a specific record You can delete a record using ``table.delete()``:: >>> db = sqlite_utils.Database("dogs.db") - >>> db["dogs"].delete(1) + >>> db.table("dogs").delete(1) The ``delete()`` method takes the primary key of the record. This can be a tuple of values if the row has a compound primary key:: - >>> db["compound_dogs"].delete((5, 3)) + >>> db.table("compound_dogs").delete((5, 3)) .. _python_api_delete_where: @@ -875,7 +1224,7 @@ You can delete all records in a table that match a specific WHERE statement usin >>> db = sqlite_utils.Database("dogs.db") >>> # Delete every dog with age less than 3 - >>> db["dogs"].delete_where("age < ?", [3]) + >>> db.table("dogs").delete_where("age < ?", [3]) Calling ``table.delete_where()`` with no other arguments will delete every row in the table. @@ -892,7 +1241,7 @@ For example, given the dogs database you could upsert the record for Cleo like s .. code-block:: python - db["dogs"].upsert({ + db.table("dogs").upsert({ "id": 1, "name": "Cleo", "twitter": "cleopaws", @@ -908,9 +1257,21 @@ Note that the ``pk`` and ``column_order`` parameters here are optional if you ar An ``upsert_all()`` method is also available, which behaves like ``insert_all()`` but performs upserts instead. +Every record passed to ``upsert()`` or ``upsert_all()`` must include a value for each primary key column - a record without one could never match an existing row, so a ``sqlite_utils.db.PrimaryKeyRequired`` exception is raised instead of quietly inserting a new row. + .. note:: ``.upsert()`` and ``.upsert_all()`` in sqlite-utils 1.x worked like ``.insert(..., replace=True)`` and ``.insert_all(..., replace=True)`` do in 2.x. See `issue #66 `__ for details of this change. +.. note:: + In the CLI: :ref:`sqlite-utils upsert ` + +.. _python_api_old_upsert: + +Alternative upserts using INSERT OR IGNORE +------------------------------------------ + +Upserts use ``INSERT INTO ... ON CONFLICT SET``. Prior to ``sqlite-utils 4.0`` these used a sequence of ``INSERT OR IGNORE`` followed by an ``UPDATE``. This older method is still used for SQLite 3.23.1 and earlier. You can force the older implementation by passing ``use_old_upsert=True`` to the ``Database()`` constructor. + .. _python_api_convert: Converting data in columns @@ -924,26 +1285,24 @@ To transform a specific column to uppercase, you would use the following: .. code-block:: python - db["dogs"].convert("name", lambda value: value.upper()) + db.table("dogs").convert("name", lambda value: value.upper()) You can pass a list of columns, in which case the transformation will be applied to each one: .. code-block:: python - db["dogs"].convert(["name", "twitter"], lambda value: value.upper()) + db.table("dogs").convert(["name", "twitter"], lambda value: value.upper()) To save the output to of the transformation to a different column, use the ``output=`` parameter: .. code-block:: python - db["dogs"].convert("name", lambda value: value.upper(), output="name_upper") + db.table("dogs").convert("name", lambda value: value.upper(), output="name_upper") This will add the new column, if it does not already exist. You can pass ``output_type=int`` or some other type to control the type of the new column - otherwise it will default to text. If you want to drop the original column after saving the results in a separate output column, pass ``drop=True``. -By default any rows with a falsey value for the column - such as ``0`` or ``None`` - will be skipped. Pass ``skip_false=False`` to disable this behaviour. - You can create multiple new columns from a single input column by passing ``multi=True`` and a conversion function that returns a Python dictionary. This example creates new ``upper`` and ``lower`` columns populated from the single ``title`` column: .. code-block:: python @@ -972,7 +1331,7 @@ A useful pattern when populating large tables in to break common values out into Creating lookup tables explicitly --------------------------------- -Calling ``db["Species"].lookup({"name": "Palm"})`` creates a table called ``Species`` (if one does not already exist) with two columns: ``id`` and ``name``. It sets up a unique constraint on the ``name`` column to guarantee it will not contain duplicate rows. It then inserts a new row with the ``name`` set to ``Palm`` and returns the new integer primary key value. +Calling ``db.table("Species").lookup({"name": "Palm"})`` creates a table called ``Species`` (if one does not already exist) with two columns: ``id`` and ``name``. It sets up a unique constraint on the ``name`` column to guarantee it will not contain duplicate rows. It then inserts a new row with the ``name`` set to ``Palm`` and returns the new integer primary key value. If the ``Species`` table already exists, it will insert the new row and return the primary key. If a row with that ``name`` already exists, it will return the corresponding primary key value directly. @@ -982,10 +1341,10 @@ If you pass in a dictionary with multiple values, both values will be used to in .. code-block:: python - db["Trees"].insert({ + db.table("Trees").insert({ "latitude": 49.1265976, "longitude": 2.5496218, - "species": db["Species"].lookup({ + "species": db.table("Species").lookup({ "common_name": "Common Juniper", "latin_name": "Juniperus communis" }) @@ -997,10 +1356,12 @@ To create a species record with a note on when it was first seen, you can use th .. code-block:: python - db["Species"].lookup({"name": "Palm"}, {"first_seen": "2021-03-04"}) + db.table("Species").lookup({"name": "Palm"}, {"first_seen": "2021-03-04"}) The first time this is called the record will be created for ``name="Palm"``. Any subsequent calls with that name will ignore the second argument, even if it includes different values. +``None`` values are matched correctly: calling ``.lookup()`` a second time with the same values will return the primary key of the existing row even if some of those values are ``None``. + ``.lookup()`` also accepts keyword arguments, which are passed through to the :ref:`insert() method ` and can be used to influence the shape of the created table. Supported parameters are: - ``pk`` - which defaults to ``id`` @@ -1011,6 +1372,7 @@ The first time this is called the record will be created for ``name="Palm"``. An - ``extracts`` - ``conversions`` - ``columns`` +- ``strict`` .. _python_api_extracts: @@ -1039,12 +1401,14 @@ To extract the ``species`` column out to a separate ``Species`` table, you can d trees = db.table("Trees", extracts=["species"]) # Using .insert() directly - db["Trees"].insert({ + db.table("Trees").insert({ "latitude": 49.1265976, "longitude": 2.5496218, "species": "Common Juniper" }, extracts={"species": "Species"}) +``None`` values are not extracted: no record is created for them in the lookup table and the column value stays ``null``. + .. _python_api_m2m: Working with many-to-many relationships @@ -1056,7 +1420,7 @@ Here's how to create two new records and connect them via a many-to-many table i .. code-block:: python - db["dogs"].insert({"id": 1, "name": "Cleo"}, pk="id").m2m( + db.table("dogs").insert({"id": 1, "name": "Cleo"}, pk="id").m2m( "humans", {"id": 1, "name": "Natalie"}, pk="id" ) @@ -1066,7 +1430,7 @@ The ``.m2m()`` method executes against the last record that was affected by ``.i .. code-block:: python - db["dogs"].update(1).m2m( + db.table("dogs").update(1).m2m( "humans", {"id": 2, "name": "Simon"}, pk="id" ) @@ -1123,17 +1487,17 @@ You can inspect the database to see the results like this:: >>> db.table_names() ['dogs', 'characteristics', 'characteristics_dogs'] - >>> list(db["dogs"].rows) + >>> list(db.table("dogs").rows) [{'id': 1, 'name': 'Cleo'}] - >>> list(db["characteristics"].rows) + >>> list(db.table("characteristics").rows) [{'id': 1, 'name': 'Playful'}, {'id': 2, 'name': 'Opinionated'}] - >>> list(db["characteristics_dogs"].rows) + >>> list(db.table("characteristics_dogs").rows) [{'characteristics_id': 1, 'dogs_id': 1}, {'characteristics_id': 2, 'dogs_id': 1}] - >>> print(db["characteristics_dogs"].schema) - CREATE TABLE [characteristics_dogs] ( - [characteristics_id] INTEGER REFERENCES [characteristics]([id]), - [dogs_id] INTEGER REFERENCES [dogs]([id]), - PRIMARY KEY ([characteristics_id], [dogs_id]) + >>> print(db.table("characteristics_dogs").schema) + CREATE TABLE "characteristics_dogs" ( + "characteristics_id" INTEGER REFERENCES "characteristics"("id"), + "dogs_id" INTEGER REFERENCES "dogs"("id"), + PRIMARY KEY ("characteristics_id", "dogs_id") ) .. _python_api_analyze_column: @@ -1195,21 +1559,21 @@ You can add a new column to a table using the ``.add_column(col_name, col_type)` .. code-block:: python - db["dogs"].add_column("instagram", str) - db["dogs"].add_column("weight", float) - db["dogs"].add_column("dob", datetime.date) - db["dogs"].add_column("image", "BLOB") - db["dogs"].add_column("website") # str by default + db.table("dogs").add_column("instagram", str) + db.table("dogs").add_column("weight", float) + db.table("dogs").add_column("dob", datetime.date) + db.table("dogs").add_column("image", "BLOB") + db.table("dogs").add_column("website") # str by default You can specify the ``col_type`` argument either using a SQLite type as a string, or by directly passing a Python type e.g. ``str`` or ``float``. The ``col_type`` is optional - if you omit it the type of ``TEXT`` will be used. -SQLite types you can specify are ``"TEXT"``, ``"INTEGER"``, ``"FLOAT"`` or ``"BLOB"``. +SQLite types you can specify are ``"TEXT"``, ``"INTEGER"``, ``"FLOAT"``, ``"REAL"`` or ``"BLOB"``. If you pass a Python type, it will be mapped to SQLite types as shown here:: - float: "FLOAT" + float: "REAL" int: "INTEGER" bool: "INTEGER" str: "TEXT" @@ -1228,15 +1592,15 @@ If you pass a Python type, it will be mapped to SQLite types as shown here:: np.uint16: "INTEGER" np.uint32: "INTEGER" np.uint64: "INTEGER" - np.float16: "FLOAT" - np.float32: "FLOAT" - np.float64: "FLOAT" + np.float16: "REAL" + np.float32: "REAL" + np.float64: "REAL" You can also add a column that is a foreign key reference to another table using the ``fk`` parameter: .. code-block:: python - db["dogs"].add_column("species_id", fk="species") + db.table("dogs").add_column("species_id", fk="species") This will automatically detect the name of the primary key on the species table and use that (and its type) for the new column. @@ -1244,13 +1608,16 @@ You can explicitly specify the column you wish to reference using ``fk_col``: .. code-block:: python - db["dogs"].add_column("species_id", fk="species", fk_col="ref") + db.table("dogs").add_column("species_id", fk="species", fk_col="ref") You can set a ``NOT NULL DEFAULT 'x'`` constraint on the new column using ``not_null_default``: .. code-block:: python - db["dogs"].add_column("friends_count", int, not_null_default=0) + db.table("dogs").add_column("friends_count", int, not_null_default=0) + +.. note:: + In the CLI: :ref:`sqlite-utils add-column ` .. _python_api_add_column_alter: @@ -1261,13 +1628,13 @@ You can insert or update data that includes new columns and have the table autom .. code-block:: python - db["new_table"].insert({"name": "Gareth"}) + db.table("new_table").insert({"name": "Gareth"}) # This will throw an exception: - db["new_table"].insert({"name": "Gareth", "age": 32}) + db.table("new_table").insert({"name": "Gareth", "age": 32}) # This will succeed and add a new "age" integer column: - db["new_table"].insert({"name": "Gareth", "age": 32}, alter=True) + db.table("new_table").insert({"name": "Gareth", "age": 32}, alter=True) # You can see confirm the new column like so: - print(db["new_table"].columns_dict) + print(db.table("new_table").columns_dict) # Outputs this: # {'name': , 'age': } @@ -1275,6 +1642,9 @@ You can insert or update data that includes new columns and have the table autom new_table = db.table("new_table", alter=True) new_table.insert({"name": "Gareth", "age": 32, "shoe_size": 11}) +.. note:: + In the CLI: :ref:`sqlite-utils insert --alter ` + .. _python_api_add_foreign_key: Adding foreign key constraints @@ -1290,15 +1660,15 @@ Here's an example of this mechanism in action: .. code-block:: python - db["authors"].insert_all([ + db.table("authors").insert_all([ {"id": 1, "name": "Sally"}, {"id": 2, "name": "Asheesh"} ], pk="id") - db["books"].insert_all([ + db.table("books").insert_all([ {"title": "Hedgehogs of the world", "author_id": 1}, {"title": "How to train your wolf", "author_id": 2}, ]) - db["books"].add_foreign_key("author_id", "authors", "id") + db.table("books").add_foreign_key("author_id", "authors", "id") The ``table.add_foreign_key(column, other_table, other_column)`` method takes the name of the column, the table that is being referenced and the key column within that other table. If you omit the ``other_column`` argument the primary key from that table will be used automatically. If you omit the ``other_table`` argument the table will be guessed based on some simple rules: @@ -1311,7 +1681,30 @@ To ignore the case where the key already exists, use ``ignore=True``: .. code-block:: python - db["books"].add_foreign_key("author_id", "authors", "id", ignore=True) + db.table("books").add_foreign_key("author_id", "authors", "id", ignore=True) + +To add a compound foreign key, pass tuples of columns: + +.. code-block:: python + + db.table("courses").add_foreign_key( + ("campus_name", "dept_code"), "departments", ("campus_name", "dept_code") + ) + +As with single columns, omitting the other columns will use the compound primary key of the other table. ``other_table`` must always be specified for a compound foreign key. + +Use ``on_delete=`` and ``on_update=`` to specify ``ON DELETE`` and ``ON UPDATE`` actions for the foreign key: + +.. code-block:: python + + db.table("books").add_foreign_key( + "author_id", "authors", "id", on_delete="CASCADE" + ) + +This creates a foreign key with an ``ON DELETE CASCADE`` clause, so deleting an author will also delete their books (provided foreign key enforcement is enabled with ``PRAGMA foreign_keys = ON``). Valid actions are ``"SET NULL"``, ``"SET DEFAULT"``, ``"CASCADE"``, ``"RESTRICT"`` and the default ``"NO ACTION"``. + +.. note:: + In the CLI: :ref:`sqlite-utils add-foreign-key ` .. _python_api_add_foreign_keys: @@ -1331,6 +1724,11 @@ Here's an example adding two foreign keys at once: This method runs the same checks as ``.add_foreign_keys()`` and will raise ``sqlite_utils.db.AlterError`` if those checks fail. +Foreign keys that already exist are silently skipped, so repeated calls are idempotent - but only if they match exactly. Requesting a foreign key that exists with different ``ON DELETE``/``ON UPDATE`` actions raises ``AlterError``: use ``table.transform()`` to change the actions of an existing foreign key. + +.. note:: + In the CLI: :ref:`sqlite-utils add-foreign-keys ` + .. _python_api_index_foreign_keys: Adding indexes for all foreign keys @@ -1342,6 +1740,11 @@ If you want to ensure that every foreign key column in your database has a corre db.index_foreign_keys() +Compound foreign keys get a single composite index across their columns. + +.. note:: + In the CLI: :ref:`sqlite-utils index-foreign-keys ` + .. _python_api_drop: Dropping a table or view @@ -1351,13 +1754,20 @@ You can drop a table or view using the ``.drop()`` method: .. code-block:: python - db["my_table"].drop() + db.table("my_table").drop() + # Or for a view: + db.view("my_view").drop() + # Or for either: + db["table_or_view_name"].drop() Pass ``ignore=True`` if you want to ignore the error caused by the table or view not existing. .. code-block:: python - db["my_table"].drop(ignore=True) + db.table("my_table").drop(ignore=True) + +.. note:: + In the CLI: :ref:`sqlite-utils drop-table ` and :ref:`sqlite-utils drop-view ` .. _python_api_transform: @@ -1385,6 +1795,11 @@ To keep the original table around instead of dropping it, pass the ``keep_table= table.transform(types={"age": int}, keep_table="original_table") +This method raises a ``sqlite_utils.db.TransformError`` exception if the table cannot be transformed, usually because there are existing constraints or indexes that are incompatible with modifications to the columns. + +.. note:: + In the CLI: :ref:`sqlite-utils transform ` + .. _python_api_transform_alter_column_types: Altering column types @@ -1399,6 +1814,29 @@ To alter the type of a column, use the ``types=`` argument: See :ref:`python_api_add_column` for a list of available types. +.. _python_api_transform_strict: + +Changing strict mode +-------------------- + +The optional ``strict=`` parameter can change whether a table uses `SQLite STRICT mode `__. Pass ``strict=True`` to convert a regular table to a strict table: + +.. code-block:: python + + table.transform(strict=True) + +Pass ``strict=False`` to convert a strict table back to a regular non-strict table: + +.. code-block:: python + + table.transform(strict=False) + +The default is ``strict=None``, which preserves the table's existing strict mode. + +Passing ``strict=True`` raises ``sqlite_utils.db.TransformError`` if the available SQLite version does not support strict tables. + +Converting to a strict table validates all existing rows as they are copied into the replacement table. If a value is incompatible with its declared column type, SQLite raises ``sqlite3.IntegrityError`` and the transformation is rolled back, leaving the original table and its data unchanged. + .. _python_api_transform_rename_columns: Renaming columns @@ -1493,7 +1931,7 @@ You can add one or more foreign key constraints to a table using the ``add_forei .. code-block:: python - db["places"].transform( + db.table("places").transform( add_foreign_keys=( ("country", "country", "id"), ("continent", "continent", "id") @@ -1504,7 +1942,7 @@ This accepts the same arguments described in :ref:`specifying foreign keys ` + .. _python_api_hash: Setting an ID based on the hash of the row contents @@ -1717,7 +2200,7 @@ In these cases, a useful technique is to create an ID that is derived from the s ``sqlite-utils`` can do this for you using the ``hash_id=`` option. For example:: db = sqlite_utils.Database("dogs.db") - db["dogs"].upsert({"name": "Cleo", "twitter": "cleopaws"}, hash_id="id") + db.table("dogs").upsert({"name": "Cleo", "twitter": "cleopaws"}, hash_id="id") print(list(db["dogs])) Outputs:: @@ -1726,7 +2209,7 @@ Outputs:: If you are going to use that ID straight away, you can access it using ``last_pk``:: - dog_id = db["dogs"].upsert({ + dog_id = db.table("dogs").upsert({ "name": "Cleo", "twitter": "cleopaws" }, hash_id="id").last_pk @@ -1734,7 +2217,7 @@ If you are going to use that ID straight away, you can access it using ``last_pk The hash will be created using all of the column values. To create a hash using a subset of the columns, pass the ``hash_id_columns=`` parameter:: - db["dogs"].upsert( + db.table("dogs").upsert( {"name": "Cleo", "twitter": "cleopaws", "age": 7}, hash_id_columns=("name", "twitter") ) @@ -1766,6 +2249,9 @@ You can pass ``ignore=True`` to silently ignore an existing view and do nothing, select * from dogs where is_good_dog = 1 """, replace=True) +.. note:: + In the CLI: :ref:`sqlite-utils create-view ` + Storing JSON ============ @@ -1775,7 +2261,7 @@ For example: .. code-block:: python - db["niche_museums"].insert({ + db.table("niche_museums").insert({ "name": "The Bigfoot Discovery Museum", "url": "http://bigfootdiscoveryproject.com/" "hours": { @@ -1811,11 +2297,11 @@ You can specify an upper case conversion for a specific column like so: .. code-block:: python - db["example"].insert({ + db.table("example").insert({ "name": "The Bigfoot Discovery Museum" }, conversions={"name": "upper(?)"}) - # list(db["example"].rows) now returns: + # list(db.table("example").rows) now returns: # [{'name': 'THE BIGFOOT DISCOVERY MUSEUM'}] The dictionary key is the column name to be converted. The value is the SQL fragment to use, with a ``?`` placeholder for the original value. @@ -1833,7 +2319,7 @@ A more useful example: if you are working with `SpatiaLite `__ method. -If you are using ``pysqlite3`` or ``sqlean.py`` the underlying method may be missing. If you install the `sqlite-dump `__ package then the ``db.iterdump()`` method will use that implementation instead: +If you are using ``pysqlite3`` the underlying method may be missing. If you install the `sqlite-dump `__ package then the ``db.iterdump()`` method will use that implementation instead: .. code-block:: bash pip install sqlite-dump +.. note:: + In the CLI: :ref:`sqlite-utils dump ` + .. _python_api_introspection: Introspecting tables and views @@ -1891,8 +2380,10 @@ Introspecting tables and views If you have loaded an existing table or view, you can use introspection to find out more about it:: - >>> db["PlantType"] + >>> db.table("PlantType")
+ ### db.view("NameOfView") + .. _python_api_introspection_exists: @@ -1901,9 +2392,11 @@ If you have loaded an existing table or view, you can use introspection to find The ``.exists()`` method can be used to find out if a table exists or not:: - >>> db["PlantType"].exists() + >>> db.table("PlantType").exists() True - >>> db["PlantType2"].exists() + >>> db.table("PlantType2").exists() + False + >>> db["table_or_view_name"].exists() False .. _python_api_introspection_count: @@ -1913,9 +2406,9 @@ The ``.exists()`` method can be used to find out if a table exists or not:: The ``.count`` property shows the current number of rows (``select count(*) from table``):: - >>> db["PlantType"].count + >>> db.table("PlantType").count 3 - >>> db["Street_Tree_List"].count + >>> db.table("Street_Tree_List").count 189144 This property will take advantage of :ref:`python_api_cached_table_counts` if the ``use_counts_table`` property is set on the database. You can avoid that optimization entirely by calling ``table.count_where()`` instead of accessing the property. @@ -1929,7 +2422,7 @@ The ``.columns`` property shows the columns in the table or view. It returns a l :: - >>> db["PlantType"].columns + >>> db.table("PlantType").columns [Column(cid=0, name='id', type='INTEGER', notnull=0, default_value=None, is_pk=1), Column(cid=1, name='value', type='TEXT', notnull=0, default_value=None, is_pk=0)] @@ -1940,7 +2433,7 @@ The ``.columns`` property shows the columns in the table or view. It returns a l The ``.columns_dict`` property returns a dictionary version of the columns with just the names and Python types:: - >>> db["PlantType"].columns_dict + >>> db.table("PlantType").columns_dict {'id': , 'value': } .. _python_api_introspection_default_values: @@ -1950,7 +2443,7 @@ The ``.columns_dict`` property returns a dictionary version of the columns with The ``.default_values`` property returns a dictionary of default values for each column that has a default:: - >>> db["table_with_defaults"].default_values + >>> db.table("table_with_defaults").default_values {'score': 5} .. _python_api_introspection_pks: @@ -1960,7 +2453,7 @@ The ``.default_values`` property returns a dictionary of default values for each The ``.pks`` property returns a list of strings naming the primary key columns for the table:: - >>> db["PlantType"].pks + >>> db.table("PlantType").pks ['id'] If a table has no primary keys but is a `rowid table `__, this property will return ``['rowid']``. @@ -1972,7 +2465,7 @@ If a table has no primary keys but is a `rowid table >> db["PlantType"].use_rowid + >>> db.table("PlantType").use_rowid False @@ -1981,17 +2474,39 @@ Almost all SQLite tables have a ``rowid`` column, but a table with no explicitly .foreign_keys ------------- -The ``.foreign_keys`` property returns any foreign key relationships for the table, as a list of ``ForeignKey(table, column, other_table, other_column)`` named tuples. It is not available on views. +The ``.foreign_keys`` property returns any foreign key relationships for the table, as a list of ``ForeignKey`` objects. It is not available on views. + +Each ``ForeignKey`` has the following attributes: + +``table`` + The table the foreign key is defined on. +``column`` + The column on this table, or ``None`` for a compound foreign key. +``other_table`` + The table being referenced. +``other_column`` + The referenced column, or ``None`` for a compound foreign key. +``columns`` + A tuple of the columns on this table, always populated (a one-item tuple for single-column foreign keys). +``other_columns`` + A tuple of the referenced columns. +``is_compound`` + ``True`` if this is a compound (multi-column) foreign key. +``on_delete`` + The ``ON DELETE`` action, e.g. ``"CASCADE"`` - ``"NO ACTION"`` if not set. +``on_update`` + The ``ON UPDATE`` action - ``"NO ACTION"`` if not set. + +``ForeignKey`` was a ``namedtuple`` prior to sqlite-utils 4.0. It is now a dataclass and can no longer be unpacked or indexed as a tuple - access its fields by name instead. See :ref:`upgrading_3_to_4` for details. :: - >>> db["Street_Tree_List"].foreign_keys - [ForeignKey(table='Street_Tree_List', column='qLegalStatus', other_table='qLegalStatus', other_column='id'), - ForeignKey(table='Street_Tree_List', column='qCareAssistant', other_table='qCareAssistant', other_column='id'), - ForeignKey(table='Street_Tree_List', column='qSiteInfo', other_table='qSiteInfo', other_column='id'), - ForeignKey(table='Street_Tree_List', column='qSpecies', other_table='qSpecies', other_column='id'), - ForeignKey(table='Street_Tree_List', column='qCaretaker', other_table='qCaretaker', other_column='id'), - ForeignKey(table='Street_Tree_List', column='PlantType', other_table='PlantType', other_column='id')] + >>> db.table("Street_Tree_List").foreign_keys + [ForeignKey(table='Street_Tree_List', column='qLegalStatus', other_table='qLegalStatus', other_column='id', columns=('qLegalStatus',), other_columns=('id',), is_compound=False, on_delete='NO ACTION', on_update='NO ACTION'), + ForeignKey(table='Street_Tree_List', column='qCareAssistant', other_table='qCareAssistant', other_column='id', columns=('qCareAssistant',), other_columns=('id',), is_compound=False, on_delete='NO ACTION', on_update='NO ACTION'), + ...] + +Compound foreign keys - defined with ``FOREIGN KEY (col_a, col_b) REFERENCES other(col_a, col_b)`` - are returned as a single ``ForeignKey`` with ``is_compound=True``, ``column`` and ``other_column`` set to ``None``, and the participating columns available in the ``columns`` and ``other_columns`` tuples. .. _python_api_introspection_schema: @@ -2000,7 +2515,7 @@ The ``.foreign_keys`` property returns any foreign key relationships for the tab The ``.schema`` property outputs the table's schema as a SQL string:: - >>> print(db["Street_Tree_List"].schema) + >>> print(db.table("Street_Tree_List").schema) CREATE TABLE "Street_Tree_List" ( "TreeID" INTEGER, "qLegalStatus" INTEGER, @@ -2021,12 +2536,12 @@ The ``.schema`` property outputs the table's schema as a SQL string:: "Longitude" REAL, "Location" TEXT , - FOREIGN KEY ("PlantType") REFERENCES [PlantType](id), - FOREIGN KEY ("qCaretaker") REFERENCES [qCaretaker](id), - FOREIGN KEY ("qSpecies") REFERENCES [qSpecies](id), - FOREIGN KEY ("qSiteInfo") REFERENCES [qSiteInfo](id), - FOREIGN KEY ("qCareAssistant") REFERENCES [qCareAssistant](id), - FOREIGN KEY ("qLegalStatus") REFERENCES [qLegalStatus](id)) + FOREIGN KEY ("PlantType") REFERENCES "PlantType"(id), + FOREIGN KEY ("qCaretaker") REFERENCES "qCaretaker"(id), + FOREIGN KEY ("qSpecies") REFERENCES "qSpecies"(id), + FOREIGN KEY ("qSiteInfo") REFERENCES "qSiteInfo"(id), + FOREIGN KEY ("qCareAssistant") REFERENCES "qCareAssistant"(id), + FOREIGN KEY ("qLegalStatus") REFERENCES "qLegalStatus"(id)) .. _python_api_introspection_strict: @@ -2037,7 +2552,7 @@ The ``.strict`` property identifies if the table is a `SQLite STRICT table >> db["ny_times_us_counties"].strict + >>> db.table("ny_times_us_counties").strict False .. _python_api_introspection_indexes: @@ -2049,7 +2564,7 @@ The ``.indexes`` property returns all indexes created for a table, as a list of :: - >>> db["Street_Tree_List"].indexes + >>> db.table("Street_Tree_List").indexes [Index(seq=0, name='"Street_Tree_List_qLegalStatus"', unique=0, origin='c', partial=0, columns=['qLegalStatus']), Index(seq=1, name='"Street_Tree_List_qCareAssistant"', unique=0, origin='c', partial=0, columns=['qCareAssistant']), Index(seq=2, name='"Street_Tree_List_qSiteInfo"', unique=0, origin='c', partial=0, columns=['qSiteInfo']), @@ -2057,6 +2572,9 @@ The ``.indexes`` property returns all indexes created for a table, as a list of Index(seq=4, name='"Street_Tree_List_qCaretaker"', unique=0, origin='c', partial=0, columns=['qCaretaker']), Index(seq=5, name='"Street_Tree_List_PlantType"', unique=0, origin='c', partial=0, columns=['PlantType'])] +.. note:: + In the CLI: :ref:`sqlite-utils indexes ` + .. _python_api_introspection_xindexes: .xindexes @@ -2066,7 +2584,7 @@ The ``.xindexes`` property returns more detailed information about the indexes o :: - >>> db["ny_times_us_counties"].xindexes + >>> db.table("ny_times_us_counties").xindexes [ XIndex( name='idx_ny_times_us_counties_date', @@ -2093,12 +2611,15 @@ The ``.triggers`` property lists database triggers. It can be used on both datab :: - >>> db["authors"].triggers + >>> db.table("authors").triggers [Trigger(name='authors_ai', table='authors', sql='CREATE TRIGGER [authors_ai] AFTER INSERT...'), Trigger(name='authors_ad', table='authors', sql="CREATE TRIGGER [authors_ad] AFTER DELETE..."), Trigger(name='authors_au', table='authors', sql="CREATE TRIGGER [authors_au] AFTER UPDATE")] >>> db.triggers - ... similar output to db["authors"].triggers + ... similar output to db.table("authors").triggers + +.. note:: + In the CLI: :ref:`sqlite-utils triggers ` .. _python_api_introspection_triggers_dict: @@ -2109,7 +2630,7 @@ The ``.triggers_dict`` property returns the triggers for that table as a diction :: - >>> db["authors"].triggers_dict + >>> db.table("authors").triggers_dict {'authors_ai': 'CREATE TRIGGER [authors_ai] AFTER INSERT...', 'authors_ad': 'CREATE TRIGGER [authors_ad] AFTER DELETE...', 'authors_au': 'CREATE TRIGGER [authors_au] AFTER UPDATE'} @@ -2132,7 +2653,7 @@ The ``detect_fts()`` method returns the associated SQLite FTS table name, if one :: - >>> db["authors"].detect_fts() + >>> db.table("authors").detect_fts() "authors_fts" .. _python_api_introspection_virtual_table_using: @@ -2142,8 +2663,8 @@ The ``detect_fts()`` method returns the associated SQLite FTS table name, if one The ``.virtual_table_using`` property reveals if a table is a virtual table. It returns ``None`` for regular tables and the upper case version of the type of virtual table otherwise. For example:: - >>> db["authors"].enable_fts(["name"]) - >>> db["authors_fts"].virtual_table_using + >>> db.table("authors").enable_fts(["name"]) + >>> db.table("authors_fts").virtual_table_using "FTS5" .. _python_api_introspection_has_counts_triggers: @@ -2155,10 +2676,22 @@ The ``.has_counts_triggers`` property shows if a table has been configured with :: - >>> db["authors"].has_counts_triggers + >>> db.table("authors").has_counts_triggers False - >>> db["authors"].enable_counts() - >>> db["authors"].has_counts_triggers + >>> db.table("authors").enable_counts() + >>> db.table("authors").has_counts_triggers + True + +.. _python_api_introspection_supports_strict: + +db.supports_strict +------------------ + +This property on the database object returns ``True`` if the available SQLite version supports `STRICT mode `__, which was added in SQLite 3.37.0 (on 2021-11-27). + +:: + + >>> db.supports_strict True .. _python_api_fts: @@ -2177,13 +2710,13 @@ You can enable full-text search on a table using ``.enable_fts(columns)``: .. code-block:: python - db["dogs"].enable_fts(["name", "twitter"]) + db.table("dogs").enable_fts(["name", "twitter"]) You can then run searches using the ``.search()`` method: .. code-block:: python - rows = list(db["dogs"].search("cleo")) + rows = list(db.table("dogs").search("cleo")) This method returns a generator that can be looped over to get dictionaries for each row, similar to :ref:`python_api_rows`. @@ -2191,32 +2724,32 @@ If you insert additional records into the table you will need to refresh the sea .. code-block:: python - db["dogs"].insert({ + db.table("dogs").insert({ "id": 2, "name": "Marnie", "twitter": "MarnieTheDog", "age": 16, "is_good_dog": True, }, pk="id") - db["dogs"].populate_fts(["name", "twitter"]) + db.table("dogs").populate_fts(["name", "twitter"]) A better solution is to use database triggers. You can set up database triggers to automatically update the full-text index using ``create_triggers=True``: .. code-block:: python - db["dogs"].enable_fts(["name", "twitter"], create_triggers=True) + db.table("dogs").enable_fts(["name", "twitter"], create_triggers=True) ``.enable_fts()`` defaults to using `FTS5 `__. If you wish to use `FTS4 `__ instead, use the following: .. code-block:: python - db["dogs"].enable_fts(["name", "twitter"], fts_version="FTS4") + db.table("dogs").enable_fts(["name", "twitter"], fts_version="FTS4") You can customize the tokenizer configured for the table using the ``tokenize=`` parameter. For example, to enable Porter stemming, where English words like "running" will match stemmed alternatives such as "run", use ``tokenize="porter"``: .. code-block:: python - db["articles"].enable_fts(["headline", "body"], tokenize="porter") + db.table("articles").enable_fts(["headline", "body"], tokenize="porter") The SQLite documentation has more on `FTS5 tokenizers `__ and `FTS4 tokenizers `__. ``porter`` is a valid option for both. @@ -2226,7 +2759,7 @@ You can replace the existing table with a new configuration using ``replace=True .. code-block:: python - db["articles"].enable_fts(["headline"], tokenize="porter", replace=True) + db.table("articles").enable_fts(["headline"], tokenize="porter", replace=True) This will have no effect if the FTS table already exists, otherwise it will drop and recreate the table with the new settings. This takes into consideration the columns, the tokenizer, the FTS version used and whether or not the table has triggers. @@ -2234,7 +2767,10 @@ To remove the FTS tables and triggers you created, use the ``disable_fts()`` tab .. code-block:: python - db["dogs"].disable_fts() + db.table("dogs").disable_fts() + +.. note:: + In the CLI: :ref:`sqlite-utils enable-fts ` .. _python_api_quote_fts: @@ -2257,7 +2793,7 @@ The ``table.search(q)`` method returns a generator over Python dictionaries repr .. code-block:: python - for article in db["articles"].search("jquery"): + for article in db.table("articles").search("jquery"): print(article) The ``.search()`` method also accepts the following optional parameters: @@ -2280,6 +2816,9 @@ The ``.search()`` method also accepts the following optional parameters: ``where_args`` dictionary Arguments to use for ``:param`` placeholders in the extra WHERE clause +``include_rank`` bool + If set a ``rank`` column will be included with the BM25 ranking score - for FTS5 tables only. + ``quote`` bool Apply :ref:`FTS quoting rules ` to the search query, disabling advanced query syntax in a way that avoids surprising errors. @@ -2287,7 +2826,7 @@ To return just the title and published columns for three matches for ``"dog"`` w .. code-block:: python - for article in db["articles"].search( + for article in db.table("articles").search( "dog", order_by="published desc", limit=3, @@ -2297,6 +2836,9 @@ To return just the title and published columns for three matches for ``"dog"`` w ): print(article) +.. note:: + In the CLI: :ref:`sqlite-utils search ` + .. _python_api_fts_search_sql: Building SQL queries with table.search_sql() @@ -2306,7 +2848,7 @@ You can generate the SQL query that would be used for a search using the ``table .. code-block:: python - print(db["articles"].search_sql(columns=["title", "author"])) + print(db.table("articles").search_sql(columns=["title", "author"])) Outputs: @@ -2369,18 +2911,21 @@ You can rebuild a table using the ``table.rebuild_fts()`` method. This is useful .. code-block:: python - db["dogs"].rebuild_fts() + db.table("dogs").rebuild_fts() This method can be called on a table that has been configured for full-text search - ``dogs`` in this instance - or directly on a ``_fts`` table: .. code-block:: python - db["dogs_fts"].rebuild_fts() + db.table("dogs_fts").rebuild_fts() This runs the following SQL:: INSERT INTO dogs_fts (dogs_fts) VALUES ("rebuild"); +.. note:: + In the CLI: :ref:`sqlite-utils rebuild-fts ` + .. _python_api_fts_optimize: Optimizing a full-text search table @@ -2390,12 +2935,15 @@ Once you have populated a FTS table you can optimize it to dramatically reduce i .. code-block:: python - db["dogs"].optimize() + db.table("dogs").optimize() This runs the following SQL:: INSERT INTO dogs_fts (dogs_fts) VALUES ("optimize"); +.. note:: + In the CLI: :ref:`sqlite-utils optimize ` + .. _python_api_cached_table_counts: Cached table counts using triggers @@ -2407,15 +2955,15 @@ The ``table.enable_counts()`` method can be used to configure triggers to contin .. code-block:: python - db["dogs"].enable_counts() + db.table("dogs").enable_counts() This will create the ``_counts`` table if it does not already exist, with the following schema: .. code-block:: sql - CREATE TABLE [_counts] ( - [table] TEXT PRIMARY KEY, - [count] INTEGER DEFAULT 0 + CREATE TABLE "_counts" ( + "table" TEXT PRIMARY KEY, + "count" INTEGER DEFAULT 0 ) You can enable cached counts for every table in a database (except for virtual tables and the ``_counts`` table itself) using the database ``enable_counts()`` method: @@ -2458,6 +3006,9 @@ If the ``_counts`` table ever becomes out-of-sync with the actual table counts y db.reset_counts() +.. note:: + In the CLI: :ref:`sqlite-utils enable-counts ` + .. _python_api_create_index: Creating indexes @@ -2467,7 +3018,7 @@ You can create an index on a table using the ``.create_index(columns)`` method. .. code-block:: python - db["dogs"].create_index(["is_good_dog"]) + db.table("dogs").create_index(["is_good_dog"]) By default the index will be named ``idx_{table-name}_{columns}``. If you pass ``find_unique_name=True`` and the automatically derived name already exists, an available name will be found by incrementing a suffix number, for example ``idx_items_title_2``. @@ -2475,7 +3026,7 @@ You can customize the name of the created index by passing the ``index_name`` pa .. code-block:: python - db["dogs"].create_index( + db.table("dogs").create_index( ["is_good_dog", "age"], index_name="good_dogs_by_age" ) @@ -2486,7 +3037,7 @@ To create an index in descending order for a column, wrap the column name in ``d from sqlite_utils.db import DescIndex - db["dogs"].create_index( + db.table("dogs").create_index( ["is_good_dog", DescIndex("age")], index_name="good_dogs_by_age" ) @@ -2495,12 +3046,23 @@ You can create a unique index by passing ``unique=True``: .. code-block:: python - db["dogs"].create_index(["name"], unique=True) + db.table("dogs").create_index(["name"], unique=True) Use ``if_not_exists=True`` to do nothing if an index with that name already exists. Pass ``analyze=True`` to run ``ANALYZE`` against the new index after creating it. +You can drop an index from a table using ``.drop_index(index_name)``: + +.. code-block:: python + + db.table("dogs").drop_index("idx_dogs_name") + +Use ``ignore=True`` to ignore the error if the index does not exist. + +.. note:: + In the CLI: :ref:`sqlite-utils create-index ` and :ref:`sqlite-utils drop-index ` + .. _python_api_analyze: Optimizing index usage with ANALYZE @@ -2526,7 +3088,10 @@ To run against all indexes attached to a specific table, you can either pass the .. code-block:: python - db["dogs"].analyze() + db.table("dogs").analyze() + +.. note:: + In the CLI: :ref:`sqlite-utils analyze ` .. _python_api_vacuum: @@ -2539,6 +3104,9 @@ You can optimize your database by running VACUUM against it like so: Database("my_database.db").vacuum() +.. note:: + In the CLI: :ref:`sqlite-utils vacuum ` + .. _python_api_wal: WAL mode @@ -2556,6 +3124,8 @@ You can disable WAL mode using ``.disable_wal()``: Database("my_database.db").disable_wal() +The journal mode can only be changed outside of a transaction. Calling either method while a transaction is open - inside a ``db.atomic()`` block, for example - raises a ``sqlite_utils.db.TransactionError``, unless the database is already in the requested mode in which case the call is a no-op. + You can check the current journal mode for a database using the ``journal_mode`` property: .. code-block:: python @@ -2564,6 +3134,9 @@ You can check the current journal mode for a database using the ``journal_mode`` This will usually be ``wal`` or ``delete`` (meaning WAL is disabled), but can have other values - see the `PRAGMA journal_mode `__ documentation. +.. note:: + In the CLI: :ref:`sqlite-utils enable-wal and disable-wal ` + .. _python_api_suggest_column_types: Suggesting column types @@ -2577,7 +3150,7 @@ That table ``.create()`` method takes a dictionary mapping column names to the P .. code-block:: python - db["cats"].create({ + db.table("cats").create({ "id": int, "name": str, "weight": float, @@ -2615,21 +3188,21 @@ For example: # Create the table db = Database("cats.db") - db["cats"].create(types, pk="id") + db.table("cats").create(types, pk="id") # Insert the records - db["cats"].insert_all(cats) + db.table("cats").insert_all(cats) - # list(db["cats"].rows) now returns: + # list(db.table("cats").rows) now returns: # [{"id": 1, "name": "Snowflake", "age": None, "thumbnail": None} # {"id": 2, "name": "Crabtree", "age": 4, "thumbnail": None}] # The table schema looks like this: - # print(db["cats"].schema) - # CREATE TABLE [cats] ( - # [id] INTEGER PRIMARY KEY, - # [name] TEXT, - # [age] INTEGER, - # [thumbnail] BLOB + # print(db.table("cats").schema) + # CREATE TABLE "cats" ( + # "id" INTEGER PRIMARY KEY, + # "name" TEXT, + # "age" INTEGER, + # "thumbnail" BLOB # ) .. _python_api_register_function: @@ -2674,7 +3247,7 @@ By default, the name of the Python function will be used as the name of the SQL print(db.execute('select rev("hello")').fetchone()[0]) -Python 3.8 added the ability to register `deterministic SQLite functions `__, allowing you to indicate that a function will return the exact same result for any given inputs and hence allowing SQLite to apply some performance optimizations. You can mark a function as deterministic using ``deterministic=True``, like this: +If a function will return the exact same result for any given inputs you can register it as a `deterministic SQLite function `__ allowing SQLite to apply some performance optimizations: .. code-block:: python @@ -2682,8 +3255,6 @@ Python 3.8 added the ability to register `deterministic SQLite functions ` + .. _python_api_quote: Quoting strings for use in SQL @@ -2792,12 +3366,12 @@ If we insert this data directly into a table we will get a schema that is entire from sqlite_utils import Database db = Database(memory=True) - db["creatures"].insert_all(rows) + db.table("creatures").insert_all(rows) print(db.schema) # Outputs: - # CREATE TABLE [creatures] ( - # [id] TEXT, - # [name] TEXT + # CREATE TABLE "creatures" ( + # "id" TEXT, + # "name" TEXT # ); We can detect the best column types using a ``TypeTracker`` instance: @@ -2807,7 +3381,7 @@ We can detect the best column types using a ``TypeTracker`` instance: from sqlite_utils.utils import TypeTracker tracker = TypeTracker() - db["creatures2"].insert_all(tracker.wrap(rows)) + db.table("creatures2").insert_all(tracker.wrap(rows)) print(tracker.types) # Outputs {'id': 'integer', 'name': 'text'} @@ -2815,12 +3389,12 @@ We can then apply those types to our new table using the :ref:`table.transform() .. code-block:: python - db["creatures2"].transform(types=tracker.types) - print(db["creatures2"].schema) + db.table("creatures2").transform(types=tracker.types) + print(db.table("creatures2").schema) # Outputs: - # CREATE TABLE [creatures2] ( - # [id] INTEGER, - # [name] TEXT + # CREATE TABLE "creatures2" ( + # "id" INTEGER, + # "name" TEXT # ); .. _python_api_gis: @@ -2838,6 +3412,9 @@ Initialize SpatiaLite .. automethod:: sqlite_utils.db.Database.init_spatialite :noindex: +.. note:: + In the CLI: :ref:`sqlite-utils create-database --init-spatialite ` + .. _python_api_gis_find_spatialite: Finding SpatiaLite @@ -2853,6 +3430,9 @@ Adding geometry columns .. automethod:: sqlite_utils.db.Table.add_geometry_column :noindex: +.. note:: + In the CLI: :ref:`sqlite-utils add-geometry-column ` + .. _python_api_gis_create_spatial_index: Creating a spatial index @@ -2860,3 +3440,6 @@ Creating a spatial index .. automethod:: sqlite_utils.db.Table.create_spatial_index :noindex: + +.. note:: + In the CLI: :ref:`sqlite-utils create-spatial-index ` diff --git a/docs/reference.rst b/docs/reference.rst index 5b5fd25..a9fdf29 100644 --- a/docs/reference.rst +++ b/docs/reference.rst @@ -70,6 +70,13 @@ sqlite_utils.db.ColumnDetails .. autoclass:: sqlite_utils.db.ColumnDetails +.. _reference_db_other_foreign_key: + +sqlite_utils.db.ForeignKey +-------------------------- + +.. autoclass:: sqlite_utils.db.ForeignKey + sqlite_utils.utils ================== diff --git a/docs/tutorial.ipynb b/docs/tutorial.ipynb index 179f010..bade686 100644 --- a/docs/tutorial.ipynb +++ b/docs/tutorial.ipynb @@ -180,10 +180,10 @@ "name": "stdout", "output_type": "stream", "text": [ - "CREATE TABLE [creatures] (\n", - " [name] TEXT,\n", - " [species] TEXT,\n", - " [age] FLOAT\n", + "CREATE TABLE \"creatures\" (\n", + " \"name\" TEXT,\n", + " \"species\" TEXT,\n", + " \"age\" FLOAT\n", ")\n" ] } @@ -534,11 +534,11 @@ "name": "stdout", "output_type": "stream", "text": [ - "CREATE TABLE [creatures] (\n", - " [id] INTEGER PRIMARY KEY,\n", - " [name] TEXT,\n", - " [species] TEXT,\n", - " [age] FLOAT\n", + "CREATE TABLE \"creatures\" (\n", + " \"id\" INTEGER PRIMARY KEY,\n", + " \"name\" TEXT,\n", + " \"species\" TEXT,\n", + " \"age\" FLOAT\n", ")\n" ] } @@ -929,11 +929,11 @@ "output_type": "stream", "text": [ "CREATE TABLE \"creatures\" (\n", - " [id] INTEGER PRIMARY KEY,\n", - " [name] TEXT,\n", - " [species_id] INTEGER,\n", - " [age] FLOAT,\n", - " FOREIGN KEY([species_id]) REFERENCES [species]([id])\n", + " \"id\" INTEGER PRIMARY KEY,\n", + " \"name\" TEXT,\n", + " \"species_id\" INTEGER,\n", + " \"age\" FLOAT,\n", + " FOREIGN KEY(\"species_id\") REFERENCES \"species\"(\"id\")\n", ")\n", "[{'id': 1, 'name': 'Cleo', 'species_id': 1, 'age': 6.0}, {'id': 2, 'name': 'Lila', 'species_id': 2, 'age': 0.8}, {'id': 3, 'name': 'Bants', 'species_id': 2, 'age': 0.8}, {'id': 4, 'name': 'Azi', 'species_id': 2, 'age': 0.8}, {'id': 5, 'name': 'Snowy', 'species_id': 2, 'age': 0.9}, {'id': 6, 'name': 'Blue', 'species_id': 2, 'age': 0.9}]\n" ] @@ -962,9 +962,9 @@ "name": "stdout", "output_type": "stream", "text": [ - "CREATE TABLE [species] (\n", - " [id] INTEGER PRIMARY KEY,\n", - " [species] TEXT\n", + "CREATE TABLE \"species\" (\n", + " \"id\" INTEGER PRIMARY KEY,\n", + " \"species\" TEXT\n", ")\n", "[{'id': 1, 'species': 'dog'}, {'id': 2, 'species': 'chicken'}]\n" ] @@ -1048,4 +1048,4 @@ }, "nbformat": 4, "nbformat_minor": 5 -} +} \ No newline at end of file diff --git a/docs/upgrading.rst b/docs/upgrading.rst new file mode 100644 index 0000000..92b582a --- /dev/null +++ b/docs/upgrading.rst @@ -0,0 +1,146 @@ +.. _upgrading: + +=========== + Upgrading +=========== + +This page describes the changes you may need to make to your own code or scripts when upgrading between major versions of ``sqlite-utils``. + +For the full list of changes in every release see the :ref:`changelog`. + +.. _upgrading_3_to_4: + +Upgrading from 3.x to 4.0 +========================= + +Requirements +------------ + +- Python 3.10 or higher is required. +- The ``click`` dependency must be version 8.3.1 or later. + +Command-line changes +-------------------- + +**Type detection is now the default for CSV and TSV imports.** ``sqlite-utils insert`` and ``sqlite-utils upsert`` now detect column types when importing CSV or TSV data - previously every column was created as ``TEXT`` unless you passed ``--detect-types``. To restore the old behavior pass the new ``--no-detect-types`` flag: + +.. code-block:: bash + + sqlite-utils insert data.db rows data.csv --csv --no-detect-types + +Two related things have been removed: + +- The ``SQLITE_UTILS_DETECT_TYPES`` environment variable. +- The old ``-d/--detect-types`` flag itself. Since detection is now the default the flag did nothing - remove it from any scripts that used it. + +**The convert command no longer skips falsey values.** ``sqlite-utils convert`` previously skipped values that evaluated to ``False`` (empty strings, ``0``) unless you passed ``--no-skip-false``. All values are now converted and the ``--no-skip-false`` flag has been removed. + +**drop-table and drop-view check the object type.** ``sqlite-utils drop-table`` 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. If you relied on that (unlikely), use the matching command instead. + +**sqlite-utils tui has moved to a plugin.** The optional terminal interface is now provided by the `sqlite-utils-tui `__ plugin: + +.. code-block:: bash + + sqlite-utils install sqlite-utils-tui + +Python API changes +------------------ + +**db.query() now rejects SQL that does not return rows.** This is likely the most common change you will need to make to existing code. ``db.query()`` used to accept any SQL statement - passing one that returns no rows, such as an ``INSERT`` or ``UPDATE`` without a ``RETURNING`` clause or a ``CREATE TABLE``, did nothing at all, silently. Those statements now raise a ``ValueError``, and are rolled back so they have no effect on the database. Transaction control statements (``BEGIN``, ``COMMIT``, ``END``, ``ROLLBACK``, ``SAVEPOINT``, ``RELEASE``) plus ``VACUUM``, ``ATTACH`` and ``DETACH`` are also rejected with a ``ValueError``, without being executed at all. Use ``db.execute()`` for statements that do not return rows: + +.. code-block:: python + + # 3.x accepted this but silently did nothing: + db.query("update dogs set name = 'Cleopaws'") + + # In 4.0 use execute() for SQL that does not return rows: + db.execute("update dogs set name = 'Cleopaws'") + +**db.query() executes immediately.** ``db.query(sql)`` previously returned a generator that did not execute the SQL until you started iterating over it. The SQL now runs as soon as the method is called - rows are still fetched lazily, but errors in your SQL raise at the ``db.query()`` call site rather than on first iteration, and a write with a ``RETURNING`` clause takes effect even if you never iterate over its results. + +**db.table() no longer returns views.** ``db.table(name)`` now raises a ``sqlite_utils.db.NoTable`` exception if ``name`` is a SQL view. Use the new ``db.view(name)`` method for views: + +.. code-block:: python + + table = db.table("my_table") + view = db.view("my_view") + +``db["name"]`` still returns either a ``Table`` or a ``View`` depending on what exists in the database. + +**Upserts use INSERT ... ON CONFLICT.** Upsert operations now use SQLite's ``INSERT ... ON CONFLICT SET`` syntax rather than the previous ``INSERT OR IGNORE`` followed by ``UPDATE``. If your code depends on the old behavior, pass ``use_old_upsert=True`` to the ``Database()`` constructor - see :ref:`python_api_old_upsert`. + +**Upsert records must include their primary keys.** ``table.upsert()`` and ``table.upsert_all()`` now raise ``sqlite_utils.db.PrimaryKeyRequired`` if a record is missing a value for any primary key column (or has ``None`` for one). Previously such records were quietly inserted as new rows. Relatedly, ``pk=`` is now optional when the table already exists with a primary key - it is detected automatically. + +**Floating point columns are now REAL.** Auto-detected floating point columns are created with the correct SQLite type ``REAL`` instead of ``FLOAT``. Code that inspects column types should expect ``REAL``. + +**Generated schemas use double quotes.** Tables created by this library now wrap table and column names in ``"double-quotes"`` where they previously used ``[square-braces]``. If you compare ``table.schema`` strings against expected values you will need to update them. + +**table.convert() no longer skips falsey values.** Matching the CLI change above, ``table.convert()`` now converts every value. The ``skip_false`` parameter has been removed - previously it defaulted to ``True``, skipping empty strings and other falsey values. + +**Null values are no longer extracted into lookup tables.** ``table.extract()`` and the ``sqlite-utils extract`` command leave rows alone if every extracted column is ``null`` - the new foreign key column is left as ``null`` instead of pointing at an all-``null`` record in the lookup table. The ``extracts=`` insert option similarly keeps ``None`` values as ``null``. Relatedly, ``table.lookup()`` now compares values using ``IS`` so that looking up a value containing ``None`` returns the existing matching row - previously it inserted a duplicate row on every call. + +**ensure_autocommit_off() is now ensure_autocommit_on().** The ``db.ensure_autocommit_off()`` context manager has been renamed to ``db.ensure_autocommit_on()``. The old name described the opposite of what the method did: it 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. The behavior is unchanged - update any calls to use the new name. + +**View.enable_fts() has been removed.** The ``View`` class previously had an ``enable_fts()`` method that existed only to raise ``NotImplementedError`` - full-text search is not supported for views. Calling it now raises ``AttributeError`` like any other missing method. + +**ForeignKey is now a dataclass, not a namedtuple.** The ``ForeignKey`` objects returned by ``table.foreign_keys`` gained new fields - ``columns``, ``other_columns``, ``is_compound``, ``on_delete`` and ``on_update`` - so that compound (multi-column) foreign keys and foreign key actions can be represented. To make room for those fields cleanly ``ForeignKey`` is now a dataclass rather than a ``namedtuple``, so it can no longer be unpacked or indexed as a tuple. Access its fields by name instead: + +.. code-block:: python + + # 3.x - tuple unpacking, no longer works: + for table, column, other_table, other_column in db["courses"].foreign_keys: + ... + + # 4.0 - access fields by name: + for fk in db["courses"].foreign_keys: + fk.table, fk.column, fk.other_table, fk.other_column + +Attempting the old unpacking or ``fk[0]`` indexing now raises ``TypeError``, so any code using those patterns will fail loudly rather than silently misbehave. Like the old namedtuple, ``ForeignKey`` instances are immutable and hashable - they can be collected into sets and used as dictionary keys. Note that equality now includes the ``on_delete`` and ``on_update`` actions: a ``ForeignKey`` with ``ON DELETE CASCADE`` is not equal to one without. + +Compound foreign keys - previously returned as one ``ForeignKey`` per column, misleadingly suggesting several independent single-column keys - are now returned as a single ``ForeignKey`` with ``is_compound=True``. For these the scalar ``column`` and ``other_column`` fields are ``None``; use the ``columns`` and ``other_columns`` tuples instead. Single-column foreign keys are unaffected apart from the class change: ``column``/``other_column`` behave as before and ``columns``/``other_columns`` are one-item tuples. + +Two related behavior changes to ``table.transform()``: compound foreign keys now survive a transform (previously they were split into separate single-column keys), and ``ON DELETE``/``ON UPDATE`` actions such as ``ON DELETE CASCADE`` are now preserved (previously they were silently stripped from the schema). + +**Validation errors raise ValueError.** Invalid arguments to Python API methods - for example ``create_table()`` with no columns, or ``ignore=True`` together with ``replace=True`` - now raise ``ValueError``. They previously raised ``AssertionError`` from bare ``assert`` statements, which were silently skipped under ``python -O``. + +**Transaction behavior is now well-defined.** 4.0 introduces the :ref:`db.atomic() ` context manager and uses it consistently for every write operation - the full model is described in :ref:`python_api_transactions`. Changes you may notice: + +- Write statements executed with raw ``db.execute()`` calls now commit automatically, unless a transaction is already open in which case they join it. Previously they opened an implicit transaction that nothing committed - if your code used ``db.execute()`` for writes and relied on ``db.conn.rollback()`` to undo them, open an explicit transaction with the new ``db.begin()`` method first. +- Multi-step operations such as ``table.transform()`` no longer commit an existing transaction you have open - they use savepoints inside it instead. +- ``db.enable_wal()`` and ``db.disable_wal()`` raise a ``sqlite_utils.db.TransactionError`` if called while a transaction is open, instead of silently committing it. +- Using ``Database`` as a context manager (``with Database(path) as db:``) closes the connection on exit *without* committing - a transaction you explicitly opened with ``db.begin()`` and did not commit is rolled back. +- ``Database()`` rejects connections created with the Python 3.12+ ``sqlite3.connect(..., autocommit=True)`` or ``autocommit=False`` options, raising ``sqlite_utils.db.TransactionError``. On those connections every write the library made was silently discarded when the connection closed. + +Packaging changes +----------------- + +- ``sqlite-utils`` now uses ``pyproject.toml`` in place of ``setup.py``. +- ``pip`` is now a runtime dependency, used by the ``sqlite-utils install`` and ``uninstall`` commands. + +New features to be aware of +--------------------------- + +Not breaking changes, but new in 4.0 and worth knowing about when you upgrade: + +- A :ref:`database migrations system `, incorporating the functionality of the ``sqlite-migrate`` plugin. If you used that plugin, the built-in system reads the same ``_sqlite_migrations`` table - your applied migrations will not run again. Update your migration files to use ``from sqlite_utils import Migrations``. +- :ref:`db.atomic() ` for nested transaction support. +- ``table.insert_all()`` and ``table.upsert_all()`` accept an iterator of lists or tuples as an alternative to dictionaries - see :ref:`python_api_insert_lists`. + +.. _upgrading_2_to_3: + +Upgrading from 2.x to 3.0 +========================= + +The 3.0 release redesigned search. The breaking changes were minor: + +- ``table.search()`` returns a generator of dictionaries, sorted by relevance. It previously returned a list of tuples sorted by ``rowid``. +- The ``-c`` shortcut for ``--csv`` and the ``-f`` shortcut for ``--fmt`` were removed from the CLI - use the full option names. + +.. _upgrading_1_to_2: + +Upgrading from 1.x to 2.0 +========================= + +The 2.0 release changed the meaning of *upsert*. In 1.x, ``table.upsert()`` and ``table.upsert_all()`` actually performed ``INSERT OR REPLACE`` operations - entirely replacing the existing row. Since 2.0 an upsert updates only the columns you provide, leaving other columns untouched. + +If you want the 1.x behavior, use ``table.insert(..., replace=True)`` or ``table.insert_all(..., replace=True)`` instead. diff --git a/mypy.ini b/mypy.ini index 768d182..2f6a875 100644 --- a/mypy.ini +++ b/mypy.ini @@ -1,4 +1,32 @@ [mypy] +python_version = 3.10 +warn_return_any = False +warn_unused_configs = True +warn_redundant_casts = False +warn_unused_ignores = False +check_untyped_defs = True +disallow_untyped_defs = False +disallow_incomplete_defs = False +no_implicit_optional = True +strict_equality = True -[mypy-pysqlite3,sqlean,sqlite_dump] -ignore_missing_imports = True \ No newline at end of file +[mypy-sqlite_utils.cli] +ignore_errors = True + +[mypy-pysqlite3.*] +ignore_missing_imports = True + +[mypy-sqlite_dump.*] +ignore_missing_imports = True + +[mypy-sqlite_fts4.*] +ignore_missing_imports = True + +[mypy-pandas.*] +ignore_missing_imports = True + +[mypy-numpy.*] +ignore_missing_imports = True + +[mypy-tests.*] +ignore_errors = True diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..003322c --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,85 @@ +[project] +name = "sqlite-utils" +version = "4.1.1" +description = "CLI tool and Python library for manipulating SQLite databases" +readme = { file = "README.md", content-type = "text/markdown" } +authors = [ + { name = "Simon Willison" }, +] +license = "Apache-2.0" +requires-python = ">=3.10" +classifiers = [ + "Development Status :: 5 - Production/Stable", + "Intended Audience :: Developers", + "Intended Audience :: End Users/Desktop", + "Intended Audience :: Science/Research", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", + "Programming Language :: Python :: 3.14", + "Topic :: Database", +] + +dependencies = [ + "click>=8.3.1", + "click-default-group>=1.2.3", + "pluggy", + "python-dateutil", + "sqlite-fts4", + "tabulate", + "pip", +] + +[dependency-groups] +dev = [ + "black>=26.3.1", + "click>=8.4.2", + "cogapp", + "hypothesis", + "pytest", + # mypy + "data-science-types", + "mypy", + "types-click", + "types-pluggy", + "types-python-dateutil", + "types-tabulate", + # flake8 + "flake8", + "flake8-pyproject", + "ty>=0.0.37", + # For stable cog: + "tabulate>=0.10.0", +] +docs = [ + "codespell", + "furo", + "pygments-csv-lexer", + "sphinx-autobuild", + "sphinx-copybutton", +] + +[project.urls] +Homepage = "https://github.com/simonw/sqlite-utils" +Documentation = "https://sqlite-utils.datasette.io/en/stable/" +Changelog = "https://sqlite-utils.datasette.io/en/stable/changelog.html" +Issues = "https://github.com/simonw/sqlite-utils/issues" +CI = "https://github.com/simonw/sqlite-utils/actions" + +[project.scripts] +sqlite-utils = "sqlite_utils.cli:cli" + +[build-system] +# setuptools 77+ is needed for the PEP 639 license = "Apache-2.0" expression +requires = ["setuptools>=77"] +build-backend = "setuptools.build_meta" + +[tool.flake8] +max-line-length = 160 +# Black compatibility, E203 whitespace before ':': +extend-ignore = ["E203"] +extend-exclude = [".venv", "build", "dist", "docs", "sqlite_utils.egg-info"] + +[tool.setuptools.package-data] +sqlite_utils = ["py.typed"] diff --git a/setup.cfg b/setup.cfg deleted file mode 100644 index 6b9c885..0000000 --- a/setup.cfg +++ /dev/null @@ -1,4 +0,0 @@ -[flake8] -max-line-length = 160 -# Black compatibility, E203 whitespace before ':': -extend-ignore = E203 \ No newline at end of file diff --git a/setup.py b/setup.py deleted file mode 100644 index 1912f6f..0000000 --- a/setup.py +++ /dev/null @@ -1,84 +0,0 @@ -from setuptools import setup, find_packages -import io -import os - -VERSION = "3.35.2" - - -def get_long_description(): - with io.open( - os.path.join(os.path.dirname(os.path.abspath(__file__)), "README.md"), - encoding="utf8", - ) as fp: - return fp.read() - - -setup( - name="sqlite-utils", - description="CLI tool and Python library for manipulating SQLite databases", - long_description=get_long_description(), - long_description_content_type="text/markdown", - author="Simon Willison", - version=VERSION, - license="Apache License, Version 2.0", - packages=find_packages(exclude=["tests", "tests.*"]), - package_data={"sqlite_utils": ["py.typed"]}, - install_requires=[ - "sqlite-fts4", - "click", - "click-default-group>=1.2.3", - "tabulate", - "python-dateutil", - "pluggy", - ], - extras_require={ - "test": ["pytest", "black", "hypothesis", "cogapp"], - "docs": [ - "furo", - "sphinx-autobuild", - "codespell", - "sphinx-copybutton", - "beanbag-docutils>=2.0", - "pygments-csv-lexer", - ], - "mypy": [ - "mypy", - "types-click", - "types-tabulate", - "types-python-dateutil", - "types-pluggy", - "data-science-types", - ], - "flake8": ["flake8"], - "tui": ["trogon"], - }, - entry_points=""" - [console_scripts] - sqlite-utils=sqlite_utils.cli:cli - """, - url="https://github.com/simonw/sqlite-utils", - project_urls={ - "Documentation": "https://sqlite-utils.datasette.io/en/stable/", - "Changelog": "https://sqlite-utils.datasette.io/en/stable/changelog.html", - "Source code": "https://github.com/simonw/sqlite-utils", - "Issues": "https://github.com/simonw/sqlite-utils/issues", - "CI": "https://github.com/simonw/sqlite-utils/actions", - }, - python_requires=">=3.7", - classifiers=[ - "Development Status :: 5 - Production/Stable", - "Intended Audience :: Developers", - "Intended Audience :: Science/Research", - "Intended Audience :: End Users/Desktop", - "Topic :: Database", - "License :: OSI Approved :: Apache Software License", - "Programming Language :: Python :: 3.7", - "Programming Language :: Python :: 3.8", - "Programming Language :: Python :: 3.9", - "Programming Language :: Python :: 3.10", - "Programming Language :: Python :: 3.11", - "Programming Language :: Python :: 3.12", - ], - # Needed to bundle py.typed so mypy can see it: - zip_safe=False, -) diff --git a/sqlite_utils/__init__.py b/sqlite_utils/__init__.py index b8046f6..58ee7ab 100644 --- a/sqlite_utils/__init__.py +++ b/sqlite_utils/__init__.py @@ -2,5 +2,6 @@ from .utils import suggest_column_types from .hookspecs import hookimpl from .hookspecs import hookspec from .db import Database +from .migrations import Migrations -__all__ = ["Database", "suggest_column_types", "hookimpl", "hookspec"] +__all__ = ["Database", "Migrations", "suggest_column_types", "hookimpl", "hookspec"] diff --git a/sqlite_utils/cli.py b/sqlite_utils/cli.py index 5821db6..e0b8969 100644 --- a/sqlite_utils/cli.py +++ b/sqlite_utils/cli.py @@ -1,13 +1,25 @@ import base64 +import difflib +from typing import Any import click -from click_default_group import DefaultGroup # type: ignore -from datetime import datetime +from click_default_group import DefaultGroup +from datetime import datetime, timezone import hashlib import pathlib from runpy import run_module import sqlite_utils -from sqlite_utils.db import AlterError, BadMultiValues, DescIndex, NoTable -from sqlite_utils.plugins import pm, get_plugins +from sqlite_utils.db import ( + AlterError, + BadMultiValues, + DEFAULT, + DescIndex, + InvalidColumns, + NoTable, + NoView, + PrimaryKeyRequired, + quote_identifier, +) +from sqlite_utils.plugins import ensure_plugins_loaded, pm, get_plugins from sqlite_utils.utils import maximize_csv_field_size_limit from sqlite_utils import recipes import textwrap @@ -24,6 +36,7 @@ from .utils import ( OperationalError, _compile_code, chunks, + dedupe_keys, file_progress, find_spatialite, flatten as _flatten, @@ -35,15 +48,30 @@ from .utils import ( TypeTracker, ) -try: - import trogon # type: ignore -except ImportError: - trogon = None - - CONTEXT_SETTINGS = dict(help_option_names=["-h", "--help"]) -VALID_COLUMN_TYPES = ("INTEGER", "TEXT", "FLOAT", "BLOB") + +def _register_db_for_cleanup(db): + """Register a database to be closed when the Click context is cleaned up.""" + ctx = click.get_current_context(silent=True) + if ctx is None: + return + if "_databases_to_close" not in ctx.meta: + ctx.meta["_databases_to_close"] = [] + ctx.call_on_close(lambda: _close_databases(ctx)) + ctx.meta["_databases_to_close"].append(db) + + +def _close_databases(ctx): + """Close all databases registered for cleanup.""" + for db in ctx.meta.get("_databases_to_close", []): + try: + db.close() + except Exception: + pass + + +VALID_COLUMN_TYPES = ("INTEGER", "TEXT", "FLOAT", "REAL", "BLOB") UNICODE_ERROR = """ {} @@ -60,6 +88,14 @@ It's often worth trying: --encoding=latin-1 maximize_csv_field_size_limit() +class CaseInsensitiveChoice(click.Choice): + def __init__(self, choices): + super().__init__([choice.lower() for choice in choices]) + + def convert(self, value, param, ctx): + return super().convert(value.lower(), param, ctx) + + def output_options(fn): for decorator in reversed( ( @@ -77,7 +113,11 @@ def output_options(fn): ), click.option("--csv", is_flag=True, help="Output CSV"), click.option("--tsv", is_flag=True, help="Output TSV"), - click.option("--no-headers", is_flag=True, help="Omit CSV headers"), + click.option( + "--no-headers", + is_flag=True, + help="Omit headers from CSV/TSV and table/--fmt output", + ), click.option( "-t", "--table", is_flag=True, help="Output as a formatted table" ), @@ -93,6 +133,13 @@ def output_options(fn): is_flag=True, default=False, ), + click.option( + "--ascii", + "ascii_", + help="Escape non-ASCII characters in JSON output as \\uXXXX", + is_flag=True, + default=False, + ), ) ): fn = decorator(fn) @@ -107,6 +154,17 @@ def load_extension_option(fn): )(fn) +def functions_option(fn): + return click.option( + "--functions", + help=( + "Python code or a file path defining custom SQL functions; " + "can be used multiple times" + ), + multiple=True, + )(fn) + + @click.group( cls=DefaultGroup, default="query", @@ -119,10 +177,6 @@ def cli(): pass -if trogon is not None: - cli = trogon.tui()(cli) - - @cli.command() @click.argument( "path", @@ -165,6 +219,7 @@ def tables( table, fmt, json_cols, + ascii_, columns, schema, load_extension, @@ -178,6 +233,7 @@ def tables( sqlite-utils tables trees.db """ db = sqlite_utils.Database(path) + _register_db_for_cleanup(db) _load_extensions(db, load_extension) headers = ["view" if views else "table"] if counts: @@ -187,27 +243,35 @@ def tables( if schema: headers.append("schema") + method = db.view if views else db.table + def _iter(): if views: items = db.view_names() else: items = db.table_names(fts4=fts4, fts5=fts5) for name in items: - row = [name] + row: list[Any] = [name] if counts: - row.append(db[name].count) + row.append(method(name).count) if columns: - cols = [c.name for c in db[name].columns] + cols = [c.name for c in method(name).columns] if csv: row.append("\n".join(cols)) else: row.append(cols) if schema: - row.append(db[name].schema) + row.append(method(name).schema) yield row if table or fmt: - print(tabulate.tabulate(_iter(), headers=headers, tablefmt=fmt or "simple")) + print( + tabulate.tabulate( + _iter(), + headers=() if no_headers else headers, + tablefmt=fmt or "simple", + ) + ) elif csv or tsv: writer = csv_std.writer(sys.stdout, dialect="excel-tab" if tsv else "excel") if not no_headers: @@ -215,7 +279,7 @@ def tables( for row in _iter(): writer.writerow(row) else: - for line in output_rows(_iter(), headers, nl, arrays, json_cols): + for line in output_rows(_iter(), headers, nl, arrays, json_cols, ascii_): click.echo(line) @@ -253,6 +317,7 @@ def views( table, fmt, json_cols, + ascii_, columns, schema, load_extension, @@ -264,6 +329,7 @@ def views( \b sqlite-utils views trees.db """ + assert tables.callback is not None tables.callback( path=path, fts4=False, @@ -277,6 +343,7 @@ def views( table=table, fmt=fmt, json_cols=json_cols, + ascii_=ascii_, columns=columns, schema=schema, load_extension=load_extension, @@ -302,12 +369,13 @@ def optimize(path, tables, no_vacuum, load_extension): sqlite-utils optimize chickens.db """ db = sqlite_utils.Database(path) + _register_db_for_cleanup(db) _load_extensions(db, load_extension) if not tables: tables = db.table_names(fts4=True) + db.table_names(fts5=True) with db.conn: for table in tables: - db[table].optimize() + db.table(table).optimize() if not no_vacuum: db.vacuum() @@ -329,12 +397,13 @@ def rebuild_fts(path, tables, load_extension): sqlite-utils rebuild-fts chickens.db chickens """ db = sqlite_utils.Database(path) + _register_db_for_cleanup(db) _load_extensions(db, load_extension) if not tables: tables = db.table_names(fts4=True) + db.table_names(fts5=True) with db.conn: for table in tables: - db[table].rebuild_fts() + db.table(table).rebuild_fts() @cli.command() @@ -353,6 +422,7 @@ def analyze(path, names): sqlite-utils analyze chickens.db """ db = sqlite_utils.Database(path) + _register_db_for_cleanup(db) try: if names: for name in names: @@ -360,7 +430,7 @@ def analyze(path, names): else: db.analyze() except OperationalError as e: - raise click.ClickException(e) + raise click.ClickException(str(e)) @cli.command() @@ -377,7 +447,9 @@ def vacuum(path): \b sqlite-utils vacuum chickens.db """ - sqlite_utils.Database(path).vacuum() + db = sqlite_utils.Database(path) + _register_db_for_cleanup(db) + db.vacuum() @cli.command() @@ -396,6 +468,7 @@ def dump(path, load_extension): sqlite-utils dump chickens.db """ db = sqlite_utils.Database(path) + _register_db_for_cleanup(db) _load_extensions(db, load_extension) for line in db.iterdump(): click.echo(line) @@ -412,7 +485,8 @@ def dump(path, load_extension): @click.argument( "col_type", type=click.Choice( - ["integer", "float", "blob", "text", "INTEGER", "FLOAT", "BLOB", "TEXT"] + ["integer", "int", "float", "real", "text", "str", "blob", "bytes"], + case_sensitive=False, ), required=False, ) @@ -456,9 +530,10 @@ def add_column( sqlite-utils add-column chickens.db chickens weight float """ db = sqlite_utils.Database(path) + _register_db_for_cleanup(db) _load_extensions(db, load_extension) try: - db[table].add_column( + db.table(table).add_column( col_name, col_type, fk=fk, fk_col=fk_col, not_null_default=not_null_default ) except OperationalError as ex: @@ -493,11 +568,14 @@ def add_foreign_key( sqlite-utils add-foreign-key my.db books author_id authors id """ db = sqlite_utils.Database(path) + _register_db_for_cleanup(db) _load_extensions(db, load_extension) try: - db[table].add_foreign_key(column, other_table, other_column, ignore=ignore) + db.table(table).add_foreign_key( + column, other_table, other_column, ignore=ignore + ) except AlterError as e: - raise click.ClickException(e) + raise click.ClickException(str(e)) @cli.command(name="add-foreign-keys") @@ -520,6 +598,7 @@ def add_foreign_keys(path, foreign_key, load_extension): authors country_id countries id """ db = sqlite_utils.Database(path) + _register_db_for_cleanup(db) _load_extensions(db, load_extension) if len(foreign_key) % 4 != 0: raise click.ClickException( @@ -531,7 +610,7 @@ def add_foreign_keys(path, foreign_key, load_extension): try: db.add_foreign_keys(tuples) except AlterError as e: - raise click.ClickException(e) + raise click.ClickException(str(e)) @cli.command(name="index-foreign-keys") @@ -551,6 +630,7 @@ def index_foreign_keys(path, load_extension): sqlite-utils index-foreign-keys chickens.db """ db = sqlite_utils.Database(path) + _register_db_for_cleanup(db) _load_extensions(db, load_extension) db.index_foreign_keys() @@ -595,6 +675,7 @@ def create_index( sqlite-utils create-index chickens.db chickens -- -name """ db = sqlite_utils.Database(path) + _register_db_for_cleanup(db) _load_extensions(db, load_extension) # Treat -prefix as descending for columns columns = [] @@ -602,7 +683,7 @@ def create_index( if col.startswith("-"): col = DescIndex(col[1:]) columns.append(col) - db[table].create_index( + db.table(table).create_index( columns, index_name=name, unique=unique, @@ -611,6 +692,34 @@ def create_index( ) +@cli.command(name="drop-index") +@click.argument( + "path", + type=click.Path(exists=True, file_okay=True, dir_okay=False, allow_dash=False), + required=True, +) +@click.argument("table") +@click.argument("index") +@click.option("--ignore", help="Ignore if index does not exist", is_flag=True) +@load_extension_option +def drop_index(path, table, index, ignore, load_extension): + """ + Drop an index by index name from the specified table + + Example: + + \b + sqlite-utils drop-index chickens.db chickens idx_chickens_name + """ + db = sqlite_utils.Database(path) + _register_db_for_cleanup(db) + _load_extensions(db, load_extension) + try: + db.table(table).drop_index(index, ignore=ignore) + except OperationalError as ex: + raise click.ClickException(str(ex)) + + @cli.command(name="enable-fts") @click.argument( "path", @@ -637,7 +746,7 @@ def create_index( def enable_fts( path, table, column, fts4, fts5, tokenize, create_triggers, replace, load_extension ): - """Enable full-text search for specific table and columns" + """Enable full-text search for specific table and columns Example: @@ -652,17 +761,18 @@ def enable_fts( fts_version = "FTS4" db = sqlite_utils.Database(path) + _register_db_for_cleanup(db) _load_extensions(db, load_extension) try: - db[table].enable_fts( + db.table(table).enable_fts( column, fts_version=fts_version, tokenize=tokenize, create_triggers=create_triggers, replace=replace, ) - except OperationalError as ex: - raise click.ClickException(ex) + except (NoTable, OperationalError) as ex: + raise click.ClickException(str(ex)) @cli.command(name="populate-fts") @@ -683,8 +793,9 @@ def populate_fts(path, table, column, load_extension): sqlite-utils populate-fts chickens.db chickens name """ db = sqlite_utils.Database(path) + _register_db_for_cleanup(db) _load_extensions(db, load_extension) - db[table].populate_fts(column) + db.table(table).populate_fts(column) @cli.command(name="disable-fts") @@ -704,8 +815,9 @@ def disable_fts(path, table, load_extension): sqlite-utils disable-fts chickens.db chickens """ db = sqlite_utils.Database(path) + _register_db_for_cleanup(db) _load_extensions(db, load_extension) - db[table].disable_fts() + db.table(table).disable_fts() @cli.command(name="enable-wal") @@ -726,6 +838,7 @@ def enable_wal(path, load_extension): """ for path_ in path: db = sqlite_utils.Database(path_) + _register_db_for_cleanup(db) _load_extensions(db, load_extension) db.enable_wal() @@ -748,6 +861,7 @@ def disable_wal(path, load_extension): """ for path_ in path: db = sqlite_utils.Database(path_) + _register_db_for_cleanup(db) _load_extensions(db, load_extension) db.disable_wal() @@ -769,6 +883,7 @@ def enable_counts(path, tables, load_extension): sqlite-utils enable-counts chickens.db """ db = sqlite_utils.Database(path) + _register_db_for_cleanup(db) _load_extensions(db, load_extension) if not tables: db.enable_counts() @@ -778,7 +893,7 @@ def enable_counts(path, tables, load_extension): if bad_tables: raise click.ClickException("Invalid tables: {}".format(bad_tables)) for table in tables: - db[table].enable_counts() + db.table(table).enable_counts() @cli.command(name="reset-counts") @@ -797,6 +912,7 @@ def reset_counts(path, load_extension): sqlite-utils reset-counts chickens.db """ db = sqlite_utils.Database(path) + _register_db_for_cleanup(db) _load_extensions(db, load_extension) db.reset_counts() @@ -856,13 +972,19 @@ def insert_upsert_options(*, require_pk=False): required=True, ), click.argument("table"), - click.argument("file", type=click.File("rb"), required=True), + click.argument( + "file", type=click.File("rb", lazy=True), required=False + ), click.option( "--pk", help="Columns to use as the primary key, e.g. id", multiple=True, required=require_pk, ), + click.option( + "--code", + help="Python code defining a rows() function or iterable of rows to insert", + ), ) + _import_options + ( @@ -887,11 +1009,19 @@ def insert_upsert_options(*, require_pk=False): help="Default value that should be set for a column", ), click.option( - "-d", - "--detect-types", + "--type", + "types", + type=( + str, + click.Choice(list(VALID_COLUMN_TYPES), case_sensitive=False), + ), + multiple=True, + help="Column types to use when creating the table", + ), + click.option( + "--no-detect-types", is_flag=True, - envvar="SQLITE_UTILS_DETECT_TYPES", - help="Detect types for columns in CSV/TSV data", + help="Treat all CSV/TSV columns as TEXT", ), click.option( "--analyze", @@ -900,6 +1030,12 @@ def insert_upsert_options(*, require_pk=False): ), load_extension_option, click.option("--silent", is_flag=True, help="Do not show progress bar"), + click.option( + "--strict", + is_flag=True, + default=False, + help="Apply STRICT mode to created table", + ), ) ): fn = decorator(fn) @@ -936,17 +1072,131 @@ def insert_upsert_implementation( truncate=False, not_null=None, default=None, - detect_types=None, + types=None, + no_detect_types=False, analyze=False, load_extension=None, silent=False, bulk_sql=None, functions=None, + strict=False, + code=None, ): db = sqlite_utils.Database(path) + _register_db_for_cleanup(db) _load_extensions(db, load_extension) - if functions: - _register_functions(db, functions) + _maybe_register_functions(db, functions) + column_type_overrides = {column: ctype.upper() for column, ctype in (types or [])} + + def _insert_docs(docs, tracker=None): + extra_kwargs = { + "ignore": ignore, + "replace": replace, + "truncate": truncate, + "analyze": analyze, + "strict": strict, + } + if not_null: + extra_kwargs["not_null"] = set(not_null) + if default: + extra_kwargs["defaults"] = dict(default) + if column_type_overrides: + extra_kwargs["columns"] = column_type_overrides + if upsert: + extra_kwargs["upsert"] = upsert + + # docs should all be dictionaries + docs = (verify_is_dict(doc) for doc in docs) + + # Apply {"$base64": true, ...} decoding, if needed + docs = (decode_base64_values(doc) for doc in docs) + + # For bulk_sql= we use cursor.executemany() instead + if bulk_sql: + if batch_size: + doc_chunks = chunks(docs, batch_size) + else: + doc_chunks = [docs] + for doc_chunk in doc_chunks: + with db.atomic(): + db.conn.cursor().executemany(bulk_sql, doc_chunk) + return + + # table_names() rather than db.table(), which raises NoTable for + # views before the error handling below can deal with them + table_existed_before_insert = table in db.table_names() + try: + db.table(table).insert_all( + docs, pk=pk, batch_size=batch_size, alter=alter, **extra_kwargs + ) + except (NoTable, InvalidColumns, PrimaryKeyRequired) as e: + raise click.ClickException(str(e)) + except Exception as e: + if ( + isinstance(e, OperationalError) + and e.args + and ( + "has no column named" in e.args[0] or "no such column" in e.args[0] + ) + ): + raise click.ClickException( + "{}\n\nTry using --alter to add additional columns".format( + e.args[0] + ) + ) + # If we can find sql= and parameters= arguments, show those + variables = _find_variables(e.__traceback__, ["sql", "parameters"]) + if "sql" in variables and "parameters" in variables: + raise click.ClickException( + "{}\n\nsql = {}\nparameters = {}".format( + str(e), variables["sql"], variables["parameters"] + ) + ) + else: + raise + # Apply detected types only to a table this command created - + # transforming a pre-existing table would rewrite its column types + # and corrupt values such as TEXT zip codes with leading zeros + if ( + tracker is not None + and not table_existed_before_insert + and db.table(table).exists() + ): + detected_types = tracker.types + detected_types.update(column_type_overrides) + db.table(table).transform(types=detected_types) + + if code is not None: + if file is not None: + raise click.ClickException("--code cannot be used with a FILE argument") + if any( + [ + flatten, + nl, + csv, + tsv, + empty_null, + lines, + text, + convert, + sniff, + no_headers, + delimiter, + quotechar, + encoding, + ] + ): + raise click.ClickException( + "--code cannot be used with input format options" + ) + _insert_docs(_rows_from_code(code)) + return + + if file is None: + raise click.ClickException( + "Provide either a FILE argument or --code to specify rows to insert" + ) + if (delimiter or quotechar or sniff or no_headers) and not tsv: csv = True if (nl + csv + tsv) >= 2: @@ -975,18 +1225,19 @@ def insert_upsert_implementation( if csv or tsv: if sniff: # Read first 2048 bytes and use that to detect + assert sniff_buffer is not None first_bytes = sniff_buffer.peek(2048) dialect = csv_std.Sniffer().sniff( first_bytes.decode(encoding, "ignore") ) else: dialect = "excel-tab" if tsv else "excel" - csv_reader_args = {"dialect": dialect} + csv_reader_args: dict[str, Any] = {"dialect": dialect} if delimiter: csv_reader_args["delimiter"] = delimiter if quotechar: csv_reader_args["quotechar"] = quotechar - reader = csv_std.reader(decoded, **csv_reader_args) + reader = csv_std.reader(decoded, **csv_reader_args) # type: ignore first_row = next(reader) if no_headers: headers = ["untitled_{}".format(i + 1) for i in range(len(first_row))] @@ -1000,7 +1251,8 @@ def insert_upsert_implementation( ) else: docs = (dict(zip(headers, row)) for row in reader) - if detect_types: + # Type detection is the default, unless --no-detect-types is passed + if not no_detect_types: tracker = TypeTracker() docs = tracker.wrap(docs) elif lines: @@ -1052,63 +1304,7 @@ def insert_upsert_implementation( else: docs = (fn(doc) or doc for doc in docs) - extra_kwargs = { - "ignore": ignore, - "replace": replace, - "truncate": truncate, - "analyze": analyze, - } - if not_null: - extra_kwargs["not_null"] = set(not_null) - if default: - extra_kwargs["defaults"] = dict(default) - if upsert: - extra_kwargs["upsert"] = upsert - - # docs should all be dictionaries - docs = (verify_is_dict(doc) for doc in docs) - - # Apply {"$base64": true, ...} decoding, if needed - docs = (decode_base64_values(doc) for doc in docs) - - # For bulk_sql= we use cursor.executemany() instead - if bulk_sql: - if batch_size: - doc_chunks = chunks(docs, batch_size) - else: - doc_chunks = [docs] - for doc_chunk in doc_chunks: - with db.conn: - db.conn.cursor().executemany(bulk_sql, doc_chunk) - return - - try: - db[table].insert_all( - docs, pk=pk, batch_size=batch_size, alter=alter, **extra_kwargs - ) - except Exception as e: - if ( - isinstance(e, OperationalError) - and e.args - and "has no column named" in e.args[0] - ): - raise click.ClickException( - "{}\n\nTry using --alter to add additional columns".format( - e.args[0] - ) - ) - # If we can find sql= and parameters= arguments, show those - variables = _find_variables(e.__traceback__, ["sql", "parameters"]) - if "sql" in variables and "parameters" in variables: - raise click.ClickException( - "{}\n\nsql = {}\nparameters = {}".format( - str(e), variables["sql"], variables["parameters"] - ) - ) - else: - raise - if tracker is not None: - db[table].transform(types=tracker.types) + _insert_docs(docs, tracker=tracker) # Clean up open file-like objects if sniff_buffer: @@ -1151,6 +1347,7 @@ def insert( table, file, pk, + code, flatten, nl, csv, @@ -1168,7 +1365,7 @@ def insert( batch_size, stop_after, alter, - detect_types, + no_detect_types, analyze, load_extension, silent, @@ -1177,6 +1374,8 @@ def insert( truncate, not_null, default, + types, + strict, ): """ Insert records from FILE into a table, creating the table if it @@ -1194,6 +1393,9 @@ def insert( - 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. @@ -1221,6 +1423,17 @@ def insert( \b 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: + + \b + sqlite-utils insert data.db creatures --code ' + def rows(): + yield {"id": 1, "name": "Cleo"} + yield {"id": 2, "name": "Suna"} + ' --pk id """ try: insert_upsert_implementation( @@ -1249,24 +1462,28 @@ def insert( ignore=ignore, replace=replace, truncate=truncate, - detect_types=detect_types, + no_detect_types=no_detect_types, analyze=analyze, load_extension=load_extension, silent=silent, not_null=not_null, default=default, + types=types, + strict=strict, + code=code, ) except UnicodeDecodeError as ex: raise click.ClickException(UNICODE_ERROR.format(ex)) @cli.command() -@insert_upsert_options(require_pk=True) +@insert_upsert_options() def upsert( path, table, file, pk, + code, flatten, nl, csv, @@ -1286,16 +1503,23 @@ def upsert( alter, not_null, default, - detect_types, + types, + no_detect_types, analyze, load_extension, silent, + strict, ): """ 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: \b @@ -1330,10 +1554,13 @@ def upsert( upsert=True, not_null=not_null, default=default, - detect_types=detect_types, + types=types, + no_detect_types=no_detect_types, analyze=analyze, load_extension=load_extension, silent=silent, + strict=strict, + code=code, ) except UnicodeDecodeError as ex: raise click.ClickException(UNICODE_ERROR.format(ex)) @@ -1348,9 +1575,7 @@ def upsert( @click.argument("sql") @click.argument("file", type=click.File("rb"), required=True) @click.option("--batch-size", type=int, default=100, help="Commit every X records") -@click.option( - "--functions", help="Python code defining one or more custom SQL functions" -) +@functions_option @import_options @load_extension_option def bulk( @@ -1414,7 +1639,7 @@ def bulk( upsert=False, not_null=set(), default={}, - detect_types=False, + no_detect_types=True, load_extension=load_extension, silent=False, bulk_sql=sql, @@ -1446,6 +1671,7 @@ def create_database(path, enable_wal, init_spatialite, load_extension): sqlite-utils create-database trees.db """ db = sqlite_utils.Database(path) + _register_db_for_cleanup(db) if enable_wal: db.enable_wal() @@ -1468,7 +1694,7 @@ def create_database(path, enable_wal, init_spatialite, load_extension): ) @click.argument("table") @click.argument("columns", nargs=-1, required=True) -@click.option("--pk", help="Column to use as primary key") +@click.option("pks", "--pk", help="Column to use as primary key", multiple=True) @click.option( "--not-null", multiple=True, @@ -1502,11 +1728,16 @@ def create_database(path, enable_wal, init_spatialite, load_extension): help="If table already exists, try to transform the schema", ) @load_extension_option +@click.option( + "--strict", + is_flag=True, + help="Apply STRICT mode to created table", +) def create_table( path, table, columns, - pk, + pks, not_null, default, fk, @@ -1514,6 +1745,7 @@ def create_table( replace, transform, load_extension, + strict, ): """ Add a table with the specified columns. Columns should be specified using @@ -1523,12 +1755,13 @@ def create_table( sqlite-utils create-table my.db people \\ id integer \\ name text \\ - height float \\ + height real \\ photo blob --pk id - Valid column types are text, integer, float and blob. + Valid column types are text, integer, real, float and blob. """ db = sqlite_utils.Database(path) + _register_db_for_cleanup(db) _load_extensions(db, load_extension) if len(columns) % 2 == 1: raise click.ClickException( @@ -1552,15 +1785,16 @@ def create_table( table ) ) - db[table].create( + db.table(table).create( coltypes, - pk=pk, + pk=pks[0] if len(pks) == 1 else pks, not_null=not_null, defaults=dict(default), foreign_keys=fk, ignore=ignore, replace=replace, transform=transform, + strict=strict, ) @@ -1579,9 +1813,10 @@ def duplicate(path, table, new_table, ignore, load_extension): Create a duplicate of this table, copying across the schema and all row data. """ db = sqlite_utils.Database(path) + _register_db_for_cleanup(db) _load_extensions(db, load_extension) try: - db[table].duplicate(new_table) + db.table(table).duplicate(new_table) except NoTable: if not ignore: raise click.ClickException('Table "{}" does not exist'.format(table)) @@ -1602,6 +1837,7 @@ def rename_table(path, table, new_name, ignore, load_extension): Rename this table. """ db = sqlite_utils.Database(path) + _register_db_for_cleanup(db) _load_extensions(db, load_extension) try: db.rename_table(table, new_name) @@ -1630,9 +1866,16 @@ def drop_table(path, table, ignore, load_extension): sqlite-utils drop-table chickens.db chickens """ db = sqlite_utils.Database(path) + _register_db_for_cleanup(db) _load_extensions(db, load_extension) try: - db[table].drop(ignore=ignore) + db.table(table).drop(ignore=ignore) + except NoTable: + # A view exists with this name + if not ignore: + raise click.ClickException( + '"{}" is a view, not a table - use drop-view to drop it'.format(table) + ) except OperationalError: raise click.ClickException('Table "{}" does not exist'.format(table)) @@ -1666,13 +1909,14 @@ def create_view(path, view, select, ignore, replace, load_extension): 'select * from chickens where weight > 3' """ db = sqlite_utils.Database(path) + _register_db_for_cleanup(db) _load_extensions(db, load_extension) # Does view already exist? if view in db.view_names(): if ignore: return elif replace: - db[view].drop() + db.view(view).drop() else: raise click.ClickException( 'View "{}" already exists. Use --replace to delete and replace it.'.format( @@ -1700,10 +1944,17 @@ def drop_view(path, view, ignore, load_extension): sqlite-utils drop-view chickens.db heavy_chickens """ db = sqlite_utils.Database(path) + _register_db_for_cleanup(db) _load_extensions(db, load_extension) try: - db[view].drop(ignore=ignore) - except OperationalError: + db.view(view).drop(ignore=ignore) + except NoView: + if ignore: + return + if view in db.table_names(): + raise click.ClickException( + '"{}" is a table, not a view - use drop-table to drop it'.format(view) + ) raise click.ClickException('View "{}" does not exist'.format(view)) @@ -1730,9 +1981,7 @@ def drop_view(path, view, ignore, load_extension): type=(str, str), help="Named :parameters for SQL query", ) -@click.option( - "--functions", help="Python code defining one or more custom SQL functions" -) +@functions_option @load_extension_option def query( path, @@ -1746,6 +1995,7 @@ def query( table, fmt, json_cols, + ascii_, raw, raw_lines, param, @@ -1760,15 +2010,23 @@ def query( sqlite-utils data.db \\ "select * from chickens where age > :age" \\ -p age 1 + + Pass "-" as the SQL to read the query from standard input: + + \b + echo "select * from chickens" | sqlite-utils data.db - """ + if sql == "-": + # Read SQL from standard input + sql = sys.stdin.read() db = sqlite_utils.Database(path) + _register_db_for_cleanup(db) for alias, attach_path in attach: db.attach(alias, attach_path) _load_extensions(db, load_extension) db.register_fts4_bm25() - if functions: - _register_functions(db, functions) + _maybe_register_functions(db, functions) _execute_query( db, @@ -1784,6 +2042,7 @@ def query( nl, arrays, json_cols, + ascii_, ) @@ -1795,9 +2054,7 @@ def query( nargs=-1, ) @click.argument("sql") -@click.option( - "--functions", help="Python code defining one or more custom SQL functions" -) +@functions_option @click.option( "--attach", type=(str, click.Path(file_okay=True, dir_okay=False, allow_dash=False)), @@ -1856,6 +2113,7 @@ def memory( table, fmt, json_cols, + ascii_, raw, raw_lines, param, @@ -1866,6 +2124,7 @@ def memory( save, analyze, load_extension, + return_db=False, ): """Execute SQL query against an in-memory database, optionally populated by imported data @@ -1894,6 +2153,9 @@ def memory( sqlite-utils memory animals.csv --schema """ db = sqlite_utils.Database(memory=True) + if not return_db: + _register_db_for_cleanup(db) + # If --dump or --save or --analyze used but no paths detected, assume SQL query is a path: if (dump or save or schema or analyze) and not paths: paths = [sql] @@ -1902,6 +2164,7 @@ def memory( for i, path in enumerate(paths): # Path may have a :format suffix fp = None + should_close_fp = False if ":" in path and path.rsplit(":", 1)[-1].upper() in Format.__members__: path, suffix = path.rsplit(":", 1) format = Format[suffix.upper()] @@ -1919,25 +2182,32 @@ def memory( file_table = stem stem_counts[stem] = stem_counts.get(stem, 1) + 1 fp = file_path.open("rb") - rows, format_used = rows_from_file(fp, format=format, encoding=encoding) - tracker = None - if format_used in (Format.CSV, Format.TSV) and not no_detect_types: - tracker = TypeTracker() - rows = tracker.wrap(rows) - if flatten: - rows = (_flatten(row) for row in rows) - db[file_table].insert_all(rows, alter=True) - if tracker is not None: - db[file_table].transform(types=tracker.types) - # Add convenient t / t1 / t2 views - view_names = ["t{}".format(i + 1)] - if i == 0: - view_names.append("t") - for view_name in view_names: - if not db[view_name].exists(): - db.create_view(view_name, "select * from [{}]".format(file_table)) - if fp: - fp.close() + should_close_fp = True + try: + rows, format_used = rows_from_file(fp, format=format, encoding=encoding) + tracker = None + if format_used in (Format.CSV, Format.TSV) and not no_detect_types: + tracker = TypeTracker() + rows = tracker.wrap(rows) + if flatten: + rows = (_flatten(row) for row in rows) + + db.table(file_table).insert_all(rows, alter=True) + if tracker is not None and db.table(file_table).exists(): + db.table(file_table).transform(types=tracker.types) + # Add convenient t / t1 / t2 views + view_names = ["t{}".format(i + 1)] + if i == 0: + view_names.append("t") + for view_name in view_names: + if not db[view_name].exists(): + db.create_view( + view_name, + "select * from {}".format(quote_identifier(file_table)), + ) + finally: + if should_close_fp and fp: + fp.close() if analyze: _analyze(db, tables=None, columns=None, save=False) @@ -1954,6 +2224,7 @@ def memory( if save: db2 = sqlite_utils.Database(save) + _register_db_for_cleanup(db2) for line in db.iterdump(): db2.execute(line) return @@ -1963,8 +2234,10 @@ def memory( _load_extensions(db, load_extension) db.register_fts4_bm25() - if functions: - _register_functions(db, functions) + _maybe_register_functions(db, functions) + + if return_db: + return db _execute_query( db, @@ -1980,6 +2253,7 @@ def memory( nl, arrays, json_cols, + ascii_, ) @@ -1997,6 +2271,7 @@ def _execute_query( nl, arrays, json_cols, + ascii_, ): with db.conn: try: @@ -2009,8 +2284,10 @@ def _execute_query( cursor = [[cursor.rowcount]] else: headers = [c[0] for c in cursor.description] + cursor_or_rows: Any = cursor if raw: - data = cursor.fetchone()[0] + row = cursor_or_rows.fetchone() + data = row[0] if row else None if isinstance(data, bytes): sys.stdout.buffer.write(data) else: @@ -2025,7 +2302,9 @@ def _execute_query( elif fmt or table: print( tabulate.tabulate( - list(cursor), headers=headers, tablefmt=fmt or "simple" + list(cursor), + headers=() if no_headers else headers, + tablefmt=fmt or "simple", ) ) elif csv or tsv: @@ -2035,7 +2314,7 @@ def _execute_query( for row in cursor: writer.writerow(row) else: - for line in output_rows(cursor, headers, nl, arrays, json_cols): + for line in output_rows(cursor, headers, nl, arrays, json_cols, ascii_): click.echo(line) @@ -2079,6 +2358,7 @@ def search( table, fmt, json_cols, + ascii_, load_extension, ): """Execute a full-text search against this table @@ -2088,9 +2368,10 @@ def search( sqlite-utils search data.db chickens lila """ db = sqlite_utils.Database(path) + _register_db_for_cleanup(db) _load_extensions(db, load_extension) # Check table exists - table_obj = db[dbtable] + table_obj = db.table(dbtable) if not table_obj.exists(): raise click.ClickException("Table '{}' does not exist".format(dbtable)) if not table_obj.detect_fts(): @@ -2124,6 +2405,7 @@ def search( table=table, fmt=fmt, json_cols=json_cols, + ascii_=ascii_, param=[("query", q)], load_extension=load_extension, ) @@ -2184,6 +2466,7 @@ def rows( table, fmt, json_cols, + ascii_, load_extension, ): """Output all rows in the specified table @@ -2195,8 +2478,8 @@ def rows( """ columns = "*" if column: - columns = ", ".join("[{}]".format(c) for c in column) - sql = "select {} from [{}]".format(columns, dbtable) + columns = ", ".join(quote_identifier(c) for c in column) + sql = "select {} from {}".format(columns, quote_identifier(dbtable)) if where: sql += " where " + where if order: @@ -2218,6 +2501,7 @@ def rows( fmt=fmt, param=param, json_cols=json_cols, + ascii_=ascii_, load_extension=load_extension, ) @@ -2244,6 +2528,7 @@ def triggers( table, fmt, json_cols, + ascii_, load_extension, ): """Show triggers configured in this database @@ -2253,10 +2538,12 @@ def triggers( \b sqlite-utils triggers trees.db """ - sql = "select name, tbl_name as [table], sql from sqlite_master where type = 'trigger'" + sql = "select name, tbl_name as \"table\", sql from sqlite_master where type = 'trigger'" if tables: - quote = sqlite_utils.Database(memory=True).quote - sql += " and [table] in ({})".format( + _quote_db = sqlite_utils.Database(memory=True) + _register_db_for_cleanup(_quote_db) + quote = _quote_db.quote + sql += ' and "table" in ({})'.format( ", ".join(quote(table) for table in tables) ) ctx.invoke( @@ -2271,6 +2558,7 @@ def triggers( table=table, fmt=fmt, json_cols=json_cols, + ascii_=ascii_, load_extension=load_extension, ) @@ -2299,6 +2587,7 @@ def indexes( table, fmt, json_cols, + ascii_, load_extension, ): """Show indexes for the whole database or specific tables @@ -2320,7 +2609,9 @@ def indexes( sqlite_master.type = 'table' """ if tables: - quote = sqlite_utils.Database(memory=True).quote + _quote_db = sqlite_utils.Database(memory=True) + _register_db_for_cleanup(_quote_db) + quote = _quote_db.quote sql += " and sqlite_master.name in ({})".format( ", ".join(quote(table) for table in tables) ) @@ -2338,6 +2629,7 @@ def indexes( table=table, fmt=fmt, json_cols=json_cols, + ascii_=ascii_, load_extension=load_extension, ) @@ -2363,6 +2655,7 @@ def schema( sqlite-utils schema trees.db """ db = sqlite_utils.Database(path) + _register_db_for_cleanup(db) _load_extensions(db, load_extension) if tables: for table in tables: @@ -2382,10 +2675,12 @@ def schema( "--type", type=( str, - click.Choice(["INTEGER", "TEXT", "FLOAT", "BLOB"], case_sensitive=False), + click.Choice( + ["INTEGER", "TEXT", "FLOAT", "REAL", "BLOB"], case_sensitive=False + ), ), multiple=True, - help="Change column type to INTEGER, TEXT, FLOAT or BLOB", + help="Change column type to INTEGER, TEXT, FLOAT, REAL or BLOB", ) @click.option("--drop", type=str, multiple=True, help="Drop this column") @click.option( @@ -2423,6 +2718,11 @@ def schema( multiple=True, help="Drop foreign key constraint for this column", ) +@click.option( + "--strict/--no-strict", + default=None, + help="Enable or disable STRICT mode (default: preserve current mode)", +) @click.option("--sql", is_flag=True, help="Output SQL without executing it") @load_extension_option def transform( @@ -2440,6 +2740,7 @@ def transform( default_none, add_foreign_keys, drop_foreign_keys, + strict, sql, load_extension, ): @@ -2453,9 +2754,9 @@ def transform( --rename column2 column_renamed """ db = sqlite_utils.Database(path) + _register_db_for_cleanup(db) _load_extensions(db, load_extension) types = {} - kwargs = {} for column, ctype in type: if ctype.upper() not in VALID_COLUMN_TYPES: raise click.ClickException( @@ -2475,29 +2776,48 @@ def transform( for column in default_none: default_dict[column] = None - kwargs["types"] = types - kwargs["drop"] = set(drop) - kwargs["rename"] = dict(rename) - kwargs["column_order"] = column_order or None - kwargs["not_null"] = not_null_dict + drop_set = set(drop) + rename_dict = dict(rename) + column_order_list = list(column_order) or None + drop_foreign_keys_value = drop_foreign_keys or None + add_foreign_keys_value = add_foreign_keys or None + pk_value = DEFAULT if pk: if len(pk) == 1: - kwargs["pk"] = pk[0] + pk_value = pk[0] else: - kwargs["pk"] = pk + pk_value = pk elif pk_none: - kwargs["pk"] = None - kwargs["defaults"] = default_dict - if drop_foreign_keys: - kwargs["drop_foreign_keys"] = drop_foreign_keys - if add_foreign_keys: - kwargs["add_foreign_keys"] = add_foreign_keys + pk_value = None + table_obj = db.table(table) if sql: - for line in db[table].transform_sql(**kwargs): + for line in table_obj.transform_sql( + types=types, + drop=drop_set, + rename=rename_dict, + column_order=column_order_list, + not_null=not_null_dict, + pk=pk_value, + defaults=default_dict, + drop_foreign_keys=drop_foreign_keys_value, + add_foreign_keys=add_foreign_keys_value, + strict=strict, + ): click.echo(line) else: - db[table].transform(**kwargs) + table_obj.transform( + types=types, + drop=drop_set, + rename=rename_dict, + column_order=column_order_list, + not_null=not_null_dict, + pk=pk_value, + defaults=default_dict, + drop_foreign_keys=drop_foreign_keys_value, + add_foreign_keys=add_foreign_keys_value, + strict=strict, + ) @cli.command() @@ -2536,14 +2856,18 @@ def extract( sqlite-utils extract trees.db Street_Trees species """ db = sqlite_utils.Database(path) + _register_db_for_cleanup(db) _load_extensions(db, load_extension) - kwargs = dict( + kwargs: dict[str, Any] = dict( columns=columns, table=other_table, fk_column=fk_column, rename=dict(rename), ) - db[table].extract(**kwargs) + try: + db.table(table).extract(**kwargs) + except (NoTable, InvalidColumns) as e: + raise click.ClickException(str(e)) @cli.command(name="insert-files") @@ -2566,7 +2890,7 @@ def extract( multiple=True, help="Column definitions for the table", ) -@click.option("--pk", type=str, help="Column to use as primary key") +@click.option("pks", "--pk", help="Column to use as primary key", multiple=True) @click.option("--alter", is_flag=True, help="Alter table to add missing columns") @click.option("--replace", is_flag=True, help="Replace files with matching primary key") @click.option("--upsert", is_flag=True, help="Upsert files with matching primary key") @@ -2583,7 +2907,7 @@ def insert_files( table, file_or_dir, column, - pk, + pks, alter, replace, upsert, @@ -2613,8 +2937,8 @@ def insert_files( column = ["path:path", "content_text:content_text", "size:size"] else: column = ["path:path", "content:content", "size:size"] - if not pk: - pk = "path" + if not pks: + pks = ["path"] def yield_paths_and_relative_paths(): for f_or_d in file_or_dir: @@ -2680,11 +3004,16 @@ def insert_files( yield row db = sqlite_utils.Database(path) + _register_db_for_cleanup(db) _load_extensions(db, load_extension) try: with db.conn: - db[table].insert_all( - to_insert(), pk=pk, alter=alter, replace=replace, upsert=upsert + db.table(table).insert_all( + to_insert(), + pk=pks[0] if len(pks) == 1 else pks, + alter=alter, + replace=replace, + upsert=upsert, ) except UnicodeDecodeErrorForPath as e: raise click.ClickException( @@ -2734,6 +3063,7 @@ def analyze_tables( sqlite-utils analyze-tables data.db trees """ db = sqlite_utils.Database(path) + _register_db_for_cleanup(db) _load_extensions(db, load_extension) _analyze(db, tables, columns, save, common_limit, no_most, no_least) @@ -2781,8 +3111,7 @@ def _analyze(db, tables, columns, save, common_limit=10, no_most=False, no_least ) details = ( ( - textwrap.dedent( - """ + textwrap.dedent(""" {table}.{column}: ({i}/{total}) Total rows: {total_rows} @@ -2790,8 +3119,7 @@ def _analyze(db, tables, columns, save, common_limit=10, no_most=False, no_least Blank rows: {num_blank} Distinct values: {num_distinct}{most_common_rendered}{least_common_rendered} - """ - ) + """) .strip() .format( i=i + 1, @@ -2838,44 +3166,45 @@ def uninstall(packages, yes): def _generate_convert_help(): - help = textwrap.dedent( - """ + help = textwrap.dedent(""" Convert columns using Python code you supply. For example: \b - sqlite-utils convert my.db mytable mycolumn \\ - '"\\n".join(textwrap.wrap(value, 10))' \\ - --import=textwrap + sqlite-utils convert my.db mytable mycolumn \\ + '"\\n".join(textwrap.wrap(value, 10))' \\ + --import=textwrap "value" is a variable with the column value to be converted. + CODE can also be a reference to a callable that takes the value, for example: + + \b + 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: - """ - ).strip() + """).strip() recipe_names = [ n for n in dir(recipes) if not n.startswith("_") - and n not in ("json", "parser") + and n not in ("json", "parser", "Callable", "Optional") and callable(getattr(recipes, n)) ] for name in recipe_names: fn = getattr(recipes, name) - help += "\n\nr.{}{}\n\n\b{}".format( - name, str(inspect.signature(fn)), fn.__doc__.rstrip() - ) + doc = textwrap.dedent(fn.__doc__.rstrip()).replace("\b\n", "") + help += "\n\nr.{}{}\n\n\b{}".format(name, str(inspect.signature(fn)), doc) help += "\n\n" - help += textwrap.dedent( - """ + help += textwrap.dedent(""" You can use these recipes like so: \b - sqlite-utils convert my.db mytable mycolumn \\ - 'r.jsonsplit(value, delimiter=":")' - """ - ).strip() + sqlite-utils convert my.db mytable mycolumn \\ + 'r.jsonsplit(value, delimiter=":")' + """).strip() return help @@ -2913,7 +3242,6 @@ def _generate_convert_help(): type=click.Choice(["integer", "float", "blob", "text"]), ) @click.option("--drop", is_flag=True, help="Drop original column afterwards") -@click.option("--no-skip-false", is_flag=True, help="Don't skip falsey values") @click.option("-s", "--silent", is_flag=True, help="Don't show a progress bar") @click.option("pdb_", "--pdb", is_flag=True, help="Open pdb debugger on first error") def convert( @@ -2929,12 +3257,12 @@ def convert( output, output_type, drop, - no_skip_false, silent, pdb_, ): sqlite3.enable_callback_tracebacks(True) db = sqlite_utils.Database(db_path) + _register_db_for_cleanup(db) if output is not None and len(columns) > 1: raise click.ClickException("Cannot use --output with more than one column") if multi and len(columns) > 1: @@ -2955,7 +3283,7 @@ def convert( if multi: def preview(v): - return json.dumps(fn(v), default=repr) if v else v + return json.dumps(fn(v), default=repr, ensure_ascii=False) if v else v else: @@ -2998,7 +3326,7 @@ def convert( fn = wrapped_fn try: - db[table].convert( + db.table(table).convert( columns, fn, where=where, @@ -3006,7 +3334,6 @@ def convert( output=output, output_type=output_type, drop=drop, - skip_false=not no_skip_false, multi=multi, show_progress=not silent, ) @@ -3032,14 +3359,14 @@ def convert( "geometry_type", type=click.Choice( [ - "POINT", - "LINESTRING", - "POLYGON", - "MULTIPOINT", - "MULTILINESTRING", - "MULTIPOLYGON", - "GEOMETRYCOLLECTION", - "GEOMETRY", + "point", + "linestring", + "polygon", + "multipoint", + "multilinestring", + "multipolygon", + "geometrycollection", + "geometry", ], case_sensitive=False, ), @@ -3078,6 +3405,7 @@ def add_geometry_column( By default, this command will try to load the SpatiaLite extension from usual paths. To load it from a specific path, use --load-extension.""" db = sqlite_utils.Database(db_path) + _register_db_for_cleanup(db) if not db[table].exists(): raise click.ClickException( "You must create a table before adding a geometry column" @@ -3088,7 +3416,7 @@ def add_geometry_column( _load_extensions(db, load_extension) db.init_spatialite() - if db[table].add_geometry_column( + if db.table(table).add_geometry_column( column_name, geometry_type, srid, coord_dimension, not_null ): click.echo(f"Added {geometry_type} column {column_name} to {table}") @@ -3110,6 +3438,7 @@ def create_spatial_index(db_path, table, column_name, load_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.""" db = sqlite_utils.Database(db_path) + _register_db_for_cleanup(db) if not db[table].exists(): raise click.ClickException( "You must create a table and add a geometry column before creating a spatial index" @@ -3125,16 +3454,197 @@ def create_spatial_index(db_path, table, column_name, load_extension): "You must add a geometry column before creating a spatial index" ) - db[table].create_spatial_index(column_name) + db.table(table).create_spatial_index(column_name) + + +def _find_migration_files(migrations): + if not migrations: + migrations = [pathlib.Path(".").resolve()] + files = set() + for path_str in migrations: + path = pathlib.Path(path_str) + if path.is_dir(): + files.update(path.rglob("migrations.py")) + else: + files.add(path) + return sorted(files) + + +def _compatible_migration_set(obj): + return isinstance(obj, sqlite_utils.Migrations) or all( + hasattr(obj, attr) for attr in ("name", "applied", "pending", "apply") + ) + + +def _load_migration_sets(files): + migration_sets = [] + for filepath in files: + code = filepath.read_text() + namespace = { + "__file__": str(filepath), + "__name__": "__sqlite_utils_migration__", + } + exec(code, namespace) + migration_sets.extend( + obj for obj in namespace.values() if _compatible_migration_set(obj) + ) + return migration_sets + + +def _display_migration_list(db, migration_sets): + for migration_set in migration_sets: + click.echo("Migrations for: {}".format(migration_set.name)) + click.echo() + click.echo(" Applied:") + for migration in migration_set.applied(db): + click.echo(" {} - {}".format(migration.name, migration.applied_at)) + click.echo() + click.echo(" Pending:") + output = False + for migration in migration_set.pending(db): + output = True + click.echo(" {}".format(migration.name)) + if not output: + click.echo(" (none)") + click.echo() + + +def _stop_before_for_migration_set(stop_before, migration_set_name): + matches = [] + for value in stop_before: + set_name, separator, migration_name = value.partition(":") + if separator: + if set_name == migration_set_name: + matches.append(migration_name) + else: + matches.append(value) + return matches + + +@click.command() +@click.argument( + "db_path", type=click.Path(dir_okay=False, readable=True, writable=True) +) +@click.argument("migrations", type=click.Path(dir_okay=True, exists=True), nargs=-1) +@click.option( + "--stop-before", + multiple=True, + help="Stop before applying this migration. Use set:name to target a migration set.", +) +@click.option( + "list_", "--list", is_flag=True, help="List migrations without running them" +) +@click.option("-v", "--verbose", is_flag=True, help="Show verbose output") +def migrate(db_path, migrations, stop_before, list_, verbose): + """ + 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. + """ + files = _find_migration_files(migrations) + migration_sets = _load_migration_sets(files) + if not migration_sets: + raise click.ClickException("No migrations.py files found") + + if list_: + if pathlib.Path(db_path).exists(): + db = sqlite_utils.Database(db_path) + else: + # Listing is read-only - don't create the database file + db = sqlite_utils.Database(memory=True) + _register_db_for_cleanup(db) + # Legacy sqlite-migrate classes create the migrations table from + # their pending()/applied() methods - run the listing inside a + # transaction and roll it back so --list stays read-only + db.begin() + try: + _display_migration_list(db, migration_sets) + finally: + db.rollback() + return + + db = sqlite_utils.Database(db_path) + _register_db_for_cleanup(db) + + prev_schema = db.schema + if verbose: + click.echo("Migrating {}".format(db_path)) + click.echo("\nSchema before:\n") + click.echo(textwrap.indent(prev_schema, " ") or " (empty)") + click.echo() + if stop_before: + # Every --stop-before value must match at least one known migration + known_names = set() + for migration_set in migration_sets: + names = {m.name for m in migration_set.pending(db)} + names.update(m.name for m in migration_set.applied(db)) + known_names.update(names) + known_names.update( + "{}:{}".format(migration_set.name, name) for name in names + ) + unknown = [value for value in stop_before if value not in known_names] + if unknown: + raise click.ClickException( + "--stop-before did not match any migrations: {}".format( + ", ".join(unknown) + ) + ) + for migration_set in migration_sets: + matches = _stop_before_for_migration_set(stop_before, migration_set.name) + if isinstance(migration_set, sqlite_utils.Migrations): + try: + migration_set.apply(db, stop_before=matches) + except ValueError as e: + raise click.ClickException(str(e)) + else: + # Legacy sqlite-migrate Migrations objects take a single string + # for stop_before, not a list + distinct = list(dict.fromkeys(matches)) + if len(distinct) > 1: + raise click.ClickException( + "Migration set '{}' uses the older sqlite-migrate class, " + "which only supports a single --stop-before value - " + "got: {}".format(migration_set.name, ", ".join(distinct)) + ) + migration_set.apply(db, stop_before=distinct[0] if distinct else None) + if verbose: + click.echo("Schema after:\n") + post_schema = db.schema + if post_schema == prev_schema: + click.echo(" (unchanged)") + else: + click.echo(textwrap.indent(post_schema, " ")) + click.echo("\nSchema diff:\n") + diff = list( + difflib.unified_diff(prev_schema.splitlines(), post_schema.splitlines()) + ) + click.echo("\n".join(diff[3:])) @cli.command(name="plugins") def plugins_list(): "List installed plugins" - click.echo(json.dumps(get_plugins(), indent=2)) + click.echo(json.dumps(get_plugins(), indent=2, ensure_ascii=False)) +ensure_plugins_loaded() pm.hook.register_commands(cli=cli) +cli.add_command(migrate) def _render_common(title, values): @@ -3164,15 +3674,23 @@ FILE_COLUMNS = { "ctime": lambda p: p.stat().st_ctime, "mtime_int": lambda p: int(p.stat().st_mtime), "ctime_int": lambda p: int(p.stat().st_ctime), - "mtime_iso": lambda p: datetime.utcfromtimestamp(p.stat().st_mtime).isoformat(), - "ctime_iso": lambda p: datetime.utcfromtimestamp(p.stat().st_ctime).isoformat(), + "mtime_iso": lambda p: datetime.fromtimestamp(p.stat().st_mtime, timezone.utc) + .replace(tzinfo=None) + .isoformat(), + "ctime_iso": lambda p: datetime.fromtimestamp(p.stat().st_ctime, timezone.utc) + .replace(tzinfo=None) + .isoformat(), "size": lambda p: p.stat().st_size, "stem": lambda p: p.stem, "suffix": lambda p: p.suffix, } -def output_rows(iterator, headers, nl, arrays, json_cols): +def output_rows(iterator, headers, nl, arrays, json_cols, ascii_=False): + # Duplicate column names would collide as dictionary keys, so rename + # later occurrences id, id -> id, id_2 - CSV and table output keep + # the original duplicate headers since they never build dictionaries + headers = dedupe_keys(headers) # We have to iterate two-at-a-time so we can know if we # should output a trailing comma or if we have reached # the last row. @@ -3189,7 +3707,7 @@ def output_rows(iterator, headers, nl, arrays, json_cols): data = dict(zip(headers, data)) line = "{firstchar}{serialized}{maybecomma}{lastchar}".format( firstchar=("[" if first else " ") if not nl else "", - serialized=json.dumps(data, default=json_binary), + serialized=json.dumps(data, default=json_binary, ensure_ascii=ascii_), maybecomma="," if (not nl and not is_last) else "", lastchar="]" if (is_last and not nl) else "", ) @@ -3232,7 +3750,10 @@ def _load_extensions(db, load_extension): db.conn.enable_load_extension(True) for ext in load_extension: if ext == "spatialite" and not os.path.exists(ext): - ext = find_spatialite() + found = find_spatialite() + if found is None: + raise click.ClickException("Could not find SpatiaLite extension") + ext = found if ":" in ext: path, _, entrypoint = ext.partition(":") db.conn.execute("SELECT load_extension(?, ?)", [path, entrypoint]) @@ -3242,6 +3763,13 @@ def _load_extensions(db, load_extension): def _register_functions(db, functions): # Register any Python functions as SQL functions: + # Check if this is a file path + if "\n" not in functions and functions.endswith(".py"): + try: + functions = pathlib.Path(functions).read_text() + except FileNotFoundError: + raise click.ClickException("File not found: {}".format(functions)) + sqlite3.enable_callback_tracebacks(True) globals = {} try: @@ -3252,3 +3780,40 @@ def _register_functions(db, functions): for name, value in globals.items(): if callable(value) and not name.startswith("_"): db.register_function(value, name=name) + + +def _maybe_register_functions(db, functions_list): + if not functions_list: + return + for functions in functions_list: + if isinstance(functions, str) and functions.strip(): + _register_functions(db, functions) + + +def _rows_from_code(code): + # code may be a path to a .py file + if "\n" not in code and code.endswith(".py"): + try: + code = pathlib.Path(code).read_text() + except FileNotFoundError: + raise click.ClickException("File not found: {}".format(code)) + namespace = {} + try: + exec(code, namespace) + except SyntaxError as ex: + raise click.ClickException("Error in --code: {}".format(ex)) + rows = namespace.get("rows") + if callable(rows): + rows = rows() + if isinstance(rows, dict): + rows = [rows] + error = click.ClickException( + "--code must define a 'rows' function or iterable of rows to insert" + ) + if rows is None or isinstance(rows, (str, bytes)): + raise error + try: + iter(rows) + except TypeError: + raise error + return rows diff --git a/sqlite_utils/db.py b/sqlite_utils/db.py index 1baa32e..e97b7d9 100644 --- a/sqlite_utils/db.py +++ b/sqlite_utils/db.py @@ -1,5 +1,6 @@ from .utils import ( chunks, + dedupe_keys, hash_record, sqlite3, OperationalError, @@ -11,10 +12,12 @@ from .utils import ( ) import binascii from collections import namedtuple +from dataclasses import dataclass, field from collections.abc import Mapping import contextlib import datetime import decimal +import importlib import inspect import itertools import json @@ -22,7 +25,7 @@ import os import pathlib import re import secrets -from sqlite_fts4 import rank_bm25 # type: ignore +from sqlite_fts4 import rank_bm25 import textwrap from typing import ( cast, @@ -31,22 +34,30 @@ from typing import ( Dict, Generator, Iterable, + Sequence, + Set, + Type, Union, Optional, List, Tuple, ) import uuid -from sqlite_utils.plugins import pm +from sqlite_utils.plugins import ensure_plugins_loaded, pm try: - from sqlite_dump import iterdump + iterdump = importlib.import_module("sqlite_dump").iterdump except ImportError: iterdump = None SQLITE_MAX_VARS = 999 +# Names that refer to a rowid table's implicit integer primary key. These are +# valid primary key targets even though they are not listed among a table's +# columns. See https://www.sqlite.org/lang_createtable.html#rowid +ROWID_ALIASES = frozenset({"rowid", "_rowid_", "oid"}) + _quote_fts_re = re.compile(r'\s+|(".*?")') _virtual_table_using_re = re.compile( @@ -69,15 +80,55 @@ USING\s+(?P\w+) # for example USING FTS5 re.VERBOSE | re.IGNORECASE, ) -try: - import pandas as pd # type: ignore -except ImportError: - pd = None # type: ignore +def quote_identifier(identifier: str) -> str: + """ + Quote an identifier (table name, column name, etc.) using double quotes. + + Double quotes inside the identifier are escaped by doubling them. + """ + return '"{}"'.format(identifier.replace('"', '""')) + + +_IDENTIFIER_CASEFOLD = str.maketrans( + "ABCDEFGHIJKLMNOPQRSTUVWXYZ", "abcdefghijklmnopqrstuvwxyz" +) + + +def fold_identifier_case(identifier: str) -> str: + """ + Lowercase an identifier using the same rules SQLite uses - only ASCII + characters are folded, other characters are left unchanged. + """ + return identifier.translate(_IDENTIFIER_CASEFOLD) + + +def resolve_casing(name: str, candidates: Iterable[str]) -> str: + """ + SQLite treats identifiers as case-insensitive. Return the entry in + ``candidates`` that matches ``name`` case-insensitively, preferring an + exact match. If nothing matches, return ``name`` unchanged. + """ + if name in candidates: + return name + folded = fold_identifier_case(name) + for candidate in candidates: + if fold_identifier_case(candidate) == folded: + return candidate + return name + + +pd: Any = None try: - import numpy as np # type: ignore + pd = importlib.import_module("pandas") except ImportError: - np = None # type: ignore + pd = None + +np: Any = None +try: + np = importlib.import_module("numpy") +except ImportError: + np = None Column = namedtuple( "Column", ("cid", "name", "type", "notnull", "default_value", "is_pk") @@ -145,9 +196,75 @@ Summary information about a column, see :ref:`python_api_analyze_column`. The ``N`` least common values as a list of ``(value, count)`` tuples, or ``None`` if the table is entirely distinct or if the number of distinct values is less than N (since they will already have been returned in ``most_common``) """ -ForeignKey = namedtuple( - "ForeignKey", ("table", "column", "other_table", "other_column") -) + + +@dataclass(order=True, frozen=True) +class ForeignKey: + """ + A foreign key defined on a table. + + For single-column foreign keys ``column`` and ``other_column`` hold the + column names, and ``columns``/``other_columns`` are one-item tuples. + + For compound (multi-column) foreign keys ``column`` and ``other_column`` + are ``None`` - use ``columns`` and ``other_columns`` instead, and check + ``is_compound``. + + ``on_delete`` and ``on_update`` hold the foreign key actions, e.g. + ``"CASCADE"`` - ``"NO ACTION"`` if not set. + + Instances are immutable and hashable, so they can be collected into + sets and used as dictionary keys. Equality covers every compared field, + including ``on_delete`` and ``on_update`` - two foreign keys differing + only in their actions are different constraints. + + Prior to sqlite-utils 4.0 this was a ``namedtuple`` and could be unpacked + or indexed as ``(table, column, other_table, other_column)``. It is now a + dataclass - access its fields by name instead. + """ + + table: str + # column/other_column are None for compound keys, which would break + # ordering against str values - comparison uses columns/other_columns + column: Optional[str] = field(compare=False) + other_table: str + other_column: Optional[str] = field(compare=False) + columns: Tuple[str, ...] = () + other_columns: Tuple[str, ...] = () + is_compound: bool = False + on_delete: str = "NO ACTION" + on_update: str = "NO ACTION" + + def __post_init__(self): + # Populate columns/other_columns for single-column foreign keys, + # normalizing any lists to tuples. object.__setattr__ because the + # dataclass is frozen + if self.columns: + object.__setattr__(self, "columns", tuple(self.columns)) + else: + object.__setattr__( + self, "columns", (self.column,) if self.column is not None else () + ) + if self.other_columns: + object.__setattr__(self, "other_columns", tuple(self.other_columns)) + else: + object.__setattr__( + self, + "other_columns", + (self.other_column,) if self.other_column is not None else (), + ) + + +def _fk_actions_sql(fk: ForeignKey) -> str: + "ON UPDATE/ON DELETE clauses for a foreign key, or an empty string." + actions = "" + if fk.on_update and fk.on_update != "NO ACTION": + actions += " ON UPDATE {}".format(fk.on_update) + if fk.on_delete and fk.on_delete != "NO ACTION": + actions += " ON DELETE {}".format(fk.on_delete) + return actions + + Index = namedtuple("Index", ("seq", "name", "unique", "origin", "partial", "columns")) XIndex = namedtuple("XIndex", ("name", "columns")) XIndexColumn = namedtuple( @@ -156,12 +273,22 @@ XIndexColumn = namedtuple( Trigger = namedtuple("Trigger", ("name", "table", "sql")) +class TransformError(Exception): + pass + + +# A single column name, or a tuple of columns for a compound foreign key +ForeignKeyColumns = Union[str, Tuple[str, ...], List[str]] + +# (table, column(s), other_table, other_column(s)) +ForeignKeyTuple = Tuple[str, ForeignKeyColumns, str, ForeignKeyColumns] + ForeignKeyIndicator = Union[ str, ForeignKey, - Tuple[str, str], - Tuple[str, str, str], - Tuple[str, str, str, str], + Tuple[ForeignKeyColumns, str], + Tuple[ForeignKeyColumns, str, ForeignKeyColumns], + ForeignKeyTuple, ] ForeignKeysType = Union[Iterable[ForeignKeyIndicator], List[ForeignKeyIndicator]] @@ -173,8 +300,24 @@ class Default: DEFAULT = Default() -COLUMN_TYPE_MAPPING = { - float: "FLOAT", +Tracer = Callable[[str, Optional[Union[Sequence[Any], Dict[str, Any]]]], None] + + +def _iter_complete_sql_statements(sql: str) -> Generator[str, None, None]: + statement = [] + for char in sql: + statement.append(char) + statement_sql = "".join(statement).strip() + if statement_sql and sqlite3.complete_statement(statement_sql): + yield statement_sql + statement = [] + statement_sql = "".join(statement).strip() + if statement_sql: + yield statement_sql + + +COLUMN_TYPE_MAPPING: Dict[Any, str] = { + float: "REAL", int: "INTEGER", bool: "INTEGER", str: "TEXT", @@ -188,36 +331,45 @@ COLUMN_TYPE_MAPPING = { datetime.date: "TEXT", datetime.time: "TEXT", datetime.timedelta: "TEXT", - decimal.Decimal: "FLOAT", + decimal.Decimal: "REAL", None.__class__: "TEXT", uuid.UUID: "TEXT", # SQLite explicit types "TEXT": "TEXT", "INTEGER": "INTEGER", "FLOAT": "FLOAT", + "REAL": "REAL", "BLOB": "BLOB", "text": "TEXT", + "str": "TEXT", "integer": "INTEGER", - "float": "FLOAT", + "int": "INTEGER", + "float": "REAL", + "real": "REAL", "blob": "BLOB", + "bytes": "BLOB", } # If numpy is available, add more types if np: - COLUMN_TYPE_MAPPING.update( - { - np.int8: "INTEGER", - np.int16: "INTEGER", - np.int32: "INTEGER", - np.int64: "INTEGER", - np.uint8: "INTEGER", - np.uint16: "INTEGER", - np.uint32: "INTEGER", - np.uint64: "INTEGER", - np.float16: "FLOAT", - np.float32: "FLOAT", - np.float64: "FLOAT", - } - ) + try: + COLUMN_TYPE_MAPPING.update( + { + np.int8: "INTEGER", + np.int16: "INTEGER", + np.int32: "INTEGER", + np.int64: "INTEGER", + np.uint8: "INTEGER", + np.uint16: "INTEGER", + np.uint32: "INTEGER", + np.uint64: "INTEGER", + np.float16: "REAL", + np.float32: "REAL", + np.float64: "REAL", + } + ) + except AttributeError: + # https://github.com/simonw/sqlite-utils/issues/632 + pass # If pandas is available, add more types if pd: @@ -226,37 +378,38 @@ if pd: class AlterError(Exception): "Error altering table" - pass class NoObviousTable(Exception): "Could not tell which table this operation refers to" - pass class NoTable(Exception): "Specified table does not exist" - pass + + +class NoView(Exception): + "Specified view does not exist" class BadPrimaryKey(Exception): "Table does not have a single obvious primary key" - pass class NotFoundError(Exception): "Record not found" - pass class PrimaryKeyRequired(Exception): "Primary key needs to be specified" - pass class InvalidColumns(Exception): "Specified columns do not exist" - pass + + +class TransactionError(Exception): + "Operation cannot be performed while a transaction is open" class DescIndex(str): @@ -266,18 +419,66 @@ class DescIndex(str): class BadMultiValues(Exception): "With multi=True code must return a Python dictionary" - def __init__(self, values): + def __init__(self, values: object) -> None: self.values = values _COUNTS_TABLE_CREATE_SQL = """ -CREATE TABLE IF NOT EXISTS [{}]( - [table] TEXT PRIMARY KEY, +CREATE TABLE IF NOT EXISTS "{}"( + "table" TEXT PRIMARY KEY, count INTEGER DEFAULT 0 ); """.strip() +_TRANSACTION_CONTROL_KEYWORDS = { + "BEGIN", + "COMMIT", + "END", + "ROLLBACK", + "SAVEPOINT", + "RELEASE", +} + +# Statements that never return rows and cannot run inside (or would break +# out of) the savepoint guard used by query() +_QUERY_REJECTED_KEYWORDS = _TRANSACTION_CONTROL_KEYWORDS | { + "VACUUM", + "ATTACH", + "DETACH", +} + + +def _first_keyword(sql: str) -> str: + """ + Return the first keyword of a SQL statement, uppercased, skipping + everything the sqlite3 driver tolerates before the first real token: + whitespace, ``--`` or ``/* ... */`` comments, empty statements + (bare ``;``) and a UTF-8 byte order mark. Returns an empty string if + there is no leading keyword. + """ + i, n = 0, len(sql) + while i < n: + if sql[i].isspace() or sql[i] in (";", "\ufeff"): + i += 1 + elif sql.startswith("--", i): + newline = sql.find("\n", i) + if newline == -1: + return "" + i = newline + 1 + elif sql.startswith("/*", i): + end = sql.find("*/", i + 2) + if end == -1: + return "" + i = end + 2 + else: + break + j = i + while j < n and (sql[j].isalpha() or sql[j] == "_"): + j += 1 + return sql[i:j].upper() + + class Database: """ Wrapper for a SQLite database connection that adds a variety of useful utility methods. @@ -300,10 +501,14 @@ class Database: ``sql, parameters`` every time a SQL query is executed :param use_counts_table: set to ``True`` to use a cached counts table, if available. See :ref:`python_api_cached_table_counts` + :param use_old_upsert: set to ``True`` to force the older upsert implementation. See + :ref:`python_api_old_upsert` + :param strict: Apply STRICT mode to all created tables (unless overridden) """ _counts_table_name = "_counts" use_counts_table = False + conn: sqlite3.Connection def __init__( self, @@ -312,13 +517,20 @@ class Database: memory_name: Optional[str] = None, recreate: bool = False, recursive_triggers: bool = True, - tracer: Optional[Callable] = None, + tracer: Optional[Tracer] = None, use_counts_table: bool = False, execute_plugins: bool = True, + use_old_upsert: bool = False, + strict: bool = False, ): - assert (filename_or_conn is not None and (not memory and not memory_name)) or ( - filename_or_conn is None and (memory or memory_name) - ), "Either specify a filename_or_conn or pass memory=True" + self.memory_name = None + self.memory = False + self.use_old_upsert = use_old_upsert + if not ( + (filename_or_conn is not None and (not memory and not memory_name)) + or (filename_or_conn is None and (memory or memory_name)) + ): + raise ValueError("Either specify a filename_or_conn or pass memory=True") if memory_name: uri = "file:{}?mode=memory&cache=shared".format(memory_name) self.conn = sqlite3.connect( @@ -326,8 +538,11 @@ class Database: uri=True, check_same_thread=False, ) + self.memory = True + self.memory_name = memory_name elif memory or filename_or_conn == ":memory:": self.conn = sqlite3.connect(":memory:") + self.memory = True elif isinstance(filename_or_conn, (str, pathlib.Path)): if recreate and os.path.exists(filename_or_conn): try: @@ -339,32 +554,139 @@ class Database: raise self.conn = sqlite3.connect(str(filename_or_conn)) else: - assert not recreate, "recreate cannot be used with connections, only paths" - self.conn = filename_or_conn - self._tracer = tracer + if recreate: + raise ValueError("recreate cannot be used with connections, only paths") + self.conn = cast(sqlite3.Connection, filename_or_conn) + # Python 3.12+ autocommit=True/False connections make commit() + # and rollback() behave differently, silently breaking the + # transaction handling used by every write method + autocommit = getattr(self.conn, "autocommit", None) + if autocommit is not None and autocommit != getattr( + sqlite3, "LEGACY_TRANSACTION_CONTROL", -1 + ): + raise TransactionError( + "sqlite-utils requires a connection that uses the default " + "transaction handling - connections created with " + "autocommit=True or autocommit=False are not supported" + ) + self._tracer: Optional[Tracer] = tracer if recursive_triggers: self.execute("PRAGMA recursive_triggers=on;") self._registered_functions: set = set() self.use_counts_table = use_counts_table if execute_plugins: + ensure_plugins_loaded() pm.hook.prepare_connection(conn=self.conn) + self.strict = strict - def close(self): + def __enter__(self) -> "Database": + return self + + def __exit__( + self, + exc_type: Optional[Type[BaseException]], + exc_val: Optional[BaseException], + exc_tb: Optional[object], + ) -> None: + self.close() + + def close(self) -> None: "Close the SQLite connection, and the underlying database file" self.conn.close() @contextlib.contextmanager - def ensure_autocommit_off(self): + def atomic(self) -> Generator["Database", None, None]: """ - Ensure autocommit is off for this database connection. + Context manager for wrapping multiple database operations in a transaction. + + Nested blocks use SQLite savepoints. + """ + if self.conn.in_transaction: + savepoint = "sqlite_utils_{}".format(secrets.token_hex(16)) + self.conn.execute("SAVEPOINT {};".format(savepoint)) + try: + yield self + except BaseException: + # An error such as a RAISE(ROLLBACK) trigger can destroy + # the whole transaction, savepoints included - cleaning up + # anyway would mask the original exception with + # "no such savepoint" + if self.conn.in_transaction: + self.conn.execute("ROLLBACK TO SAVEPOINT {};".format(savepoint)) + self.conn.execute("RELEASE SAVEPOINT {};".format(savepoint)) + raise + else: + self.conn.execute("RELEASE SAVEPOINT {};".format(savepoint)) + else: + self.conn.execute("BEGIN") + try: + yield self + except BaseException: + # rollback() is a no-op if the error already destroyed the + # transaction, so the original exception propagates + self.rollback() + raise + else: + try: + self.conn.execute("COMMIT") + except BaseException: + self.rollback() + raise + + def begin(self) -> None: + """ + Start a transaction with ``BEGIN``, taking manual control of transaction + handling. End it by calling :meth:`commit` or :meth:`rollback`. + + Raises ``sqlite3.OperationalError`` if a transaction is already open. + + Most code should use the :meth:`atomic` context manager instead, which + commits and rolls back automatically. See :ref:`python_api_transactions`. + """ + self.execute("BEGIN") + + def commit(self) -> None: + """ + Commit the current transaction. Does nothing if no transaction is open. + """ + if self.conn.in_transaction: + self.conn.execute("COMMIT") + + def rollback(self) -> None: + """ + Roll back the current transaction, discarding its changes. Does nothing + if no transaction is open. + """ + if self.conn.in_transaction: + self.conn.execute("ROLLBACK") + + @contextlib.contextmanager + def ensure_autocommit_on(self) -> Generator[None, None, None]: + """ + Ensure the connection is in driver-level autocommit mode for the + duration of a block of code. + + This temporarily sets ``isolation_level = None`` on the underlying + ``sqlite3`` connection, so the driver does not open implicit + transactions. This is useful for statements such as + ``PRAGMA journal_mode=wal`` which cannot run inside a transaction. Example usage:: - with db.ensure_autocommit_off(): + with db.ensure_autocommit_on(): # do stuff here - This will reset to the previous autocommit state at the end of the block. + The previous ``isolation_level`` is restored at the end of the block. + + :raises TransactionError: if a transaction is open - assigning + ``isolation_level`` would commit it as a side effect, silently + breaking the caller's ability to roll back """ + if self.conn.in_transaction: + raise TransactionError( + "ensure_autocommit_on() cannot be used inside a transaction - " + "changing isolation_level would commit the open transaction" + ) old_isolation_level = self.conn.isolation_level try: self.conn.isolation_level = None @@ -373,7 +695,9 @@ class Database: self.conn.isolation_level = old_isolation_level @contextlib.contextmanager - def tracer(self, tracer: Optional[Callable] = None): + def tracer( + self, tracer: Optional[Tracer] = None + ) -> Generator["Database", None, None]: """ Context manager to temporarily set a tracer function - all executed SQL queries will be passed to this. @@ -390,7 +714,7 @@ class Database: :param tracer: Callable accepting ``sql`` and ``parameters`` arguments """ prev_tracer = self._tracer - self._tracer = tracer or print + self._tracer = tracer or cast(Tracer, print) try: yield self finally: @@ -398,11 +722,15 @@ class Database: def __getitem__(self, table_name: str) -> Union["Table", "View"]: """ - ``db[table_name]`` returns a :class:`.Table` object for the table with the specified name. - If the table does not exist yet it will be created the first time data is inserted into it. + ``db[name]`` returns a :class:`.Table` object for the table with the specified name, + or a :class:`.View` object if the name matches an existing SQL view. + If neither exists yet, a table is assumed - it will be created the first + time data is inserted into it. - :param table_name: The name of the table + :param table_name: The name of the table or view """ + if table_name in self.view_names(): + return self.view(table_name) return self.table(table_name) def __repr__(self) -> str: @@ -414,7 +742,7 @@ class Database: deterministic: bool = False, replace: bool = False, name: Optional[str] = None, - ): + ) -> Optional[Callable[[Callable], Callable]]: """ ``fn`` will be made available as a function within SQL, with the same name and number of arguments. Can be used as a decorator:: @@ -437,12 +765,12 @@ class Database: :param name: name of the SQLite function - if not specified, the Python function name will be used """ - def register(fn): - fn_name = name or fn.__name__ + def register(fn: Callable) -> Callable: + fn_name = name or fn.__name__ # type: ignore arity = len(inspect.signature(fn).parameters) if not replace and (fn_name, arity) in self._registered_functions: return fn - kwargs = {} + kwargs: Dict[str, bool] = {} registered = False if deterministic: # Try this, but fall back if sqlite3.NotSupportedError @@ -451,8 +779,7 @@ class Database: fn_name, arity, fn, **dict(kwargs, deterministic=True) ) registered = True - except (sqlite3.NotSupportedError, TypeError): - # TypeError is Python 3.7 "function takes at most 3 arguments" + except sqlite3.NotSupportedError: pass if not registered: self.conn.create_function(fn_name, arity, fn, **kwargs) @@ -463,12 +790,13 @@ class Database: return register else: register(fn) + return None - def register_fts4_bm25(self): + def register_fts4_bm25(self) -> None: "Register the ``rank_bm25(match_info)`` function used for calculating relevance with SQLite FTS4." self.register_function(rank_bm25, deterministic=True, replace=True) - def attach(self, alias: str, filepath: Union[str, pathlib.Path]): + def attach(self, alias: str, filepath: Union[str, pathlib.Path]) -> None: """ Attach another SQLite database file to this connection with the specified alias, equivalent to:: @@ -478,43 +806,131 @@ class Database: :param filepath: Path to SQLite database file on disk """ attach_sql = """ - ATTACH DATABASE '{}' AS [{}]; + ATTACH DATABASE '{}' AS {}; """.format( - str(pathlib.Path(filepath).resolve()), alias + str(pathlib.Path(filepath).resolve()), quote_identifier(alias) ).strip() self.execute(attach_sql) def query( - self, sql: str, params: Optional[Union[Iterable, dict]] = None + self, sql: str, params: Optional[Union[Sequence, Dict[str, Any]]] = None ) -> Generator[dict, None, None]: """ Execute ``sql`` and return an iterable of dictionaries representing each row. + The SQL is executed as soon as this method is called - the resulting rows + are then fetched lazily as the returned iterable is iterated over. A + row-returning write such as ``INSERT ... RETURNING`` takes effect + immediately, even if the results are never iterated. + :param sql: SQL query to execute :param params: Parameters to use in that query - an iterable for ``where id = ?`` parameters, or a dictionary for ``where id = :id`` + :raises ValueError: if the SQL statement does not return rows - use + :meth:`execute` for those statements instead. The rejected statement + is rolled back, so it has no effect on the database. One exception: + a row-less ``PRAGMA`` statement takes effect despite the + ``ValueError``, because PRAGMAs run outside the savepoint guard - + some of them refuse to run inside a transaction """ - cursor = self.execute(sql, params or tuple()) - keys = [d[0] for d in cursor.description] - for row in cursor: - yield dict(zip(keys, row)) + message = ( + "query() can only be used with SQL that returns rows - " + "use execute() for other statements" + ) + keyword = _first_keyword(sql) + if keyword in _QUERY_REJECTED_KEYWORDS: + # None of these return rows - reject them without executing anything + raise ValueError(message) + if self._tracer: + self._tracer(sql, params) + args: tuple = (params,) if params is not None else () + if keyword == "PRAGMA": + # Some PRAGMA statements refuse to run inside a transaction, so + # execute these without the savepoint guard used below. Some + # adapters open an implicit transaction before comment-prefixed + # PRAGMAs, so temporarily use driver autocommit when it is safe. + if self.conn.in_transaction: + cursor = self.conn.execute(sql, *args) + else: + with self.ensure_autocommit_on(): + cursor = self.conn.execute(sql, *args) + if cursor.description is None: + raise ValueError(message) + keys = dedupe_keys(d[0] for d in cursor.description) + return (dict(zip(keys, row)) for row in cursor) + # Execute inside a savepoint, so a statement that turns out not to + # return rows can be rolled back before the ValueError is raised + self.conn.execute('SAVEPOINT "sqlite_utils_query"') + released = False + try: + cursor = self.conn.execute(sql, *args) + if cursor.description is None: + raise ValueError(message) + keys = dedupe_keys(d[0] for d in cursor.description) + try: + self.conn.execute('RELEASE "sqlite_utils_query"') + released = True + except sqlite3.OperationalError: + # The savepoint cannot be released while a write statement is + # still executing - this is INSERT ... RETURNING or similar, + # with unfetched rows. Fetch them so the write completes, then + # release again - committing the write immediately, unless an + # outer transaction is open + fetched = cursor.fetchall() + self.conn.execute('RELEASE "sqlite_utils_query"') + released = True + return (dict(zip(keys, row)) for row in fetched) + return (dict(zip(keys, row)) for row in cursor) + finally: + if not released and self.conn.in_transaction: + # An error occurred - undo anything the statement changed. + # If the error itself destroyed the transaction (such as a + # RAISE(ROLLBACK) trigger) the savepoint is already gone + # and there is nothing left to undo + self.conn.execute('ROLLBACK TO "sqlite_utils_query"') + self.conn.execute('RELEASE "sqlite_utils_query"') def execute( - self, sql: str, parameters: Optional[Union[Iterable, dict]] = None + self, sql: str, parameters: Optional[Union[Sequence, Dict[str, Any]]] = None ) -> sqlite3.Cursor: """ Execute SQL query and return a ``sqlite3.Cursor``. + A write statement - ``INSERT``, ``UPDATE``, ``CREATE TABLE`` and so on - + is committed automatically, unless a transaction is already open, in + which case it becomes part of that transaction. See + :ref:`python_api_transactions`. + :param sql: SQL query to execute :param parameters: Parameters to use in that query - an iterable for ``where id = ?`` parameters, or a dictionary for ``where id = :id`` """ if self._tracer: self._tracer(sql, parameters) - if parameters is not None: - return self.conn.execute(sql, parameters) - else: - return self.conn.execute(sql) + was_in_transaction = self.conn.in_transaction + try: + if parameters is not None: + cursor = self.conn.execute(sql, parameters) + else: + cursor = self.conn.execute(sql) + except Exception: + if not was_in_transaction and self.conn.in_transaction: + # The failed statement opened an implicit transaction that + # nothing would ever commit - roll it back, otherwise it + # would capture every subsequent write + self.conn.execute("ROLLBACK") + raise + if ( + not was_in_transaction + and self.conn.in_transaction + and cursor.description is None + and _first_keyword(sql) not in _TRANSACTION_CONTROL_KEYWORDS + ): + # The statement opened an implicit transaction - commit it, so + # that execute() behaves consistently with the rest of the + # library and identically across connection modes + self.conn.execute("COMMIT") + return cursor def executescript(self, sql: str) -> sqlite3.Cursor: """ @@ -524,9 +940,18 @@ class Database: """ if self._tracer: self._tracer(sql, None) + return self._executescript(sql) + + def _executescript(self, sql: str) -> sqlite3.Cursor: + if self.conn.in_transaction: + cursor = self.conn.cursor() + # avoid sqlite3.executescript()'s implicit commit: + for statement in _iter_complete_sql_statements(sql): + cursor.execute(statement) + return cursor return self.conn.executescript(sql) - def table(self, table_name: str, **kwargs) -> Union["Table", "View"]: + def table(self, table_name: str, **kwargs: Any) -> "Table": """ Return a table object, optionally configured with default options. @@ -534,8 +959,26 @@ class Database: :param table_name: Name of the table """ - klass = View if table_name in self.view_names() else Table - return klass(self, table_name, **kwargs) + if table_name in self.view_names(): + raise NoTable("Table {} is actually a view".format(table_name)) + kwargs.setdefault("strict", self.strict) + return Table(self, table_name, **kwargs) + + def view(self, view_name: str) -> "View": + """ + Return a view object. + + :param view_name: Name of the view + """ + if view_name not in self.view_names(): + if view_name in self.table_names(): + raise NoView( + "View {name} does not exist - {name} is a table".format( + name=view_name + ) + ) + raise NoView("View {} does not exist".format(view_name)) + return View(self, view_name) def quote(self, value: str) -> str: """ @@ -586,6 +1029,11 @@ class Database: if str(value).upper() in ("CURRENT_TIME", "CURRENT_DATE", "CURRENT_TIMESTAMP"): return value + if isinstance(value, str) and value.upper() in ("TRUE", "FALSE", "NULL"): + # Keyword literals must stay unquoted; quoting them would turn the + # default into a string ('TRUE' instead of 1, 'NULL' instead of null). + return value + if str(value).endswith(")"): # Expr return "({})".format(value) @@ -619,12 +1067,12 @@ class Database: @property def tables(self) -> List["Table"]: "List of Table objects in this database." - return cast(List["Table"], [self[name] for name in self.table_names()]) + return [self.table(name) for name in self.table_names()] @property def views(self) -> List["View"]: "List of View objects in this database." - return cast(List["View"], [self[name] for name in self.view_names()]) + return [self.view(name) for name in self.view_names()] @property def triggers(self) -> List[Trigger]: @@ -657,16 +1105,46 @@ class Database: @property def supports_strict(self) -> bool: "Does this database support STRICT mode?" - try: + if not hasattr(self, "_supports_strict"): + try: + table_name = "t{}".format(secrets.token_hex(16)) + with self.atomic(): + self.conn.execute( + "create table {} (name text) strict".format(table_name) + ) + self.conn.execute("drop table {}".format(table_name)) + self._supports_strict = True + except Exception: + self._supports_strict = False + return self._supports_strict + + @property + def supports_on_conflict(self) -> bool: + # SQLite's upsert is implemented as INSERT INTO ... ON CONFLICT DO ... + if not hasattr(self, "_supports_on_conflict"): table_name = "t{}".format(secrets.token_hex(16)) - with self.conn: - self.conn.execute( - "create table {} (name text) strict".format(table_name) - ) - self.conn.execute("drop table {}".format(table_name)) - return True - except Exception: - return False + try: + with self.atomic(): + self.conn.execute( + "create table {} (id integer primary key, name text)".format( + table_name + ) + ) + self.conn.execute( + "insert into {} (id, name) values (1, 'one')".format(table_name) + ) + self.conn.execute( + ( + "insert into {} (id, name) values (1, 'two') " + "on conflict do update set name = 'two'" + ).format(table_name) + ) + self._supports_on_conflict = True + except Exception: + self._supports_on_conflict = False + finally: + self.conn.execute("drop table if exists {}".format(table_name)) + return self._supports_on_conflict @property def sqlite_version(self) -> Tuple[int, ...]: @@ -683,25 +1161,44 @@ class Database: """ return self.execute("PRAGMA journal_mode;").fetchone()[0] - def enable_wal(self): + def enable_wal(self) -> None: """ Sets ``journal_mode`` to ``'wal'`` to enable Write-Ahead Log mode. + + :raises TransactionError: if called while a transaction is open - the + journal mode can only be changed outside of a transaction """ if self.journal_mode != "wal": - with self.ensure_autocommit_off(): + self._ensure_no_open_transaction("enable_wal()") + with self.ensure_autocommit_on(): self.execute("PRAGMA journal_mode=wal;") - def disable_wal(self): - "Sets ``journal_mode`` back to ``'delete'`` to disable Write-Ahead Log mode." + def disable_wal(self) -> None: + """ + Sets ``journal_mode`` back to ``'delete'`` to disable Write-Ahead Log mode. + + :raises TransactionError: if called while a transaction is open - the + journal mode can only be changed outside of a transaction + """ if self.journal_mode != "delete": - with self.ensure_autocommit_off(): + self._ensure_no_open_transaction("disable_wal()") + with self.ensure_autocommit_on(): self.execute("PRAGMA journal_mode=delete;") - def _ensure_counts_table(self): - with self.conn: + def _ensure_no_open_transaction(self, operation: str) -> None: + # Changing journal mode assigns conn.isolation_level, which commits + # any open transaction as a side effect - breaking the rollback + # guarantee of atomic() and of user-managed transactions + if self.conn.in_transaction: + raise TransactionError( + "{} cannot be used while a transaction is open".format(operation) + ) + + def _ensure_counts_table(self) -> None: + with self.atomic(): self.execute(_COUNTS_TABLE_CREATE_SQL.format(self._counts_table_name)) - def enable_counts(self): + def enable_counts(self) -> None: """ Enable trigger-based count caching for every table in the database, see :ref:`python_api_cached_table_counts`. @@ -722,20 +1219,21 @@ class Database: :param tables: Subset list of tables to return counts for. """ - sql = "select [table], count from {}".format(self._counts_table_name) - if tables: - sql += " where [table] in ({})".format(", ".join("?" for table in tables)) + sql = 'select "table", count from {}'.format(self._counts_table_name) + tables_list = list(tables) if tables else None + if tables_list: + sql += ' where "table" in ({})'.format(", ".join("?" for _ in tables_list)) try: - return {r[0]: r[1] for r in self.execute(sql, tables).fetchall()} + return {r[0]: r[1] for r in self.execute(sql, tables_list).fetchall()} except OperationalError: return {} - def reset_counts(self): + def reset_counts(self) -> None: "Re-calculate cached counts for tables." tables = [table for table in self.tables if table.has_counts_triggers] - with self.conn: + with self.atomic(): self._ensure_counts_table() - counts_table = self[self._counts_table_name] + counts_table = self.table(self._counts_table_name) counts_table.delete_where() counts_table.insert_all( {"table": table.name, "count": table.execute_count()} @@ -743,7 +1241,7 @@ class Database: ) def execute_returning_dicts( - self, sql: str, params: Optional[Union[Iterable, dict]] = None + self, sql: str, params: Optional[Union[Sequence, Dict[str, Any]]] = None ) -> List[dict]: return list(self.query(sql, params)) @@ -756,58 +1254,138 @@ class Database: :param name: Name of table that foreign keys are being defined for :param foreign_keys: List of foreign keys, each of which can be a - string, a ForeignKey() named tuple, a tuple of (column, other_table), + string, a ForeignKey() object, a tuple of (column, other_table), or a tuple of (column, other_table, other_column), or a tuple of - (table, column, other_table, other_column) + (table, column, other_table, other_column). For compound foreign + keys the column elements can be tuples of column names, e.g. + (("campus_name", "dept_code"), "departments") or + (("campus_name", "dept_code"), "departments", ("campus_name", "dept_code")) """ - table = cast(Table, self[name]) - if all(isinstance(fk, ForeignKey) for fk in foreign_keys): - return cast(List[ForeignKey], foreign_keys) - if all(isinstance(fk, str) for fk in foreign_keys): - # It's a list of columns - fks = [] - for column in foreign_keys: - column = cast(str, column) - other_table = table.guess_foreign_table(column) - other_column = table.guess_foreign_column(other_table) - fks.append(ForeignKey(name, column, other_table, other_column)) - return fks - assert all( - isinstance(fk, (tuple, list)) for fk in foreign_keys - ), "foreign_keys= should be a list of tuples" + table = self.table(name) fks = [] - for tuple_or_list in foreign_keys: + for fk in foreign_keys: + if isinstance(fk, ForeignKey): + fks.append(fk) + continue + if isinstance(fk, str): + # A bare column name - guess the other table and column + other_table = table.guess_foreign_table(fk) + other_column = table.guess_foreign_column(other_table) + fks.append(ForeignKey(name, fk, other_table, other_column)) + continue + if not isinstance(fk, (tuple, list)): + raise ValueError( + "foreign_keys= should be a list of tuples, " + "ForeignKey objects or column name strings" + ) + tuple_or_list = cast(Sequence[Any], fk) if len(tuple_or_list) == 4: - assert ( - tuple_or_list[0] == name - ), "First item in {} should have been {}".format(tuple_or_list, name) - assert len(tuple_or_list) in ( - 2, - 3, - 4, - ), "foreign_keys= should be a list of tuple pairs or triples" - if len(tuple_or_list) in (3, 4): - if len(tuple_or_list) == 4: - tuple_or_list = cast(Tuple[str, str, str], tuple_or_list[1:]) - else: - tuple_or_list = cast(Tuple[str, str, str], tuple_or_list) - fks.append( - ForeignKey( - name, tuple_or_list[0], tuple_or_list[1], tuple_or_list[2] + if tuple_or_list[0] != name: + raise ValueError( + "First item in {} should have been {}".format( + tuple_or_list, name + ) ) + tuple_or_list = tuple_or_list[1:] + if len(tuple_or_list) not in (2, 3): + raise ValueError( + "foreign_keys= should be a list of tuple pairs or triples" + ) + column_or_columns = tuple_or_list[0] + other_table = tuple_or_list[1] + if isinstance(column_or_columns, (list, tuple)): + # Compound foreign key + columns = tuple(column_or_columns) + if len(tuple_or_list) == 3: + if not isinstance(tuple_or_list[2], (list, tuple)): + raise ValueError( + "Compound foreign key {} should reference a tuple " + "of other columns".format(tuple(tuple_or_list)) + ) + other_columns = tuple(tuple_or_list[2]) + else: + # Guess the compound primary key of the other table + other_columns = tuple(self.table(other_table).pks) + if len(columns) != len(other_columns): + raise ValueError( + "Compound foreign key {} should have the same number " + "of columns on both sides".format(tuple(tuple_or_list)) + ) + if len(columns) == 1: + # Single-column key passed as a one-item list + fks.append( + ForeignKey(name, columns[0], other_table, other_columns[0]) + ) + else: + fks.append( + ForeignKey( + name, + None, + other_table, + None, + columns=columns, + other_columns=other_columns, + is_compound=True, + ) + ) + elif len(tuple_or_list) == 3: + fks.append( + ForeignKey(name, column_or_columns, other_table, tuple_or_list[2]) ) else: # Guess the primary key fks.append( ForeignKey( name, - tuple_or_list[0], - tuple_or_list[1], - table.guess_foreign_column(tuple_or_list[1]), + column_or_columns, + other_table, + table.guess_foreign_column(other_table), ) ) return fks + def _resolve_foreign_key_casing( + self, fk: ForeignKey, columns: Iterable[str] + ) -> ForeignKey: + """ + Return ``fk`` with its column references resolved to match the casing + of the actual columns. ``columns`` provides the column names of + ``fk.table``, which may be a table that is still being created. + """ + resolved_columns = tuple(resolve_casing(c, columns) for c in fk.columns) + if fk.other_table == fk.table: + other_candidates: Iterable[str] = columns + else: + other_candidates = self[fk.other_table].columns_dict + resolved_other_columns = tuple( + resolve_casing(c, other_candidates) for c in fk.other_columns + ) + if ( + resolved_columns == fk.columns + and resolved_other_columns == fk.other_columns + ): + return fk + if fk.is_compound: + return ForeignKey( + fk.table, + None, + fk.other_table, + None, + columns=resolved_columns, + other_columns=resolved_other_columns, + is_compound=True, + on_delete=fk.on_delete, + on_update=fk.on_update, + ) + return ForeignKey( + fk.table, + resolved_columns[0], + fk.other_table, + resolved_other_columns[0], + on_delete=fk.on_delete, + on_update=fk.on_update, + ) + def create_table_sql( self, name: str, @@ -821,6 +1399,7 @@ class Database: hash_id_columns: Optional[Iterable[str]] = None, extracts: Optional[Union[Dict[str, str], List[str]]] = None, if_not_exists: bool = False, + strict: bool = False, ) -> str: """ Returns the SQL ``CREATE TABLE`` statement for creating the specified table. @@ -836,11 +1415,19 @@ class Database: :param hash_id_columns: List of columns to be used when calculating the hash ID for a row :param extracts: List or dictionary of columns to be extracted during inserts, see :ref:`python_api_extracts` :param if_not_exists: Use ``CREATE TABLE IF NOT EXISTS`` + :param strict: Apply STRICT mode to table """ if hash_id_columns and (hash_id is None): hash_id = "id" - foreign_keys = self.resolve_foreign_keys(name, foreign_keys or []) - foreign_keys_by_column = {fk.column: fk for fk in foreign_keys} + resolved_fks: List[ForeignKey] = [ + self._resolve_foreign_key_casing(fk, columns) + for fk in self.resolve_foreign_keys(name, foreign_keys or []) + ] + # Compound foreign keys are rendered as table-level constraints; + # single-column ones as inline REFERENCES on their column + foreign_keys_by_column = { + fk.column: fk for fk in resolved_fks if not fk.is_compound + } # any extracts will be treated as integer columns with a foreign key extracts = resolve_extracts(extracts) for extract_column, extract_table in extracts.items(): @@ -854,20 +1441,24 @@ class Database: name, extract_column, extract_table, "id" ) # Soundness check not_null, and defaults if provided - not_null = not_null or set() - defaults = defaults or {} - assert columns, "Tables must have at least one column" - assert all( - n in columns for n in not_null - ), "not_null set {} includes items not in columns {}".format( - repr(not_null), repr(set(columns.keys())) - ) - assert all( - n in columns for n in defaults - ), "defaults set {} includes items not in columns {}".format( - repr(set(defaults)), repr(set(columns.keys())) - ) - validate_column_names(columns.keys()) + not_null = {resolve_casing(n, columns) for n in not_null or set()} + defaults = {resolve_casing(n, columns): v for n, v in (defaults or {}).items()} + if column_order is not None: + column_order = [resolve_casing(c, columns) for c in column_order] + if not columns: + raise ValueError("Tables must have at least one column") + if not all(n in columns for n in not_null): + raise ValueError( + "not_null set {} includes items not in columns {}".format( + repr(not_null), repr(set(columns.keys())) + ) + ) + if not all(n in columns for n in defaults): + raise ValueError( + "defaults set {} includes items not in columns {}".format( + repr(set(defaults)), repr(set(columns.keys())) + ) + ) column_items = list(columns.items()) if column_order is not None: @@ -879,25 +1470,28 @@ class Database: column_items.insert(0, (hash_id, str)) pk = hash_id # Soundness check foreign_keys point to existing tables - for fk in foreign_keys: - if fk.other_table == name and columns.get(fk.other_column): - continue - if fk.other_column != "rowid" and not any( - c for c in self[fk.other_table].columns if c.name == fk.other_column - ): - raise AlterError( - "No such column: {}.{}".format(fk.other_table, fk.other_column) - ) + for fk in resolved_fks: + for other_column in fk.other_columns: + if fk.other_table == name and columns.get(other_column): + continue + if other_column != "rowid" and not any( + c for c in self[fk.other_table].columns if c.name == other_column + ): + raise AlterError( + "No such column: {}.{}".format(fk.other_table, other_column) + ) column_defs = [] # ensure pk is a tuple single_pk = None - if isinstance(pk, list) and len(pk) == 1 and isinstance(pk[0], str): + if isinstance(pk, (list, tuple)) and len(pk) == 1 and isinstance(pk[0], str): pk = pk[0] if isinstance(pk, str): - single_pk = pk + single_pk = pk = resolve_casing(pk, [c[0] for c in column_items]) if pk not in [c[0] for c in column_items]: column_items.insert(0, (pk, int)) + elif pk: + pk = [resolve_casing(p, [c[0] for c in column_items]) for p in pk] for column_name, column_type in column_items: column_extras = [] if column_name == single_pk: @@ -909,35 +1503,63 @@ class Database: "DEFAULT {}".format(self.quote_default_value(defaults[column_name])) ) if column_name in foreign_keys_by_column: + fk = foreign_keys_by_column[column_name] column_extras.append( - "REFERENCES [{other_table}]([{other_column}])".format( - other_table=foreign_keys_by_column[column_name].other_table, - other_column=foreign_keys_by_column[column_name].other_column, + "REFERENCES {}({}){}".format( + quote_identifier(fk.other_table), + quote_identifier(cast(str, fk.other_column)), + _fk_actions_sql(fk), ) ) + column_type_str = COLUMN_TYPE_MAPPING[column_type] + # Special case for strict tables to map FLOAT to REAL + # Refs https://github.com/simonw/sqlite-utils/issues/644 + if strict and column_type_str == "FLOAT": + column_type_str = "REAL" column_defs.append( - " [{column_name}] {column_type}{column_extras}".format( - column_name=column_name, - column_type=COLUMN_TYPE_MAPPING[column_type], - column_extras=(" " + " ".join(column_extras)) - if column_extras - else "", + " {} {column_type}{column_extras}".format( + quote_identifier(column_name), + column_type=column_type_str, + column_extras=( + (" " + " ".join(column_extras)) if column_extras else "" + ), ) ) extra_pk = "" if single_pk is None and pk and len(pk) > 1: extra_pk = ",\n PRIMARY KEY ({pks})".format( - pks=", ".join(["[{}]".format(p) for p in pk]) + pks=", ".join([quote_identifier(p) for p in pk]) + ) + # Compound foreign keys become table-level FOREIGN KEY constraints + column_names = [c[0] for c in column_items] + for fk in resolved_fks: + if not fk.is_compound: + continue + missing = [c for c in fk.columns if c not in column_names] + if missing: + raise AlterError( + "No such column: {}".format(", ".join(sorted(missing))) + ) + column_defs.append( + " FOREIGN KEY ({columns}) REFERENCES {other_table}({other_columns}){actions}".format( + columns=", ".join(quote_identifier(c) for c in fk.columns), + other_table=quote_identifier(fk.other_table), + other_columns=", ".join( + quote_identifier(c) for c in fk.other_columns + ), + actions=_fk_actions_sql(fk), + ) ) columns_sql = ",\n".join(column_defs) - sql = """CREATE TABLE {if_not_exists}[{table}] ( + sql = """CREATE TABLE {if_not_exists}{table} ( {columns_sql}{extra_pk} -); +){strict}; """.format( if_not_exists="IF NOT EXISTS " if if_not_exists else "", - table=name, + table=quote_identifier(name), columns_sql=columns_sql, extra_pk=extra_pk, + strict=" STRICT" if strict and self.supports_strict else "", ) return sql @@ -957,6 +1579,7 @@ class Database: replace: bool = False, ignore: bool = False, transform: bool = False, + strict: bool = False, ) -> "Table": """ Create a table with the specified name and the specified ``{column_name: type}`` columns. @@ -977,18 +1600,24 @@ class Database: :param replace: Drop and replace table if it already exists :param ignore: Silently do nothing if table already exists :param transform: If table already exists transform it to fit the specified schema + :param strict: Apply STRICT mode to table """ # Transform table to match the new definition if table already exists: if self[name].exists(): if ignore: - return cast(Table, self[name]) + return self.table(name) elif replace: self[name].drop() if transform and self[name].exists(): - table = cast(Table, self[name]) + table = self.table(name) should_transform = False # First add missing columns and figure out columns to drop existing_columns = table.columns_dict + # Match existing columns case-insensitively, the way SQLite does + columns = { + resolve_casing(col_name, existing_columns): col_type + for col_name, col_type in columns.items() + } missing_columns = dict( (col_name, col_type) for col_name, col_type in columns.items() @@ -1012,18 +1641,28 @@ class Database: current_pks = table.pks desired_pk = None if isinstance(pk, str): - desired_pk = [pk] + desired_pk = [resolve_casing(pk, existing_columns)] elif pk: - desired_pk = list(pk) + desired_pk = [resolve_casing(p, existing_columns) for p in pk] if desired_pk and current_pks != desired_pk: should_transform = True # Any not-null changes? current_not_null = {c.name for c in table.columns if c.notnull} - desired_not_null = set(not_null) if not_null else set() + desired_not_null = ( + {resolve_casing(n, existing_columns) for n in not_null} + if not_null + else set() + ) if current_not_null != desired_not_null: should_transform = True # How about defaults? - if defaults and defaults != table.default_values: + if ( + defaults + and { + resolve_casing(c, existing_columns): v for c, v in defaults.items() + } + != table.default_values + ): should_transform = True # Only run .transform() if there is something to do if should_transform: @@ -1048,9 +1687,10 @@ class Database: hash_id_columns=hash_id_columns, extracts=extracts, if_not_exists=if_not_exists, + strict=strict, ) self.execute(sql) - created_table = self.table( + return self.table( name, pk=pk, foreign_keys=foreign_keys, @@ -1060,9 +1700,8 @@ class Database: hash_id=hash_id, hash_id_columns=hash_id_columns, ) - return cast(Table, created_table) - def rename_table(self, name: str, new_name: str): + def rename_table(self, name: str, new_name: str) -> None: """ Rename a table. @@ -1070,14 +1709,14 @@ class Database: :param new_name: Name to rename it to """ self.execute( - "ALTER TABLE [{name}] RENAME TO [{new_name}]".format( - name=name, new_name=new_name + "ALTER TABLE {} RENAME TO {}".format( + quote_identifier(name), quote_identifier(new_name) ) ) def create_view( self, name: str, sql: str, ignore: bool = False, replace: bool = False - ): + ) -> "Database": """ Create a new SQL view with the specified name - ``sql`` should start with ``SELECT ...``. @@ -1086,10 +1725,11 @@ class Database: :param ignore: Set to ``True`` to do nothing if a view with this name already exists :param replace: Set to ``True`` to replace the view if one with this name already exists """ - assert not ( - ignore and replace - ), "Use one or the other of ignore/replace, not both" - create_sql = "CREATE VIEW {name} AS {sql}".format(name=name, sql=sql) + if ignore and replace: + raise ValueError("Use one or the other of ignore/replace, not both") + create_sql = "CREATE VIEW {name} AS {sql}".format( + name=quote_identifier(name), sql=sql + ) if ignore or replace: # Does view exist already? if name in self.view_names(): @@ -1121,77 +1761,145 @@ class Database: candidates.append(table_obj.name) return candidates - def add_foreign_keys(self, foreign_keys: Iterable[Tuple[str, str, str, str]]): + def add_foreign_keys( + self, foreign_keys: Iterable[Union[ForeignKey, ForeignKeyTuple]] + ) -> None: """ See :ref:`python_api_add_foreign_keys`. :param foreign_keys: A list of ``(table, column, other_table, other_column)`` - tuples + tuples - for compound foreign keys, ``column`` and ``other_column`` can + be tuples of column names """ # foreign_keys is a list of explicit 4-tuples - assert all( - len(fk) == 4 and isinstance(fk, (list, tuple)) for fk in foreign_keys - ), "foreign_keys must be a list of 4-tuples, (table, column, other_table, other_column)" + if not all( + isinstance(fk, ForeignKey) + or (isinstance(fk, (list, tuple)) and len(fk) == 4) + for fk in foreign_keys + ): + raise ValueError( + "foreign_keys must be a list of 4-tuples, " + "(table, column, other_table, other_column)" + ) - foreign_keys_to_create = [] + foreign_keys_to_create: List[ForeignKey] = [] # Verify that all tables and columns exist - for table, column, other_table, other_column in foreign_keys: - if not self[table].exists(): + for fk in foreign_keys: + if isinstance(fk, ForeignKey): + fk_object = fk + else: + table, column_or_columns, other_table, other_column_or_columns = fk + # Compound foreign keys use tuples of columns + columns = ( + (column_or_columns,) + if isinstance(column_or_columns, str) + else tuple(column_or_columns) + ) + other_columns = ( + (other_column_or_columns,) + if isinstance(other_column_or_columns, str) + else tuple(other_column_or_columns) + ) + if len(columns) != len(other_columns): + raise ValueError( + "Compound foreign key must have the same number of " + "columns on both sides" + ) + if len(columns) == 1: + fk_object = ForeignKey( + table, columns[0], other_table, other_columns[0] + ) + else: + fk_object = ForeignKey( + table, + None, + other_table, + None, + columns=columns, + other_columns=other_columns, + is_compound=True, + ) + table = fk_object.table + other_table = fk_object.other_table + if not self.table(table).exists(): raise AlterError("No such table: {}".format(table)) - table_obj = self[table] - if not isinstance(table_obj, Table): - raise AlterError("Must be a table, not a view: {}".format(table)) - table_obj = cast(Table, table_obj) - if column not in table_obj.columns_dict: - raise AlterError("No such column: {} in {}".format(column, table)) + table_obj = self.table(table) + fk_object = self._resolve_foreign_key_casing( + fk_object, table_obj.columns_dict + ) + columns = fk_object.columns + other_columns = fk_object.other_columns + for column in columns: + if column not in table_obj.columns_dict: + raise AlterError("No such column: {} in {}".format(column, table)) if not self[other_table].exists(): raise AlterError("No such other_table: {}".format(other_table)) - if ( - other_column != "rowid" - and other_column not in self[other_table].columns_dict - ): - raise AlterError( - "No such other_column: {} in {}".format(other_column, other_table) - ) - # We will silently skip foreign keys that exist already - if not any( + for other_column in other_columns: + if ( + other_column != "rowid" + and other_column not in self[other_table].columns_dict + ): + raise AlterError( + "No such other_column: {} in {}".format( + other_column, other_table + ) + ) + # Silently skip foreign keys that exist already - but only if + # they match exactly, including ON DELETE/ON UPDATE actions + columns_folded = tuple(fold_identifier_case(c) for c in columns) + other_columns_folded = tuple(fold_identifier_case(c) for c in other_columns) + existing = [ fk for fk in table_obj.foreign_keys - if fk.column == column - and fk.other_table == other_table - and fk.other_column == other_column + if tuple(fold_identifier_case(c) for c in fk.columns) == columns_folded + and fold_identifier_case(fk.other_table) + == fold_identifier_case(other_table) + and tuple(fold_identifier_case(c) for c in fk.other_columns) + == other_columns_folded + ] + if not existing: + foreign_keys_to_create.append(fk_object) + elif any( + fk.on_delete != fk_object.on_delete + or fk.on_update != fk_object.on_update + for fk in existing ): - foreign_keys_to_create.append( - (table, column, other_table, other_column) + raise AlterError( + "Foreign key already exists for {} => {}.{} but with " + "different ON DELETE/ON UPDATE actions - use " + "table.transform() to change them".format( + ", ".join(columns), other_table, ", ".join(other_columns) + ) ) # Group them by table - by_table: Dict[str, List] = {} - for fk in foreign_keys_to_create: - by_table.setdefault(fk[0], []).append(fk) + by_table: Dict[str, List[ForeignKey]] = {} + for fk_object in foreign_keys_to_create: + by_table.setdefault(fk_object.table, []).append(fk_object) for table, fks in by_table.items(): - cast(Table, self[table]).transform(add_foreign_keys=fks) + self.table(table).transform(add_foreign_keys=fks) - self.vacuum() + if not self.conn.in_transaction: + self.vacuum() - def index_foreign_keys(self): + def index_foreign_keys(self) -> None: "Create indexes for every foreign key column on every table in the database." for table_name in self.table_names(): - table = self[table_name] - existing_indexes = { - i.columns[0] for i in table.indexes if len(i.columns) == 1 - } + table = self.table(table_name) + existing_indexes = {tuple(i.columns) for i in table.indexes} for fk in table.foreign_keys: - if fk.column not in existing_indexes: - table.create_index([fk.column], find_unique_name=True) + # A compound foreign key gets a single composite index + if fk.columns not in existing_indexes: + table.create_index(fk.columns, find_unique_name=True) + existing_indexes.add(fk.columns) - def vacuum(self): + def vacuum(self) -> None: "Run a SQLite ``VACUUM`` against the database." self.execute("VACUUM;") - def analyze(self, name=None): + def analyze(self, name: Optional[str] = None) -> None: """ Run ``ANALYZE`` against the entire database or a named table or index. @@ -1199,7 +1907,7 @@ class Database: """ sql = "ANALYZE" if name is not None: - sql += " [{}]".format(name) + sql += " {}".format(quote_identifier(name)) self.execute(sql) def iterdump(self) -> Generator[str, None, None]: @@ -1245,6 +1953,8 @@ class Database: """ if path is None: path = find_spatialite() + if path is None: + raise OSError("Could not find SpatiaLite extension") self.conn.enable_load_extension(True) self.conn.load_extension(path) @@ -1257,18 +1967,21 @@ class Database: class Queryable: + db: "Database" + name: str + def exists(self) -> bool: "Does this table or view exist yet?" return False - def __init__(self, db, name): + def __init__(self, db: "Database", name: str) -> None: self.db = db self.name = name def count_where( self, where: Optional[str] = None, - where_args: Optional[Union[Iterable, dict]] = None, + where_args: Optional[Union[Sequence, Dict[str, Any]]] = None, ) -> int: """ Executes ``SELECT count(*) FROM table WHERE ...`` and returns a count. @@ -1277,12 +1990,12 @@ class Queryable: :param where_args: Parameters to use with that fragment - an iterable for ``id > ?`` parameters, or a dictionary for ``id > :id`` """ - sql = "select count(*) from [{}]".format(self.name) + sql = "select count(*) from {}".format(quote_identifier(self.name)) if where is not None: sql += " where " + where return self.db.execute(sql, where_args or []).fetchone()[0] - def execute_count(self): + def execute_count(self) -> int: # Backwards compatibility, see https://github.com/simonw/sqlite-utils/issues/305#issuecomment-890713185 return self.count_where() @@ -1292,19 +2005,19 @@ class Queryable: return self.count_where() @property - def rows(self) -> Generator[dict, None, None]: + def rows(self) -> Generator[Dict[str, Any], None, None]: "Iterate over every dictionaries for each row in this table or view." return self.rows_where() def rows_where( self, where: Optional[str] = None, - where_args: Optional[Union[Iterable, dict]] = None, + where_args: Optional[Union[Sequence, Dict[str, Any]]] = None, order_by: Optional[str] = None, select: str = "*", limit: Optional[int] = None, offset: Optional[int] = None, - ) -> Generator[dict, None, None]: + ) -> Generator[Dict[str, Any], None, None]: """ Iterate over every row in this table or view that matches the specified where clause. @@ -1320,7 +2033,7 @@ class Queryable: """ if not self.exists(): return - sql = "select {} from [{}]".format(select, self.name) + sql = "select {} from {}".format(select, quote_identifier(self.name)) if where is not None: sql += " where " + where if order_by is not None: @@ -1330,18 +2043,18 @@ class Queryable: if offset is not None: sql += " offset {}".format(offset) cursor = self.db.execute(sql, where_args or []) - columns = [c[0] for c in cursor.description] + columns = dedupe_keys(c[0] for c in cursor.description) for row in cursor: yield dict(zip(columns, row)) def pks_and_rows_where( self, where: Optional[str] = None, - where_args: Optional[Union[Iterable, dict]] = None, + where_args: Optional[Union[Sequence, Dict[str, Any]]] = None, order_by: Optional[str] = None, limit: Optional[int] = None, offset: Optional[int] = None, - ) -> Generator[Tuple[Any, Dict], None, None]: + ) -> Generator[Tuple[Any, Dict[str, Any]], None, None]: """ Like ``.rows_where()`` but returns ``(pk, row)`` pairs - ``pk`` can be a single value or tuple. @@ -1353,12 +2066,22 @@ class Queryable: :param limit: Integer number of rows to limit to :param offset: Integer for SQL offset """ - column_names = [column.name for column in self.columns] - pks = [column.name for column in self.columns if column.is_pk] + # This method is defined on Queryable so it serves views too, which + # have no pks property - sort pk columns into declaration order here + pk_columns = sorted( + (column for column in self.columns if column.is_pk), + key=lambda column: column.is_pk, + ) + pks = [column.name for column in pk_columns] + select_parts = [quote_identifier(column.name) for column in self.columns] if not pks: - column_names.insert(0, "rowid") + # rowid is left unquoted: it is not a real column, and SQLite + # turns a double-quoted identifier that does not resolve into a + # string literal - on a view that would silently select the + # string 'rowid' instead of raising an error + select_parts.insert(0, "rowid") pks = ["rowid"] - select = ",".join("[{}]".format(column_name) for column_name in column_names) + select = ",".join(select_parts) for row in self.rows_where( select=select, where=where, @@ -1377,7 +2100,9 @@ class Queryable: "List of :ref:`Columns ` representing the columns in this table or view." if not self.exists(): return [] - rows = self.db.execute("PRAGMA table_info([{}])".format(self.name)).fetchall() + rows = self.db.execute( + "PRAGMA table_info({})".format(quote_identifier(self.name)) + ).fetchall() return [Column(*row) for row in rows] @property @@ -1408,7 +2133,8 @@ class Table(Queryable): :param not_null: List of columns that cannot be null :param defaults: Dictionary of column names and default values :param batch_size: Integer number of rows to insert at a time - :param hash_id: If True, use a hash of the row values as the primary key + :param hash_id: Name of a column to create and use as a primary key, where the + value of that primary key is derived from a hash of the row values :param hash_id_columns: List of columns to use for the hash_id :param alter: If True, automatically alter the table if it doesn't match the schema :param ignore: If True, ignore rows that already exist when inserting @@ -1416,6 +2142,7 @@ class Table(Queryable): :param extracts: Dictionary or list of column names to extract into a separate table on inserts :param conversions: Dictionary of column names and conversion functions :param columns: Dictionary of column names to column types + :param strict: If True, apply STRICT mode to table """ #: The ``rowid`` of the last inserted, updated or selected row. @@ -1441,6 +2168,7 @@ class Table(Queryable): extracts: Optional[Union[Dict[str, str], List[str]]] = None, conversions: Optional[dict] = None, columns: Optional[Dict[str, Any]] = None, + strict: bool = False, ): super().__init__(db, name) self._defaults = dict( @@ -1458,14 +2186,17 @@ class Table(Queryable): extracts=extracts, conversions=conversions or {}, columns=columns, + strict=strict, ) def __repr__(self) -> str: return "
".format( self.name, - " (does not exist yet)" - if not self.exists() - else " ({})".format(", ".join(c.name for c in self.columns)), + ( + " (does not exist yet)" + if not self.exists() + else " ({})".format(", ".join(c.name for c in self.columns)) + ), ) @property @@ -1482,8 +2213,18 @@ class Table(Queryable): @property def pks(self) -> List[str]: - "Primary key columns for this table." - names = [column.name for column in self.columns if column.is_pk] + """ + Primary key columns for this table, in PRIMARY KEY declaration order - + ``PRAGMA table_info`` sets ``is_pk`` to the 1-based position of each + column within the primary key, which can differ from the order of the + columns in the table. SQLite uses the declaration order to resolve + implicit foreign key references, so this order matters. + """ + pk_columns = sorted( + (column for column in self.columns if column.is_pk), + key=lambda column: column.is_pk, + ) + names = [column.name for column in pk_columns] if not names: names = ["rowid"] return names @@ -1512,7 +2253,7 @@ class Table(Queryable): ) ) - wheres = ["[{}] = ?".format(pk_name) for pk_name in pks] + wheres = ["{} = ?".format(quote_identifier(pk_name)) for pk_name in pks] rows = self.rows_where(" and ".join(wheres), pk_values) try: row = list(rows)[0] @@ -1523,21 +2264,50 @@ class Table(Queryable): @property def foreign_keys(self) -> List["ForeignKey"]: - "List of foreign keys defined on this table." - fks = [] + """ + List of foreign keys defined on this table. + + Compound (multi-column) foreign keys are returned as a single + ``ForeignKey`` with ``is_compound=True`` and populated + ``columns``/``other_columns`` lists. + """ + # PRAGMA foreign_key_list returns one row per column, grouped by "id" + # with "seq" giving the column order within a compound foreign key. + by_id: Dict[int, list] = {} for row in self.db.execute( - "PRAGMA foreign_key_list([{}])".format(self.name) + "PRAGMA foreign_key_list({})".format(quote_identifier(self.name)) ).fetchall(): if row is not None: id, seq, table_name, from_, to_, on_update, on_delete, match = row - fks.append( - ForeignKey( - table=self.name, - column=from_, - other_table=table_name, - other_column=to_, - ) + by_id.setdefault(id, []).append( + (seq, table_name, from_, to_, on_update, on_delete) ) + fks = [] + for id in sorted(by_id): + rows = sorted(by_id[id]) # order columns by seq + other_table = rows[0][1] + columns = tuple(row[2] for row in rows) + other_columns = tuple(row[3] for row in rows) + if all(c is None for c in other_columns): + # "REFERENCES other_table" with no columns - the pragma + # returns None, meaning the other table's primary key + other_table_pks = tuple(self.db.table(other_table).pks) + if len(other_table_pks) == len(columns): + other_columns = other_table_pks + is_compound = len(rows) > 1 + fks.append( + ForeignKey( + table=self.name, + column=None if is_compound else columns[0], + other_table=other_table, + other_column=None if is_compound else other_columns[0], + columns=columns, + other_columns=other_columns, + is_compound=is_compound, + on_update=rows[0][4], + on_delete=rows[0][5], + ) + ) return fks @property @@ -1627,18 +2397,19 @@ class Table(Queryable): def create( self, columns: Dict[str, Any], - pk: Optional[Any] = None, - foreign_keys: Optional[ForeignKeysType] = None, - column_order: Optional[List[str]] = None, - not_null: Optional[Iterable[str]] = None, - defaults: Optional[Dict[str, Any]] = None, - hash_id: Optional[str] = None, - hash_id_columns: Optional[Iterable[str]] = None, - extracts: Optional[Union[Dict[str, str], List[str]]] = None, + pk: Optional[Any] = DEFAULT, + foreign_keys: Union[Optional[ForeignKeysType], Default] = DEFAULT, + column_order: Union[Optional[List[str]], Default] = DEFAULT, + not_null: Union[Optional[Iterable[str]], Default] = DEFAULT, + defaults: Union[Optional[Dict[str, Any]], Default] = DEFAULT, + hash_id: Union[Optional[str], Default] = DEFAULT, + hash_id_columns: Union[Optional[Iterable[str]], Default] = DEFAULT, + extracts: Union[Optional[Union[Dict[str, str], List[str]]], Default] = DEFAULT, if_not_exists: bool = False, replace: bool = False, ignore: bool = False, transform: bool = False, + strict: Union[bool, Default] = DEFAULT, ) -> "Table": """ Create a table with the specified columns. @@ -1658,24 +2429,58 @@ class Table(Queryable): :param replace: Drop and replace table if it already exists :param ignore: Silently do nothing if table already exists :param transform: If table already exists transform it to fit the specified schema + :param strict: Apply STRICT mode to table """ + # Resolve defaults from _defaults (issue #655) + pk = self.value_or_default("pk", pk) + foreign_keys = self.value_or_default("foreign_keys", foreign_keys) + column_order = self.value_or_default("column_order", column_order) + not_null = self.value_or_default("not_null", not_null) + defaults = self.value_or_default("defaults", defaults) + hash_id = self.value_or_default("hash_id", hash_id) + hash_id_columns = self.value_or_default("hash_id_columns", hash_id_columns) + extracts = self.value_or_default("extracts", extracts) + strict = self.value_or_default("strict", strict) + + # Store configuration in _defaults for subsequent operations (issue #655) + # Don't store pk if hash_id is set, since pk is derived from hash_id in that case + if pk is not None and hash_id is None: + self._defaults["pk"] = pk + if foreign_keys is not None: + self._defaults["foreign_keys"] = foreign_keys + if column_order is not None: + self._defaults["column_order"] = column_order + if not_null is not None: + self._defaults["not_null"] = not_null + if defaults is not None: + self._defaults["defaults"] = defaults + if hash_id is not None: + self._defaults["hash_id"] = hash_id + if hash_id_columns is not None: + self._defaults["hash_id_columns"] = hash_id_columns + if extracts is not None: + self._defaults["extracts"] = extracts + if strict: + self._defaults["strict"] = strict + columns = {name: value for (name, value) in columns.items()} - with self.db.conn: + with self.db.atomic(): self.db.create_table( self.name, columns, pk=pk, - foreign_keys=foreign_keys, - column_order=column_order, - not_null=not_null, - defaults=defaults, - hash_id=hash_id, - hash_id_columns=hash_id_columns, - extracts=extracts, + foreign_keys=foreign_keys, # type: ignore[arg-type] + column_order=column_order, # type: ignore[arg-type] + not_null=not_null, # type: ignore[arg-type] + defaults=defaults, # type: ignore[arg-type] + hash_id=hash_id, # type: ignore[arg-type] + hash_id_columns=hash_id_columns, # type: ignore[arg-type] + extracts=extracts, # type: ignore[arg-type] if_not_exists=if_not_exists, replace=replace, ignore=ignore, transform=transform, + strict=strict, # type: ignore[arg-type] ) return self @@ -1687,13 +2492,13 @@ class Table(Queryable): """ if not self.exists(): raise NoTable(f"Table {self.name} does not exist") - with self.db.conn: - sql = "CREATE TABLE [{new_table}] AS SELECT * FROM [{table}];".format( - new_table=new_name, - table=self.name, + with self.db.atomic(): + sql = "CREATE TABLE {} AS SELECT * FROM {};".format( + quote_identifier(new_name), + quote_identifier(self.name), ) self.db.execute(sql) - return self.db[new_name] + return self.db.table(new_name) def transform( self, @@ -1709,6 +2514,7 @@ class Table(Queryable): foreign_keys: Optional[ForeignKeysType] = None, column_order: Optional[List[str]] = None, keep_table: Optional[str] = None, + strict: Optional[bool] = None, ) -> "Table": """ Apply an advanced alter table, including operations that are not supported by @@ -1716,21 +2522,31 @@ class Table(Queryable): See :ref:`python_api_transform` for full details. + Raises :py:class:`sqlite_utils.db.TransactionError` if called while a + transaction is open with ``PRAGMA foreign_keys`` enabled and the table + is referenced by foreign keys with destructive ``ON DELETE`` actions - + see :ref:`python_api_transform_foreign_keys_transactions`. + :param types: Columns that should have their type changed, for example ``{"weight": float}`` :param rename: Columns to rename, for example ``{"headline": "title"}`` :param drop: Columns to drop :param pk: New primary key for the table :param not_null: Columns to set as ``NOT NULL`` :param defaults: Default values for columns - :param drop_foreign_keys: Names of columns that should have their foreign key constraints removed + :param drop_foreign_keys: Foreign key constraints to remove - a column name + drops any foreign key that column participates in, a tuple of column names + drops the compound foreign key with exactly those columns :param add_foreign_keys: List of foreign keys to add to the table :param foreign_keys: List of foreign keys to set for the table, replacing any existing foreign keys :param column_order: List of strings specifying a full or partial column order to use when creating the table :param keep_table: If specified, the existing table will be renamed to this and will not be dropped + :param strict: Set to ``True`` to make the table strict or ``False`` to make it + non-strict. Defaults to ``None``, which preserves the existing strict mode. """ - assert self.exists(), "Cannot transform a table that doesn't exist yet" + if not self.exists(): + raise ValueError("Cannot transform a table that doesn't exist yet") sqls = self.transform_sql( types=types, rename=rename, @@ -1743,22 +2559,75 @@ class Table(Queryable): foreign_keys=foreign_keys, column_order=column_order, keep_table=keep_table, + strict=strict, ) - pragma_foreign_keys_was_on = self.db.execute("PRAGMA foreign_keys").fetchone()[ - 0 - ] + pragma_foreign_keys_was_on = bool( + self.db.execute("PRAGMA foreign_keys").fetchone()[0] + ) + already_in_transaction = self.db.conn.in_transaction + should_disable_foreign_keys = ( + pragma_foreign_keys_was_on and not already_in_transaction + ) + should_defer_foreign_keys = ( + pragma_foreign_keys_was_on and already_in_transaction + ) + if should_defer_foreign_keys: + # PRAGMA foreign_keys is a no-op inside a transaction, and + # defer_foreign_keys only defers violation checks, not ON DELETE + # actions - so dropping the old table would still fire destructive + # actions on any tables that reference it. Refuse rather than + # silently modify or delete those rows. + destructive_fks = [ + (table.name, fk) + for table in self.db.tables + for fk in table.foreign_keys + if fk.other_table == self.name + and fk.on_delete in ("CASCADE", "SET NULL", "SET DEFAULT") + ] + if destructive_fks: + raise TransactionError( + "Cannot transform table {table} while a transaction is open: " + "PRAGMA foreign_keys cannot be changed inside a transaction, " + "and the table is referenced by foreign keys with ON DELETE " + "actions that would fire when the old table is dropped: " + "{fks}. Call transform() outside of the transaction, or " + 'execute "PRAGMA foreign_keys = off" before opening it.'.format( + table=self.name, + fks=", ".join( + "{}.{} (ON DELETE {})".format( + table_name, ", ".join(fk.columns), fk.on_delete + ) + for table_name, fk in destructive_fks + ), + ) + ) + defer_foreign_keys_was_on = False try: - if pragma_foreign_keys_was_on: + if should_disable_foreign_keys: self.db.execute("PRAGMA foreign_keys=0;") - with self.db.conn: + elif should_defer_foreign_keys: + defer_foreign_keys_was_on = bool( + self.db.execute("PRAGMA defer_foreign_keys").fetchone()[0] + ) + if not defer_foreign_keys_was_on: + self.db.execute("PRAGMA defer_foreign_keys=ON;") + with self.db.atomic(): for sql in sqls: self.db.execute(sql) # Run the foreign_key_check before we commit if pragma_foreign_keys_was_on: - self.db.execute("PRAGMA foreign_key_check;") + foreign_key_violations = self.db.execute( + "PRAGMA foreign_key_check;" + ).fetchall() + if foreign_key_violations: + raise sqlite3.IntegrityError("FOREIGN KEY constraint failed") finally: - if pragma_foreign_keys_was_on: + if should_defer_foreign_keys and not defer_foreign_keys_was_on: + self.db.execute("PRAGMA defer_foreign_keys=OFF;") + if should_disable_foreign_keys: self.db.execute("PRAGMA foreign_keys=1;") + if strict is not None: + self._defaults["strict"] = strict return self def transform_sql( @@ -1776,6 +2645,7 @@ class Table(Queryable): column_order: Optional[List[str]] = None, tmp_suffix: Optional[str] = None, keep_table: Optional[str] = None, + strict: Optional[bool] = None, ) -> List[str]: """ Return a list of SQL statements that should be executed in order to apply this transformation. @@ -1786,7 +2656,9 @@ class Table(Queryable): :param pk: New primary key for the table :param not_null: Columns to set as ``NOT NULL`` :param defaults: Default values for columns - :param drop_foreign_keys: Names of columns that should have their foreign key constraints removed + :param drop_foreign_keys: Foreign key constraints to remove - a column name + drops any foreign key that column participates in, a tuple of column names + drops the compound foreign key with exactly those columns :param add_foreign_keys: List of foreign keys to add to the table :param foreign_keys: List of foreign keys to set for the table, replacing any existing foreign keys :param column_order: List of strings specifying a full or partial column order @@ -1794,11 +2666,40 @@ class Table(Queryable): :param tmp_suffix: Suffix to use for the temporary table name :param keep_table: If specified, the existing table will be renamed to this and will not be dropped + :param strict: Set to ``True`` to make the table strict or ``False`` to make it + non-strict. Defaults to ``None``, which preserves the existing strict mode. """ + if strict is True and not self.db.supports_strict: + raise TransformError("SQLite does not support STRICT tables") types = types or {} rename = rename or {} drop = drop or set() + # Resolve column references against the existing schema, matching + # case-insensitively the way SQLite does + existing_columns = self.columns_dict + types = {resolve_casing(c, existing_columns): t for c, t in types.items()} + rename = {resolve_casing(c, existing_columns): v for c, v in rename.items()} + drop = {resolve_casing(c, existing_columns) for c in drop} + if pk is not DEFAULT and pk is not None: + if isinstance(pk, str): + pk = resolve_casing(pk, existing_columns) + else: + pk = [resolve_casing(p, existing_columns) for p in pk] + if isinstance(not_null, dict): + not_null = { + resolve_casing(c, existing_columns): v + for c, v in cast(Dict[str, Any], not_null).items() + } + elif isinstance(not_null, set): + not_null = {resolve_casing(c, existing_columns) for c in not_null} + if defaults is not None: + defaults = { + resolve_casing(c, existing_columns): v for c, v in defaults.items() + } + if column_order is not None: + column_order = [resolve_casing(c, existing_columns) for c in column_order] + create_table_foreign_keys: List[ForeignKeyIndicator] = [] if foreign_keys is not None: @@ -1813,29 +2714,68 @@ class Table(Queryable): create_table_foreign_keys.extend(foreign_keys) else: # Construct foreign_keys from current, plus add_foreign_keys, minus drop_foreign_keys - create_table_foreign_keys = [] - for table, column, other_table, other_column in self.foreign_keys: - # Copy over old foreign keys, unless we are dropping them - if (drop_foreign_keys is None) or (column not in drop_foreign_keys): - create_table_foreign_keys.append( - ForeignKey( - table, - rename.get(column) or column, - other_table, - other_column, - ) + # The casing of columns in a foreign key definition can differ + # from the casing of the columns themselves, so these comparisons + # are all case-folded + dropped_columns_folded = {fold_identifier_case(c) for c in drop} + renamed_columns_folded = { + fold_identifier_case(k): v for k, v in rename.items() + } + + def fk_should_be_dropped(fk: ForeignKey) -> bool: + fk_columns_folded = tuple(fold_identifier_case(c) for c in fk.columns) + if drop_foreign_keys is not None: + for spec in drop_foreign_keys: + if isinstance(spec, str): + # A column name matches any foreign key it participates in + if fold_identifier_case(spec) in fk_columns_folded: + return True + elif ( + tuple(fold_identifier_case(s) for s in spec) + == fk_columns_folded + ): + # A tuple/list must match a compound key's columns exactly + return True + # Dropping any of a foreign key's columns drops the whole key + return any( + column in dropped_columns_folded for column in fk_columns_folded + ) + + def fk_with_renamed_columns(fk: ForeignKey) -> ForeignKey: + columns = tuple( + renamed_columns_folded.get(fold_identifier_case(column)) or column + for column in fk.columns + ) + if fk.is_compound: + return ForeignKey( + self.name, + None, + fk.other_table, + None, + columns=columns, + other_columns=fk.other_columns, + is_compound=True, + on_delete=fk.on_delete, + on_update=fk.on_update, ) + return ForeignKey( + self.name, + columns[0], + fk.other_table, + fk.other_columns[0], + on_delete=fk.on_delete, + on_update=fk.on_update, + ) + + create_table_foreign_keys = [] + # Copy over old foreign keys, unless we are dropping them + for fk in self.foreign_keys: + if not fk_should_be_dropped(fk): + create_table_foreign_keys.append(fk_with_renamed_columns(fk)) # Add new foreign keys if add_foreign_keys is not None: for fk in self.db.resolve_foreign_keys(self.name, add_foreign_keys): - create_table_foreign_keys.append( - ForeignKey( - self.name, - rename.get(fk.column) or fk.column, - fk.other_table, - fk.other_column, - ) - ) + create_table_foreign_keys.append(fk_with_renamed_columns(fk)) new_table_name = "{}_new_{}".format( self.name, tmp_suffix or os.urandom(6).hex() @@ -1854,7 +2794,8 @@ class Table(Queryable): if pk is DEFAULT: pks_renamed = tuple( - rename.get(p.name) or p.name for p in self.columns if p.is_pk + rename.get(pk_name) or pk_name + for pk_name in (self.pks if not self.use_rowid else []) ) if len(pks_renamed) == 1: pk = pks_renamed[0] @@ -1882,8 +2823,10 @@ class Table(Queryable): elif not not_null: pass else: - assert False, "not_null must be a dict or a set or None, it was {}".format( - repr(not_null) + raise ValueError( + "not_null must be a dict or a set or None, it was {}".format( + repr(not_null) + ) ) # defaults= create_table_defaults = { @@ -1909,6 +2852,7 @@ class Table(Queryable): defaults=create_table_defaults, foreign_keys=create_table_foreign_keys, column_order=column_order, + strict=self.strict if strict is None else strict, ).strip() ) @@ -1922,24 +2866,52 @@ class Table(Queryable): if "rowid" not in new_cols: new_cols.insert(0, "rowid") old_cols.insert(0, "rowid") - copy_sql = "INSERT INTO [{new_table}] ({new_cols})\n SELECT {old_cols} FROM [{old_table}];".format( - new_table=new_table_name, - old_table=self.name, - old_cols=", ".join("[{}]".format(col) for col in old_cols), - new_cols=", ".join("[{}]".format(col) for col in new_cols), + copy_sql = "INSERT INTO {} ({new_cols})\n SELECT {old_cols} FROM {};".format( + quote_identifier(new_table_name), + quote_identifier(self.name), + old_cols=", ".join(quote_identifier(col) for col in old_cols), + new_cols=", ".join(quote_identifier(col) for col in new_cols), ) sqls.append(copy_sql) # Drop (or keep) the old table if keep_table: sqls.append( - "ALTER TABLE [{}] RENAME TO [{}];".format(self.name, keep_table) + "ALTER TABLE {} RENAME TO {};".format( + quote_identifier(self.name), quote_identifier(keep_table) + ) ) else: - sqls.append("DROP TABLE [{}];".format(self.name)) + sqls.append("DROP TABLE {};".format(quote_identifier(self.name))) # Rename the new one sqls.append( - "ALTER TABLE [{}] RENAME TO [{}];".format(new_table_name, self.name) + "ALTER TABLE {} RENAME TO {};".format( + quote_identifier(new_table_name), quote_identifier(self.name) + ) ) + # Re-add existing indexes + for index in self.indexes: + if index.origin != "pk": + index_sql = self.db.execute( + """SELECT sql FROM sqlite_master WHERE type = 'index' AND name = :index_name;""", + {"index_name": index.name}, + ).fetchall()[0][0] + if index_sql is None: + raise TransformError( + f"Index '{index.name}' on table '{self.name}' does not have a " + "CREATE INDEX statement. You must manually drop this index prior to running this " + "transformation and manually recreate the new index after running this transformation." + ) + if keep_table: + sqls.append(f"DROP INDEX IF EXISTS {quote_identifier(index.name)};") + for col in index.columns: + if col in rename.keys() or col in drop: + raise TransformError( + f"Index '{index.name}' column '{col}' is not in updated table '{self.name}'. " + f"You must manually drop this index prior to running this transformation " + f"and manually recreate the new index after running this transformation. " + f"The original index sql statement is: `{index_sql}`. No changes have been applied to this table." + ) + sqls.append(index_sql) return sqls def extract( @@ -1962,92 +2934,120 @@ class Table(Queryable): rename = rename or {} if isinstance(columns, str): columns = [columns] + columns = [resolve_casing(c, self.columns_dict) for c in columns] + rename = {resolve_casing(k, self.columns_dict): v for k, v in rename.items()} if not set(columns).issubset(self.columns_dict.keys()): raise InvalidColumns( "Invalid columns {} for table with columns {}".format( columns, list(self.columns_dict.keys()) ) ) - table = table or "_".join(columns) - lookup_table = self.db[table] - fk_column = fk_column or "{}_id".format(table) - magic_lookup_column = "{}_{}".format(fk_column, os.urandom(6).hex()) + with self.db.atomic(): + table = table or "_".join(columns) + lookup_table = self.db.table(table) + fk_column = fk_column or "{}_id".format(table) + magic_lookup_column = "{}_{}".format(fk_column, os.urandom(6).hex()) - # Populate the lookup table with all of the extracted unique values - lookup_columns_definition = { - (rename.get(col) or col): typ - for col, typ in self.columns_dict.items() - if col in columns - } - if lookup_table.exists(): - if not set(lookup_columns_definition.items()).issubset( - lookup_table.columns_dict.items() - ): - raise InvalidColumns( - "Lookup table {} already exists but does not have columns {}".format( - table, lookup_columns_definition + # Populate the lookup table with all of the extracted unique values + lookup_columns_definition = { + (rename.get(col) or col): typ + for col, typ in self.columns_dict.items() + if col in columns + } + if lookup_table.exists(): + if not set(lookup_columns_definition.items()).issubset( + lookup_table.columns_dict.items() + ): + raise InvalidColumns( + "Lookup table {} already exists but does not have columns {}".format( + table, lookup_columns_definition + ) ) - ) - else: - lookup_table.create( - { - **{ - "id": int, - }, - **lookup_columns_definition, - }, - pk="id", - ) - lookup_columns = [(rename.get(col) or col) for col in columns] - lookup_table.create_index(lookup_columns, unique=True, if_not_exists=True) - self.db.execute( - "INSERT OR IGNORE INTO [{lookup_table}] ({lookup_columns}) SELECT DISTINCT {table_cols} FROM [{table}]".format( - lookup_table=table, - lookup_columns=", ".join("[{}]".format(c) for c in lookup_columns), - table_cols=", ".join("[{}]".format(c) for c in columns), - table=self.name, - ) - ) - - # Now add the new fk_column - self.add_column(magic_lookup_column, int) - - # And populate it - self.db.execute( - "UPDATE [{table}] SET [{magic_lookup_column}] = (SELECT id FROM [{lookup_table}] WHERE {where})".format( - table=self.name, - magic_lookup_column=magic_lookup_column, - lookup_table=table, - where=" AND ".join( - "[{table}].[{column}] IS [{lookup_table}].[{lookup_column}]".format( - table=self.name, - lookup_table=table, - column=column, - lookup_column=rename.get(column) or column, - ) - for column in columns - ), - ) - ) - # Figure out the right column order - column_order = [] - for c in self.columns: - if c.name in columns and magic_lookup_column not in column_order: - column_order.append(magic_lookup_column) - elif c.name == magic_lookup_column: - continue else: - column_order.append(c.name) + lookup_table.create( + { + **{ + "id": int, + }, + **lookup_columns_definition, + }, + pk="id", + ) + lookup_columns = [(rename.get(col) or col) for col in columns] + lookup_table.create_index(lookup_columns, unique=True, if_not_exists=True) + # Rows where every extracted column is null are left alone - they + # get a null foreign key and no lookup table record, see #186 + all_columns_are_null = " AND ".join( + "{} IS NULL".format(quote_identifier(c)) for c in columns + ) + # INSERT OR IGNORE dedupes against the unique index, but unique + # indexes treat NULLs as distinct - the NOT EXISTS guard uses IS + # comparison so NULL-containing rows match existing lookup rows + # instead of being inserted again + already_in_lookup = " AND ".join( + "{lookup}.{lookup_col} IS {source}.{source_col}".format( + lookup=quote_identifier(table), + lookup_col=quote_identifier(rename.get(column) or column), + source=quote_identifier(self.name), + source_col=quote_identifier(column), + ) + for column in columns + ) + self.db.execute( + "INSERT OR IGNORE INTO {} ({lookup_columns}) SELECT DISTINCT {table_cols} FROM {} " + "WHERE NOT ({all_null}) AND NOT EXISTS (SELECT 1 FROM {lookup} WHERE {already_in_lookup})".format( + quote_identifier(table), + quote_identifier(self.name), + lookup_columns=", ".join( + quote_identifier(c) for c in lookup_columns + ), + table_cols=", ".join(quote_identifier(c) for c in columns), + all_null=all_columns_are_null, + lookup=quote_identifier(table), + already_in_lookup=already_in_lookup, + ) + ) - # Drop the unnecessary columns and rename lookup column - self.transform( - drop=set(columns), - rename={magic_lookup_column: fk_column}, - column_order=column_order, - ) + # Now add the new fk_column + self.add_column(magic_lookup_column, int) - # And add the foreign key constraint - self.add_foreign_key(fk_column, table, "id") + # And populate it + self.db.execute( + "UPDATE {} SET {} = (SELECT id FROM {} WHERE {where}) WHERE NOT ({all_null})".format( + quote_identifier(self.name), + quote_identifier(magic_lookup_column), + quote_identifier(table), + where=" AND ".join( + "{}.{} IS {}.{}".format( + quote_identifier(self.name), + quote_identifier(column), + quote_identifier(table), + quote_identifier(rename.get(column) or column), + ) + for column in columns + ), + all_null=all_columns_are_null, + ) + ) + # Figure out the right column order + column_order = [] + for c in self.columns: + if c.name in columns and magic_lookup_column not in column_order: + column_order.append(magic_lookup_column) + elif c.name == magic_lookup_column: + continue + else: + column_order.append(c.name) + + # Drop the unnecessary columns and rename lookup column + self.transform( + drop=set(columns), + rename={magic_lookup_column: fk_column}, + column_order=column_order, + ) + + # And add the foreign key constraint + self.add_foreign_key(fk_column, table, "id") return self def create_index( @@ -2080,10 +3080,9 @@ class Table(Queryable): columns_sql = [] for column in columns: if isinstance(column, DescIndex): - fmt = "[{}] desc" + columns_sql.append("{} desc".format(quote_identifier(column))) else: - fmt = "[{}]" - columns_sql.append(fmt.format(column)) + columns_sql.append(quote_identifier(column)) suffix = None created_index_name = None @@ -2092,16 +3091,14 @@ class Table(Queryable): "{}_{}".format(index_name, suffix) if suffix else index_name ) sql = ( - textwrap.dedent( - """ - CREATE {unique}INDEX {if_not_exists}[{index_name}] - ON [{table_name}] ({columns}); - """ - ) + textwrap.dedent(""" + CREATE {unique}INDEX {if_not_exists}{index_name} + ON {table_name} ({columns}); + """) .strip() .format( - index_name=created_index_name, - table_name=self.name, + index_name=quote_identifier(created_index_name), + table_name=quote_identifier(self.name), columns=", ".join(columns_sql), unique="UNIQUE " if unique else "", if_not_exists="IF NOT EXISTS " if if_not_exists else "", @@ -2129,6 +3126,22 @@ class Table(Queryable): self.db.analyze(created_index_name) return self + def drop_index(self, index_name: str, ignore: bool = False): + """ + Drop an index on this table. + + :param index_name: Name of the index to drop + :param ignore: Set to ``True`` to ignore the error if the index does not exist + """ + if index_name not in {index.name for index in self.indexes}: + if ignore: + return self + raise OperationalError( + "No index named {} on table {}".format(index_name, self.name) + ) + self.db.execute("DROP INDEX {}".format(quote_identifier(index_name))) + return self + def add_column( self, col_name: str, @@ -2153,11 +3166,15 @@ class Table(Queryable): raise AlterError("table '{}' does not exist".format(fk)) # if fk_col specified, must be a valid column if fk_col is not None: + fk_col = resolve_casing(fk_col, self.db[fk].columns_dict) if fk_col not in self.db[fk].columns_dict: raise AlterError("table '{}' has no column {}".format(fk, fk_col)) else: # automatically set fk_col to first primary_key of fk table - pks = [c for c in self.db[fk].columns if c.is_pk] + pks = sorted( + (c for c in self.db[fk].columns if c.is_pk), + key=lambda c: c.is_pk, + ) if pks: fk_col = pks[0].name fk_col_type = pks[0].type @@ -2171,9 +3188,9 @@ class Table(Queryable): not_null_sql = "NOT NULL DEFAULT {}".format( self.db.quote_default_value(not_null_default) ) - sql = "ALTER TABLE [{table}] ADD COLUMN [{col_name}] {col_type}{not_null_default};".format( - table=self.name, - col_name=col_name, + sql = "ALTER TABLE {} ADD COLUMN {} {col_type}{not_null_default};".format( + quote_identifier(self.name), + quote_identifier(col_name), col_type=fk_col_type or COLUMN_TYPE_MAPPING[col_type], not_null_default=(" " + not_null_sql) if not_null_sql else "", ) @@ -2182,14 +3199,14 @@ class Table(Queryable): self.add_foreign_key(col_name, fk, fk_col) return self - def drop(self, ignore: bool = False): + def drop(self, ignore: bool = False) -> None: """ Drop this table. :param ignore: Set to ``True`` to ignore the error if the table does not exist """ try: - self.db.execute("DROP TABLE [{}]".format(self.name)) + self.db.execute("DROP TABLE {}".format(quote_identifier(self.name))) except sqlite3.OperationalError: if not ignore: raise @@ -2226,7 +3243,7 @@ class Table(Queryable): ) ) - def guess_foreign_column(self, other_table: str): + def guess_foreign_column(self, other_table: str) -> str: pks = [c for c in self.db[other_table].columns if c.is_pk] if len(pks) != 1: raise BadPrimaryKey( @@ -2237,101 +3254,159 @@ class Table(Queryable): def add_foreign_key( self, - column: str, + column: ForeignKeyColumns, other_table: Optional[str] = None, - other_column: Optional[str] = None, + other_column: Optional[ForeignKeyColumns] = None, ignore: bool = False, + on_delete: str = "NO ACTION", + on_update: str = "NO ACTION", ): """ Alter the schema to mark the specified column as a foreign key to another table. - :param column: The column to mark as a foreign key. + :param column: The column to mark as a foreign key - use a tuple of columns + for a compound foreign key. :param other_table: The table it refers to - if omitted, will be guessed based on the column name. :param other_column: The column on the other table it - if omitted, will be guessed. + Use a tuple of columns for a compound foreign key. :param ignore: Set this to ``True`` to ignore an existing foreign key - otherwise a ``AlterError`` will be raised. + :param on_delete: ``ON DELETE`` action for the foreign key, e.g. ``"CASCADE"`` + or ``"SET NULL"``. + :param on_update: ``ON UPDATE`` action for the foreign key. """ - # Ensure column exists - if column not in self.columns_dict: - raise AlterError("No such column: {}".format(column)) + columns = (column,) if isinstance(column, str) else tuple(column) + columns = tuple(resolve_casing(c, self.columns_dict) for c in columns) + # Ensure columns exist + for col in columns: + if col not in self.columns_dict: + raise AlterError("No such column: {}".format(col)) # If other_table is not specified, attempt to guess it from the column if other_table is None: - other_table = self.guess_foreign_table(column) + if len(columns) > 1: + raise ValueError( + "other_table must be specified for a compound foreign key" + ) + other_table = self.guess_foreign_table(columns[0]) # If other_column is not specified, detect the primary key on other_table if other_column is None: - other_column = self.guess_foreign_column(other_table) + if len(columns) > 1: + other_columns = tuple(self.db.table(other_table).pks) + else: + other_columns = (self.guess_foreign_column(other_table),) + elif isinstance(other_column, str): + other_columns = (other_column,) + else: + other_columns = tuple(other_column) + other_columns = tuple( + resolve_casing(c, self.db[other_table].columns_dict) for c in other_columns + ) + if len(columns) != len(other_columns): + raise ValueError( + "Compound foreign key must have the same number of columns " + "on both sides" + ) - # Soundness check that the other column exists - if ( - not [c for c in self.db[other_table].columns if c.name == other_column] - and other_column != "rowid" - ): - raise AlterError("No such column: {}.{}".format(other_table, other_column)) + # Soundness check that the other columns exist + for other_col in other_columns: + if ( + not [c for c in self.db[other_table].columns if c.name == other_col] + and other_col != "rowid" + ): + raise AlterError("No such column: {}.{}".format(other_table, other_col)) # Check we do not already have an existing foreign key if any( fk for fk in self.foreign_keys - if fk.column == column - and fk.other_table == other_table - and fk.other_column == other_column + if tuple(fold_identifier_case(c) for c in fk.columns) + == tuple(fold_identifier_case(c) for c in columns) + and fold_identifier_case(fk.other_table) + == fold_identifier_case(other_table) + and tuple(fold_identifier_case(c) for c in fk.other_columns) + == tuple(fold_identifier_case(c) for c in other_columns) ): if ignore: return self else: raise AlterError( "Foreign key already exists for {} => {}.{}".format( - column, other_table, other_column + ", ".join(columns), other_table, ", ".join(other_columns) ) ) - self.db.add_foreign_keys([(self.name, column, other_table, other_column)]) + if len(columns) == 1: + fk_object = ForeignKey( + self.name, + columns[0], + other_table, + other_columns[0], + on_delete=on_delete, + on_update=on_update, + ) + else: + fk_object = ForeignKey( + self.name, + None, + other_table, + None, + columns=columns, + other_columns=other_columns, + is_compound=True, + on_delete=on_delete, + on_update=on_update, + ) + self.db.add_foreign_keys([fk_object]) return self - def enable_counts(self): + def enable_counts(self) -> None: """ Set up triggers to update a cache of the count of rows in this table. See :ref:`python_api_cached_table_counts` for details. """ sql = ( - textwrap.dedent( - """ + textwrap.dedent(""" {create_counts_table} - CREATE TRIGGER IF NOT EXISTS [{table}{counts_table}_insert] AFTER INSERT ON [{table}] + CREATE TRIGGER IF NOT EXISTS {trigger_insert} AFTER INSERT ON {table} BEGIN - INSERT OR REPLACE INTO [{counts_table}] + INSERT OR REPLACE INTO {counts_table} VALUES ( {table_quoted}, COALESCE( - (SELECT count FROM [{counts_table}] WHERE [table] = {table_quoted}), + (SELECT count FROM {counts_table} WHERE "table" = {table_quoted}), 0 ) + 1 ); END; - CREATE TRIGGER IF NOT EXISTS [{table}{counts_table}_delete] AFTER DELETE ON [{table}] + CREATE TRIGGER IF NOT EXISTS {trigger_delete} AFTER DELETE ON {table} BEGIN - INSERT OR REPLACE INTO [{counts_table}] + INSERT OR REPLACE INTO {counts_table} VALUES ( {table_quoted}, COALESCE( - (SELECT count FROM [{counts_table}] WHERE [table] = {table_quoted}), + (SELECT count FROM {counts_table} WHERE "table" = {table_quoted}), 0 ) - 1 ); END; - INSERT OR REPLACE INTO _counts VALUES ({table_quoted}, (select count(*) from [{table}])); - """ - ) + INSERT OR REPLACE INTO _counts VALUES ({table_quoted}, (select count(*) from {table})); + """) .strip() .format( create_counts_table=_COUNTS_TABLE_CREATE_SQL.format( self.db._counts_table_name ), - counts_table=self.db._counts_table_name, - table=self.name, + counts_table=quote_identifier(self.db._counts_table_name), + table=quote_identifier(self.name), table_quoted=self.db.quote(self.name), + trigger_insert=quote_identifier( + self.name + self.db._counts_table_name + "_insert" + ), + trigger_delete=quote_identifier( + self.name + self.db._counts_table_name + "_delete" + ), ) ) - with self.db.conn: - self.db.conn.executescript(sql) + with self.db.atomic(): + self.db._executescript(sql) self.db.use_counts_table = True @property @@ -2365,18 +3440,17 @@ class Table(Queryable): :param replace: Should any existing FTS index for this table be replaced by the new one? """ create_fts_sql = ( - textwrap.dedent( - """ - CREATE VIRTUAL TABLE [{table}_fts] USING {fts_version} ( + textwrap.dedent(""" + CREATE VIRTUAL TABLE {table_fts} USING {fts_version} ( {columns},{tokenize} - content=[{table}] - ) - """ + content={table} ) + """) .strip() .format( - table=self.name, - columns=", ".join("[{}]".format(c) for c in columns), + table=quote_identifier(self.name), + table_fts=quote_identifier(self.name + "_fts"), + columns=", ".join(quote_identifier(c) for c in columns), fts_version=fts_version, tokenize="\n tokenize='{}',".format(tokenize) if tokenize else "", ) @@ -2403,27 +3477,32 @@ class Table(Queryable): self.populate_fts(columns) if create_triggers: - old_cols = ", ".join("old.[{}]".format(c) for c in columns) - new_cols = ", ".join("new.[{}]".format(c) for c in columns) + old_cols = ", ".join("old.{}".format(quote_identifier(c)) for c in columns) + new_cols = ", ".join("new.{}".format(quote_identifier(c)) for c in columns) + columns_quoted = ", ".join(quote_identifier(c) for c in columns) + table = quote_identifier(self.name) + table_fts = quote_identifier(self.name + "_fts") triggers = ( - textwrap.dedent( - """ - CREATE TRIGGER [{table}_ai] AFTER INSERT ON [{table}] BEGIN - INSERT INTO [{table}_fts] (rowid, {columns}) VALUES (new.rowid, {new_cols}); + textwrap.dedent(""" + CREATE TRIGGER {table_ai} AFTER INSERT ON {table} BEGIN + INSERT INTO {table_fts} (rowid, {columns}) VALUES (new.rowid, {new_cols}); END; - CREATE TRIGGER [{table}_ad] AFTER DELETE ON [{table}] BEGIN - INSERT INTO [{table}_fts] ([{table}_fts], rowid, {columns}) VALUES('delete', old.rowid, {old_cols}); + CREATE TRIGGER {table_ad} AFTER DELETE ON {table} BEGIN + INSERT INTO {table_fts} ({table_fts}, rowid, {columns}) VALUES('delete', old.rowid, {old_cols}); END; - CREATE TRIGGER [{table}_au] AFTER UPDATE ON [{table}] BEGIN - INSERT INTO [{table}_fts] ([{table}_fts], rowid, {columns}) VALUES('delete', old.rowid, {old_cols}); - INSERT INTO [{table}_fts] (rowid, {columns}) VALUES (new.rowid, {new_cols}); + CREATE TRIGGER {table_au} AFTER UPDATE ON {table} BEGIN + INSERT INTO {table_fts} ({table_fts}, rowid, {columns}) VALUES('delete', old.rowid, {old_cols}); + INSERT INTO {table_fts} (rowid, {columns}) VALUES (new.rowid, {new_cols}); END; - """ - ) + """) .strip() .format( - table=self.name, - columns=", ".join("[{}]".format(c) for c in columns), + table=table, + table_fts=table_fts, + table_ai=quote_identifier(self.name + "_ai"), + table_ad=quote_identifier(self.name + "_ad"), + table_au=quote_identifier(self.name + "_au"), + columns=columns_quoted, old_cols=old_cols, new_cols=new_cols, ) @@ -2438,16 +3517,17 @@ class Table(Queryable): :param columns: Columns to populate the data for """ + columns_quoted = ", ".join(quote_identifier(c) for c in columns) sql = ( - textwrap.dedent( - """ - INSERT INTO [{table}_fts] (rowid, {columns}) - SELECT rowid, {columns} FROM [{table}]; - """ - ) + textwrap.dedent(""" + INSERT INTO {table_fts} (rowid, {columns}) + SELECT rowid, {columns} FROM {table}; + """) .strip() .format( - table=self.name, columns=", ".join("[{}]".format(c) for c in columns) + table=quote_identifier(self.name), + table_fts=quote_identifier(self.name + "_fts"), + columns=columns_quoted, ) ) self.db.executescript(sql) @@ -2459,42 +3539,38 @@ class Table(Queryable): if fts_table: self.db[fts_table].drop() # Now delete the triggers that related to that table - sql = ( - textwrap.dedent( - """ + sql = textwrap.dedent(""" SELECT name FROM sqlite_master WHERE type = 'trigger' - AND sql LIKE '% INSERT INTO [{}]%' - """ - ) - .strip() - .format(fts_table) - ) + AND (sql LIKE '% INSERT INTO [{}]%' OR sql LIKE '% INSERT INTO "{}"%') + """).strip().format(fts_table, fts_table) trigger_names = [] for row in self.db.execute(sql).fetchall(): trigger_names.append(row[0]) - with self.db.conn: + with self.db.atomic(): for trigger_name in trigger_names: - self.db.execute("DROP TRIGGER IF EXISTS [{}]".format(trigger_name)) + self.db.execute( + "DROP TRIGGER IF EXISTS {}".format(quote_identifier(trigger_name)) + ) return self - def rebuild_fts(self): + def rebuild_fts(self) -> "Table": "Run the ``rebuild`` operation against the associated full-text search index table." fts_table = self.detect_fts() if fts_table is None: # Assume this is itself an FTS table fts_table = self.name - self.db.execute( - "INSERT INTO [{table}]([{table}]) VALUES('rebuild');".format( - table=fts_table + with self.db.atomic(): + self.db.execute( + "INSERT INTO {table}({table}) VALUES('rebuild');".format( + table=quote_identifier(fts_table) + ) ) - ) return self def detect_fts(self) -> Optional[str]: "Detect if table has a corresponding FTS virtual table and return it" - sql = textwrap.dedent( - """ + sql = textwrap.dedent(""" SELECT name FROM sqlite_master WHERE rootpage = 0 AND ( @@ -2505,8 +3581,7 @@ class Table(Queryable): AND sql LIKE '%VIRTUAL TABLE%USING FTS%' ) ) - """ - ).strip() + """).strip() args = { "like": "%VIRTUAL TABLE%USING FTS%content=[{}]%".format(self.name), "like2": '%VIRTUAL TABLE%USING FTS%content="{}"%'.format(self.name), @@ -2522,13 +3597,10 @@ class Table(Queryable): "Run the ``optimize`` operation against the associated full-text search index table." fts_table = self.detect_fts() if fts_table is not None: - self.db.execute( - """ - INSERT INTO [{table}] ([{table}]) VALUES ("optimize"); - """.strip().format( - table=fts_table - ) - ) + with self.db.atomic(): + self.db.execute(""" + INSERT INTO {table} ({table}) VALUES ("optimize"); + """.strip().format(table=quote_identifier(fts_table))) return self def search_sql( @@ -2552,44 +3624,45 @@ class Table(Queryable): """ # Pick names for table and rank column that don't clash original = "original_" if self.name == "original" else "original" + original_quoted = quote_identifier(original) columns_sql = "*" - columns_with_prefix_sql = "[{}].*".format(original) + columns_with_prefix_sql = "{}.*".format(original_quoted) if columns: - columns_sql = ",\n ".join("[{}]".format(c) for c in columns) + columns_sql = ",\n ".join(quote_identifier(c) for c in columns) columns_with_prefix_sql = ",\n ".join( - "[{}].[{}]".format(original, c) for c in columns + "{}.{}".format(original_quoted, quote_identifier(c)) for c in columns ) fts_table = self.detect_fts() - assert fts_table, "Full-text search is not configured for table '{}'".format( - self.name - ) - virtual_table_using = self.db[fts_table].virtual_table_using - sql = textwrap.dedent( - """ + if not fts_table: + raise ValueError( + "Full-text search is not configured for table '{}'".format(self.name) + ) + fts_table_quoted = quote_identifier(fts_table) + virtual_table_using = self.db.table(fts_table).virtual_table_using + sql = textwrap.dedent(""" with {original} as ( select rowid, {columns} - from [{dbtable}]{where_clause} + from {dbtable}{where_clause} ) select {columns_with_prefix} from - [{original}] - join [{fts_table}] on [{original}].rowid = [{fts_table}].rowid + {original} + join {fts_table} on {original}.rowid = {fts_table}.rowid where - [{fts_table}] match :query + {fts_table} match :query order by {order_by} {limit_offset} - """ - ).strip() + """).strip() if virtual_table_using == "FTS5": - rank_implementation = "[{}].rank".format(fts_table) + rank_implementation = "{}.rank".format(fts_table_quoted) else: self.db.register_fts4_bm25() - rank_implementation = "rank_bm25(matchinfo([{}], 'pcnalx'))".format( - fts_table + rank_implementation = "rank_bm25(matchinfo({}, 'pcnalx'))".format( + fts_table_quoted ) if include_rank: columns_with_prefix_sql += ",\n " + rank_implementation + " rank" @@ -2599,12 +3672,12 @@ class Table(Queryable): if offset is not None: limit_offset += " offset {}".format(offset) return sql.format( - dbtable=self.name, + dbtable=quote_identifier(self.name), where_clause="\n where {}".format(where) if where else "", - original=original, + original=original_quoted, columns=columns_sql, columns_with_prefix=columns_with_prefix_sql, - fts_table=fts_table, + fts_table=fts_table_quoted, order_by=order_by or rank_implementation, limit_offset=limit_offset.strip(), ).strip() @@ -2618,6 +3691,7 @@ class Table(Queryable): offset: Optional[int] = None, where: Optional[str] = None, where_args: Optional[Union[Iterable, dict]] = None, + include_rank: bool = False, quote: bool = False, ) -> Generator[dict, None, None]: """ @@ -2631,6 +3705,7 @@ class Table(Queryable): :param offset: Optional integer SQL offset. :param where: Extra SQL fragment for the WHERE clause :param where_args: Arguments to use for :param placeholders in the extra WHERE clause + :param include_rank: Select the search rank column in the final query :param quote: Apply quoting to disable any special characters in the search query See :ref:`python_api_fts_search`. @@ -2650,14 +3725,15 @@ class Table(Queryable): limit=limit, offset=offset, where=where, + include_rank=include_rank, ), args, ) - columns = [c[0] for c in cursor.description] + columns = dedupe_keys(c[0] for c in cursor.description) for row in cursor: yield dict(zip(columns, row)) - def value_or_default(self, key, value): + def value_or_default(self, key: str, value: Any) -> Any: return self._defaults[key] if value is DEFAULT else value def delete(self, pk_values: Union[list, tuple, str, int, float]) -> "Table": @@ -2669,18 +3745,18 @@ class Table(Queryable): if not isinstance(pk_values, (list, tuple)): pk_values = [pk_values] self.get(pk_values) - wheres = ["[{}] = ?".format(pk_name) for pk_name in self.pks] - sql = "delete from [{table}] where {wheres}".format( - table=self.name, wheres=" and ".join(wheres) + wheres = ["{} = ?".format(quote_identifier(pk_name)) for pk_name in self.pks] + sql = "delete from {} where {wheres}".format( + quote_identifier(self.name), wheres=" and ".join(wheres) ) - with self.db.conn: + with self.db.atomic(): self.db.execute(sql, pk_values) return self def delete_where( self, where: Optional[str] = None, - where_args: Optional[Union[Iterable, dict]] = None, + where_args: Optional[Union[Sequence, Dict[str, Any]]] = None, analyze: bool = False, ) -> "Table": """ @@ -2695,10 +3771,11 @@ class Table(Queryable): """ if not self.exists(): return self - sql = "delete from [{}]".format(self.name) + sql = "delete from {}".format(quote_identifier(self.name)) if where is not None: sql += " where " + where - self.db.execute(sql, where_args or []) + with self.db.atomic(): + self.db.execute(sql, where_args or []) if analyze: self.analyze() return self @@ -2734,16 +3811,19 @@ class Table(Queryable): sets = [] wheres = [] pks = self.pks - validate_column_names(updates.keys()) for key, value in updates.items(): - sets.append("[{}] = {}".format(key, conversions.get(key, "?"))) + sets.append( + "{} = {}".format(quote_identifier(key), conversions.get(key, "?")) + ) args.append(jsonify_if_needed(value)) - wheres = ["[{}] = ?".format(pk_name) for pk_name in pks] + wheres = ["{} = ?".format(quote_identifier(pk_name)) for pk_name in pks] args.extend(pk_values) - sql = "update [{table}] set {sets} where {wheres}".format( - table=self.name, sets=", ".join(sets), wheres=" and ".join(wheres) + sql = "update {} set {sets} where {wheres}".format( + quote_identifier(self.name), + sets=", ".join(sets), + wheres=" and ".join(wheres), ) - with self.db.conn: + with self.db.atomic(): try: rowcount = self.db.execute(sql, args).rowcount except OperationalError as e: @@ -2768,10 +3848,9 @@ class Table(Queryable): drop: bool = False, multi: bool = False, where: Optional[str] = None, - where_args: Optional[Union[Iterable, dict]] = None, + where_args: Optional[Union[Sequence, Dict[str, Any]]] = None, show_progress: bool = False, - skip_false: bool = True, - ): + ) -> "Table": """ Apply conversion function ``fn`` to every value in the specified columns. @@ -2792,6 +3871,7 @@ class Table(Queryable): """ if isinstance(columns, str): columns = [columns] + columns = [resolve_casing(c, self.columns_dict) for c in columns] if multi: return self._convert_multi( @@ -2804,7 +3884,9 @@ class Table(Queryable): ) if output is not None: - assert len(columns) == 1, "output= can only be used with a single column" + if len(columns) != 1: + raise ValueError("output= can only be used with a single column") + output = resolve_casing(output, self.columns_dict) if output not in self.columns_dict: self.add_column(output, output_type or "text") @@ -2813,29 +3895,27 @@ class Table(Queryable): def convert_value(v): bar.update(1) - if skip_false and not v: - return v return jsonify_if_needed(fn(v)) - fn_name = fn.__name__ + fn_name = getattr(fn, "__name__", "fn") if fn_name == "": fn_name = f"lambda_{abs(hash(fn))}" self.db.register_function(convert_value, name=fn_name) - sql = "update [{table}] set {sets}{where};".format( - table=self.name, + sql = "update {} set {sets}{where};".format( + quote_identifier(self.name), sets=", ".join( [ - "[{output_column}] = {fn_name}([{column}])".format( - output_column=output or column, - column=column, - fn_name=fn_name, + "{} = {}({})".format( + quote_identifier(output or column), + fn_name, + quote_identifier(column), ) for column in columns ] ), where=" where {}".format(where) if where is not None else "", ) - with self.db.conn: + with self.db.atomic(): self.db.execute(sql, where_args or []) if drop: self.transform(drop=columns) @@ -2846,17 +3926,15 @@ class Table(Queryable): ): # First we execute the function pk_to_values = {} - new_column_types = {} - pks = [column.name for column in self.columns if column.is_pk] - if not pks: - pks = ["rowid"] + new_column_types: Dict[str, Set[type]] = {} + pks = self.pks with progressbar( length=self.count, silent=not show_progress, label="1: Evaluating" ) as bar: for row in self.rows_where( select=", ".join( - "[{}]".format(column_name) for column_name in (pks + [column]) + quote_identifier(column_name) for column_name in (pks + [column]) ), where=where, where_args=where_args, @@ -2883,7 +3961,7 @@ class Table(Queryable): with progressbar( length=self.count, silent=not show_progress, label="2: Updating" ) as bar: - with self.db.conn: + with self.db.atomic(): for pk, updates in pk_to_values.items(): self.update(pk, updates) bar.update(1) @@ -2904,101 +3982,207 @@ class Table(Queryable): num_records_processed, replace, ignore, + list_mode=False, ): - # values is the list of insert data that is passed to the - # .execute() method - but some of them may be replaced by - # new primary keys if we are extracting any columns. - values = [] + """ + Given a list ``chunk`` of records that should be written to *this* table, + return a list of ``(sql, parameters)`` 2-tuples which, when executed in + order, perform the desired INSERT / UPSERT / REPLACE operation. + """ + # Dict-mode insert({}) has no explicit columns; SQLite spells that as + # DEFAULT VALUES. List mode with no columns is a different input shape. + if not list_mode and not all_columns: + if upsert: + raise PrimaryKeyRequired( + "upsert() requires a value for the primary key - " + "an empty record cannot be upserted" + ) + or_clause = "" + if replace: + or_clause = " OR REPLACE" + elif ignore: + or_clause = " OR IGNORE" + sql = ( + f"INSERT{or_clause} INTO {quote_identifier(self.name)} " + "DEFAULT VALUES" + ) + return [(sql, []) for _ in chunk] + if hash_id_columns and hash_id is None: hash_id = "id" + extracts = resolve_extracts(extracts) - for record in chunk: - record_values = [] - for key in all_columns: - value = jsonify_if_needed( - record.get( - key, - None - if key != hash_id - else hash_record(record, hash_id_columns), + + # Build a row-list ready for executemany-style flattening + values = [] + + if list_mode: + # In list mode, records are already lists of values + num_columns = len(all_columns) + has_extracts = bool(extracts) + for record in chunk: + # Pad short records with None, truncate long ones + record_len = len(record) + if record_len < num_columns: + record_values = [jsonify_if_needed(v) for v in record] + [None] * ( + num_columns - record_len + ) + else: + record_values = [jsonify_if_needed(v) for v in record[:num_columns]] + # Only process extracts if there are any + if has_extracts: + for i, key in enumerate(all_columns): + if key in extracts and record_values[i] is not None: + record_values[i] = self.db.table(extracts[key]).lookup( + {"value": record_values[i]} + ) + values.append(record_values) + else: + # Dict mode: original logic + for record in chunk: + record_values = [] + for key in all_columns: + value = jsonify_if_needed( + record.get( + key, + ( + None + if key != hash_id + else hash_record(record, hash_id_columns) + ), + ) + ) + if key in extracts and value is not None: + extract_table = extracts[key] + value = self.db.table(extract_table).lookup({"value": value}) + record_values.append(value) + values.append(record_values) + + columns_sql = ", ".join(quote_identifier(c) for c in all_columns) + placeholder_expr = ", ".join(conversions.get(c, "?") for c in all_columns) + row_placeholders_sql = ", ".join(f"({placeholder_expr})" for _ in values) + flat_params = list(itertools.chain.from_iterable(values)) + + # replace=True mean INSERT OR REPLACE INTO + if replace: + sql = ( + f"INSERT OR REPLACE INTO {quote_identifier(self.name)} " + f"({columns_sql}) VALUES {row_placeholders_sql}" + ) + return [(sql, flat_params)] + + # If not an upsert it's an INSERT, maybe with OR IGNORE + if not upsert: + or_ignore = "" + if ignore: + or_ignore = " OR IGNORE" + sql = ( + f"INSERT{or_ignore} INTO {quote_identifier(self.name)} " + f"({columns_sql}) VALUES {row_placeholders_sql}" + ) + return [(sql, flat_params)] + + # Everything from here on is for upsert=True + pk_cols = [pk] if isinstance(pk, str) else list(pk) + # The records may use different casing for the pk columns than pk= + pk_cols = [resolve_casing(c, all_columns) for c in pk_cols] + # Every record must provide a value for every primary key column - a + # NULL primary key never matches ON CONFLICT, so the record would be + # inserted as a brand new row instead of upserted + missing_pk_cols = [c for c in pk_cols if c not in all_columns] + if missing_pk_cols: + raise PrimaryKeyRequired( + "upsert() requires a value for the primary key column{}: {}".format( + "s" if len(missing_pk_cols) > 1 else "", + ", ".join(missing_pk_cols), + ) + ) + pk_indexes = [all_columns.index(c) for c in pk_cols] + for record_values in values: + if any(record_values[i] is None for i in pk_indexes): + raise PrimaryKeyRequired( + "upsert() requires a value for the primary key column{}: {}".format( + "s" if len(pk_cols) > 1 else "", + ", ".join(pk_cols), ) ) - if key in extracts: - extract_table = extracts[key] - value = self.db[extract_table].lookup({"value": value}) - record_values.append(value) - values.append(record_values) + non_pk_cols = [c for c in all_columns if c not in pk_cols] + conflict_sql = ", ".join(quote_identifier(c) for c in pk_cols) - queries_and_params = [] - if upsert: - if isinstance(pk, str): - pks = [pk] + if self.db.supports_on_conflict and not self.db.use_old_upsert: + if non_pk_cols: + # DO UPDATE + assignments = [] + for c in non_pk_cols: + c_quoted = quote_identifier(c) + if c in conversions: + assignments.append( + f"{c_quoted} = {conversions[c].replace('?', f'excluded.{c_quoted}')}" + ) + else: + assignments.append(f"{c_quoted} = excluded.{c_quoted}") + do_clause = "DO UPDATE SET " + ", ".join(assignments) else: - pks = pk - self.last_pk = None - for record_values in values: - record = dict(zip(all_columns, record_values)) - placeholders = list(pks) - # Need to populate not-null columns too, or INSERT OR IGNORE ignores - # them since it ignores the resulting integrity errors - if not_null: - placeholders.extend(not_null) - sql = "INSERT OR IGNORE INTO [{table}]({cols}) VALUES({placeholders});".format( - table=self.name, - cols=", ".join(["[{}]".format(p) for p in placeholders]), + # All columns are in the PK – nothing to update. + do_clause = "DO NOTHING" + + sql = ( + f"INSERT INTO {quote_identifier(self.name)} ({columns_sql}) " + f"VALUES {row_placeholders_sql} " + f"ON CONFLICT({conflict_sql}) {do_clause}" + ) + return [(sql, flat_params)] + + # At this point we need compatibility UPSERT for SQLite < 3.24.0 + # (INSERT OR IGNORE + second UPDATE stage) + queries_and_params = [] + pks = pk_cols + self.last_pk = None + for record_values in values: + record = dict(zip(all_columns, record_values)) + placeholders = list(pks) + # Need to populate not-null columns too, or INSERT OR IGNORE ignores + # them since it ignores the resulting integrity errors + if not_null: + placeholders.extend(not_null) + sql = ( + "INSERT OR IGNORE INTO {table}({cols}) VALUES({placeholders});".format( + table=quote_identifier(self.name), + cols=", ".join([quote_identifier(p) for p in placeholders]), placeholders=", ".join(["?" for p in placeholders]), ) - queries_and_params.append( - (sql, [record[col] for col in pks] + ["" for _ in (not_null or [])]) - ) - # UPDATE [book] SET [name] = 'Programming' WHERE [id] = 1001; - set_cols = [col for col in all_columns if col not in pks] - if set_cols: - sql2 = "UPDATE [{table}] SET {pairs} WHERE {wheres}".format( - table=self.name, - pairs=", ".join( - "[{}] = {}".format(col, conversions.get(col, "?")) - for col in set_cols - ), - wheres=" AND ".join("[{}] = ?".format(pk) for pk in pks), - ) - queries_and_params.append( - ( - sql2, - [record[col] for col in set_cols] - + [record[pk] for pk in pks], - ) - ) - # We can populate .last_pk right here - if num_records_processed == 1: - self.last_pk = tuple(record[pk] for pk in pks) - if len(self.last_pk) == 1: - self.last_pk = self.last_pk[0] - - else: - or_what = "" - if replace: - or_what = "OR REPLACE " - elif ignore: - or_what = "OR IGNORE " - sql = """ - INSERT {or_what}INTO [{table}] ({columns}) VALUES {rows}; - """.strip().format( - or_what=or_what, - table=self.name, - columns=", ".join("[{}]".format(c) for c in all_columns), - rows=", ".join( - "({placeholders})".format( - placeholders=", ".join( - [conversions.get(col, "?") for col in all_columns] - ) - ) - for record in chunk - ), ) - flat_values = list(itertools.chain(*values)) - queries_and_params = [(sql, flat_values)] - + queries_and_params.append( + (sql, [record[col] for col in pks] + ["" for _ in (not_null or [])]) + ) + # UPDATE "book" SET "name" = 'Programming' WHERE "id" = 1001; + set_cols = [col for col in all_columns if col not in pks] + if set_cols: + sql2 = "UPDATE {} SET {pairs} WHERE {wheres}".format( + quote_identifier(self.name), + pairs=", ".join( + "{} = {}".format( + quote_identifier(col), conversions.get(col, "?") + ) + for col in set_cols + ), + wheres=" AND ".join( + "{} = ?".format(quote_identifier(pk)) for pk in pks + ), + ) + queries_and_params.append( + ( + sql2, + [record[col] for col in set_cols] + [record[pk] for pk in pks], + ) + ) + # We can populate .last_pk right here + if num_records_processed == 1: + pk_values = tuple(record[pk] for pk in pks) + if len(pk_values) == 1: + self.last_pk = pk_values[0] + else: + self.last_pk = pk_values return queries_and_params def insert_chunk( @@ -3016,7 +4200,8 @@ class Table(Queryable): num_records_processed, replace, ignore, - ): + list_mode=False, + ) -> Optional[sqlite3.Cursor]: queries_and_params = self.build_insert_queries_and_params( extracts, chunk, @@ -3030,10 +4215,10 @@ class Table(Queryable): num_records_processed, replace, ignore, + list_mode, ) - - with self.db.conn: - result = None + result = None + with self.db.atomic(): for query, params in queries_and_params: try: result = self.db.execute(query, params) @@ -3060,9 +4245,10 @@ class Table(Queryable): num_records_processed, replace, ignore, + list_mode, ) - self.insert_chunk( + result = self.insert_chunk( alter, extracts, second_half, @@ -3076,24 +4262,12 @@ class Table(Queryable): num_records_processed, replace, ignore, + list_mode, ) else: raise - if num_records_processed == 1 and not upsert: - self.last_rowid = result.lastrowid - self.last_pk = self.last_rowid - # self.last_rowid will be 0 if a "INSERT OR IGNORE" happened - if (hash_id or pk) and self.last_rowid: - row = list(self.rows_where("rowid = ?", [self.last_rowid]))[0] - if hash_id: - self.last_pk = row[hash_id] - elif isinstance(pk, str): - self.last_pk = row[pk] - else: - self.last_pk = tuple(row[p] for p in pk) - - return + return result def insert( self, @@ -3111,6 +4285,7 @@ class Table(Queryable): extracts: Optional[Union[Dict[str, str], List[str], Default]] = DEFAULT, conversions: Optional[Union[Dict[str, str], Default]] = DEFAULT, columns: Optional[Union[Dict[str, Any], Default]] = DEFAULT, + strict: Optional[Union[bool, Default]] = DEFAULT, ) -> "Table": """ Insert a single record into the table. The table will be created with a schema that matches @@ -3132,7 +4307,7 @@ class Table(Queryable): :param not_null: Set of strings specifying columns that should be ``NOT NULL``. :param defaults: Dictionary specifying default values for specific columns. :param hash_id: Name of a column to create and use as a primary key, where the - value of thet primary key will be derived as a SHA1 hash of the other column values + value of that primary key will be derived as a SHA1 hash of the other column values in the record. ``hash_id="id"`` is a common column name used for this. :param alter: Boolean, should any missing columns be added automatically? :param ignore: Boolean, if a record already exists with this primary key, ignore this insert. @@ -3143,6 +4318,7 @@ class Table(Queryable): is being inserted, for example ``{"name": "upper(?)"}``. See :ref:`python_api_conversions`. :param columns: Dictionary over-riding the detected types used for the columns, for example ``{"age": int, "weight": float}``. + :param strict: Boolean, apply STRICT mode if creating the table. """ return self.insert_all( [record], @@ -3159,11 +4335,15 @@ class Table(Queryable): extracts=extracts, conversions=conversions, columns=columns, + strict=strict, ) def insert_all( self, - records, + records: Union[ + Iterable[Dict[str, Any]], + Iterable[Sequence[Any]], + ], pk=DEFAULT, foreign_keys=DEFAULT, column_order=DEFAULT, @@ -3181,6 +4361,7 @@ class Table(Queryable): columns=DEFAULT, upsert=False, analyze=False, + strict=DEFAULT, ) -> "Table": """ Like ``.insert()`` but takes a list of records and ensures that the table @@ -3202,50 +4383,139 @@ class Table(Queryable): extracts = self.value_or_default("extracts", extracts) conversions = self.value_or_default("conversions", conversions) or {} columns = self.value_or_default("columns", columns) + strict = self.value_or_default("strict", strict) if hash_id_columns and hash_id is None: hash_id = "id" + if upsert and not pk and not hash_id and self.exists(): + existing_pks = [column.name for column in self.columns if column.is_pk] + if existing_pks: + pk = existing_pks[0] if len(existing_pks) == 1 else tuple(existing_pks) + if upsert and (not pk and not hash_id): raise PrimaryKeyRequired("upsert() requires a pk") - assert not (hash_id and pk), "Use either pk= or hash_id=" + + if hash_id and pk: + raise ValueError("Use either pk= or hash_id=") if hash_id_columns and (hash_id is None): hash_id = "id" if hash_id: pk = hash_id - assert not ( - ignore and replace - ), "Use either ignore=True or replace=True, not both" + # pk columns missing from an existing table are an error - unless + # alter=True, where a pk column supplied by the records will be + # added, so validation waits until the record keys are known + deferred_invalid_pk_check = None + if pk and not hash_id and self.exists(): + pk_cols = [pk] if isinstance(pk, str) else list(pk) + existing_columns = self.columns_dict + # rowid and its aliases are valid primary keys for a rowid table + # even though they are not listed among the table's columns + rowid_aliases = ROWID_ALIASES if self.use_rowid else frozenset() + missing_pk_cols = [ + col + for col in pk_cols + if col.lower() not in rowid_aliases + and resolve_casing(col, existing_columns) not in existing_columns + ] + if missing_pk_cols: + invalid_pk_error = InvalidColumns( + "Invalid primary key column{} {} for table {} with columns {}".format( + "s" if len(missing_pk_cols) > 1 else "", + missing_pk_cols, + self.name, + list(existing_columns), + ) + ) + if not alter: + raise invalid_pk_error + deferred_invalid_pk_check = (missing_pk_cols, invalid_pk_error) + + if ignore and replace: + raise ValueError("Use either ignore=True or replace=True, not both") all_columns = [] first = True num_records_processed = 0 - # Fix up any records with square braces in the column names - records = fix_square_braces(records) - # We can only handle a max of 999 variables in a SQL insert, so - # we need to adjust the batch_size down if we have too many cols - records = iter(records) - # Peek at first record to count its columns: + + # Detect if we're using list-based iteration or dict-based iteration + list_mode = False + column_names: List[str] = [] + + # Fix up any records with square braces in the column names (only for dict mode) + # We'll handle this differently for list mode + records_iter = iter(records) + + # Peek at first record to determine mode: try: - first_record = next(records) + first_record = next(records_iter) except StopIteration: return self # It was an empty list - num_columns = len(first_record.keys()) - assert ( - num_columns <= SQLITE_MAX_VARS - ), "Rows can have a maximum of {} columns".format(SQLITE_MAX_VARS) - batch_size = max(1, min(batch_size, SQLITE_MAX_VARS // num_columns)) + + # Check if this is list mode or dict mode + if isinstance(first_record, (list, tuple)): + # List/tuple mode: first record should be column names + list_mode = True + if not all(isinstance(col, str) for col in first_record): + raise ValueError( + "When using list-based iteration, the first yielded value must be a list of column name strings" + ) + column_names = cast(List[str], list(first_record)) + all_columns = column_names + num_columns = len(column_names) + # Get the actual first data record + try: + first_record = next(records_iter) + except StopIteration: + return self # Only headers, no data + if not isinstance(first_record, (list, tuple)): + raise ValueError( + "After column names list, all subsequent records must also be lists" + ) + else: + # Dict mode: traditional behavior + records_iter = itertools.chain([first_record], records_iter) + try: + first_record = next(records_iter) + except StopIteration: + return self + first_record = cast(Dict[str, Any], first_record) + num_columns = len(first_record.keys()) + + if num_columns > SQLITE_MAX_VARS: + raise ValueError( + "Rows can have a maximum of {} columns".format(SQLITE_MAX_VARS) + ) + batch_size = ( + 1 + if num_columns == 0 + else max(1, min(batch_size, SQLITE_MAX_VARS // num_columns)) + ) self.last_rowid = None self.last_pk = None if truncate and self.exists(): - self.db.execute("DELETE FROM [{}];".format(self.name)) - for chunk in chunks(itertools.chain([first_record], records), batch_size): + with self.db.atomic(): + self.db.execute("DELETE FROM {};".format(quote_identifier(self.name))) + result = None + for chunk in chunks(itertools.chain([first_record], records_iter), batch_size): chunk = list(chunk) num_records_processed += len(chunk) if first: if not self.exists(): # Use the first batch to derive the table names - column_types = suggest_column_types(chunk) + if list_mode: + # Convert list records to dicts for type detection + chunk_as_dicts = [dict(zip(column_names, row)) for row in chunk] + column_types = suggest_column_types(chunk_as_dicts) + else: + dict_chunk = cast(List[Dict[str, Any]], chunk) + column_types = suggest_column_types(dict_chunk) + if extracts: + for col in extracts: + if col in column_types: + column_types[col] = ( + int # This will be an integer foreign key + ) column_types.update(columns or {}) self.create( column_types, @@ -3257,22 +4527,40 @@ class Table(Queryable): hash_id=hash_id, hash_id_columns=hash_id_columns, extracts=extracts, + strict=strict, ) - all_columns_set = set() - for record in chunk: - all_columns_set.update(record.keys()) - all_columns = list(sorted(all_columns_set)) - if hash_id: - all_columns.insert(0, hash_id) + if list_mode: + # In list mode, columns are already known + all_columns = list(column_names) + if hash_id: + all_columns.insert(0, hash_id) + else: + all_columns_set: Set[str] = set() + for record in cast(List[Dict[str, Any]], chunk): + all_columns_set.update(record.keys()) + all_columns = list(sorted(all_columns_set)) + if hash_id: + all_columns.insert(0, hash_id) + if deferred_invalid_pk_check is not None: + # alter=True - pk columns the table lacks are valid if + # the records supply them, otherwise raise the error + missing_pk_cols, invalid_pk_error = deferred_invalid_pk_check + record_columns = {column: True for column in all_columns} + if any( + resolve_casing(col, record_columns) not in record_columns + for col in missing_pk_cols + ): + raise invalid_pk_error else: - for record in chunk: - all_columns += [ - column for column in record if column not in all_columns - ] + if not list_mode: + for record in cast(List[Dict[str, Any]], chunk): + all_columns += [ + column for column in record if column not in all_columns + ] first = False - self.insert_chunk( + result = self.insert_chunk( alter, extracts, chunk, @@ -3286,8 +4574,125 @@ class Table(Queryable): num_records_processed, replace, ignore, + list_mode, ) + # If we only handled a single row populate self.last_pk + if num_records_processed == 1: + # For an insert we need to use result.lastrowid + if not upsert and result is not None: + ignored_insert = ignore and result.rowcount == 0 + if ignored_insert: + # The row was not inserted because it conflicts with an + # existing row. Point last_pk / last_rowid at that existing + # row when we can identify it from the record's primary key + # values, rather than leaving them stale or unset. + if list_mode: + first_record_dict = dict( + zip(column_names, cast(Sequence[Any], first_record)) + ) + else: + first_record_dict = cast(Dict[str, Any], first_record) + if hash_id: + self.last_pk = hash_record(first_record_dict, hash_id_columns) + elif isinstance(pk, str): + self.last_pk = first_record_dict[ + resolve_casing(pk, first_record_dict) + ] + elif pk: + self.last_pk = tuple( + first_record_dict[resolve_casing(p, first_record_dict)] + for p in pk + ) + # Locate the existing conflicting row using its primary key + # columns so we can report its rowid (and pk if not already + # known). Falls back to leaving them unset if the conflict + # cannot be resolved to a pk lookup (e.g. a UNIQUE column). + key_cols: Optional[List[str]] = None + if isinstance(pk, str): + key_cols = [pk] + elif pk: + key_cols = list(pk) + elif not hash_id and not self.use_rowid: + key_cols = self.pks + if key_cols: + try: + key_values = [ + first_record_dict[resolve_casing(c, first_record_dict)] + for c in key_cols + ] + except KeyError: + key_values = None + if key_values is not None: + where = " and ".join( + "{} = ?".format(quote_identifier(c)) for c in key_cols + ) + existing = self.db.execute( + "select rowid from {} where {} limit 1".format( + quote_identifier(self.name), where + ), + key_values, + ).fetchone() + if existing is not None: + self.last_rowid = existing[0] + # On a primary key conflict the record's pk + # values identify the existing row + if self.last_pk is None: + self.last_pk = ( + key_values[0] + if len(key_cols) == 1 + else tuple(key_values) + ) + else: + self.last_rowid = result.lastrowid + # A rowid-alias pk resolves directly to the rowid, so there + # is no separate pk column to look up + rowid_pk = isinstance(pk, str) and pk.lower() in ROWID_ALIASES + if (hash_id or (pk and not rowid_pk)) and self.last_rowid: + # Set self.last_pk to the pk(s) for that rowid + row = list(self.rows_where("rowid = ?", [self.last_rowid]))[0] + if hash_id: + self.last_pk = row[hash_id] + elif isinstance(pk, str): + self.last_pk = row[resolve_casing(pk, row)] + else: + self.last_pk = tuple( + row[resolve_casing(p, row)] for p in pk + ) + else: + self.last_pk = self.last_rowid + else: + # For an upsert use first_record from earlier + if list_mode: + # In list mode, look up pk value by column index + first_record_list = cast(Sequence[Any], first_record) + if hash_id: + # hash_id not supported in list mode for last_pk + pass + elif isinstance(pk, str): + pk_index = column_names.index(resolve_casing(pk, column_names)) + self.last_pk = first_record_list[pk_index] + else: + self.last_pk = tuple( + first_record_list[ + column_names.index(resolve_casing(p, column_names)) + ] + for p in pk + ) + else: + first_record_dict = cast(Dict[str, Any], first_record) + if hash_id: + self.last_pk = hash_record(first_record_dict, hash_id_columns) + else: + self.last_pk = ( + first_record_dict[resolve_casing(pk, first_record_dict)] + if isinstance(pk, str) + else tuple( + first_record_dict[resolve_casing(p, first_record_dict)] + for p in pk + ) + ) + if analyze: self.analyze() @@ -3307,6 +4712,7 @@ class Table(Queryable): extracts=DEFAULT, conversions=DEFAULT, columns=DEFAULT, + strict=DEFAULT, ) -> "Table": """ Like ``.insert()`` but performs an ``UPSERT``, where records are inserted if they do @@ -3327,11 +4733,15 @@ class Table(Queryable): extracts=extracts, conversions=conversions, columns=columns, + strict=strict, ) def upsert_all( self, - records, + records: Union[ + Iterable[Dict[str, Any]], + Iterable[Sequence[Any]], + ], pk=DEFAULT, foreign_keys=DEFAULT, column_order=DEFAULT, @@ -3345,6 +4755,7 @@ class Table(Queryable): conversions=DEFAULT, columns=DEFAULT, analyze=False, + strict=DEFAULT, ) -> "Table": """ Like ``.upsert()`` but can be applied to a list of records. @@ -3365,6 +4776,7 @@ class Table(Queryable): columns=columns, upsert=True, analyze=analyze, + strict=strict, ) def add_missing_columns(self, records: Iterable[Dict[str, Any]]) -> "Table": @@ -3387,6 +4799,7 @@ class Table(Queryable): extracts: Optional[Union[Dict[str, str], List[str]]] = None, conversions: Optional[Dict[str, str]] = None, columns: Optional[Dict[str, Any]] = None, + strict: Optional[bool] = False, ): """ Create or populate a lookup table with the specified values. @@ -3409,26 +4822,37 @@ class Table(Queryable): :param lookup_values: Dictionary specifying column names and values to use for the lookup :param extra_values: Additional column values to be used only if creating a new record + :param strict: Boolean, apply STRICT mode if creating the table. """ - assert isinstance(lookup_values, dict) - if extra_values is not None: - assert isinstance(extra_values, dict) + if not isinstance(lookup_values, dict): + raise ValueError("lookup_values must be a dictionary") + if pk is None: + raise ValueError("pk cannot be None") + if extra_values is not None and not isinstance(extra_values, dict): + raise ValueError("extra_values must be a dictionary") combined_values = dict(lookup_values) if extra_values is not None: combined_values.update(extra_values) if self.exists(): self.add_missing_columns([combined_values]) - unique_column_sets = [set(i.columns) for i in self.indexes] - if set(lookup_values.keys()) not in unique_column_sets: + unique_column_sets = [ + {fold_identifier_case(c) for c in i.columns} for i in self.indexes + ] + if { + fold_identifier_case(c) for c in lookup_values + } not in unique_column_sets: self.create_index(lookup_values.keys(), unique=True) - wheres = ["[{}] = ?".format(column) for column in lookup_values] + # IS rather than = so that null values are matched correctly + wheres = [ + "{} IS ?".format(quote_identifier(column)) for column in lookup_values + ] rows = list( self.rows_where( " and ".join(wheres), [value for _, value in lookup_values.items()] ) ) try: - return rows[0][pk] + return rows[0][resolve_casing(pk, rows[0])] except IndexError: return self.insert( combined_values, @@ -3440,6 +4864,7 @@ class Table(Queryable): extracts=extracts, conversions=conversions, columns=columns, + strict=strict, ).last_pk else: pk = self.insert( @@ -3452,6 +4877,7 @@ class Table(Queryable): extracts=extracts, conversions=conversions, columns=columns, + strict=strict, ).last_pk self.create_index(lookup_values.keys(), unique=True) return pk @@ -3490,12 +4916,13 @@ class Table(Queryable): already exists. """ if isinstance(other_table, str): - other_table = cast(Table, self.db.table(other_table, pk=pk)) + other_table = self.db.table(other_table, pk=pk) our_id = self.last_pk if lookup is not None: - assert record_or_iterable is None, "Provide lookup= or record, not both" - else: - assert record_or_iterable is not None, "Provide lookup= or record, not both" + if record_or_iterable is not None: + raise ValueError("Provide lookup= or record, not both") + elif record_or_iterable is None: + raise ValueError("Provide lookup= or record, not both") tables = list(sorted([self.name, other_table.name])) columns = ["{}_id".format(t) for t in tables] if m2m_table is not None: @@ -3544,7 +4971,7 @@ class Table(Queryable): ) return self - def analyze(self): + def analyze(self) -> None: "Run ANALYZE against this table" self.db.analyze(self.name) @@ -3582,20 +5009,24 @@ class Table(Queryable): value = value[:value_truncate] + "..." return value + table_quoted = quote_identifier(table) + column_quoted = quote_identifier(column) num_null = db.execute( - "select count(*) from [{}] where [{}] is null".format(table, column) + "select count(*) from {} where {} is null".format( + table_quoted, column_quoted + ) ).fetchone()[0] num_blank = db.execute( - "select count(*) from [{}] where [{}] = ''".format(table, column) + "select count(*) from {} where {} = ''".format(table_quoted, column_quoted) ).fetchone()[0] num_distinct = db.execute( - "select count(distinct [{}]) from [{}]".format(column, table) + "select count(distinct {}) from {}".format(column_quoted, table_quoted) ).fetchone()[0] most_common_results = None least_common_results = None if num_distinct == 1: value = db.execute( - "select [{}] from [{}] limit 1".format(column, table) + "select {} from {} limit 1".format(column_quoted, table_quoted) ).fetchone()[0] most_common_results = [(truncate(value), total_rows)] elif num_distinct != total_rows: @@ -3607,8 +5038,12 @@ class Table(Queryable): most_common_results = [ (truncate(r[0]), r[1]) for r in db.execute( - "select [{}], count(*) from [{}] group by [{}] order by count(*) desc, [{}] limit {}".format( - column, table, column, column, common_limit + "select {}, count(*) from {} group by {} order by count(*) desc, {} limit {}".format( + column_quoted, + table_quoted, + column_quoted, + column_quoted, + common_limit, ) ).fetchall() ] @@ -3621,8 +5056,12 @@ class Table(Queryable): least_common_results = [ (truncate(r[0]), r[1]) for r in db.execute( - "select [{}], count(*) from [{}] group by [{}] order by count(*), [{}] desc limit {}".format( - column, table, column, column, common_limit + "select {}, count(*) from {} group by {} order by count(*), {} desc limit {}".format( + column_quoted, + table_quoted, + column_quoted, + column_quoted, + common_limit, ) ).fetchall() ] @@ -3724,7 +5163,7 @@ class Table(Queryable): class View(Queryable): - def exists(self): + def exists(self) -> bool: return True def __repr__(self) -> str: @@ -3732,7 +5171,7 @@ class View(Queryable): self.name, ", ".join(c.name for c in self.columns) ) - def drop(self, ignore=False): + def drop(self, ignore: bool = False) -> None: """ Drop this view. @@ -3740,19 +5179,13 @@ class View(Queryable): """ try: - self.db.execute("DROP VIEW [{}]".format(self.name)) + self.db.execute("DROP VIEW {}".format(quote_identifier(self.name))) except sqlite3.OperationalError: if not ignore: raise - def enable_fts(self, *args, **kwargs): - "``enable_fts()`` is supported on tables but not on views." - raise NotImplementedError( - "enable_fts() is supported on tables but not on views" - ) - -def jsonify_if_needed(value): +def jsonify_if_needed(value: object) -> object: if isinstance(value, decimal.Decimal): return float(value) if isinstance(value, (dict, list, tuple)): @@ -3768,7 +5201,7 @@ def jsonify_if_needed(value): def resolve_extracts( - extracts: Optional[Union[Dict[str, str], List[str], Tuple[str]]] + extracts: Optional[Union[Dict[str, str], List[str], Tuple[str]]], ) -> dict: if extracts is None: extracts = {} @@ -3777,26 +5210,7 @@ def resolve_extracts( return extracts -def validate_column_names(columns): - # Validate no columns contain '[' or ']' - #86 - for column in columns: - assert ( - "[" not in column and "]" not in column - ), "'[' and ']' cannot be used in column names" - - -def fix_square_braces(records: Iterable[Dict[str, Any]]): - for record in records: - if any("[" in key or "]" in key for key in record.keys()): - yield { - key.replace("[", "_").replace("]", "_"): value - for key, value in record.items() - } - else: - yield record - - -def _decode_default_value(value): +def _decode_default_value(value: str) -> object: if value.startswith("'") and value.endswith("'"): # It's a string return value[1:-1] diff --git a/sqlite_utils/hookspecs.py b/sqlite_utils/hookspecs.py index 83466be..a746619 100644 --- a/sqlite_utils/hookspecs.py +++ b/sqlite_utils/hookspecs.py @@ -1,3 +1,6 @@ +import sqlite3 + +import click from pluggy import HookimplMarker from pluggy import HookspecMarker @@ -6,10 +9,10 @@ hookimpl = HookimplMarker("sqlite_utils") @hookspec -def register_commands(cli): +def register_commands(cli: click.Group) -> None: """Register additional CLI commands, e.g. 'sqlite-utils mycommand ...'""" @hookspec -def prepare_connection(conn): +def prepare_connection(conn: sqlite3.Connection) -> None: """Modify SQLite connection in some way e.g. register custom SQL functions""" diff --git a/sqlite_utils/migrations.py b/sqlite_utils/migrations.py new file mode 100644 index 0000000..00d0fa5 --- /dev/null +++ b/sqlite_utils/migrations.py @@ -0,0 +1,177 @@ +from collections.abc import Iterable +from dataclasses import dataclass +import datetime +from typing import Callable, cast, TYPE_CHECKING + +if TYPE_CHECKING: + from sqlite_utils.db import Database, Table + + +class Migrations: + migrations_table = "_sqlite_migrations" + + @dataclass + class _Migration: + name: str + fn: Callable + transactional: bool = True + + @dataclass + class _AppliedMigration: + name: str + # A string timestamp such as "2026-07-04 12:00:00.000000+00:00" - + # stored as TEXT in the _sqlite_migrations table + applied_at: str + + def __init__(self, name: str): + """ + :param name: The name of the migration set. This should be unique. + """ + self.name = name + self._migrations: list[Migrations._Migration] = [] + + def __call__( + self, *, name: str | None = None, transactional: bool = True + ) -> Callable: + """ + :param name: The name to use for this migration - if not provided, + the name of the function will be used. + :param transactional: If ``True`` (the default) the migration and the + record of it having been applied are wrapped in a transaction, which + will be rolled back if the migration raises an exception. Pass + ``False`` for migrations that cannot run inside a transaction, for + example those that execute ``VACUUM``. + """ + + def inner(func: Callable) -> Callable: + migration_name = name or getattr(func, "__name__") + if any(m.name == migration_name for m in self._migrations): + raise ValueError( + "Migration '{}' is already registered in set '{}'".format( + migration_name, self.name + ) + ) + self._migrations.append( + self._Migration(migration_name, func, transactional) + ) + return func + + return inner + + def pending(self, db: "Database") -> list["Migrations._Migration"]: + """ + Return a list of pending migrations. + + This is a read-only operation - it does not write to the database. + """ + already_applied = {migration.name for migration in self.applied(db)} + return [ + migration + for migration in self._migrations + if migration.name not in already_applied + ] + + def applied(self, db: "Database") -> list["Migrations._AppliedMigration"]: + """ + Return a list of applied migrations, in the order they were applied. + + This is a read-only operation - it does not write to the database. + """ + table = _table(db, self.migrations_table) + if not table.exists(): + return [] + return [ + self._AppliedMigration(name=row["name"], applied_at=row["applied_at"]) + for row in table.rows_where( + "migration_set = ?", [self.name], order_by="rowid" + ) + ] + + def apply(self, db: "Database", *, stop_before: str | Iterable[str] | None = None): + """ + Apply any pending migrations to the database. + + Each migration runs inside a transaction, together with the record of + it having been applied - if the migration raises an exception its + changes are rolled back, no record is written and the migration stays + pending. Migrations registered with ``transactional=False`` run + outside of a transaction. + + :raises ValueError: if a ``stop_before`` name matches a migration in + this set that has already been applied - stopping before it is + impossible to honor, and no pending migrations are applied + """ + if stop_before is None: + stop_before_names = set() + elif isinstance(stop_before, str): + stop_before_names = {stop_before} + else: + stop_before_names = set(stop_before) + # A stop_before naming an already-applied migration cannot be + # honored - error rather than applying everything after it. Names + # not in this set at all are ignored, because unqualified CLI + # values are offered to every migration set + already_applied = stop_before_names.intersection( + migration.name for migration in self.applied(db) + ) + if already_applied: + raise ValueError( + "Cannot stop before migration{} {} in set '{}' - already " + "been applied".format( + "s" if len(already_applied) > 1 else "", + ", ".join(sorted(already_applied)), + self.name, + ) + ) + self.ensure_migrations_table(db) + for migration in self.pending(db): + name = migration.name + if name in stop_before_names: + return + if migration.transactional: + with db.atomic(): + migration.fn(db) + self._record_applied(db, name) + else: + migration.fn(db) + self._record_applied(db, name) + + def _record_applied(self, db: "Database", name: str): + _table(db, self.migrations_table).insert( + { + "migration_set": self.name, + "name": name, + "applied_at": str(datetime.datetime.now(datetime.timezone.utc)), + } + ) + + def ensure_migrations_table(self, db: "Database"): + """ + Ensure the _sqlite_migrations table exists and has the correct schema. + """ + table = _table(db, self.migrations_table) + if not table.exists(): + table.create( + { + "id": int, + "migration_set": str, + "name": str, + "applied_at": str, + }, + pk="id", + ) + table.create_index(["migration_set", "name"], unique=True) + elif table.pks != ["id"]: + table.transform(pk="id") + unique_indexes = {tuple(index.columns) for index in table.indexes} + if ("migration_set", "name") not in unique_indexes: + table.create_index(["migration_set", "name"], unique=True) + + def __repr__(self): + return "".format( + self.name, ", ".join(m.name for m in self._migrations) + ) + + +def _table(db: "Database", name: str) -> "Table": + return cast("Table", db[name]) diff --git a/sqlite_utils/plugins.py b/sqlite_utils/plugins.py index 1e45e62..0aff7ff 100644 --- a/sqlite_utils/plugins.py +++ b/sqlite_utils/plugins.py @@ -1,22 +1,31 @@ +from typing import Dict, List, Union + import pluggy import sys from . import hookspecs -pm = pluggy.PluginManager("sqlite_utils") +pm: pluggy.PluginManager = pluggy.PluginManager("sqlite_utils") pm.add_hookspecs(hookspecs) +_plugins_loaded = False -if not getattr(sys, "_called_from_test", False): - # Only load plugins if not running tests + +def ensure_plugins_loaded() -> None: + global _plugins_loaded + if _plugins_loaded or getattr(sys, "_called_from_test", False): + return pm.load_setuptools_entrypoints("sqlite_utils") + _plugins_loaded = True -def get_plugins(): - plugins = [] +def get_plugins() -> List[Dict[str, Union[str, List[str]]]]: + ensure_plugins_loaded() + plugins: List[Dict[str, Union[str, List[str]]]] = [] plugin_to_distinfo = dict(pm.list_plugin_distinfo()) for plugin in pm.get_plugins(): - plugin_info = { + hookcallers = pm.get_hookcallers(plugin) or [] + plugin_info: Dict[str, Union[str, List[str]]] = { "name": plugin.__name__, - "hooks": [h.name for h in pm.get_hookcallers(plugin)], + "hooks": [h.name for h in hookcallers], } distinfo = plugin_to_distinfo.get(plugin) if distinfo: diff --git a/sqlite_utils/recipes.py b/sqlite_utils/recipes.py index ac41954..55b55a4 100644 --- a/sqlite_utils/recipes.py +++ b/sqlite_utils/recipes.py @@ -1,11 +1,20 @@ +from __future__ import annotations + +from typing import Callable, Optional + from dateutil import parser import json -IGNORE = object() -SET_NULL = object() +IGNORE: object = object() +SET_NULL: object = object() -def parsedate(value, dayfirst=False, yearfirst=False, errors=None): +def parsedate( + value: str, + dayfirst: bool = False, + yearfirst: bool = False, + errors: Optional[object] = None, +) -> Optional[str]: """ Parse a date and convert it to ISO date format: yyyy-mm-dd \b @@ -14,6 +23,8 @@ def parsedate(value, dayfirst=False, yearfirst=False, errors=None): - errors=r.IGNORE to ignore values that cannot be parsed - errors=r.SET_NULL to set values that cannot be parsed to null """ + if not value: + return value try: return ( parser.parse(value, dayfirst=dayfirst, yearfirst=yearfirst) @@ -29,7 +40,12 @@ def parsedate(value, dayfirst=False, yearfirst=False, errors=None): raise -def parsedatetime(value, dayfirst=False, yearfirst=False, errors=None): +def parsedatetime( + value: str, + dayfirst: bool = False, + yearfirst: bool = False, + errors: Optional[object] = None, +) -> Optional[str]: """ Parse a datetime and convert it to ISO datetime format: yyyy-mm-ddTHH:MM:SS \b @@ -38,6 +54,8 @@ def parsedatetime(value, dayfirst=False, yearfirst=False, errors=None): - errors=r.IGNORE to ignore values that cannot be parsed - errors=r.SET_NULL to set values that cannot be parsed to null """ + if not value: + return value try: return parser.parse(value, dayfirst=dayfirst, yearfirst=yearfirst).isoformat() except parser.ParserError: @@ -49,7 +67,9 @@ def parsedatetime(value, dayfirst=False, yearfirst=False, errors=None): raise -def jsonsplit(value, delimiter=",", type=str): +def jsonsplit( + value: str, delimiter: str = ",", type: Callable[[str], object] = str +) -> str: """ Convert a string like a,b,c into a JSON array ["a", "b", "c"] """ diff --git a/sqlite_utils/utils.py b/sqlite_utils/utils.py index 29440a5..b39b117 100644 --- a/sqlite_utils/utils.py +++ b/sqlite_utils/utils.py @@ -3,26 +3,44 @@ import contextlib import csv import enum import hashlib +import importlib import io import itertools import json import os import sys -from . import recipes -from typing import Dict, cast, BinaryIO, Iterable, Optional, Tuple, Type +from typing import ( + Any, + BinaryIO, + Callable, + Dict, + Generator, + Iterable, + Iterator, + List, + Optional, + Set, + Tuple, + Type, + TYPE_CHECKING, + TypeVar, + Union, + cast, +) import click -try: - import pysqlite3 as sqlite3 # noqa: F401 - from pysqlite3 import dbapi2 # noqa: F401 +from . import recipes + +if TYPE_CHECKING: + import sqlite3 # noqa: F401 + from sqlite3 import dbapi2 # noqa: F401 OperationalError = dbapi2.OperationalError -except ImportError: +else: try: - import sqlean as sqlite3 # noqa: F401 - from sqlean import dbapi2 # noqa: F401 - + sqlite3 = importlib.import_module("pysqlite3") + dbapi2 = importlib.import_module("pysqlite3.dbapi2") OperationalError = dbapi2.OperationalError except ImportError: import sqlite3 # noqa: F401 @@ -42,8 +60,35 @@ SPATIALITE_PATHS = ( # Mainly so we can restore it if needed in the tests: ORIGINAL_CSV_FIELD_SIZE_LIMIT = csv.field_size_limit() +# Type alias for row dictionaries - values can be various SQLite-compatible types +RowValue = Union[None, int, float, str, bytes, bool, List[str]] +Row = Dict[str, RowValue] -def maximize_csv_field_size_limit(): +T = TypeVar("T") + + +class _CloseableIterator(Iterator[Row]): + """Iterator wrapper that closes a file when iteration is complete.""" + + def __init__(self, iterator: Iterator[Row], closeable: io.IOBase) -> None: + self._iterator = iterator + self._closeable = closeable + + def __iter__(self) -> "_CloseableIterator": + return self + + def __next__(self) -> Row: + try: + return next(self._iterator) + except StopIteration: + self._closeable.close() + raise + + def close(self) -> None: + self._closeable.close() + + +def maximize_csv_field_size_limit() -> None: """ Increase the CSV field size limit to the maximum possible. """ @@ -86,20 +131,25 @@ def find_spatialite() -> Optional[str]: return None -def suggest_column_types(records): - all_column_types = {} +def suggest_column_types( + records: Iterable[Dict[str, Any]], +) -> Dict[str, type]: + all_column_types: Dict[str, Set[type]] = {} for record in records: for key, value in record.items(): all_column_types.setdefault(key, set()).add(type(value)) return types_for_column_types(all_column_types) -def types_for_column_types(all_column_types): - column_types = {} +def types_for_column_types( + all_column_types: Dict[str, Set[type]], +) -> Dict[str, type]: + column_types: Dict[str, type] = {} for key, types in all_column_types.items(): # Ignore null values if at least one other type present: if len(types) > 1: types.discard(None.__class__) + t: type if {None.__class__} == types: t = str elif len(types) == 1: @@ -121,7 +171,7 @@ def types_for_column_types(all_column_types): return column_types -def column_affinity(column_type): +def column_affinity(column_type: str) -> type: # Implementation of SQLite affinity rules from # https://www.sqlite.org/datatype3.html#determination_of_column_affinity assert isinstance(column_type, str) @@ -140,38 +190,42 @@ def column_affinity(column_type): return float -def decode_base64_values(doc): +def decode_base64_values(doc: Dict[str, Any]) -> Dict[str, Any]: # Looks for '{"$base64": true..., "encoded": ...}' values and decodes them to_fix = [ k for k in doc if isinstance(doc[k], dict) - and doc[k].get("$base64") is True - and "encoded" in doc[k] + and cast(dict, doc[k]).get("$base64") is True + and "encoded" in cast(dict, doc[k]) ] if not to_fix: return doc - return dict(doc, **{k: base64.b64decode(doc[k]["encoded"]) for k in to_fix}) + return dict( + doc, **{k: base64.b64decode(cast(dict, doc[k])["encoded"]) for k in to_fix} + ) class UpdateWrapper: - def __init__(self, wrapped, update): + def __init__(self, wrapped: io.IOBase, update: Callable[[int], None]) -> None: self._wrapped = wrapped self._update = update - def __iter__(self): + def __iter__(self) -> Iterator[bytes]: for line in self._wrapped: self._update(len(line)) yield line - def read(self, size=-1): + def read(self, size: int = -1) -> bytes: data = self._wrapped.read(size) self._update(len(data)) return data @contextlib.contextmanager -def file_progress(file, silent=False, **kwargs): +def file_progress( + file: io.IOBase, silent: bool = False, **kwargs: object +) -> Generator[Union[io.IOBase, "UpdateWrapper"], None, None]: if silent: yield file return @@ -184,8 +238,8 @@ def file_progress(file, silent=False, **kwargs): if fileno == 0: # 0 means stdin yield file else: - file_length = os.path.getsize(file.name) - with click.progressbar(length=file_length, **kwargs) as bar: + file_length = os.path.getsize(file.name) # type: ignore + with click.progressbar(length=file_length, **kwargs) as bar: # type: ignore yield UpdateWrapper(file, bar.update) @@ -209,28 +263,30 @@ class RowError(Exception): def _extra_key_strategy( - reader: Iterable[dict], + reader: Iterable[Dict[Optional[str], object]], ignore_extras: Optional[bool] = False, extras_key: Optional[str] = None, -) -> Iterable[dict]: +) -> Iterable[Row]: # Logic for handling CSV rows with more values than there are headings for row in reader: # DictReader adds a 'None' key with extra row values if None not in row: - yield row + yield cast(Row, row) elif ignore_extras: # ignoring row.pop(none) because of this issue: # https://github.com/simonw/sqlite-utils/issues/440#issuecomment-1155358637 - row.pop(None) # type: ignore - yield row + row.pop(None) + yield cast(Row, row) elif not extras_key: - extras = row.pop(None) # type: ignore + extras = row.pop(None) raise RowError( "Row {} contained these extra values: {}".format(row, extras) ) else: - row[extras_key] = row.pop(None) # type: ignore - yield row + extras_value = row.pop(None) + row_out = cast(Row, row) + row_out[extras_key] = cast(RowValue, extras_value) + yield row_out def rows_from_file( @@ -240,7 +296,7 @@ def rows_from_file( encoding: Optional[str] = None, ignore_extras: Optional[bool] = False, extras_key: Optional[str] = None, -) -> Tuple[Iterable[dict], Format]: +) -> Tuple[Iterable[Row], Format]: """ Load a sequence of dictionaries from a file-like object containing one of four different formats. @@ -299,13 +355,18 @@ def rows_from_file( reader = csv.DictReader(decoded_fp, dialect=dialect) else: reader = csv.DictReader(decoded_fp) - return _extra_key_strategy(reader, ignore_extras, extras_key), Format.CSV + rows = _extra_key_strategy(reader, ignore_extras, extras_key) + return _CloseableIterator(iter(rows), decoded_fp), Format.CSV elif format == Format.TSV: - rows = rows_from_file( + rows, _ = rows_from_file( fp, format=Format.CSV, dialect=csv.excel_tab, encoding=encoding - )[0] + ) return ( - _extra_key_strategy(rows, ignore_extras, extras_key), + _extra_key_strategy( + cast(Iterable[Dict[Optional[str], object]], rows), + ignore_extras, + extras_key, + ), Format.TSV, ) elif format is None: @@ -329,8 +390,15 @@ def rows_from_file( buffered, format=Format.CSV, dialect=dialect, encoding=encoding ) # Make sure we return the format we detected - format = Format.TSV if dialect.delimiter == "\t" else Format.CSV - return _extra_key_strategy(rows, ignore_extras, extras_key), format + detected_format = Format.TSV if dialect.delimiter == "\t" else Format.CSV + return ( + _extra_key_strategy( + cast(Iterable[Dict[Optional[str], object]], rows), + ignore_extras, + extras_key, + ), + detected_format, + ) else: raise RowsFromFileError("Bad format") @@ -356,10 +424,10 @@ class TypeTracker: db["creatures"].transform(types=tracker.types) """ - def __init__(self): - self.trackers = {} + def __init__(self) -> None: + self.trackers: Dict[str, "ValueTracker"] = {} - def wrap(self, iterator: Iterable[dict]) -> Iterable[dict]: + def wrap(self, iterator: Iterable[Dict[str, Any]]) -> Iterable[Dict[str, Any]]: """ Use this to loop through an existing iterator, tracking the column types as part of the iteration. @@ -382,27 +450,29 @@ class TypeTracker: class ValueTracker: - def __init__(self): + couldbe: Dict[str, Callable[[object], bool]] + + def __init__(self) -> None: self.couldbe = {key: getattr(self, "test_" + key) for key in self.get_tests()} @classmethod - def get_tests(cls): + def get_tests(cls) -> List[str]: return [ key.split("test_")[-1] for key in cls.__dict__.keys() if key.startswith("test_") ] - def test_integer(self, value): + def test_integer(self, value: object) -> bool: try: - int(value) + int(cast(Any, value)) return True except (ValueError, TypeError): return False - def test_float(self, value): + def test_float(self, value: object) -> bool: try: - float(value) + float(cast(Any, value)) return True except (ValueError, TypeError): return False @@ -411,7 +481,7 @@ class ValueTracker: return self.guessed_type + ": possibilities = " + repr(self.couldbe) @property - def guessed_type(self): + def guessed_type(self) -> str: options = set(self.couldbe.keys()) # Return based on precedence for key in self.get_tests(): @@ -419,10 +489,10 @@ class ValueTracker: return key return "text" - def evaluate(self, value): + def evaluate(self, value: object) -> None: if not value or not self.couldbe: return - not_these = [] + not_these: List[str] = [] for name, test in self.couldbe.items(): if not test(value): not_these.append(name) @@ -431,35 +501,50 @@ class ValueTracker: class NullProgressBar: - def __init__(self, *args): + def __init__(self, *args: Iterable[T]) -> None: self.args = args - def __iter__(self): - yield from self.args[0] + def __iter__(self) -> Iterator[T]: + yield from self.args[0] # type: ignore - def update(self, value): + def update(self, value: int) -> None: pass @contextlib.contextmanager -def progressbar(*args, **kwargs): +def progressbar(*args: Iterable[T], **kwargs: Any) -> Generator[Any, None, None]: silent = kwargs.pop("silent") if silent: yield NullProgressBar(*args) else: - with click.progressbar(*args, **kwargs) as bar: + with click.progressbar(*args, **kwargs) as bar: # type: ignore yield bar -def _compile_code(code, imports, variable="value"): - globals = {"r": recipes, "recipes": recipes} +def _compile_code( + code: str, imports: Iterable[str], variable: str = "value" +) -> Callable[..., Any]: + globals_dict: Dict[str, Any] = {"r": recipes, "recipes": recipes} + # Handle imports first so they're available for all approaches + for import_ in imports: + globals_dict[import_.split(".")[0]] = __import__(import_) + # If user defined a convert() function, return that try: - exec(code, globals) - return globals["convert"] + exec(code, globals_dict) + return cast(Callable[..., object], globals_dict["convert"]) except (AttributeError, SyntaxError, NameError, KeyError, TypeError): pass + # Check if code is a direct callable reference + # e.g. "r.parsedate" instead of "r.parsedate(value)" + try: + fn = eval(code, globals_dict) + if callable(fn): + return cast(Callable[..., object], fn) + except Exception: + pass + # Try compiling their code as a function instead body_variants = [code] # If single line and no 'return', try adding the return @@ -481,13 +566,11 @@ def _compile_code(code, imports, variable="value"): if code_o is None: raise SyntaxError("Could not compile code") - for import_ in imports: - globals[import_.split(".")[0]] = __import__(import_) - exec(code_o, globals) - return globals["fn"] + exec(code_o, globals_dict) + return cast(Callable[..., object], globals_dict["fn"]) -def chunks(sequence: Iterable, size: int) -> Iterable[Iterable]: +def chunks(sequence: Iterable[T], size: int) -> Iterable[Iterable[T]]: """ Iterate over chunks of the sequence of the given size. @@ -499,7 +582,7 @@ def chunks(sequence: Iterable, size: int) -> Iterable[Iterable]: yield itertools.chain([item], itertools.islice(iterator, size - 1)) -def hash_record(record: Dict, keys: Optional[Iterable[str]] = None): +def hash_record(record: Dict[str, Any], keys: Optional[Iterable[str]] = None) -> str: """ ``record`` should be a Python dictionary. Returns a sha1 hash of the keys and values in that record. @@ -520,7 +603,7 @@ def hash_record(record: Dict, keys: Optional[Iterable[str]] = None): :param record: Record to generate a hash for :param keys: Subset of keys to use for that hash """ - to_hash = record + to_hash: Dict[str, Any] = record if keys is not None: to_hash = {key: record[key] for key in keys} return hashlib.sha1( @@ -530,7 +613,38 @@ def hash_record(record: Dict, keys: Optional[Iterable[str]] = None): ).hexdigest() -def _flatten(d): +def dedupe_keys(keys: Iterable[str]) -> List[str]: + """ + Rename duplicates in a list of column names so every name is unique, + by appending ``_2``, ``_3``... to later occurrences - skipping any + suffix that would collide with another column in the list. + + Used when converting SQL query rows to dictionaries, where duplicate + column names would otherwise silently overwrite each other. + + :param keys: List of column names, possibly containing duplicates + """ + keys = list(keys) + taken = set(keys) + if len(taken) == len(keys): + # No duplicates - the common case + return keys + seen: set = set() + result = [] + for key in keys: + if key in seen: + new_key = key + suffix = 2 + while new_key in seen or new_key in taken: + new_key = "{}_{}".format(key, suffix) + suffix += 1 + key = new_key + seen.add(key) + result.append(key) + return result + + +def _flatten(d: Dict[str, Any]) -> Generator[Tuple[str, Any], None, None]: for key, value in d.items(): if isinstance(value, dict): for key2, value2 in _flatten(value): @@ -539,7 +653,7 @@ def _flatten(d): yield key, value -def flatten(row: dict) -> dict: +def flatten(row: Dict[str, Any]) -> Dict[str, Any]: """ Turn a nested dict e.g. ``{"a": {"b": 1}}`` into a flat dict: ``{"a_b": 1}`` diff --git a/tests/conftest.py b/tests/conftest.py index 3932f05..728db7b 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -8,10 +8,55 @@ create table Gosh2 (c1 text, c2 text, c3 text); """ +def pytest_addoption(parser): + parser.addoption( + "--sqlite-autocommit", + action="store_true", + default=False, + help=( + "Run every test against connections created with the Python 3.12+ " + "sqlite3.connect(autocommit=True) mode" + ), + ) + + def pytest_configure(config): import sys - sys._called_from_test = True + sys._called_from_test = True # type: ignore[attr-defined] + + if config.getoption("--sqlite-autocommit"): + if sys.version_info < (3, 12): + raise pytest.UsageError( + "--sqlite-autocommit requires Python 3.12 or higher" + ) + real_connect = sqlite3.connect + + def autocommit_connect(*args, **kwargs): + kwargs.setdefault("autocommit", True) + return real_connect(*args, **kwargs) + + sqlite3.connect = autocommit_connect + + +@pytest.fixture(autouse=True) +def close_all_databases(): + """Automatically close all Database objects created during a test.""" + databases = [] + original_init = Database.__init__ + + def tracking_init(self, *args, **kwargs): + original_init(self, *args, **kwargs) + databases.append(self) + + Database.__init__ = tracking_init # type: ignore[method-assign] + yield + Database.__init__ = original_init # type: ignore[method-assign] + for db in databases: + try: + db.close() + except Exception: + pass @pytest.fixture @@ -22,14 +67,12 @@ def fresh_db(): @pytest.fixture def existing_db(): database = Database(memory=True) - database.executescript( - """ + database.executescript(""" CREATE TABLE foo (text TEXT); INSERT INTO foo (text) values ("one"); INSERT INTO foo (text) values ("two"); INSERT INTO foo (text) values ("three"); - """ - ) + """) return database @@ -38,4 +81,5 @@ def db_path(tmpdir): path = str(tmpdir / "test.db") db = sqlite3.connect(path) db.executescript(CREATE_TABLES) + db.close() return path diff --git a/tests/test_analyze_tables.py b/tests/test_analyze_tables.py index 9634cfc..a2ce585 100644 --- a/tests/test_analyze_tables.py +++ b/tests/test_analyze_tables.py @@ -137,15 +137,13 @@ def db_to_analyze_path(db_to_analyze, tmpdir): db = sqlite3.connect(path) sql = "\n".join(db_to_analyze.iterdump()) db.executescript(sql) + db.close() return path def test_analyze_table(db_to_analyze_path): result = CliRunner().invoke(cli.cli, ["analyze-tables", db_to_analyze_path]) - assert ( - result.output.strip() - == ( - """ + assert result.output.strip() == (""" stuff.id: (1/3) Total rows: 8 @@ -178,9 +176,7 @@ stuff.size: (3/3) Most common: 5: 5 - 3: 4""" - ).strip() - ) + 3: 4""").strip() def test_analyze_table_save(db_to_analyze_path): diff --git a/tests/test_atomic.py b/tests/test_atomic.py new file mode 100644 index 0000000..c3fd02f --- /dev/null +++ b/tests/test_atomic.py @@ -0,0 +1,382 @@ +import pytest + +from sqlite_utils.db import Database, _iter_complete_sql_statements +from sqlite_utils.utils import sqlite3 + + +@pytest.mark.parametrize( + "sql,expected", + ( + ( + "CREATE TABLE t(id); INSERT INTO t VALUES (1)", + ["CREATE TABLE t(id);", "INSERT INTO t VALUES (1)"], + ), + ( + "INSERT INTO t VALUES ('a;b');", + ["INSERT INTO t VALUES ('a;b');"], + ), + ( + "-- comment;\nCREATE TABLE t(id);", + ["-- comment;\nCREATE TABLE t(id);"], + ), + ( + """ + CREATE TRIGGER t_ai AFTER INSERT ON t + BEGIN + UPDATE t SET value = 'a;b' WHERE id = new.id; + INSERT INTO log VALUES ('x;y'); + END; + """, + [ + "CREATE TRIGGER t_ai AFTER INSERT ON t\n" + " BEGIN\n" + " UPDATE t SET value = 'a;b' WHERE id = new.id;\n" + " INSERT INTO log VALUES ('x;y');\n" + " END;" + ], + ), + ), +) +def test_iter_complete_sql_statements(sql, expected): + assert list(_iter_complete_sql_statements(sql)) == expected + + +def test_atomic_commits(fresh_db): + with fresh_db.atomic(): + fresh_db["dogs"].insert({"id": 1, "name": "Cleo"}, pk="id") + + assert list(fresh_db["dogs"].rows) == [{"id": 1, "name": "Cleo"}] + + +def test_atomic_rolls_back(fresh_db): + with pytest.raises(RuntimeError): + with fresh_db.atomic(): + fresh_db["dogs"].insert({"id": 1, "name": "Cleo"}, pk="id") + raise RuntimeError("boom") + + assert not fresh_db["dogs"].exists() + + +def test_nested_atomic_rolls_back_to_savepoint(fresh_db): + fresh_db["dogs"].create({"id": int, "name": str}, pk="id") + + with fresh_db.atomic(): + fresh_db["dogs"].insert({"id": 1, "name": "Cleo"}) + with pytest.raises(RuntimeError): + with fresh_db.atomic(): + fresh_db["dogs"].insert({"id": 2, "name": "Pancakes"}) + raise RuntimeError("boom") + fresh_db["dogs"].insert({"id": 3, "name": "Marnie"}) + + assert list(fresh_db["dogs"].rows) == [ + {"id": 1, "name": "Cleo"}, + {"id": 3, "name": "Marnie"}, + ] + + +def test_outer_atomic_rolls_back_released_savepoint(fresh_db): + with pytest.raises(RuntimeError): + with fresh_db.atomic(): + fresh_db["dogs"].insert({"id": 1, "name": "Cleo"}, pk="id") + with fresh_db.atomic(): + fresh_db["dogs"].insert({"id": 2, "name": "Pancakes"}) + raise RuntimeError("boom") + + assert not fresh_db["dogs"].exists() + + +def test_executescript_does_not_commit_open_atomic_block(fresh_db): + with pytest.raises(RuntimeError): + with fresh_db.atomic(): + fresh_db.executescript(""" + CREATE TABLE dogs(id INTEGER PRIMARY KEY, name TEXT); + CREATE TRIGGER dogs_ai AFTER INSERT ON dogs + BEGIN + UPDATE dogs SET name = upper(new.name) || '; updated' WHERE id = new.id; + END; + -- This comment has a semicolon; + INSERT INTO dogs VALUES (1, 'Cleo; the first'); + """) + raise RuntimeError("boom") + + assert not fresh_db["dogs"].exists() + + +def test_transform_does_not_commit_open_atomic_block(fresh_db): + fresh_db["dogs"].insert({"id": 1, "name": "Cleo", "age": "5"}, pk="id") + + with pytest.raises(RuntimeError): + with fresh_db.atomic(): + fresh_db["dogs"].insert({"id": 2, "name": "Pancakes", "age": "6"}) + fresh_db["dogs"].transform(rename={"age": "dog_age"}) + raise RuntimeError("boom") + + assert ( + fresh_db["dogs"].schema + == 'CREATE TABLE "dogs" (\n "id" INTEGER PRIMARY KEY,\n "name" TEXT,\n "age" TEXT\n)' + ) + assert list(fresh_db["dogs"].rows) == [ + {"id": 1, "name": "Cleo", "age": "5"}, + ] + + +def test_transform_parent_table_with_foreign_keys_in_atomic(fresh_db): + fresh_db.conn.execute("PRAGMA foreign_keys=ON") + fresh_db["authors"].insert({"id": 1, "name": "Tina"}, pk="id") + fresh_db["books"].insert( + {"id": 1, "title": "Book", "author_id": 1}, + pk="id", + foreign_keys={"author_id"}, + ) + + with fresh_db.atomic(): + fresh_db["authors"].transform(rename={"name": "full_name"}) + assert fresh_db.conn.execute("PRAGMA foreign_keys").fetchone()[0] + + assert ( + fresh_db["authors"].schema + == 'CREATE TABLE "authors" (\n "id" INTEGER PRIMARY KEY,\n "full_name" TEXT\n)' + ) + assert fresh_db.execute("PRAGMA foreign_key_check").fetchall() == [] + + +def test_transform_parent_table_with_foreign_keys_rolls_back(fresh_db): + fresh_db.conn.execute("PRAGMA foreign_keys=ON") + fresh_db["authors"].insert({"id": 1, "name": "Tina"}, pk="id") + fresh_db["books"].insert( + {"id": 1, "title": "Book", "author_id": 1}, + pk="id", + foreign_keys={"author_id"}, + ) + + with pytest.raises(RuntimeError): + with fresh_db.atomic(): + fresh_db["authors"].transform(rename={"name": "full_name"}) + raise RuntimeError("boom") + + assert ( + fresh_db["authors"].schema + == 'CREATE TABLE "authors" (\n "id" INTEGER PRIMARY KEY,\n "name" TEXT\n)' + ) + assert fresh_db.conn.execute("PRAGMA foreign_keys").fetchone()[0] + assert fresh_db.execute("PRAGMA foreign_key_check").fetchall() == [] + + +def test_transform_detects_foreign_key_check_violations(fresh_db): + fresh_db.conn.execute("PRAGMA foreign_keys=ON") + fresh_db["authors"].insert({"id": 1, "name": "Tina"}, pk="id") + fresh_db["books"].insert({"id": 1, "author_id": 2}, pk="id") + + with pytest.raises(sqlite3.IntegrityError): + fresh_db["books"].transform(add_foreign_keys=(("author_id", "authors", "id"),)) + + assert fresh_db["books"].foreign_keys == [] + assert fresh_db.conn.execute("PRAGMA foreign_keys").fetchone()[0] + + +def test_atomic_inside_manual_transaction_uses_savepoint(fresh_db): + fresh_db["t"].insert({"id": 1}, pk="id") + fresh_db.execute("begin") + with fresh_db.atomic(): + fresh_db["t"].insert({"id": 2}, pk="id") + # Nothing is committed until the user's own transaction commits + assert fresh_db.conn.in_transaction + fresh_db.rollback() + assert [r["id"] for r in fresh_db["t"].rows] == [1] + # And with a commit instead, the atomic block's writes persist + fresh_db.execute("begin") + with fresh_db.atomic(): + fresh_db["t"].insert({"id": 3}, pk="id") + fresh_db.commit() + assert [r["id"] for r in fresh_db["t"].rows] == [1, 3] + + +def test_begin_commit_rollback(tmpdir): + path = str(tmpdir / "test.db") + db = Database(path) + db["t"].insert({"id": 1}, pk="id") + db.begin() + db["t"].insert({"id": 2}, pk="id") + assert db.conn.in_transaction + db.rollback() + assert not db.conn.in_transaction + assert [r["id"] for r in db["t"].rows] == [1] + db.begin() + db["t"].insert({"id": 3}, pk="id") + db.commit() + db.close() + db2 = Database(path) + assert [r["id"] for r in db2["t"].rows] == [1, 3] + db2.close() + + +def test_begin_inside_transaction_errors(fresh_db): + fresh_db.begin() + with pytest.raises(sqlite3.OperationalError): + fresh_db.begin() + fresh_db.rollback() + + +def test_commit_and_rollback_without_transaction_are_noops(fresh_db): + fresh_db.commit() + fresh_db.rollback() + assert not fresh_db.conn.in_transaction + + +def test_execute_write_commits_immediately(tmpdir): + path = str(tmpdir / "test.db") + db = Database(path) + db["t"].insert({"id": 1}, pk="id") + db.execute("insert into t (id) values (2)") + # No implicit transaction is left open + assert not db.conn.in_transaction + # A completely separate connection sees the row straight away + other = sqlite3.connect(path) + assert other.execute("select count(*) from t").fetchone()[0] == 2 + other.close() + db.close() + + +def test_execute_write_respects_explicit_transaction(fresh_db): + fresh_db["t"].insert({"id": 1}, pk="id") + fresh_db.begin() + fresh_db.execute("insert into t (id) values (2)") + # Still inside the explicit transaction - not committed + assert fresh_db.conn.in_transaction + fresh_db.rollback() + assert [r["id"] for r in fresh_db["t"].rows] == [1] + + +def test_execute_comment_prefixed_begin_leaves_transaction_open(fresh_db): + # A BEGIN hidden behind a leading comment must not be auto-committed + # out from under the caller + fresh_db["t"].insert({"id": 1}, pk="id") + fresh_db.execute("-- start a transaction\nbegin") + assert fresh_db.conn.in_transaction + fresh_db.execute("insert into t (id) values (2)") + fresh_db.rollback() + assert [r["id"] for r in fresh_db["t"].rows] == [1] + + +def _sqlite_accepts_bom(): + try: + sqlite3.connect(":memory:").execute("\ufeffselect 1") + return True + except sqlite3.OperationalError: + return False + + +@pytest.mark.parametrize("begin_sql", ["; begin", "\ufeffbegin"]) +def test_execute_prefixed_begin_leaves_transaction_open(fresh_db, begin_sql): + # sqlite3 tolerates empty statements and a UTF-8 BOM before the first + # real token, so a BEGIN behind either must not be auto-committed + # out from under the caller + if begin_sql.startswith("\ufeff") and not _sqlite_accepts_bom(): + pytest.skip("This SQLite version rejects a leading byte order mark") + fresh_db["t"].insert({"id": 1}, pk="id") + fresh_db.execute(begin_sql) + assert fresh_db.conn.in_transaction + fresh_db.execute("insert into t (id) values (2)") + fresh_db.rollback() + assert [r["id"] for r in fresh_db["t"].rows] == [1] + + +def test_execute_failed_write_rolls_back_implicit_transaction(tmpdir): + # A failed write must not leave the driver's implicit transaction open - + # that would silently disable auto-commit for every subsequent write + path = str(tmpdir / "test.db") + db = Database(path) + db["t"].insert({"id": 1}, pk="id") + with pytest.raises(sqlite3.IntegrityError): + db.execute("insert into t (id) values (1)") + assert not db.conn.in_transaction + # Subsequent writes commit as normal and survive closing the connection + db["other"].insert({"id": 2}) + db.close() + db2 = Database(path) + assert db2["other"].exists() + db2.close() + + +def test_execute_failed_write_preserves_explicit_transaction(fresh_db): + # A failed write inside an explicit transaction must not roll back + # the caller's earlier work - only the caller decides that + fresh_db["t"].insert({"id": 1}, pk="id") + fresh_db.begin() + fresh_db.execute("insert into t (id) values (2)") + with pytest.raises(sqlite3.IntegrityError): + fresh_db.execute("insert into t (id) values (1)") + assert fresh_db.conn.in_transaction + fresh_db.commit() + assert [r["id"] for r in fresh_db["t"].rows] == [1, 2] + + +def test_execute_failed_write_inside_atomic_preserves_block(fresh_db): + # A caught failure inside an atomic() block must leave the block's + # transaction open so its other work still commits + fresh_db["t"].insert({"id": 1}, pk="id") + with fresh_db.atomic(): + fresh_db.execute("insert into t (id) values (2)") + with pytest.raises(sqlite3.IntegrityError): + fresh_db.execute("insert into t (id) values (1)") + assert [r["id"] for r in fresh_db["t"].rows] == [1, 2] + + +def test_query_returning_commits_after_iteration(tmpdir): + if sqlite3.sqlite_version_info < (3, 35, 0): + import pytest as _pytest + + _pytest.skip("RETURNING requires SQLite 3.35.0 or higher") + path = str(tmpdir / "test.db") + db = Database(path) + db["t"].insert({"id": 1}, pk="id") + rows = list(db.query("insert into t (id) values (2) returning id")) + assert rows == [{"id": 2}] + assert not db.conn.in_transaction + other = sqlite3.connect(path) + assert other.execute("select count(*) from t").fetchone()[0] == 2 + other.close() + db.close() + + +TRIGGER_SQL = """ +create trigger no_bad before insert on t +when new.v = 'bad' +begin + select raise(rollback, 'trigger says no'); +end +""" + + +def test_atomic_preserves_error_from_transaction_destroying_trigger(fresh_db): + # RAISE(ROLLBACK) rolls back the whole transaction and destroys every + # savepoint - atomic()'s cleanup must not mask the IntegrityError + # with "cannot rollback - no transaction is active" + fresh_db.execute("create table t (id integer primary key, v text)") + fresh_db.execute(TRIGGER_SQL) + with pytest.raises(sqlite3.IntegrityError, match="trigger says no"): + with fresh_db.atomic(): + fresh_db.execute("insert into t (v) values ('bad')") + assert not fresh_db.conn.in_transaction + + +def test_nested_atomic_preserves_error_from_transaction_destroying_trigger( + fresh_db, +): + # The nested savepoint branch previously raised + # "no such savepoint" from ROLLBACK TO SAVEPOINT + fresh_db.execute("create table t (id integer primary key, v text)") + fresh_db.execute(TRIGGER_SQL) + with pytest.raises(sqlite3.IntegrityError, match="trigger says no"): + with fresh_db.atomic(): + with fresh_db.atomic(): + fresh_db.execute("insert into t (v) values ('bad')") + assert not fresh_db.conn.in_transaction + + +def test_atomic_preserves_error_from_insert_or_rollback(fresh_db): + fresh_db["t"].insert({"id": 1}, pk="id") + with pytest.raises(sqlite3.IntegrityError): + with fresh_db.atomic(): + fresh_db.execute("insert or rollback into t (id) values (1)") + assert not fresh_db.conn.in_transaction diff --git a/tests/test_cli.py b/tests/test_cli.py index 0a93504..a2135b0 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -3,8 +3,8 @@ from sqlite_utils.db import Index, ForeignKey from click.testing import CliRunner from pathlib import Path import subprocess +import sqlite3 import sys -from unittest import mock import json import os import pytest @@ -20,9 +20,11 @@ def _supports_pragma_function_list(): db = Database(memory=True) try: db.execute("select * from pragma_function_list()") + return True except Exception: return False - return True + finally: + db.close() def _has_compiled_ext(): @@ -62,8 +64,8 @@ def test_views(db_path): result = CliRunner().invoke(cli.cli, ["views", db_path, "--table", "--schema"]) assert ( "view schema\n" - "------ --------------------------------------------\n" - "hello CREATE VIEW hello AS select sqlite_version()" + "------ ----------------------------------------------\n" + 'hello CREATE VIEW "hello" AS select sqlite_version()' ) == result.output.strip() @@ -132,7 +134,7 @@ def test_tables_schema(db_path): assert ( '[{"table": "Gosh", "schema": "CREATE TABLE Gosh (c1 text, c2 text, c3 text)"},\n' ' {"table": "Gosh2", "schema": "CREATE TABLE Gosh2 (c1 text, c2 text, c3 text)"},\n' - ' {"table": "lots", "schema": "CREATE TABLE [lots] (\\n [id] INTEGER,\\n [age] INTEGER\\n)"}]' + ' {"table": "lots", "schema": "CREATE TABLE \\"lots\\" (\\n \\"id\\" INTEGER,\\n \\"age\\" INTEGER\\n)"}]' ) == result.output.strip() @@ -194,6 +196,50 @@ def test_output_table(db_path, options, expected): assert expected == result.output.strip() +@pytest.mark.parametrize( + "fmt_option", [["--fmt", "simple"], ["-t"], ["--fmt", "github"]] +) +def test_output_table_no_headers(db_path, fmt_option): + # --no-headers should omit the header row from --fmt/--table output too, not + # just from --csv/--tsv (#566). Previously the flag was silently ignored for + # tabulate formats and the column names were always printed. + db = Database(db_path) + with db.conn: + db["dogs"].insert_all( + [ + {"id": 1, "name": "Cleo", "age": 4}, + {"id": 2, "name": "Pancakes", "age": 2}, + ] + ) + sql = "select id, name, age from dogs order by id" + + with_headers = CliRunner().invoke(cli.cli, ["query", db_path, sql] + fmt_option) + without_headers = CliRunner().invoke( + cli.cli, ["query", db_path, sql] + fmt_option + ["--no-headers"] + ) + assert with_headers.exit_code == 0 + assert without_headers.exit_code == 0 + + # The column names appear when headers are shown, and must not appear at all + # once --no-headers is passed. + assert "name" in with_headers.output + for header in ("id", "name", "age"): + assert ( + header not in without_headers.output + ), f"header {header!r} leaked into --no-headers output" + # The data is still all present. + for value in ("Cleo", "Pancakes", "1", "2", "4"): + assert value in without_headers.output + + # The rows command shares the same code path. + rows_no_headers = CliRunner().invoke( + cli.cli, ["rows", db_path, "dogs"] + fmt_option + ["--no-headers"] + ) + assert rows_no_headers.exit_code == 0 + assert "name" not in rows_no_headers.output + assert "Cleo" in rows_no_headers.output + + def test_create_index(db_path): db = Database(db_path) assert [] == db["Gosh"].indexes @@ -246,6 +292,24 @@ def test_create_index(db_path): ) +def test_drop_index(db_path): + db = Database(db_path) + db["Gosh"].create_index(["c1"]) + assert [index.name for index in db["Gosh"].indexes] == ["idx_Gosh_c1"] + result = CliRunner().invoke(cli.cli, ["drop-index", db_path, "Gosh", "idx_Gosh_c1"]) + assert result.exit_code == 0 + assert db["Gosh"].indexes == [] + + result = CliRunner().invoke(cli.cli, ["drop-index", db_path, "Gosh", "idx_Gosh_c1"]) + assert result.exit_code == 1 + assert "No index named idx_Gosh_c1" in result.output + + result = CliRunner().invoke( + cli.cli, ["drop-index", db_path, "Gosh", "idx_Gosh_c1", "--ignore"] + ) + assert result.exit_code == 0 + + def test_create_index_analyze(db_path): db = Database(db_path) assert "sqlite_stat1" not in db.table_names() @@ -264,28 +328,38 @@ def test_create_index_desc(db_path): assert result.exit_code == 0 assert ( db.execute("select sql from sqlite_master where type='index'").fetchone()[0] - == "CREATE INDEX [idx_Gosh_c1]\n ON [Gosh] ([c1] desc)" + == 'CREATE INDEX "idx_Gosh_c1"\n ON "Gosh" ("c1" desc)' ) @pytest.mark.parametrize( "col_name,col_type,expected_schema", ( - ("text", "TEXT", "CREATE TABLE [dogs] (\n [name] TEXT\n, [text] TEXT)"), + ("text", "TEXT", 'CREATE TABLE "dogs" (\n "name" TEXT\n, "text" TEXT)'), + ("text", "str", 'CREATE TABLE "dogs" (\n "name" TEXT\n, "text" TEXT)'), + ("text", "STR", 'CREATE TABLE "dogs" (\n "name" TEXT\n, "text" TEXT)'), ( "integer", "INTEGER", - "CREATE TABLE [dogs] (\n [name] TEXT\n, [integer] INTEGER)", + 'CREATE TABLE "dogs" (\n "name" TEXT\n, "integer" INTEGER)', ), - ("float", "FLOAT", "CREATE TABLE [dogs] (\n [name] TEXT\n, [float] FLOAT)"), - ("blob", "blob", "CREATE TABLE [dogs] (\n [name] TEXT\n, [blob] BLOB)"), - ("default", None, "CREATE TABLE [dogs] (\n [name] TEXT\n, [default] TEXT)"), + ( + "integer", + "int", + 'CREATE TABLE "dogs" (\n "name" TEXT\n, "integer" INTEGER)', + ), + ("float", "FLOAT", 'CREATE TABLE "dogs" (\n "name" TEXT\n, "float" REAL)'), + ("blob", "blob", 'CREATE TABLE "dogs" (\n "name" TEXT\n, "blob" BLOB)'), + ("blob", "BLOB", 'CREATE TABLE "dogs" (\n "name" TEXT\n, "blob" BLOB)'), + ("blob", "bytes", 'CREATE TABLE "dogs" (\n "name" TEXT\n, "blob" BLOB)'), + ("blob", "BYTES", 'CREATE TABLE "dogs" (\n "name" TEXT\n, "blob" BLOB)'), + ("default", None, 'CREATE TABLE "dogs" (\n "name" TEXT\n, "default" TEXT)'), ), ) def test_add_column(db_path, col_name, col_type, expected_schema): db = Database(db_path) db.create_table("dogs", {"name": str}) - assert db["dogs"].schema == "CREATE TABLE [dogs] (\n [name] TEXT\n)" + assert db["dogs"].schema == 'CREATE TABLE "dogs" (\n "name" TEXT\n)' args = ["add-column", db_path, "dogs", col_name] if col_type is not None: args.append(col_type) @@ -309,7 +383,7 @@ def test_add_column_ignore(db_path, ignore): def test_add_column_not_null_default(db_path): db = Database(db_path) db.create_table("dogs", {"name": str}) - assert db["dogs"].schema == "CREATE TABLE [dogs] (\n [name] TEXT\n)" + assert db["dogs"].schema == 'CREATE TABLE "dogs" (\n "name" TEXT\n)' args = [ "add-column", db_path, @@ -320,9 +394,9 @@ def test_add_column_not_null_default(db_path): ] assert CliRunner().invoke(cli.cli, args).exit_code == 0 assert db["dogs"].schema == ( - "CREATE TABLE [dogs] (\n" - " [name] TEXT\n" - ", [nickname] TEXT NOT NULL DEFAULT 'dogs''dawg')" + 'CREATE TABLE "dogs" (\n' + ' "name" TEXT\n' + ", \"nickname\" TEXT NOT NULL DEFAULT 'dogs''dawg')" ) @@ -393,8 +467,8 @@ def test_add_column_foreign_key(db_path): assert result.exit_code == 0, result.output assert db["books"].schema == ( 'CREATE TABLE "books" (\n' - " [title] TEXT,\n" - " [author_id] INTEGER REFERENCES [authors]([id])\n" + ' "title" TEXT,\n' + ' "author_id" INTEGER REFERENCES "authors"("id")\n' ")" ) # Try it again with a custom --fk-col @@ -414,9 +488,9 @@ def test_add_column_foreign_key(db_path): assert result.exit_code == 0, result.output assert db["books"].schema == ( 'CREATE TABLE "books" (\n' - " [title] TEXT,\n" - " [author_id] INTEGER REFERENCES [authors]([id]),\n" - " [author_name_ref] TEXT REFERENCES [authors]([name])\n" + ' "title" TEXT,\n' + ' "author_id" INTEGER REFERENCES "authors"("id"),\n' + ' "author_name_ref" TEXT REFERENCES "authors"("name")\n' ")" ) # Throw an error if the --fk table does not exist @@ -482,10 +556,10 @@ def test_enable_fts(db_path): assert "http://example.com_fts" == db["http://example.com"].detect_fts() # Check tokenize was set to porter assert ( - "CREATE VIRTUAL TABLE [http://example.com_fts] USING FTS4 (\n" - " [c1],\n" + 'CREATE VIRTUAL TABLE "http://example.com_fts" USING FTS4 (\n' + ' "c1",\n' " tokenize='porter',\n" - " content=[http://example.com]" + ' content="http://example.com"' "\n)" ) == db["http://example.com_fts"].schema db["http://example.com"].drop() @@ -506,7 +580,7 @@ def test_enable_fts_replace(db_path): cli.cli, ["enable-fts", db_path, "Gosh", "c1", "--fts4"] ) assert result2.exit_code == 1 - assert result2.output == "Error: table [Gosh_fts] already exists\n" + assert result2.output == 'Error: table "Gosh_fts" already exists\n' # This should work result3 = CliRunner().invoke( @@ -727,6 +801,25 @@ def test_query_json(db_path, sql, args, expected): assert expected == result.output.strip() +def test_query_sql_from_stdin(db_path): + # https://github.com/simonw/sqlite-utils/issues/765 + db = Database(db_path) + with db.conn: + db["dogs"].insert_all( + [ + {"id": 1, "age": 4, "name": "Cleo"}, + {"id": 2, "age": 2, "name": "Pancakes"}, + ] + ) + result = CliRunner().invoke( + cli.cli, + ["query", db_path, "-"], + input="select name from dogs order by name", + ) + assert result.exit_code == 0, result.output + assert json.loads(result.output) == [{"name": "Cleo"}, {"name": "Pancakes"}] + + def test_query_json_empty(db_path): result = CliRunner().invoke( cli.cli, @@ -735,6 +828,26 @@ def test_query_json_empty(db_path): assert result.output.strip() == "[]" +def test_query_json_duplicate_columns_are_deduped(db_path): + # https://github.com/simonw/sqlite-utils/issues/624 + result = CliRunner().invoke( + cli.cli, + [db_path, "select 1 as id, 2 as id, 'x' as value, 'y' as value"], + ) + assert result.output.strip() == ( + '[{"id": 1, "id_2": 2, "value": "x", "value_2": "y"}]' + ) + + +def test_query_csv_duplicate_columns_are_preserved(db_path): + # CSV output should keep the duplicate headers, not rename them + result = CliRunner().invoke( + cli.cli, + [db_path, "select 1 as id, 2 as id", "--csv"], + ) + assert result.output.replace("\r", "").strip() == "id,id\n1,2" + + def test_query_invalid_function(db_path): result = CliRunner().invoke( cli.cli, [db_path, "select bad()", "--functions", "def invalid_python"] @@ -796,6 +909,77 @@ def test_hidden_functions_are_hidden(db_path): assert "_two" not in functions +def test_query_functions_from_file(db_path, tmp_path): + # Create a temporary file with function definitions + functions_file = tmp_path / "my_functions.py" + functions_file.write_text(TEST_FUNCTIONS) + + result = CliRunner().invoke( + cli.cli, + [ + db_path, + "select zero(), one(1), two(1, 2)", + "--functions", + str(functions_file), + ], + ) + assert result.exit_code == 0 + assert json.loads(result.output.strip()) == [ + {"zero()": 0, "one(1)": 1, "two(1, 2)": 3} + ] + + +def test_query_functions_file_not_found(db_path): + result = CliRunner().invoke( + cli.cli, + [ + db_path, + "select zero()", + "--functions", + "nonexistent.py", + ], + ) + assert result.exit_code == 1 + assert "File not found: nonexistent.py" in result.output + + +def test_query_functions_multiple_invocations(db_path): + # Test using --functions multiple times + result = CliRunner().invoke( + cli.cli, + [ + db_path, + "select triple(2), quadruple(2)", + "--functions", + "def triple(x):\n return x * 3", + "--functions", + "def quadruple(x):\n return x * 4", + ], + ) + assert result.exit_code == 0 + assert json.loads(result.output.strip()) == [{"triple(2)": 6, "quadruple(2)": 8}] + + +def test_query_functions_file_and_inline(db_path, tmp_path): + # Test combining file and inline code + functions_file = tmp_path / "file_funcs.py" + functions_file.write_text("def triple(x):\n return x * 3") + + result = CliRunner().invoke( + cli.cli, + [ + db_path, + "select triple(2), quadruple(2)", + "--functions", + str(functions_file), + "--functions", + "def quadruple(x):\n return x * 4", + ], + ) + assert result.exit_code == 0 + assert json.loads(result.output.strip()) == [{"triple(2)": 6, "quadruple(2)": 8}] + + LOREM_IPSUM_COMPRESSED = ( b"x\x9c\xed\xd1\xcdq\x03!\x0c\x05\xe0\xbb\xabP\x01\x1eW\x91\xdc|M\x01\n\xc8\x8e" b"f\xf83H\x1e\x97\x1f\x91M\x8e\xe9\xe0\xdd\x96\x05\x84\xf4\xbek\x9fRI\xc7\xf2J" @@ -885,12 +1069,9 @@ def test_query_json_with_json_cols(db_path): result = CliRunner().invoke( cli.cli, [db_path, "select id, name, friends from dogs"] ) - assert ( - r""" + assert r""" [{"id": 1, "name": "Cleo", "friends": "[{\"name\": \"Pancakes\"}, {\"name\": \"Bailey\"}]"}] - """.strip() - == result.output.strip() - ) + """.strip() == result.output.strip() # With --json-cols: result = CliRunner().invoke( cli.cli, [db_path, "select id, name, friends from dogs", "--json-cols"] @@ -904,9 +1085,37 @@ def test_query_json_with_json_cols(db_path): assert expected == result_rows.output.strip() +def test_query_json_unicode_not_escaped_by_default(db_path): + db = Database(db_path) + with db.conn: + db["text"].insert({"id": 1, "text": "Japanese 日本語"}, pk="id") + result = CliRunner().invoke(cli.cli, [db_path, "select id, text from text"]) + assert result.exit_code == 0 + assert result.output.strip() == '[{"id": 1, "text": "Japanese 日本語"}]' + # Same for --nl + result = CliRunner().invoke(cli.cli, [db_path, "select id, text from text", "--nl"]) + assert result.exit_code == 0 + assert result.output.strip() == '{"id": 1, "text": "Japanese 日本語"}' + + +@pytest.mark.parametrize("command", ["query", "rows"]) +def test_query_json_ascii_option(db_path, command): + db = Database(db_path) + with db.conn: + db["text"].insert({"id": 1, "text": "Japanese 日本語"}, pk="id") + if command == "query": + args = [db_path, "select id, text from text", "--ascii"] + else: + args = ["rows", db_path, "text", "--ascii"] + result = CliRunner().invoke(cli.cli, args) + assert result.exit_code == 0 + expected = '[{"id": 1, "text": "Japanese ' + "\\u65e5\\u672c\\u8a9e" + '"}]' + assert result.output.strip() == expected + + @pytest.mark.parametrize( "content,is_binary", - [(b"\x00\x0Fbinary", True), ("this is text", False), (1, False), (1.5, False)], + [(b"\x00\x0fbinary", True), ("this is text", False), (1, False), (1.5, False)], ) def test_query_raw(db_path, content, is_binary): Database(db_path)["files"].insert({"content": content}) @@ -921,7 +1130,7 @@ def test_query_raw(db_path, content, is_binary): @pytest.mark.parametrize( "content,is_binary", - [(b"\x00\x0Fbinary", True), ("this is text", False), (1, False), (1.5, False)], + [(b"\x00\x0fbinary", True), ("this is text", False), (1, False), (1.5, False)], ) def test_query_raw_lines(db_path, content, is_binary): Database(db_path)["files"].insert_all({"content": content} for _ in range(3)) @@ -1045,20 +1254,38 @@ def test_upsert(db_path, tmpdir): ] -def test_upsert_pk_required(db_path, tmpdir): +def test_upsert_pk_inferred_from_existing_table(db_path, tmpdir): json_path = str(tmpdir / "dogs.json") + db = Database(db_path) insert_dogs = [ {"id": 1, "name": "Cleo", "age": 4}, {"id": 2, "name": "Nixie", "age": 4}, ] write_json(json_path, insert_dogs) + result = CliRunner().invoke( + cli.cli, + ["insert", db_path, "dogs", json_path, "--pk", "id"], + catch_exceptions=False, + ) + assert result.exit_code == 0, result.output + + write_json( + json_path, + [ + {"id": 1, "age": 5}, + {"id": 2, "age": 5}, + ], + ) result = CliRunner().invoke( cli.cli, ["upsert", db_path, "dogs", json_path], catch_exceptions=False, ) - assert result.exit_code == 2 - assert "Error: Missing option '--pk'" in result.output + assert result.exit_code == 0, result.output + assert list(db.query("select * from dogs order by id")) == [ + {"id": 1, "name": "Cleo", "age": 5}, + {"id": 2, "name": "Nixie", "age": 5}, + ] def test_upsert_analyze(db_path, tmpdir): @@ -1106,11 +1333,8 @@ def test_upsert_alter(db_path, tmpdir): cli.cli, ["upsert", db_path, "dogs", json_path, "--pk", "id"] ) assert result.exit_code == 1 - assert ( - "Error: no such column: age\n\n" - "sql = UPDATE [dogs] SET [age] = ? WHERE [id] = ?\n" - "parameters = [5, 1]" - ) == result.output.strip() + # Could be one of two errors depending on SQLite version + assert ("Try using --alter to add additional columns") in result.output.strip() # Should succeed with --alter result = CliRunner().invoke( cli.cli, ["upsert", db_path, "dogs", json_path, "--pk", "id", "--alter"] @@ -1132,7 +1356,7 @@ def test_upsert_alter(db_path, tmpdir): "age", "integer", ], - ("CREATE TABLE [t] (\n [name] TEXT,\n [age] INTEGER\n)"), + ('CREATE TABLE "t" (\n "name" TEXT,\n "age" INTEGER\n)'), ), # All types: ( @@ -1151,24 +1375,32 @@ def test_upsert_alter(db_path, tmpdir): "id", ], ( - "CREATE TABLE [t] (\n" - " [id] INTEGER PRIMARY KEY,\n" - " [name] TEXT,\n" - " [age] INTEGER,\n" - " [weight] FLOAT,\n" - " [thumbnail] BLOB\n" + 'CREATE TABLE "t" (\n' + ' "id" INTEGER PRIMARY KEY,\n' + ' "name" TEXT,\n' + ' "age" INTEGER,\n' + ' "weight" FLOAT,\n' + ' "thumbnail" BLOB\n' ")" ), ), # Not null: ( ["name", "text", "--not-null", "name"], - ("CREATE TABLE [t] (\n" " [name] TEXT NOT NULL\n" ")"), + ('CREATE TABLE "t" (\n' ' "name" TEXT NOT NULL\n' ")"), ), # Default: ( ["age", "integer", "--default", "age", "3"], - ("CREATE TABLE [t] (\n" " [age] INTEGER DEFAULT '3'\n" ")"), + ('CREATE TABLE "t" (\n' " \"age\" INTEGER DEFAULT '3'\n" ")"), + ), + # Compound primary key + ( + ["category", "text", "name", "text", "--pk", "category", "--pk", "name"], + ( + 'CREATE TABLE "t" (\n "category" TEXT,\n "name" TEXT,\n' + ' PRIMARY KEY ("category", "name")\n)' + ), ), ], ) @@ -1218,16 +1450,16 @@ def test_create_table_foreign_key(): assert result.exit_code == 0 db = Database("books.db") assert ( - "CREATE TABLE [authors] (\n" - " [id] INTEGER PRIMARY KEY,\n" - " [name] TEXT\n" + 'CREATE TABLE "authors" (\n' + ' "id" INTEGER PRIMARY KEY,\n' + ' "name" TEXT\n' ")" ) == db["authors"].schema assert ( - "CREATE TABLE [books] (\n" - " [id] INTEGER PRIMARY KEY,\n" - " [title] TEXT,\n" - " [author_id] INTEGER REFERENCES [authors]([id])\n" + 'CREATE TABLE "books" (\n' + ' "id" INTEGER PRIMARY KEY,\n' + ' "title" TEXT,\n' + ' "author_id" INTEGER REFERENCES "authors"("id")\n' ")" ) == db["books"].schema @@ -1256,7 +1488,7 @@ def test_create_table_ignore(): cli.cli, ["create-table", "test.db", "dogs", "id", "integer", "--ignore"] ) assert result.exit_code == 0 - assert "CREATE TABLE [dogs] (\n [name] TEXT\n)" == db["dogs"].schema + assert 'CREATE TABLE "dogs" (\n "name" TEXT\n)' == db["dogs"].schema def test_create_table_replace(): @@ -1268,7 +1500,7 @@ def test_create_table_replace(): cli.cli, ["create-table", "test.db", "dogs", "id", "integer", "--replace"] ) assert result.exit_code == 0 - assert "CREATE TABLE [dogs] (\n [id] INTEGER\n)" == db["dogs"].schema + assert 'CREATE TABLE "dogs" (\n "id" INTEGER\n)' == db["dogs"].schema def test_create_view(): @@ -1279,7 +1511,9 @@ def test_create_view(): cli.cli, ["create-view", "test.db", "version", "select sqlite_version()"] ) assert result.exit_code == 0 - assert "CREATE VIEW version AS select sqlite_version()" == db["version"].schema + assert ( + 'CREATE VIEW "version" AS select sqlite_version()' == db["version"].schema + ) def test_create_view_error_if_view_exists(): @@ -1314,7 +1548,8 @@ def test_create_view_ignore(): ) assert result.exit_code == 0 assert ( - "CREATE VIEW version AS select sqlite_version() + 1" == db["version"].schema + 'CREATE VIEW "version" AS select sqlite_version() + 1' + == db["version"].schema ) @@ -1334,7 +1569,9 @@ def test_create_view_replace(): ], ) assert result.exit_code == 0 - assert "CREATE VIEW version AS select sqlite_version()" == db["version"].schema + assert ( + 'CREATE VIEW "version" AS select sqlite_version()' == db["version"].schema + ) def test_drop_table(): @@ -1378,6 +1615,24 @@ def test_drop_table_error(): assert result.exit_code == 0 +def test_drop_table_on_view_errors(): + runner = CliRunner() + with runner.isolated_filesystem(): + db = Database("test.db") + db["t"].insert({"id": 1}) + db.create_view("v", "select * from t") + result = runner.invoke(cli.cli, ["drop-table", "test.db", "v"]) + assert result.exit_code == 1 + assert 'Error: "v" is a view, not a table - use drop-view to drop it' == ( + result.output.strip() + ) + assert "v" in db.view_names() + # --ignore exits cleanly but must still not drop the view + result = runner.invoke(cli.cli, ["drop-table", "test.db", "v", "--ignore"]) + assert result.exit_code == 0 + assert "v" in db.view_names() + + def test_drop_view(): runner = CliRunner() with runner.isolated_filesystem(): @@ -1396,6 +1651,23 @@ def test_drop_view(): assert "hello" not in db.view_names() +def test_drop_view_on_table_errors(): + runner = CliRunner() + with runner.isolated_filesystem(): + db = Database("test.db") + db["t"].insert({"id": 1}) + result = runner.invoke(cli.cli, ["drop-view", "test.db", "t"]) + assert result.exit_code == 1 + assert 'Error: "t" is a table, not a view - use drop-table to drop it' == ( + result.output.strip() + ) + assert "t" in db.table_names() + # --ignore exits cleanly but must still not drop the table + result = runner.invoke(cli.cli, ["drop-view", "test.db", "t", "--ignore"]) + assert result.exit_code == 0 + assert "t" in db.table_names() + + def test_drop_view_error(): runner = CliRunner() with runner.isolated_filesystem(): @@ -1522,9 +1794,9 @@ def test_add_foreign_keys(db_path): [], ( 'CREATE TABLE "dogs" (\n' - " [id] INTEGER PRIMARY KEY,\n" - " [age] INTEGER NOT NULL DEFAULT '1',\n" - " [name] TEXT\n" + ' "id" INTEGER PRIMARY KEY,\n' + " \"age\" INTEGER NOT NULL DEFAULT '1',\n" + ' "name" TEXT\n' ")" ), ), @@ -1532,9 +1804,9 @@ def test_add_foreign_keys(db_path): ["--type", "age", "text"], ( 'CREATE TABLE "dogs" (\n' - " [id] INTEGER PRIMARY KEY,\n" - " [age] TEXT NOT NULL DEFAULT '1',\n" - " [name] TEXT\n" + ' "id" INTEGER PRIMARY KEY,\n' + " \"age\" TEXT NOT NULL DEFAULT '1',\n" + ' "name" TEXT\n' ")" ), ), @@ -1542,8 +1814,8 @@ def test_add_foreign_keys(db_path): ["--drop", "age"], ( 'CREATE TABLE "dogs" (\n' - " [id] INTEGER PRIMARY KEY,\n" - " [name] TEXT\n" + ' "id" INTEGER PRIMARY KEY,\n' + ' "name" TEXT\n' ")" ), ), @@ -1551,9 +1823,9 @@ def test_add_foreign_keys(db_path): ["--rename", "age", "age2", "--rename", "id", "pk"], ( 'CREATE TABLE "dogs" (\n' - " [pk] INTEGER PRIMARY KEY,\n" - " [age2] INTEGER NOT NULL DEFAULT '1',\n" - " [name] TEXT\n" + ' "pk" INTEGER PRIMARY KEY,\n' + " \"age2\" INTEGER NOT NULL DEFAULT '1',\n" + ' "name" TEXT\n' ")" ), ), @@ -1561,9 +1833,9 @@ def test_add_foreign_keys(db_path): ["--not-null", "name"], ( 'CREATE TABLE "dogs" (\n' - " [id] INTEGER PRIMARY KEY,\n" - " [age] INTEGER NOT NULL DEFAULT '1',\n" - " [name] TEXT NOT NULL\n" + ' "id" INTEGER PRIMARY KEY,\n' + " \"age\" INTEGER NOT NULL DEFAULT '1',\n" + ' "name" TEXT NOT NULL\n' ")" ), ), @@ -1571,9 +1843,9 @@ def test_add_foreign_keys(db_path): ["--not-null-false", "age"], ( 'CREATE TABLE "dogs" (\n' - " [id] INTEGER PRIMARY KEY,\n" - " [age] INTEGER DEFAULT '1',\n" - " [name] TEXT\n" + ' "id" INTEGER PRIMARY KEY,\n' + " \"age\" INTEGER DEFAULT '1',\n" + ' "name" TEXT\n' ")" ), ), @@ -1581,9 +1853,9 @@ def test_add_foreign_keys(db_path): ["--pk", "name"], ( 'CREATE TABLE "dogs" (\n' - " [id] INTEGER,\n" - " [age] INTEGER NOT NULL DEFAULT '1',\n" - " [name] TEXT PRIMARY KEY\n" + ' "id" INTEGER,\n' + " \"age\" INTEGER NOT NULL DEFAULT '1',\n" + ' "name" TEXT PRIMARY KEY\n' ")" ), ), @@ -1591,9 +1863,9 @@ def test_add_foreign_keys(db_path): ["--pk-none"], ( 'CREATE TABLE "dogs" (\n' - " [id] INTEGER,\n" - " [age] INTEGER NOT NULL DEFAULT '1',\n" - " [name] TEXT\n" + ' "id" INTEGER,\n' + " \"age\" INTEGER NOT NULL DEFAULT '1',\n" + ' "name" TEXT\n' ")" ), ), @@ -1601,9 +1873,9 @@ def test_add_foreign_keys(db_path): ["--default", "name", "Turnip"], ( 'CREATE TABLE "dogs" (\n' - " [id] INTEGER PRIMARY KEY,\n" - " [age] INTEGER NOT NULL DEFAULT '1',\n" - " [name] TEXT DEFAULT 'Turnip'\n" + ' "id" INTEGER PRIMARY KEY,\n' + " \"age\" INTEGER NOT NULL DEFAULT '1',\n" + " \"name\" TEXT DEFAULT 'Turnip'\n" ")" ), ), @@ -1611,9 +1883,9 @@ def test_add_foreign_keys(db_path): ["--default-none", "age"], ( 'CREATE TABLE "dogs" (\n' - " [id] INTEGER PRIMARY KEY,\n" - " [age] INTEGER NOT NULL,\n" - " [name] TEXT\n" + ' "id" INTEGER PRIMARY KEY,\n' + ' "age" INTEGER NOT NULL,\n' + ' "name" TEXT\n' ")" ), ), @@ -1621,9 +1893,9 @@ def test_add_foreign_keys(db_path): ["-o", "name", "--column-order", "age", "-o", "id"], ( 'CREATE TABLE "dogs" (\n' - " [name] TEXT,\n" - " [age] INTEGER NOT NULL DEFAULT '1',\n" - " [id] INTEGER PRIMARY KEY\n" + ' "name" TEXT,\n' + " \"age\" INTEGER NOT NULL DEFAULT '1',\n" + ' "id" INTEGER PRIMARY KEY\n' ")" ), ), @@ -1645,6 +1917,87 @@ def test_transform(db_path, args, expected_schema): assert schema == expected_schema +def test_transform_sql(db_path): + db = Database(db_path) + with db.conn: + db["dogs"].insert( + {"id": 1, "age": 4, "name": "Cleo"}, + not_null={"age"}, + defaults={"age": 1}, + pk="id", + ) + original_schema = db["dogs"].schema + + result = CliRunner().invoke( + cli.cli, ["transform", db_path, "dogs", "--drop", "name", "--sql"] + ) + + assert result.exit_code == 0, result.output + assert 'CREATE TABLE "dogs_new_' in result.output + assert '"age" INTEGER NOT NULL DEFAULT' in result.output + assert 'DROP TABLE "dogs";' in result.output + assert 'ALTER TABLE "dogs_new_' in result.output + assert db["dogs"].schema == original_schema + + +@pytest.mark.parametrize( + "initial_strict,args,expected_strict", + ( + (False, [], False), + (True, [], True), + (False, ["--strict"], True), + (True, ["--no-strict"], False), + ), +) +def test_transform_strict_option(db_path, initial_strict, args, expected_strict): + db = Database(db_path) + if not db.supports_strict: + pytest.skip("SQLite version does not support strict tables") + db["dogs"].create({"id": int}, strict=initial_strict) + + result = CliRunner().invoke(cli.cli, ["transform", db_path, "dogs"] + args) + + assert result.exit_code == 0, result.output + assert db["dogs"].strict is expected_strict + + +@pytest.mark.parametrize( + "initial_strict,flag,sql_is_strict", + ( + (False, "--strict", True), + (True, "--no-strict", False), + ), +) +def test_transform_strict_option_sql(db_path, initial_strict, flag, sql_is_strict): + db = Database(db_path) + if not db.supports_strict: + pytest.skip("SQLite version does not support strict tables") + db["dogs"].create({"id": int}, strict=initial_strict) + + result = CliRunner().invoke(cli.cli, ["transform", db_path, "dogs", flag, "--sql"]) + + assert result.exit_code == 0, result.output + assert (") STRICT;" in result.output) is sql_is_strict + assert db["dogs"].strict is initial_strict + + +def test_transform_strict_option_with_invalid_data(db_path): + db = Database(db_path) + if not db.supports_strict: + pytest.skip("SQLite version does not support strict tables") + dogs = db["dogs"] + dogs.create({"id": int}) + dogs.insert({"id": "not-an-integer"}) + + result = CliRunner().invoke(cli.cli, ["transform", db_path, "dogs", "--strict"]) + + assert result.exit_code == 1 + assert isinstance(result.exception, sqlite3.IntegrityError) + assert dogs.strict is False + assert list(dogs.rows) == [{"id": "not-an-integer"}] + assert not any(name.startswith("dogs_new_") for name in db.table_names()) + + @pytest.mark.parametrize( "extra_args,expected_schema", ( @@ -1652,11 +2005,11 @@ def test_transform(db_path, args, expected_schema): ["--drop-foreign-key", "country"], ( 'CREATE TABLE "places" (\n' - " [id] INTEGER PRIMARY KEY,\n" - " [name] TEXT,\n" - " [country] INTEGER,\n" - " [city] INTEGER REFERENCES [city]([id]),\n" - " [continent] INTEGER\n" + ' "id" INTEGER PRIMARY KEY,\n' + ' "name" TEXT,\n' + ' "country" INTEGER,\n' + ' "city" INTEGER REFERENCES "city"("id"),\n' + ' "continent" INTEGER\n' ")" ), ), @@ -1664,11 +2017,11 @@ def test_transform(db_path, args, expected_schema): ["--drop-foreign-key", "country", "--drop-foreign-key", "city"], ( 'CREATE TABLE "places" (\n' - " [id] INTEGER PRIMARY KEY,\n" - " [name] TEXT,\n" - " [country] INTEGER,\n" - " [city] INTEGER,\n" - " [continent] INTEGER\n" + ' "id" INTEGER PRIMARY KEY,\n' + ' "name" TEXT,\n' + ' "country" INTEGER,\n' + ' "city" INTEGER,\n' + ' "continent" INTEGER\n' ")" ), ), @@ -1676,11 +2029,11 @@ def test_transform(db_path, args, expected_schema): ["--add-foreign-key", "continent", "continent", "id"], ( 'CREATE TABLE "places" (\n' - " [id] INTEGER PRIMARY KEY,\n" - " [name] TEXT,\n" - " [country] INTEGER REFERENCES [country]([id]),\n" - " [city] INTEGER REFERENCES [city]([id]),\n" - " [continent] INTEGER REFERENCES [continent]([id])\n" + ' "id" INTEGER PRIMARY KEY,\n' + ' "name" TEXT,\n' + ' "country" INTEGER REFERENCES "country"("id"),\n' + ' "city" INTEGER REFERENCES "city"("id"),\n' + ' "continent" INTEGER REFERENCES "continent"("id")\n' ")" ), ), @@ -1719,7 +2072,7 @@ def test_transform_add_or_drop_foreign_key(db_path, extra_args, expected_schema) _common_other_schema = ( - "CREATE TABLE [species] (\n [id] INTEGER PRIMARY KEY,\n [species] TEXT\n)" + 'CREATE TABLE "species" (\n "id" INTEGER PRIMARY KEY,\n "species" TEXT\n)' ) @@ -1730,9 +2083,9 @@ _common_other_schema = ( [], ( 'CREATE TABLE "trees" (\n' - " [id] INTEGER PRIMARY KEY,\n" - " [address] TEXT,\n" - " [species_id] INTEGER REFERENCES [species]([id])\n" + ' "id" INTEGER PRIMARY KEY,\n' + ' "address" TEXT,\n' + ' "species_id" INTEGER REFERENCES "species"("id")\n' ")" ), _common_other_schema, @@ -1741,20 +2094,20 @@ _common_other_schema = ( ["--table", "custom_table"], ( 'CREATE TABLE "trees" (\n' - " [id] INTEGER PRIMARY KEY,\n" - " [address] TEXT,\n" - " [custom_table_id] INTEGER REFERENCES [custom_table]([id])\n" + ' "id" INTEGER PRIMARY KEY,\n' + ' "address" TEXT,\n' + ' "custom_table_id" INTEGER REFERENCES "custom_table"("id")\n' ")" ), - "CREATE TABLE [custom_table] (\n [id] INTEGER PRIMARY KEY,\n [species] TEXT\n)", + 'CREATE TABLE "custom_table" (\n "id" INTEGER PRIMARY KEY,\n "species" TEXT\n)', ), ( ["--fk-column", "custom_fk"], ( 'CREATE TABLE "trees" (\n' - " [id] INTEGER PRIMARY KEY,\n" - " [address] TEXT,\n" - " [custom_fk] INTEGER REFERENCES [species]([id])\n" + ' "id" INTEGER PRIMARY KEY,\n' + ' "address" TEXT,\n' + ' "custom_fk" INTEGER REFERENCES "species"("id")\n' ")" ), _common_other_schema, @@ -1762,11 +2115,11 @@ _common_other_schema = ( ( ["--rename", "name", "name2"], 'CREATE TABLE "trees" (\n' - " [id] INTEGER PRIMARY KEY,\n" - " [address] TEXT,\n" - " [species_id] INTEGER REFERENCES [species]([id])\n" + ' "id" INTEGER PRIMARY KEY,\n' + ' "address" TEXT,\n' + ' "species_id" INTEGER REFERENCES "species"("id")\n' ")", - "CREATE TABLE [species] (\n [id] INTEGER PRIMARY KEY,\n [species] TEXT\n)", + 'CREATE TABLE "species" (\n "id" INTEGER PRIMARY KEY,\n "species" TEXT\n)', ), ], ) @@ -1816,7 +2169,16 @@ def test_insert_encoding(tmpdir): # Using --encoding=latin-1 should work good_result = CliRunner().invoke( cli.cli, - ["insert", db_path, "places", csv_path, "--encoding", "latin-1", "--csv"], + [ + "insert", + db_path, + "places", + csv_path, + "--encoding", + "latin-1", + "--csv", + "--no-detect-types", + ], catch_exceptions=False, ) assert good_result.exit_code == 0 @@ -1897,12 +2259,10 @@ def test_search_quote(tmpdir): def test_indexes(tmpdir): db_path = str(tmpdir / "test.db") db = Database(db_path) - db.conn.executescript( - """ + db.conn.executescript(""" create table Gosh (c1 text, c2 text, c3 text); create index Gosh_idx on Gosh(c2, c3 desc); - """ - ) + """) result = CliRunner().invoke( cli.cli, ["indexes", str(db_path)], @@ -1993,16 +2353,12 @@ def test_triggers(tmpdir, extra_args, expected): pk="id", ) db["counter"].insert({"count": 1}) - db.conn.execute( - textwrap.dedent( - """ + db.conn.execute(textwrap.dedent(""" CREATE TRIGGER blah AFTER INSERT ON articles BEGIN UPDATE counter SET count = count + 1; END - """ - ) - ) + """)) args = ["triggers", db_path] if extra_args: args.extend(extra_args) @@ -2021,34 +2377,34 @@ def test_triggers(tmpdir, extra_args, expected): ( [], ( - "CREATE TABLE [dogs] (\n" - " [id] INTEGER,\n" - " [name] TEXT\n" + 'CREATE TABLE "dogs" (\n' + ' "id" INTEGER,\n' + ' "name" TEXT\n' ");\n" - "CREATE TABLE [chickens] (\n" - " [id] INTEGER,\n" - " [name] TEXT,\n" - " [breed] TEXT\n" + 'CREATE TABLE "chickens" (\n' + ' "id" INTEGER,\n' + ' "name" TEXT,\n' + ' "breed" TEXT\n' ");\n" - "CREATE INDEX [idx_chickens_breed]\n" - " ON [chickens] ([breed]);\n" + 'CREATE INDEX "idx_chickens_breed"\n' + ' ON "chickens" ("breed");\n' ), ), ( ["dogs"], - ("CREATE TABLE [dogs] (\n" " [id] INTEGER,\n" " [name] TEXT\n" ")\n"), + ('CREATE TABLE "dogs" (\n' ' "id" INTEGER,\n' ' "name" TEXT\n' ")\n"), ), ( ["chickens", "dogs"], ( - "CREATE TABLE [chickens] (\n" - " [id] INTEGER,\n" - " [name] TEXT,\n" - " [breed] TEXT\n" + 'CREATE TABLE "chickens" (\n' + ' "id" INTEGER,\n' + ' "name" TEXT,\n' + ' "breed" TEXT\n' ")\n" - "CREATE TABLE [dogs] (\n" - " [id] INTEGER,\n" - " [name] TEXT\n" + 'CREATE TABLE "dogs" (\n' + ' "id" INTEGER,\n' + ' "name" TEXT\n' ")\n" ), ), @@ -2072,11 +2428,10 @@ def test_schema(tmpdir, options, expected): def test_long_csv_column_value(tmpdir): db_path = str(tmpdir / "test.db") csv_path = str(tmpdir / "test.csv") - csv_file = open(csv_path, "w") - long_string = "a" * 131073 - csv_file.write("id,text\n") - csv_file.write("1,{}\n".format(long_string)) - csv_file.close() + with open(csv_path, "w") as csv_file: + long_string = "a" * 131073 + csv_file.write("id,text\n") + csv_file.write("1,{}\n".format(long_string)) result = CliRunner().invoke( cli.cli, ["insert", db_path, "bigtable", csv_path, "--csv"], @@ -2100,24 +2455,23 @@ def test_long_csv_column_value(tmpdir): def test_import_no_headers(tmpdir, args, tsv): db_path = str(tmpdir / "test.db") csv_path = str(tmpdir / "test.csv") - csv_file = open(csv_path, "w") - sep = "\t" if tsv else "," - csv_file.write("Cleo{sep}Dog{sep}5\n".format(sep=sep)) - csv_file.write("Tracy{sep}Spider{sep}7\n".format(sep=sep)) - csv_file.close() + with open(csv_path, "w") as csv_file: + sep = "\t" if tsv else "," + csv_file.write("Cleo{sep}Dog{sep}5\n".format(sep=sep)) + csv_file.write("Tracy{sep}Spider{sep}7\n".format(sep=sep)) result = CliRunner().invoke( cli.cli, - ["insert", db_path, "creatures", csv_path] + args, + ["insert", db_path, "creatures", csv_path] + args + ["--no-detect-types"], catch_exceptions=False, ) assert result.exit_code == 0, result.output db = Database(db_path) schema = db["creatures"].schema assert schema == ( - "CREATE TABLE [creatures] (\n" - " [untitled_1] TEXT,\n" - " [untitled_2] TEXT,\n" - " [untitled_3] TEXT\n" + 'CREATE TABLE "creatures" (\n' + ' "untitled_1" TEXT,\n' + ' "untitled_2" TEXT,\n' + ' "untitled_3" TEXT\n' ")" ) rows = list(db["creatures"].rows) @@ -2156,61 +2510,73 @@ def test_csv_insert_bom(tmpdir): fp.write(b"\xef\xbb\xbfname,age\nCleo,5") result = CliRunner().invoke( cli.cli, - ["insert", db_path, "broken", bom_csv_path, "--encoding", "utf-8", "--csv"], + [ + "insert", + db_path, + "broken", + bom_csv_path, + "--encoding", + "utf-8", + "--csv", + "--no-detect-types", + ], catch_exceptions=False, ) assert result.exit_code == 0 result2 = CliRunner().invoke( cli.cli, - ["insert", db_path, "fixed", bom_csv_path, "--csv"], + ["insert", db_path, "fixed", bom_csv_path, "--csv", "--no-detect-types"], catch_exceptions=False, ) assert result2.exit_code == 0 db = Database(db_path) tables = db.execute("select name, sql from sqlite_master").fetchall() assert tables == [ - ("broken", "CREATE TABLE [broken] (\n [\ufeffname] TEXT,\n [age] TEXT\n)"), - ("fixed", "CREATE TABLE [fixed] (\n [name] TEXT,\n [age] TEXT\n)"), + ("broken", 'CREATE TABLE "broken" (\n "\ufeffname" TEXT,\n "age" TEXT\n)'), + ("fixed", 'CREATE TABLE "fixed" (\n "name" TEXT,\n "age" TEXT\n)'), ] -@pytest.mark.parametrize("option_or_env_var", (None, "-d", "--detect-types")) -def test_insert_detect_types(tmpdir, option_or_env_var): +def test_insert_detect_types(tmpdir): + """Test that type detection is the default behavior""" db_path = str(tmpdir / "test.db") data = "name,age,weight\nCleo,6,45.5\nDori,1,3.5" - extra = [] - if option_or_env_var: - extra = [option_or_env_var] - def _test(): - result = CliRunner().invoke( - cli.cli, - ["insert", db_path, "creatures", "-", "--csv"] + extra, - catch_exceptions=False, - input=data, - ) - assert result.exit_code == 0 - db = Database(db_path) - assert list(db["creatures"].rows) == [ - {"name": "Cleo", "age": 6, "weight": 45.5}, - {"name": "Dori", "age": 1, "weight": 3.5}, - ] - - if option_or_env_var is None: - # Use environment variable instead of option - with mock.patch.dict(os.environ, {"SQLITE_UTILS_DETECT_TYPES": "1"}): - _test() - else: - _test() + result = CliRunner().invoke( + cli.cli, + ["insert", db_path, "creatures", "-", "--csv"], + catch_exceptions=False, + input=data, + ) + assert result.exit_code == 0 + db = Database(db_path) + assert list(db["creatures"].rows) == [ + {"name": "Cleo", "age": 6, "weight": 45.5}, + {"name": "Dori", "age": 1, "weight": 3.5}, + ] +@pytest.mark.parametrize("command", ("insert", "upsert")) @pytest.mark.parametrize("option", ("-d", "--detect-types")) -def test_upsert_detect_types(tmpdir, option): +def test_detect_types_flag_removed(tmpdir, command, option): + # The old no-op flag was removed in 4.0 - it should now error + db_path = str(tmpdir / "test.db") + result = CliRunner().invoke( + cli.cli, + [command, db_path, "creatures", "-", "--csv", "--pk", "id", option], + input="id,name\n1,Cleo", + ) + assert result.exit_code == 2 + assert "No such option" in result.output + + +def test_upsert_detect_types(tmpdir): + """Test that type detection is the default behavior for upsert""" db_path = str(tmpdir / "test.db") data = "id,name,age,weight\n1,Cleo,6,45.5\n2,Dori,1,3.5" result = CliRunner().invoke( cli.cli, - ["upsert", db_path, "creatures", "-", "--csv", "--pk", "id"] + [option], + ["upsert", db_path, "creatures", "-", "--csv", "--pk", "id"], catch_exceptions=False, input=data, ) @@ -2222,6 +2588,90 @@ def test_upsert_detect_types(tmpdir, option): ] +def test_csv_detect_types_creates_real_columns(tmpdir): + """Test that CSV import creates REAL columns for floats (default behavior)""" + db_path = str(tmpdir / "test.db") + data = "name,age,weight\nCleo,6,45.5\nDori,1,3.5" + result = CliRunner().invoke( + cli.cli, + ["insert", db_path, "creatures", "-", "--csv"], + catch_exceptions=False, + input=data, + ) + assert result.exit_code == 0 + db = Database(db_path) + # Check that the schema uses REAL for the weight column + assert db["creatures"].schema == ( + 'CREATE TABLE "creatures" (\n' + ' "name" TEXT,\n' + ' "age" INTEGER,\n' + ' "weight" REAL\n' + ")" + ) + + +def test_insert_no_detect_types(tmpdir): + """Test that --no-detect-types treats all columns as TEXT""" + db_path = str(tmpdir / "test.db") + data = "name,age,weight\nCleo,6,45.5\nDori,1,3.5" + result = CliRunner().invoke( + cli.cli, + ["insert", db_path, "creatures", "-", "--csv", "--no-detect-types"], + catch_exceptions=False, + input=data, + ) + assert result.exit_code == 0 + db = Database(db_path) + # All columns should be TEXT when --no-detect-types is used + assert list(db["creatures"].rows) == [ + {"name": "Cleo", "age": "6", "weight": "45.5"}, + {"name": "Dori", "age": "1", "weight": "3.5"}, + ] + assert db["creatures"].schema == ( + 'CREATE TABLE "creatures" (\n' + ' "name" TEXT,\n' + ' "age" TEXT,\n' + ' "weight" TEXT\n' + ")" + ) + + +def test_upsert_no_detect_types(tmpdir): + """Test that --no-detect-types treats all columns as TEXT for upsert""" + db_path = str(tmpdir / "test.db") + data = "id,name,age,weight\n1,Cleo,6,45.5\n2,Dori,1,3.5" + result = CliRunner().invoke( + cli.cli, + [ + "upsert", + db_path, + "creatures", + "-", + "--csv", + "--pk", + "id", + "--no-detect-types", + ], + catch_exceptions=False, + input=data, + ) + assert result.exit_code == 0 + db = Database(db_path) + # All columns should be TEXT when --no-detect-types is used + assert list(db["creatures"].rows) == [ + {"id": "1", "name": "Cleo", "age": "6", "weight": "45.5"}, + {"id": "2", "name": "Dori", "age": "1", "weight": "3.5"}, + ] + assert db["creatures"].schema == ( + 'CREATE TABLE "creatures" (\n' + ' "id" TEXT PRIMARY KEY,\n' + ' "name" TEXT,\n' + ' "age" TEXT,\n' + ' "weight" TEXT\n' + ")" + ) + + def test_integer_overflow_error(tmpdir): db_path = str(tmpdir / "test.db") result = CliRunner().invoke( @@ -2232,7 +2682,7 @@ def test_integer_overflow_error(tmpdir): assert result.exit_code == 1 assert result.output == ( "Error: Python int too large to convert to SQLite INTEGER\n\n" - "sql = INSERT INTO [items] ([bignumber]) VALUES (?);\n" + 'sql = INSERT INTO "items" ("bignumber") VALUES (?)\n' "parameters = [34223049823094832094802398430298048240]\n" ) @@ -2391,3 +2841,53 @@ def test_load_extension(entrypoint, should_pass, should_fail): catch_exceptions=False, ) assert result.exit_code == 1 + + +@pytest.mark.parametrize("strict", (False, True)) +def test_create_table_strict(strict): + runner = CliRunner() + with runner.isolated_filesystem(): + db = Database("test.db") + result = runner.invoke( + cli.cli, + ["create-table", "test.db", "items", "id", "integer", "w", "float"] + + (["--strict"] if strict else []), + ) + assert result.exit_code == 0 + assert db["items"].strict == strict or not db.supports_strict + # Should have a floating point column + assert db["items"].columns_dict == {"id": int, "w": float} + + +@pytest.mark.parametrize("method", ("insert", "upsert")) +@pytest.mark.parametrize("strict", (False, True)) +def test_insert_upsert_strict(tmpdir, method, strict): + db_path = str(tmpdir / "test.db") + result = CliRunner().invoke( + cli.cli, + [method, db_path, "items", "-", "--csv", "--pk", "id"] + + (["--strict"] if strict else []), + input="id\n1", + ) + assert result.exit_code == 0 + db = Database(db_path) + assert db["items"].strict == strict or not db.supports_strict + + +def test_extract_bad_column_clean_error(db_path): + db = Database(db_path) + db["trees"].insert({"id": 1, "species": "Palm"}, pk="id") + result = CliRunner().invoke(cli.cli, ["extract", db_path, "trees", "nope"]) + assert result.exit_code == 1 + assert result.exception is None or isinstance(result.exception, SystemExit) + assert result.output.startswith("Error: Invalid columns") + + +def test_extract_view_clean_error(db_path): + db = Database(db_path) + db["trees"].insert({"id": 1, "species": "Palm"}, pk="id") + db.create_view("v", "select * from trees") + result = CliRunner().invoke(cli.cli, ["extract", db_path, "v", "species"]) + assert result.exit_code == 1 + assert result.exception is None or isinstance(result.exception, SystemExit) + assert result.output.startswith("Error:") diff --git a/tests/test_cli_bulk.py b/tests/test_cli_bulk.py index 909ed09..514f4ac 100644 --- a/tests/test_cli_bulk.py +++ b/tests/test_cli_bulk.py @@ -45,6 +45,32 @@ def test_cli_bulk(test_db_and_path): ] == list(db["example"].rows) +def test_cli_bulk_multiple_functions(test_db_and_path): + db, db_path = test_db_and_path + result = CliRunner().invoke( + cli.cli, + [ + "bulk", + db_path, + "insert into example (id, name) values (:id, myupper(mylower(:name)))", + "-", + "--nl", + "--functions", + "myupper = lambda s: s.upper()", + "--functions", + "mylower = lambda s: s.lower()", + ], + input='{"id": 3, "name": "ThReE"}\n{"id": 4, "name": "FoUr"}\n', + ) + assert result.exit_code == 0, result.output + assert [ + {"id": 1, "name": "One"}, + {"id": 2, "name": "Two"}, + {"id": 3, "name": "THREE"}, + {"id": 4, "name": "FOUR"}, + ] == list(db["example"].rows) + + def test_cli_bulk_batch_size(test_db_and_path): db, db_path = test_db_and_path proc = subprocess.Popen( diff --git a/tests/test_cli_convert.py b/tests/test_cli_convert.py index 53c33be..6c3f5c5 100644 --- a/tests/test_cli_convert.py +++ b/tests/test_cli_convert.py @@ -80,7 +80,7 @@ def test_convert_import(test_db_and_path): db_path, "example", "dt", - "return re.sub('O..', 'OXX', value)", + "return re.sub('O..', 'OXX', value) if value else value", "--import", "re", ], @@ -215,6 +215,25 @@ def test_convert_multi_dryrun(test_db_and_path): ) +def test_convert_multi_dryrun_unicode_not_escaped(test_db_and_path): + db_path = test_db_and_path[1] + result = CliRunner().invoke( + cli.cli, + [ + "convert", + db_path, + "example", + "dt", + "{'text': 'Japanese 日本語'}", + "--dry-run", + "--multi", + ], + ) + assert result.exit_code == 0 + # Preview should match what jsonify_if_needed() would actually store + assert '{"text": "Japanese 日本語"}' in result.output + + @pytest.mark.parametrize("drop", (True, False)) def test_convert_output_column(test_db_and_path, drop): db, db_path = test_db_and_path @@ -223,7 +242,7 @@ def test_convert_output_column(test_db_and_path, drop): db_path, "example", "dt", - "value.replace('October', 'Spooktober')", + "value.replace('October', 'Spooktober') if value else value", "--output", "newcol", ] @@ -371,16 +390,14 @@ def test_convert_multi_complex_column_types(fresh_db_and_path): ], pk="id", ) - code = textwrap.dedent( - """ + code = textwrap.dedent(""" if value == 1: return {"is_str": "", "is_float": 1.2, "is_int": None} elif value == 2: return {"is_float": 1, "is_int": 12} elif value == 3: return {"is_bytes": b"blah"} - """ - ) + """) result = CliRunner().invoke( cli.cli, [ @@ -406,9 +423,9 @@ def test_convert_multi_complex_column_types(fresh_db_and_path): {"id": 4, "is_str": None, "is_float": None, "is_int": None, "is_bytes": None}, ] assert db["rows"].schema == ( - "CREATE TABLE [rows] (\n" - " [id] INTEGER PRIMARY KEY\n" - ", [is_str] TEXT, [is_float] FLOAT, [is_int] INTEGER, [is_bytes] BLOB)" + 'CREATE TABLE "rows" (\n' + ' "id" INTEGER PRIMARY KEY\n' + ', "is_str" TEXT, "is_float" REAL, "is_int" INTEGER, "is_bytes" BLOB)' ) @@ -535,7 +552,7 @@ def test_convert_where(test_db_and_path): "id = :id", "-p", "id", - 2, + "2", ], ) assert result.exit_code == 0, result.output @@ -564,7 +581,7 @@ def test_convert_where_multi(fresh_db_and_path): "id = :id", "-p", "id", - 2, + "2", "--multi", ], ) @@ -628,14 +645,8 @@ def test_convert_initialization_pattern(fresh_db_and_path): ] -@pytest.mark.parametrize( - "no_skip_false,expected", - ( - (True, 1), - (False, 0), - ), -) -def test_convert_no_skip_false(fresh_db_and_path, no_skip_false, expected): +def test_convert_handles_falsey_values(fresh_db_and_path): + # Falsey values like 0 should be converted (issue #527) db, db_path = fresh_db_and_path args = [ "convert", @@ -644,12 +655,58 @@ def test_convert_no_skip_false(fresh_db_and_path, no_skip_false, expected): "x", "-", ] - if no_skip_false: - args.append("--no-skip-false") db["t"].insert_all([{"x": 0}, {"x": 1}]) assert db["t"].get(1)["x"] == 0 assert db["t"].get(2)["x"] == 1 result = CliRunner().invoke(cli.cli, args, input="value + 1") assert result.exit_code == 0, result.output - assert db["t"].get(1)["x"] == expected + assert db["t"].get(1)["x"] == 1 assert db["t"].get(2)["x"] == 2 + + +@pytest.mark.parametrize( + "code", + [ + # Direct callable reference (issue #686) + "r.parsedate", + "recipes.parsedate", + # Traditional call syntax still works + "r.parsedate(value)", + "recipes.parsedate(value)", + ], +) +def test_convert_callable_reference(test_db_and_path, code): + """Test that callable references like r.parsedate work without (value)""" + db, db_path = test_db_and_path + result = CliRunner().invoke( + cli.cli, ["convert", db_path, "example", "dt", code], catch_exceptions=False + ) + assert result.exit_code == 0, result.output + rows = list(db["example"].rows) + assert rows[0]["dt"] == "2019-10-05" + assert rows[1]["dt"] == "2019-10-06" + assert rows[2]["dt"] == "" + assert rows[3]["dt"] is None + + +def test_convert_callable_reference_with_import(fresh_db_and_path): + """Test callable reference from an imported module""" + db, db_path = fresh_db_and_path + db["example"].insert({"id": 1, "data": '{"name": "test"}'}) + result = CliRunner().invoke( + cli.cli, + [ + "convert", + db_path, + "example", + "data", + "json.loads", + "--import", + "json", + ], + catch_exceptions=False, + ) + assert result.exit_code == 0, result.output + # json.loads returns a dict, which sqlite stores as JSON string + row = db["example"].get(1) + assert row["data"] == '{"name": "test"}' diff --git a/tests/test_cli_insert.py b/tests/test_cli_insert.py index e1dfd50..df6f80c 100644 --- a/tests/test_cli_insert.py +++ b/tests/test_cli_insert.py @@ -77,19 +77,24 @@ def test_insert_json_flatten_nl(tmpdir): ] -def test_insert_with_primary_key(db_path, tmpdir): +@pytest.mark.parametrize( + "args,expected_pks", + ( + (["--pk", "id"], ["id"]), + (["--pk", "id", "--pk", "name"], ["id", "name"]), + ), +) +def test_insert_with_primary_keys(db_path, tmpdir, args, expected_pks): json_path = str(tmpdir / "dog.json") with open(json_path, "w") as fp: fp.write(json.dumps({"id": 1, "name": "Cleo", "age": 4})) - result = CliRunner().invoke( - cli.cli, ["insert", db_path, "dogs", json_path, "--pk", "id"] - ) + result = CliRunner().invoke(cli.cli, ["insert", db_path, "dogs", json_path] + args) assert result.exit_code == 0 assert [{"id": 1, "age": 4, "name": "Cleo"}] == list( Database(db_path).query("select * from dogs") ) db = Database(db_path) - assert ["id"] == db["dogs"].pks + assert db["dogs"].pks == expected_pks def test_insert_multiple_with_primary_key(db_path, tmpdir): @@ -122,12 +127,12 @@ def test_insert_multiple_with_compound_primary_key(db_path, tmpdir): assert dogs == list(db.query("select * from dogs order by breed, id")) assert {"breed", "id"} == set(db["dogs"].pks) assert ( - "CREATE TABLE [dogs] (\n" - " [breed] TEXT,\n" - " [id] INTEGER,\n" - " [name] TEXT,\n" - " [age] INTEGER,\n" - " PRIMARY KEY ([id], [breed])\n" + 'CREATE TABLE "dogs" (\n' + ' "breed" TEXT,\n' + ' "id" INTEGER,\n' + ' "name" TEXT,\n' + ' "age" INTEGER,\n' + ' PRIMARY KEY ("id", "breed")\n' ")" ) == db["dogs"].schema @@ -149,11 +154,11 @@ def test_insert_not_null_default(db_path, tmpdir): assert result.exit_code == 0 db = Database(db_path) assert ( - "CREATE TABLE [dogs] (\n" - " [id] INTEGER PRIMARY KEY,\n" - " [name] TEXT NOT NULL,\n" - " [age] INTEGER NOT NULL DEFAULT '1',\n" - " [score] INTEGER DEFAULT '5'\n)" + 'CREATE TABLE "dogs" (\n' + ' "id" INTEGER PRIMARY KEY,\n' + ' "name" TEXT NOT NULL,\n' + " \"age\" INTEGER NOT NULL DEFAULT '1',\n" + " \"score\" INTEGER DEFAULT '5'\n)" ) == db["dogs"].schema @@ -222,7 +227,7 @@ def test_insert_csv_tsv(content, options, db_path, tmpdir): fp.write(content) result = CliRunner().invoke( cli.cli, - ["insert", db_path, "data", file_path] + options, + ["insert", db_path, "data", file_path] + options + ["--no-detect-types"], catch_exceptions=False, ) assert result.exit_code == 0 @@ -231,7 +236,7 @@ def test_insert_csv_tsv(content, options, db_path, tmpdir): @pytest.mark.parametrize("empty_null", (True, False)) def test_insert_csv_empty_null(db_path, empty_null): - options = ["--csv"] + options = ["--csv", "--no-detect-types"] if empty_null: options.append("--empty-null") result = CliRunner().invoke( @@ -425,7 +430,7 @@ def test_insert_text(db_path): "options,input", ( ([], '[{"id": "1", "name": "Bob"}, {"id": "2", "name": "Cat"}]'), - (["--csv"], "id,name\n1,Bob\n2,Cat"), + (["--csv", "--no-detect-types"], "id,name\n1,Bob\n2,Cat"), (["--nl"], '{"id": "1", "name": "Bob"}\n{"id": "2", "name": "Cat"}'), ), ) @@ -461,7 +466,7 @@ def test_insert_convert_text(db_path): ) assert result.exit_code == 0, result.output db = Database(db_path) - rows = list(db.query("select [text] from [text]")) + rows = list(db.query('select "text" from "text"')) assert rows == [{"text": "THIS IS TEXT\nWILL BE UPPER NOW"}] @@ -481,7 +486,7 @@ def test_insert_convert_text_returning_iterator(db_path): ) assert result.exit_code == 0, result.output db = Database(db_path) - rows = list(db.query("select [word] from [text]")) + rows = list(db.query('select "word" from "text"')) assert rows == [{"word": "A"}, {"word": "bunch"}, {"word": "of"}, {"word": "words"}] @@ -501,7 +506,7 @@ def test_insert_convert_lines(db_path): ) assert result.exit_code == 0, result.output db = Database(db_path) - rows = list(db.query("select [line] from [all]")) + rows = list(db.query('select "line" from "all"')) assert rows == [{"line": "THIS IS TEXT"}, {"line": "WILL BE UPPER NOW"}] @@ -592,3 +597,294 @@ def test_insert_streaming_batch_size_1(db_path): proc.stdin.close() proc.wait() assert proc.returncode == 0 + + +def test_insert_csv_headers_only(tmpdir): + """Test that CSV with only header row (no data) works with --detect-types (issue #702)""" + db_path = str(tmpdir / "test.db") + csv_path = str(tmpdir / "headers_only.csv") + with open(csv_path, "w") as fp: + fp.write("id,name,age\n") + # Should not crash with --detect-types (which is now the default) + result = CliRunner().invoke( + cli.cli, + ["insert", db_path, "data", csv_path, "--csv"], + catch_exceptions=False, + ) + assert result.exit_code == 0 + # Table should not exist since there were no data rows + db = Database(db_path) + assert not db["data"].exists() + + +def test_insert_into_view_errors(tmpdir): + db_path = str(tmpdir / "test.db") + db = Database(db_path) + db["t"].insert({"id": 1}) + db.create_view("v", "select * from t") + db.close() + result = CliRunner().invoke( + cli.cli, ["insert", db_path, "v", "-"], input='{"id": 2}' + ) + assert result.exit_code == 1 + assert result.output.strip() == "Error: Table v is actually a view" + + +def test_insert_csv_detect_types_leaves_existing_table_alone(db_path): + # Type detection is the default for CSV/TSV inserts, but it must only + # apply to tables created by this command - transforming a pre-existing + # table would rewrite its column types and corrupt data such as + # TEXT zip codes with leading zeros + db = Database(db_path) + db["places"].insert({"name": "Boston", "zip": "01234"}) + result = CliRunner().invoke( + cli.cli, + ["insert", db_path, "places", "-", "--csv"], + catch_exceptions=False, + input="name,zip\nSF,94107", + ) + assert result.exit_code == 0, result.output + assert db["places"].columns_dict["zip"] is str + assert list(db["places"].rows) == [ + {"name": "Boston", "zip": "01234"}, + {"name": "SF", "zip": "94107"}, + ] + + +def test_insert_csv_detect_types_new_table(db_path): + # A table created by the insert still gets detected types + result = CliRunner().invoke( + cli.cli, + ["insert", db_path, "data", "-", "--csv"], + catch_exceptions=False, + input="name,age,weight\nCleo,5,12.5", + ) + assert result.exit_code == 0, result.output + db = Database(db_path) + assert db["data"].columns_dict == {"name": str, "age": int, "weight": float} + + +@pytest.mark.parametrize( + "command,extra_args,input_text,expected_row", + ( + ( + "insert", + [], + "zipcode,score\n01234,9.5\n", + {"zipcode": "01234", "score": 9.5}, + ), + ( + "upsert", + ["--pk", "id"], + "id,zipcode,score\n1,01234,9.5\n", + {"id": 1, "zipcode": "01234", "score": 9.5}, + ), + ), +) +def test_insert_upsert_csv_type_overrides_detected_types( + db_path, command, extra_args, input_text, expected_row +): + result = CliRunner().invoke( + cli.cli, + [ + command, + db_path, + "places", + "-", + "--csv", + ] + + extra_args + + [ + "--type", + "zipcode", + "text", + ], + catch_exceptions=False, + input=input_text, + ) + assert result.exit_code == 0, result.output + db = Database(db_path) + expected_columns = {"zipcode": str, "score": float} + if command == "upsert": + expected_columns = {"id": int, **expected_columns} + assert db["places"].columns_dict == expected_columns + assert list(db["places"].rows) == [expected_row] + + +def test_upsert_csv_detect_types_leaves_existing_table_alone(db_path): + db = Database(db_path) + db["places"].insert({"id": 1, "name": "Boston", "zip": "01234"}, pk="id") + result = CliRunner().invoke( + cli.cli, + ["upsert", db_path, "places", "-", "--csv", "--pk", "id"], + catch_exceptions=False, + input="id,name,zip\n2,SF,94107", + ) + assert result.exit_code == 0, result.output + assert db["places"].columns_dict["zip"] is str + assert db["places"].get(1)["zip"] == "01234" + + +def test_insert_invalid_pk_clean_error(db_path): + # An invalid --pk against an existing table should be a clean CLI + # error, not a raw InvalidColumns traceback + db = Database(db_path) + db["t"].insert({"a": 1}) + result = CliRunner().invoke( + cli.cli, + ["insert", db_path, "t", "-", "--pk", "badcol"], + input='{"a": 2}', + ) + assert result.exit_code == 1 + assert result.exception is None or isinstance(result.exception, SystemExit) + assert result.output.startswith("Error: Invalid primary key column") + + +# --code tests, see https://github.com/simonw/sqlite-utils/issues/684 +CODE_ROWS_FUNCTION = """ +def rows(): + yield {"id": 1, "name": "Cleo"} + yield {"id": 2, "name": "Suna"} +""" + +CODE_ROWS_ITERABLE = """ +rows = [ + {"id": 1, "name": "Cleo"}, + {"id": 2, "name": "Suna"}, +] +""" + + +@pytest.mark.parametrize("code", (CODE_ROWS_FUNCTION, CODE_ROWS_ITERABLE)) +def test_insert_code(tmpdir, code): + db_path = str(tmpdir / "dogs.db") + result = CliRunner().invoke( + cli.cli, + ["insert", db_path, "creatures", "--code", code, "--pk", "id"], + ) + assert result.exit_code == 0, result.output + db = Database(db_path) + assert db["creatures"].pks == ["id"] + assert list(db["creatures"].rows) == [ + {"id": 1, "name": "Cleo"}, + {"id": 2, "name": "Suna"}, + ] + + +def test_insert_code_from_file(tmpdir): + db_path = str(tmpdir / "dogs.db") + code_path = str(tmpdir / "gen.py") + with open(code_path, "w") as fp: + fp.write(CODE_ROWS_FUNCTION) + result = CliRunner().invoke( + cli.cli, + ["insert", db_path, "creatures", "--code", code_path], + ) + assert result.exit_code == 0, result.output + assert list(Database(db_path)["creatures"].rows) == [ + {"id": 1, "name": "Cleo"}, + {"id": 2, "name": "Suna"}, + ] + + +def test_upsert_code(tmpdir): + db_path = str(tmpdir / "dogs.db") + db = Database(db_path) + db["creatures"].insert_all( + [{"id": 1, "name": "old"}, {"id": 2, "name": "Suna"}], pk="id" + ) + result = CliRunner().invoke( + cli.cli, + ["upsert", db_path, "creatures", "--code", CODE_ROWS_FUNCTION, "--pk", "id"], + ) + assert result.exit_code == 0, result.output + assert list(db["creatures"].rows) == [ + {"id": 1, "name": "Cleo"}, + {"id": 2, "name": "Suna"}, + ] + + +def test_insert_code_requires_file_or_code(tmpdir): + db_path = str(tmpdir / "dogs.db") + result = CliRunner().invoke(cli.cli, ["insert", db_path, "creatures"]) + assert result.exit_code == 1 + assert "Provide either a FILE argument or --code" in result.output + + +def test_insert_code_mutually_exclusive_with_file(tmpdir): + db_path = str(tmpdir / "dogs.db") + result = CliRunner().invoke( + cli.cli, + ["insert", db_path, "creatures", "-", "--code", CODE_ROWS_FUNCTION], + input="{}", + ) + assert result.exit_code == 1 + assert "--code cannot be used with a FILE argument" in result.output + + +def test_insert_code_rejects_input_format_options(tmpdir): + db_path = str(tmpdir / "dogs.db") + result = CliRunner().invoke( + cli.cli, + ["insert", db_path, "creatures", "--code", CODE_ROWS_FUNCTION, "--csv"], + ) + assert result.exit_code == 1 + assert "--code cannot be used with input format options" in result.output + + +def test_insert_code_missing_rows(tmpdir): + db_path = str(tmpdir / "dogs.db") + result = CliRunner().invoke( + cli.cli, + ["insert", db_path, "creatures", "--code", "x = 1"], + ) + assert result.exit_code == 1 + assert "must define a 'rows' function or iterable" in result.output + + +def test_insert_code_single_dict(tmpdir): + db_path = str(tmpdir / "dogs.db") + result = CliRunner().invoke( + cli.cli, + [ + "insert", + db_path, + "creatures", + "--code", + 'rows = {"id": 1, "name": "Cleo"}', + "--pk", + "id", + ], + ) + assert result.exit_code == 0, result.output + assert list(Database(db_path)["creatures"].rows) == [{"id": 1, "name": "Cleo"}] + + +def test_insert_code_not_iterable(tmpdir): + db_path = str(tmpdir / "dogs.db") + result = CliRunner().invoke( + cli.cli, + ["insert", db_path, "creatures", "--code", "rows = 5"], + ) + assert result.exit_code == 1 + assert "must define a 'rows' function or iterable" in result.output + + +def test_insert_code_syntax_error(tmpdir): + db_path = str(tmpdir / "dogs.db") + result = CliRunner().invoke( + cli.cli, + ["insert", db_path, "creatures", "--code", "def rows(:"], + ) + assert result.exit_code == 1 + assert "Error in --code" in result.output + + +def test_insert_code_file_not_found(tmpdir): + db_path = str(tmpdir / "dogs.db") + result = CliRunner().invoke( + cli.cli, + ["insert", db_path, "creatures", "--code", "missing.py"], + ) + assert result.exit_code == 1 + assert "File not found: missing.py" in result.output diff --git a/tests/test_cli_memory.py b/tests/test_cli_memory.py index f69de22..2ed4aaa 100644 --- a/tests/test_cli_memory.py +++ b/tests/test_cli_memory.py @@ -1,5 +1,5 @@ +import click import json - import pytest from click.testing import CliRunner @@ -156,6 +156,24 @@ def test_memory_csv_encoding(tmpdir, use_stdin): } +def test_memory_csv_headers_only(tmpdir): + csv_path = str(tmpdir / "headers_only.csv") + with open(csv_path, "w") as fp: + fp.write("id,name,age\n") + + result = CliRunner().invoke( + cli.cli, + ["memory", csv_path, "", "--schema"], + catch_exceptions=False, + ) + + assert result.exit_code == 0 + assert result.output.strip() == ( + 'CREATE VIEW "t1" AS select * from "headers_only";\n' + 'CREATE VIEW "t" AS select * from "headers_only";' + ) + + @pytest.mark.parametrize("extra_args", ([], ["select 1"])) def test_memory_dump(extra_args): result = CliRunner().invoke( @@ -167,13 +185,13 @@ def test_memory_dump(extra_args): expected = ( "BEGIN TRANSACTION;\n" 'CREATE TABLE IF NOT EXISTS "stdin" (\n' - " [id] INTEGER,\n" - " [name] TEXT\n" + ' "id" INTEGER,\n' + ' "name" TEXT\n' ");\n" "INSERT INTO \"stdin\" VALUES(1,'Cleo');\n" "INSERT INTO \"stdin\" VALUES(2,'Bants');\n" - "CREATE VIEW t1 AS select * from [stdin];\n" - "CREATE VIEW t AS select * from [stdin];\n" + 'CREATE VIEW "t1" AS select * from "stdin";\n' + 'CREATE VIEW "t" AS select * from "stdin";\n' "COMMIT;" ) # Using sqlite-dump it won't have IF NOT EXISTS @@ -191,11 +209,11 @@ def test_memory_schema(extra_args): assert result.exit_code == 0 assert result.output.strip() == ( 'CREATE TABLE "stdin" (\n' - " [id] INTEGER,\n" - " [name] TEXT\n" + ' "id" INTEGER,\n' + ' "name" TEXT\n' ");\n" - "CREATE VIEW t1 AS select * from [stdin];\n" - "CREATE VIEW t AS select * from [stdin];" + 'CREATE VIEW "t1" AS select * from "stdin";\n' + 'CREATE VIEW "t" AS select * from "stdin";' ) @@ -285,16 +303,16 @@ def test_memory_two_files_with_same_stem(tmpdir): assert result.exit_code == 0 assert result.output == ( 'CREATE TABLE "data" (\n' - " [id] INTEGER,\n" - " [name] TEXT\n" + ' "id" INTEGER,\n' + ' "name" TEXT\n' ");\n" - "CREATE VIEW t1 AS select * from [data];\n" - "CREATE VIEW t AS select * from [data];\n" + 'CREATE VIEW "t1" AS select * from "data";\n' + 'CREATE VIEW "t" AS select * from "data";\n' 'CREATE TABLE "data_2" (\n' - " [id] INTEGER,\n" - " [name] TEXT\n" + ' "id" INTEGER,\n' + ' "name" TEXT\n' ");\n" - "CREATE VIEW t2 AS select * from [data_2];\n" + 'CREATE VIEW "t2" AS select * from "data_2";\n' ) @@ -305,3 +323,33 @@ def test_memory_functions(): ) assert result.exit_code == 0 assert result.output.strip() == '[{"hello()": "Hello"}]' + + +def test_memory_functions_multiple(): + result = CliRunner().invoke( + cli.cli, + [ + "memory", + "select triple(2), quadruple(2)", + "--functions", + "def triple(x):\n return x * 3", + "--functions", + "def quadruple(x):\n return x * 4", + ], + ) + assert result.exit_code == 0 + assert result.output.strip() == '[{"triple(2)": 6, "quadruple(2)": 8}]' + + +def test_memory_return_db(tmpdir): + # https://github.com/simonw/sqlite-utils/issues/643 + from sqlite_utils.cli import cli + + path = str(tmpdir / "dogs.csv") + with open(path, "w") as f: + f.write("id,name\n1,Cleo") + + with click.Context(cli) as ctx: # type: ignore[attr-defined] + db = ctx.invoke(cli.commands["memory"], paths=(path,), return_db=True) + + assert db.table_names() == ["dogs"] diff --git a/tests/test_cli_migrate.py b/tests/test_cli_migrate.py new file mode 100644 index 0000000..0f29e36 --- /dev/null +++ b/tests/test_cli_migrate.py @@ -0,0 +1,507 @@ +import pathlib + +from click.testing import CliRunner +import pytest +import sqlite_utils +import sqlite_utils.cli + +TWO_MIGRATIONS = """ +from sqlite_utils import Migrations + +m = Migrations("hello") + +@m() +def foo(db): + db["foo"].insert({"hello": "world"}) + +@m() +def bar(db): + db["bar"].insert({"hello": "world"}) +""" + + +@pytest.fixture +def two_migrations(tmpdir): + path = pathlib.Path(tmpdir) + (path / "foo").mkdir() + migrations_py = path / "foo" / "migrations.py" + migrations_py.write_text(TWO_MIGRATIONS, "utf-8") + return path, migrations_py + + +@pytest.fixture +def two_sets_same_migration_name(tmpdir): + path = pathlib.Path(tmpdir) + migrations_py = path / "migrations.py" + migrations_py.write_text( + """ +from sqlite_utils import Migrations + +creatures = Migrations("creatures") + +@creatures() +def create_table(db): + db["creatures"].insert({"name": "Cleo"}) + +@creatures() +def add_weight(db): + db["creature_weights"].insert({"weight": 4.2}) + +sales = Migrations("sales") + +@sales() +def create_table(db): + db["sales"].insert({"id": 1}) + +@sales() +def add_weight(db): + db["sales_weights"].insert({"weight": 10}) +""", + "utf-8", + ) + return path, migrations_py + + +@pytest.mark.parametrize("arg", ("TMPDIR", "TMPDIR/foo/migrations.py", "TMPDIR/foo/")) +def test_basic(two_migrations, arg): + path, _ = two_migrations + db_path = str(path / "test.db") + + runner = CliRunner() + + def _list(): + list_result = runner.invoke( + sqlite_utils.cli.cli, + ["migrate", db_path, "--list", arg.replace("TMPDIR", str(path))], + ) + assert list_result.exit_code == 0 + return list_result.output + + assert _list() == ( + "Migrations for: hello\n\n" + " Applied:\n\n" + " Pending:\n" + " foo\n" + " bar\n\n" + ) + + result = runner.invoke( + sqlite_utils.cli.cli, ["migrate", db_path, arg.replace("TMPDIR", str(path))] + ) + assert result.exit_code == 0, result.output + + list_output = _list() + assert "Migrations for: hello\n\n Applied:\n " in list_output + prior_to_pending = list_output.split(" Pending")[0] + assert " foo" in prior_to_pending + assert " bar" in prior_to_pending + assert " Pending:\n (none)" in list_output + + db = sqlite_utils.Database(db_path) + assert db["foo"].exists() + assert db["bar"].exists() + assert db["_sqlite_migrations"].exists() + rows = list(db["_sqlite_migrations"].rows) + assert len(rows) == 2 + assert rows[0]["name"] == "foo" + assert rows[1]["name"] == "bar" + + +def test_list_same_migration_names_in_different_sets(capsys): + applied = sqlite_utils.Migrations("applied") + + @applied(name="foo") + def applied_foo(db): + db["applied"].insert({"hello": "world"}) + + pending = sqlite_utils.Migrations("pending") + + @pending(name="foo") + def pending_foo(db): + db["pending"].insert({"hello": "world"}) + + db = sqlite_utils.Database(memory=True) + applied.apply(db) + + sqlite_utils.cli._display_migration_list(db, [applied, pending]) + + output = capsys.readouterr().out + assert ( + "Migrations for: pending\n\n" " Applied:\n\n" " Pending:\n" " foo\n\n" + ) in output + + +def test_verbose(tmpdir): + path = pathlib.Path(tmpdir) + (path / "foo").mkdir() + migrations_py = path / "foo" / "migrations.py" + migrations_py.write_text( + """ +from sqlite_utils import Migrations + +m = Migrations("hello") + +@m() +def foo(db): + db["dogs"].insert({"id": 1, "name": "Cleo"}) + """, + "utf-8", + ) + db_path = str(path / "test.db") + runner = CliRunner() + result = runner.invoke( + sqlite_utils.cli.cli, ["migrate", db_path, str(migrations_py)] + ) + assert result.exit_code == 0 + + result = runner.invoke( + sqlite_utils.cli.cli, ["migrate", db_path, str(migrations_py), "--verbose"] + ) + assert result.exit_code == 0 + expected = """ +Schema before: + + CREATE TABLE "_sqlite_migrations" ( + "id" INTEGER PRIMARY KEY, + "migration_set" TEXT, + "name" TEXT, + "applied_at" TEXT + ); + CREATE UNIQUE INDEX "idx__sqlite_migrations_migration_set_name" + ON "_sqlite_migrations" ("migration_set", "name"); + CREATE TABLE "dogs" ( + "id" INTEGER, + "name" TEXT + ); + +Schema after: + + (unchanged) +""".strip() + assert expected in result.output + + new_migration = """ +@m() +def bar(db): + db["dogs"].add_column("age", int) + db["dogs"].add_column("weight", float) + db["dogs"].transform() +""" + migrations_py.write_text(migrations_py.read_text("utf-8") + new_migration) + + result = runner.invoke( + sqlite_utils.cli.cli, ["migrate", db_path, str(migrations_py), "--verbose"] + ) + assert result.exit_code == 0 + expected_diff = """ +Schema diff: + + ON "_sqlite_migrations" ("migration_set", "name"); + CREATE TABLE "dogs" ( + "id" INTEGER, +- "name" TEXT ++ "name" TEXT, ++ "age" INTEGER, ++ "weight" REAL + ); +""".strip() + assert expected_diff in result.output + + +def test_stop_before(two_migrations): + path, _ = two_migrations + db_path = str(path / "test.db") + result = CliRunner().invoke( + sqlite_utils.cli.cli, + [ + "migrate", + db_path, + str(path / "foo" / "migrations.py"), + "--stop-before", + "bar", + ], + ) + assert result.exit_code == 0 + db = sqlite_utils.Database(db_path) + assert db["foo"].exists() + assert not db["bar"].exists() + + +def test_stop_before_multiple_sets_unqualified(two_migrations): + path, _ = two_migrations + db_path = str(path / "test.db") + (path / "foo" / "migrations2.py").write_text( + """ +from sqlite_utils import Migrations + +m = Migrations("hello2") + +@m() +def foo(db): + db["foo"].insert({"hello": "world"}) + """, + "utf-8", + ) + result = CliRunner().invoke( + sqlite_utils.cli.cli, + [ + "migrate", + db_path, + str(path / "foo" / "migrations.py"), + str(path / "foo" / "migrations2.py"), + "--stop-before", + "foo", + ], + ) + assert result.exit_code == 0, result.output + db = sqlite_utils.Database(db_path) + assert db.table_names() == ["_sqlite_migrations"] + assert list(db["_sqlite_migrations"].rows) == [] + + +def test_stop_before_qualified_only_affects_named_set(two_sets_same_migration_name): + path, migrations_py = two_sets_same_migration_name + db_path = str(path / "test.db") + result = CliRunner().invoke( + sqlite_utils.cli.cli, + [ + "migrate", + db_path, + str(migrations_py), + "--stop-before", + "creatures:add_weight", + ], + ) + assert result.exit_code == 0, result.output + db = sqlite_utils.Database(db_path) + assert db["creatures"].exists() + assert not db["creature_weights"].exists() + assert db["sales"].exists() + assert db["sales_weights"].exists() + + +def test_stop_before_multiple_qualified(two_sets_same_migration_name): + path, migrations_py = two_sets_same_migration_name + db_path = str(path / "test.db") + result = CliRunner().invoke( + sqlite_utils.cli.cli, + [ + "migrate", + db_path, + str(migrations_py), + "--stop-before", + "creatures:add_weight", + "--stop-before", + "sales:add_weight", + ], + ) + assert result.exit_code == 0, result.output + db = sqlite_utils.Database(db_path) + assert db["creatures"].exists() + assert not db["creature_weights"].exists() + assert db["sales"].exists() + assert not db["sales_weights"].exists() + + +LEGACY_MIGRATIONS = """ +import datetime + +class _Migration: + def __init__(self, name, fn): + self.name = name + self.fn = fn + +class _Applied: + def __init__(self, name, applied_at): + self.name = name + self.applied_at = applied_at + +class LegacyMigrations: + # Mimics the sqlite-migrate 0.x Migrations class, in particular + # apply(db, stop_before=None) taking a single string + migrations_table = "_sqlite_migrations" + + def __init__(self, name): + self.name = name + self._migrations = [] + + def __call__(self, fn): + self._migrations.append(_Migration(fn.__name__, fn)) + return fn + + def ensure_migrations_table(self, db): + db[self.migrations_table].create( + {"migration_set": str, "name": str, "applied_at": str}, + pk=("migration_set", "name"), + if_not_exists=True, + ) + + def applied(self, db): + self.ensure_migrations_table(db) + return [ + _Applied(row["name"], row["applied_at"]) + for row in db[self.migrations_table].rows_where( + "migration_set = ?", [self.name] + ) + ] + + def pending(self, db): + applied = {m.name for m in self.applied(db)} + return [m for m in self._migrations if m.name not in applied] + + def apply(self, db, stop_before=None): + for migration in self.pending(db): + if migration.name == stop_before: + return + migration.fn(db) + db[self.migrations_table].insert( + { + "migration_set": self.name, + "name": migration.name, + "applied_at": str( + datetime.datetime.now(datetime.timezone.utc) + ), + } + ) + +legacy = LegacyMigrations("legacy_set") + +@legacy +def first(db): + db["first"].insert({"hello": "world"}) + +@legacy +def second(db): + db["second"].insert({"hello": "world"}) +""" + + +def test_stop_before_unknown_name_errors(two_migrations): + path, _ = two_migrations + db_path = str(path / "test.db") + runner = CliRunner() + result = runner.invoke( + sqlite_utils.cli.cli, + ["migrate", db_path, str(path), "--stop-before", "fooo"], + ) + assert result.exit_code == 1 + assert "--stop-before did not match any migrations: fooo" in result.output + # Nothing should have been applied + db = sqlite_utils.Database(db_path) + assert "foo" not in db.table_names() + assert "bar" not in db.table_names() + + +def test_stop_before_with_legacy_migrations_class(tmpdir): + path = pathlib.Path(tmpdir) + (path / "migrations.py").write_text(LEGACY_MIGRATIONS, "utf-8") + db_path = str(path / "test.db") + runner = CliRunner() + result = runner.invoke( + sqlite_utils.cli.cli, + ["migrate", db_path, str(path), "--stop-before", "second"], + ) + assert result.exit_code == 0, result.output + db = sqlite_utils.Database(db_path) + assert "first" in db.table_names() + assert "second" not in db.table_names() + + +def test_stop_before_multiple_values_for_legacy_set_errors(tmpdir): + path = pathlib.Path(tmpdir) + (path / "migrations.py").write_text(LEGACY_MIGRATIONS, "utf-8") + db_path = str(path / "test.db") + runner = CliRunner() + result = runner.invoke( + sqlite_utils.cli.cli, + [ + "migrate", + db_path, + str(path), + "--stop-before", + "legacy_set:first", + "--stop-before", + "legacy_set:second", + ], + ) + assert result.exit_code == 1 + assert "single --stop-before" in result.output + + +def test_list_does_not_create_database_file(two_migrations): + path, _ = two_migrations + db_path = path / "test.db" + runner = CliRunner() + result = runner.invoke( + sqlite_utils.cli.cli, ["migrate", str(db_path), str(path), "--list"] + ) + assert result.exit_code == 0, result.output + assert "Pending:\n foo\n bar" in result.output + # Listing migrations must not create the database file + assert not db_path.exists() + + +def test_list_does_not_upgrade_legacy_migrations_table(two_migrations): + path, _ = two_migrations + db_path = str(path / "test.db") + db = sqlite_utils.Database(db_path) + db["_sqlite_migrations"].create( + {"migration_set": str, "name": str, "applied_at": str}, + pk=("migration_set", "name"), + ) + db["_sqlite_migrations"].insert( + {"migration_set": "hello", "name": "foo", "applied_at": "x"} + ) + db.close() + runner = CliRunner() + result = runner.invoke( + sqlite_utils.cli.cli, ["migrate", db_path, str(path), "--list"] + ) + assert result.exit_code == 0, result.output + assert "foo - x" in result.output + # --list must not perform the one-way legacy schema upgrade + db2 = sqlite_utils.Database(db_path) + assert db2["_sqlite_migrations"].pks == ["migration_set", "name"] + db2.close() + + +def test_stop_before_applied_migration_errors(two_migrations): + path, _ = two_migrations + db_path = str(path / "test.db") + migrations_path = str(path / "foo" / "migrations.py") + # Apply everything first + first = CliRunner().invoke( + sqlite_utils.cli.cli, + ["migrate", db_path, migrations_path, "--stop-before", "bar"], + ) + assert first.exit_code == 0 + # foo is now applied - stopping before it is an error, and bar + # must not be applied as a side effect + result = CliRunner().invoke( + sqlite_utils.cli.cli, + ["migrate", db_path, migrations_path, "--stop-before", "foo"], + ) + assert result.exit_code != 0 + assert "already been applied" in result.output + db = sqlite_utils.Database(db_path) + assert not db["bar"].exists() + + +def test_list_with_legacy_class_is_read_only(tmpdir): + # Legacy sqlite-migrate classes create the _sqlite_migrations table + # from their pending()/applied() methods - --list must roll that + # back so it stays a read-only operation as documented + path = pathlib.Path(tmpdir) + (path / "migrations.py").write_text(LEGACY_MIGRATIONS, "utf-8") + db_path = str(path / "test.db") + db = sqlite_utils.Database(db_path) + db["existing"].insert({"id": 1}) + db.close() + result = CliRunner().invoke( + sqlite_utils.cli.cli, ["migrate", db_path, str(path), "--list"] + ) + assert result.exit_code == 0, result.output + assert "first" in result.output + db2 = sqlite_utils.Database(db_path) + assert "_sqlite_migrations" not in db2.table_names() + db2.close() diff --git a/tests/test_column_casing.py b/tests/test_column_casing.py new file mode 100644 index 0000000..ce11345 --- /dev/null +++ b/tests/test_column_casing.py @@ -0,0 +1,233 @@ +""" +SQLite treats column names as case-insensitive. These tests exercise the +places where sqlite-utils performs Python-side lookups of column names +provided by the caller, which should match the schema case-insensitively. + +https://github.com/simonw/sqlite-utils/issues/760 +""" + +import pytest + +from sqlite_utils import Database +from sqlite_utils.db import ForeignKey + + +def test_insert_populates_last_pk_case_insensitively(fresh_db): + books = fresh_db["books"] + books.create({"Id": int, "Title": str}, pk="Id") + books.insert({"Id": 1, "Title": "One"}, pk="id") + assert books.last_pk == 1 + + +def test_insert_populates_last_pk_compound_pk_case_insensitively(fresh_db): + books = fresh_db["books"] + books.create({"Author": str, "Position": int, "Title": str}) + books.insert( + {"Author": "Sue", "Position": 1, "Title": "One"}, pk=("author", "position") + ) + assert books.last_pk == ("Sue", 1) + + +@pytest.mark.parametrize("use_old_upsert", (False, True)) +def test_upsert_pk_case_differs_from_schema(use_old_upsert): + db = Database(memory=True, use_old_upsert=use_old_upsert) + books = db["books"] + books.create({"Id": int, "Title": str}, pk="Id") + books.insert({"Id": 1, "Title": "One"}) + books.upsert({"id": 1, "title": "Won"}, pk="id") + assert list(books.rows) == [{"Id": 1, "Title": "Won"}] + assert books.last_pk == 1 + + +@pytest.mark.parametrize("use_old_upsert", (False, True)) +def test_upsert_record_key_case_differs_from_pk(use_old_upsert): + # all_columns comes from the record keys, pk= from the caller + db = Database(memory=True, use_old_upsert=use_old_upsert) + books = db["books"] + books.create({"Id": int, "Title": str}, pk="Id") + books.upsert({"ID": 1, "Title": "One"}, pk="id") + assert list(books.rows) == [{"Id": 1, "Title": "One"}] + assert books.last_pk == 1 + + +def test_upsert_inferred_pk_case_differs_from_record_keys(fresh_db): + # pk is inferred from the existing schema as "Id", records use "id" + books = fresh_db["books"] + books.create({"Id": int, "Title": str}, pk="Id") + books.upsert({"id": 1, "title": "One"}) + assert list(books.rows) == [{"Id": 1, "Title": "One"}] + assert books.last_pk == 1 + + +def test_upsert_list_mode_pk_case_insensitive(fresh_db): + books = fresh_db["books"] + books.create({"Id": int, "Title": str}, pk="Id") + books.upsert_all([["id", "title"], [1, "One"]], pk="Id") + assert list(books.rows) == [{"Id": 1, "Title": "One"}] + assert books.last_pk == 1 + + +def test_lookup_pk_case_insensitive(fresh_db): + fresh_db["species"].create({"ID": int, "Name": str}, pk="ID") + fresh_db["species"].insert({"ID": 5, "Name": "Palm"}) + fresh_db["species"].create_index(["Name"], unique=True) + assert fresh_db["species"].lookup({"Name": "Palm"}, pk="id") == 5 + + +def test_lookup_does_not_create_redundant_index(fresh_db): + fresh_db["species"].create({"id": int, "Name": str}, pk="id") + fresh_db["species"].create_index(["Name"], unique=True) + fresh_db["species"].lookup({"name": "Palm"}) + assert len(fresh_db["species"].indexes) == 1 + + +def test_create_table_transform_same_columns_different_case(fresh_db): + fresh_db["t"].create({"Name": str, "Age": int}) + fresh_db["t"].insert({"Name": "Cleo", "Age": 5}) + fresh_db.create_table("t", {"name": str, "age": int}, transform=True) + # Schema casing is preserved - SQLite considers these the same columns + assert fresh_db["t"].columns_dict == {"Name": str, "Age": int} + assert list(fresh_db["t"].rows) == [{"Name": "Cleo", "Age": 5}] + + +def test_create_table_transform_case_insensitive_with_changes(fresh_db): + fresh_db["t"].create({"Name": str, "Age": int}) + fresh_db.create_table("t", {"name": str, "age": str, "size": int}, transform=True) + # age changed type, size added, Name untouched + assert fresh_db["t"].columns_dict == {"Name": str, "Age": str, "size": int} + + +def test_transform_types_case_insensitive(fresh_db): + fresh_db["t"].create({"Name": str, "Age": str}) + fresh_db["t"].transform(types={"age": int}) + assert fresh_db["t"].columns_dict == {"Name": str, "Age": int} + + +def test_transform_rename_case_insensitive(fresh_db): + fresh_db["t"].create({"Name": str}) + fresh_db["t"].transform(rename={"name": "title"}) + assert fresh_db["t"].columns_dict == {"title": str} + + +def test_transform_drop_case_insensitive(fresh_db): + fresh_db["t"].create({"Name": str, "Age": int}) + fresh_db["t"].transform(drop=["name"]) + assert fresh_db["t"].columns_dict == {"Age": int} + + +def test_transform_not_null_and_defaults_case_insensitive(fresh_db): + fresh_db["t"].create({"Name": str, "Age": int}) + fresh_db["t"].transform(not_null={"name"}, defaults={"age": 3}) + columns = {c.name: c for c in fresh_db["t"].columns} + assert columns["Name"].notnull + assert fresh_db["t"].default_values == {"Age": 3} + + +def test_transform_pk_case_insensitive(fresh_db): + fresh_db["t"].create({"Id": int, "Name": str}) + fresh_db["t"].transform(pk="id") + assert fresh_db["t"].pks == ["Id"] + assert fresh_db["t"].columns_dict == {"Id": int, "Name": str} + + +def test_transform_drop_foreign_keys_case_insensitive(fresh_db): + fresh_db["parent"].create({"Id": int}, pk="Id") + fresh_db["child"].create( + {"id": int, "Parent_ID": int}, + pk="id", + foreign_keys=[("Parent_ID", "parent", "Id")], + ) + fresh_db["child"].transform(drop_foreign_keys=["parent_id"]) + assert fresh_db["child"].foreign_keys == [] + + +def test_add_foreign_key_case_insensitive(fresh_db): + fresh_db["parent"].create({"Id": int}, pk="Id") + fresh_db["child"].create({"id": int, "Parent_ID": int}, pk="id") + fresh_db["child"].add_foreign_key("parent_id", "parent", "id") + fks = fresh_db["child"].foreign_keys + assert len(fks) == 1 + # The foreign key should use the schema casing of the columns + assert fks[0].column == "Parent_ID" + assert fks[0].other_column == "Id" + + +def test_add_foreign_keys_case_insensitive(fresh_db): + fresh_db["parent"].create({"Id": int}, pk="Id") + fresh_db["child"].create({"id": int, "Parent_ID": int}, pk="id") + fresh_db.add_foreign_keys([("child", "parent_id", "parent", "id")]) + fks = fresh_db["child"].foreign_keys + assert len(fks) == 1 + assert fks[0].column == "Parent_ID" + assert fks[0].other_column == "Id" + + +def test_add_foreign_key_detects_existing_case_insensitively(fresh_db): + fresh_db["parent"].create({"Id": int}, pk="Id") + fresh_db["child"].create( + {"id": int, "Parent_ID": int}, + pk="id", + foreign_keys=[("Parent_ID", "parent", "Id")], + ) + # ignore=True should treat this as already existing, not add a duplicate + fresh_db["child"].add_foreign_key("parent_id", "parent", "id", ignore=True) + assert len(fresh_db["child"].foreign_keys) == 1 + + +def test_add_column_fk_col_case_insensitive(fresh_db): + fresh_db["parent"].create({"Id": int}, pk="Id") + fresh_db["child"].create({"id": int}, pk="id") + fresh_db["child"].add_column("parent_id", int, fk="parent", fk_col="id") + fks = fresh_db["child"].foreign_keys + assert len(fks) == 1 + assert fks[0].other_column == "Id" + + +def test_extract_case_insensitive(fresh_db): + fresh_db["trees"].insert({"id": 1, "Species": "Palm"}, pk="id") + fresh_db["trees"].extract("species") + assert fresh_db["trees"].columns_dict == {"id": int, "Species_id": int} + assert list(fresh_db["Species"].rows) == [{"id": 1, "Species": "Palm"}] + + +def test_convert_multi_case_insensitive(fresh_db): + fresh_db["t"].insert({"id": 1, "Name": "Cleo"}, pk="id") + fresh_db["t"].convert("name", lambda v: {"upper": v.upper()}, multi=True) + assert list(fresh_db["t"].rows) == [{"id": 1, "Name": "Cleo", "upper": "CLEO"}] + + +def test_convert_output_case_insensitive(fresh_db): + fresh_db["t"].insert({"id": 1, "Name": "Cleo", "Upper": None}, pk="id") + fresh_db["t"].convert("name", lambda v: v.upper(), output="upper") + assert list(fresh_db["t"].rows) == [{"id": 1, "Name": "Cleo", "Upper": "CLEO"}] + + +def test_create_table_sql_pk_case_insensitive(fresh_db): + fresh_db["t"].create({"Id": int, "Name": str}, pk="id") + # Should not have created an extra lowercase "id" column + assert fresh_db["t"].columns_dict == {"Id": int, "Name": str} + assert fresh_db["t"].pks == ["Id"] + + +def test_create_table_not_null_and_defaults_case_insensitive(fresh_db): + fresh_db["t"].create( + {"Name": str, "Age": int}, not_null={"name"}, defaults={"age": 1} + ) + columns = {c.name: c for c in fresh_db["t"].columns} + assert columns["Name"].notnull + assert fresh_db["t"].default_values == {"Age": 1} + + +def test_create_table_foreign_keys_case_insensitive(fresh_db): + fresh_db["parent"].create({"Id": int}, pk="Id") + fresh_db["child"].create( + {"id": int, "Parent_ID": int}, + pk="id", + foreign_keys=[("parent_id", "parent", "id")], + ) + fks = fresh_db["child"].foreign_keys + assert fks == [ + ForeignKey( + table="child", column="Parent_ID", other_table="parent", other_column="Id" + ) + ] diff --git a/tests/test_constructor.py b/tests/test_constructor.py index 8743911..a619fba 100644 --- a/tests/test_constructor.py +++ b/tests/test_constructor.py @@ -1,6 +1,8 @@ from sqlite_utils import Database +from sqlite_utils.db import TransactionError from sqlite_utils.utils import sqlite3 import pytest +import sys def test_recursive_triggers(): @@ -29,6 +31,24 @@ def test_sqlite_version(): assert actual == as_string +def test_database_context_manager(tmpdir): + path = str(tmpdir / "test.db") + with Database(path) as db: + db["t"].insert({"id": 1}) + # Raw writes commit automatically too + db.execute("insert into t (id) values (2)") + # An explicitly opened transaction left uncommitted on purpose: + db.begin() + db.execute("insert into t (id) values (3)") + # The connection is closed... + with pytest.raises(sqlite3.ProgrammingError): + db.execute("select 1") + # ... and the open explicit transaction was rolled back, not committed + db2 = Database(path) + assert [r["id"] for r in db2["t"].rows] == [1, 2] + db2.close() + + @pytest.mark.parametrize("memory", [True, False]) def test_database_close(tmpdir, memory): if memory: @@ -39,3 +59,55 @@ def test_database_close(tmpdir, memory): db.close() with pytest.raises(sqlite3.ProgrammingError): db.execute("select 1 + 1") + + +@pytest.mark.skipif( + sys.version_info < (3, 12), + reason="sqlite3.connect(autocommit=) requires Python 3.12", +) +@pytest.mark.parametrize("autocommit", [True, False]) +def test_autocommit_connections_are_rejected(tmpdir, autocommit): + # These connection modes break commit()/rollback() in ways that + # silently lose data, so the constructor refuses them + conn = sqlite3.connect(str(tmpdir / "test.db"), autocommit=autocommit) + with pytest.raises(TransactionError): + Database(conn) + conn.close() + + +@pytest.mark.skipif( + sys.version_info < (3, 12), + reason="sqlite3.LEGACY_TRANSACTION_CONTROL requires Python 3.12", +) +def test_legacy_transaction_control_connection_is_accepted(tmpdir): + conn = sqlite3.connect( + str(tmpdir / "test.db"), autocommit=sqlite3.LEGACY_TRANSACTION_CONTROL + ) + db = Database(conn) + db["t"].insert({"id": 1}, pk="id") + assert [r["id"] for r in db["t"].rows] == [1] + db.close() + + +def test_memory_attribute_for_memory_true(): + db = Database(memory=True) + assert db.memory is True + assert db.memory_name is None + + +def test_memory_attribute_for_memory_name(): + db = Database(memory_name="shared_attr") + assert db.memory is True + assert db.memory_name == "shared_attr" + + +def test_memory_attribute_for_memory_string_path(): + db = Database(":memory:") + assert db.memory is True + assert db.memory_name is None + + +def test_memory_attribute_for_file_path(tmpdir): + db = Database(str(tmpdir / "file.db")) + assert db.memory is False + assert db.memory_name is None diff --git a/tests/test_convert.py b/tests/test_convert.py index 5279bc5..ea3fd96 100644 --- a/tests/test_convert.py +++ b/tests/test_convert.py @@ -50,12 +50,13 @@ def test_convert_where(fresh_db, where, where_args): assert list(table.rows) == [{"id": 1, "title": "One"}, {"id": 2, "title": "TWO"}] -def test_convert_skip_false(fresh_db): +def test_convert_handles_falsey_values(fresh_db): + # Falsey values like 0 should be converted (issue #527) table = fresh_db["table"] table.insert_all([{"x": 0}, {"x": 1}]) assert table.get(1)["x"] == 0 assert table.get(2)["x"] == 1 - table.convert("x", lambda x: x + 1, skip_false=False) + table.convert("x", lambda x: x + 1) assert table.get(1)["x"] == 1 assert table.get(2)["x"] == 2 @@ -76,7 +77,7 @@ def test_convert_output(fresh_db, drop, expected): def test_convert_output_multiple_column_error(fresh_db): table = fresh_db["table"] - with pytest.raises(AssertionError) as excinfo: + with pytest.raises(ValueError) as excinfo: table.convert(["title", "other"], lambda v: v, output="out") assert "output= can only be used with a single column" in str(excinfo.value) diff --git a/tests/test_create.py b/tests/test_create.py index a88374f..d281eb4 100644 --- a/tests/test_create.py +++ b/tests/test_create.py @@ -3,11 +3,14 @@ from sqlite_utils.db import ( Database, DescIndex, AlterError, + InvalidColumns, NoObviousTable, OperationalError, ForeignKey, Table, View, + NoTable, + NoView, ) from sqlite_utils.utils import hash_record, sqlite3 import collections @@ -18,7 +21,6 @@ import pathlib import pytest import uuid - try: import pandas as pd # type: ignore except ImportError: @@ -41,20 +43,20 @@ def test_create_table(fresh_db): assert ["test_table"] == fresh_db.table_names() assert [ {"name": "text_col", "type": "TEXT"}, - {"name": "float_col", "type": "FLOAT"}, + {"name": "float_col", "type": "REAL"}, {"name": "int_col", "type": "INTEGER"}, {"name": "bool_col", "type": "INTEGER"}, {"name": "bytes_col", "type": "BLOB"}, {"name": "datetime_col", "type": "TEXT"}, ] == [{"name": col.name, "type": col.type} for col in table.columns] assert ( - "CREATE TABLE [test_table] (\n" - " [text_col] TEXT,\n" - " [float_col] FLOAT,\n" - " [int_col] INTEGER,\n" - " [bool_col] INTEGER,\n" - " [bytes_col] BLOB,\n" - " [datetime_col] TEXT\n" + 'CREATE TABLE "test_table" (\n' + ' "text_col" TEXT,\n' + ' "float_col" REAL,\n' + ' "int_col" INTEGER,\n' + ' "bool_col" INTEGER,\n' + ' "bytes_col" BLOB,\n' + ' "datetime_col" TEXT\n' ")" ) == table.schema @@ -64,11 +66,11 @@ def test_create_table_compound_primary_key(fresh_db): "test_table", {"id1": str, "id2": str, "value": int}, pk=("id1", "id2") ) assert ( - "CREATE TABLE [test_table] (\n" - " [id1] TEXT,\n" - " [id2] TEXT,\n" - " [value] INTEGER,\n" - " PRIMARY KEY ([id1], [id2])\n" + 'CREATE TABLE "test_table" (\n' + ' "id1" TEXT,\n' + ' "id2" TEXT,\n' + ' "value" INTEGER,\n' + ' PRIMARY KEY ("id1", "id2")\n' ")" ) == table.schema assert ["id1", "id2"] == table.pks @@ -78,13 +80,17 @@ def test_create_table_compound_primary_key(fresh_db): def test_create_table_with_single_primary_key(fresh_db, pk): fresh_db["foo"].insert({"id": 1}, pk=pk) assert ( - fresh_db["foo"].schema == "CREATE TABLE [foo] (\n [id] INTEGER PRIMARY KEY\n)" + fresh_db["foo"].schema == 'CREATE TABLE "foo" (\n "id" INTEGER PRIMARY KEY\n)' ) -def test_create_table_with_invalid_column_characters(fresh_db): - with pytest.raises(AssertionError): - fresh_db.create_table("players", {"name[foo]": str}) +def test_create_table_with_special_column_characters(fresh_db): + # With double-quote escaping, columns with special characters are now valid + table = fresh_db.create_table("players", {"name[foo]": str}) + assert ["players"] == fresh_db.table_names() + assert [{"name": "name[foo]", "type": "TEXT"}] == [ + {"name": col.name, "type": col.type} for col in table.columns + ] def test_create_table_with_defaults(fresh_db): @@ -98,12 +104,12 @@ def test_create_table_with_defaults(fresh_db): {"name": col.name, "type": col.type} for col in table.columns ] assert ( - "CREATE TABLE [players] (\n [name] TEXT DEFAULT 'bob''''bob',\n [score] INTEGER DEFAULT 1\n)" + "CREATE TABLE \"players\" (\n \"name\" TEXT DEFAULT 'bob''''bob',\n \"score\" INTEGER DEFAULT 1\n)" ) == table.schema def test_create_table_with_bad_not_null(fresh_db): - with pytest.raises(AssertionError): + with pytest.raises(ValueError): fresh_db.create_table( "players", {"name": str, "score": int}, not_null={"mouse"} ) @@ -121,7 +127,7 @@ def test_create_table_with_not_null(fresh_db): {"name": col.name, "type": col.type} for col in table.columns ] assert ( - "CREATE TABLE [players] (\n [name] TEXT NOT NULL,\n [score] INTEGER NOT NULL DEFAULT 3\n)" + 'CREATE TABLE "players" (\n "name" TEXT NOT NULL,\n "score" INTEGER NOT NULL DEFAULT 3\n)' ) == table.schema @@ -137,13 +143,13 @@ def test_create_table_with_not_null(fresh_db): [{"name": "create", "type": "TEXT"}, {"name": "table", "type": "TEXT"}], ), ({"day": datetime.time(11, 0)}, [{"name": "day", "type": "TEXT"}]), - ({"decimal": decimal.Decimal("1.2")}, [{"name": "decimal", "type": "FLOAT"}]), + ({"decimal": decimal.Decimal("1.2")}, [{"name": "decimal", "type": "REAL"}]), ( {"memoryview": memoryview(b"hello")}, [{"name": "memoryview", "type": "BLOB"}], ), ({"uuid": uuid.uuid4()}, [{"name": "uuid", "type": "TEXT"}]), - ({"foo[bar]": 1}, [{"name": "foo_bar_", "type": "INTEGER"}]), + ({"foo[bar]": 1}, [{"name": "foo[bar]", "type": "INTEGER"}]), ( {"timedelta": datetime.timedelta(hours=1)}, [{"name": "timedelta", "type": "TEXT"}], @@ -173,19 +179,21 @@ def test_create_table_from_example_with_compound_primary_keys(fresh_db): @pytest.mark.parametrize( "method_name", ("insert", "upsert", "insert_all", "upsert_all") ) -def test_create_table_with_custom_columns(fresh_db, method_name): - table = fresh_db["dogs"] +@pytest.mark.parametrize("use_old_upsert", (False, True)) +def test_create_table_with_custom_columns(method_name, use_old_upsert): + db = Database(memory=True, use_old_upsert=use_old_upsert) + table = db["dogs"] method = getattr(table, method_name) record = {"id": 1, "name": "Cleo", "age": "5"} if method_name.endswith("_all"): record = [record] method(record, pk="id", columns={"age": int, "weight": float}) - assert ["dogs"] == fresh_db.table_names() + assert ["dogs"] == db.table_names() expected_columns = [ {"name": "id", "type": "INTEGER"}, {"name": "name", "type": "TEXT"}, {"name": "age", "type": "INTEGER"}, - {"name": "weight", "type": "FLOAT"}, + {"name": "weight", "type": "REAL"}, ] assert expected_columns == [ {"name": col.name, "type": col.type} for col in table.columns @@ -236,11 +244,11 @@ def test_create_table_column_order(fresh_db, use_table_factory): # If you specify a column that doesn't point to a table, you get an error: (("one_id", "two_id", "three_id"), NoObviousTable), # Tuples of the wrong length get an error: - ((("one_id", "one", "id", "five"), ("two_id", "two", "id")), AssertionError), + ((("one_id", "one", "id", "five"), ("two_id", "two", "id")), ValueError), # Likewise a bad column: ((("one_id", "one", "id2"),), AlterError), # Or a list of dicts - (({"one_id": "one"},), AssertionError), + (({"one_id": "one"},), ValueError), ), ) @pytest.mark.parametrize("use_table_factory", [True, False]) @@ -303,9 +311,9 @@ def test_self_referential_foreign_key(fresh_db): foreign_keys=(("ref", "test_table", "id"),), ) assert ( - "CREATE TABLE [test_table] (\n" - " [id] INTEGER PRIMARY KEY,\n" - " [ref] INTEGER REFERENCES [test_table]([id])\n" + 'CREATE TABLE "test_table" (\n' + ' "id" INTEGER PRIMARY KEY,\n' + ' "ref" INTEGER REFERENCES "test_table"("id")\n' ")" ) == table.schema @@ -336,58 +344,58 @@ def test_create_error_if_invalid_self_referential_foreign_keys(fresh_db): "nickname", str, None, - "CREATE TABLE [dogs] (\n [name] TEXT\n, [nickname] TEXT)", + 'CREATE TABLE "dogs" (\n "name" TEXT\n, "nickname" TEXT)', ), ( "dob", datetime.date, None, - "CREATE TABLE [dogs] (\n [name] TEXT\n, [dob] TEXT)", + 'CREATE TABLE "dogs" (\n "name" TEXT\n, "dob" TEXT)', ), - ("age", int, None, "CREATE TABLE [dogs] (\n [name] TEXT\n, [age] INTEGER)"), + ("age", int, None, 'CREATE TABLE "dogs" (\n "name" TEXT\n, "age" INTEGER)'), ( "weight", float, None, - "CREATE TABLE [dogs] (\n [name] TEXT\n, [weight] FLOAT)", + 'CREATE TABLE "dogs" (\n "name" TEXT\n, "weight" REAL)', ), - ("text", "TEXT", None, "CREATE TABLE [dogs] (\n [name] TEXT\n, [text] TEXT)"), + ("text", "TEXT", None, 'CREATE TABLE "dogs" (\n "name" TEXT\n, "text" TEXT)'), ( "integer", "INTEGER", None, - "CREATE TABLE [dogs] (\n [name] TEXT\n, [integer] INTEGER)", + 'CREATE TABLE "dogs" (\n "name" TEXT\n, "integer" INTEGER)', ), ( "float", "FLOAT", None, - "CREATE TABLE [dogs] (\n [name] TEXT\n, [float] FLOAT)", + 'CREATE TABLE "dogs" (\n "name" TEXT\n, "float" FLOAT)', ), - ("blob", "blob", None, "CREATE TABLE [dogs] (\n [name] TEXT\n, [blob] BLOB)"), + ("blob", "blob", None, 'CREATE TABLE "dogs" (\n "name" TEXT\n, "blob" BLOB)'), ( "default_str", None, None, - "CREATE TABLE [dogs] (\n [name] TEXT\n, [default_str] TEXT)", + 'CREATE TABLE "dogs" (\n "name" TEXT\n, "default_str" TEXT)', ), ( "nickname", str, "", - "CREATE TABLE [dogs] (\n [name] TEXT\n, [nickname] TEXT NOT NULL DEFAULT '')", + 'CREATE TABLE "dogs" (\n "name" TEXT\n, "nickname" TEXT NOT NULL DEFAULT \'\')', ), ( "nickname", str, "dawg's dawg", - "CREATE TABLE [dogs] (\n [name] TEXT\n, [nickname] TEXT NOT NULL DEFAULT 'dawg''s dawg')", + 'CREATE TABLE "dogs" (\n "name" TEXT\n, "nickname" TEXT NOT NULL DEFAULT \'dawg\'\'s dawg\')', ), ), ) def test_add_column(fresh_db, col_name, col_type, not_null_default, expected_schema): fresh_db.create_table("dogs", {"name": str}) - assert fresh_db["dogs"].schema == "CREATE TABLE [dogs] (\n [name] TEXT\n)" + assert fresh_db["dogs"].schema == 'CREATE TABLE "dogs" (\n "name" TEXT\n)' fresh_db["dogs"].add_column(col_name, col_type, not_null_default=not_null_default) assert fresh_db["dogs"].schema == expected_schema @@ -492,8 +500,8 @@ def test_add_column_foreign_key(fresh_db): fresh_db["dogs"].add_column("breed_id", fk="breeds") assert fresh_db["dogs"].schema == ( 'CREATE TABLE "dogs" (\n' - " [name] TEXT,\n" - " [breed_id] INTEGER REFERENCES [breeds]([rowid])\n" + ' "name" TEXT,\n' + ' "breed_id" INTEGER REFERENCES "breeds"("rowid")\n' ")" ) # And again with an explicit primary key column @@ -501,9 +509,9 @@ def test_add_column_foreign_key(fresh_db): fresh_db["dogs"].add_column("subbreed_id", fk="subbreeds") assert fresh_db["dogs"].schema == ( 'CREATE TABLE "dogs" (\n' - " [name] TEXT,\n" - " [breed_id] INTEGER REFERENCES [breeds]([rowid]),\n" - " [subbreed_id] TEXT REFERENCES [subbreeds]([primkey])\n" + ' "name" TEXT,\n' + ' "breed_id" INTEGER REFERENCES "breeds"("rowid"),\n' + ' "subbreed_id" TEXT REFERENCES "subbreeds"("primkey")\n' ")" ) @@ -515,8 +523,8 @@ def test_add_foreign_key_guess_table(fresh_db): fresh_db["dogs"].add_foreign_key("breed_id") assert fresh_db["dogs"].schema == ( 'CREATE TABLE "dogs" (\n' - " [name] TEXT,\n" - " [breed_id] INTEGER REFERENCES [breeds]([id])\n" + ' "name" TEXT,\n' + ' "breed_id" INTEGER REFERENCES "breeds"("id")\n' ")" ) @@ -553,7 +561,7 @@ def test_index_foreign_keys_if_index_name_is_already_used(fresh_db): ), ( {"hats": 5, "rating": 3.5}, - [{"name": "hats", "type": "INTEGER"}, {"name": "rating", "type": "FLOAT"}], + [{"name": "hats", "type": "INTEGER"}, {"name": "rating", "type": "REAL"}], ), ], ) @@ -587,7 +595,7 @@ def test_add_missing_columns_case_insensitive(fresh_db): table.add_missing_columns([{"Name": ".", "age": 4}]) assert ( table.schema - == "CREATE TABLE [foo] (\n [id] INTEGER PRIMARY KEY,\n [name] TEXT\n, [age] INTEGER)" + == 'CREATE TABLE "foo" (\n "id" INTEGER PRIMARY KEY,\n "name" TEXT\n, "age" INTEGER)' ) @@ -693,7 +701,7 @@ def test_bulk_insert_more_than_999_values(fresh_db): def test_error_if_more_than_999_columns(fresh_db, num_columns, should_error): record = dict([("c{}".format(i), i) for i in range(num_columns)]) if should_error: - with pytest.raises(AssertionError): + with pytest.raises(ValueError): fresh_db["big"].insert(record) else: fresh_db["big"].insert(record) @@ -801,6 +809,34 @@ def test_create_index_if_not_exists(fresh_db): dogs.create_index(["name"], if_not_exists=True) +def test_drop_index(fresh_db): + dogs = fresh_db["dogs"] + dogs.insert({"name": "Cleo", "twitter": "cleopaws", "age": 3, "is_good_dog": True}) + dogs.create_index(["name"]) + assert [index.name for index in dogs.indexes] == ["idx_dogs_name"] + dogs.drop_index("idx_dogs_name") + assert dogs.indexes == [] + + +def test_drop_index_ignore(fresh_db): + dogs = fresh_db["dogs"] + dogs.insert({"name": "Cleo"}) + with pytest.raises(OperationalError, match="No index named idx_dogs_name"): + dogs.drop_index("idx_dogs_name") + dogs.drop_index("idx_dogs_name", ignore=True) + + +def test_drop_index_wrong_table(fresh_db): + dogs = fresh_db["dogs"] + cats = fresh_db["cats"] + dogs.insert({"name": "Cleo"}) + cats.insert({"name": "Misty"}) + dogs.create_index(["name"]) + with pytest.raises(OperationalError, match="No index named idx_dogs_name"): + cats.drop_index("idx_dogs_name") + assert [index.name for index in dogs.indexes] == ["idx_dogs_name"] + + def test_create_index_desc(fresh_db): dogs = fresh_db["dogs"] dogs.insert({"name": "Cleo", "twitter": "cleopaws", "age": 3, "is good dog": True}) @@ -810,7 +846,7 @@ def test_create_index_desc(fresh_db): "select sql from sqlite_master where name='idx_dogs_age_name'" ).fetchone()[0] assert sql == ( - "CREATE INDEX [idx_dogs_age_name]\n" " ON [dogs] ([age] desc, [name])" + 'CREATE INDEX "idx_dogs_age_name"\n' ' ON "dogs" ("age" desc, "name")' ) @@ -918,6 +954,58 @@ def test_insert_thousands_adds_extra_columns_after_first_100_with_alter(fresh_db assert rows == [{"i": 101, "word": None, "extra": "Should trigger ALTER"}] +@pytest.mark.parametrize("num_rows", (0, 1, 2, 3, 10)) +def test_insert_all_pk_not_in_records_raises(fresh_db, num_rows): + # https://github.com/simonw/sqlite-utils/issues/732 + fresh_db.conn.execute("CREATE TABLE t (a TEXT, b INT, PRIMARY KEY (a, b))") + rows = [{"a": "x{}".format(i), "b": i} for i in range(num_rows)] + + with pytest.raises(InvalidColumns) as ex: + fresh_db["t"].insert_all(rows, pk="not_a_column") + + assert ex.value.args == ( + "Invalid primary key column ['not_a_column'] for table t with columns ['a', 'b']", + ) + assert fresh_db["t"].count == 0 + + +@pytest.mark.parametrize("num_rows", (1, 2, 3, 10)) +def test_insert_all_pk_not_in_records_alter_raises(fresh_db, num_rows): + # With alter=True the check is deferred until the record keys are + # known - a pk column that is in neither the table nor the records + # still raises + fresh_db.conn.execute("CREATE TABLE t (a TEXT, b INT, PRIMARY KEY (a, b))") + rows = [{"a": "x{}".format(i), "b": i} for i in range(num_rows)] + + with pytest.raises(InvalidColumns) as ex: + fresh_db["t"].insert_all(rows, pk="not_a_column", alter=True) + + assert ex.value.args == ( + "Invalid primary key column ['not_a_column'] for table t with columns ['a', 'b']", + ) + assert fresh_db["t"].count == 0 + + +def test_insert_pk_in_records_with_alter_adds_column(fresh_db): + # 3.x allowed insert(pk=..., alter=True) to add the pk column from the + # records - the InvalidColumns check must not fire in that case + fresh_db["t"].insert({"a": 1}) + fresh_db["t"].insert({"id": 5, "a": 2}, pk="id", alter=True) + assert fresh_db["t"].columns_dict.keys() == {"a", "id"} + assert list(fresh_db.query("select * from t order by a")) == [ + {"a": 1, "id": None}, + {"a": 2, "id": 5}, + ] + + +def test_insert_all_invalid_pk_alter_empty_records_is_noop(fresh_db): + # With alter=True the pk check needs record keys, so an empty iterator + # returns without error - matching the 3.x no-op for empty inserts + fresh_db.conn.execute("CREATE TABLE t (a TEXT)") + fresh_db["t"].insert_all([], pk="not_a_column", alter=True) + assert fresh_db["t"].count == 0 + + def test_insert_ignore(fresh_db): fresh_db["test"].insert({"id": 1, "bar": 2}, pk="id") # Should raise an error if we try this again @@ -930,6 +1018,114 @@ def test_insert_ignore(fresh_db): assert rows == [{"id": 1, "bar": 2}] +def test_insert_ignore_reports_existing_row(fresh_db): + # An ignored insert (row already exists) should point last_rowid and + # last_pk at the existing conflicting row - see the Datasette insert API + fresh_db["docs"].insert({"id": 1, "title": "Exists"}, pk="id") + # Insert a conflicting row with ignore=True and no explicit pk= + table = fresh_db["docs"].insert({"id": 1, "title": "One"}, ignore=True) + assert table.last_rowid == 1 + assert table.last_pk == 1 + assert list(fresh_db["docs"].rows_where("rowid = ?", [table.last_rowid])) == [ + {"id": 1, "title": "Exists"} + ] + + +@pytest.mark.parametrize("rowid_alias", ("rowid", "_rowid_", "oid")) +@pytest.mark.parametrize("method", ("upsert", "insert_replace", "insert_ignore")) +def test_pk_rowid_alias_on_rowid_table(fresh_db, rowid_alias, method): + # rowid and its aliases are valid primary keys for a rowid table even + # though they are not listed among the table's columns - see the Datasette + # upsert API against tables without an explicit primary key + fresh_db["t"].insert({"title": "Hello"}) + assert fresh_db["t"].pks == ["rowid"] + record = {rowid_alias: 1, "title": "Updated"} + if method == "upsert": + table = fresh_db["t"].upsert(record, pk=rowid_alias) + elif method == "insert_replace": + table = fresh_db["t"].insert(record, pk=rowid_alias, replace=True) + else: + table = fresh_db["t"].insert(record, pk=rowid_alias, ignore=True) + assert table.last_pk == 1 + expected_title = "Hello" if method == "insert_ignore" else "Updated" + assert list(fresh_db["t"].rows) == [{"title": expected_title}] + + +def test_insert_ignore_reports_existing_row_compound_pk(fresh_db): + # Compound primary key variant of the ignored-insert lookup + fresh_db["t"].insert_all([{"a": 1, "b": 2, "note": "first"}], pk=("a", "b")) + table = fresh_db["t"].insert( + {"a": 1, "b": 2, "note": "second"}, pk=("a", "b"), ignore=True + ) + assert table.last_pk == (1, 2) + assert list(fresh_db["t"].rows_where("rowid = ?", [table.last_rowid])) == [ + {"a": 1, "b": 2, "note": "first"} + ] + + +def test_insert_ignore_reports_existing_row_list_mode(fresh_db): + # List-based iteration variant of the ignored-insert lookup + fresh_db["t"].insert_all([["id", "title"], [1, "first"]], pk="id") + table = fresh_db["t"].insert_all( + [["id", "title"], [1, "second"]], pk="id", ignore=True + ) + assert table.last_pk == 1 + assert table.last_rowid == 1 + assert list(fresh_db["t"].rows) == [{"id": 1, "title": "first"}] + + +def test_insert_ignore_hash_id_reports_pk(fresh_db): + # With hash_id the pk is the computed hash; the original record has no id + # column to look up so last_rowid is left unset + first = fresh_db["dogs"].insert({"name": "Cleo"}, hash_id="id") + table = fresh_db["dogs"].insert({"name": "Cleo"}, hash_id="id", ignore=True) + assert table.last_pk == first.last_pk + assert table.last_rowid is None + assert fresh_db["dogs"].count == 1 + + +def test_insert_ignore_unresolvable_conflict_leaves_pk_unset(fresh_db): + # When the conflict cannot be resolved to a primary key lookup, last_pk and + # last_rowid are left unset rather than reporting a misleading value + + # rowid table with a UNIQUE column and no primary key: no pk to look up + fresh_db["u"].db.execute("create table u (title text unique)") + fresh_db["u"].insert({"title": "x"}) + table = fresh_db["u"].insert({"title": "x"}, ignore=True) + assert table.last_pk is None + assert table.last_rowid is None + assert fresh_db["u"].count == 1 + + # Conflict on a UNIQUE column other than the primary key: the pk value from + # the record does not match the existing row, so the lookup finds nothing + fresh_db["docs"].db.execute( + "create table docs (id integer primary key, email text unique)" + ) + fresh_db["docs"].insert({"id": 1, "email": "a"}, pk="id") + table = fresh_db["docs"].insert({"id": 2, "email": "a"}, ignore=True) + assert table.last_pk is None + assert table.last_rowid is None + assert fresh_db["docs"].count == 1 + + +def test_insert_ignore_with_pk_after_other_table_insert(fresh_db): + # https://github.com/simonw/sqlite-utils/issues/554 + user = {"id": "abc", "name": "david"} + + fresh_db["users"].insert(user, pk="id") + fresh_db["comments"].insert_all( + [ + {"id": "def", "text": "ok"}, + {"id": "ghi", "text": "great"}, + ], + ) + + table = fresh_db["users"].insert(user, pk="id", ignore=True) + + assert table.last_pk == "abc" + assert list(fresh_db["users"].rows) == [user] + + def test_insert_hash_id(fresh_db): dogs = fresh_db["dogs"] id = dogs.insert({"name": "Cleo", "twitter": "cleopaws"}, hash_id="id").last_pk @@ -1054,7 +1250,7 @@ def test_create_table_numpy(fresh_db): def test_cannot_provide_both_filename_and_memory(): with pytest.raises( - AssertionError, match="Either specify a filename_or_conn or pass memory=True" + ValueError, match="Either specify a filename_or_conn or pass memory=True" ): Database("/tmp/foo.db", memory=True) @@ -1150,19 +1346,19 @@ def test_quote(fresh_db, input, expected): ( ( {"id": int}, - "[id] INTEGER", + '"id" INTEGER', ), ( {"col": dict}, - "[col] TEXT", + '"col" TEXT', ), ( {"col": tuple}, - "[col] TEXT", + '"col" TEXT', ), ( {"col": list}, - "[col] TEXT", + '"col" TEXT', ), ), ) @@ -1187,12 +1383,12 @@ def test_create(fresh_db): defaults={"integer": 0}, ) assert fresh_db["t"].schema == ( - "CREATE TABLE [t] (\n" - " [id] INTEGER PRIMARY KEY,\n" - " [float] FLOAT NOT NULL,\n" - " [text] TEXT,\n" - " [integer] INTEGER NOT NULL DEFAULT 0,\n" - " [bytes] BLOB\n" + 'CREATE TABLE "t" (\n' + ' "id" INTEGER PRIMARY KEY,\n' + ' "float" REAL NOT NULL,\n' + ' "text" TEXT,\n' + ' "integer" INTEGER NOT NULL DEFAULT 0,\n' + ' "bytes" BLOB\n' ")" ) @@ -1207,7 +1403,7 @@ def test_create_if_not_exists(fresh_db): def test_create_if_no_columns(fresh_db): - with pytest.raises(AssertionError) as error: + with pytest.raises(ValueError) as error: fresh_db["t"].create({}) assert error.value.args[0] == "Tables must have at least one column" @@ -1228,7 +1424,7 @@ def test_create_replace(fresh_db): fresh_db["t"].create({"id": int}) # This should not fresh_db["t"].create({"name": str}, replace=True) - assert fresh_db["t"].schema == ("CREATE TABLE [t] (\n" " [name] TEXT\n" ")") + assert fresh_db["t"].schema == ('CREATE TABLE "t" (\n' ' "name" TEXT\n' ")") @pytest.mark.parametrize( @@ -1238,58 +1434,58 @@ def test_create_replace(fresh_db): ( {"id": int, "name": str}, {"pk": "id"}, - "CREATE TABLE [demo] (\n [id] INTEGER PRIMARY KEY,\n [name] TEXT\n)", + 'CREATE TABLE "demo" (\n "id" INTEGER PRIMARY KEY,\n "name" TEXT\n)', False, ), # Drop name column, remove primary key - ({"id": int}, {}, 'CREATE TABLE "demo" (\n [id] INTEGER\n)', True), + ({"id": int}, {}, 'CREATE TABLE "demo" (\n "id" INTEGER\n)', True), # Add a new column ( {"id": int, "name": str, "age": int}, {"pk": "id"}, - 'CREATE TABLE "demo" (\n [id] INTEGER PRIMARY KEY,\n [name] TEXT,\n [age] INTEGER\n)', + 'CREATE TABLE "demo" (\n "id" INTEGER PRIMARY KEY,\n "name" TEXT,\n "age" INTEGER\n)', True, ), # Change a column type ( {"id": int, "name": bytes}, {"pk": "id"}, - 'CREATE TABLE "demo" (\n [id] INTEGER PRIMARY KEY,\n [name] BLOB\n)', + 'CREATE TABLE "demo" (\n "id" INTEGER PRIMARY KEY,\n "name" BLOB\n)', True, ), # Change the primary key ( {"id": int, "name": str}, {"pk": "name"}, - 'CREATE TABLE "demo" (\n [id] INTEGER,\n [name] TEXT PRIMARY KEY\n)', + 'CREATE TABLE "demo" (\n "id" INTEGER,\n "name" TEXT PRIMARY KEY\n)', True, ), # Change in column order ( {"id": int, "name": str}, {"pk": "id", "column_order": ["name"]}, - 'CREATE TABLE "demo" (\n [name] TEXT,\n [id] INTEGER PRIMARY KEY\n)', + 'CREATE TABLE "demo" (\n "name" TEXT,\n "id" INTEGER PRIMARY KEY\n)', True, ), # Same column order is ignored ( {"id": int, "name": str}, {"pk": "id", "column_order": ["id", "name"]}, - "CREATE TABLE [demo] (\n [id] INTEGER PRIMARY KEY,\n [name] TEXT\n)", + 'CREATE TABLE "demo" (\n "id" INTEGER PRIMARY KEY,\n "name" TEXT\n)', False, ), # Change not null ( {"id": int, "name": str}, {"pk": "id", "not_null": {"name"}}, - 'CREATE TABLE "demo" (\n [id] INTEGER PRIMARY KEY,\n [name] TEXT NOT NULL\n)', + 'CREATE TABLE "demo" (\n "id" INTEGER PRIMARY KEY,\n "name" TEXT NOT NULL\n)', True, ), # Change default values ( {"id": int, "name": str}, {"pk": "id", "defaults": {"id": 0, "name": "Bob"}}, - "CREATE TABLE \"demo\" (\n [id] INTEGER PRIMARY KEY DEFAULT 0,\n [name] TEXT DEFAULT 'Bob'\n)", + 'CREATE TABLE "demo" (\n "id" INTEGER PRIMARY KEY DEFAULT 0,\n "name" TEXT DEFAULT \'Bob\'\n)', True, ), ), @@ -1316,3 +1512,164 @@ def test_rename_table(fresh_db): # Should error if table does not exist: with pytest.raises(sqlite3.OperationalError): fresh_db.rename_table("does_not_exist", "renamed") + + +@pytest.mark.parametrize("strict", (False, True)) +def test_database_strict(strict): + db = Database(memory=True, strict=strict) + table = db.table("t", columns={"id": int}) + table.insert({"id": 1}) + assert table.strict == strict or not db.supports_strict + + +@pytest.mark.parametrize("strict", (False, True)) +def test_database_strict_override(strict): + db = Database(memory=True, strict=strict) + table = db.table("t", columns={"id": int}, strict=not strict) + table.insert({"id": 1}) + assert table.strict != strict or not db.supports_strict + + +@pytest.mark.parametrize( + "method_name", ("insert", "upsert", "insert_all", "upsert_all") +) +@pytest.mark.parametrize("strict", (False, True)) +def test_insert_upsert_strict(fresh_db, method_name, strict): + table = fresh_db["t"] + method = getattr(table, method_name) + record = {"id": 1} + if method_name.endswith("_all"): + record = [record] + method(record, pk="id", strict=strict) + assert table.strict == strict or not fresh_db.supports_strict + + +@pytest.mark.parametrize("strict", (False, True)) +def test_create_table_strict(fresh_db, strict): + table = fresh_db.create_table("t", {"id": int, "f": float}, strict=strict) + assert table.strict == strict or not fresh_db.supports_strict + expected_schema = 'CREATE TABLE "t" (\n' ' "id" INTEGER,\n' ' "f" REAL\n' ")" + if strict and not fresh_db.supports_strict: + return + if strict: + expected_schema = 'CREATE TABLE "t" (\n "id" INTEGER,\n "f" REAL\n) STRICT' + assert table.schema == expected_schema + + +@pytest.mark.parametrize("strict", (False, True)) +def test_create_strict(fresh_db, strict): + table = fresh_db["t"] + table.create({"id": int}, strict=strict) + assert table.strict == strict or not fresh_db.supports_strict + + +def test_bad_table_and_view_exceptions(fresh_db): + fresh_db.table("t").insert({"id": 1}, pk="id") + fresh_db.create_view("v", "select * from t") + with pytest.raises(NoTable) as ex: + fresh_db.table("v") + assert ex.value.args[0] == "Table v is actually a view" + with pytest.raises(NoView) as ex2: + fresh_db.view("t") + assert ex2.value.args[0] == "View t does not exist - t is a table" + with pytest.raises(NoView) as ex3: + fresh_db.view("missing") + assert ex3.value.args[0] == "View missing does not exist" + + +# Tests for issue #655: Table configuration should be stored in _defaults +# after table creation, so subsequent operations use the same settings. + + +def test_pk_persists_after_insert_655(fresh_db): + """When pk is passed to insert(), subsequent inserts should use it.""" + table = fresh_db["users"] + table.insert({"id": 1, "name": "Alice"}, pk="id") + # Second insert should use pk="id" from _defaults + table.insert({"id": 2, "name": "Bob"}) + assert table.pks == ["id"] + # Verify both rows exist (not overwritten due to missing pk) + assert table.count == 2 + + +def test_pk_persists_after_insert_all_655(fresh_db): + """When pk is passed to insert_all(), subsequent inserts should use it.""" + table = fresh_db["users"] + table.insert_all([{"id": 1, "name": "Alice"}], pk="id") + # Second insert_all should use pk="id" from _defaults + table.insert_all([{"id": 2, "name": "Bob"}]) + assert table.pks == ["id"] + assert table.count == 2 + + +def test_pk_persists_after_create_655(fresh_db): + """When pk is passed to create(), it should be stored in _defaults.""" + table = fresh_db["users"] + table.create({"id": int, "name": str}, pk="id") + assert table._defaults["pk"] == "id" + # Subsequent insert should use the pk + table.insert({"id": 1, "name": "Alice"}) + table.insert({"id": 2, "name": "Bob"}) + assert table.count == 2 + + +def test_foreign_keys_persist_after_create_655(fresh_db): + """When foreign_keys is passed to create(), it should be stored in _defaults.""" + fresh_db["authors"].insert({"id": 1, "name": "Alice"}, pk="id") + table = fresh_db["books"] + table.create( + {"id": int, "title": str, "author_id": int}, + pk="id", + foreign_keys=[("author_id", "authors", "id")], + ) + assert table._defaults["pk"] == "id" + assert table._defaults["foreign_keys"] == [("author_id", "authors", "id")] + + +def test_not_null_persists_after_create_655(fresh_db): + """When not_null is passed to create(), it should be stored in _defaults.""" + table = fresh_db["users"] + table.create({"id": int, "name": str}, pk="id", not_null=["name"]) + assert table._defaults["not_null"] == ["name"] + + +def test_defaults_persist_after_create_655(fresh_db): + """When defaults is passed to create(), it should be stored in _defaults.""" + table = fresh_db["users"] + table.create({"id": int, "score": int}, pk="id", defaults={"score": 0}) + assert table._defaults["defaults"] == {"score": 0} + + +def test_strict_persists_after_create_655(fresh_db): + """When strict is passed to create(), it should be stored in _defaults.""" + table = fresh_db["users"] + table.create({"id": int, "name": str}, pk="id", strict=True) + assert table._defaults["strict"] is True + + +def test_upsert_uses_pk_from_prior_insert_655(fresh_db): + """After insert with pk, upsert should use the same pk.""" + table = fresh_db["users"] + table.insert({"id": 1, "name": "Alice"}, pk="id") + # Upsert should work without specifying pk again + table.upsert({"id": 1, "name": "Alice Updated"}) + assert table.count == 1 + assert list(table.rows)[0]["name"] == "Alice Updated" + + +def test_upsert_all_uses_pk_from_prior_insert_655(fresh_db): + """After insert with pk, upsert_all should use the same pk.""" + table = fresh_db["users"] + table.insert({"id": 1, "name": "Alice"}, pk="id") + # Upsert_all should work without specifying pk again + table.upsert_all([{"id": 1, "name": "Alice Updated"}, {"id": 2, "name": "Bob"}]) + assert table.count == 2 + rows = {row["id"]: row["name"] for row in table.rows} + assert rows == {1: "Alice Updated", 2: "Bob"} + + +def test_chained_create_sets_pks(fresh_db): + table = fresh_db.table("dogs3", pk="id").create( + {"id": int, "name": str, "color": str} + ) + assert table.pks == ["id"] diff --git a/tests/test_create_view.py b/tests/test_create_view.py index f0e2855..056e246 100644 --- a/tests/test_create_view.py +++ b/tests/test_create_view.py @@ -15,7 +15,7 @@ def test_create_view_error(fresh_db): def test_create_view_only_arrow_one_param(fresh_db): - with pytest.raises(AssertionError): + with pytest.raises(ValueError): fresh_db.create_view("bar", "select 1 + 2", ignore=True, replace=True) diff --git a/tests/test_default_value.py b/tests/test_default_value.py index 9ffdb14..3724d99 100644 --- a/tests/test_default_value.py +++ b/tests/test_default_value.py @@ -1,6 +1,5 @@ import pytest - EXAMPLES = [ ("TEXT DEFAULT 'foo'", "'foo'", "'foo'"), ("TEXT DEFAULT 'foo)'", "'foo)'", "'foo)'"), @@ -22,6 +21,11 @@ EXAMPLES = [ # Strings ("TEXT DEFAULT 'CURRENT_TIMESTAMP'", "'CURRENT_TIMESTAMP'", "'CURRENT_TIMESTAMP'"), ('TEXT DEFAULT "CURRENT_TIMESTAMP"', '"CURRENT_TIMESTAMP"', '"CURRENT_TIMESTAMP"'), + # Boolean and null keyword literals must stay unquoted + ("INTEGER DEFAULT TRUE", "TRUE", "TRUE"), + ("INTEGER DEFAULT FALSE", "FALSE", "FALSE"), + ("INTEGER DEFAULT true", "true", "true"), + ("TEXT DEFAULT NULL", "NULL", "NULL"), ] @@ -32,3 +36,24 @@ def test_quote_default_value(fresh_db, column_def, initial_value, expected_value assert expected_value == fresh_db.quote_default_value( fresh_db["foo"].columns[0].default_value ) + + +def test_insert_empty_record_uses_default_values(fresh_db): + fresh_db.execute(""" + CREATE TABLE has_defaults ( + id INTEGER PRIMARY KEY, + name TEXT, + timestamp TEXT DEFAULT CURRENT_TIMESTAMP, + is_active INTEGER NOT NULL DEFAULT 1 + ) + """) + + table = fresh_db["has_defaults"] + table.insert({}) + + rows = list(table.rows) + assert len(rows) == 1 + assert rows[0]["id"] == 1 + assert rows[0]["name"] is None + assert rows[0]["timestamp"] is not None + assert rows[0]["is_active"] == 1 diff --git a/tests/test_delete.py b/tests/test_delete.py index 652096c..a2d93aa 100644 --- a/tests/test_delete.py +++ b/tests/test_delete.py @@ -1,3 +1,6 @@ +import sqlite_utils + + def test_delete_rowid_table(fresh_db): table = fresh_db["table"] table.insert({"foo": 1}).last_pk @@ -32,6 +35,21 @@ def test_delete_where_all(fresh_db): assert table.count == 0 +def test_delete_where_commits(tmpdir): + path = str(tmpdir / "test.db") + db = sqlite_utils.Database(path) + db["table"].insert_all([{"id": i} for i in range(5)], pk="id") + db["table"].delete_where("id > ?", [2]) + # The connection must not be left inside an open transaction, + # otherwise subsequent atomic() blocks never commit either + assert not db.conn.in_transaction + db["table"].insert({"id": 100}) + db.close() + db2 = sqlite_utils.Database(path) + assert [r["id"] for r in db2["table"].rows] == [0, 1, 2, 100] + db2.close() + + def test_delete_where_analyze(fresh_db): table = fresh_db["table"] table.insert_all(({"id": i, "i": i} for i in range(10)), pk="id") diff --git a/tests/test_docs.py b/tests/test_docs.py index a36b053..f657416 100644 --- a/tests/test_docs.py +++ b/tests/test_docs.py @@ -41,9 +41,9 @@ def test_convert_help(): result = CliRunner().invoke(cli.cli, ["convert", "--help"]) assert result.exit_code == 0 for expected in ( - "r.jsonsplit(value, ", - "r.parsedate(value, ", - "r.parsedatetime(value, ", + "r.jsonsplit(value:", + "r.parsedate(value:", + "r.parsedatetime(value:", ): assert expected in result.output @@ -54,7 +54,7 @@ def test_convert_help(): n for n in dir(recipes) if not n.startswith("_") - and n not in ("json", "parser") + and n not in ("json", "parser", "Callable", "Optional") and callable(getattr(recipes, n)) ], ) diff --git a/tests/test_duplicate.py b/tests/test_duplicate.py index 87996ef..28961d2 100644 --- a/tests/test_duplicate.py +++ b/tests/test_duplicate.py @@ -5,14 +5,12 @@ import pytest def test_duplicate(fresh_db): # Create table using native Sqlite statement: - fresh_db.execute( - """CREATE TABLE [table1] ( - [text_col] TEXT, - [real_col] REAL, - [int_col] INTEGER, - [bool_col] INTEGER, - [datetime_col] TEXT)""" - ) + fresh_db.execute("""CREATE TABLE "table1" ( + "text_col" TEXT, + "real_col" REAL, + "int_col" INTEGER, + "bool_col" INTEGER, + "datetime_col" TEXT)""") # Insert one row of mock data: dt = datetime.datetime.now() data = { diff --git a/tests/test_enable_counts.py b/tests/test_enable_counts.py index d724e80..2f6b0db 100644 --- a/tests/test_enable_counts.py +++ b/tests/test_enable_counts.py @@ -15,25 +15,25 @@ def test_enable_counts_specific_table(fresh_db): foo.enable_counts() assert foo.triggers_dict == { "foo_counts_insert": ( - "CREATE TRIGGER [foo_counts_insert] AFTER INSERT ON [foo]\n" + 'CREATE TRIGGER "foo_counts_insert" AFTER INSERT ON "foo"\n' "BEGIN\n" - " INSERT OR REPLACE INTO [_counts]\n" + ' INSERT OR REPLACE INTO "_counts"\n' " VALUES (\n 'foo',\n" " COALESCE(\n" - " (SELECT count FROM [_counts] WHERE [table] = 'foo'),\n" + ' (SELECT count FROM "_counts" WHERE "table" = \'foo\'),\n' " 0\n" " ) + 1\n" " );\n" "END" ), "foo_counts_delete": ( - "CREATE TRIGGER [foo_counts_delete] AFTER DELETE ON [foo]\n" + 'CREATE TRIGGER "foo_counts_delete" AFTER DELETE ON "foo"\n' "BEGIN\n" - " INSERT OR REPLACE INTO [_counts]\n" + ' INSERT OR REPLACE INTO "_counts"\n' " VALUES (\n" " 'foo',\n" " COALESCE(\n" - " (SELECT count FROM [_counts] WHERE [table] = 'foo'),\n" + ' (SELECT count FROM "_counts" WHERE "table" = \'foo\'),\n' " 0\n" " ) - 1\n" " );\n" @@ -129,19 +129,19 @@ def test_uses_counts_after_enable_counts(counts_db_path): db = Database(counts_db_path) logged = [] with db.tracer(lambda sql, parameters: logged.append((sql, parameters))): - assert db["foo"].count == 1 + assert db.table("foo").count == 1 assert logged == [ ("select name from sqlite_master where type = 'view'", None), - ("select count(*) from [foo]", []), + ('select count(*) from "foo"', []), ] logged.clear() assert not db.use_counts_table db.enable_counts() assert db.use_counts_table - assert db["foo"].count == 1 + assert db.table("foo").count == 1 assert logged == [ ( - "CREATE TABLE IF NOT EXISTS [_counts](\n [table] TEXT PRIMARY KEY,\n count INTEGER DEFAULT 0\n);", + 'CREATE TABLE IF NOT EXISTS "_counts"(\n "table" TEXT PRIMARY KEY,\n count INTEGER DEFAULT 0\n);', None, ), ("select name from sqlite_master where type = 'table'", None), @@ -157,7 +157,7 @@ def test_uses_counts_after_enable_counts(counts_db_path): ("SELECT quote(:value)", {"value": "baz"}), ("select sql from sqlite_master where name = ?", ("_counts",)), ("select name from sqlite_master where type = 'view'", None), - ("select [table], count from _counts where [table] in (?)", ["foo"]), + ('select "table", count from _counts where "table" in (?)', ["foo"]), ] diff --git a/tests/test_extract.py b/tests/test_extract.py index 7a663c5..c73ee7a 100644 --- a/tests/test_extract.py +++ b/tests/test_extract.py @@ -24,16 +24,16 @@ def test_extract_single_column(fresh_db, table, fk_column): fresh_db["tree"].extract("species", table=table, fk_column=fk_column) assert fresh_db["tree"].schema == ( 'CREATE TABLE "tree" (\n' - " [id] INTEGER PRIMARY KEY,\n" - " [name] TEXT,\n" - " [{}] INTEGER REFERENCES [{}]([id]),\n".format(expected_fk, expected_table) - + " [end] INTEGER\n" + ' "id" INTEGER PRIMARY KEY,\n' + ' "name" TEXT,\n' + ' "{}" INTEGER REFERENCES "{}"("id"),\n'.format(expected_fk, expected_table) + + ' "end" INTEGER\n' + ")" ) assert fresh_db[expected_table].schema == ( - "CREATE TABLE [{}] (\n".format(expected_table) - + " [id] INTEGER PRIMARY KEY,\n" - " [species] TEXT\n" + 'CREATE TABLE "{}" (\n'.format(expected_table) + + ' "id" INTEGER PRIMARY KEY,\n' + ' "species" TEXT\n' ")" ) assert list(fresh_db[expected_table].rows) == [ @@ -71,16 +71,16 @@ def test_extract_multiple_columns_with_rename(fresh_db): ) assert fresh_db["tree"].schema == ( 'CREATE TABLE "tree" (\n' - " [id] INTEGER PRIMARY KEY,\n" - " [name] TEXT,\n" - " [common_name_latin_name_id] INTEGER REFERENCES [common_name_latin_name]([id])\n" + ' "id" INTEGER PRIMARY KEY,\n' + ' "name" TEXT,\n' + ' "common_name_latin_name_id" INTEGER REFERENCES "common_name_latin_name"("id")\n' ")" ) assert fresh_db["common_name_latin_name"].schema == ( - "CREATE TABLE [common_name_latin_name] (\n" - " [id] INTEGER PRIMARY KEY,\n" - " [name] TEXT,\n" - " [latin_name] TEXT\n" + 'CREATE TABLE "common_name_latin_name" (\n' + ' "id" INTEGER PRIMARY KEY,\n' + ' "name" TEXT,\n' + ' "latin_name" TEXT\n' ")" ) assert list(fresh_db["common_name_latin_name"].rows) == [ @@ -122,13 +122,11 @@ def test_extract_rowid_table(fresh_db): fresh_db["tree"].extract(["common_name", "latin_name"]) assert fresh_db["tree"].schema == ( 'CREATE TABLE "tree" (\n' - " [name] TEXT,\n" - " [common_name_latin_name_id] INTEGER REFERENCES [common_name_latin_name]([id])\n" + ' "name" TEXT,\n' + ' "common_name_latin_name_id" INTEGER REFERENCES "common_name_latin_name"("id")\n' ")" ) - assert ( - fresh_db.execute( - """ + assert fresh_db.execute(""" select tree.name, common_name_latin_name.common_name, @@ -136,10 +134,7 @@ def test_extract_rowid_table(fresh_db): from tree join common_name_latin_name on tree.common_name_latin_name_id = common_name_latin_name.id - """ - ).fetchall() - == [("Tree 1", "Palm", "Arecaceae")] - ) + """).fetchall() == [("Tree 1", "Palm", "Arecaceae")] def test_reuse_lookup_table(fresh_db): @@ -152,15 +147,15 @@ def test_reuse_lookup_table(fresh_db): fresh_db["individuals"].extract("species", rename={"species": "name"}) assert fresh_db["sightings"].schema == ( 'CREATE TABLE "sightings" (\n' - " [id] INTEGER PRIMARY KEY,\n" - " [species_id] INTEGER REFERENCES [species]([id])\n" + ' "id" INTEGER PRIMARY KEY,\n' + ' "species_id" INTEGER REFERENCES "species"("id")\n' ")" ) assert fresh_db["individuals"].schema == ( 'CREATE TABLE "individuals" (\n' - " [id] INTEGER PRIMARY KEY,\n" - " [name] TEXT,\n" - " [species_id] INTEGER REFERENCES [species]([id])\n" + ' "id" INTEGER PRIMARY KEY,\n' + ' "name" TEXT,\n' + ' "species_id" INTEGER REFERENCES "species"("id")\n' ")" ) assert list(fresh_db["species"].rows) == [ @@ -194,9 +189,116 @@ def test_extract_works_with_null_values(fresh_db): ) assert list(fresh_db["listens"].rows) == [ {"id": 1, "track_title": "foo", "album_id": 1}, - {"id": 2, "track_title": "baz", "album_id": 2}, + {"id": 2, "track_title": "baz", "album_id": None}, ] assert list(fresh_db["albums"].rows) == [ {"id": 1, "album_title": "bar"}, - {"id": 2, "album_title": None}, ] + + +def test_extract_null_values_single_column(fresh_db): + # https://github.com/simonw/sqlite-utils/issues/186 + fresh_db["species"].insert({"id": 1, "species": "Wolf"}, pk="id") + fresh_db["individuals"].insert_all( + [ + {"id": 10, "name": "Terriana", "species": "Fox"}, + {"id": 11, "name": "Spenidorm", "species": None}, + {"id": 12, "name": "Grantheim", "species": "Wolf"}, + {"id": 13, "name": "Turnutopia", "species": None}, + {"id": 14, "name": "Wargal", "species": "Wolf"}, + ], + pk="id", + ) + fresh_db["individuals"].extract("species") + # No null row should have been added to species + assert list(fresh_db["species"].rows) == [ + {"id": 1, "species": "Wolf"}, + {"id": 2, "species": "Fox"}, + ] + assert list(fresh_db["individuals"].rows) == [ + {"id": 10, "name": "Terriana", "species_id": 2}, + {"id": 11, "name": "Spenidorm", "species_id": None}, + {"id": 12, "name": "Grantheim", "species_id": 1}, + {"id": 13, "name": "Turnutopia", "species_id": None}, + {"id": 14, "name": "Wargal", "species_id": 1}, + ] + + +def test_extract_null_values_multiple_columns(fresh_db): + # A row should be extracted if at least one column is not null - + # only rows where ALL extracted columns are null are left alone + fresh_db["circulation"].insert_all( + [ + {"id": 1, "title": "title one", "creator": "creator one", "year": 2018}, + {"id": 2, "title": "title two", "creator": None, "year": 2019}, + {"id": 3, "title": None, "creator": None, "year": 2020}, + {"id": 4, "title": None, "creator": None, "year": 2021}, + ], + pk="id", + ) + fresh_db["circulation"].extract( + ["title", "creator"], table="books", fk_column="book_id" + ) + assert list(fresh_db["books"].rows) == [ + {"id": 1, "title": "title one", "creator": "creator one"}, + {"id": 2, "title": "title two", "creator": None}, + ] + assert list(fresh_db["circulation"].rows) == [ + {"id": 1, "book_id": 1, "year": 2018}, + {"id": 2, "book_id": 2, "year": 2019}, + {"id": 3, "book_id": None, "year": 2020}, + {"id": 4, "book_id": None, "year": 2021}, + ] + + +def test_extract_null_values_existing_lookup_table_with_null_row(fresh_db): + # Even if the lookup table already contains an all-null row, rows where + # every extracted column is null should keep a null foreign key + fresh_db["species"].insert({"id": 1, "species": None}, pk="id") + fresh_db["individuals"].insert_all( + [ + {"id": 10, "name": "Terriana", "species": "Fox"}, + {"id": 11, "name": "Spenidorm", "species": None}, + ], + pk="id", + ) + fresh_db["individuals"].extract("species") + assert list(fresh_db["species"].rows) == [ + {"id": 1, "species": None}, + {"id": 2, "species": "Fox"}, + ] + assert list(fresh_db["individuals"].rows) == [ + {"id": 10, "name": "Terriana", "species_id": 2}, + {"id": 11, "name": "Spenidorm", "species_id": None}, + ] + + +def test_extract_repeated_into_shared_lookup_with_nulls(fresh_db): + # Unique indexes treat NULLs as distinct, so INSERT OR IGNORE alone + # cannot dedupe NULL-containing rows against the existing lookup + # table - extracting a second table into the same lookup previously + # inserted duplicate rows that nothing pointed to + fresh_db["t1"].insert_all( + [ + {"id": 1, "species": None, "common": "X"}, + {"id": 2, "species": "Oak", "common": "Oak"}, + ], + pk="id", + ) + fresh_db["t2"].insert_all([{"id": 1, "species": None, "common": "X"}], pk="id") + fresh_db["t1"].extract(["species", "common"], table="lk") + fresh_db["t2"].extract(["species", "common"], table="lk") + assert fresh_db["lk"].count == 2 + # Both tables point at the same lookup row + t1_fk = fresh_db.execute("select lk_id from t1 where id = 1").fetchone()[0] + t2_fk = fresh_db.execute("select lk_id from t2 where id = 1").fetchone()[0] + assert t1_fk == t2_fk + + +def test_extract_repeated_into_shared_lookup_no_nulls(fresh_db): + # Non-NULL rows were already deduped by the unique index - keep it so + fresh_db["t1"].insert_all([{"id": 1, "species": "Oak"}], pk="id") + fresh_db["t2"].insert_all([{"id": 1, "species": "Oak"}], pk="id") + fresh_db["t1"].extract(["species"], table="lk") + fresh_db["t2"].extract(["species"], table="lk") + assert fresh_db["lk"].count == 1 diff --git a/tests/test_extracts.py b/tests/test_extracts.py index cca16ba..7add79a 100644 --- a/tests/test_extracts.py +++ b/tests/test_extracts.py @@ -25,18 +25,18 @@ def test_extracts(fresh_db, kwargs, expected_table, use_table_factory): {"id": 2, "species_id": "Oak"}, {"id": 3, "species_id": "Palm"}, ], - **insert_kwargs + **insert_kwargs, ) # Should now have two tables: Trees and Species assert {expected_table, "Trees"} == set(fresh_db.table_names()) assert ( - "CREATE TABLE [{}] (\n [id] INTEGER PRIMARY KEY,\n [value] TEXT\n)".format( + 'CREATE TABLE "{}" (\n "id" INTEGER PRIMARY KEY,\n "value" TEXT\n)'.format( expected_table ) == fresh_db[expected_table].schema ) assert ( - "CREATE TABLE [Trees] (\n [id] INTEGER,\n [species_id] INTEGER REFERENCES [{}]([id])\n)".format( + 'CREATE TABLE "Trees" (\n "id" INTEGER,\n "species_id" INTEGER REFERENCES "{}"("id")\n)'.format( expected_table ) == fresh_db["Trees"].schema @@ -67,3 +67,51 @@ def test_extracts(fresh_db, kwargs, expected_table, use_table_factory): {"id": 2, "species_id": 1}, {"id": 3, "species_id": 2}, ] == list(fresh_db["Trees"].rows) + + +def test_extracts_null_values(fresh_db): + # https://github.com/simonw/sqlite-utils/issues/186 + # Null values should stay null, not be extracted into the lookup table + fresh_db["Trees"].insert_all( + [ + {"id": 1, "species_id": "Oak"}, + {"id": 2, "species_id": None}, + {"id": 3, "species_id": "Palm"}, + {"id": 4, "species_id": None}, + ], + extracts={"species_id": "Species"}, + ) + assert list(fresh_db["Species"].rows) == [ + {"id": 1, "value": "Oak"}, + {"id": 2, "value": "Palm"}, + ] + assert list(fresh_db["Trees"].rows) == [ + {"id": 1, "species_id": 1}, + {"id": 2, "species_id": None}, + {"id": 3, "species_id": 2}, + {"id": 4, "species_id": None}, + ] + + +def test_extracts_null_values_list_mode(fresh_db): + # Same as test_extracts_null_values but for list-based records + fresh_db["Trees"].insert_all( + [ + ["id", "species_id"], + [1, "Oak"], + [2, None], + [3, "Palm"], + [4, None], + ], + extracts={"species_id": "Species"}, + ) + assert list(fresh_db["Species"].rows) == [ + {"id": 1, "value": "Oak"}, + {"id": 2, "value": "Palm"}, + ] + assert list(fresh_db["Trees"].rows) == [ + {"id": 1, "species_id": 1}, + {"id": 2, "species_id": None}, + {"id": 3, "species_id": 2}, + {"id": 4, "species_id": None}, + ] diff --git a/tests/test_foreign_keys.py b/tests/test_foreign_keys.py new file mode 100644 index 0000000..b37d374 --- /dev/null +++ b/tests/test_foreign_keys.py @@ -0,0 +1,691 @@ +"""Tests for compound (multi-column) foreign keys - issue #594.""" + +import pytest +from sqlite_utils import Database +from sqlite_utils.db import AlterError, ForeignKey +from sqlite_utils.utils import sqlite3 + +COMPOUND_SCHEMA = """ +CREATE TABLE departments ( + campus_name TEXT NOT NULL, + dept_code TEXT NOT NULL, + dept_name TEXT, + PRIMARY KEY (campus_name, dept_code) +); +CREATE TABLE courses ( + course_code TEXT PRIMARY KEY, + course_name TEXT, + campus_name TEXT NOT NULL, + dept_code TEXT NOT NULL, + FOREIGN KEY (campus_name, dept_code) + REFERENCES departments(campus_name, dept_code) +); +""" + + +@pytest.fixture +def compound_db(): + db = Database(memory=True) + db.executescript(COMPOUND_SCHEMA) + return db + + +def test_compound_foreign_key(compound_db): + fks = compound_db["courses"].foreign_keys + assert len(fks) == 1 + fk = fks[0] + assert fk.is_compound is True + assert fk.table == "courses" + assert fk.other_table == "departments" + assert fk.columns == ("campus_name", "dept_code") + assert fk.other_columns == ("campus_name", "dept_code") + # Scalar column/other_column can't sensibly hold a compound key + assert fk.column is None + assert fk.other_column is None + + +def test_single_foreign_key_gets_columns_fields(fresh_db): + fresh_db["authors"].insert({"id": 1, "name": "Sally"}, pk="id") + fresh_db["books"].insert({"title": "Hedgehogs", "author_id": 1}) + fresh_db["books"].add_foreign_key("author_id", "authors", "id") + fk = fresh_db["books"].foreign_keys[0] + assert fk.is_compound is False + assert fk.column == "author_id" + assert fk.other_column == "id" + assert fk.columns == ("author_id",) + assert fk.other_columns == ("id",) + + +def test_foreign_key_no_longer_unpacks_as_tuple(fresh_db): + # Clean break in 4.0: ForeignKey is a dataclass, not a namedtuple, so the + # old tuple unpacking and indexing patterns now fail hard. + fresh_db["authors"].insert({"id": 1, "name": "Sally"}, pk="id") + fresh_db["books"].insert({"title": "Hedgehogs", "author_id": 1}) + fresh_db["books"].add_foreign_key("author_id", "authors", "id") + fk = fresh_db["books"].foreign_keys[0] + with pytest.raises(TypeError): + table, column, other_table, other_column = fk + with pytest.raises(TypeError): + fk[0] + + +def test_foreign_keys_are_sortable(fresh_db): + fresh_db["authors"].insert({"id": 1, "name": "Sally"}, pk="id") + fresh_db["categories"].insert({"id": 1, "name": "Wildlife"}, pk="id") + fresh_db["books"].insert({"title": "Hedgehogs", "author_id": 1, "category_id": 1}) + fresh_db.add_foreign_keys( + [ + ("books", "author_id", "authors", "id"), + ("books", "category_id", "categories", "id"), + ] + ) + fks = sorted(fresh_db["books"].foreign_keys) + assert fks[0].column == "author_id" + assert fks[1].column == "category_id" + + +def test_mixed_compound_and_single_foreign_keys_are_sortable(): + # compound FKs have column=None, which must not break sorting + # against single-column FKs (None < str raises TypeError) + db = Database(memory=True) + db.executescript(""" + CREATE TABLE departments ( + campus_name TEXT NOT NULL, + dept_code TEXT NOT NULL, + PRIMARY KEY (campus_name, dept_code) + ); + CREATE TABLE accreditations (id INTEGER PRIMARY KEY); + CREATE TABLE courses ( + course_code TEXT PRIMARY KEY, + campus_name TEXT NOT NULL, + dept_code TEXT NOT NULL, + accreditation_id INTEGER REFERENCES accreditations(id), + FOREIGN KEY (campus_name, dept_code) + REFERENCES departments(campus_name, dept_code) + ); + """) + fks = db["courses"].foreign_keys + assert len(fks) == 2 + assert {fk.is_compound for fk in fks} == {True, False} + fks_sorted = sorted(fks) + assert fks_sorted[0].other_table == "accreditations" + assert fks_sorted[1].other_table == "departments" + + +@pytest.fixture +def departments_db(): + db = Database(memory=True) + db.create_table( + "departments", + {"campus_name": str, "dept_code": str, "dept_name": str}, + pk=("campus_name", "dept_code"), + ) + return db + + +EXPECTED_COURSES_SCHEMA = ( + 'CREATE TABLE "courses" (\n' + ' "course_code" TEXT PRIMARY KEY,\n' + ' "campus_name" TEXT,\n' + ' "dept_code" TEXT,\n' + ' FOREIGN KEY ("campus_name", "dept_code") ' + 'REFERENCES "departments"("campus_name", "dept_code")\n' + ")" +) + + +@pytest.mark.parametrize( + "foreign_keys", + ( + [ + ForeignKey( + table="courses", + column=None, + other_table="departments", + other_column=None, + columns=("campus_name", "dept_code"), + other_columns=("campus_name", "dept_code"), + is_compound=True, + ) + ], + [(("campus_name", "dept_code"), "departments", ("campus_name", "dept_code"))], + # Two-item form guesses the other table's primary key: + [(("campus_name", "dept_code"), "departments")], + # Lists work too, though tuples are the documented form: + [(["campus_name", "dept_code"], "departments", ["campus_name", "dept_code"])], + ), +) +def test_create_table_with_compound_foreign_key(departments_db, foreign_keys): + departments_db.create_table( + "courses", + {"course_code": str, "campus_name": str, "dept_code": str}, + pk="course_code", + foreign_keys=foreign_keys, + ) + assert departments_db["courses"].schema == EXPECTED_COURSES_SCHEMA + fks = departments_db["courses"].foreign_keys + assert len(fks) == 1 + fk = fks[0] + assert fk.is_compound is True + assert fk.columns == ("campus_name", "dept_code") + assert fk.other_table == "departments" + assert fk.other_columns == ("campus_name", "dept_code") + + +def test_create_table_compound_foreign_key_enforced(departments_db): + departments_db.execute("PRAGMA foreign_keys = ON") + departments_db.create_table( + "courses", + {"course_code": str, "campus_name": str, "dept_code": str}, + pk="course_code", + foreign_keys=[(("campus_name", "dept_code"), "departments")], + ) + departments_db["departments"].insert( + {"campus_name": "Berkeley", "dept_code": "CS", "dept_name": "Computer Science"} + ) + departments_db["courses"].insert( + {"course_code": "CS101", "campus_name": "Berkeley", "dept_code": "CS"} + ) + with pytest.raises(sqlite3.IntegrityError): + departments_db.execute( + "insert into courses (course_code, campus_name, dept_code) " + "values ('X1', 'Nowhere', 'NOPE')" + ) + + +def test_create_table_compound_foreign_key_missing_other_column(departments_db): + with pytest.raises(AlterError): + departments_db.create_table( + "courses", + {"course_code": str, "campus_name": str, "dept_code": str}, + pk="course_code", + foreign_keys=[ + (("campus_name", "dept_code"), "departments", ("campus_name", "nope")) + ], + ) + + +def test_transform_preserves_compound_foreign_key(compound_db): + compound_db["courses"].transform(rename={"course_name": "title"}) + fks = compound_db["courses"].foreign_keys + assert len(fks) == 1 + fk = fks[0] + assert fk.is_compound is True + assert fk.columns == ("campus_name", "dept_code") + assert fk.other_table == "departments" + assert fk.other_columns == ("campus_name", "dept_code") + + +def test_transform_rename_member_column_updates_compound_foreign_key(compound_db): + compound_db["courses"].transform(rename={"campus_name": "campus"}) + fks = compound_db["courses"].foreign_keys + assert len(fks) == 1 + fk = fks[0] + assert fk.is_compound is True + assert fk.columns == ("campus", "dept_code") + # Referenced columns in the other table are unchanged + assert fk.other_columns == ("campus_name", "dept_code") + + +def test_transform_drop_member_column_drops_compound_foreign_key(compound_db): + # Matches single-column behavior: dropping the column silently + # drops the foreign key that used it + compound_db["courses"].transform(drop={"dept_code"}) + assert compound_db["courses"].foreign_keys == [] + assert "FOREIGN KEY" not in compound_db["courses"].schema + + +@pytest.mark.parametrize( + "drop_foreign_keys", + ( + # A bare column name matches any foreign key it participates in: + ["campus_name"], + # A tuple must match the full compound key: + [("campus_name", "dept_code")], + ), +) +def test_transform_drop_compound_foreign_key(compound_db, drop_foreign_keys): + compound_db["courses"].transform(drop_foreign_keys=drop_foreign_keys) + assert compound_db["courses"].foreign_keys == [] + # The columns themselves survive + assert {"campus_name", "dept_code"} <= set( + compound_db["courses"].columns_dict.keys() + ) + + +@pytest.fixture +def courses_db(departments_db): + departments_db.create_table( + "courses", + {"course_code": str, "campus_name": str, "dept_code": str}, + pk="course_code", + ) + return departments_db + + +def test_add_compound_foreign_key(courses_db): + t = courses_db["courses"].add_foreign_key( + ("campus_name", "dept_code"), "departments", ("campus_name", "dept_code") + ) + # Returns self + assert t.name == "courses" + fks = courses_db["courses"].foreign_keys + assert len(fks) == 1 + fk = fks[0] + assert fk.is_compound is True + assert fk.columns == ("campus_name", "dept_code") + assert fk.other_table == "departments" + assert fk.other_columns == ("campus_name", "dept_code") + + +def test_add_compound_foreign_key_guesses_other_columns(courses_db): + # Lists work here too, though tuples are the documented form + courses_db["courses"].add_foreign_key(["campus_name", "dept_code"], "departments") + fk = courses_db["courses"].foreign_keys[0] + assert fk.other_columns == ("campus_name", "dept_code") + + +def test_add_compound_foreign_key_error_if_already_exists(courses_db): + courses_db["courses"].add_foreign_key(("campus_name", "dept_code"), "departments") + with pytest.raises(AlterError) as ex: + courses_db["courses"].add_foreign_key( + ("campus_name", "dept_code"), "departments" + ) + assert "already exists" in ex.value.args[0] + # ignore=True should not raise + courses_db["courses"].add_foreign_key( + ("campus_name", "dept_code"), "departments", ignore=True + ) + + +def test_add_compound_foreign_key_error_if_column_missing(courses_db): + with pytest.raises(AlterError): + courses_db["courses"].add_foreign_key(("campus_name", "nope"), "departments") + + +def test_db_add_foreign_keys_compound(courses_db): + courses_db.add_foreign_keys( + [ + ( + "courses", + ("campus_name", "dept_code"), + "departments", + ("campus_name", "dept_code"), + ) + ] + ) + fk = courses_db["courses"].foreign_keys[0] + assert fk.is_compound is True + assert fk.columns == ("campus_name", "dept_code") + + +def test_index_foreign_keys_compound_creates_composite_index(compound_db): + compound_db.index_foreign_keys() + index_columns = [i.columns for i in compound_db["courses"].indexes] + assert ["campus_name", "dept_code"] in index_columns + # No separate single-column indexes for the members + assert ["campus_name"] not in index_columns + assert ["dept_code"] not in index_columns + + +def test_foreign_key_captures_on_delete_and_on_update(): + db = Database(memory=True) + db.executescript(""" + CREATE TABLE authors (id INTEGER PRIMARY KEY); + CREATE TABLE books ( + id INTEGER PRIMARY KEY, + author_id INTEGER REFERENCES authors(id) + ON DELETE CASCADE ON UPDATE RESTRICT + ); + """) + fk = db["books"].foreign_keys[0] + assert fk.on_delete == "CASCADE" + assert fk.on_update == "RESTRICT" + + +def test_foreign_key_on_delete_defaults_to_no_action(fresh_db): + fresh_db["authors"].insert({"id": 1}, pk="id") + fresh_db["books"].insert({"id": 1, "author_id": 1}, pk="id") + fresh_db["books"].add_foreign_key("author_id", "authors", "id") + fk = fresh_db["books"].foreign_keys[0] + assert fk.on_delete == "NO ACTION" + assert fk.on_update == "NO ACTION" + + +def test_create_table_foreign_key_with_on_delete(fresh_db): + fresh_db["authors"].insert({"id": 1}, pk="id") + fresh_db.create_table( + "books", + {"id": int, "author_id": int}, + pk="id", + foreign_keys=[ + ForeignKey( + table="books", + column="author_id", + other_table="authors", + other_column="id", + on_delete="CASCADE", + ) + ], + ) + assert "ON DELETE CASCADE" in fresh_db["books"].schema + assert fresh_db["books"].foreign_keys[0].on_delete == "CASCADE" + + +def test_transform_preserves_on_delete_cascade(): + db = Database(memory=True) + db.executescript(""" + CREATE TABLE authors (id INTEGER PRIMARY KEY); + CREATE TABLE books ( + id INTEGER PRIMARY KEY, + title TEXT, + author_id INTEGER REFERENCES authors(id) ON DELETE CASCADE + ); + """) + db["books"].transform(rename={"title": "book_title"}) + fk = db["books"].foreign_keys[0] + assert fk.on_delete == "CASCADE" + assert fk.on_update == "NO ACTION" + assert "ON DELETE CASCADE" in db["books"].schema + + +def test_transform_preserves_compound_foreign_key_on_delete(): + db = Database(memory=True) + db.executescript(""" + CREATE TABLE departments ( + campus_name TEXT NOT NULL, + dept_code TEXT NOT NULL, + PRIMARY KEY (campus_name, dept_code) + ); + CREATE TABLE courses ( + course_code TEXT PRIMARY KEY, + campus_name TEXT NOT NULL, + dept_code TEXT NOT NULL, + FOREIGN KEY (campus_name, dept_code) + REFERENCES departments(campus_name, dept_code) ON DELETE CASCADE + ); + """) + db["courses"].transform(rename={"course_code": "code"}) + fk = db["courses"].foreign_keys[0] + assert fk.is_compound is True + assert fk.on_delete == "CASCADE" + assert "ON DELETE CASCADE" in db["courses"].schema + + +def test_implicit_primary_key_reference_is_resolved(): + # REFERENCES authors (no column) has "to" of None in the pragma - + # it should be resolved to the primary key of the other table + db = Database(memory=True) + db.executescript(""" + CREATE TABLE authors (author_id INTEGER PRIMARY KEY); + CREATE TABLE books ( + id INTEGER PRIMARY KEY, + author_id INTEGER REFERENCES authors + ); + """) + fk = db["books"].foreign_keys[0] + assert fk.is_compound is False + assert fk.other_column == "author_id" + assert fk.other_columns == ("author_id",) + + +def test_implicit_compound_primary_key_reference_is_resolved(): + db = Database(memory=True) + db.executescript(""" + CREATE TABLE departments ( + campus_name TEXT NOT NULL, + dept_code TEXT NOT NULL, + PRIMARY KEY (campus_name, dept_code) + ); + CREATE TABLE courses ( + course_code TEXT PRIMARY KEY, + campus_name TEXT NOT NULL, + dept_code TEXT NOT NULL, + FOREIGN KEY (campus_name, dept_code) REFERENCES departments + ); + """) + fk = db["courses"].foreign_keys[0] + assert fk.is_compound is True + assert fk.other_columns == ("campus_name", "dept_code") + + +def test_foreign_key_normalizes_list_columns_to_tuples(): + # Compound columns passed as lists are normalized to tuples, so they + # compare equal to introspected ForeignKeys + fk = ForeignKey( + table="courses", + column=None, + other_table="departments", + other_column=None, + columns=["campus_name", "dept_code"], + other_columns=["campus_name", "dept_code"], + is_compound=True, + ) + assert fk.columns == ("campus_name", "dept_code") + assert fk.other_columns == ("campus_name", "dept_code") + + +def test_add_foreign_keys_preserves_actions(fresh_db): + # https://github.com/simonw/sqlite-utils/issues/594 review finding: + # ForeignKey objects passed to db.add_foreign_keys() were flattened + # to plain tuples, losing on_delete/on_update + fresh_db["authors"].insert({"id": 1}, pk="id") + fresh_db["books"].insert({"id": 1, "author_id": 1}, pk="id") + fresh_db.add_foreign_keys( + [ForeignKey("books", "author_id", "authors", "id", on_delete="CASCADE")] + ) + fk = fresh_db["books"].foreign_keys[0] + assert fk.on_delete == "CASCADE" + assert "ON DELETE CASCADE" in fresh_db["books"].schema + + +def test_add_foreign_keys_preserves_actions_compound(courses_db): + courses_db.add_foreign_keys( + [ + ForeignKey( + table="courses", + column=None, + other_table="departments", + other_column=None, + columns=("campus_name", "dept_code"), + other_columns=("campus_name", "dept_code"), + is_compound=True, + on_delete="CASCADE", + ) + ] + ) + fk = courses_db["courses"].foreign_keys[0] + assert fk.is_compound is True + assert fk.on_delete == "CASCADE" + assert "ON DELETE CASCADE" in courses_db["courses"].schema + + +def test_add_foreign_key_on_delete_on_update(fresh_db): + fresh_db["authors"].insert({"id": 1}, pk="id") + fresh_db["books"].insert({"id": 1, "author_id": 1}, pk="id") + fresh_db["books"].add_foreign_key( + "author_id", "authors", "id", on_delete="CASCADE", on_update="RESTRICT" + ) + fk = fresh_db["books"].foreign_keys[0] + assert fk.on_delete == "CASCADE" + assert fk.on_update == "RESTRICT" + assert "ON UPDATE RESTRICT ON DELETE CASCADE" in fresh_db["books"].schema + # The cascade should actually fire + fresh_db.execute("PRAGMA foreign_keys = ON") + fresh_db.execute("delete from authors where id = 1") + assert fresh_db["books"].count == 0 + + +def test_add_compound_foreign_key_on_delete(courses_db): + courses_db["courses"].add_foreign_key( + ("campus_name", "dept_code"), "departments", on_delete="SET NULL" + ) + fk = courses_db["courses"].foreign_keys[0] + assert fk.is_compound is True + assert fk.on_delete == "SET NULL" + assert "ON DELETE SET NULL" in courses_db["courses"].schema + + +def test_implicit_compound_foreign_key_resolves_pk_declaration_order(fresh_db): + # The other table's PRIMARY KEY declares its columns in a different + # order to the table's column order. SQLite resolves the implicit + # "REFERENCES other" using PRIMARY KEY declaration order, so the + # introspected other_columns must too + fresh_db.execute("create table other (b text, a text, primary key (a, b))") + fresh_db.execute( + "create table child (x text, y text, foreign key (x, y) references other)" + ) + fk = fresh_db["child"].foreign_keys[0] + assert fk.other_columns == ("a", "b") + + +def test_transform_implicit_compound_foreign_key_stays_valid(fresh_db): + # transform() rewrites the implicit FK with explicit columns - they + # must be in PRIMARY KEY declaration order or valid data fails the + # foreign key check with an IntegrityError + fresh_db.execute("create table other (b text, a text, primary key (a, b))") + fresh_db.execute( + "create table child (x text, y text, foreign key (x, y) references other)" + ) + fresh_db.execute("PRAGMA foreign_keys = ON") + fresh_db["other"].insert({"a": "A", "b": "B"}) + fresh_db["child"].insert({"x": "A", "y": "B"}) + fresh_db["child"].transform(types={"x": str}) + assert fresh_db["child"].foreign_keys[0].other_columns == ("a", "b") + # The constraint still points the right way around + fresh_db["child"].insert({"x": "A", "y": "B"}) + with pytest.raises(sqlite3.IntegrityError): + fresh_db["child"].insert({"x": "B", "y": "A"}) + + +def test_create_compound_foreign_key_guesses_pk_declaration_order(fresh_db): + fresh_db.execute("create table other (b text, a text, primary key (a, b))") + fresh_db["other"].insert({"a": "A", "b": "B"}) + fresh_db["child"].create( + {"id": int, "x": str, "y": str}, + pk="id", + foreign_keys=[(("x", "y"), "other")], + ) + assert fresh_db["child"].foreign_keys[0].other_columns == ("a", "b") + fresh_db.execute("PRAGMA foreign_keys = ON") + fresh_db["child"].insert({"id": 1, "x": "A", "y": "B"}) + with pytest.raises(sqlite3.IntegrityError): + fresh_db["child"].insert({"id": 2, "x": "B", "y": "A"}) + + +def test_add_compound_foreign_key_guesses_pk_declaration_order(fresh_db): + fresh_db.execute("create table other (b text, a text, primary key (a, b))") + fresh_db["child"].insert({"id": 1, "x": "A", "y": "B"}, pk="id") + fresh_db["child"].add_foreign_key(("x", "y"), "other") + assert fresh_db["child"].foreign_keys[0].other_columns == ("a", "b") + + +def test_foreign_keys_are_hashable(fresh_db): + # set() over foreign_keys worked with the 3.x namedtuple and must + # keep working with the dataclass + fresh_db["p"].insert({"id": 1}, pk="id") + fresh_db["c"].insert( + {"id": 1, "pid": 1}, pk="id", foreign_keys=[("pid", "p", "id")] + ) + fks = set(fresh_db["c"].foreign_keys) + assert len(fks) == 1 + assert ForeignKey("c", "pid", "p", "id") in fks + # Usable as dict keys too + assert {fk: True for fk in fks} + + +def test_foreign_key_is_immutable(): + import dataclasses + + fk = ForeignKey("c", "pid", "p", "id") + with pytest.raises(dataclasses.FrozenInstanceError): + fk.table = "other" + + +def test_foreign_key_equality_and_hash_include_actions(): + # Two foreign keys differing only in ON DELETE behavior are different + # constraints - they compare unequal and hash separately + plain = ForeignKey("c", "pid", "p", "id") + cascade = ForeignKey("c", "pid", "p", "id", on_delete="CASCADE") + assert plain != cascade + assert len({plain, cascade}) == 2 + assert plain == ForeignKey("c", "pid", "p", "id") + + +def test_create_table_mixed_foreign_keys_list(fresh_db): + # 3.x accepted a mix of ForeignKey objects, tuples and bare column + # strings in foreign_keys= (ForeignKey was a namedtuple, so it passed + # the tuple check) - keep accepting the mix + fresh_db["authors"].insert({"id": 1}, pk="id") + fresh_db["publishers"].insert({"id": 1}, pk="id") + fresh_db["books"].create( + {"id": int, "author_id": int, "publisher_id": int}, + pk="id", + foreign_keys=[ + ForeignKey("books", "author_id", "authors", "id"), + ("publisher_id", "publishers", "id"), + ], + ) + fks = {fk.column: fk.other_table for fk in fresh_db["books"].foreign_keys} + assert fks == {"author_id": "authors", "publisher_id": "publishers"} + + +def test_create_table_mixed_foreign_keys_with_string(fresh_db): + fresh_db["authors"].insert({"id": 1}, pk="id") + fresh_db["publishers"].insert({"id": 1}, pk="id") + fresh_db["books"].create( + {"id": int, "author_id": int, "publisher_id": int}, + pk="id", + foreign_keys=[ + "author_id", # bare column, table and column guessed + ("publisher_id", "publishers", "id"), + ], + ) + fks = {fk.column: fk.other_table for fk in fresh_db["books"].foreign_keys} + assert fks == {"author_id": "authors", "publisher_id": "publishers"} + + +def test_add_foreign_keys_existing_with_different_actions_errors(fresh_db): + # Requesting an existing foreign key with different ON DELETE/ON UPDATE + # actions was silently skipped, dropping the requested change + fresh_db["authors"].insert({"id": 1}, pk="id") + fresh_db["books"].insert( + {"id": 1, "author_id": 1}, + pk="id", + foreign_keys=[("author_id", "authors", "id")], + ) + with pytest.raises(AlterError) as ex: + fresh_db.add_foreign_keys( + [ForeignKey("books", "author_id", "authors", "id", on_delete="CASCADE")] + ) + assert "ON DELETE" in str(ex.value) + assert fresh_db["books"].foreign_keys[0].on_delete == "NO ACTION" + + +def test_add_foreign_keys_identical_existing_is_noop(fresh_db): + # An exact match, including actions, is silently skipped so repeated + # calls stay idempotent + fresh_db["authors"].insert({"id": 1}, pk="id") + fresh_db["books"].insert({"id": 1, "author_id": 1}, pk="id") + fresh_db["books"].add_foreign_key("author_id", "authors", "id", on_delete="CASCADE") + fresh_db.add_foreign_keys( + [ForeignKey("books", "author_id", "authors", "id", on_delete="CASCADE")] + ) + fks = fresh_db["books"].foreign_keys + assert len(fks) == 1 + assert fks[0].on_delete == "CASCADE" + + +def test_add_foreign_keys_compound_column_count_mismatch_errors(fresh_db): + # Previously the extra other-column was silently discarded, creating + # a single-column foreign key to just ("id") + fresh_db["departments"].insert( + {"campus": "north", "code": "cs"}, pk=("campus", "code") + ) + fresh_db["courses"].insert({"id": 1, "campus": "north"}, pk="id") + with pytest.raises(ValueError) as ex: + fresh_db.add_foreign_keys( + [("courses", ("campus",), "departments", ("campus", "code"))] + ) + assert "same number of columns" in str(ex.value) + assert fresh_db["courses"].foreign_keys == [] diff --git a/tests/test_fts.py b/tests/test_fts.py index ecfcff9..64ec645 100644 --- a/tests/test_fts.py +++ b/tests/test_fts.py @@ -1,6 +1,7 @@ import pytest from sqlite_utils import Database from sqlite_utils.utils import sqlite3 +from unittest.mock import ANY search_records = [ { @@ -82,6 +83,20 @@ def test_enable_fts_escape_table_names(fresh_db): assert [] == list(table.search("bar")) +def test_search_duplicate_columns_are_deduped(fresh_db): + # https://github.com/simonw/sqlite-utils/issues/624 + table = fresh_db["t"] + table.insert_all(search_records) + table.enable_fts(["text", "country"], fts_version="FTS4") + rows = list(table.search("tanuki", columns=["text", "text"])) + assert rows == [ + { + "text": "tanuki are running tricksters", + "text_2": "tanuki are running tricksters", + } + ] + + def test_search_limit_offset(fresh_db): table = fresh_db["t"] table.insert_all(search_records) @@ -126,6 +141,32 @@ def test_search_where_args_disallows_query(fresh_db): ) +def test_search_include_rank(fresh_db): + table = fresh_db["t"] + table.insert_all(search_records) + table.enable_fts(["text", "country"], fts_version="FTS5") + results = list(table.search("are", include_rank=True)) + assert results == [ + { + "rowid": 1, + "text": "tanuki are running tricksters", + "country": "Japan", + "not_searchable": "foo", + "rank": ANY, + }, + { + "rowid": 2, + "text": "racoons are biting trash pandas", + "country": "USA", + "not_searchable": "bar", + "rank": ANY, + }, + ] + assert isinstance(results[0]["rank"], float) + assert isinstance(results[1]["rank"], float) + assert results[0]["rank"] < results[1]["rank"] + + def test_enable_fts_table_names_containing_spaces(fresh_db): table = fresh_db["test"] table.insert({"column with spaces": "in its name"}) @@ -309,6 +350,24 @@ def test_rebuild_fts(fresh_db): assert len(rows2) == 2 +@pytest.mark.parametrize("method", ["optimize", "rebuild_fts"]) +def test_optimize_and_rebuild_fts_commit(tmpdir, method): + path = str(tmpdir / "test.db") + db = Database(path) + table = db["searchable"] + table.insert(search_records[0]) + table.enable_fts(["text", "country"]) + getattr(table, method)() + # The connection must not be left inside an open transaction, + # otherwise this and all subsequent writes are lost on close + assert not db.conn.in_transaction + table.insert(search_records[1]) + db.close() + db2 = Database(path) + assert db2["searchable"].count == 2 + db2.close() + + @pytest.mark.parametrize("invalid_table", ["does_not_exist", "not_searchable"]) def test_rebuild_fts_invalid(fresh_db, invalid_table): fresh_db["not_searchable"].insert({"foo": "bar"}) @@ -393,12 +452,35 @@ def test_enable_fts_replace_does_nothing_if_args_the_same(): assert all(q[0].startswith("select ") for q in queries) -def test_enable_fts_error_message_on_views(): +def test_enable_fts_replace_handles_legacy_bracket_quoted_content_table(): + db = Database(memory=True) + db["books"].insert( + { + "id": 1, + "title": "Habits of Australian Marsupials", + "author": "Marlee Hawkins", + }, + pk="id", + ) + db.executescript(""" + CREATE VIRTUAL TABLE [books_fts] USING FTS5 ( + [title], + content=[books] + ); + """) + + db["books"].enable_fts(["title", "author"], replace=True) + + assert db["books_fts"].columns_dict.keys() == {"title", "author"} + assert 'content="books"' in db["books_fts"].schema + + +def test_view_has_no_enable_fts(): db = Database(memory=True) db.create_view("hello", "select 1 + 1") - with pytest.raises(NotImplementedError) as e: - db["hello"].enable_fts() - assert e.value.args[0] == "enable_fts() is supported on tables but not on views" + # Views deliberately do not have an enable_fts() method + with pytest.raises(AttributeError): + db["hello"].enable_fts() # type: ignore[union-attr] @pytest.mark.parametrize( @@ -408,40 +490,40 @@ def test_enable_fts_error_message_on_views(): {}, "FTS5", ( - "with original as (\n" + 'with "original" as (\n' " select\n" " rowid,\n" " *\n" - " from [books]\n" + ' from "books"\n' ")\n" "select\n" - " [original].*\n" + ' "original".*\n' "from\n" - " [original]\n" - " join [books_fts] on [original].rowid = [books_fts].rowid\n" + ' "original"\n' + ' join "books_fts" on "original".rowid = "books_fts".rowid\n' "where\n" - " [books_fts] match :query\n" + ' "books_fts" match :query\n' "order by\n" - " [books_fts].rank" + ' "books_fts".rank' ), ), ( {"columns": ["title"], "order_by": "rowid", "limit": 10}, "FTS5", ( - "with original as (\n" + 'with "original" as (\n' " select\n" " rowid,\n" - " [title]\n" - " from [books]\n" + ' "title"\n' + ' from "books"\n' ")\n" "select\n" - " [original].[title]\n" + ' "original"."title"\n' "from\n" - " [original]\n" - " join [books_fts] on [original].rowid = [books_fts].rowid\n" + ' "original"\n' + ' join "books_fts" on "original".rowid = "books_fts".rowid\n' "where\n" - " [books_fts] match :query\n" + ' "books_fts" match :query\n' "order by\n" " rowid\n" "limit 10" @@ -451,64 +533,64 @@ def test_enable_fts_error_message_on_views(): {"where": "author = :author"}, "FTS5", ( - "with original as (\n" + 'with "original" as (\n' " select\n" " rowid,\n" " *\n" - " from [books]\n" + ' from "books"\n' " where author = :author\n" ")\n" "select\n" - " [original].*\n" + ' "original".*\n' "from\n" - " [original]\n" - " join [books_fts] on [original].rowid = [books_fts].rowid\n" + ' "original"\n' + ' join "books_fts" on "original".rowid = "books_fts".rowid\n' "where\n" - " [books_fts] match :query\n" + ' "books_fts" match :query\n' "order by\n" - " [books_fts].rank" + ' "books_fts".rank' ), ), ( {"columns": ["title"]}, "FTS4", ( - "with original as (\n" + 'with "original" as (\n' " select\n" " rowid,\n" - " [title]\n" - " from [books]\n" + ' "title"\n' + ' from "books"\n' ")\n" "select\n" - " [original].[title]\n" + ' "original"."title"\n' "from\n" - " [original]\n" - " join [books_fts] on [original].rowid = [books_fts].rowid\n" + ' "original"\n' + ' join "books_fts" on "original".rowid = "books_fts".rowid\n' "where\n" - " [books_fts] match :query\n" + ' "books_fts" match :query\n' "order by\n" - " rank_bm25(matchinfo([books_fts], 'pcnalx'))" + " rank_bm25(matchinfo(\"books_fts\", 'pcnalx'))" ), ), ( {"offset": 1, "limit": 1}, "FTS4", ( - "with original as (\n" + 'with "original" as (\n' " select\n" " rowid,\n" " *\n" - " from [books]\n" + ' from "books"\n' ")\n" "select\n" - " [original].*\n" + ' "original".*\n' "from\n" - " [original]\n" - " join [books_fts] on [original].rowid = [books_fts].rowid\n" + ' "original"\n' + ' join "books_fts" on "original".rowid = "books_fts".rowid\n' "where\n" - " [books_fts] match :query\n" + ' "books_fts" match :query\n' "order by\n" - " rank_bm25(matchinfo([books_fts], 'pcnalx'))\n" + " rank_bm25(matchinfo(\"books_fts\", 'pcnalx'))\n" "limit 1 offset 1" ), ), @@ -516,21 +598,21 @@ def test_enable_fts_error_message_on_views(): {"limit": 2}, "FTS4", ( - "with original as (\n" + 'with "original" as (\n' " select\n" " rowid,\n" " *\n" - " from [books]\n" + ' from "books"\n' ")\n" "select\n" - " [original].*\n" + ' "original".*\n' "from\n" - " [original]\n" - " join [books_fts] on [original].rowid = [books_fts].rowid\n" + ' "original"\n' + ' join "books_fts" on "original".rowid = "books_fts".rowid\n' "where\n" - " [books_fts] match :query\n" + ' "books_fts" match :query\n' "order by\n" - " rank_bm25(matchinfo([books_fts], 'pcnalx'))\n" + " rank_bm25(matchinfo(\"books_fts\", 'pcnalx'))\n" "limit 2" ), ), @@ -538,66 +620,66 @@ def test_enable_fts_error_message_on_views(): {"where": "author = :author"}, "FTS4", ( - "with original as (\n" + 'with "original" as (\n' " select\n" " rowid,\n" " *\n" - " from [books]\n" + ' from "books"\n' " where author = :author\n" ")\n" "select\n" - " [original].*\n" + ' "original".*\n' "from\n" - " [original]\n" - " join [books_fts] on [original].rowid = [books_fts].rowid\n" + ' "original"\n' + ' join "books_fts" on "original".rowid = "books_fts".rowid\n' "where\n" - " [books_fts] match :query\n" + ' "books_fts" match :query\n' "order by\n" - " rank_bm25(matchinfo([books_fts], 'pcnalx'))" + " rank_bm25(matchinfo(\"books_fts\", 'pcnalx'))" ), ), ( {"include_rank": True}, "FTS5", ( - "with original as (\n" + 'with "original" as (\n' " select\n" " rowid,\n" " *\n" - " from [books]\n" + ' from "books"\n' ")\n" "select\n" - " [original].*,\n" - " [books_fts].rank rank\n" + ' "original".*,\n' + ' "books_fts".rank rank\n' "from\n" - " [original]\n" - " join [books_fts] on [original].rowid = [books_fts].rowid\n" + ' "original"\n' + ' join "books_fts" on "original".rowid = "books_fts".rowid\n' "where\n" - " [books_fts] match :query\n" + ' "books_fts" match :query\n' "order by\n" - " [books_fts].rank" + ' "books_fts".rank' ), ), ( {"include_rank": True}, "FTS4", ( - "with original as (\n" + 'with "original" as (\n' " select\n" " rowid,\n" " *\n" - " from [books]\n" + ' from "books"\n' ")\n" "select\n" - " [original].*,\n" - " rank_bm25(matchinfo([books_fts], 'pcnalx')) rank\n" + ' "original".*,\n' + " rank_bm25(matchinfo(\"books_fts\", 'pcnalx')) rank\n" "from\n" - " [original]\n" - " join [books_fts] on [original].rowid = [books_fts].rowid\n" + ' "original"\n' + ' join "books_fts" on "original".rowid = "books_fts".rowid\n' "where\n" - " [books_fts] match :query\n" + ' "books_fts" match :query\n' "order by\n" - " rank_bm25(matchinfo([books_fts], 'pcnalx'))" + " rank_bm25(matchinfo(\"books_fts\", 'pcnalx'))" ), ), ], @@ -650,3 +732,17 @@ def test_search_quote(fresh_db): list(table.search(query)) # No exception with quote=True list(table.search(query, quote=True)) + + +def test_enable_fts_cli_on_view_errors(tmpdir): + db_path = str(tmpdir / "test.db") + db = Database(db_path) + db["t"].insert({"text": "hello"}) + db.create_view("v", "select * from t") + db.close() + from click.testing import CliRunner + from sqlite_utils import cli as cli_module + + result = CliRunner().invoke(cli_module.cli, ["enable-fts", db_path, "v", "text"]) + assert result.exit_code == 1 + assert result.output.strip() == "Error: Table v is actually a view" diff --git a/tests/test_gis.py b/tests/test_gis.py index a4ee75e..f39554e 100644 --- a/tests/test_gis.py +++ b/tests/test_gis.py @@ -6,12 +6,6 @@ from sqlite_utils.cli import cli from sqlite_utils.db import Database from sqlite_utils.utils import find_spatialite, sqlite3 -try: - import sqlean -except ImportError: - sqlean = None - - pytestmark = [ pytest.mark.skipif( not find_spatialite(), reason="Could not find SpatiaLite extension" @@ -20,9 +14,6 @@ pytestmark = [ not hasattr(sqlite3.Connection, "enable_load_extension"), reason="sqlite3.Connection missing enable_load_extension", ), - pytest.mark.skipif( - sqlean is not None, reason="sqlean.py is not compatible with SpatiaLite" - ), ] @@ -50,7 +41,7 @@ def test_add_geometry_column(): column_name="geometry", geometry_type="Point", srid=4326, - coord_dimension=2, + coord_dimension="XY", ) assert db["geometry_columns"].get(["locations", "geometry"]) == { diff --git a/tests/test_insert_files.py b/tests/test_insert_files.py index d7af28e..88e49a8 100644 --- a/tests/test_insert_files.py +++ b/tests/test_insert_files.py @@ -7,7 +7,14 @@ import sys @pytest.mark.parametrize("silent", (False, True)) -def test_insert_files(silent): +@pytest.mark.parametrize( + "pk_args,expected_pks", + ( + (["--pk", "path"], ["path"]), + (["--pk", "path", "--pk", "name"], ["path", "name"]), + ), +) +def test_insert_files(silent, pk_args, expected_pks): runner = CliRunner() with runner.isolated_filesystem(): tmpdir = pathlib.Path(".") @@ -42,7 +49,7 @@ def test_insert_files(silent): cli.cli, ["insert-files", db_path, "files", str(tmpdir)] + cols - + ["--pk", "path"] + + pk_args + (["--silent"] if silent else []), catch_exceptions=False, ) @@ -105,6 +112,7 @@ def test_insert_files(silent): for colname, expected_type in expected_types.items(): for row in (one, two, three): assert isinstance(row[colname], expected_type) + assert set(db["files"].pks) == set(expected_pks) @pytest.mark.parametrize( diff --git a/tests/test_introspect.py b/tests/test_introspect.py index f668344..8b6765d 100644 --- a/tests/test_introspect.py +++ b/tests/test_introspect.py @@ -2,6 +2,14 @@ from sqlite_utils.db import Index, View, Database, XIndex, XIndexColumn import pytest +def _check_supports_strict(): + """Check if SQLite supports strict tables without leaking the database.""" + db = Database(memory=True) + result = db.supports_strict + db.close() + return result + + def test_table_names(existing_db): assert ["foo"] == existing_db.table_names() @@ -101,13 +109,11 @@ def test_table_repr(fresh_db): def test_indexes(fresh_db): - fresh_db.executescript( - """ + fresh_db.executescript(""" create table Gosh (c1 text, c2 text, c3 text); create index Gosh_c1 on Gosh(c1); create index Gosh_c2c3 on Gosh(c2, c3); - """ - ) + """) assert [ Index( seq=0, @@ -122,13 +128,11 @@ def test_indexes(fresh_db): def test_xindexes(fresh_db): - fresh_db.executescript( - """ + fresh_db.executescript(""" create table Gosh (c1 text, c2 text, c3 text); create index Gosh_c1 on Gosh(c1); create index Gosh_c2c3 on Gosh(c2, c3 desc); - """ - ) + """) assert fresh_db["Gosh"].xindexes == [ XIndex( name="Gosh_c2c3", @@ -200,19 +204,19 @@ def test_triggers_and_triggers_dict(fresh_db): } expected_triggers = { "authors_ai": ( - "CREATE TRIGGER [authors_ai] AFTER INSERT ON [authors] BEGIN\n" - " INSERT INTO [authors_fts] (rowid, [name], [famous_works]) VALUES (new.rowid, new.[name], new.[famous_works]);\n" + 'CREATE TRIGGER "authors_ai" AFTER INSERT ON "authors" BEGIN\n' + ' INSERT INTO "authors_fts" (rowid, "name", "famous_works") VALUES (new.rowid, new."name", new."famous_works");\n' "END" ), "authors_ad": ( - "CREATE TRIGGER [authors_ad] AFTER DELETE ON [authors] BEGIN\n" - " INSERT INTO [authors_fts] ([authors_fts], rowid, [name], [famous_works]) VALUES('delete', old.rowid, old.[name], old.[famous_works]);\n" + 'CREATE TRIGGER "authors_ad" AFTER DELETE ON "authors" BEGIN\n' + ' INSERT INTO "authors_fts" ("authors_fts", rowid, "name", "famous_works") VALUES(\'delete\', old.rowid, old."name", old."famous_works");\n' "END" ), "authors_au": ( - "CREATE TRIGGER [authors_au] AFTER UPDATE ON [authors] BEGIN\n" - " INSERT INTO [authors_fts] ([authors_fts], rowid, [name], [famous_works]) VALUES('delete', old.rowid, old.[name], old.[famous_works]);\n" - " INSERT INTO [authors_fts] (rowid, [name], [famous_works]) VALUES (new.rowid, new.[name], new.[famous_works]);\nEND" + 'CREATE TRIGGER "authors_au" AFTER UPDATE ON "authors" BEGIN\n' + ' INSERT INTO "authors_fts" ("authors_fts", rowid, "name", "famous_works") VALUES(\'delete\', old.rowid, old."name", old."famous_works");\n' + ' INSERT INTO "authors_fts" (rowid, "name", "famous_works") VALUES (new.rowid, new."name", new."famous_works");\nEND' ), } assert authors.triggers_dict == expected_triggers @@ -282,7 +286,7 @@ def test_use_rowid(fresh_db): @pytest.mark.skipif( - not Database(memory=True).supports_strict, + not _check_supports_strict(), reason="Needs SQLite version that supports strict", ) @pytest.mark.parametrize( @@ -317,3 +321,18 @@ def test_table_default_values(fresh_db, value): ) default_values = fresh_db["default_values"].default_values assert default_values == {"value": value} + + +def test_pks_use_primary_key_declaration_order(fresh_db): + # PRIMARY KEY (a, b) declared against columns stored in order (b, a) - + # pks must follow the declaration order, which is what SQLite uses to + # resolve implicit foreign key references and compound pk lookups + fresh_db.execute("create table t (b text, a text, primary key (a, b))") + assert fresh_db["t"].pks == ["a", "b"] + + +def test_transform_preserves_compound_pk_declaration_order(fresh_db): + fresh_db.execute("create table t (a text, b text, c text, primary key (b, a))") + fresh_db["t"].transform(drop={"c"}) + assert fresh_db["t"].pks == ["b", "a"] + assert 'PRIMARY KEY ("b", "a")' in fresh_db["t"].schema diff --git a/tests/test_list_mode.py b/tests/test_list_mode.py new file mode 100644 index 0000000..746c9c1 --- /dev/null +++ b/tests/test_list_mode.py @@ -0,0 +1,288 @@ +""" +Tests for list-based iteration in insert_all and upsert_all +""" + +import pytest +from sqlite_utils import Database + + +def test_insert_all_list_mode_basic(): + """Test basic insert_all with list-based iteration""" + db = Database(memory=True) + + def data_generator(): + # First yield column names + yield ["id", "name", "age"] + # Then yield data rows + yield [1, "Alice", 30] + yield [2, "Bob", 25] + yield [3, "Charlie", 35] + + db["people"].insert_all(data_generator()) + + rows = list(db["people"].rows) + assert len(rows) == 3 + assert rows[0] == {"id": 1, "name": "Alice", "age": 30} + assert rows[1] == {"id": 2, "name": "Bob", "age": 25} + assert rows[2] == {"id": 3, "name": "Charlie", "age": 35} + + +def test_insert_all_list_mode_with_pk(): + """Test insert_all with list mode and primary key""" + db = Database(memory=True) + + def data_generator(): + yield ["id", "name", "score"] + yield [1, "Alice", 95] + yield [2, "Bob", 87] + + db["scores"].insert_all(data_generator(), pk="id") + + assert db["scores"].pks == ["id"] + rows = list(db["scores"].rows) + assert len(rows) == 2 + + +def test_upsert_all_list_mode(): + """Test upsert_all with list-based iteration""" + db = Database(memory=True) + + # Initial insert + def initial_data(): + yield ["id", "name", "value"] + yield [1, "Alice", 100] + yield [2, "Bob", 200] + + db["data"].insert_all(initial_data(), pk="id") + + # Upsert with some updates and new records + def upsert_data(): + yield ["id", "name", "value"] + yield [1, "Alice", 150] # Update existing + yield [3, "Charlie", 300] # Insert new + + db["data"].upsert_all(upsert_data(), pk="id") + + rows = list(db["data"].rows_where(order_by="id")) + assert len(rows) == 3 + assert rows[0] == {"id": 1, "name": "Alice", "value": 150} + assert rows[1] == {"id": 2, "name": "Bob", "value": 200} + assert rows[2] == {"id": 3, "name": "Charlie", "value": 300} + + +def test_list_mode_with_various_types(): + """Test list mode with different data types""" + db = Database(memory=True) + + def data_generator(): + yield ["id", "name", "score", "active"] + yield [1, "Alice", 95.5, True] + yield [2, "Bob", 87.3, False] + yield [3, "Charlie", None, True] + + db["mixed"].insert_all(data_generator()) + + rows = list(db["mixed"].rows) + assert len(rows) == 3 + assert rows[0]["score"] == 95.5 + assert rows[1]["active"] == 0 # SQLite stores boolean as int + assert rows[2]["score"] is None + + +def test_list_mode_error_non_string_columns(): + """Test that non-string column names raise an error""" + db = Database(memory=True) + + def bad_data(): + yield [1, 2, 3] # Non-string column names + yield ["a", "b", "c"] + + with pytest.raises(ValueError, match="must be a list of column name strings"): + db["bad"].insert_all(bad_data()) + + +def test_list_mode_error_mixed_types(): + """Test that mixing list and dict raises an error""" + db = Database(memory=True) + + def bad_data(): + yield ["id", "name"] + yield {"id": 1, "name": "Alice"} # Should be a list, not dict + + with pytest.raises(ValueError, match="must also be lists"): + db["bad"].insert_all(bad_data()) + + +def test_list_mode_empty_after_headers(): + """Test that only headers without data works gracefully""" + db = Database(memory=True) + + def data_generator(): + yield ["id", "name", "age"] + # No data rows + + result = db["people"].insert_all(data_generator()) + assert result is not None + assert not db["people"].exists() + + +def test_list_mode_batch_processing(): + """Test list mode with large dataset requiring batching""" + db = Database(memory=True) + + def large_data(): + yield ["id", "value"] + for i in range(1000): + yield [i, f"value_{i}"] + + db["large"].insert_all(large_data(), batch_size=100) + + count = db.execute("SELECT COUNT(*) as c FROM large").fetchone()[0] + assert count == 1000 + + +def test_list_mode_shorter_rows(): + """Test that rows shorter than column list get NULL values""" + db = Database(memory=True) + + def data_generator(): + yield ["id", "name", "age", "city"] + yield [1, "Alice", 30, "NYC"] + yield [2, "Bob"] # Missing age and city + yield [3, "Charlie", 35] # Missing city + + db["people"].insert_all(data_generator()) + + rows = list(db["people"].rows_where(order_by="id")) + assert rows[0] == {"id": 1, "name": "Alice", "age": 30, "city": "NYC"} + assert rows[1] == {"id": 2, "name": "Bob", "age": None, "city": None} + assert rows[2] == {"id": 3, "name": "Charlie", "age": 35, "city": None} + + +def test_backwards_compatibility_dict_mode(): + """Ensure dict mode still works (backward compatibility)""" + db = Database(memory=True) + + # Traditional dict-based insert + data = [ + {"id": 1, "name": "Alice", "age": 30}, + {"id": 2, "name": "Bob", "age": 25}, + ] + + db["people"].insert_all(data) + + rows = list(db["people"].rows) + assert len(rows) == 2 + assert rows[0] == {"id": 1, "name": "Alice", "age": 30} + + +def test_insert_all_tuple_mode_basic(): + """Test basic insert_all with tuple-based iteration""" + db = Database(memory=True) + + def data_generator(): + # First yield column names as tuple + yield ("id", "name", "age") + # Then yield data rows as tuples + yield (1, "Alice", 30) + yield (2, "Bob", 25) + yield (3, "Charlie", 35) + + db["people"].insert_all(data_generator()) + + rows = list(db["people"].rows) + assert len(rows) == 3 + assert rows[0] == {"id": 1, "name": "Alice", "age": 30} + assert rows[1] == {"id": 2, "name": "Bob", "age": 25} + assert rows[2] == {"id": 3, "name": "Charlie", "age": 35} + + +def test_insert_all_mixed_list_tuple(): + """Test insert_all with mixed lists and tuples for data rows""" + db = Database(memory=True) + + def data_generator(): + # Column names as list + yield ["id", "name", "age"] + # Mix of list and tuple data rows + yield [1, "Alice", 30] + yield (2, "Bob", 25) + yield [3, "Charlie", 35] + yield (4, "Diana", 40) + + db["people"].insert_all(data_generator()) + + rows = list(db["people"].rows) + assert len(rows) == 4 + assert rows[0] == {"id": 1, "name": "Alice", "age": 30} + assert rows[1] == {"id": 2, "name": "Bob", "age": 25} + assert rows[2] == {"id": 3, "name": "Charlie", "age": 35} + assert rows[3] == {"id": 4, "name": "Diana", "age": 40} + + +def test_upsert_all_tuple_mode(): + """Test upsert_all with tuple-based iteration""" + db = Database(memory=True) + + # Initial insert with tuples + def initial_data(): + yield ("id", "name", "value") + yield (1, "Alice", 100) + yield (2, "Bob", 200) + + db["data"].insert_all(initial_data(), pk="id") + + # Upsert with tuples + def upsert_data(): + yield ("id", "name", "value") + yield (1, "Alice", 150) # Update existing + yield (3, "Charlie", 300) # Insert new + + db["data"].upsert_all(upsert_data(), pk="id") + + rows = list(db["data"].rows_where(order_by="id")) + assert len(rows) == 3 + assert rows[0] == {"id": 1, "name": "Alice", "value": 150} + assert rows[1] == {"id": 2, "name": "Bob", "value": 200} + assert rows[2] == {"id": 3, "name": "Charlie", "value": 300} + + +def test_tuple_mode_shorter_rows(): + """Test that tuple rows shorter than column list get NULL values""" + db = Database(memory=True) + + def data_generator(): + yield "id", "name", "age", "city" + yield 1, "Alice", 30, "NYC" + yield 2, "Bob" # Missing age and city + yield 3, "Charlie", 35 # Missing city + + db["people"].insert_all(data_generator()) + + rows = list(db["people"].rows_where(order_by="id")) + assert rows[0] == {"id": 1, "name": "Alice", "age": 30, "city": "NYC"} + assert rows[1] == {"id": 2, "name": "Bob", "age": None, "city": None} + assert rows[2] == {"id": 3, "name": "Charlie", "age": 35, "city": None} + + +def test_list_mode_single_record_upsert_last_pk(): + """Test that last_pk is populated correctly for single-record upserts in list mode""" + db = Database(memory=True) + + # Create table first + db["data"].insert({"id": 1, "name": "Alice", "value": 100}, pk="id") + + # Now upsert a single record using list mode + def upsert_data(): + yield ["id", "name", "value"] + yield [1, "Alice", 150] # Update existing + + table = db["data"] + table.upsert_all(upsert_data(), pk="id") + + # Verify the data was updated + rows = list(db["data"].rows) + assert rows == [{"id": 1, "name": "Alice", "value": 150}] + + # Verify last_pk is populated correctly + assert table.last_pk == 1 diff --git a/tests/test_lookup.py b/tests/test_lookup.py index 31be414..da4f18b 100644 --- a/tests/test_lookup.py +++ b/tests/test_lookup.py @@ -114,18 +114,18 @@ def test_lookup_with_extra_insert_parameters(fresh_db): columns={"make_this_integer": int}, ) assert species.schema == ( - "CREATE TABLE [species] (\n" - " [renamed_id] INTEGER PRIMARY KEY,\n" - " [this_at_front] INTEGER,\n" - " [name] TEXT,\n" - " [type] TEXT,\n" - " [first_seen] TEXT,\n" - " [make_not_null] INTEGER NOT NULL,\n" - " [fk_to_other] INTEGER REFERENCES [other_table]([id]),\n" - " [default_is_dog] TEXT DEFAULT 'dog',\n" - " [extract_this] INTEGER REFERENCES [extract_this]([id]),\n" - " [convert_to_upper] TEXT,\n" - " [make_this_integer] INTEGER\n" + 'CREATE TABLE "species" (\n' + ' "renamed_id" INTEGER PRIMARY KEY,\n' + ' "this_at_front" INTEGER,\n' + ' "name" TEXT,\n' + ' "type" TEXT,\n' + ' "first_seen" TEXT,\n' + ' "make_not_null" INTEGER NOT NULL,\n' + ' "fk_to_other" INTEGER REFERENCES "other_table"("id"),\n' + " \"default_is_dog\" TEXT DEFAULT 'dog',\n" + ' "extract_this" INTEGER REFERENCES "extract_this"("id"),\n' + ' "convert_to_upper" TEXT,\n' + ' "make_this_integer" INTEGER\n' ")" ) assert species.get(id) == { @@ -151,3 +151,33 @@ def test_lookup_with_extra_insert_parameters(fresh_db): columns=["name", "type"], ) ] + + +@pytest.mark.parametrize("strict", (False, True)) +def test_lookup_new_table_strict(fresh_db, strict): + fresh_db["species"].lookup({"name": "Palm"}, strict=strict) + assert fresh_db["species"].strict == strict or not fresh_db.supports_strict + + +def test_lookup_null_value_idempotent(fresh_db): + # https://github.com/simonw/sqlite-utils/issues/186 + # Repeated lookups of a null value should return the same row, + # not insert a duplicate row each time + species = fresh_db["species"] + first_id = species.lookup({"name": None}) + second_id = species.lookup({"name": None}) + assert first_id == second_id + assert list(species.rows) == [{"id": first_id, "name": None}] + + +def test_lookup_compound_key_with_null_idempotent(fresh_db): + species = fresh_db["species"] + palm_id = species.lookup({"name": "Palm", "type": None}) + oak_id = species.lookup({"name": "Oak", "type": "Tree"}) + assert palm_id == species.lookup({"name": "Palm", "type": None}) + assert oak_id == species.lookup({"name": "Oak", "type": "Tree"}) + assert palm_id != oak_id + assert list(species.rows) == [ + {"id": palm_id, "name": "Palm", "type": None}, + {"id": oak_id, "name": "Oak", "type": "Tree"}, + ] diff --git a/tests/test_m2m.py b/tests/test_m2m.py index 2cb2ca3..d613bb9 100644 --- a/tests/test_m2m.py +++ b/tests/test_m2m.py @@ -139,9 +139,9 @@ def test_m2m_lookup(fresh_db): def test_m2m_requires_either_records_or_lookup(fresh_db): people = fresh_db.table("people", pk="id").insert({"name": "Wahyu"}) - with pytest.raises(AssertionError): + with pytest.raises(ValueError): people.m2m("tags") - with pytest.raises(AssertionError): + with pytest.raises(ValueError): people.m2m("tags", {"tag": "hello"}, lookup={"foo": "bar"}) diff --git a/tests/test_migrations.py b/tests/test_migrations.py new file mode 100644 index 0000000..04185fc --- /dev/null +++ b/tests/test_migrations.py @@ -0,0 +1,246 @@ +import pytest +import sqlite_utils +from sqlite_utils import Migrations + + +@pytest.fixture +def migrations(): + migrations = Migrations("test") + + @migrations() + def m001(db): + db["dogs"].insert({"name": "Cleo"}) + + @migrations() + def m002(db): + db["cats"].create({"name": str}) + db.execute("insert into dogs (name) values ('Pancakes')") + + return migrations + + +@pytest.fixture +def migrations_not_ordered_alphabetically(): + # Names order alphabetically in the wrong direction but this + # should still be applied correctly. + migrations = Migrations("test") + + @migrations() + def m002(db): + db["dogs"].insert({"name": "Cleo"}) + + @migrations() + def m001(db): + db["cats"].create({"name": str}) + db.execute("insert into dogs (name) values ('Pancakes')") + + return migrations + + +@pytest.fixture +def migrations2(): + migrations = Migrations("test2") + + @migrations() + def m001(db): + db["dogs2"].insert({"name": "Cleo"}) + + return migrations + + +def test_basic(migrations): + db = sqlite_utils.Database(memory=True) + assert db.table_names() == [] + migrations.apply(db) + assert set(db.table_names()) == {"_sqlite_migrations", "dogs", "cats"} + + +def test_stop_before(migrations): + db = sqlite_utils.Database(memory=True) + assert db.table_names() == [] + migrations.apply(db, stop_before="m002") + assert set(db.table_names()) == {"_sqlite_migrations", "dogs"} + migrations.apply(db) + assert set(db.table_names()) == {"_sqlite_migrations", "dogs", "cats"} + + +def test_two_migration_sets(migrations, migrations2): + db = sqlite_utils.Database(memory=True) + assert db.table_names() == [] + migrations.apply(db) + migrations2.apply(db) + assert set(db.table_names()) == {"_sqlite_migrations", "dogs", "cats", "dogs2"} + + +def test_order_does_not_matter(migrations, migrations_not_ordered_alphabetically): + db1 = sqlite_utils.Database(memory=True) + db2 = sqlite_utils.Database(memory=True) + migrations.apply(db1) + migrations_not_ordered_alphabetically.apply(db2) + assert db1.schema == db2.schema + + +def test_applied_at_is_a_string(migrations): + db = sqlite_utils.Database(memory=True) + migrations.apply(db) + applied = migrations.applied(db) + assert len(applied) == 2 + for migration in applied: + # applied_at is the TEXT timestamp straight from the + # _sqlite_migrations table, e.g. "2026-07-04 12:00:00.000000+00:00" + assert isinstance(migration.applied_at, str) + assert migration.applied_at.endswith("+00:00") + + +def test_failing_migration_rolls_back(migrations): + @migrations() + def m003(db): + db["birds"].create({"name": str}) + db.execute("insert into dogs (name) values ('Dozer')") + raise ValueError("boom") + + db = sqlite_utils.Database(memory=True) + with pytest.raises(ValueError): + migrations.apply(db) + # m001 and m002 committed before the failure and stay applied + assert set(db.table_names()) == {"_sqlite_migrations", "dogs", "cats"} + assert [r["name"] for r in db["dogs"].rows] == ["Cleo", "Pancakes"] + assert [m.name for m in migrations.applied(db)] == ["m001", "m002"] + # Everything m003 did was rolled back and it is still pending + assert [m.name for m in migrations.pending(db)] == ["m003"] + + +def test_rerun_after_failure_applies_each_migration_once(): + state = {"fail": True} + migrations = Migrations("test") + + @migrations() + def m001(db): + db["dogs"].insert({"name": "Cleo"}) + + @migrations() + def m002(db): + db["dogs"].insert({"name": "Pancakes"}) + if state["fail"]: + raise ValueError("boom") + + db = sqlite_utils.Database(memory=True) + with pytest.raises(ValueError): + migrations.apply(db) + state["fail"] = False + migrations.apply(db) + # m001 must not have been re-applied, m002 applied exactly once + assert [r["name"] for r in db["dogs"].rows] == ["Cleo", "Pancakes"] + assert [m.name for m in migrations.applied(db)] == ["m001", "m002"] + + +def test_non_transactional_migration_allows_vacuum(tmpdir): + path = str(tmpdir / "test.db") + db = sqlite_utils.Database(path) + migrations = Migrations("test") + + @migrations() + def m001(db): + db["dogs"].insert({"name": "Cleo"}) + + @migrations(transactional=False) + def m002(db): + db.execute("VACUUM") + + migrations.apply(db) + assert [m.name for m in migrations.applied(db)] == ["m001", "m002"] + db.close() + + +def test_apply_composes_inside_outer_transaction(migrations): + db = sqlite_utils.Database(memory=True) + with pytest.raises(ZeroDivisionError): + with db.atomic(): + migrations.apply(db) + raise ZeroDivisionError + # The outer transaction rolled back, taking the migrations with it + assert db.table_names() == [] + + +@pytest.mark.parametrize( + "create_table,pk", + ( + ( + { + "migration_set": str, + "name": str, + "applied_at": str, + }, + "name", + ), + ( + { + "migration_set": str, + "name": str, + "applied_at": str, + }, + ("migration_set", "name"), + ), + ), +) +def test_upgrades_sqlite_migrations(migrations, create_table, pk): + db = sqlite_utils.Database(memory=True) + db["_sqlite_migrations"].create(create_table, pk=pk) + assert db.table_names() == ["_sqlite_migrations"] + assert db["_sqlite_migrations"].pks == ([pk] if isinstance(pk, str) else list(pk)) + migrations.apply(db) + assert db["_sqlite_migrations"].pks == ["id"] + + +def test_pending_and_applied_are_read_only(migrations): + db = sqlite_utils.Database(memory=True) + assert [m.name for m in migrations.pending(db)] == ["m001", "m002"] + assert migrations.applied(db) == [] + # Neither call should have created the tracking table + assert db.table_names() == [] + + +def test_duplicate_migration_name_errors(): + migrations = Migrations("test") + + @migrations() + def m001(db): + pass + + with pytest.raises(ValueError) as ex: + + @migrations(name="m001") + def m001_again(db): + pass + + assert "m001" in str(ex.value) + + +def test_stop_before_applied_migration_errors(migrations): + # Stopping before a migration that has already been applied is + # impossible to honor - previously the stop name was only checked + # against pending migrations, so everything after it was applied + db = sqlite_utils.Database(memory=True) + migrations.apply(db, stop_before="m002") # applies m001 only + with pytest.raises(ValueError) as ex: + migrations.apply(db, stop_before="m001") + assert "m001" in str(ex.value) + assert "already been applied" in str(ex.value) + # Nothing else was applied + assert not db["cats"].exists() + + +def test_stop_before_applied_migration_errors_before_any_apply(migrations): + # The error fires before any pending migration runs, even those that + # come before the already-applied stop target in registration order + db = sqlite_utils.Database(memory=True) + only_second = Migrations("test") + + @only_second() + def m002(db): + db["cats"].create({"name": str}) + + only_second.apply(db) # m002 applied, m001 still pending + with pytest.raises(ValueError): + migrations.apply(db, stop_before="m002") + assert not db["dogs"].exists() diff --git a/tests/test_plugins.py b/tests/test_plugins.py index e82ed31..c793e32 100644 --- a/tests/test_plugins.py +++ b/tests/test_plugins.py @@ -1,9 +1,52 @@ from click.testing import CliRunner import click import importlib +import pytest +import sys from sqlite_utils import cli, Database, hookimpl, plugins +def _supports_pragma_function_list(): + db = Database(memory=True) + try: + db.execute("select * from pragma_function_list()") + return True + except Exception: + return False + finally: + db.close() + + +def test_get_plugins_loads_setuptools_entrypoints_once(monkeypatch): + calls = [] + monkeypatch.delattr(sys, "_called_from_test", raising=False) + monkeypatch.setattr(plugins, "_plugins_loaded", False) + monkeypatch.setattr( + plugins.pm, + "load_setuptools_entrypoints", + lambda group: calls.append(group) or 0, + ) + + plugins.get_plugins() + plugins.get_plugins() + + assert calls == ["sqlite_utils"] + + +def test_get_plugins_does_not_load_setuptools_entrypoints_in_tests(monkeypatch): + calls = [] + monkeypatch.setattr(sys, "_called_from_test", True, raising=False) + monkeypatch.setattr(plugins, "_plugins_loaded", False) + monkeypatch.setattr( + plugins.pm, + "load_setuptools_entrypoints", + lambda group: calls.append(group) or 0, + ) + + assert plugins.get_plugins() == [] + assert calls == [] + + def test_register_commands(): importlib.reload(cli) assert plugins.get_plugins() == [] @@ -37,6 +80,10 @@ def test_register_commands(): assert plugins.get_plugins() == [] +@pytest.mark.skipif( + not _supports_pragma_function_list(), + reason="Needs SQLite version that supports pragma_function_list()", +) def test_prepare_connection(): importlib.reload(cli) assert plugins.get_plugins() == [] @@ -54,7 +101,7 @@ def test_prepare_connection(): return [ row[0] for row in db.execute( - "select distinct name from pragma_function_list order by 1" + "select distinct name from pragma_function_list() order by 1" ).fetchall() ] diff --git a/tests/test_query.py b/tests/test_query.py index fe79cc0..06847da 100644 --- a/tests/test_query.py +++ b/tests/test_query.py @@ -1,5 +1,8 @@ +import pytest import types +from sqlite_utils.utils import sqlite3 + def test_query(fresh_db): fresh_db["dogs"].insert_all([{"name": "Cleo"}, {"name": "Pancakes"}]) @@ -8,6 +11,268 @@ def test_query(fresh_db): assert list(results) == [{"name": "Pancakes"}, {"name": "Cleo"}] +def test_query_executes_eagerly(fresh_db): + # The SQL runs when query() is called, not when the result is iterated, + # so errors are raised at the call site + with pytest.raises(sqlite3.OperationalError): + fresh_db.query("select * from missing_table") + + +def test_query_rejects_statements_that_return_no_rows(fresh_db): + fresh_db["dogs"].insert({"name": "Cleo"}) + with pytest.raises(ValueError) as ex: + fresh_db.query("update dogs set name = 'Cleopaws'") + assert "execute()" in str(ex.value) + # The rejected update was rolled back, and no transaction is left open + assert not fresh_db.conn.in_transaction + assert [row["name"] for row in fresh_db["dogs"].rows] == ["Cleo"] + + +def test_query_rejected_ddl_is_rolled_back(fresh_db): + with pytest.raises(ValueError): + fresh_db.query("create table dogs (id integer primary key)") + assert not fresh_db.conn.in_transaction + assert fresh_db.table_names() == [] + + +def test_query_rejected_write_inside_transaction_is_rolled_back(fresh_db): + fresh_db["dogs"].insert({"name": "Cleo"}) + fresh_db.begin() + fresh_db.execute("insert into dogs (name) values ('Pancakes')") + with pytest.raises(ValueError): + fresh_db.query("update dogs set name = 'Cleopaws'") + # The transaction is still open and the earlier insert is intact + assert fresh_db.conn.in_transaction + fresh_db.commit() + assert [row["name"] for row in fresh_db["dogs"].rows] == ["Cleo", "Pancakes"] + + +@pytest.mark.parametrize( + "sql", + [ + "begin", + "commit", + "rollback", + "vacuum", + "detach database foo", + "/* comment */ commit", + "-- comment\nbegin", + "/* multi\nline */ -- and another\n vacuum", + "\t /* a */ /* b */ savepoint s1", + "; commit", + ";;\n ; rollback", + "; /* comment */ vacuum", + "\ufeffbegin", + ], +) +def test_query_rejects_transaction_control_and_vacuum(fresh_db, sql): + with pytest.raises(ValueError) as ex: + fresh_db.query(sql) + assert "execute()" in str(ex.value) + assert not fresh_db.conn.in_transaction + + +def test_query_comment_prefixed_commit_does_not_commit_transaction(fresh_db): + # A COMMIT hidden behind a leading comment must not slip past the + # keyword check - previously it committed the caller's open + # transaction before the ValueError was raised + fresh_db["dogs"].insert({"name": "Cleo"}) + fresh_db.begin() + fresh_db.execute("insert into dogs (name) values ('Pancakes')") + with pytest.raises(ValueError): + fresh_db.query("/* comment */ COMMIT") + # The explicit transaction is still open and can still be rolled back + assert fresh_db.conn.in_transaction + fresh_db.rollback() + assert [row["name"] for row in fresh_db["dogs"].rows] == ["Cleo"] + + +@pytest.mark.parametrize("sql", ["; COMMIT", "\ufeffCOMMIT"]) +def test_query_prefixed_commit_does_not_commit_transaction(fresh_db, sql): + # sqlite3 tolerates empty statements and a UTF-8 BOM before the first + # real token, so the keyword scanner must skip them too - previously + # '; COMMIT' slipped past the check and committed the caller's open + # transaction before raising OperationalError + fresh_db["dogs"].insert({"name": "Cleo"}) + fresh_db.begin() + fresh_db.execute("insert into dogs (name) values ('Pancakes')") + with pytest.raises(ValueError): + fresh_db.query(sql) + # The explicit transaction is still open and can still be rolled back + assert fresh_db.conn.in_transaction + fresh_db.rollback() + assert [row["name"] for row in fresh_db["dogs"].rows] == ["Cleo"] + + +def test_query_error_leaves_no_transaction_open(fresh_db): + with pytest.raises(sqlite3.OperationalError): + fresh_db.query("select * from missing_table") + assert not fresh_db.conn.in_transaction + + +def test_query_pragma(tmpdir): + from sqlite_utils import Database + + db = Database(str(tmpdir / "test.db")) + # A row-returning PRAGMA works, including one that cannot run in a transaction + assert list(db.query("pragma journal_mode = wal")) == [{"journal_mode": "wal"}] + # A PRAGMA that returns no rows raises ValueError + with pytest.raises(ValueError): + db.query("pragma user_version = 5") + db.close() + + +def test_query_rejected_pragma_still_takes_effect(fresh_db): + # Documented limitation: PRAGMAs run outside the savepoint guard, + # because some of them refuse to run inside a transaction - so a + # row-less PRAGMA takes effect even though it raises ValueError. + # If this test starts failing because the pragma was rolled back, + # the limitation has been fixed - update the docs in python-api.rst + # and the query() docstring to remove the carve-out + with pytest.raises(ValueError): + fresh_db.query("pragma user_version = 5") + assert fresh_db.execute("pragma user_version").fetchone()[0] == 5 + + +def test_query_comment_prefixed_pragma(tmpdir): + from sqlite_utils import Database + + db = Database(str(tmpdir / "test.db")) + # A leading comment must not stop a PRAGMA being recognized as one - + # previously it was executed inside the savepoint guard, where + # journal mode changes are refused + assert list(db.query("-- set WAL mode\npragma journal_mode = wal")) == [ + {"journal_mode": "wal"} + ] + db.close() + + +def test_query_comment_prefixed_pragma_inside_transaction(fresh_db): + fresh_db.begin() + assert list(fresh_db.query("-- check version\npragma user_version")) == [ + {"user_version": 0} + ] + assert fresh_db.conn.in_transaction + fresh_db.rollback() + + +@pytest.mark.parametrize( + "sql,expected", + [ + ("select 1", "SELECT"), + (" \t\n select 1", "SELECT"), + ("-- comment\nbegin", "BEGIN"), + ("/* one */ /* two */ pragma user_version", "PRAGMA"), + ("/* multi\nline */vacuum", "VACUUM"), + ("insert into t values (1)", "INSERT"), + ("-- only a comment", ""), + ("/* unterminated", ""), + ("", ""), + (" ", ""), + ("123", ""), + ("; commit", "COMMIT"), + (";;\n ; rollback", "ROLLBACK"), + ("; -- comment\n begin", "BEGIN"), + ("\ufeffcommit", "COMMIT"), + ("\ufeff ; select 1", "SELECT"), + (";", ""), + ], +) +def test_first_keyword(sql, expected): + from sqlite_utils.db import _first_keyword + + assert _first_keyword(sql) == expected + + +@pytest.mark.skipif( + sqlite3.sqlite_version_info < (3, 35, 0), + reason="RETURNING requires SQLite 3.35.0 or higher", +) +def test_query_insert_returning(fresh_db): + fresh_db["dogs"].insert({"name": "Cleo"}) + rows = list( + fresh_db.query("insert into dogs (name) values ('Pancakes') returning name") + ) + assert rows == [{"name": "Pancakes"}] + assert fresh_db["dogs"].count == 2 + + +@pytest.mark.skipif( + sqlite3.sqlite_version_info < (3, 35, 0), + reason="RETURNING requires SQLite 3.35.0 or higher", +) +def test_query_insert_returning_commits_without_iteration(tmpdir): + from sqlite_utils import Database + + path = str(tmpdir / "test.db") + db = Database(path) + db["dogs"].insert({"name": "Cleo"}) + # Never iterate over the results + db.query("insert into dogs (name) values ('Pancakes') returning name") + assert not db.conn.in_transaction + # A completely separate connection sees the new row straight away + other = sqlite3.connect(path) + assert other.execute("select count(*) from dogs").fetchone()[0] == 2 + other.close() + db.close() + + +@pytest.mark.skipif( + sqlite3.sqlite_version_info < (3, 35, 0), + reason="RETURNING requires SQLite 3.35.0 or higher", +) +def test_query_insert_returning_partial_iteration_still_commits(tmpdir): + from sqlite_utils import Database + + path = str(tmpdir / "test.db") + db = Database(path) + db["dogs"].insert({"name": "Cleo"}) + row = next( + db.query( + "insert into dogs (name) values ('Pancakes'), ('Marnie') returning name" + ) + ) + assert row == {"name": "Pancakes"} + assert not db.conn.in_transaction + other = sqlite3.connect(path) + assert other.execute("select count(*) from dogs").fetchone()[0] == 3 + other.close() + db.close() + + +@pytest.mark.skipif( + sqlite3.sqlite_version_info < (3, 35, 0), + reason="RETURNING requires SQLite 3.35.0 or higher", +) +def test_query_insert_returning_respects_explicit_transaction(fresh_db): + fresh_db["dogs"].insert({"name": "Cleo"}) + fresh_db.begin() + rows = list( + fresh_db.query("insert into dogs (name) values ('Pancakes') returning name") + ) + assert rows == [{"name": "Pancakes"}] + # Still inside the explicit transaction - not committed + assert fresh_db.conn.in_transaction + fresh_db.rollback() + assert [row["name"] for row in fresh_db["dogs"].rows] == ["Cleo"] + + +def test_query_duplicate_column_names_are_deduped(fresh_db): + # https://github.com/simonw/sqlite-utils/issues/624 + fresh_db["one"].insert({"id": 1, "value": "left"}) + fresh_db["two"].insert({"id": 2, "value": "right"}) + rows = list( + fresh_db.query("select one.id, two.id, one.value, two.value from one, two") + ) + assert rows == [{"id": 1, "id_2": 2, "value": "left", "value_2": "right"}] + + +def test_query_deduped_column_avoids_existing_names(fresh_db): + # The renamed duplicate must not overwrite a real column called id_2 + rows = list(fresh_db.query("select 1 as id, 2 as id, 3 as id_2")) + assert rows == [{"id": 1, "id_3": 2, "id_2": 3}] + + def test_execute_returning_dicts(fresh_db): # Like db.query() but returns a list, included for backwards compatibility # see https://github.com/simonw/sqlite-utils/issues/290 @@ -15,3 +280,24 @@ def test_execute_returning_dicts(fresh_db): assert fresh_db.execute_returning_dicts("select * from test") == [ {"id": 1, "bar": 2} ] + + +@pytest.mark.skipif( + sqlite3.sqlite_version_info < (3, 35, 0), + reason="RETURNING requires SQLite 3.35.0 or higher", +) +def test_query_preserves_error_from_transaction_destroying_trigger(fresh_db): + # RAISE(ROLLBACK) destroys the savepoint guard - the original + # IntegrityError must propagate, not "no such savepoint" + fresh_db.execute("create table t (id integer primary key, v text)") + fresh_db.execute(""" + create trigger no_bad before insert on t + when new.v = 'bad' + begin + select raise(rollback, 'trigger says no'); + end + """) + with pytest.raises(sqlite3.IntegrityError, match="trigger says no"): + fresh_db.query("insert into t (id, v) values (1, 'bad') returning id") + assert not fresh_db.conn.in_transaction + assert fresh_db.execute("select count(*) from t").fetchone()[0] == 0 diff --git a/tests/test_recipes.py b/tests/test_recipes.py index eca3987..a7c7ef7 100644 --- a/tests/test_recipes.py +++ b/tests/test_recipes.py @@ -62,26 +62,37 @@ def test_dayfirst_yearfirst(fresh_db, recipe, kwargs, expected): ] +@pytest.mark.filterwarnings("ignore::pytest.PytestUnraisableExceptionWarning") @pytest.mark.parametrize("fn", ("parsedate", "parsedatetime")) -@pytest.mark.parametrize("errors", (None, recipes.SET_NULL, recipes.IGNORE)) -def test_dateparse_errors(fresh_db, fn, errors): +def test_dateparse_errors_raises(fresh_db, fn): + """Test that invalid dates raise errors when errors=None""" fresh_db["example"].insert_all( [ {"id": 1, "dt": "invalid"}, ], pk="id", ) - if errors is None: - # Should raise an error - with pytest.raises(sqlite3.OperationalError): - fresh_db["example"].convert("dt", lambda value: getattr(recipes, fn)(value)) - else: - fresh_db["example"].convert( - "dt", lambda value: getattr(recipes, fn)(value, errors=errors) - ) - rows = list(fresh_db["example"].rows) - expected = [{"id": 1, "dt": None if errors is recipes.SET_NULL else "invalid"}] - assert rows == expected + # Exception in SQLite callback surfaces as OperationalError + with pytest.raises(sqlite3.OperationalError): + fresh_db["example"].convert("dt", lambda value: getattr(recipes, fn)(value)) + + +@pytest.mark.parametrize("fn", ("parsedate", "parsedatetime")) +@pytest.mark.parametrize("errors", (recipes.SET_NULL, recipes.IGNORE)) +def test_dateparse_errors_handled(fresh_db, fn, errors): + """Test error handling modes for invalid dates""" + fresh_db["example"].insert_all( + [ + {"id": 1, "dt": "invalid"}, + ], + pk="id", + ) + fresh_db["example"].convert( + "dt", lambda value: getattr(recipes, fn)(value, errors=errors) + ) + rows = list(fresh_db["example"].rows) + expected = [{"id": 1, "dt": None if errors is recipes.SET_NULL else "invalid"}] + assert rows == expected @pytest.mark.parametrize("delimiter", [None, ";", "-"]) diff --git a/tests/test_recreate.py b/tests/test_recreate.py index 49dba2b..bce53d5 100644 --- a/tests/test_recreate.py +++ b/tests/test_recreate.py @@ -14,8 +14,11 @@ def test_recreate_ignored_for_in_memory(): def test_recreate_not_allowed_for_connection(): conn = sqlite3.connect(":memory:") - with pytest.raises(AssertionError): - Database(conn, recreate=True) + try: + with pytest.raises(ValueError): + Database(conn, recreate=True) + finally: + conn.close() @pytest.mark.parametrize( diff --git a/tests/test_register_function.py b/tests/test_register_function.py index e2591f4..618bf1e 100644 --- a/tests/test_register_function.py +++ b/tests/test_register_function.py @@ -42,39 +42,46 @@ def test_register_function_deterministic(fresh_db): def test_register_function_deterministic_tries_again_if_exception_raised(fresh_db): + # Save the original connection so we can close it later + original_conn = fresh_db.conn fresh_db.conn = MagicMock() fresh_db.conn.create_function = MagicMock() - @fresh_db.register_function(deterministic=True) - def to_lower_2(s): - return s.lower() + try: - fresh_db.conn.create_function.assert_called_with( - "to_lower_2", 1, to_lower_2, deterministic=True - ) + @fresh_db.register_function(deterministic=True) + def to_lower_2(s): + return s.lower() - first = True + fresh_db.conn.create_function.assert_called_with( + "to_lower_2", 1, to_lower_2, deterministic=True + ) - def side_effect(*args, **kwargs): - # Raise exception only first time this is called - nonlocal first - if first: - first = False - raise sqlite3.NotSupportedError() + first = True - # But if sqlite3.NotSupportedError is raised, it tries again - fresh_db.conn.create_function.reset_mock() - fresh_db.conn.create_function.side_effect = side_effect + def side_effect(*args, **kwargs): + # Raise exception only first time this is called + nonlocal first + if first: + first = False + raise sqlite3.NotSupportedError() - @fresh_db.register_function(deterministic=True) - def to_lower_3(s): - return s.lower() + # But if sqlite3.NotSupportedError is raised, it tries again + fresh_db.conn.create_function.reset_mock() + fresh_db.conn.create_function.side_effect = side_effect - # Should have been called once with deterministic=True and once without - assert fresh_db.conn.create_function.call_args_list == [ - call("to_lower_3", 1, to_lower_3, deterministic=True), - call("to_lower_3", 1, to_lower_3), - ] + @fresh_db.register_function(deterministic=True) + def to_lower_3(s): + return s.lower() + + # Should have been called once with deterministic=True and once without + assert fresh_db.conn.create_function.call_args_list == [ + call("to_lower_3", 1, to_lower_3, deterministic=True), + call("to_lower_3", 1, to_lower_3), + ] + finally: + # Close the original connection that was replaced with the mock + original_conn.close() def test_register_function_replace(fresh_db): diff --git a/tests/test_rows.py b/tests/test_rows.py index a8a4ca0..46d4f53 100644 --- a/tests/test_rows.py +++ b/tests/test_rows.py @@ -104,3 +104,37 @@ def test_pks_and_rows_where_compound_pk(fresh_db): (("number", 1), {"type": "number", "number": 1, "plusone": 2}), (("number", 2), {"type": "number", "number": 2, "plusone": 3}), ] + + +def test_rows_where_duplicate_select_columns_are_deduped(fresh_db): + # https://github.com/simonw/sqlite-utils/issues/624 + fresh_db["t"].insert({"id": 1, "name": "Cleo"}) + rows = list(fresh_db["t"].rows_where(select="id, id, name")) + assert rows == [{"id": 1, "id_2": 1, "name": "Cleo"}] + + +def test_pks_and_rows_where_view(fresh_db): + # pks_and_rows_where() lives on Queryable so views expose it, but + # SQLite views have no rowid. Modern SQLite (3.36+) raises an + # OperationalError from the generated SQL; older versions returned + # NULL for a view's rowid. Either way it must not fail earlier with + # an AttributeError from View lacking Table-only properties + from sqlite_utils.utils import sqlite3 + + fresh_db["dogs"].insert({"id": 1, "name": "Cleo"}, pk="id") + fresh_db.create_view("dog_names", "select name from dogs") + try: + result = list(fresh_db["dog_names"].pks_and_rows_where()) + except sqlite3.OperationalError: + pass # SQLite 3.36+: no such column: rowid + else: + # Older SQLite returns NULL rowids for views + assert result == [(None, {"rowid": None, "name": "Cleo"})] + + +def test_pks_and_rows_where_compound_pk_declaration_order(fresh_db): + # Compound pks are returned in PRIMARY KEY declaration order + fresh_db.execute("create table t (b text, a text, primary key (a, b))") + fresh_db["t"].insert({"a": "A", "b": "B"}) + pks_and_rows = list(fresh_db["t"].pks_and_rows_where()) + assert pks_and_rows == [(("A", "B"), {"b": "B", "a": "A"})] diff --git a/tests/test_rows_from_file.py b/tests/test_rows_from_file.py index 5316b86..a19fed6 100644 --- a/tests/test_rows_from_file.py +++ b/tests/test_rows_from_file.py @@ -48,7 +48,7 @@ def test_rows_from_file_extra_fields_strategies(ignore_extras, extras_key, expec def test_rows_from_file_error_on_string_io(): with pytest.raises(TypeError) as ex: - rows_from_file(StringIO("id,name\r\n1,Cleo")) + rows_from_file(StringIO("id,name\r\n1,Cleo")) # type: ignore[arg-type] assert ex.value.args == ( "rows_from_file() requires a file-like object that supports peek(), such as io.BytesIO", ) diff --git a/tests/test_sniff.py b/tests/test_sniff.py index 36cc471..4bbdb66 100644 --- a/tests/test_sniff.py +++ b/tests/test_sniff.py @@ -6,13 +6,13 @@ import pytest sniff_dir = pathlib.Path(__file__).parent / "sniff" -@pytest.mark.parametrize("filepath", sniff_dir.glob("example*")) +@pytest.mark.parametrize("filepath", sorted(sniff_dir.glob("example*"))) def test_sniff(tmpdir, filepath): db_path = str(tmpdir / "test.db") runner = CliRunner() result = runner.invoke( cli.cli, - ["insert", db_path, "creatures", str(filepath), "--sniff"], + ["insert", db_path, "creatures", str(filepath), "--sniff", "--no-detect-types"], catch_exceptions=False, ) assert result.exit_code == 0, result.stdout diff --git a/tests/test_tracer.py b/tests/test_tracer.py index 26318ae..d14697d 100644 --- a/tests/test_tracer.py +++ b/tests/test_tracer.py @@ -6,29 +6,29 @@ def test_tracer(): db = Database( memory=True, tracer=lambda sql, params: collected.append((sql, params)) ) - db["dogs"].insert({"name": "Cleopaws"}) - db["dogs"].enable_fts(["name"]) - db["dogs"].search("Cleopaws") + dogs = db.table("dogs") + dogs.insert({"name": "Cleopaws"}) + dogs.enable_fts(["name"]) + dogs.search("Cleopaws") assert collected == [ ("PRAGMA recursive_triggers=on;", None), ("select name from sqlite_master where type = 'view'", None), ("select name from sqlite_master where type = 'table'", None), ("select name from sqlite_master where type = 'view'", None), + ("select name from sqlite_master where type = 'view'", None), ("select name from sqlite_master where type = 'table'", None), ("select name from sqlite_master where type = 'view'", None), - ("CREATE TABLE [dogs] (\n [name] TEXT\n);\n ", None), - ("select name from sqlite_master where type = 'view'", None), - ("INSERT INTO [dogs] ([name]) VALUES (?);", ["Cleopaws"]), + ('CREATE TABLE "dogs" (\n "name" TEXT\n);\n ', None), ("select name from sqlite_master where type = 'view'", None), + ('INSERT INTO "dogs" ("name") VALUES (?)', ["Cleopaws"]), ( - "CREATE VIRTUAL TABLE [dogs_fts] USING FTS5 (\n [name],\n content=[dogs]\n)", + 'CREATE VIRTUAL TABLE "dogs_fts" USING FTS5 (\n "name",\n content="dogs"\n)', None, ), ( - "INSERT INTO [dogs_fts] (rowid, [name])\n SELECT rowid, [name] FROM [dogs];", + 'INSERT INTO "dogs_fts" (rowid, "name")\n SELECT rowid, "name" FROM "dogs";', None, ), - ("select name from sqlite_master where type = 'view'", None), ] @@ -40,60 +40,57 @@ def test_with_tracer(): db = Database(memory=True) - db["dogs"].insert({"name": "Cleopaws"}) - db["dogs"].enable_fts(["name"]) + dogs = db.table("dogs") + + dogs.insert({"name": "Cleopaws"}) + dogs.enable_fts(["name"]) assert len(collected) == 0 with db.tracer(tracer): - list(db["dogs"].search("Cleopaws")) + list(dogs.search("Cleopaws")) - assert len(collected) == 5 + assert len(collected) == 4 assert collected == [ - ("select name from sqlite_master where type = 'view'", None), ( - ( - "SELECT name FROM sqlite_master\n" - " WHERE rootpage = 0\n" - " AND (\n" - " sql LIKE :like\n" - " OR sql LIKE :like2\n" - " OR (\n" - " tbl_name = :table\n" - " AND sql LIKE '%VIRTUAL TABLE%USING FTS%'\n" - " )\n" - " )", - { - "like": "%VIRTUAL TABLE%USING FTS%content=[dogs]%", - "like2": '%VIRTUAL TABLE%USING FTS%content="dogs"%', - "table": "dogs", - }, - ) + "SELECT name FROM sqlite_master\n" + " WHERE rootpage = 0\n" + " AND (\n" + " sql LIKE :like\n" + " OR sql LIKE :like2\n" + " OR (\n" + " tbl_name = :table\n" + " AND sql LIKE '%VIRTUAL TABLE%USING FTS%'\n" + " )\n" + " )", + { + "like": "%VIRTUAL TABLE%USING FTS%content=[dogs]%", + "like2": '%VIRTUAL TABLE%USING FTS%content="dogs"%', + "table": "dogs", + }, ), ("select name from sqlite_master where type = 'view'", None), ("select sql from sqlite_master where name = ?", ("dogs_fts",)), ( - ( - "with original as (\n" - " select\n" - " rowid,\n" - " *\n" - " from [dogs]\n" - ")\n" - "select\n" - " [original].*\n" - "from\n" - " [original]\n" - " join [dogs_fts] on [original].rowid = [dogs_fts].rowid\n" - "where\n" - " [dogs_fts] match :query\n" - "order by\n" - " [dogs_fts].rank" - ), + 'with "original" as (\n' + " select\n" + " rowid,\n" + " *\n" + ' from "dogs"\n' + ")\n" + "select\n" + ' "original".*\n' + "from\n" + ' "original"\n' + ' join "dogs_fts" on "original".rowid = "dogs_fts".rowid\n' + "where\n" + ' "dogs_fts" match :query\n' + "order by\n" + ' "dogs_fts".rank', {"query": "Cleopaws"}, ), ] # Outside the with block collected should not be appended to - db["dogs"].insert({"name": "Cleopaws"}) - assert len(collected) == 5 + dogs.insert({"name": "Cleopaws"}) + assert len(collected) == 4 diff --git a/tests/test_transform.py b/tests/test_transform.py index 1894494..362f1ca 100644 --- a/tests/test_transform.py +++ b/tests/test_transform.py @@ -1,4 +1,6 @@ -from sqlite_utils.db import ForeignKey +import sqlite3 + +from sqlite_utils.db import ForeignKey, TransactionError, TransformError from sqlite_utils.utils import OperationalError import pytest @@ -10,90 +12,90 @@ import pytest ( {}, [ - "CREATE TABLE [dogs_new_suffix] (\n [id] INTEGER PRIMARY KEY,\n [name] TEXT,\n [age] TEXT\n);", - "INSERT INTO [dogs_new_suffix] ([rowid], [id], [name], [age])\n SELECT [rowid], [id], [name], [age] FROM [dogs];", - "DROP TABLE [dogs];", - "ALTER TABLE [dogs_new_suffix] RENAME TO [dogs];", + 'CREATE TABLE "dogs_new_suffix" (\n "id" INTEGER PRIMARY KEY,\n "name" TEXT,\n "age" TEXT\n);', + 'INSERT INTO "dogs_new_suffix" ("rowid", "id", "name", "age")\n SELECT "rowid", "id", "name", "age" FROM "dogs";', + 'DROP TABLE "dogs";', + 'ALTER TABLE "dogs_new_suffix" RENAME TO "dogs";', ], ), # Change column type ( {"types": {"age": int}}, [ - "CREATE TABLE [dogs_new_suffix] (\n [id] INTEGER PRIMARY KEY,\n [name] TEXT,\n [age] INTEGER\n);", - "INSERT INTO [dogs_new_suffix] ([rowid], [id], [name], [age])\n SELECT [rowid], [id], [name], [age] FROM [dogs];", - "DROP TABLE [dogs];", - "ALTER TABLE [dogs_new_suffix] RENAME TO [dogs];", + 'CREATE TABLE "dogs_new_suffix" (\n "id" INTEGER PRIMARY KEY,\n "name" TEXT,\n "age" INTEGER\n);', + 'INSERT INTO "dogs_new_suffix" ("rowid", "id", "name", "age")\n SELECT "rowid", "id", "name", "age" FROM "dogs";', + 'DROP TABLE "dogs";', + 'ALTER TABLE "dogs_new_suffix" RENAME TO "dogs";', ], ), # Rename a column ( {"rename": {"age": "dog_age"}}, [ - "CREATE TABLE [dogs_new_suffix] (\n [id] INTEGER PRIMARY KEY,\n [name] TEXT,\n [dog_age] TEXT\n);", - "INSERT INTO [dogs_new_suffix] ([rowid], [id], [name], [dog_age])\n SELECT [rowid], [id], [name], [age] FROM [dogs];", - "DROP TABLE [dogs];", - "ALTER TABLE [dogs_new_suffix] RENAME TO [dogs];", + 'CREATE TABLE "dogs_new_suffix" (\n "id" INTEGER PRIMARY KEY,\n "name" TEXT,\n "dog_age" TEXT\n);', + 'INSERT INTO "dogs_new_suffix" ("rowid", "id", "name", "dog_age")\n SELECT "rowid", "id", "name", "age" FROM "dogs";', + 'DROP TABLE "dogs";', + 'ALTER TABLE "dogs_new_suffix" RENAME TO "dogs";', ], ), # Drop a column ( {"drop": ["age"]}, [ - "CREATE TABLE [dogs_new_suffix] (\n [id] INTEGER PRIMARY KEY,\n [name] TEXT\n);", - "INSERT INTO [dogs_new_suffix] ([rowid], [id], [name])\n SELECT [rowid], [id], [name] FROM [dogs];", - "DROP TABLE [dogs];", - "ALTER TABLE [dogs_new_suffix] RENAME TO [dogs];", + 'CREATE TABLE "dogs_new_suffix" (\n "id" INTEGER PRIMARY KEY,\n "name" TEXT\n);', + 'INSERT INTO "dogs_new_suffix" ("rowid", "id", "name")\n SELECT "rowid", "id", "name" FROM "dogs";', + 'DROP TABLE "dogs";', + 'ALTER TABLE "dogs_new_suffix" RENAME TO "dogs";', ], ), # Convert type AND rename column ( {"types": {"age": int}, "rename": {"age": "dog_age"}}, [ - "CREATE TABLE [dogs_new_suffix] (\n [id] INTEGER PRIMARY KEY,\n [name] TEXT,\n [dog_age] INTEGER\n);", - "INSERT INTO [dogs_new_suffix] ([rowid], [id], [name], [dog_age])\n SELECT [rowid], [id], [name], [age] FROM [dogs];", - "DROP TABLE [dogs];", - "ALTER TABLE [dogs_new_suffix] RENAME TO [dogs];", + 'CREATE TABLE "dogs_new_suffix" (\n "id" INTEGER PRIMARY KEY,\n "name" TEXT,\n "dog_age" INTEGER\n);', + 'INSERT INTO "dogs_new_suffix" ("rowid", "id", "name", "dog_age")\n SELECT "rowid", "id", "name", "age" FROM "dogs";', + 'DROP TABLE "dogs";', + 'ALTER TABLE "dogs_new_suffix" RENAME TO "dogs";', ], ), # Change primary key ( {"pk": "age"}, [ - "CREATE TABLE [dogs_new_suffix] (\n [id] INTEGER,\n [name] TEXT,\n [age] TEXT PRIMARY KEY\n);", - "INSERT INTO [dogs_new_suffix] ([rowid], [id], [name], [age])\n SELECT [rowid], [id], [name], [age] FROM [dogs];", - "DROP TABLE [dogs];", - "ALTER TABLE [dogs_new_suffix] RENAME TO [dogs];", + 'CREATE TABLE "dogs_new_suffix" (\n "id" INTEGER,\n "name" TEXT,\n "age" TEXT PRIMARY KEY\n);', + 'INSERT INTO "dogs_new_suffix" ("rowid", "id", "name", "age")\n SELECT "rowid", "id", "name", "age" FROM "dogs";', + 'DROP TABLE "dogs";', + 'ALTER TABLE "dogs_new_suffix" RENAME TO "dogs";', ], ), # Change primary key to a compound pk ( {"pk": ("age", "name")}, [ - "CREATE TABLE [dogs_new_suffix] (\n [id] INTEGER,\n [name] TEXT,\n [age] TEXT,\n PRIMARY KEY ([age], [name])\n);", - "INSERT INTO [dogs_new_suffix] ([rowid], [id], [name], [age])\n SELECT [rowid], [id], [name], [age] FROM [dogs];", - "DROP TABLE [dogs];", - "ALTER TABLE [dogs_new_suffix] RENAME TO [dogs];", + 'CREATE TABLE "dogs_new_suffix" (\n "id" INTEGER,\n "name" TEXT,\n "age" TEXT,\n PRIMARY KEY ("age", "name")\n);', + 'INSERT INTO "dogs_new_suffix" ("rowid", "id", "name", "age")\n SELECT "rowid", "id", "name", "age" FROM "dogs";', + 'DROP TABLE "dogs";', + 'ALTER TABLE "dogs_new_suffix" RENAME TO "dogs";', ], ), # Remove primary key, creating a rowid table ( {"pk": None}, [ - "CREATE TABLE [dogs_new_suffix] (\n [id] INTEGER,\n [name] TEXT,\n [age] TEXT\n);", - "INSERT INTO [dogs_new_suffix] ([rowid], [id], [name], [age])\n SELECT [rowid], [id], [name], [age] FROM [dogs];", - "DROP TABLE [dogs];", - "ALTER TABLE [dogs_new_suffix] RENAME TO [dogs];", + 'CREATE TABLE "dogs_new_suffix" (\n "id" INTEGER,\n "name" TEXT,\n "age" TEXT\n);', + 'INSERT INTO "dogs_new_suffix" ("rowid", "id", "name", "age")\n SELECT "rowid", "id", "name", "age" FROM "dogs";', + 'DROP TABLE "dogs";', + 'ALTER TABLE "dogs_new_suffix" RENAME TO "dogs";', ], ), # Keeping the table ( {"drop": ["age"], "keep_table": "kept_table"}, [ - "CREATE TABLE [dogs_new_suffix] (\n [id] INTEGER PRIMARY KEY,\n [name] TEXT\n);", - "INSERT INTO [dogs_new_suffix] ([rowid], [id], [name])\n SELECT [rowid], [id], [name] FROM [dogs];", - "ALTER TABLE [dogs] RENAME TO [kept_table];", - "ALTER TABLE [dogs_new_suffix] RENAME TO [dogs];", + 'CREATE TABLE "dogs_new_suffix" (\n "id" INTEGER PRIMARY KEY,\n "name" TEXT\n);', + 'INSERT INTO "dogs_new_suffix" ("rowid", "id", "name")\n SELECT "rowid", "id", "name" FROM "dogs";', + 'ALTER TABLE "dogs" RENAME TO "kept_table";', + 'ALTER TABLE "dogs_new_suffix" RENAME TO "dogs";', ], ), ], @@ -133,40 +135,40 @@ def test_transform_sql_table_with_primary_key( ( {}, [ - "CREATE TABLE [dogs_new_suffix] (\n [id] INTEGER,\n [name] TEXT,\n [age] TEXT\n);", - "INSERT INTO [dogs_new_suffix] ([rowid], [id], [name], [age])\n SELECT [rowid], [id], [name], [age] FROM [dogs];", - "DROP TABLE [dogs];", - "ALTER TABLE [dogs_new_suffix] RENAME TO [dogs];", + 'CREATE TABLE "dogs_new_suffix" (\n "id" INTEGER,\n "name" TEXT,\n "age" TEXT\n);', + 'INSERT INTO "dogs_new_suffix" ("rowid", "id", "name", "age")\n SELECT "rowid", "id", "name", "age" FROM "dogs";', + 'DROP TABLE "dogs";', + 'ALTER TABLE "dogs_new_suffix" RENAME TO "dogs";', ], ), # Change column type ( {"types": {"age": int}}, [ - "CREATE TABLE [dogs_new_suffix] (\n [id] INTEGER,\n [name] TEXT,\n [age] INTEGER\n);", - "INSERT INTO [dogs_new_suffix] ([rowid], [id], [name], [age])\n SELECT [rowid], [id], [name], [age] FROM [dogs];", - "DROP TABLE [dogs];", - "ALTER TABLE [dogs_new_suffix] RENAME TO [dogs];", + 'CREATE TABLE "dogs_new_suffix" (\n "id" INTEGER,\n "name" TEXT,\n "age" INTEGER\n);', + 'INSERT INTO "dogs_new_suffix" ("rowid", "id", "name", "age")\n SELECT "rowid", "id", "name", "age" FROM "dogs";', + 'DROP TABLE "dogs";', + 'ALTER TABLE "dogs_new_suffix" RENAME TO "dogs";', ], ), # Rename a column ( {"rename": {"age": "dog_age"}}, [ - "CREATE TABLE [dogs_new_suffix] (\n [id] INTEGER,\n [name] TEXT,\n [dog_age] TEXT\n);", - "INSERT INTO [dogs_new_suffix] ([rowid], [id], [name], [dog_age])\n SELECT [rowid], [id], [name], [age] FROM [dogs];", - "DROP TABLE [dogs];", - "ALTER TABLE [dogs_new_suffix] RENAME TO [dogs];", + 'CREATE TABLE "dogs_new_suffix" (\n "id" INTEGER,\n "name" TEXT,\n "dog_age" TEXT\n);', + 'INSERT INTO "dogs_new_suffix" ("rowid", "id", "name", "dog_age")\n SELECT "rowid", "id", "name", "age" FROM "dogs";', + 'DROP TABLE "dogs";', + 'ALTER TABLE "dogs_new_suffix" RENAME TO "dogs";', ], ), # Make ID a primary key ( {"pk": "id"}, [ - "CREATE TABLE [dogs_new_suffix] (\n [id] INTEGER PRIMARY KEY,\n [name] TEXT,\n [age] TEXT\n);", - "INSERT INTO [dogs_new_suffix] ([rowid], [id], [name], [age])\n SELECT [rowid], [id], [name], [age] FROM [dogs];", - "DROP TABLE [dogs];", - "ALTER TABLE [dogs_new_suffix] RENAME TO [dogs];", + 'CREATE TABLE "dogs_new_suffix" (\n "id" INTEGER PRIMARY KEY,\n "name" TEXT,\n "age" TEXT\n);', + 'INSERT INTO "dogs_new_suffix" ("rowid", "id", "name", "age")\n SELECT "rowid", "id", "name", "age" FROM "dogs";', + 'DROP TABLE "dogs";', + 'ALTER TABLE "dogs_new_suffix" RENAME TO "dogs";', ], ), ], @@ -204,13 +206,13 @@ def test_transform_sql_with_no_primary_key_to_primary_key_of_id(fresh_db): dogs.insert({"id": 1, "name": "Cleo", "age": "5"}) assert ( dogs.schema - == "CREATE TABLE [dogs] (\n [id] INTEGER,\n [name] TEXT,\n [age] TEXT\n)" + == 'CREATE TABLE "dogs" (\n "id" INTEGER,\n "name" TEXT,\n "age" TEXT\n)' ) dogs.transform(pk="id") # Slight oddity: [dogs] becomes "dogs" during the rename: assert ( dogs.schema - == 'CREATE TABLE "dogs" (\n [id] INTEGER PRIMARY KEY,\n [name] TEXT,\n [age] TEXT\n)' + == 'CREATE TABLE "dogs" (\n "id" INTEGER PRIMARY KEY,\n "name" TEXT,\n "age" TEXT\n)' ) @@ -220,17 +222,51 @@ def test_transform_rename_pk(fresh_db): dogs.transform(rename={"id": "pk"}) assert ( dogs.schema - == 'CREATE TABLE "dogs" (\n [pk] INTEGER PRIMARY KEY,\n [name] TEXT,\n [age] TEXT\n)' + == 'CREATE TABLE "dogs" (\n "pk" INTEGER PRIMARY KEY,\n "name" TEXT,\n "age" TEXT\n)' ) +def test_transform_preserves_keyword_literal_defaults(fresh_db): + # transform() used to requote keyword-literal defaults (DEFAULT TRUE became + # DEFAULT 'TRUE'), so a default insert stored the text 'TRUE' instead of the + # integer 1 -- silent value corruption on every rebuilt table. + fresh_db.execute( + "CREATE TABLE t (" + " id INTEGER PRIMARY KEY," + " is_active INTEGER DEFAULT TRUE," + " flag INTEGER DEFAULT FALSE," + " note TEXT DEFAULT NULL" + ")" + ) + table = fresh_db["t"] + table.insert({"id": 1}) + before = fresh_db.execute("SELECT is_active, flag, note FROM t").fetchone() + assert before == (1, 0, None) + + # Rebuild the table via an unrelated change. + table.transform(rename={"note": "note2"}) + + # The keyword literals stay unquoted in the schema ... + assert "DEFAULT TRUE" in table.schema + assert "DEFAULT FALSE" in table.schema + assert "DEFAULT NULL" in table.schema + assert "'TRUE'" not in table.schema + + # ... and a fresh default insert still yields 1 / 0 / NULL, not strings. + table.insert({"id": 2}) + after = fresh_db.execute( + "SELECT is_active, flag, note2 FROM t WHERE id = 2" + ).fetchone() + assert after == (1, 0, None) + + def test_transform_not_null(fresh_db): dogs = fresh_db["dogs"] dogs.insert({"id": 1, "name": "Cleo", "age": "5"}, pk="id") dogs.transform(not_null={"name"}) assert ( dogs.schema - == 'CREATE TABLE "dogs" (\n [id] INTEGER PRIMARY KEY,\n [name] TEXT NOT NULL,\n [age] TEXT\n)' + == 'CREATE TABLE "dogs" (\n "id" INTEGER PRIMARY KEY,\n "name" TEXT NOT NULL,\n "age" TEXT\n)' ) @@ -240,7 +276,7 @@ def test_transform_remove_a_not_null(fresh_db): dogs.transform(not_null={"name": True, "age": False}) assert ( dogs.schema - == 'CREATE TABLE "dogs" (\n [id] INTEGER PRIMARY KEY,\n [name] TEXT NOT NULL,\n [age] TEXT\n)' + == 'CREATE TABLE "dogs" (\n "id" INTEGER PRIMARY KEY,\n "name" TEXT NOT NULL,\n "age" TEXT\n)' ) @@ -251,7 +287,7 @@ def test_transform_add_not_null_with_rename(fresh_db, not_null): dogs.transform(not_null=not_null, rename={"age": "dog_age"}) assert ( dogs.schema - == 'CREATE TABLE "dogs" (\n [id] INTEGER PRIMARY KEY,\n [name] TEXT,\n [dog_age] TEXT NOT NULL\n)' + == 'CREATE TABLE "dogs" (\n "id" INTEGER PRIMARY KEY,\n "name" TEXT,\n "dog_age" TEXT NOT NULL\n)' ) @@ -261,7 +297,7 @@ def test_transform_defaults(fresh_db): dogs.transform(defaults={"age": 1}) assert ( dogs.schema - == 'CREATE TABLE "dogs" (\n [id] INTEGER PRIMARY KEY,\n [name] TEXT,\n [age] INTEGER DEFAULT 1\n)' + == 'CREATE TABLE "dogs" (\n "id" INTEGER PRIMARY KEY,\n "name" TEXT,\n "age" INTEGER DEFAULT 1\n)' ) @@ -271,7 +307,7 @@ def test_transform_defaults_and_rename_column(fresh_db): dogs.transform(rename={"age": "dog_age"}, defaults={"age": 1}) assert ( dogs.schema - == 'CREATE TABLE "dogs" (\n [id] INTEGER PRIMARY KEY,\n [name] TEXT,\n [dog_age] INTEGER DEFAULT 1\n)' + == 'CREATE TABLE "dogs" (\n "id" INTEGER PRIMARY KEY,\n "name" TEXT,\n "dog_age" INTEGER DEFAULT 1\n)' ) @@ -281,7 +317,7 @@ def test_remove_defaults(fresh_db): dogs.transform(defaults={"age": None}) assert ( dogs.schema - == 'CREATE TABLE "dogs" (\n [id] INTEGER PRIMARY KEY,\n [name] TEXT,\n [age] INTEGER\n)' + == 'CREATE TABLE "dogs" (\n "id" INTEGER PRIMARY KEY,\n "name" TEXT,\n "age" INTEGER\n)' ) @@ -391,11 +427,170 @@ def test_transform_verify_foreign_keys(fresh_db): # This should have rolled us back assert ( fresh_db["authors"].schema - == "CREATE TABLE [authors] (\n [id] INTEGER PRIMARY KEY,\n [name] TEXT\n)" + == 'CREATE TABLE "authors" (\n "id" INTEGER PRIMARY KEY,\n "name" TEXT\n)' ) assert fresh_db.conn.execute("PRAGMA foreign_keys").fetchone()[0] +@pytest.mark.parametrize("use_pragma_foreign_keys", [False, True]) +def test_transform_on_delete_cascade_does_not_delete_records( + fresh_db, use_pragma_foreign_keys +): + # Transforming a table drops and recreates it - if another table references + # it with ON DELETE CASCADE and PRAGMA foreign_keys is on, that drop must + # not cascade and delete the referencing records + if use_pragma_foreign_keys: + fresh_db.conn.execute("PRAGMA foreign_keys=ON") + fresh_db.executescript(""" + CREATE TABLE authors (id INTEGER PRIMARY KEY, name TEXT); + CREATE TABLE books ( + id INTEGER PRIMARY KEY, + title TEXT, + author_id INTEGER REFERENCES authors(id) ON DELETE CASCADE + ); + """) + fresh_db["authors"].insert({"id": 1, "name": "Ursula K. Le Guin"}) + fresh_db["books"].insert({"id": 1, "title": "The Dispossessed", "author_id": 1}) + # Transform the table on the other end of the cascading foreign key + fresh_db["authors"].transform(rename={"name": "author_name"}) + assert list(fresh_db["authors"].rows) == [ + {"id": 1, "author_name": "Ursula K. Le Guin"} + ] + assert list(fresh_db["books"].rows) == [ + {"id": 1, "title": "The Dispossessed", "author_id": 1} + ] + # Transforming the table with the cascading foreign key should not + # delete its records either + fresh_db["books"].transform(rename={"title": "book_title"}) + assert list(fresh_db["books"].rows) == [ + {"id": 1, "book_title": "The Dispossessed", "author_id": 1} + ] + if use_pragma_foreign_keys: + assert fresh_db.conn.execute("PRAGMA foreign_keys").fetchone()[0] + + +@pytest.mark.parametrize("on_delete", ["CASCADE", "SET NULL", "SET DEFAULT", "cascade"]) +def test_transform_in_transaction_refuses_destructive_on_delete(fresh_db, on_delete): + # PRAGMA foreign_keys is a no-op inside a transaction, so transforming a + # table referenced by ON DELETE CASCADE / SET NULL / SET DEFAULT foreign + # keys inside an open transaction would fire those actions when the old + # table is dropped - transform() should refuse instead + fresh_db.conn.execute("PRAGMA foreign_keys=ON") + fresh_db.executescript(""" + CREATE TABLE authors (id INTEGER PRIMARY KEY, name TEXT); + CREATE TABLE books ( + id INTEGER PRIMARY KEY, + title TEXT, + author_id INTEGER REFERENCES authors(id) ON DELETE {} + ); + """.format(on_delete)) + fresh_db["authors"].insert({"id": 1, "name": "Ursula K. Le Guin"}) + fresh_db["books"].insert({"id": 1, "title": "The Dispossessed", "author_id": 1}) + previous_schema = fresh_db["authors"].schema + with fresh_db.atomic(): + with pytest.raises(TransactionError) as excinfo: + fresh_db["authors"].transform(rename={"name": "author_name"}) + message = str(excinfo.value) + assert "books" in message + assert "ON DELETE {}".format(on_delete.upper()) in message + # Nothing should have changed + assert fresh_db["authors"].schema == previous_schema + assert list(fresh_db["books"].rows) == [ + {"id": 1, "title": "The Dispossessed", "author_id": 1} + ] + assert fresh_db.conn.execute("PRAGMA foreign_keys").fetchone()[0] + + +def test_transform_in_transaction_refuses_self_referential_cascade(fresh_db): + # The copied table carries a foreign key referencing the original table + # name, so a self-referential cascade would wipe the copy too + fresh_db.conn.execute("PRAGMA foreign_keys=ON") + fresh_db.executescript(""" + CREATE TABLE categories ( + id INTEGER PRIMARY KEY, + name TEXT, + parent_id INTEGER REFERENCES categories(id) ON DELETE CASCADE + ); + """) + fresh_db["categories"].insert_all( + [ + {"id": 1, "name": "Fiction", "parent_id": None}, + {"id": 2, "name": "Science Fiction", "parent_id": 1}, + ] + ) + with fresh_db.atomic(): + with pytest.raises(TransactionError) as excinfo: + fresh_db["categories"].transform(rename={"name": "title"}) + assert "categories" in str(excinfo.value) + assert fresh_db["categories"].count == 2 + + +def test_transform_in_transaction_allowed_with_no_action_foreign_key(fresh_db): + # An inbound foreign key without a destructive ON DELETE action is safe + # inside a transaction thanks to PRAGMA defer_foreign_keys + fresh_db.conn.execute("PRAGMA foreign_keys=ON") + fresh_db.executescript(""" + CREATE TABLE authors (id INTEGER PRIMARY KEY, name TEXT); + CREATE TABLE books ( + id INTEGER PRIMARY KEY, + title TEXT, + author_id INTEGER REFERENCES authors(id) + ); + """) + fresh_db["authors"].insert({"id": 1, "name": "Ursula K. Le Guin"}) + fresh_db["books"].insert({"id": 1, "title": "The Dispossessed", "author_id": 1}) + with fresh_db.atomic(): + fresh_db["authors"].transform(rename={"name": "author_name"}) + assert list(fresh_db["authors"].rows) == [ + {"id": 1, "author_name": "Ursula K. Le Guin"} + ] + assert list(fresh_db["books"].rows) == [ + {"id": 1, "title": "The Dispossessed", "author_id": 1} + ] + assert fresh_db.conn.execute("PRAGMA foreign_keys").fetchone()[0] + + +def test_transform_in_transaction_allowed_for_child_table(fresh_db): + # The table being transformed only has an outbound foreign key - dropping + # it fires no ON DELETE actions, so this is allowed inside a transaction + fresh_db.conn.execute("PRAGMA foreign_keys=ON") + fresh_db.executescript(""" + CREATE TABLE authors (id INTEGER PRIMARY KEY, name TEXT); + CREATE TABLE books ( + id INTEGER PRIMARY KEY, + title TEXT, + author_id INTEGER REFERENCES authors(id) ON DELETE CASCADE + ); + """) + fresh_db["authors"].insert({"id": 1, "name": "Ursula K. Le Guin"}) + fresh_db["books"].insert({"id": 1, "title": "The Dispossessed", "author_id": 1}) + with fresh_db.atomic(): + fresh_db["books"].transform(rename={"title": "book_title"}) + assert list(fresh_db["books"].rows) == [ + {"id": 1, "book_title": "The Dispossessed", "author_id": 1} + ] + + +def test_transform_in_transaction_allowed_with_foreign_keys_off(fresh_db): + # With PRAGMA foreign_keys off (the default) no cascades can fire, so + # transform inside a transaction is safe even with a CASCADE schema + fresh_db.executescript(""" + CREATE TABLE authors (id INTEGER PRIMARY KEY, name TEXT); + CREATE TABLE books ( + id INTEGER PRIMARY KEY, + title TEXT, + author_id INTEGER REFERENCES authors(id) ON DELETE CASCADE + ); + """) + fresh_db["authors"].insert({"id": 1, "name": "Ursula K. Le Guin"}) + fresh_db["books"].insert({"id": 1, "title": "The Dispossessed", "author_id": 1}) + with fresh_db.atomic(): + fresh_db["authors"].transform(rename={"name": "author_name"}) + assert list(fresh_db["books"].rows) == [ + {"id": 1, "title": "The Dispossessed", "author_id": 1} + ] + + def test_transform_add_foreign_keys_from_scratch(fresh_db): _add_country_city_continent(fresh_db) fresh_db["places"].insert(_CAVEAU) @@ -420,11 +615,11 @@ def test_transform_add_foreign_keys_from_scratch(fresh_db): ] assert fresh_db["places"].schema == ( 'CREATE TABLE "places" (\n' - " [id] INTEGER,\n" - " [name] TEXT,\n" - " [country] INTEGER REFERENCES [country]([id]),\n" - " [continent] INTEGER REFERENCES [continent]([id]),\n" - " [city] INTEGER REFERENCES [city]([id])\n" + ' "id" INTEGER,\n' + ' "name" TEXT,\n' + ' "country" INTEGER REFERENCES "country"("id"),\n' + ' "continent" INTEGER REFERENCES "continent"("id"),\n' + ' "city" INTEGER REFERENCES "city"("id")\n' ")" ) @@ -491,11 +686,11 @@ def test_transform_replace_foreign_keys(fresh_db, foreign_keys): fresh_db["places"].transform(foreign_keys=foreign_keys) assert fresh_db["places"].schema == ( 'CREATE TABLE "places" (\n' - " [id] INTEGER,\n" - " [name] TEXT,\n" - " [country] INTEGER REFERENCES [country]([id]),\n" - " [continent] INTEGER REFERENCES [continent]([id]),\n" - " [city] INTEGER\n" + ' "id" INTEGER,\n' + ' "name" TEXT,\n' + ' "country" INTEGER REFERENCES "country"("id"),\n' + ' "continent" INTEGER REFERENCES "continent"("id"),\n' + ' "city" INTEGER\n' ")" ) @@ -530,3 +725,182 @@ def test_transform_preserves_rowids(fresh_db, table_type): tuple(row) for row in fresh_db.execute("select rowid, id, name from places") ) assert previous_rows == next_rows + + +@pytest.mark.parametrize( + "initial_strict,transform_strict,expected_strict", + ( + (False, None, False), + (True, None, True), + (False, True, True), + (True, False, False), + ), +) +def test_transform_strict(fresh_db, initial_strict, transform_strict, expected_strict): + if not fresh_db.supports_strict: + pytest.skip("SQLite version does not support strict tables") + dogs = fresh_db.table("dogs", strict=initial_strict) + dogs.insert({"id": 1, "name": "Cleo"}) + assert dogs.strict is initial_strict + dogs.transform(strict=transform_strict) + assert dogs.strict is expected_strict + + +def test_transform_to_strict_with_invalid_data(fresh_db): + if not fresh_db.supports_strict: + pytest.skip("SQLite version does not support strict tables") + dogs = fresh_db["dogs"] + dogs.create({"id": int}) + dogs.insert({"id": "not-an-integer"}) + + with pytest.raises(sqlite3.IntegrityError): + dogs.transform(strict=True) + + assert dogs.strict is False + assert list(dogs.rows) == [{"id": "not-an-integer"}] + assert fresh_db.table_names() == ["dogs"] + + +def test_transform_strict_updates_default(fresh_db): + if not fresh_db.supports_strict: + pytest.skip("SQLite version does not support strict tables") + table = fresh_db.table("items", strict=True) + table.create({"id": int}) + + table.transform(strict=False) + assert table.strict is False + + table.create({"id": int}, replace=True) + assert table.strict is False + + +@pytest.mark.parametrize("method_name", ("transform", "transform_sql")) +def test_transform_to_strict_not_supported(fresh_db, method_name): + table = fresh_db["items"] + table.create({"id": int}) + fresh_db._supports_strict = False + + with pytest.raises(TransformError, match="SQLite does not support STRICT tables"): + getattr(table, method_name)(strict=True) + + assert table.strict is False + + +@pytest.mark.parametrize( + "indexes, transform_params", + [ + ([["name"]], {"types": {"age": str}}), + ([["name"], ["age", "breed"]], {"types": {"age": str}}), + ([], {"types": {"age": str}}), + ([["name"]], {"types": {"age": str}, "keep_table": "old_dogs"}), + ], +) +def test_transform_indexes(fresh_db, indexes, transform_params): + # https://github.com/simonw/sqlite-utils/issues/633 + # New table should have same indexes as old table after transformation + dogs = fresh_db["dogs"] + dogs.insert({"id": 1, "name": "Cleo", "age": 5, "breed": "Labrador"}, pk="id") + + for index in indexes: + dogs.create_index(index) + + indexes_before_transform = dogs.indexes + + dogs.transform(**transform_params) + + assert sorted( + [ + {k: v for k, v in idx._asdict().items() if k != "seq"} + for idx in dogs.indexes + ], + key=lambda x: x["name"], + ) == sorted( + [ + {k: v for k, v in idx._asdict().items() if k != "seq"} + for idx in indexes_before_transform + ], + key=lambda x: x["name"], + ), f"Indexes before transform: {indexes_before_transform}\nIndexes after transform: {dogs.indexes}" + if "keep_table" in transform_params: + assert all( + index.origin == "pk" + for index in fresh_db[transform_params["keep_table"]].indexes + ) + + +def test_transform_retains_indexes_with_foreign_keys(fresh_db): + dogs = fresh_db["dogs"] + owners = fresh_db["owners"] + + dogs.insert({"id": 1, "name": "Cleo", "owner_id": 1}, pk="id") + owners.insert({"id": 1, "name": "Alice"}, pk="id") + + dogs.create_index(["name"]) + + indexes_before_transform = dogs.indexes + + fresh_db.add_foreign_keys([("dogs", "owner_id", "owners", "id")]) # calls transform + + assert sorted( + [ + {k: v for k, v in idx._asdict().items() if k != "seq"} + for idx in dogs.indexes + ], + key=lambda x: x["name"], + ) == sorted( + [ + {k: v for k, v in idx._asdict().items() if k != "seq"} + for idx in indexes_before_transform + ], + key=lambda x: x["name"], + ), f"Indexes before transform: {indexes_before_transform}\nIndexes after transform: {dogs.indexes}" + + +@pytest.mark.parametrize( + "transform_params", + [ + {"rename": {"age": "dog_age"}}, + {"drop": ["age"]}, + ], +) +def test_transform_with_indexes_errors(fresh_db, transform_params): + # Should error with a compound (name, age) index if age is renamed or dropped + dogs = fresh_db["dogs"] + dogs.insert({"id": 1, "name": "Cleo", "age": 5}, pk="id") + + dogs.create_index(["name", "age"]) + + with pytest.raises(TransformError) as excinfo: + dogs.transform(**transform_params) + + assert ( + "Index 'idx_dogs_name_age' column 'age' is not in updated table 'dogs'. " + "You must manually drop this index prior to running this transformation" + in str(excinfo.value) + ) + + +def test_transform_with_unique_constraint_implicit_index(fresh_db): + dogs = fresh_db["dogs"] + # Create a table with a UNIQUE constraint on 'name', which creates an implicit index + fresh_db.execute(""" + CREATE TABLE dogs ( + id INTEGER PRIMARY KEY, + name TEXT UNIQUE, + age INTEGER + ); + """) + dogs.insert({"id": 1, "name": "Cleo", "age": 5}) + + # Attempt to transform the table without modifying 'name' + with pytest.raises(TransformError) as excinfo: + dogs.transform(types={"age": str}) + + assert ( + "Index 'sqlite_autoindex_dogs_1' on table 'dogs' does not have a CREATE INDEX statement." + in str(excinfo.value) + ) + assert ( + "You must manually drop this index prior to running this transformation and manually recreate the new index after running this transformation." + in str(excinfo.value) + ) diff --git a/tests/test_update.py b/tests/test_update.py index 916eb19..03bec11 100644 --- a/tests/test_update.py +++ b/tests/test_update.py @@ -70,11 +70,12 @@ def test_update_alter(fresh_db): ] == list(table.rows) -def test_update_alter_with_invalid_column_characters(fresh_db): +def test_update_alter_with_special_column_characters(fresh_db): + # With double-quote escaping, columns with special characters are now valid table = fresh_db["table"] rowid = table.insert({"foo": "bar"}).last_pk - with pytest.raises(AssertionError): - table.update(rowid, {"new_col[abc]": 1.2}, alter=True) + table.update(rowid, {"new_col[abc]": 1.2}, alter=True) + assert list(table.rows) == [{"foo": "bar", "new_col[abc]": 1.2}] def test_update_with_no_values_sets_last_pk(fresh_db): diff --git a/tests/test_upsert.py b/tests/test_upsert.py index 8a34d4e..a782b26 100644 --- a/tests/test_upsert.py +++ b/tests/test_upsert.py @@ -1,9 +1,12 @@ from sqlite_utils.db import PrimaryKeyRequired +from sqlite_utils import Database import pytest -def test_upsert(fresh_db): - table = fresh_db["table"] +@pytest.mark.parametrize("use_old_upsert", (False, True)) +def test_upsert(use_old_upsert): + db = Database(memory=True, use_old_upsert=use_old_upsert) + table = db["table"] table.insert({"id": 1, "name": "Cleo"}, pk="id") table.upsert({"id": 1, "age": 5}, pk="id", alter=True) assert list(table.rows) == [{"id": 1, "name": "Cleo", "age": 5}] @@ -46,6 +49,89 @@ def test_upsert_error_if_no_pk(fresh_db): table.upsert({"id": 1, "name": "Cleo"}) +@pytest.mark.parametrize("use_old_upsert", (False, True)) +def test_upsert_empty_record_errors(use_old_upsert): + db = Database(memory=True, use_old_upsert=use_old_upsert) + table = db["table"] + table.insert({"id": 1, "name": "Cleo"}, pk="id") + with pytest.raises(PrimaryKeyRequired): + table.upsert({}, pk="id") + with pytest.raises(PrimaryKeyRequired): + table.upsert_all([{}, {}], pk="id") + # No rows can have been inserted + assert table.count == 1 + + +@pytest.mark.parametrize("use_old_upsert", (False, True)) +def test_upsert_missing_pk_value_errors(use_old_upsert): + db = Database(memory=True, use_old_upsert=use_old_upsert) + table = db["table"] + table.insert({"id": 1, "name": "Cleo"}, pk="id") + # Records that omit the pk column entirely + with pytest.raises(PrimaryKeyRequired): + table.upsert_all([{"name": "Pancakes"}, {"name": "Marnie"}], pk="id") + # A record with an explicit None pk value can never conflict + with pytest.raises(PrimaryKeyRequired): + table.upsert({"id": None, "name": "Pancakes"}, pk="id") + assert list(table.rows) == [{"id": 1, "name": "Cleo"}] + + +def test_upsert_missing_compound_pk_value_errors(fresh_db): + table = fresh_db["table"] + table.insert({"a": "x", "b": "y", "v": 1}, pk=("a", "b")) + # Missing one component of the detected compound primary key + with pytest.raises(PrimaryKeyRequired): + table.upsert({"a": "x", "v": 2}) + assert list(table.rows) == [{"a": "x", "b": "y", "v": 1}] + + +def test_upsert_error_if_existing_table_has_no_pk(fresh_db): + table = fresh_db.create_table("table", {"id": int, "name": str}) + with pytest.raises(PrimaryKeyRequired): + table.upsert({"id": 1, "name": "Cleo"}) + + +@pytest.mark.parametrize("use_old_upsert", (False, True)) +def test_upsert_uses_compound_pk_from_existing_table(use_old_upsert): + # https://github.com/simonw/sqlite-utils/issues/629 + db = Database(memory=True, use_old_upsert=use_old_upsert) + db.execute(""" + create table summary ( + Source text, + Object text, + Category text, + Count integer, + primary key (Source, Object, Category) + ) + """) + table = db["summary"] + table.upsert( + { + "Source": "Client A", + "Object": "Accounts", + "Category": "All", + "Count": 3, + } + ) + assert table.last_pk == ("Client A", "Accounts", "All") + table.upsert( + { + "Source": "Client A", + "Object": "Accounts", + "Category": "All", + "Count": 4, + } + ) + assert list(table.rows) == [ + { + "Source": "Client A", + "Object": "Accounts", + "Category": "All", + "Count": 4, + } + ] + + def test_upsert_with_hash_id(fresh_db): table = fresh_db["table"] table.upsert({"foo": "bar"}, hash_id="pk") diff --git a/tests/test_utils.py b/tests/test_utils.py index f728bcd..3de5e94 100644 --- a/tests/test_utils.py +++ b/tests/test_utils.py @@ -83,3 +83,20 @@ def test_maximize_csv_field_size_limit(): ) def test_flatten(input, expected): assert utils.flatten(input) == expected + + +@pytest.mark.parametrize( + "input,expected", + ( + ([], []), + (["id", "name"], ["id", "name"]), + (["id", "id"], ["id", "id_2"]), + (["id", "id", "id"], ["id", "id_2", "id_3"]), + # A renamed duplicate must not clobber a real column called id_2 + (["id", "id", "id_2"], ["id", "id_3", "id_2"]), + (["id_2", "id", "id"], ["id_2", "id", "id_3"]), + (["id", "id", "id_2", "id_2"], ["id", "id_3", "id_2", "id_2_2"]), + ), +) +def test_dedupe_keys(input, expected): + assert utils.dedupe_keys(input) == expected diff --git a/tests/test_wal.py b/tests/test_wal.py index 23ca144..2ddcf54 100644 --- a/tests/test_wal.py +++ b/tests/test_wal.py @@ -1,5 +1,6 @@ import pytest from sqlite_utils import Database +from sqlite_utils.db import TransactionError @pytest.fixture @@ -21,3 +22,67 @@ def test_enable_disable_wal(db_path_tmpdir): db.disable_wal() assert "delete" == db.journal_mode assert "test.db-wal" not in [f.basename for f in tmpdir.listdir()] + + +def test_enable_wal_inside_transaction_raises(db_path_tmpdir): + db, path, tmpdir = db_path_tmpdir + db["test"].insert({"id": 1}, pk="id") + with pytest.raises(TransactionError): + with db.atomic(): + db["test"].insert({"id": 2}, pk="id") + db.enable_wal() + # The atomic() block must have rolled back cleanly and the + # journal mode must be unchanged + assert db.journal_mode == "delete" + assert [r["id"] for r in db["test"].rows] == [1] + + +def test_disable_wal_inside_transaction_raises(db_path_tmpdir): + db, path, tmpdir = db_path_tmpdir + db.enable_wal() + db["test"].insert({"id": 1}, pk="id") + with pytest.raises(TransactionError): + with db.atomic(): + db["test"].insert({"id": 2}, pk="id") + db.disable_wal() + assert db.journal_mode == "wal" + assert [r["id"] for r in db["test"].rows] == [1] + + +def test_ensure_autocommit_on(db_path_tmpdir): + db, path, tmpdir = db_path_tmpdir + previous_isolation_level = db.conn.isolation_level + assert previous_isolation_level is not None + with db.ensure_autocommit_on(): + # isolation_level of None means driver-level autocommit mode + assert db.conn.isolation_level is None + # Restored afterwards + assert db.conn.isolation_level == previous_isolation_level + + +def test_enable_wal_noop_inside_transaction_is_allowed(db_path_tmpdir): + # Calling enable_wal() when WAL is already enabled is a no-op, + # so it is fine inside a transaction + db, path, tmpdir = db_path_tmpdir + db.enable_wal() + with db.atomic(): + db["test"].insert({"id": 1}, pk="id") + db.enable_wal() + assert [r["id"] for r in db["test"].rows] == [1] + + +def test_ensure_autocommit_on_inside_transaction_raises(db_path_tmpdir): + # Setting isolation_level commits any pending transaction as a side + # effect, silently breaking the caller's rollback guarantee - so + # entering autocommit mode with a transaction open is an error + db, path, tmpdir = db_path_tmpdir + db["test"].insert({"id": 1}, pk="id") + db.begin() + db.execute("insert into test (id) values (2)") + with pytest.raises(TransactionError): + with db.ensure_autocommit_on(): + pass + # The transaction is still open and can still be rolled back + assert db.conn.in_transaction + db.rollback() + assert [r["id"] for r in db["test"].rows] == [1]