From aabcf8586bfef5cf571bb2c546977237f2051919 Mon Sep 17 00:00:00 2001 From: Shubham Gandhi <68658240+Shubham-147@users.noreply.github.com> Date: Thu, 12 Nov 2026 16:56:07 +0530 Subject: [PATCH] Add standalone executable builds --- .github/workflows/standalone.yml | 90 +++++++++++ README.md | 4 + docs/installation.rst | 48 ++++++ packaging/build.py | 67 ++++++++ .../pyinstaller/hooks/hook-sqlite_utils.db.py | 7 + .../hooks/hook-sqlite_utils.plugins.py | 3 + packaging/standalone.py | 4 + pyproject.toml | 6 + sqlite_utils/cli.py | 10 ++ tests/standalone_plugin/pyproject.toml | 14 ++ .../sqlite_utils_standalone_test_plugin.py | 9 ++ tests/test_standalone.py | 150 ++++++++++++++++++ 12 files changed, 412 insertions(+) create mode 100644 .github/workflows/standalone.yml create mode 100644 packaging/build.py create mode 100644 packaging/pyinstaller/hooks/hook-sqlite_utils.db.py create mode 100644 packaging/pyinstaller/hooks/hook-sqlite_utils.plugins.py create mode 100644 packaging/standalone.py create mode 100644 tests/standalone_plugin/pyproject.toml create mode 100644 tests/standalone_plugin/sqlite_utils_standalone_test_plugin.py create mode 100644 tests/test_standalone.py diff --git a/.github/workflows/standalone.yml b/.github/workflows/standalone.yml new file mode 100644 index 000000000..71234a0ec --- /dev/null +++ b/.github/workflows/standalone.yml @@ -0,0 +1,90 @@ +name: Standalone executables + +on: + push: + pull_request: + release: + types: [created] + +permissions: + contents: read + +jobs: + build-and-test: + runs-on: ${{ matrix.os }} + strategy: + matrix: + include: + - os: ubuntu-22.04 + platform: linux-x86_64 + - os: macos-14 + platform: macos-arm64 + - os: windows-latest + platform: windows-x86_64 + steps: + - uses: actions/checkout@v7 + - name: Set up Python + uses: actions/setup-python@v7 + with: + python-version: "3.14" + cache: pip + cache-dependency-path: pyproject.toml + - name: Install build and test dependencies + run: pip install . --group executable --group dev + - name: Build standalone executable + run: python packaging/build.py + - name: Test standalone executable + shell: bash + run: | + executable="$(find dist -maxdepth 1 -type f -name 'sqlite-utils-*' -print -quit)" + test -n "$executable" + SQLITE_UTILS_EXECUTABLE="$executable" pytest -v tests/test_standalone.py + - name: Save executable for release upload + if: github.event_name == 'release' + uses: actions/upload-artifact@v4 + with: + name: sqlite-utils-${{ matrix.platform }} + path: dist/sqlite-utils-* + if-no-files-found: error + + upload-release-assets: + if: github.event_name == 'release' + needs: [build-and-test, test-build-time-plugin] + runs-on: ubuntu-latest + permissions: + contents: write + steps: + - name: Download platform executables + uses: actions/download-artifact@v4 + with: + path: dist + pattern: sqlite-utils-* + merge-multiple: true + - name: Upload executables to release + env: + GH_TOKEN: ${{ github.token }} + run: gh release upload "$GITHUB_REF_NAME" dist/* --clobber + + test-build-time-plugin: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7 + - name: Set up Python + uses: actions/setup-python@v7 + with: + python-version: "3.14" + cache: pip + cache-dependency-path: pyproject.toml + - name: Install build and test dependencies + run: pip install . --group executable --group dev + - name: Install test plugin + run: pip install ./tests/standalone_plugin + - name: Build standalone executable with plugin + run: python packaging/build.py + - name: Test bundled plugin + shell: bash + run: | + executable="$(find dist -maxdepth 1 -type f -name 'sqlite-utils-*' -print -quit)" + SQLITE_UTILS_EXECUTABLE="$executable" \ + SQLITE_UTILS_STANDALONE_TEST_PLUGIN=sqlite-utils-standalone-test-plugin \ + pytest -v tests/test_standalone.py diff --git a/README.md b/README.md index c444c641a..af859d2ad 100644 --- a/README.md +++ b/README.md @@ -29,6 +29,10 @@ Read more on my blog, in this series of posts on [New features in sqlite-utils]( pip install sqlite-utils +Standalone executables that do not require Python are available from the +[GitHub releases](https://github.com/simonw/sqlite-utils/releases). See the +[standalone installation instructions](https://sqlite-utils.datasette.io/en/stable/installation.html#standalone-executables). + Or if you use [Homebrew](https://brew.sh/) for macOS: brew install sqlite-utils diff --git a/docs/installation.rst b/docs/installation.rst index 1333f5d9f..ee3ffd489 100644 --- a/docs/installation.rst +++ b/docs/installation.rst @@ -39,6 +39,54 @@ Using pipx pipx install sqlite-utils +.. _installation_standalone: + +Standalone executables +====================== + +Standalone executables for Linux, macOS and Windows are attached to each +`GitHub release `__. They +include Python and the required ``sqlite-utils`` dependencies, so Python does +not need to be installed separately. Download the executable for your operating +system and processor architecture, then run it directly. Release assets are +named ``sqlite-utils-linux-x86_64``, ``sqlite-utils-macos-arm64`` and +``sqlite-utils-windows-x86_64.exe``. On macOS or Linux you may need to make the +downloaded file executable first:: + + chmod +x sqlite-utils-* + +The Linux executable is built on Ubuntu 22.04 and requires a compatible glibc +runtime. Executables are specific to their operating system and CPU architecture. +The SQLite library is the one bundled with the Python runtime used to build the +executable; available SQLite features therefore depend on that build. SQLite +extensions such as SpatiaLite are not included and must be supplied separately +as compatible native libraries. + +The executable includes plugins installed in the build environment. Since it +does not use a system Python installation, plugins installed after downloading +the executable are not discovered. The ``install`` and ``uninstall`` commands +are therefore unavailable in the executable. To use additional plugins, install +them before building your own executable as described below. Other optional +integrations such as ``numpy``, ``pandas``, ``sqlite_dump`` and ``pysqlite3`` are +included when installed in the build environment. Modules imported dynamically +by custom Python code may need an explicit PyInstaller hook. + +Building a standalone executable +-------------------------------- + +Builds must be performed on the operating system and architecture for which the +executable is intended; PyInstaller does not cross-compile. From a checkout of +the ``sqlite-utils`` source, install the executable build dependencies and run +the build script:: + + pip install . --group executable + python packaging/build.py + +The platform-specific executable will be written to ``dist/``. To include +plugins, install them into the same Python environment before running the build +script. PyInstaller collects ``sqlite_utils`` entry points and their modules +from that environment. + .. _installation_sqlite3_alternatives: Alternatives to sqlite3 diff --git a/packaging/build.py b/packaging/build.py new file mode 100644 index 000000000..02ae16a89 --- /dev/null +++ b/packaging/build.py @@ -0,0 +1,67 @@ +import platform +import shutil +import subprocess +import sys +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +DIST = ROOT / "dist" + + +def main() -> None: + system = platform.system().lower() + machine = platform.machine().lower() + architectures = { + "amd64": "x86_64", + "aarch64": "arm64" if system == "darwin" else "aarch64", + "arm64": "arm64", + "x86_64": "x86_64", + } + if system not in {"darwin", "linux", "windows"}: + raise SystemExit(f"Unsupported operating system: {system}") + try: + architecture = architectures[machine] + except KeyError: + raise SystemExit(f"Unsupported architecture: {machine}") from None + + if DIST.exists(): + shutil.rmtree(DIST) + DIST.mkdir(parents=True) + + subprocess.run( + [ + sys.executable, + "-m", + "PyInstaller", + "--clean", + "--noconfirm", + "--onefile", + "--name", + "sqlite-utils", + "--copy-metadata", + "sqlite-utils", + "--additional-hooks-dir", + str(ROOT / "packaging" / "pyinstaller" / "hooks"), + "--distpath", + str(DIST), + "--workpath", + str(ROOT / "build" / "pyinstaller"), + "--specpath", + str(ROOT / "build" / "pyinstaller"), + str(ROOT / "packaging" / "standalone.py"), + ], + cwd=ROOT, + check=True, + ) + + executable_os = {"darwin": "macos"}.get(system, system) + extension = ".exe" if system == "windows" else "" + executable = DIST / f"sqlite-utils{extension}" + asset = DIST / f"sqlite-utils-{executable_os}-{architecture}{extension}" + asset.parent.mkdir(exist_ok=True) + shutil.move(str(executable), str(asset)) + print(f"Built {asset}") + + +if __name__ == "__main__": + main() diff --git a/packaging/pyinstaller/hooks/hook-sqlite_utils.db.py b/packaging/pyinstaller/hooks/hook-sqlite_utils.db.py new file mode 100644 index 000000000..0fa3e36cc --- /dev/null +++ b/packaging/pyinstaller/hooks/hook-sqlite_utils.db.py @@ -0,0 +1,7 @@ +from PyInstaller.utils.hooks import can_import_module + +hiddenimports = [ + module + for module in ("numpy", "pandas", "sqlite_dump", "pysqlite3", "pysqlite3.dbapi2") + if can_import_module(module) +] diff --git a/packaging/pyinstaller/hooks/hook-sqlite_utils.plugins.py b/packaging/pyinstaller/hooks/hook-sqlite_utils.plugins.py new file mode 100644 index 000000000..5b85eace1 --- /dev/null +++ b/packaging/pyinstaller/hooks/hook-sqlite_utils.plugins.py @@ -0,0 +1,3 @@ +from PyInstaller.utils.hooks import collect_entry_point + +datas, hiddenimports = collect_entry_point("sqlite_utils") # codespell:ignore datas diff --git a/packaging/standalone.py b/packaging/standalone.py new file mode 100644 index 000000000..58722bd05 --- /dev/null +++ b/packaging/standalone.py @@ -0,0 +1,4 @@ +from sqlite_utils.cli import cli + +if __name__ == "__main__": + cli() diff --git a/pyproject.toml b/pyproject.toml index 92650e23b..cf60d6e9a 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -60,6 +60,9 @@ docs = [ "sphinx-autobuild", "sphinx-copybutton", ] +executable = [ + "pyinstaller==6.22.3", +] [project.urls] Homepage = "https://github.com/simonw/sqlite-utils" @@ -76,6 +79,9 @@ sqlite-utils = "sqlite_utils.cli:cli" requires = ["setuptools>=77"] build-backend = "setuptools.build_meta" +[tool.setuptools.packages.find] +include = ["sqlite_utils*"] + [tool.flake8] max-line-length = 160 # Black compatibility, E203 whitespace before ':': diff --git a/sqlite_utils/cli.py b/sqlite_utils/cli.py index c23090283..f0045bc56 100644 --- a/sqlite_utils/cli.py +++ b/sqlite_utils/cli.py @@ -3149,6 +3149,7 @@ def _analyze(db, tables, columns, save, common_limit=10, no_most=False, no_least ) def install(packages, upgrade, editable): """Install packages from PyPI into the same environment as sqlite-utils""" + _ensure_not_frozen_for_package_management() args = ["pip", "install"] if upgrade: args += ["--upgrade"] @@ -3164,10 +3165,19 @@ def install(packages, upgrade, editable): @click.option("-y", "--yes", is_flag=True, help="Don't ask for confirmation") def uninstall(packages, yes): """Uninstall Python packages from the sqlite-utils environment""" + _ensure_not_frozen_for_package_management() sys.argv = ["pip", "uninstall"] + list(packages) + (["-y"] if yes else []) run_module("pip", run_name="__main__") +def _ensure_not_frozen_for_package_management(): + if getattr(sys, "frozen", False): + raise click.ClickException( + "Package installation and removal are not supported by the standalone " + "executable. Install plugins before building the executable instead." + ) + + def _generate_convert_help(): help = textwrap.dedent(""" Convert columns using Python code you supply. For example: diff --git a/tests/standalone_plugin/pyproject.toml b/tests/standalone_plugin/pyproject.toml new file mode 100644 index 000000000..2abd7b415 --- /dev/null +++ b/tests/standalone_plugin/pyproject.toml @@ -0,0 +1,14 @@ +[build-system] +requires = ["setuptools"] +build-backend = "setuptools.build_meta" + +[project] +name = "sqlite-utils-standalone-test-plugin" +version = "1.0" +requires-python = ">=3.10" + +[project.entry-points.sqlite_utils] +standalone_test_plugin = "sqlite_utils_standalone_test_plugin" + +[tool.setuptools] +py-modules = ["sqlite_utils_standalone_test_plugin"] diff --git a/tests/standalone_plugin/sqlite_utils_standalone_test_plugin.py b/tests/standalone_plugin/sqlite_utils_standalone_test_plugin.py new file mode 100644 index 000000000..164968b2e --- /dev/null +++ b/tests/standalone_plugin/sqlite_utils_standalone_test_plugin.py @@ -0,0 +1,9 @@ +import click +import sqlite_utils + + +@sqlite_utils.hookimpl +def register_commands(cli): + @cli.command() + def standalone_plugin_test(): + click.echo("Bundled plugin works") diff --git a/tests/test_standalone.py b/tests/test_standalone.py new file mode 100644 index 000000000..7dd0418a6 --- /dev/null +++ b/tests/test_standalone.py @@ -0,0 +1,150 @@ +import importlib.metadata +import json +import os +import subprocess +from pathlib import Path + +import pytest + + +@pytest.fixture(scope="session") +def standalone_executable(): + executable = os.environ.get("SQLITE_UTILS_EXECUTABLE") + if not executable: + pytest.skip("Set SQLITE_UTILS_EXECUTABLE to a built standalone executable") + path = Path(executable).resolve() + assert path.is_file(), f"Standalone executable does not exist: {path}" + return path + + +@pytest.fixture +def run_standalone(standalone_executable, tmp_path): + empty_path = tmp_path / "empty-path" + empty_path.mkdir() + env = { + key: value + for key, value in os.environ.items() + if not key.startswith(("PYTHON", "VIRTUAL_ENV", "CONDA")) + } + env["PATH"] = str(empty_path) + + def run(*args): + return subprocess.run( + [str(standalone_executable), *map(str, args)], + cwd=tmp_path, + env=env, + capture_output=True, + text=True, + check=False, + ) + + return run + + +def test_standalone_help_and_version(run_standalone): + help_result = run_standalone("--help") + assert help_result.returncode == 0, help_result.stderr + assert "create-table" in help_result.stdout + assert "insert" in help_result.stdout + assert "query" in help_result.stdout + + version_result = run_standalone("--version") + assert version_result.returncode == 0, version_result.stderr + assert version_result.stdout.strip().endswith( + f", version {importlib.metadata.version('sqlite-utils')}" + ) + + +def test_standalone_import_query_export_and_fts(run_standalone, tmp_path): + database = tmp_path / "people.db" + json_file = tmp_path / "people.json" + json_file.write_text( + json.dumps([{"id": 1, "name": "Ada"}, {"id": 2, "name": "Grace"}]), + encoding="utf-8", + ) + csv_file = tmp_path / "cities.csv" + csv_file.write_text("id,city\n1,London\n2,New York\n", encoding="utf-8") + + created = run_standalone( + "create-table", + database, + "people", + "id", + "integer", + "name", + "text", + "--pk", + "id", + ) + assert created.returncode == 0, created.stderr + + imported_json = run_standalone( + "insert", database, "people", json_file, "--pk", "id" + ) + assert imported_json.returncode == 0, imported_json.stderr + + imported_csv = run_standalone("insert", database, "cities", csv_file, "--csv") + assert imported_csv.returncode == 0, imported_csv.stderr + + query = run_standalone("query", database, "select id, name from people order by id") + assert query.returncode == 0, query.stderr + assert json.loads(query.stdout) == [ + {"id": 1, "name": "Ada"}, + {"id": 2, "name": "Grace"}, + ] + + csv_export = run_standalone( + "query", database, "select city from cities order by id", "--csv" + ) + assert csv_export.returncode == 0, csv_export.stderr + assert csv_export.stdout == "city\nLondon\nNew York\n" + + enabled_fts = run_standalone("enable-fts", database, "people", "name") + assert enabled_fts.returncode == 0, enabled_fts.stderr + fts_query = run_standalone( + "query", database, "select count(*) as count from people_fts" + ) + assert fts_query.returncode == 0, fts_query.stderr + assert json.loads(fts_query.stdout) == [{"count": 2}] + + +def test_standalone_invalid_arguments_have_click_error(run_standalone): + result = run_standalone("query", "--not-a-real-option") + assert result.returncode == 2 + assert "No such option" in result.stderr + + +def test_standalone_missing_arguments_have_click_error(run_standalone): + result = run_standalone("create-table") + assert result.returncode == 2 + assert "Missing argument" in result.stderr + + +@pytest.mark.parametrize( + "command", + [("install", "example-plugin"), ("uninstall", "example-plugin")], +) +def test_standalone_package_management_has_helpful_error(run_standalone, command): + result = run_standalone(*command) + assert result.returncode == 1 + assert "not supported by the standalone executable" in result.stderr + assert "Traceback" not in result.stderr + + +def test_standalone_plugin_listing(run_standalone): + result = run_standalone("plugins") + assert result.returncode == 0, result.stderr + plugins = json.loads(result.stdout) + expected_plugin = os.environ.get("SQLITE_UTILS_STANDALONE_TEST_PLUGIN") + if expected_plugin: + assert any(plugin["name"] == expected_plugin for plugin in plugins) + else: + assert plugins == [] + + +def test_standalone_loads_plugin_bundled_at_build_time(run_standalone): + if not os.environ.get("SQLITE_UTILS_STANDALONE_TEST_PLUGIN"): + pytest.skip("Test plugin was not installed when the executable was built") + result = run_standalone("standalone-plugin-test") + assert result.returncode == 0, result.stderr + assert result.stdout == "Bundled plugin works\n"