├── VERSION ├── python ├── sqlite_fastrand │ ├── noop.c │ ├── sqlite_fastrand │ │ ├── version.py │ │ └── __init__.py │ ├── setup.py │ └── README.md ├── datasette_sqlite_fastrand │ ├── datasette_sqlite_fastrand │ │ ├── version.py │ │ └── __init__.py │ ├── README.md │ ├── tests │ │ └── test_sqlite_fastrand.py │ └── setup.py ├── README.md └── .gitignore ├── bindings ├── ruby │ ├── .gitignore │ ├── Rakefile │ ├── lib │ │ ├── version.rb │ │ ├── version.rb.tmpl │ │ └── sqlite_fastrand.rb │ ├── Gemfile │ └── sqlite_fastrand.gemspec └── sqlite-utils │ ├── sqlite_utils_sqlite_fastrand │ ├── version.py │ ├── version.py.tmpl │ └── __init__.py │ ├── README.md │ ├── pyproject.toml │ ├── pyproject.toml.tmpl │ └── .gitignore ├── npm ├── sqlite-fastrand-darwin-x64 │ ├── lib │ │ └── .gitkeep │ ├── package.json │ └── README.md ├── sqlite-fastrand-linux-x64 │ ├── lib │ │ └── .gitkeep │ ├── package.json │ └── README.md ├── sqlite-fastrand-darwin-arm64 │ ├── lib │ │ └── .gitkeep │ ├── package.json │ └── README.md ├── sqlite-fastrand-windows-x64 │ ├── lib │ │ └── .gitkeep │ ├── package.json │ └── README.md ├── README.md ├── platform-package.package.json.tmpl ├── platform-package.README.md.tmpl ├── sqlite-fastrand │ ├── package.json │ ├── package.json.tmpl │ ├── test.js │ ├── src │ │ └── index.js │ └── README.md └── .gitignore ├── .gitignore ├── deno ├── deno.json ├── deno.json.tmpl ├── test.ts ├── README.md ├── README.md.tmpl ├── mod.ts └── deno.lock ├── scripts ├── deno_generate_package.sh ├── publish_release.sh └── npm_generate_platform_packages.sh ├── tests ├── test-python.py └── test-loadable.py ├── bench.sh ├── Cargo.toml ├── LICENSE-MIT ├── .github └── workflows │ ├── upload-deno-assets.js │ ├── rename-wheels.py │ ├── test.yaml │ └── release.yaml ├── test.sql ├── docs.md ├── Makefile ├── README.md ├── LICENSE-APACHE └── src └── lib.rs /VERSION: -------------------------------------------------------------------------------- 1 | 0.2.1 -------------------------------------------------------------------------------- /python/sqlite_fastrand/noop.c: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /bindings/ruby/.gitignore: -------------------------------------------------------------------------------- 1 | *.gem 2 | -------------------------------------------------------------------------------- /npm/sqlite-fastrand-darwin-x64/lib/.gitkeep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /npm/sqlite-fastrand-linux-x64/lib/.gitkeep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /npm/sqlite-fastrand-darwin-arm64/lib/.gitkeep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /npm/sqlite-fastrand-windows-x64/lib/.gitkeep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /bindings/ruby/Rakefile: -------------------------------------------------------------------------------- 1 | require "bundler/gem_tasks" 2 | task :default => :spec 3 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | /Cargo.lock 3 | billion/ 4 | dist/ 5 | *.dylib 6 | *.so 7 | *.dll 8 | 9 | -------------------------------------------------------------------------------- /python/sqlite_fastrand/sqlite_fastrand/version.py: -------------------------------------------------------------------------------- 1 | __version__ = "0.2.1" 2 | __version_info__ = tuple(__version__.split(".")) 3 | -------------------------------------------------------------------------------- /bindings/ruby/lib/version.rb: -------------------------------------------------------------------------------- 1 | # automatically generated, do not edit by hand. 2 | module SqliteFastrand 3 | VERSION = "0.2.1" 4 | end 5 | -------------------------------------------------------------------------------- /bindings/sqlite-utils/sqlite_utils_sqlite_fastrand/version.py: -------------------------------------------------------------------------------- 1 | __version__ = "0.2.1" 2 | __version_info__ = tuple(__version__.split(".")) 3 | -------------------------------------------------------------------------------- /bindings/ruby/lib/version.rb.tmpl: -------------------------------------------------------------------------------- 1 | # automatically generated, do not edit by hand. 2 | module SqliteFastrand 3 | VERSION = "${VERSION}" 4 | end 5 | -------------------------------------------------------------------------------- /python/datasette_sqlite_fastrand/datasette_sqlite_fastrand/version.py: -------------------------------------------------------------------------------- 1 | __version__ = "0.2.1" 2 | __version_info__ = tuple(__version__.split(".")) 3 | -------------------------------------------------------------------------------- /bindings/ruby/Gemfile: -------------------------------------------------------------------------------- 1 | source "https://rubygems.org" 2 | 3 | git_source(:github) {|repo_name| "https://github.com/#{repo_name}" } 4 | 5 | gemspec 6 | -------------------------------------------------------------------------------- /bindings/sqlite-utils/README.md: -------------------------------------------------------------------------------- 1 | # `sqlite-utils-sqlite-fastrand` 2 | 3 | A `sqlite-utils` plugin that registers the `sqlite-fastrand` extension. 4 | -------------------------------------------------------------------------------- /bindings/sqlite-utils/sqlite_utils_sqlite_fastrand/version.py.tmpl: -------------------------------------------------------------------------------- 1 | __version__ = "${VERSION}" 2 | __version_info__ = tuple(__version__.split(".")) 3 | -------------------------------------------------------------------------------- /deno/deno.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "sqlite-fastrand", 3 | "version": "0.2.1", 4 | "github": "https://github.com/asg017/sqlite-fastrand", 5 | "tasks": { 6 | "test": "deno test --unstable -A test.ts" 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /deno/deno.json.tmpl: -------------------------------------------------------------------------------- 1 | { 2 | "name": "sqlite-fastrand", 3 | "version": "${VERSION}", 4 | "github": "https://github.com/asg017/${PACKAGE_NAME}", 5 | "tasks": { 6 | "test": "deno test --unstable -A test.ts" 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /bindings/ruby/lib/sqlite_fastrand.rb: -------------------------------------------------------------------------------- 1 | require "version" 2 | 3 | module SqliteFastrand 4 | class Error < StandardError; end 5 | def self.fastrand_loadable_path 6 | File.expand_path('../fastrand0', __FILE__) 7 | end 8 | def self.load(db) 9 | db.load_extension(self.fastrand_loadable_path) 10 | end 11 | end 12 | -------------------------------------------------------------------------------- /python/datasette_sqlite_fastrand/datasette_sqlite_fastrand/__init__.py: -------------------------------------------------------------------------------- 1 | from datasette import hookimpl 2 | import sqlite_fastrand 3 | 4 | from datasette_sqlite_fastrand.version import __version_info__, __version__ 5 | 6 | @hookimpl 7 | def prepare_connection(conn): 8 | conn.enable_load_extension(True) 9 | sqlite_fastrand.load(conn) 10 | conn.enable_load_extension(False) -------------------------------------------------------------------------------- /scripts/deno_generate_package.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | set -euo pipefail 4 | 5 | export PACKAGE_NAME="sqlite-fastrand" 6 | export EXTENSION_NAME="fastrand0" 7 | export VERSION=$(cat VERSION) 8 | 9 | envsubst < deno/deno.json.tmpl > deno/deno.json 10 | echo "✅ generated deno/deno.json" 11 | 12 | envsubst < deno/README.md.tmpl > deno/README.md 13 | echo "✅ generated deno/README.md" 14 | -------------------------------------------------------------------------------- /bindings/sqlite-utils/sqlite_utils_sqlite_fastrand/__init__.py: -------------------------------------------------------------------------------- 1 | from sqlite_utils import hookimpl 2 | import sqlite_fastrand 3 | 4 | from sqlite_utils_sqlite_fastrand.version import __version_info__, __version__ 5 | 6 | 7 | @hookimpl 8 | def prepare_connection(conn): 9 | conn.enable_load_extension(True) 10 | sqlite_fastrand.load(conn) 11 | conn.enable_load_extension(False) 12 | -------------------------------------------------------------------------------- /python/sqlite_fastrand/sqlite_fastrand/__init__.py: -------------------------------------------------------------------------------- 1 | import os 2 | import sqlite3 3 | 4 | from sqlite_fastrand.version import __version_info__, __version__ 5 | 6 | def loadable_path(): 7 | loadable_path = os.path.join(os.path.dirname(__file__), "fastrand0") 8 | return os.path.normpath(loadable_path) 9 | 10 | def load(conn: sqlite3.Connection) -> None: 11 | conn.load_extension(loadable_path()) 12 | -------------------------------------------------------------------------------- /npm/README.md: -------------------------------------------------------------------------------- 1 | # sqlite-fastrand on npm 2 | 3 | `sqlite-fastrand` is also available for download through [`npm`](https://www.npmjs.com/) for Node.js developers. See the [`sqlite-fastrand` NPM package README](./sqlite-fastrand/README.md) for details. 4 | 5 | The other NPM packages in this folder (`sqlite-fastrand-darwin-x64`, `sqlite-fastrand-windows-x64` etc.) are autogenerated platform-specific packages. See [Supported Platforms](./sqlite-fastrand/README.md#supported-platforms) for details. 6 | -------------------------------------------------------------------------------- /npm/sqlite-fastrand-linux-x64/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "//": "Autogenerated by the npm_generate_platform_packages.sh script, do not edit by hand", 3 | "name": "sqlite-fastrand-linux-x64", 4 | "version": "0.2.1", 5 | "repository": { 6 | "type": "git", 7 | "url": "https://github.com/asg017/sqlite-fastrand.git", 8 | "directory": "npm/sqlite-fastrand-linux-x64" 9 | }, 10 | "author": "Alex Garcia ", 11 | "os": [ 12 | "linux" 13 | ], 14 | "cpu": [ 15 | "x64" 16 | ] 17 | } -------------------------------------------------------------------------------- /npm/platform-package.package.json.tmpl: -------------------------------------------------------------------------------- 1 | { 2 | "//": "Autogenerated by the npm_generate_platform_packages.sh script, do not edit by hand", 3 | "name": "${PACKAGE_NAME}", 4 | "version": "${VERSION}", 5 | "repository": { 6 | "type": "git", 7 | "url": "https://github.com/asg017/${PACKAGE_NAME_BASE}.git", 8 | "directory": "npm/${PACKAGE_NAME}" 9 | }, 10 | "author": "Alex Garcia ", 11 | "os": [ 12 | "${PLATFORM_OS}" 13 | ], 14 | "cpu": [ 15 | "${PLATFORM_ARCH}" 16 | ] 17 | } -------------------------------------------------------------------------------- /npm/sqlite-fastrand-darwin-x64/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "//": "Autogenerated by the npm_generate_platform_packages.sh script, do not edit by hand", 3 | "name": "sqlite-fastrand-darwin-x64", 4 | "version": "0.2.1", 5 | "repository": { 6 | "type": "git", 7 | "url": "https://github.com/asg017/sqlite-fastrand.git", 8 | "directory": "npm/sqlite-fastrand-darwin-x64" 9 | }, 10 | "author": "Alex Garcia ", 11 | "os": [ 12 | "darwin" 13 | ], 14 | "cpu": [ 15 | "x64" 16 | ] 17 | } -------------------------------------------------------------------------------- /npm/sqlite-fastrand-windows-x64/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "//": "Autogenerated by the npm_generate_platform_packages.sh script, do not edit by hand", 3 | "name": "sqlite-fastrand-windows-x64", 4 | "version": "0.2.1", 5 | "repository": { 6 | "type": "git", 7 | "url": "https://github.com/asg017/sqlite-fastrand.git", 8 | "directory": "npm/sqlite-fastrand-windows-x64" 9 | }, 10 | "author": "Alex Garcia ", 11 | "os": [ 12 | "windows" 13 | ], 14 | "cpu": [ 15 | "x64" 16 | ] 17 | } -------------------------------------------------------------------------------- /tests/test-python.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | import sqlite3 3 | import sqlite_fastrand 4 | 5 | class TestSqlitefastrandPython(unittest.TestCase): 6 | def test_path(self): 7 | db = sqlite3.connect(':memory:') 8 | db.enable_load_extension(True) 9 | 10 | self.assertEqual(type(sqlite_fastrand.loadable_path()), str) 11 | 12 | sqlite_fastrand.load(db) 13 | version, = db.execute('select fastrand_version()').fetchone() 14 | self.assertEqual(version[0], "v") 15 | 16 | if __name__ == '__main__': 17 | unittest.main() -------------------------------------------------------------------------------- /npm/sqlite-fastrand-darwin-arm64/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "//": "Autogenerated by the npm_generate_platform_packages.sh script, do not edit by hand", 3 | "name": "sqlite-fastrand-darwin-arm64", 4 | "version": "0.2.1", 5 | "repository": { 6 | "type": "git", 7 | "url": "https://github.com/asg017/sqlite-fastrand.git", 8 | "directory": "npm/sqlite-fastrand-darwin-arm64" 9 | }, 10 | "author": "Alex Garcia ", 11 | "os": [ 12 | "darwin" 13 | ], 14 | "cpu": [ 15 | "arm64" 16 | ] 17 | } -------------------------------------------------------------------------------- /bench.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | END=1e6 4 | 5 | hyperfine --warmup=10 \ 6 | "sqlite3 :memory: 'select count(random()) from generate_series(1, $END);'" \ 7 | "sqlite3 :memory: '.load dist/release/fastrand0' 'select count(fastrand_int64()) from generate_series(1, $END);'" 8 | 9 | 10 | END=1e5 11 | LENGTH=1024 12 | hyperfine --warmup=10 \ 13 | "sqlite3 :memory: 'select count(randomblob($LENGTH)) from generate_series(1, $END);'" \ 14 | "sqlite3 :memory: '.load target/release/libfastrand0' 'select count(fastrand_blob($LENGTH)) from generate_series(1, $END);'" -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "sqlite-fastrand" 3 | version = "0.2.1" 4 | edition = "2021" 5 | authors = ["Alex Garcia "] 6 | description = "A SQLite extension for generating numbers and blobs very quickly" 7 | homepage = "https://github.com/asg017/sqlite-fastrand" 8 | repository = "https://github.com/asg017/sqlite-fastrand" 9 | keywords = ["sqlite", "sqlite-extension"] 10 | license = "MIT/Apache-2.0" 11 | 12 | [dependencies] 13 | sqlite-loadable = "0.0.5" 14 | fastrand = "1.8.0" 15 | 16 | [lib] 17 | crate-type=["lib", "staticlib", "cdylib"] 18 | -------------------------------------------------------------------------------- /python/README.md: -------------------------------------------------------------------------------- 1 | # `sqlite-fastrand` Python Packages 2 | 3 | The `sqlite-fastrand` project offers two python packages for easy distribution. They are: 4 | 5 | 1. The [`sqlite-fastrand` Python package](https://pypi.org/project/sqlite-fastrand/), source in [`sqlite_fastrand/`](./sqlite_fastrand/README.md) 6 | 2. The [`datasette-sqlite-fastrand` Python package](https://pypi.org/project/sqlite-fastrand/), a [Datasette](https://datasette.io/) plugin,which is a light wrapper around the `sqlite-fastrand` package, source in [`datasette_sqlite_fastrand/`](./datasette_sqlite_fastrand/README.md) 7 | -------------------------------------------------------------------------------- /bindings/sqlite-utils/pyproject.toml: -------------------------------------------------------------------------------- 1 | [project] 2 | name = "sqlite-utils-sqlite-fastrand" 3 | version = "0.2.1" 4 | description = "TODO" 5 | readme = "README.md" 6 | authors = [{name = "Alex Garcia"}] 7 | license = {text = "Apache-2.0"} 8 | classifiers = [] 9 | 10 | dependencies = [ 11 | "sqlite-utils", 12 | "sqlite-fastrand" 13 | ] 14 | 15 | [project.urls] 16 | Homepage = "https://github.com/asg017/sqlite-fastrand" 17 | Changelog = "https://github.com/asg017/sqlite-fastrand/releases" 18 | Issues = "https://github.com/asg017/sqlite-fastrand/issues" 19 | 20 | [project.entry-points.sqlite_utils] 21 | sqlite_fastrand = "sqlite_utils_sqlite_fastrand" 22 | -------------------------------------------------------------------------------- /deno/test.ts: -------------------------------------------------------------------------------- 1 | import * as sqlite_fastrand from "./mod.ts"; 2 | import meta from "./deno.json" assert { type: "json" }; 3 | 4 | import { assertEquals } from "https://deno.land/std@0.177.0/testing/asserts.ts"; 5 | import { Database } from "https://deno.land/x/sqlite3@0.8.0/mod.ts"; 6 | 7 | Deno.test("x/sqlite3", (t) => { 8 | const db = new Database(":memory:"); 9 | 10 | db.enableLoadExtension = true; 11 | sqlite_fastrand.load(db); 12 | 13 | const [version] = db.prepare("select fastrand_version()").value<[string]>()!; 14 | 15 | assertEquals(version[0], "v"); 16 | assertEquals(version.substring(1), meta.version); 17 | 18 | db.close(); 19 | }); 20 | -------------------------------------------------------------------------------- /bindings/sqlite-utils/pyproject.toml.tmpl: -------------------------------------------------------------------------------- 1 | [project] 2 | name = "sqlite-utils-sqlite-fastrand" 3 | version = "${VERSION}" 4 | description = "TODO" 5 | readme = "README.md" 6 | authors = [{name = "Alex Garcia"}] 7 | license = {text = "Apache-2.0"} 8 | classifiers = [] 9 | 10 | dependencies = [ 11 | "sqlite-utils", 12 | "sqlite-fastrand" 13 | ] 14 | 15 | [project.urls] 16 | Homepage = "https://github.com/asg017/sqlite-fastrand" 17 | Changelog = "https://github.com/asg017/sqlite-fastrand/releases" 18 | Issues = "https://github.com/asg017/sqlite-fastrand/issues" 19 | 20 | [project.entry-points.sqlite_utils] 21 | sqlite_fastrand = "sqlite_utils_sqlite_fastrand" 22 | -------------------------------------------------------------------------------- /scripts/publish_release.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | set -euo pipefail xtrace 4 | 5 | if [[ -n $(git status --porcelain | grep -v VERSION) ]]; then 6 | echo "❌ There are other un-staged changes to the repository besides VERSION" 7 | exit 1 8 | fi 9 | 10 | VERSION="$(cat VERSION)" 11 | 12 | echo "Publishing version v$VERSION..." 13 | 14 | make version 15 | git add --all 16 | git commit -m "v$VERSION" 17 | git tag v$VERSION 18 | git push origin main v$VERSION 19 | 20 | if grep -qE "alpha|beta" VERSION; then 21 | gh release create v$VERSION --title=v$VERSION --prerelease --notes="" 22 | else 23 | gh release create v$VERSION --title=v$VERSION 24 | fi 25 | 26 | 27 | echo "✅ Published! version v$VERSION" 28 | -------------------------------------------------------------------------------- /npm/sqlite-fastrand-linux-x64/README.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | # sqlite-fastrand-linux-x64 4 | 5 | A `sqlite-fastrand` platform-specific package for `linux-x64`. 6 | 7 | When `sqlite-fastrand` is installed and the host computer has a `linux` operating system with `x64` architecture, then this package is downloaded with the pre-compiled SQLite extension bundled under `lib/fastrand0.so`. At runtime, the `sqlite-fastrand` package will resolve to this platform-specific package for use with [`better-sqlite3`](https://github.com/WiseLibs/better-sqlite3)' or [`node-sqlite3`](https://github.com/TryGhost/node-sqlite3). 8 | 9 | See the `sqlite-fastrand` package for more details. -------------------------------------------------------------------------------- /npm/sqlite-fastrand-darwin-x64/README.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | # sqlite-fastrand-darwin-x64 4 | 5 | A `sqlite-fastrand` platform-specific package for `darwin-x64`. 6 | 7 | When `sqlite-fastrand` is installed and the host computer has a `darwin` operating system with `x64` architecture, then this package is downloaded with the pre-compiled SQLite extension bundled under `lib/fastrand0.dylib`. At runtime, the `sqlite-fastrand` package will resolve to this platform-specific package for use with [`better-sqlite3`](https://github.com/WiseLibs/better-sqlite3)' or [`node-sqlite3`](https://github.com/TryGhost/node-sqlite3). 8 | 9 | See the `sqlite-fastrand` package for more details. -------------------------------------------------------------------------------- /npm/sqlite-fastrand-windows-x64/README.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | # sqlite-fastrand-windows-x64 4 | 5 | A `sqlite-fastrand` platform-specific package for `windows-x64`. 6 | 7 | When `sqlite-fastrand` is installed and the host computer has a `windows` operating system with `x64` architecture, then this package is downloaded with the pre-compiled SQLite extension bundled under `lib/fastrand0.dll`. At runtime, the `sqlite-fastrand` package will resolve to this platform-specific package for use with [`better-sqlite3`](https://github.com/WiseLibs/better-sqlite3)' or [`node-sqlite3`](https://github.com/TryGhost/node-sqlite3). 8 | 9 | See the `sqlite-fastrand` package for more details. -------------------------------------------------------------------------------- /npm/sqlite-fastrand-darwin-arm64/README.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | # sqlite-fastrand-darwin-arm64 4 | 5 | A `sqlite-fastrand` platform-specific package for `darwin-arm64`. 6 | 7 | When `sqlite-fastrand` is installed and the host computer has a `darwin` operating system with `arm64` architecture, then this package is downloaded with the pre-compiled SQLite extension bundled under `lib/fastrand0.dylib`. At runtime, the `sqlite-fastrand` package will resolve to this platform-specific package for use with [`better-sqlite3`](https://github.com/WiseLibs/better-sqlite3)' or [`node-sqlite3`](https://github.com/TryGhost/node-sqlite3). 8 | 9 | See the `sqlite-fastrand` package for more details. -------------------------------------------------------------------------------- /npm/platform-package.README.md.tmpl: -------------------------------------------------------------------------------- 1 | 2 | 3 | # ${PACKAGE_NAME} 4 | 5 | A `${PACKAGE_NAME_BASE}` platform-specific package for `${PLATFORM_OS}-${PLATFORM_ARCH}`. 6 | 7 | When `${PACKAGE_NAME_BASE}` is installed and the host computer has a `${PLATFORM_OS}` operating system with `${PLATFORM_ARCH}` architecture, then this package is downloaded with the pre-compiled SQLite extension bundled under `lib/${EXTENSION_NAME}.${EXTENSION_SUFFIX}`. At runtime, the `${PACKAGE_NAME_BASE}` package will resolve to this platform-specific package for use with [`better-sqlite3`](https://github.com/WiseLibs/better-sqlite3)' or [`node-sqlite3`](https://github.com/TryGhost/node-sqlite3). 8 | 9 | See the `${PACKAGE_NAME_BASE}` package for more details. -------------------------------------------------------------------------------- /python/datasette_sqlite_fastrand/README.md: -------------------------------------------------------------------------------- 1 | # The `datasette-sqlite-fastrand` Datasette Plugin 2 | 3 | `datasette-sqlite-fastrand` is a [Datasette plugin](https://docs.datasette.io/en/stable/plugins.html) that loads the [`sqlite-fastrand`](https://github.com/asg017/sqlite-fastrand) extension in Datasette instances, allowing you to generate and work with [fastrands](https://github.com/fastrand/spec) in SQL. 4 | 5 | ``` 6 | datasette install datasette-sqlite-fastrand 7 | ``` 8 | 9 | See [`docs.md`](../../docs.md) for a full API reference for the fastrand SQL functions. 10 | 11 | Alternatively, when publishing Datasette instances, you can use the `--install` option to install the plugin. 12 | 13 | ``` 14 | datasette publish cloudrun data.db --service=my-service --install=datasette-sqlite-fastrand 15 | 16 | ``` 17 | -------------------------------------------------------------------------------- /python/datasette_sqlite_fastrand/tests/test_sqlite_fastrand.py: -------------------------------------------------------------------------------- 1 | from datasette.app import Datasette 2 | import pytest 3 | 4 | 5 | @pytest.mark.asyncio 6 | async def test_plugin_is_installed(): 7 | datasette = Datasette(memory=True) 8 | response = await datasette.client.get("/-/plugins.json") 9 | assert response.status_code == 200 10 | installed_plugins = {p["name"] for p in response.json()} 11 | assert "datasette-sqlite-fastrand" in installed_plugins 12 | 13 | @pytest.mark.asyncio 14 | async def test_sqlite_fastrand_functions(): 15 | datasette = Datasette(memory=True) 16 | response = await datasette.client.get("/_memory.json?sql=select+fastrand_version(),fastrand()") 17 | assert response.status_code == 200 18 | fastrand_version, fastrand = response.json()["rows"][0] 19 | assert fastrand_version[0] == "v" 20 | assert len(fastrand) == 26 -------------------------------------------------------------------------------- /npm/sqlite-fastrand/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "//": "Autogenerated by the npm_generate_platform_packages.sh script, do not edit by hand", 3 | "name": "sqlite-fastrand", 4 | "version": "0.2.1", 5 | "description": "", 6 | "repository": { 7 | "type": "git", 8 | "url": "https://github.com/asg017/sqlite-fastrand.git", 9 | "directory": "npm/sqlite-fastrand" 10 | }, 11 | "author": "Alex Garcia ", 12 | "license": "(MIT OR Apache-2.0)", 13 | "main": "src/index.js", 14 | "type": "module", 15 | "scripts": { 16 | "test": "node test.js" 17 | }, 18 | "files": [ 19 | "*.dylib", 20 | "*.so", 21 | "*.dll" 22 | ], 23 | "optionalDependencies": { 24 | "sqlite-fastrand-darwin-arm64": "0.2.1", 25 | "sqlite-fastrand-darwin-x64": "0.2.1", 26 | "sqlite-fastrand-linux-x64": "0.2.1", 27 | "sqlite-fastrand-windows-x64": "0.2.1" 28 | }, 29 | "devDependencies": { 30 | "better-sqlite3": "^8.1.0", 31 | "sqlite3": "^5.1.4" 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /npm/sqlite-fastrand/package.json.tmpl: -------------------------------------------------------------------------------- 1 | { 2 | "//": "Autogenerated by the npm_generate_platform_packages.sh script, do not edit by hand", 3 | "name": "${PACKAGE_NAME_BASE}", 4 | "version": "${VERSION}", 5 | "description": "", 6 | "repository": { 7 | "type": "git", 8 | "url": "https://github.com/asg017/${PACKAGE_NAME_BASE}.git", 9 | "directory": "npm/${PACKAGE_NAME_BASE}" 10 | }, 11 | "author": "Alex Garcia ", 12 | "license": "(MIT OR Apache-2.0)", 13 | "main": "src/index.js", 14 | "type": "module", 15 | "scripts": { 16 | "test": "node test.js" 17 | }, 18 | "files": [ 19 | "*.dylib", 20 | "*.so", 21 | "*.dll" 22 | ], 23 | "optionalDependencies": { 24 | "sqlite-fastrand-darwin-arm64": "${VERSION}", 25 | "sqlite-fastrand-darwin-x64": "${VERSION}", 26 | "sqlite-fastrand-linux-x64": "${VERSION}", 27 | "sqlite-fastrand-windows-x64": "${VERSION}" 28 | }, 29 | "devDependencies": { 30 | "better-sqlite3": "^8.1.0", 31 | "sqlite3": "^5.1.4" 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /python/datasette_sqlite_fastrand/setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import setup 2 | 3 | version = {} 4 | with open("datasette_sqlite_fastrand/version.py") as fp: 5 | exec(fp.read(), version) 6 | 7 | VERSION = version['__version__'] 8 | 9 | 10 | setup( 11 | name="datasette-sqlite-fastrand", 12 | description="", 13 | long_description="", 14 | long_description_content_type="text/markdown", 15 | author="Alex Garcia", 16 | url="https://github.com/asg017/sqlite-fastrand", 17 | project_urls={ 18 | "Issues": "https://github.com/asg017/sqlite-fastrand/issues", 19 | "CI": "https://github.com/asg017/sqlite-fastrand/actions", 20 | "Changelog": "https://github.com/asg017/sqlite-fastrand/releases", 21 | }, 22 | license="MIT License, Apache License, Version 2.0", 23 | version=VERSION, 24 | packages=["datasette_sqlite_fastrand"], 25 | entry_points={"datasette": ["sqlite_fastrand = datasette_sqlite_fastrand"]}, 26 | install_requires=["datasette", "sqlite-fastrand"], 27 | extras_require={"test": ["pytest"]}, 28 | python_requires=">=3.7", 29 | ) -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2023 Alex Garcia 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /scripts/npm_generate_platform_packages.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | set -euo pipefail 4 | 5 | export PACKAGE_NAME_BASE="sqlite-fastrand" 6 | export EXTENSION_NAME="fastrand0" 7 | export VERSION=$(cat VERSION) 8 | 9 | generate () { 10 | export PLATFORM_OS=$1 11 | export PLATFORM_ARCH=$2 12 | export PACKAGE_NAME=$PACKAGE_NAME_BASE-$PLATFORM_OS-$PLATFORM_ARCH 13 | 14 | if [ "$PLATFORM_OS" == "windows" ]; then 15 | export EXTENSION_SUFFIX="dll" 16 | elif [ "$PLATFORM_OS" == "darwin" ]; then 17 | export EXTENSION_SUFFIX="dylib" 18 | else 19 | export EXTENSION_SUFFIX="so" 20 | fi 21 | 22 | 23 | mkdir -p npm/$PACKAGE_NAME/lib 24 | 25 | envsubst < npm/platform-package.package.json.tmpl > npm/$PACKAGE_NAME/package.json 26 | envsubst < npm/platform-package.README.md.tmpl > npm/$PACKAGE_NAME/README.md 27 | 28 | touch npm/$PACKAGE_NAME/lib/.gitkeep 29 | 30 | echo "✅ generated npm/$PACKAGE_NAME" 31 | } 32 | 33 | envsubst < npm/$PACKAGE_NAME_BASE/package.json.tmpl > npm/$PACKAGE_NAME_BASE/package.json 34 | echo "✅ generated npm/$PACKAGE_NAME_BASE" 35 | 36 | generate darwin x64 37 | generate darwin arm64 38 | generate linux x64 39 | generate windows x64 -------------------------------------------------------------------------------- /npm/sqlite-fastrand/test.js: -------------------------------------------------------------------------------- 1 | import test from "node:test"; 2 | import * as assert from "node:assert"; 3 | 4 | import { getLoadablePath } from "./src/index.js"; 5 | import { basename, extname, isAbsolute } from "node:path"; 6 | 7 | import Database from "better-sqlite3"; 8 | import sqlite3 from "sqlite3"; 9 | 10 | test("getLoadblePath()", (t) => { 11 | const loadablePath = getLoadablePath(); 12 | assert.strictEqual(isAbsolute(loadablePath), true); 13 | assert.strictEqual( 14 | basename(loadablePath, extname(loadablePath)), 15 | "fastrand0" 16 | ); 17 | }); 18 | 19 | test("better-sqlite3", (t) => { 20 | const db = new Database(":memory:"); 21 | db.loadExtension(getLoadablePath()); 22 | const version = db.prepare("select fastrand_version()").pluck().get(); 23 | assert.strictEqual(version[0], "v"); 24 | }); 25 | 26 | test("sqlite3", async (t) => { 27 | const db = new sqlite3.Database(":memory:"); 28 | db.loadExtension(getLoadablePath()); 29 | let version = await new Promise((resolve, reject) => { 30 | db.get("select fastrand_version()", (err, row) => { 31 | if (err) return reject(err); 32 | resolve(row["fastrand_version()"]); 33 | }); 34 | }); 35 | assert.strictEqual(version[0], "v"); 36 | }); 37 | -------------------------------------------------------------------------------- /.github/workflows/upload-deno-assets.js: -------------------------------------------------------------------------------- 1 | const fs = require("fs").promises; 2 | 3 | module.exports = async ({ github, context }) => { 4 | const { 5 | repo: { owner, repo }, 6 | sha, 7 | } = context; 8 | console.log(process.env.GITHUB_REF); 9 | const release = await github.rest.repos.getReleaseByTag({ 10 | owner, 11 | repo, 12 | tag: process.env.GITHUB_REF.replace("refs/tags/", ""), 13 | }); 14 | console.log("release id: ", release.data.id); 15 | const release_id = release.data.id; 16 | 17 | const compiled_extensions = [ 18 | { 19 | path: "sqlite-fastrand-macos-arm/fastrand0.dylib", 20 | name: "deno-darwin-aarch64.fastrand0.dylib", 21 | }, 22 | { 23 | path: "sqlite-fastrand-macos/fastrand0.dylib", 24 | name: "deno-darwin-x86_64.fastrand0.dylib", 25 | }, 26 | { 27 | path: "sqlite-fastrand-ubuntu/fastrand0.so", 28 | name: "deno-linux-x86_64.fastrand0.so", 29 | }, 30 | { 31 | path: "sqlite-fastrand-windows/fastrand0.dll", 32 | name: "deno-windows-x86_64.fastrand0.dll", 33 | }, 34 | ]; 35 | await Promise.all( 36 | compiled_extensions.map(async ({ name, path }) => { 37 | return github.rest.repos.uploadReleaseAsset({ 38 | owner, 39 | repo, 40 | release_id, 41 | name, 42 | data: await fs.readFile(path), 43 | }); 44 | }) 45 | ); 46 | }; 47 | -------------------------------------------------------------------------------- /bindings/ruby/sqlite_fastrand.gemspec: -------------------------------------------------------------------------------- 1 | 2 | lib = File.expand_path("../lib", __FILE__) 3 | $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) 4 | require "version" 5 | 6 | Gem::Specification.new do |spec| 7 | spec.name = "sqlite-fastrand" 8 | spec.version = SqliteFastrand::VERSION 9 | spec.authors = ["Alex Garcia"] 10 | spec.email = ["alexsebastian.garcia@gmail.com"] 11 | 12 | spec.summary = "a" 13 | spec.description = "b" 14 | spec.homepage = "https://github.com/asg017/sqlite-fastrand" 15 | spec.license = "MIT" 16 | 17 | # The --platform flag would work in most cases, but on a GH action 18 | # linux runner, it would set platform to "ruby" and not "x86-linux". 19 | # Setting this to Gem::Platform::CURRENT 20 | spec.platform = ENV['PLATFORM'] 21 | 22 | if spec.respond_to?(:metadata) 23 | 24 | spec.metadata["homepage_uri"] = spec.homepage 25 | spec.metadata["source_code_uri"] = spec.homepage 26 | spec.metadata["changelog_uri"] = spec.homepage 27 | else 28 | raise "RubyGems 2.0 or newer is required to protect against " \ 29 | "public gem pushes." 30 | end 31 | 32 | spec.files = Dir["lib/*.rb"] + Dir.glob('lib/*.{so,dylib,dll}') 33 | 34 | spec.require_paths = ["lib"] 35 | 36 | spec.add_development_dependency "bundler", "~> 1.17" 37 | spec.add_development_dependency "rake", "~> 10.0" 38 | end 39 | -------------------------------------------------------------------------------- /.github/workflows/rename-wheels.py: -------------------------------------------------------------------------------- 1 | # This file is a small utility that rename all .whl files in a given directory 2 | # and "generalizes" them. The wheels made by python/sqlite_fastrand contain the 3 | # pre-compiled sqlite extension, but those aren't bound by a specfic Python 4 | # runtime or version, that other wheels might be. So, this file will rename 5 | # those wheels to be "generalized", like replacing "c37-cp37" to "py3-none". 6 | import sys 7 | import os 8 | from pathlib import Path 9 | 10 | wheel_dir = sys.argv[1] 11 | 12 | is_macos_arm_build = '--is-macos-arm' in sys.argv 13 | 14 | for filename in os.listdir(wheel_dir): 15 | filename = Path(wheel_dir, filename) 16 | if not filename.suffix == '.whl': 17 | continue 18 | new_filename = (filename.name 19 | .replace('cp37-cp37', 'py3-none') 20 | .replace('cp38-cp38', 'py3-none') 21 | .replace('cp39-cp39', 'py3-none') 22 | .replace('cp310-cp310', 'py3-none') 23 | .replace('cp311-cp311', 'py3-none') 24 | .replace('linux_x86_64', 'manylinux_2_17_x86_64.manylinux2014_x86_64.manylinux1_x86_64') 25 | 26 | 27 | ) 28 | if is_macos_arm_build: 29 | new_filename = new_filename.replace('macosx_12_0_universal2', 'macosx_11_0_arm64') 30 | else: 31 | new_filename = (new_filename 32 | .replace('macosx_12_0_universal2', 'macosx_10_6_x86_64') 33 | .replace('macosx_12_0_x86_64', 'macosx_10_6_x86_64') 34 | ) 35 | 36 | os.rename(filename, Path(wheel_dir, new_filename)) -------------------------------------------------------------------------------- /deno/README.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | # `x/sqlite_fastrand` Deno Module 4 | 5 | [![Tags](https://img.shields.io/github/release/asg017/sqlite-fastrand)](https://github.com/asg017/sqlite-fastrand/releases) 6 | [![Doc](https://doc.deno.land/badge.svg)](https://doc.deno.land/https/deno.land/x/sqlite-fastrand@0.2.1/mod.ts) 7 | 8 | The [`sqlite-fastrand`](https://github.com/asg017/sqlite-fastrand) SQLite extension is available to Deno developers with the [`x/sqlite_fastrand`](https://deno.land/x/sqlite_fastrand) Deno module. It works with [`x/sqlite3`](https://deno.land/x/sqlite3), the fastest and native Deno SQLite3 module. 9 | 10 | ```js 11 | import { Database } from "https://deno.land/x/sqlite3@0.8.0/mod.ts"; 12 | import * as sqlite_fastrand from "https://deno.land/x/sqlite_fastrand@v0.2.1/mod.ts"; 13 | 14 | const db = new Database(":memory:"); 15 | 16 | db.enableLoadExtension = true; 17 | db.loadExtension(sqlite_fastrand.getLoadablePath()); 18 | 19 | const [version] = db 20 | .prepare("select fastrand_version()") 21 | .value<[string]>()!; 22 | 23 | console.log(version); 24 | 25 | ``` 26 | 27 | Like `x/sqlite3`, `x/sqlite_fastrand` requires network and filesystem permissions to download and cache the pre-compiled SQLite extension for your machine. Though `x/sqlite3` already requires `--allow-ffi` and `--unstable`, so you might as well use `--allow-all`/`-A`. 28 | 29 | ```bash 30 | deno run -A --unstable 31 | ``` 32 | 33 | `x/sqlite_fastrand` does not work with [`x/sqlite`](https://deno.land/x/sqlite@v3.7.0), which is a WASM-based Deno SQLite module that does not support loading extensions. 34 | -------------------------------------------------------------------------------- /deno/README.md.tmpl: -------------------------------------------------------------------------------- 1 | 2 | 3 | # `x/sqlite_fastrand` Deno Module 4 | 5 | [![Tags](https://img.shields.io/github/release/asg017/sqlite-fastrand)](https://github.com/asg017/sqlite-fastrand/releases) 6 | [![Doc](https://doc.deno.land/badge.svg)](https://doc.deno.land/https/deno.land/x/sqlite-fastrand@${VERSION}/mod.ts) 7 | 8 | The [`sqlite-fastrand`](https://github.com/asg017/sqlite-fastrand) SQLite extension is available to Deno developers with the [`x/sqlite_fastrand`](https://deno.land/x/sqlite_fastrand) Deno module. It works with [`x/sqlite3`](https://deno.land/x/sqlite3), the fastest and native Deno SQLite3 module. 9 | 10 | ```js 11 | import { Database } from "https://deno.land/x/sqlite3@0.8.0/mod.ts"; 12 | import * as sqlite_fastrand from "https://deno.land/x/sqlite_fastrand@v${VERSION}/mod.ts"; 13 | 14 | const db = new Database(":memory:"); 15 | 16 | db.enableLoadExtension = true; 17 | db.loadExtension(sqlite_fastrand.getLoadablePath()); 18 | 19 | const [version] = db 20 | .prepare("select fastrand_version()") 21 | .value<[string]>()!; 22 | 23 | console.log(version); 24 | 25 | ``` 26 | 27 | Like `x/sqlite3`, `x/sqlite_fastrand` requires network and filesystem permissions to download and cache the pre-compiled SQLite extension for your machine. Though `x/sqlite3` already requires `--allow-ffi` and `--unstable`, so you might as well use `--allow-all`/`-A`. 28 | 29 | ```bash 30 | deno run -A --unstable 31 | ``` 32 | 33 | `x/sqlite_fastrand` does not work with [`x/sqlite`](https://deno.land/x/sqlite@v3.7.0), which is a WASM-based Deno SQLite module that does not support loading extensions. 34 | -------------------------------------------------------------------------------- /test.sql: -------------------------------------------------------------------------------- 1 | .load target/debug/libfastrand0 2 | 3 | .header on 4 | .mode box 5 | .bail on 6 | 7 | select fastrand_bool(), fastrand_bool(); 8 | select fastrand_i32(), fastrand_i32(); 9 | select fastrand_i64(), fastrand_i64(); 10 | 11 | select fastrand_seed(); 12 | 13 | 14 | select fastrand_bool(), fastrand_bool(); 15 | 16 | select fastrand_char(), fastrand_char(); 17 | select fastrand_alphabetic(), fastrand_alphabetic(); 18 | select fastrand_alphanumeric(), fastrand_alphanumeric(); 19 | select fastrand_uppercase(), fastrand_uppercase(); 20 | select fastrand_lowercase(), fastrand_lowercase(); 21 | 22 | select fastrand_i8(), fastrand_i8(); 23 | select fastrand_u8(), fastrand_u8(); 24 | 25 | select fastrand_i16(), fastrand_i16(); 26 | select fastrand_u16(), fastrand_u16(); 27 | 28 | select fastrand_int(), fastrand_int(); 29 | select fastrand_i32(), fastrand_i32(); 30 | select fastrand_u32(), fastrand_u32(); 31 | 32 | select fastrand_int64(), fastrand_int64(); 33 | select fastrand_i64(), fastrand_i64(); 34 | select fastrand_u64(), fastrand_u64(); 35 | 36 | select fastrand_i128(), fastrand_i128(); 37 | select fastrand_u128(), fastrand_u128(); 38 | 39 | select fastrand_float(), fastrand_float(); 40 | select fastrand_f32(), fastrand_f32(); 41 | select fastrand_double(), fastrand_double(); 42 | select fastrand_f64(), fastrand_f64(); 43 | 44 | select fastrand_digit(1), fastrand_digit(2); 45 | select fastrand_seed(), fastrand_seed(); 46 | 47 | select length(fastrand_blob(20)), hex(fastrand_blob(8)); 48 | 49 | 50 | 51 | 52 | select fastrand_set_seed(0x400); 53 | select fastrand_int() == 881574422; 54 | select fastrand_int() == 654116233; 55 | 56 | select fastrand_set_seed(0x400); 57 | select fastrand_int() == 881574422; 58 | select fastrand_int() == 654116233; 59 | 60 | 61 | select fastrand_i8(1, 2); 62 | -------------------------------------------------------------------------------- /python/sqlite_fastrand/setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import setup, Extension 2 | import os 3 | import platform 4 | 5 | version = {} 6 | with open("sqlite_fastrand/version.py") as fp: 7 | exec(fp.read(), version) 8 | 9 | VERSION = version['__version__'] 10 | 11 | 12 | system = platform.system() 13 | machine = platform.machine() 14 | 15 | print(system, machine) 16 | 17 | if system == 'Darwin': 18 | if machine not in ['x86_64', 'arm64']: 19 | raise Exception("unsupported platform") 20 | elif system == 'Linux': 21 | if machine not in ['x86_64']: 22 | raise Exception("unsupported platform") 23 | elif system == 'Windows': 24 | # TODO only 64 bit I think 25 | pass 26 | else: 27 | raise Exception("unsupported platform") 28 | 29 | setup( 30 | name="sqlite-fastrand", 31 | description="", 32 | long_description="", 33 | long_description_content_type="text/markdown", 34 | author="Alex Garcia", 35 | url="https://github.com/asg017/sqlite-fastrand", 36 | project_urls={ 37 | "Issues": "https://github.com/asg017/sqlite-fastrand/issues", 38 | "CI": "https://github.com/asg017/sqlite-fastrand/actions", 39 | "Changelog": "https://github.com/asg017/sqlite-fastrand/releases", 40 | }, 41 | license="MIT License, Apache License, Version 2.0", 42 | version=VERSION, 43 | packages=["sqlite_fastrand"], 44 | package_data={"sqlite_fastrand": ['*.so', '*.dylib', '*.dll']}, 45 | install_requires=[], 46 | # Adding an Extension makes `pip wheel` believe that this isn't a 47 | # pure-python package. The noop.c was added since the windows build 48 | # didn't seem to respect optional=True 49 | ext_modules=[Extension("noop", ["noop.c"], optional=True)], 50 | extras_require={"test": ["pytest"]}, 51 | python_requires=">=3.7", 52 | ) -------------------------------------------------------------------------------- /npm/sqlite-fastrand/src/index.js: -------------------------------------------------------------------------------- 1 | import { join } from "node:path"; 2 | import { fileURLToPath } from "node:url"; 3 | import { arch, platform } from "node:process"; 4 | import { statSync } from "node:fs"; 5 | 6 | const supportedPlatforms = [ 7 | ["darwin", "x64"], 8 | ["darwin", "arm64"], 9 | ["win32", "x64"], 10 | ["linux", "x64"], 11 | ]; 12 | 13 | function validPlatform(platform, arch) { 14 | return ( 15 | supportedPlatforms.find(([p, a]) => platform == p && arch === a) !== null 16 | ); 17 | } 18 | function extensionSuffix(platform) { 19 | if (platform === "win32") return "dll"; 20 | if (platform === "darwin") return "dylib"; 21 | return "so"; 22 | } 23 | function platformPackageName(platform, arch) { 24 | const os = platform === "win32" ? "windows" : platform; 25 | return `sqlite-fastrand-${os}-${arch}`; 26 | } 27 | 28 | export function getLoadablePath() { 29 | if (!validPlatform(platform, arch)) { 30 | throw new Error( 31 | `Unsupported platform for sqlite-fastrand, on a ${platform}-${arch} machine, but not in supported platforms (${supportedPlatforms 32 | .map(([p, a]) => `${p}-${a}`) 33 | .join( 34 | "," 35 | )}). Consult the sqlite-fastrand NPM package README for details. ` 36 | ); 37 | } 38 | const packageName = platformPackageName(platform, arch); 39 | const loadablePath = join( 40 | fileURLToPath(new URL(".", import.meta.url)), 41 | "..", 42 | "..", 43 | packageName, 44 | "lib", 45 | `fastrand0.${extensionSuffix(platform)}` 46 | ); 47 | if (!statSync(loadablePath, { throwIfNoEntry: false })) { 48 | throw new Error( 49 | `Loadble extension for sqlite-fastrand not found. Was the ${packageName} package installed? Avoid using the --no-optional flag, as the optional dependencies for sqlite-fastrand are required.` 50 | ); 51 | } 52 | 53 | return loadablePath; 54 | } 55 | -------------------------------------------------------------------------------- /deno/mod.ts: -------------------------------------------------------------------------------- 1 | import { download } from "https://deno.land/x/plug@1.0.1/mod.ts"; 2 | import meta from "./deno.json" assert { type: "json" }; 3 | 4 | const BASE = `${meta.github}/releases/download/v${meta.version}`; 5 | 6 | // Similar to https://github.com/denodrivers/sqlite3/blob/f7529897720631c2341b713f0d78d4d668593ea9/src/ffi.ts#L561 7 | let path: string; 8 | try { 9 | const customPath = Deno.env.get("DENO_SQLITE_FASTRAND_PATH"); 10 | if (customPath) path = customPath; 11 | else { 12 | path = await download({ 13 | url: { 14 | darwin: { 15 | aarch64: `${BASE}/deno-darwin-aarch64.fastrand0.dylib`, 16 | x86_64: `${BASE}/deno-darwin-x86_64.fastrand0.dylib`, 17 | }, 18 | windows: { 19 | x86_64: `${BASE}/deno-windows-x86_64.fastrand0.dll`, 20 | }, 21 | linux: { 22 | x86_64: `${BASE}/deno-linux-x86_64.fastrand0.so`, 23 | }, 24 | }, 25 | suffixes: { 26 | darwin: "", 27 | linux: "", 28 | windows: "", 29 | }, 30 | }); 31 | } 32 | } catch (e) { 33 | if (e instanceof Deno.errors.PermissionDenied) { 34 | throw e; 35 | } 36 | 37 | const error = new Error("Failed to load sqlite-fastrand extension"); 38 | error.cause = e; 39 | 40 | throw error; 41 | } 42 | 43 | /** 44 | * Returns the full path to the compiled sqlite-fastrand extension. 45 | * Caution: this will not be named "fastrand0.dylib|so|dll", since plug will 46 | * replace the name with a hash. 47 | */ 48 | export function getLoadablePath(): string { 49 | return path; 50 | } 51 | 52 | /** 53 | * Entrypoint name for the sqlite-fastrand extension. 54 | */ 55 | export const entrypoint = "sqlite3_fastrand_init"; 56 | 57 | interface Db { 58 | // after https://deno.land/x/sqlite3@0.8.0/mod.ts?s=Database#method_loadExtension_0 59 | loadExtension(file: string, entrypoint?: string | undefined): void; 60 | } 61 | /** 62 | * Loads the sqlite-fastrand extension on the given sqlite3 database. 63 | */ 64 | export function load(db: Db): void { 65 | db.loadExtension(path, entrypoint); 66 | } 67 | -------------------------------------------------------------------------------- /npm/.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | yarn-debug.log* 6 | yarn-error.log* 7 | lerna-debug.log* 8 | .pnpm-debug.log* 9 | 10 | # Diagnostic reports (https://nodejs.org/api/report.html) 11 | report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json 12 | 13 | # Runtime data 14 | pids 15 | *.pid 16 | *.seed 17 | *.pid.lock 18 | 19 | # Directory for instrumented libs generated by jscoverage/JSCover 20 | lib-cov 21 | 22 | # Coverage directory used by tools like istanbul 23 | coverage 24 | *.lcov 25 | 26 | # nyc test coverage 27 | .nyc_output 28 | 29 | # Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) 30 | .grunt 31 | 32 | # Bower dependency directory (https://bower.io/) 33 | bower_components 34 | 35 | # node-waf configuration 36 | .lock-wscript 37 | 38 | # Compiled binary addons (https://nodejs.org/api/addons.html) 39 | build/Release 40 | 41 | # Dependency directories 42 | node_modules/ 43 | jspm_packages/ 44 | 45 | # Snowpack dependency directory (https://snowpack.dev/) 46 | web_modules/ 47 | 48 | # TypeScript cache 49 | *.tsbuildinfo 50 | 51 | # Optional npm cache directory 52 | .npm 53 | 54 | # Optional eslint cache 55 | .eslintcache 56 | 57 | # Optional stylelint cache 58 | .stylelintcache 59 | 60 | # Microbundle cache 61 | .rpt2_cache/ 62 | .rts2_cache_cjs/ 63 | .rts2_cache_es/ 64 | .rts2_cache_umd/ 65 | 66 | # Optional REPL history 67 | .node_repl_history 68 | 69 | # Output of 'npm pack' 70 | *.tgz 71 | 72 | # Yarn Integrity file 73 | .yarn-integrity 74 | 75 | # dotenv environment variable files 76 | .env 77 | .env.development.local 78 | .env.test.local 79 | .env.production.local 80 | .env.local 81 | 82 | # parcel-bundler cache (https://parceljs.org/) 83 | .cache 84 | .parcel-cache 85 | 86 | # Next.js build output 87 | .next 88 | out 89 | 90 | # Nuxt.js build / generate output 91 | .nuxt 92 | dist 93 | 94 | # Gatsby files 95 | .cache/ 96 | # Comment in the public line in if your project uses Gatsby and not Next.js 97 | # https://nextjs.org/blog/next-9-1#public-directory-support 98 | # public 99 | 100 | # vuepress build output 101 | .vuepress/dist 102 | 103 | # vuepress v2.x temp and cache directory 104 | .temp 105 | .cache 106 | 107 | # Docusaurus cache and generated files 108 | .docusaurus 109 | 110 | # Serverless directories 111 | .serverless/ 112 | 113 | # FuseBox cache 114 | .fusebox/ 115 | 116 | # DynamoDB Local files 117 | .dynamodb/ 118 | 119 | # TernJS port file 120 | .tern-port 121 | 122 | # Stores VSCode versions used for testing VSCode extensions 123 | .vscode-test 124 | 125 | # yarn v2 126 | .yarn/cache 127 | .yarn/unplugged 128 | .yarn/build-state.yml 129 | .yarn/install-state.gz 130 | .pnp.* 131 | 132 | # not needed for libraries, right? running into some issues in ci with this, so gonna yeet 133 | package-lock.json -------------------------------------------------------------------------------- /python/sqlite_fastrand/README.md: -------------------------------------------------------------------------------- 1 | # The `sqlite-fastrand` Python package 2 | 3 | `sqlite-fastrand` is also distributed on PyPi as a Python package, for use in Python applications. It works well with the builtin [`sqlite3`](https://docs.python.org/3/library/sqlite3.html) Python module. 4 | 5 | ``` 6 | pip install sqlite-fastrand 7 | ``` 8 | 9 | ## Usage 10 | 11 | The `sqlite-fastrand` python package exports two functions: `loadable_path()`, which returns the full path to the loadable extension, and `load(conn)`, which loads the `sqlite-fastrand` extension into the given [sqlite3 Connection object](https://docs.python.org/3/library/sqlite3.html#connection-objects). 12 | 13 | ```python 14 | import sqlite_fastrand 15 | print(sqlite_fastrand.loadable_path()) 16 | # '/.../venv/lib/python3.9/site-packages/sqlite_fastrand/fastrand0' 17 | 18 | import sqlite3 19 | conn = sqlite3.connect(':memory:') 20 | sqlite_fastrand.load(conn) 21 | conn.execute('select fastrand_version(), fastrand()').fetchone() 22 | # ('v0.1.0', '01gr7gwc5aq22ycea6j8kxq4s9') 23 | ``` 24 | 25 | See [the full API Reference](#api-reference) for the Python API, and [`docs.md`](../../docs.md) for documentation on the `sqlite-fastrand` SQL API. 26 | 27 | See [`datasette-sqlite-fastrand`](../datasette_sqlite_fastrand/) for a Datasette plugin that is a light wrapper around the `sqlite-fastrand` Python package. 28 | 29 | ## Compatibility 30 | 31 | Currently the `sqlite-fastrand` Python package is only distributed on PyPi as pre-build wheels, it's not possible to install from the source distribution. This is because the underlying `sqlite-fastrand` extension requires a lot of build dependencies like `make`, `cc`, and `cargo`. 32 | 33 | If you get a `unsupported platform` error when pip installing `sqlite-fastrand`, you'll have to build the `sqlite-fastrand` manually and load in the dynamic library manually. 34 | 35 | ## API Reference 36 | 37 |

loadable_path()

38 | 39 | Returns the full path to the locally-install `sqlite-fastrand` extension, without the filename. 40 | 41 | This can be directly passed to [`sqlite3.Connection.load_extension()`](https://docs.python.org/3/library/sqlite3.html#sqlite3.Connection.load_extension), but the [`sqlite_fastrand.load()`](#load) function is preferred. 42 | 43 | ```python 44 | import sqlite_fastrand 45 | print(sqlite_fastrand.loadable_path()) 46 | # '/.../venv/lib/python3.9/site-packages/sqlite_fastrand/fastrand0' 47 | ``` 48 | 49 | > Note: this extension path doesn't include the file extension (`.dylib`, `.so`, `.dll`). This is because [SQLite will infer the correct extension](https://www.sqlite.org/loadext.html#loading_an_extension). 50 | 51 |

load(connection)

52 | 53 | Loads the `sqlite-fastrand` extension on the given [`sqlite3.Connection`](https://docs.python.org/3/library/sqlite3.html#sqlite3.Connection) object, calling [`Connection.load_extension()`](https://docs.python.org/3/library/sqlite3.html#sqlite3.Connection.load_extension). 54 | 55 | ```python 56 | import sqlite_fastrand 57 | import sqlite3 58 | conn = sqlite3.connect(':memory:') 59 | 60 | conn.enable_load_extension(True) 61 | sqlite_fastrand.load(conn) 62 | conn.enable_load_extension(False) 63 | 64 | conn.execute('select fastrand_version(), fastrand()').fetchone() 65 | # ('v0.1.0', '01gr7gwc5aq22ycea6j8kxq4s9') 66 | ``` 67 | -------------------------------------------------------------------------------- /python/.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | share/python-wheels/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | MANIFEST 28 | 29 | # PyInstaller 30 | # Usually these files are written by a python script from a template 31 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 32 | *.manifest 33 | *.spec 34 | 35 | # Installer logs 36 | pip-log.txt 37 | pip-delete-this-directory.txt 38 | 39 | # Unit test / coverage reports 40 | htmlcov/ 41 | .tox/ 42 | .nox/ 43 | .coverage 44 | .coverage.* 45 | .cache 46 | nosetests.xml 47 | coverage.xml 48 | *.cover 49 | *.py,cover 50 | .hypothesis/ 51 | .pytest_cache/ 52 | cover/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | .pybuilder/ 76 | target/ 77 | 78 | # Jupyter Notebook 79 | .ipynb_checkpoints 80 | 81 | # IPython 82 | profile_default/ 83 | ipython_config.py 84 | 85 | # pyenv 86 | # For a library or package, you might want to ignore these files since the code is 87 | # intended to run in multiple environments; otherwise, check them in: 88 | # .python-version 89 | 90 | # pipenv 91 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 92 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 93 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 94 | # install all needed dependencies. 95 | #Pipfile.lock 96 | 97 | # poetry 98 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. 99 | # This is especially recommended for binary packages to ensure reproducibility, and is more 100 | # commonly ignored for libraries. 101 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control 102 | #poetry.lock 103 | 104 | # pdm 105 | # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. 106 | #pdm.lock 107 | # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it 108 | # in version control. 109 | # https://pdm.fming.dev/#use-with-ide 110 | .pdm.toml 111 | 112 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm 113 | __pypackages__/ 114 | 115 | # Celery stuff 116 | celerybeat-schedule 117 | celerybeat.pid 118 | 119 | # SageMath parsed files 120 | *.sage.py 121 | 122 | # Environments 123 | .env 124 | .venv 125 | env/ 126 | venv/ 127 | ENV/ 128 | env.bak/ 129 | venv.bak/ 130 | 131 | # Spyder project settings 132 | .spyderproject 133 | .spyproject 134 | 135 | # Rope project settings 136 | .ropeproject 137 | 138 | # mkdocs documentation 139 | /site 140 | 141 | # mypy 142 | .mypy_cache/ 143 | .dmypy.json 144 | dmypy.json 145 | 146 | # Pyre type checker 147 | .pyre/ 148 | 149 | # pytype static type analyzer 150 | .pytype/ 151 | 152 | # Cython debug symbols 153 | cython_debug/ 154 | 155 | # PyCharm 156 | # JetBrains specific template is maintained in a separate JetBrains.gitignore that can 157 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore 158 | # and can be added to the global gitignore or merged into this file. For a more nuclear 159 | # option (not recommended) you can uncomment the following to ignore the entire idea folder. 160 | #.idea/ -------------------------------------------------------------------------------- /bindings/sqlite-utils/.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | share/python-wheels/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | MANIFEST 28 | 29 | # PyInstaller 30 | # Usually these files are written by a python script from a template 31 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 32 | *.manifest 33 | *.spec 34 | 35 | # Installer logs 36 | pip-log.txt 37 | pip-delete-this-directory.txt 38 | 39 | # Unit test / coverage reports 40 | htmlcov/ 41 | .tox/ 42 | .nox/ 43 | .coverage 44 | .coverage.* 45 | .cache 46 | nosetests.xml 47 | coverage.xml 48 | *.cover 49 | *.py,cover 50 | .hypothesis/ 51 | .pytest_cache/ 52 | cover/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | .pybuilder/ 76 | target/ 77 | 78 | # Jupyter Notebook 79 | .ipynb_checkpoints 80 | 81 | # IPython 82 | profile_default/ 83 | ipython_config.py 84 | 85 | # pyenv 86 | # For a library or package, you might want to ignore these files since the code is 87 | # intended to run in multiple environments; otherwise, check them in: 88 | # .python-version 89 | 90 | # pipenv 91 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 92 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 93 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 94 | # install all needed dependencies. 95 | #Pipfile.lock 96 | 97 | # poetry 98 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. 99 | # This is especially recommended for binary packages to ensure reproducibility, and is more 100 | # commonly ignored for libraries. 101 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control 102 | #poetry.lock 103 | 104 | # pdm 105 | # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. 106 | #pdm.lock 107 | # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it 108 | # in version control. 109 | # https://pdm.fming.dev/#use-with-ide 110 | .pdm.toml 111 | 112 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm 113 | __pypackages__/ 114 | 115 | # Celery stuff 116 | celerybeat-schedule 117 | celerybeat.pid 118 | 119 | # SageMath parsed files 120 | *.sage.py 121 | 122 | # Environments 123 | .env 124 | .venv 125 | env/ 126 | venv/ 127 | ENV/ 128 | env.bak/ 129 | venv.bak/ 130 | 131 | # Spyder project settings 132 | .spyderproject 133 | .spyproject 134 | 135 | # Rope project settings 136 | .ropeproject 137 | 138 | # mkdocs documentation 139 | /site 140 | 141 | # mypy 142 | .mypy_cache/ 143 | .dmypy.json 144 | dmypy.json 145 | 146 | # Pyre type checker 147 | .pyre/ 148 | 149 | # pytype static type analyzer 150 | .pytype/ 151 | 152 | # Cython debug symbols 153 | cython_debug/ 154 | 155 | # PyCharm 156 | # JetBrains specific template is maintained in a separate JetBrains.gitignore that can 157 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore 158 | # and can be added to the global gitignore or merged into this file. For a more nuclear 159 | # option (not recommended) you can uncomment the following to ignore the entire idea folder. 160 | #.idea/ 161 | -------------------------------------------------------------------------------- /npm/sqlite-fastrand/README.md: -------------------------------------------------------------------------------- 1 | # `sqlite-fastrand` NPM Package 2 | 3 | `sqlite-fastrand` is distributed on `npm` for Node.js developers. To install on [supported platforms](#supported-platforms), simply run: 4 | 5 | ``` 6 | npm install sqlite-fastrand 7 | ``` 8 | 9 | The `sqlite-fastrand` package is meant to be used with Node SQLite clients like [`better-sqlite3`](https://github.com/WiseLibs/better-sqlite3) and [`node-sqlite3`](https://github.com/TryGhost/node-sqlite3). For `better-sqlite3`, call [`.loadExtension()`](https://github.com/WiseLibs/better-sqlite3/blob/master/docs/api.md#loadextensionpath-entrypoint---this) on your database object, passing in [`getLoadablePath()`](#getLoadablePath). 10 | 11 | ```js 12 | import Database from "better-sqlite3"; 13 | import * as sqlite_fastrand from "sqlite-fastrand"; 14 | 15 | const db = new Database(":memory:"); 16 | 17 | db.loadExtension(sqlite_fastrand.getLoadablePath()); 18 | 19 | const version = db.prepare("select fastrand_version()").pluck().get(); 20 | console.log(version); // "v0.2.0" 21 | ``` 22 | 23 | For `node-sqlite3`, call the similarly named [`.loadExtension()`](https://github.com/TryGhost/node-sqlite3/wiki/API#loadextensionpath--callback) method on your database object, and pass in [`getLoadablePath()`](#getLoadablePath). 24 | 25 | ```js 26 | import sqlite3 from "sqlite3"; 27 | import * as sqlite_fastrand from "sqlite-fastrand"; 28 | 29 | const db = new sqlite3.Database(":memory:"); 30 | 31 | db.loadExtension(sqlite_fastrand.getLoadablePath()); 32 | 33 | db.get("select fastrand_version()", (err, row) => { 34 | console.log(row); // {json_schema_version(): "v0.2.0"} 35 | }); 36 | ``` 37 | 38 | See [the full API Reference](#api-reference) for the Node API, and [`docs.md`](../../docs.md) for documentation on the `sqlite-fastrand` SQL API. 39 | 40 | ## Supported Platforms 41 | 42 | Since the underlying `fastrand0` SQLite extension is pre-compiled, the `sqlite-fastrand` NPM package only works on a few "platforms" (operating systems + CPU architectures). These platforms include: 43 | 44 | - `darwin-x64` (MacOS x86_64) 45 | - `darwin-arm64` (MacOS M1 and M2 chips) 46 | - `win32-x64` (Windows x86_64) 47 | - `linux-x64` (Linux x86_64) 48 | 49 | To see which platform your machine is, check the [`process.arch`](https://nodejs.org/api/process.html#processarch) and [`process.platform`](https://nodejs.org/api/process.html#processplatform) values like so: 50 | 51 | ```bash 52 | $ node -e 'console.log([process.platform, process.arch])' 53 | [ 'darwin', 'x64' ] 54 | ``` 55 | 56 | When the `sqlite-fastrand` NPM package is installed, the correct pre-compiled extension for your operating system and CPU architecture will be downloaded from the [optional dependencies](https://docs.npmjs.com/cli/v9/configuring-npm/package-json#optionaldependencies), with platform-specific packages like `sqlite-fastrand-darwin-x64`. This will be automatically, there's no need to directly install those packages. 57 | 58 | More platforms may be supported in the future. Consider [supporting my work](https://github.com/sponsors/asg017/) if you'd like to see more operating systems and CPU architectures supported in `sqlite-fastrand`. 59 | 60 | ## API Reference 61 | 62 | # getLoadablePath [<>](https://github.com/asg017/sqlite-fastrand/blob/main/npm/sqlite-fastrand/src/index.js "Source") 63 | 64 | Returns the full path to where the `sqlite-fastrand` _should_ be installed, based on the `sqlite-fastrand`'s `package.json` optional dependencies and the host's operating system and architecture. 65 | 66 | This path can be directly passed into [`better-sqlite3`](https://github.com/WiseLibs/better-sqlite3)'s [`.loadExtension()`](https://github.com/WiseLibs/better-sqlite3/blob/master/docs/api.md#loadextensionpath-entrypoint---this). 67 | 68 | ```js 69 | import Database from "better-sqlite3"; 70 | import * as sqlite_fastrand from "sqlite-fastrand"; 71 | 72 | const db = new Database(":memory:"); 73 | db.loadExtension(sqlite_fastrand.getLoadablePath()); 74 | ``` 75 | 76 | It can also be used in [`node-sqlite3`](https://github.com/TryGhost/node-sqlite3)'s [`.loadExtension()`](https://github.com/TryGhost/node-sqlite3/wiki/API#loadextensionpath--callback). 77 | 78 | ```js 79 | import sqlite3 from "sqlite3"; 80 | import * as sqlite_fastrand from "sqlite-fastrand"; 81 | 82 | const db = new sqlite3.Database(":memory:"); 83 | db.loadExtension(sqlite_fastrand.getLoadablePath()); 84 | ``` 85 | 86 | This function throws an `Error` in two different cases. The first case is when `sqlite-fastrand` is installed and run on an [unsupported platform](#supported-platforms). The second case is when the platform-specific optional dependency is not installed. If you reach this, ensure you aren't using `--no-optional` flag, and [file an issue](https://github.com/asg017/sqlite-fastrand/issues/new) if you are stuck. 87 | 88 | The `db.loadExtension()` function may also throw an Error if the compiled extension is incompatible with your SQLite connection for any reason, including missing system packages, outdated glib versions, or other misconfigurations. If you reach this, please [file an issue](https://github.com/asg017/sqlite-fastrand/issues/new). 89 | -------------------------------------------------------------------------------- /docs.md: -------------------------------------------------------------------------------- 1 | # `sqlite-fastrand` Documentation 2 | 3 | A full reference to every function and module that `sqlite-fastrand` offers. 4 | 5 | As a reminder, `sqlite-fastrand` follows semver and is pre v1, so breaking changes are to be expected. 6 | 7 | ## API Reference 8 | 9 |

fastrand_version()

10 | 11 | Returns the semver version string of the current version of `sqlite-fastrand`. 12 | 13 | ```sql 14 | select fastrand_version(); -- "v0.1.0" 15 | ``` 16 | 17 |

fastrand_debug()

18 | 19 | Returns a debug string of various info about `sqlite-fastrand`, including 20 | the version string, build date, and commit hash. 21 | 22 | ```sql 23 | select fastrand_debug(); 24 | 'Version: v0.1.0 25 | Source: 247dca8f4cea1abdc30ed3e852c3e5b71374c177' 26 | ``` 27 | 28 |

fastrand_seed_get()

29 | 30 | Gets the current seed value powering the underlying random number generator. Returns text, because the seed is an unsigned 64 bit integer, larger than SQLite's max integer size. Based on [`Rng.get_seed()`](https://docs.rs/fastrand/1.8.0/fastrand/struct.Rng.html#method.get_seed). 31 | 32 | ```sql 33 | select fastrand_seed_get(); -- '3362862862133652073' 34 | ``` 35 | 36 |

fastrand_seed_set()

37 | 38 | Set the seed value of the underlying random number generator. Only i64 values allows. Returns 1 if succesful. Based on [`Rng.seed()`](https://docs.rs/fastrand/1.8.0/fastrand/struct.Rng.html#method.seed). 39 | 40 | ```sql 41 | select fastrand_seed_set(); -- 1 42 | ``` 43 | 44 |

fastrand_double()

45 | 46 | Returns a random number between 0 and 1. Based on [`Rng.f64()`]https://docs.rs/fastrand/1.8.0/fastrand/struct.Rng.html#method.f64(). 47 | 48 | ```sql 49 | select fastrand_double(); -- 0.644268998061438 50 | select fastrand_double(); -- 0.810443374870184 51 | ``` 52 | 53 |

fastrand_int()

54 | 55 | Returns a random 32 bit integer between `-2_147_483_648` and `2_147_483_647`. Based on [`Rng.i32()`](https://docs.rs/fastrand/1.8.0/fastrand/struct.Rng.html#method.i32). 56 | 57 | ```sql 58 | select fastrand_int(); -- 1321083668 59 | select fastrand_int(); -- 1579705906 60 | ``` 61 | 62 |

fastrand_int64()

63 | 64 | Returns a random 64 bit integer between `-9_223_372_036_854_775_808` and `9_223_372_036_854_775_807`. Based on [`Rng.i64()`](https://docs.rs/fastrand/1.8.0/fastrand/struct.Rng.html#method.i64). 65 | 66 | ```sql 67 | select fastrand_int64(); -- -6587368321689545426 68 | select fastrand_int64(); -- 7259195115703397710 69 | ``` 70 | 71 |

fastrand_blob(N)

72 | 73 | Returns a blob of length `N` with random bytes. Based on [`Rng.u8()`](https://docs.rs/fastrand/1.8.0/fastrand/struct.Rng.html#method.u8). 74 | 75 | ```sql 76 | select fastrand_blob(4); -- X'bc71ef5b' 77 | select fastrand_blob(12); -- X'22fce3c0c809c20b0c54251e' 78 | ``` 79 | 80 |

fastrand_bool()

81 | 82 | Returns a random boolean value, `0` or `1`. Based on [`Rng.bool`](https://docs.rs/fastrand/1.8.0/fastrand/struct.Rng.html#method.bool). 83 | 84 | ```sql 85 | select fastrand_bool(); -- 1 86 | select fastrand_bool(); -- 0 87 | ``` 88 | 89 |

fastrand_alphabetic()

90 | 91 | Returns a random alphabetic character, within `a-z` and `A-Z`. Based on [`Rng.alphabetic`](https://docs.rs/fastrand/1.8.0/fastrand/struct.Rng.html#method.alphabetic). 92 | 93 | ```sql 94 | select fastrand_alphabetic(); -- 'Q' 95 | select fastrand_alphabetic(); -- 'b' 96 | ``` 97 | 98 |

fastrand_alphanumeric()

99 | 100 | Returns a random alphanumeric character, within `a-z`, `A-Z`, or `0-9`. Based on [`Rng.alphanumeric`](https://docs.rs/fastrand/1.8.0/fastrand/struct.Rng.html#method.alphanumeric). 101 | 102 | ```sql 103 | select fastrand_alphanumeric(); -- 'U' 104 | select fastrand_alphanumeric(); -- '4' 105 | select fastrand_alphanumeric(); -- 'i' 106 | ``` 107 | 108 |

fastrand_digit(base)

109 | 110 | Returns a random digit in the given `base`. The `base` must be greater than 0 and less than 36. Based on [`Rng.digit`](https://docs.rs/fastrand/1.8.0/fastrand/struct.Rng.html#method.digit). 111 | 112 | ```sql 113 | select fastrand_digit(4); -- '1' 114 | select fastrand_digit(35); -- 'v' 115 | ``` 116 | 117 |

fastrand_lowercase()

118 | 119 | Returns a random character within `a-z`. Based on [`Rng.lowercase()`](https://docs.rs/fastrand/1.8.0/fastrand/struct.Rng.html#method.lowercase). 120 | 121 | ```sql 122 | select fastrand_lowercase(); -- 's' 123 | select fastrand_lowercase(); -- 'p' 124 | ``` 125 | 126 |

fastrand_uppercase()

127 | 128 | Returns a random character within `A-Z`. Based on [`Rng.uppercase()`](https://docs.rs/fastrand/1.8.0/fastrand/struct.Rng.html#method.uppercase). 129 | 130 | ```sql 131 | select fastrand_uppercase(); -- 'E' 132 | select fastrand_uppercase(); -- 'J' 133 | ``` 134 | -------------------------------------------------------------------------------- /tests/test-loadable.py: -------------------------------------------------------------------------------- 1 | import sqlite3 2 | import unittest 3 | import time 4 | import os 5 | 6 | EXT_PATH="./dist/debug/fastrand0" 7 | 8 | def connect(ext): 9 | db = sqlite3.connect(":memory:") 10 | 11 | db.execute("create table base_functions as select name from pragma_function_list") 12 | db.execute("create table base_modules as select name from pragma_module_list") 13 | 14 | db.enable_load_extension(True) 15 | db.load_extension(ext) 16 | 17 | db.execute("create temp table loaded_functions as select name from pragma_function_list where name not in (select name from base_functions) order by name") 18 | db.execute("create temp table loaded_modules as select name from pragma_module_list where name not in (select name from base_modules) order by name") 19 | 20 | db.row_factory = sqlite3.Row 21 | return db 22 | 23 | 24 | db = connect(EXT_PATH) 25 | 26 | def explain_query_plan(sql): 27 | return db.execute("explain query plan " + sql).fetchone()["detail"] 28 | 29 | def execute_all(sql, args=None): 30 | if args is None: args = [] 31 | results = db.execute(sql, args).fetchall() 32 | return list(map(lambda x: dict(x), results)) 33 | 34 | FUNCTIONS = [ 35 | 'fastrand_alphabetic', 36 | 'fastrand_alphanumeric', 37 | 'fastrand_blob', 38 | 'fastrand_bool', 39 | 'fastrand_debug', 40 | 'fastrand_digit', 41 | 'fastrand_double', 42 | 'fastrand_int', 43 | 'fastrand_int', 44 | 'fastrand_int', 45 | 'fastrand_int64', 46 | 'fastrand_int64', 47 | 'fastrand_int64', 48 | 'fastrand_lowercase', 49 | 'fastrand_seed_get', 50 | 'fastrand_seed_set', 51 | 'fastrand_uppercase', 52 | 'fastrand_version' 53 | 54 | ] 55 | 56 | MODULES = [ 57 | ] 58 | def spread_args(args): 59 | return ",".join(['?'] * len(args)) 60 | 61 | class TestFastrand(unittest.TestCase): 62 | def test_funcs(self): 63 | funcs = list(map(lambda a: a[0], db.execute("select name from loaded_functions").fetchall())) 64 | self.assertEqual(funcs, FUNCTIONS) 65 | 66 | def test_modules(self): 67 | modules = list(map(lambda a: a[0], db.execute("select name from loaded_modules").fetchall())) 68 | self.assertEqual(modules, MODULES) 69 | 70 | def test_fastrand_version(self): 71 | self.assertEqual(db.execute("select fastrand_version()").fetchone()[0][0], "v") 72 | 73 | def test_fastrand_debug(self): 74 | debug = db.execute("select fastrand_debug()").fetchone()[0] 75 | self.assertEqual(len(debug.splitlines()), 2) 76 | 77 | def test_fastrand_int(self): 78 | self.skipTest("TODO") 79 | fastrand_int = lambda x: db.execute("select fastrand_int(?)", []).fetchone()[0] 80 | self.assertEqual(fastrand_int(), 0) 81 | 82 | def test_fastrand_int64(self): 83 | self.skipTest("TODO") 84 | fastrand_int64 = lambda x: db.execute("select fastrand_int64(?)", []).fetchone()[0] 85 | self.assertEqual(fastrand_int64(), 0) 86 | 87 | def test_fastrand_double(self): 88 | self.skipTest("TODO") 89 | fastrand_double = lambda x: db.execute("select fastrand_double(?)", []).fetchone()[0] 90 | self.assertEqual(fastrand_double(), 0) 91 | 92 | def test_fastrand_blob(self): 93 | self.skipTest("TODO") 94 | fastrand_blob = lambda x: db.execute("select fastrand_blob(?)", []).fetchone()[0] 95 | self.assertEqual(fastrand_blob(), 0) 96 | 97 | def test_fastrand_seed_get(self): 98 | self.skipTest("TODO") 99 | fastrand_seed_get = lambda x: db.execute("select fastrand_seed_get(?)", []).fetchone()[0] 100 | self.assertEqual(fastrand_seed_get(), 0) 101 | 102 | def test_fastrand_seed_set(self): 103 | self.skipTest("TODO") 104 | fastrand_seed_set = lambda x: db.execute("select fastrand_seed_set(?)", []).fetchone()[0] 105 | self.assertEqual(fastrand_seed_set(), 0) 106 | 107 | 108 | 109 | def test_fastrand_alphabetic(self): 110 | self.skipTest("TODO") 111 | fastrand_alphabetic = lambda x: db.execute("select fastrand_alphabetic(?)", []).fetchone()[0] 112 | self.assertEqual(fastrand_alphabetic(), 0) 113 | 114 | def test_fastrand_alphanumeric(self): 115 | self.skipTest("TODO") 116 | fastrand_alphanumeric = lambda x: db.execute("select fastrand_alphanumeric(?)", []).fetchone()[0] 117 | self.assertEqual(fastrand_alphanumeric(), 0) 118 | 119 | def test_fastrand_bool(self): 120 | self.skipTest("TODO") 121 | fastrand_bool = lambda x: db.execute("select fastrand_bool(?)", []).fetchone()[0] 122 | self.assertEqual(fastrand_bool(), 0) 123 | 124 | def test_fastrand_char(self): 125 | self.skipTest("TODO") 126 | fastrand_char = lambda x: db.execute("select fastrand_char(?)", []).fetchone()[0] 127 | self.assertEqual(fastrand_char(), 0) 128 | 129 | def test_fastrand_digit(self): 130 | self.skipTest("TODO") 131 | fastrand_digit = lambda x: db.execute("select fastrand_digit(?)", []).fetchone()[0] 132 | self.assertEqual(fastrand_digit(), 0) 133 | 134 | 135 | def test_fastrand_lowercase(self): 136 | self.skipTest("TODO") 137 | fastrand_lowercase = lambda x: db.execute("select fastrand_lowercase(?)", []).fetchone()[0] 138 | self.assertEqual(fastrand_lowercase(), 0) 139 | 140 | def test_fastrand_uppercase(self): 141 | self.skipTest("TODO") 142 | fastrand_uppercase = lambda x: db.execute("select fastrand_uppercase(?)", []).fetchone()[0] 143 | self.assertEqual(fastrand_uppercase(), 0) 144 | 145 | class TestCoverage(unittest.TestCase): 146 | def test_coverage(self): 147 | test_methods = [method for method in dir(TestFastrand) if method.startswith('test_')] 148 | funcs_with_tests = set([x.replace("test_", "") for x in test_methods]) 149 | 150 | for func in FUNCTIONS: 151 | self.assertTrue(func in funcs_with_tests, f"{func} does not have corresponding test in {funcs_with_tests}") 152 | 153 | for module in MODULES: 154 | self.assertTrue(module in funcs_with_tests, f"{module} does not have corresponding test in {funcs_with_tests}") 155 | 156 | if __name__ == '__main__': 157 | unittest.main() 158 | -------------------------------------------------------------------------------- /deno/deno.lock: -------------------------------------------------------------------------------- 1 | { 2 | "version": "2", 3 | "remote": { 4 | "https://deno.land/std@0.152.0/_util/assert.ts": "e94f2eb37cebd7f199952e242c77654e43333c1ac4c5c700e929ea3aa5489f74", 5 | "https://deno.land/std@0.152.0/_util/os.ts": "3b4c6e27febd119d36a416d7a97bd3b0251b77c88942c8f16ee5953ea13e2e49", 6 | "https://deno.land/std@0.152.0/path/_constants.ts": "df1db3ffa6dd6d1252cc9617e5d72165cd2483df90e93833e13580687b6083c3", 7 | "https://deno.land/std@0.152.0/path/_interface.ts": "ee3b431a336b80cf445441109d089b70d87d5e248f4f90ff906820889ecf8d09", 8 | "https://deno.land/std@0.152.0/path/_util.ts": "c1e9686d0164e29f7d880b2158971d805b6e0efc3110d0b3e24e4b8af2190d2b", 9 | "https://deno.land/std@0.152.0/path/common.ts": "bee563630abd2d97f99d83c96c2fa0cca7cee103e8cb4e7699ec4d5db7bd2633", 10 | "https://deno.land/std@0.152.0/path/glob.ts": "cb5255638de1048973c3e69e420c77dc04f75755524cb3b2e160fe9277d939ee", 11 | "https://deno.land/std@0.152.0/path/mod.ts": "56fec03ad0ebd61b6ab39ddb9b0ddb4c4a5c9f2f4f632e09dd37ec9ebfd722ac", 12 | "https://deno.land/std@0.152.0/path/posix.ts": "c1f7afe274290ea0b51da07ee205653b2964bd74909a82deb07b69a6cc383aaa", 13 | "https://deno.land/std@0.152.0/path/separator.ts": "fe1816cb765a8068afb3e8f13ad272351c85cbc739af56dacfc7d93d710fe0f9", 14 | "https://deno.land/std@0.152.0/path/win32.ts": "bd7549042e37879c68ff2f8576a25950abbfca1d696d41d82c7bca0b7e6f452c", 15 | "https://deno.land/std@0.176.0/_util/asserts.ts": "178dfc49a464aee693a7e285567b3d0b555dc805ff490505a8aae34f9cfb1462", 16 | "https://deno.land/std@0.176.0/_util/os.ts": "d932f56d41e4f6a6093d56044e29ce637f8dcc43c5a90af43504a889cf1775e3", 17 | "https://deno.land/std@0.176.0/encoding/hex.ts": "50f8c95b52eae24395d3dfcb5ec1ced37c5fe7610ef6fffdcc8b0fdc38e3b32f", 18 | "https://deno.land/std@0.176.0/fmt/colors.ts": "938c5d44d889fb82eff6c358bea8baa7e85950a16c9f6dae3ec3a7a729164471", 19 | "https://deno.land/std@0.176.0/fs/_util.ts": "65381f341af1ff7f40198cee15c20f59951ac26e51ddc651c5293e24f9ce6f32", 20 | "https://deno.land/std@0.176.0/fs/copy.ts": "14214efd94fc3aa6db1e4af2b4b9578e50f7362b7f3725d5a14ad259a5df26c8", 21 | "https://deno.land/std@0.176.0/fs/empty_dir.ts": "c3d2da4c7352fab1cf144a1ecfef58090769e8af633678e0f3fabaef98594688", 22 | "https://deno.land/std@0.176.0/fs/ensure_dir.ts": "724209875497a6b4628dfb256116e5651c4f7816741368d6c44aab2531a1e603", 23 | "https://deno.land/std@0.176.0/fs/ensure_file.ts": "c38602670bfaf259d86ca824a94e6cb9e5eb73757fefa4ebf43a90dd017d53d9", 24 | "https://deno.land/std@0.176.0/fs/ensure_link.ts": "c0f5b2f0ec094ed52b9128eccb1ee23362a617457aa0f699b145d4883f5b2fb4", 25 | "https://deno.land/std@0.176.0/fs/ensure_symlink.ts": "2955cc8332aeca9bdfefd05d8d3976b94e282b0f353392a71684808ed2ffdd41", 26 | "https://deno.land/std@0.176.0/fs/eol.ts": "f1f2eb348a750c34500741987b21d65607f352cf7205f48f4319d417fff42842", 27 | "https://deno.land/std@0.176.0/fs/exists.ts": "b8c8a457b71e9d7f29b9d2f87aad8dba2739cbe637e8926d6ba6e92567875f8e", 28 | "https://deno.land/std@0.176.0/fs/expand_glob.ts": "45d17e89796a24bd6002e4354eda67b4301bb8ba67d2cac8453cdabccf1d9ab0", 29 | "https://deno.land/std@0.176.0/fs/mod.ts": "bc3d0acd488cc7b42627044caf47d72019846d459279544e1934418955ba4898", 30 | "https://deno.land/std@0.176.0/fs/move.ts": "4cb47f880e3f0582c55e71c9f8b1e5e8cfaacb5e84f7390781dd563b7298ec19", 31 | "https://deno.land/std@0.176.0/fs/walk.ts": "ea95ffa6500c1eda6b365be488c056edc7c883a1db41ef46ec3bf057b1c0fe32", 32 | "https://deno.land/std@0.176.0/path/_constants.ts": "e49961f6f4f48039c0dfed3c3f93e963ca3d92791c9d478ac5b43183413136e0", 33 | "https://deno.land/std@0.176.0/path/_interface.ts": "6471159dfbbc357e03882c2266d21ef9afdb1e4aa771b0545e90db58a0ba314b", 34 | "https://deno.land/std@0.176.0/path/_util.ts": "d7abb1e0dea065f427b89156e28cdeb32b045870acdf865833ba808a73b576d0", 35 | "https://deno.land/std@0.176.0/path/common.ts": "ee7505ab01fd22de3963b64e46cff31f40de34f9f8de1fff6a1bd2fe79380000", 36 | "https://deno.land/std@0.176.0/path/glob.ts": "d479e0a695621c94d3fd7fe7abd4f9499caf32a8de13f25073451c6ef420a4e1", 37 | "https://deno.land/std@0.176.0/path/mod.ts": "4b83694ac500d7d31b0cdafc927080a53dc0c3027eb2895790fb155082b0d232", 38 | "https://deno.land/std@0.176.0/path/posix.ts": "8b7c67ac338714b30c816079303d0285dd24af6b284f7ad63da5b27372a2c94d", 39 | "https://deno.land/std@0.176.0/path/separator.ts": "0fb679739d0d1d7bf45b68dacfb4ec7563597a902edbaf3c59b50d5bcadd93b1", 40 | "https://deno.land/std@0.176.0/path/win32.ts": "d186344e5583bcbf8b18af416d13d82b35a317116e6460a5a3953508c3de5bba", 41 | "https://deno.land/std@0.177.0/fmt/colors.ts": "938c5d44d889fb82eff6c358bea8baa7e85950a16c9f6dae3ec3a7a729164471", 42 | "https://deno.land/std@0.177.0/testing/_diff.ts": "1a3c044aedf77647d6cac86b798c6417603361b66b54c53331b312caeb447aea", 43 | "https://deno.land/std@0.177.0/testing/_format.ts": "a69126e8a469009adf4cf2a50af889aca364c349797e63174884a52ff75cf4c7", 44 | "https://deno.land/std@0.177.0/testing/asserts.ts": "984ab0bfb3faeed92ffaa3a6b06536c66811185328c5dd146257c702c41b01ab", 45 | "https://deno.land/x/plug@1.0.1/deps.ts": "35ea2acd5e3e11846817a429b7ef4bec47b80f2d988f5d63797147134cbd35c2", 46 | "https://deno.land/x/plug@1.0.1/download.ts": "8d6a023ade0806a0653b48cd5f6f8b15fcfaa1dbf2aa1f4bc90fc5732d27b144", 47 | "https://deno.land/x/plug@1.0.1/mod.ts": "5dec80ee7a3a325be45c03439558531bce7707ac118f4376cebbd6740ff24bfb", 48 | "https://deno.land/x/plug@1.0.1/types.ts": "d8eb738fc6ed883e6abf77093442c2f0b71af9090f15c7613621d4039e410ee1", 49 | "https://deno.land/x/plug@1.0.1/util.ts": "5ba8127b9adc36e070b9e22971fb8106869eea1741f452a87b4861e574f13481", 50 | "https://deno.land/x/sqlite3@0.8.0/deno.json": "61fbd0665a1b48f5e0f1773371d49b776f559cd6c3747a4e674adc3eb423686c", 51 | "https://deno.land/x/sqlite3@0.8.0/deps.ts": "722c865b9cef27b4cde0bb1ac9ebb08e94c43ad090a7313cea576658ff1e3bb0", 52 | "https://deno.land/x/sqlite3@0.8.0/mod.ts": "d41b8b30e1b20b537ef4d78cae98d90f6bd65c727b64aa1a18bffbb28f7d6ec3", 53 | "https://deno.land/x/sqlite3@0.8.0/src/blob.ts": "a956fc0cf4a8c7a21dc3fcb71a07ef773bcd08b5fd72e8ace89b1bfbd031bf06", 54 | "https://deno.land/x/sqlite3@0.8.0/src/constants.ts": "85fd27aa6e199093f25f5f437052e16fd0e0870b96ca9b24a98e04ddc8b7d006", 55 | "https://deno.land/x/sqlite3@0.8.0/src/database.ts": "c68c7fdfa7548000ea7e194360cdce86b81b667aab6b0778ea7ed9b74a37b7cb", 56 | "https://deno.land/x/sqlite3@0.8.0/src/ffi.ts": "d5d5e3b4524cf0b980d23e57b08f75dc0debc7af2e93ff8b00cdc5af52637b31", 57 | "https://deno.land/x/sqlite3@0.8.0/src/statement.ts": "0b2b3c8b5564ad3c35f2c7d57607e5755c38b23b835e9a46aa1002e68e6ec3a2", 58 | "https://deno.land/x/sqlite3@0.8.0/src/util.ts": "9627ebecc7a5eb250d2df9386a456a9a9ed7842a20fe32be1ee6b7c663c77bd3" 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | SHELL := /bin/bash 2 | 3 | VERSION=$(shell cat VERSION) 4 | 5 | ifeq ($(shell uname -s),Darwin) 6 | CONFIG_DARWIN=y 7 | else ifeq ($(OS),Windows_NT) 8 | CONFIG_WINDOWS=y 9 | else 10 | CONFIG_LINUX=y 11 | endif 12 | 13 | LIBRARY_PREFIX=lib 14 | ifdef CONFIG_DARWIN 15 | LOADABLE_EXTENSION=dylib 16 | endif 17 | 18 | ifdef CONFIG_LINUX 19 | LOADABLE_EXTENSION=so 20 | endif 21 | 22 | 23 | ifdef CONFIG_WINDOWS 24 | LOADABLE_EXTENSION=dll 25 | LIBRARY_PREFIX= 26 | endif 27 | 28 | prefix=dist 29 | TARGET_LOADABLE=$(prefix)/debug/fastrand0.$(LOADABLE_EXTENSION) 30 | TARGET_LOADABLE_RELEASE=$(prefix)/release/fastrand0.$(LOADABLE_EXTENSION) 31 | 32 | TARGET_STATIC=$(prefix)/debug/fastrand0.a 33 | TARGET_STATIC_RELEASE=$(prefix)/release/fastrand0.a 34 | 35 | TARGET_WHEELS=$(prefix)/debug/wheels 36 | TARGET_WHEELS_RELEASE=$(prefix)/release/wheels 37 | 38 | INTERMEDIATE_PYPACKAGE_EXTENSION=python/sqlite_fastrand/sqlite_fastrand/fastrand0.$(LOADABLE_EXTENSION) 39 | 40 | ifdef target 41 | CARGO_TARGET=--target=$(target) 42 | BUILT_LOCATION=target/$(target)/debug/$(LIBRARY_PREFIX)sqlite_fastrand.$(LOADABLE_EXTENSION) 43 | BUILT_LOCATION_RELEASE=target/$(target)/release/$(LIBRARY_PREFIX)sqlite_fastrand.$(LOADABLE_EXTENSION) 44 | else 45 | CARGO_TARGET= 46 | BUILT_LOCATION=target/debug/$(LIBRARY_PREFIX)sqlite_fastrand.$(LOADABLE_EXTENSION) 47 | BUILT_LOCATION_RELEASE=target/release/$(LIBRARY_PREFIX)sqlite_fastrand.$(LOADABLE_EXTENSION) 48 | endif 49 | 50 | ifdef python 51 | PYTHON=$(python) 52 | else 53 | PYTHON=python3 54 | endif 55 | 56 | ifdef IS_MACOS_ARM 57 | RENAME_WHEELS_ARGS=--is-macos-arm 58 | else 59 | RENAME_WHEELS_ARGS= 60 | endif 61 | 62 | $(prefix): 63 | mkdir -p $(prefix)/debug 64 | mkdir -p $(prefix)/release 65 | 66 | $(TARGET_WHEELS): $(prefix) 67 | mkdir -p $(TARGET_WHEELS) 68 | 69 | $(TARGET_WHEELS_RELEASE): $(prefix) 70 | mkdir -p $(TARGET_WHEELS_RELEASE) 71 | 72 | $(TARGET_LOADABLE): $(prefix) $(shell find . -type f -name '*.rs') 73 | cargo build $(CARGO_TARGET) 74 | cp $(BUILT_LOCATION) $@ 75 | 76 | $(TARGET_LOADABLE_RELEASE): $(prefix) $(shell find . -type f -name '*.rs') 77 | cargo build --release $(CARGO_TARGET) 78 | cp $(BUILT_LOCATION_RELEASE) $@ 79 | 80 | python: $(TARGET_WHEELS) $(TARGET_LOADABLE) python/sqlite_fastrand/setup.py python/sqlite_fastrand/sqlite_fastrand/__init__.py .github/workflows/rename-wheels.py 81 | cp $(TARGET_LOADABLE) $(INTERMEDIATE_PYPACKAGE_EXTENSION) 82 | rm $(TARGET_WHEELS)/sqlite_fastrand* || true 83 | pip3 wheel python/sqlite_fastrand/ -w $(TARGET_WHEELS) 84 | python3 .github/workflows/rename-wheels.py $(TARGET_WHEELS) $(RENAME_WHEELS_ARGS) 85 | 86 | python-release: $(TARGET_LOADABLE_RELEASE) $(TARGET_WHEELS_RELEASE) python/sqlite_fastrand/setup.py python/sqlite_fastrand/sqlite_fastrand/__init__.py .github/workflows/rename-wheels.py 87 | cp $(TARGET_LOADABLE_RELEASE) $(INTERMEDIATE_PYPACKAGE_EXTENSION) 88 | rm $(TARGET_WHEELS_RELEASE)/sqlite_fastrand* || true 89 | pip3 wheel python/sqlite_fastrand/ -w $(TARGET_WHEELS_RELEASE) 90 | python3 .github/workflows/rename-wheels.py $(TARGET_WHEELS_RELEASE) $(RENAME_WHEELS_ARGS) 91 | 92 | datasette: $(TARGET_WHEELS) python/datasette_sqlite_fastrand/setup.py python/datasette_sqlite_fastrand/datasette_sqlite_fastrand/__init__.py 93 | rm $(TARGET_WHEELS)/datasette* || true 94 | pip3 wheel python/datasette_sqlite_fastrand/ --no-deps -w $(TARGET_WHEELS) 95 | 96 | datasette-release: $(TARGET_WHEELS_RELEASE) python/datasette_sqlite_fastrand/setup.py python/datasette_sqlite_fastrand/datasette_sqlite_fastrand/__init__.py 97 | rm $(TARGET_WHEELS_RELEASE)/datasette* || true 98 | pip3 wheel python/datasette_sqlite_fastrand/ --no-deps -w $(TARGET_WHEELS_RELEASE) 99 | 100 | bindings/sqlite-utils/pyproject.toml: bindings/sqlite-utils/pyproject.toml.tmpl VERSION 101 | VERSION=$(VERSION) envsubst < $< > $@ 102 | echo "✅ generated $@" 103 | 104 | bindings/sqlite-utils/sqlite_utils_sqlite_fastrand/version.py: bindings/sqlite-utils/sqlite_utils_sqlite_fastrand/version.py.tmpl VERSION 105 | VERSION=$(VERSION) envsubst < $< > $@ 106 | echo "✅ generated $@" 107 | 108 | sqlite-utils: $(TARGET_WHEELS) bindings/sqlite-utils/pyproject.toml bindings/sqlite-utils/sqlite_utils_sqlite_fastrand/version.py 109 | python3 -m build bindings/sqlite-utils -w -o $(TARGET_WHEELS) 110 | 111 | sqlite-utils-release: $(TARGET_WHEELS) bindings/sqlite-utils/pyproject.toml bindings/sqlite-utils/sqlite_utils_sqlite_fastrand/version.py 112 | python3 -m build bindings/sqlite-utils -w -o $(TARGET_WHEELS_RELEASE) 113 | 114 | npm: VERSION npm/platform-package.README.md.tmpl npm/platform-package.package.json.tmpl npm/sqlite-fastrand/package.json.tmpl scripts/npm_generate_platform_packages.sh 115 | scripts/npm_generate_platform_packages.sh 116 | 117 | deno: VERSION deno/deno.json.tmpl 118 | scripts/deno_generate_package.sh 119 | 120 | Cargo.toml: VERSION 121 | cargo set-version `cat VERSION` 122 | 123 | python/sqlite_fastrand/sqlite_fastrand/version.py: VERSION 124 | printf '__version__ = "%s"\n__version_info__ = tuple(__version__.split("."))\n' `cat VERSION` > $@ 125 | 126 | python/datasette_sqlite_fastrand/datasette_sqlite_fastrand/version.py: VERSION 127 | printf '__version__ = "%s"\n__version_info__ = tuple(__version__.split("."))\n' `cat VERSION` > $@ 128 | 129 | bindings/ruby/lib/version.rb: bindings/ruby/lib/version.rb.tmpl VERSION 130 | VERSION=$(VERSION) envsubst < $< > $@ 131 | 132 | ruby: bindings/ruby/lib/version.rb 133 | 134 | version: 135 | make Cargo.toml 136 | make python/sqlite_fastrand/sqlite_fastrand/version.py 137 | make python/datasette_sqlite_fastrand/datasette_sqlite_fastrand/version.py 138 | make bindings/sqlite-utils/pyproject.toml bindings/sqlite-utils/sqlite_utils_sqlite_fastrand/version.py 139 | make npm 140 | make deno 141 | make ruby 142 | 143 | format: 144 | cargo fmt 145 | 146 | sqlite-fastrand.h: cbindgen.toml 147 | rustup run nightly cbindgen --config $< -o $@ 148 | 149 | release: $(TARGET_LOADABLE_RELEASE) $(TARGET_STATIC_RELEASE) 150 | 151 | loadable: $(TARGET_LOADABLE) 152 | loadable-release: $(TARGET_LOADABLE_RELEASE) 153 | 154 | static: $(TARGET_STATIC) 155 | static-release: $(TARGET_STATIC_RELEASE) 156 | 157 | debug: loadable static python datasette 158 | release: loadable-release static-release python-release datasette-release 159 | 160 | clean: 161 | rm dist/* 162 | cargo clean 163 | 164 | test-loadable: 165 | $(PYTHON) tests/test-loadable.py 166 | 167 | test-python: 168 | $(PYTHON) tests/test-python.py 169 | 170 | test-npm: 171 | node npm/sqlite-fastrand/test.js 172 | 173 | test-deno: 174 | deno task --config deno/deno.json test 175 | 176 | test: 177 | make test-loadable 178 | make test-python 179 | make test-npm 180 | make test-deno 181 | 182 | publish-release: 183 | ./scripts/publish_release.sh 184 | 185 | .PHONY: clean \ 186 | test test-loadable test-python test-npm test-deno \ 187 | loadable loadable-release \ 188 | python python-release \ 189 | datasette datasette-release \ 190 | sqlite-utils sqlite-utils-release \ 191 | static static-release \ 192 | debug release \ 193 | format version publish-release \ 194 | npm deno ruby 195 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # sqlite-fastrandom 2 | 3 | A SQLite extension for quickly generating random numbers, booleans, characters, and blobs. **Not cryptographically secure.** Based on [`sqlite-loadable-rs`](https://github.com/asg017/sqlite-loadable-rs) and the [fastrand crate](https://crates.io/crates/fastrand).` 4 | 5 | According to my local benchmarks, `fastrand_int64()` is about 2.6x faster than SQLite's `random()`, and `fastrand_blob()` is about 1.6x faster than `randomblob()`. `sqlite-fastrand` also offers a more ergonomic API with custom ranges, seeds, and boolean/character support. However, it yields psuedo-random results and isn't "truly" random. 6 | 7 | If your company or organization finds this library useful, consider [supporting my work](#supporting)! 8 | 9 | ## Usage 10 | 11 | ```sql 12 | .load ./fastrand0 13 | select fastrand_int(); -- 556823563 14 | select fastrand_int(); -- 363294620 15 | select fastrand_int(); -- -320463573 16 | ``` 17 | 18 | Set a seed for the underlying random number generator, for deterministic values. 19 | 20 | ```sql 21 | select fastrand_seed_set(1234); 22 | select fastrand_int(); -- -2058591105 23 | select fastrand_int(); -- -211244717 24 | select fastrand_int(); -- -1772832958 25 | 26 | select fastrand_seed_set(1234); 27 | select fastrand_int(); -- -2058591105 28 | select fastrand_int(); -- -211244717 29 | select fastrand_int(); -- -1772832958 30 | ``` 31 | 32 | Include `start` and `end` (exclusive) parameters to generate random numbers within a range. 33 | 34 | ```sql 35 | select fastrand_int(0, 10); -- 0 36 | select fastrand_int(0, 10); -- 9 37 | select fastrand_int(0, 10); -- 6 38 | ``` 39 | 40 | Generate random digits, lowercase/uppercase/alphabetic/alphanumeric characters. 41 | 42 | ```sql 43 | select fastrand_alphabetic(); -- 's' 44 | select fastrand_alphanumeric(); -- '2' 45 | select fastrand_char(); -- '񠞼' 46 | select fastrand_lowercase(); -- 'g' 47 | select fastrand_uppercase();-- 'M' 48 | 49 | select fastrand_digit(16); -- 'c' 50 | ``` 51 | 52 | Generate a random float between 0 and 1. 53 | 54 | ```sql 55 | select fastrand_double(); -- 0.740834390248454 56 | select fastrand_double(); -- 0.46936608707793 57 | ``` 58 | 59 | ### Differences from `random()` and `randomblob()` 60 | 61 | The builtin [`random()`](https://www.sqlite.org/lang_corefunc.html#random) and [`randomblob()`](https://www.sqlite.org/lang_corefunc.html#randomblob) are powerful tools that already exist in SQLite standard library, but they can be confusing at times. 62 | 63 | For example, the `random()` function returns "_... a pseudo-random integer between -9223372036854775808 and +9223372036854775807_", which are the minimum and maximum values of a 64 bit signed integer. 64 | 65 | ```sql 66 | select random(); -- 8247412491507365610 67 | select random(); -- 8124278049726255864 68 | ``` 69 | 70 | This may work fine in your use-case, but typically I want a more constrained random number, like any number between `0-100`. This can technically be done with `random()` if you use `abs()` and the modulus `%` operator, but it gets awkward: 71 | 72 | ```sql 73 | select abs(random()) % 100; -- 96 74 | select abs(random()) % 100; -- 41 75 | ``` 76 | 77 | The `fastrand_int64()` function works the same as `random()` but offers an optional `start` and `end` parameters to specify a range in which the random number should be generated in. 78 | 79 | ```sql 80 | select fastrand_int64(); -- 5216671854996406003 81 | select fastrand_int64(0, 100); -- 19 82 | ``` 83 | 84 | [`randomblob(N)`](https://www.sqlite.org/lang_corefunc.html#randomblob) 85 | 86 | > _The randomblob(N) function return an N-byte blob containing pseudo-random bytes. If N is less than 1 then a 1-byte random blob is returned._ 87 | 88 | ```sql 89 | select hex(randomblob(16)); -- '4E7EFDB9E687EED4F376359986CB695E' 90 | select hex(randomblob(16)); -- 'F6CFF9249E3BD8755E10D6BB3CA81C66' 91 | ``` 92 | 93 | The [`fastrand_blob(N)`](./docs.md#fastrand_blob) function acts in the same way. 94 | 95 | ```sql 96 | select hex(fastrand_blob(16)); -- 'D86FF5409D3FAD7DBE707580C7E7DE14' 97 | select hex(fastrand_blob(16)); -- 'AB72BFE9480197F487933E8071072D4A' 98 | ``` 99 | 100 | ## Installing 101 | 102 | | Language | Install | | 103 | | -------------- | -------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | 104 | | Python | `pip install sqlite-fastrand` | [![PyPI](https://img.shields.io/pypi/v/sqlite-fastrand.svg?color=blue&logo=python&logoColor=white)](https://pypi.org/project/sqlite-fastrand/) | 105 | | Datasette | `datasette install datasette-sqlite-fastrand` | [![Datasette](https://img.shields.io/pypi/v/datasette-sqlite-fastrand.svg?color=B6B6D9&label=Datasette+plugin&logoColor=white&logo=python)](https://datasette.io/plugins/datasette-sqlite-fastrand) | 106 | | Node.js | `npm install sqlite-fastrand` | [![npm](https://img.shields.io/npm/v/sqlite-fastrand.svg?color=green&logo=nodedotjs&logoColor=white)](https://www.npmjs.com/package/sqlite-fastrand) | 107 | | Deno | [`deno.land/x/sqlite_fastrand`](https://deno.land/x/sqlite_fastrand) | [![deno.land/x release](https://img.shields.io/github/v/release/asg017/sqlite-fastrand?color=fef8d2&include_prereleases&label=deno.land%2Fx&logo=deno)](https://deno.land/x/sqlite_fastrand) | 108 | | Ruby | `gem install sqlite-fastrand` | ![Gem](https://img.shields.io/gem/v/sqlite-fastrand?color=red&logo=rubygems&logoColor=white) | 109 | | Github Release | | ![GitHub tag (latest SemVer pre-release)](https://img.shields.io/github/v/tag/asg017/sqlite-fastrand?color=lightgrey&include_prereleases&label=Github+release&logo=github) | 110 | | Rust | `cargo add sqlite-fastrand` | [![Crates.io](https://img.shields.io/crates/v/sqlite-fastrand?logo=rust)](https://crates.io/crates/sqlite-fastrand) | 111 | 112 | 116 | 117 | The [Releases page](https://github.com/asg017/sqlite-fastrand/releases) contains pre-built binaries for Linux x86_64, MacOS, and Windows. 118 | 119 | ### As a loadable extension 120 | 121 | If you want to use `sqlite-fastrand` as a [Runtime-loadable extension](https://www.sqlite.org/loadext.html), Download the `fastrand0.dylib` (for MacOS), `fastrand0.so` (Linux), or `fastrand0.dll` (Windows) file from a release and load it into your SQLite environment. 122 | 123 | > **Note:** 124 | > The `0` in the filename (`fastrand0.dylib`/ `fastrand0.so`/`fastrand0.dll`) denotes the major version of `sqlite-fastrand`. Currently `sqlite-fastrand` is pre v1, so expect breaking changes in future versions. 125 | 126 | For example, if you are using the [SQLite CLI](https://www.sqlite.org/cli.html), you can load the library like so: 127 | 128 | ```sql 129 | .load ./fastrand0 130 | select fastrand_version(); 131 | -- v0.1.0 132 | ``` 133 | 134 | Or in Python, using the builtin [sqlite3 module](https://docs.python.org/3/library/sqlite3.html): 135 | 136 | ```python 137 | import sqlite3 138 | con = sqlite3.connect(":memory:") 139 | con.enable_load_extension(True) 140 | con.load_extension("./fastrand0") 141 | print(con.execute("select fastrand_version()").fetchone()) 142 | # ('v0.1.0',) 143 | ``` 144 | 145 | Or in Node.js using [better-sqlite3](https://github.com/WiseLibs/better-sqlite3): 146 | 147 | ```javascript 148 | const Database = require("better-sqlite3"); 149 | const db = new Database(":memory:"); 150 | db.loadExtension("./fastrand0"); 151 | console.log(db.prepare("select fastrand_version()").get()); 152 | // { 'fastrand_version()': 'v0.1.0' } 153 | ``` 154 | 155 | Or with [Datasette](https://datasette.io/): 156 | 157 | ``` 158 | datasette data.db --load-extension ./fastrand0 159 | ``` 160 | 161 | ## Supporting 162 | 163 | I (Alex 👋🏼) spent a lot of time and energy on this project and [many other open source projects](https://github.com/asg017?tab=repositories&q=&type=&language=&sort=stargazers). If your company or organization uses this library (or you're feeling generous), then please [consider supporting my work](https://alexgarcia.xyz/work.html), or share this project with a friend! 164 | 165 | ## See also 166 | 167 | - [sqlite-xsv](https://github.com/asg017/sqlite-xsv), A SQLite extension for working with CSVs 168 | - [sqlite-loadable](https://github.com/asg017/sqlite-loadable-rs), A framework for writing SQLite extensions in Rust 169 | - [sqlite-http](https://github.com/asg017/sqlite-http), A SQLite extension for making HTTP requests 170 | -------------------------------------------------------------------------------- /LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /.github/workflows/test.yaml: -------------------------------------------------------------------------------- 1 | name: "build" 2 | on: 3 | push: 4 | branches: 5 | - main 6 | - pip-install 7 | permissions: 8 | contents: read 9 | jobs: 10 | build-ubuntu-extension: 11 | name: Building ubuntu 12 | runs-on: ubuntu-20.04 13 | steps: 14 | - uses: actions/checkout@v3 15 | - uses: actions/cache@v3 16 | with: 17 | path: | 18 | ~/.cargo/bin/ 19 | ~/.cargo/registry/index/ 20 | ~/.cargo/registry/cache/ 21 | ~/.cargo/git/db/ 22 | target/ 23 | key: ${{ runner.os }}-cargo-${{ hashFiles('**/Cargo.lock') }} 24 | - uses: actions-rs/toolchain@v1 25 | with: 26 | toolchain: stable 27 | - run: make loadable 28 | - name: Upload artifacts 29 | uses: actions/upload-artifact@v3 30 | with: 31 | name: sqlite-fastrand-ubuntu 32 | path: dist/debug/fastrand0.so 33 | build-ubuntu-python: 34 | runs-on: ubuntu-20.04 35 | needs: [build-ubuntu-extension] 36 | steps: 37 | - uses: actions/checkout@v3 38 | - name: Download workflow artifacts 39 | uses: actions/download-artifact@v3 40 | with: 41 | name: sqlite-fastrand-ubuntu 42 | path: dist/debug/ 43 | - uses: actions/setup-python@v3 44 | - run: pip install wheel 45 | - run: make python 46 | - run: make datasette 47 | - uses: actions/upload-artifact@v3 48 | with: 49 | name: sqlite-fastrand-ubuntu-wheels 50 | path: dist/debug/wheels/*.whl 51 | test-ubuntu: 52 | runs-on: ubuntu-20.04 53 | needs: [build-ubuntu-extension, build-ubuntu-python] 54 | env: 55 | DENO_DIR: deno_cache 56 | steps: 57 | - uses: actions/checkout@v3 58 | - uses: actions/download-artifact@v3 59 | with: 60 | name: sqlite-fastrand-ubuntu 61 | path: dist/debug/ 62 | - uses: actions/download-artifact@v3 63 | with: 64 | name: sqlite-fastrand-ubuntu 65 | path: npm/sqlite-fastrand-linux-x64/lib 66 | - uses: actions/download-artifact@v3 67 | with: 68 | name: sqlite-fastrand-ubuntu-wheels 69 | path: dist/debug/ 70 | - run: pip install --find-links dist/debug/ sqlite_fastrand 71 | - run: make test-loadable 72 | - run: make test-python 73 | # for test-npm 74 | - uses: actions/setup-node@v3 75 | with: 76 | cache: "npm" 77 | cache-dependency-path: npm/sqlite-fastrand/package.json 78 | - run: npm install 79 | working-directory: npm/sqlite-fastrand 80 | - run: make test-npm 81 | # for test-deno 82 | - uses: denoland/setup-deno@v1 83 | with: 84 | deno-version: v1.30 85 | - name: Cache Deno dependencies 86 | uses: actions/cache@v3 87 | with: 88 | path: ${{ env.DENO_DIR }} 89 | key: ${{ runner.os }}-${{ hashFiles('deno/deno.lock') }} 90 | - run: make test-deno 91 | env: 92 | DENO_SQLITE_FASTRAND_PATH: ${{ github.workspace }}/dist/debug/fastrand0 93 | build-macos-extension: 94 | name: Building macos-latest 95 | runs-on: macos-latest 96 | steps: 97 | - uses: actions/checkout@v3 98 | - uses: actions/cache@v3 99 | with: 100 | path: | 101 | ~/.cargo/bin/ 102 | ~/.cargo/registry/index/ 103 | ~/.cargo/registry/cache/ 104 | ~/.cargo/git/db/ 105 | target/ 106 | key: ${{ runner.os }}-cargo-${{ hashFiles('**/Cargo.lock') }} 107 | - uses: actions-rs/toolchain@v1 108 | with: 109 | toolchain: stable 110 | - run: make loadable 111 | - name: Upload artifacts 112 | uses: actions/upload-artifact@v3 113 | with: 114 | name: sqlite-fastrand-macos 115 | path: dist/debug/fastrand0.dylib 116 | build-macos-python: 117 | runs-on: macos-latest 118 | needs: [build-macos-extension] 119 | steps: 120 | - uses: actions/checkout@v3 121 | - name: Download workflow artifacts 122 | uses: actions/download-artifact@v3 123 | with: 124 | name: sqlite-fastrand-macos 125 | path: dist/debug/ 126 | - uses: actions/setup-python@v3 127 | - run: pip install wheel 128 | - run: make python 129 | - run: make datasette 130 | - uses: actions/upload-artifact@v3 131 | with: 132 | name: sqlite-fastrand-macos-wheels 133 | path: dist/debug/wheels/*.whl 134 | test-macos: 135 | runs-on: macos-latest 136 | needs: [build-macos-extension, build-macos-python] 137 | env: 138 | DENO_DIR: deno_cache 139 | steps: 140 | - uses: actions/checkout@v3 141 | - uses: actions/download-artifact@v3 142 | with: 143 | name: sqlite-fastrand-macos 144 | path: dist/debug/ 145 | - uses: actions/download-artifact@v3 146 | with: 147 | name: sqlite-fastrand-macos 148 | path: npm/sqlite-fastrand-darwin-x64/lib 149 | - uses: actions/download-artifact@v3 150 | with: 151 | name: sqlite-fastrand-macos-wheels 152 | path: dist/debug/ 153 | - run: brew install python 154 | - run: /usr/local/opt/python@3/libexec/bin/pip install --find-links dist/debug/ sqlite_fastrand 155 | - run: make test-loadable python=/usr/local/opt/python@3/libexec/bin/python 156 | - run: make test-python python=/usr/local/opt/python@3/libexec/bin/python 157 | # for test-npm 158 | - uses: actions/setup-node@v3 159 | with: 160 | cache: "npm" 161 | cache-dependency-path: npm/sqlite-fastrand/package.json 162 | - run: npm install 163 | working-directory: npm/sqlite-fastrand 164 | - run: make test-npm 165 | # for test-deno 166 | - uses: denoland/setup-deno@v1 167 | with: 168 | deno-version: v1.30 169 | - name: Cache Deno dependencies 170 | uses: actions/cache@v3 171 | with: 172 | path: ${{ env.DENO_DIR }} 173 | key: ${{ runner.os }}-${{ hashFiles('deno/deno.lock') }} 174 | - run: make test-deno 175 | env: 176 | DENO_SQLITE_FASTRAND_PATH: ${{ github.workspace }}/dist/debug/fastrand0 177 | build-macos-arm-extension: 178 | name: Building macos arm extension 179 | runs-on: macos-latest 180 | steps: 181 | - uses: actions/checkout@v3 182 | - uses: actions/cache@v3 183 | with: 184 | path: | 185 | ~/.cargo/bin/ 186 | ~/.cargo/registry/index/ 187 | ~/.cargo/registry/cache/ 188 | ~/.cargo/git/db/ 189 | target/ 190 | key: ${{ runner.os }}-cargo-${{ hashFiles('**/Cargo.lock') }} 191 | - uses: actions-rs/toolchain@v1 192 | with: 193 | toolchain: stable 194 | - run: rustup target add aarch64-apple-darwin 195 | - run: make loadable target=aarch64-apple-darwin 196 | - name: Upload artifacts 197 | uses: actions/upload-artifact@v3 198 | with: 199 | name: sqlite-fastrand-macos-arm 200 | path: dist/debug/fastrand0.dylib 201 | build-macos-arm-python: 202 | runs-on: macos-latest 203 | needs: [build-macos-arm-extension] 204 | steps: 205 | - uses: actions/checkout@v3 206 | - name: Download workflow artifacts 207 | uses: actions/download-artifact@v3 208 | with: 209 | name: sqlite-fastrand-macos-arm 210 | path: dist/debug/ 211 | - uses: actions/setup-python@v3 212 | - run: pip install wheel 213 | - run: make python IS_MACOS_ARM=1 214 | - run: make datasette 215 | - uses: actions/upload-artifact@v3 216 | with: 217 | name: sqlite-fastrand-macos-arm-wheels 218 | path: dist/debug/wheels/*.whl 219 | build-windows-extension: 220 | name: Building windows extension 221 | runs-on: windows-latest 222 | steps: 223 | - uses: actions/checkout@v3 224 | - uses: actions/cache@v3 225 | with: 226 | path: | 227 | ~/.cargo/bin/ 228 | ~/.cargo/registry/index/ 229 | ~/.cargo/registry/cache/ 230 | ~/.cargo/git/db/ 231 | target/ 232 | key: ${{ runner.os }}-cargo-${{ hashFiles('**/Cargo.lock') }} 233 | - uses: actions-rs/toolchain@v1 234 | with: 235 | toolchain: stable 236 | - run: make loadable 237 | - name: Upload artifacts 238 | uses: actions/upload-artifact@v3 239 | with: 240 | name: sqlite-fastrand-windows 241 | path: dist/debug/fastrand0.dll 242 | build-windows-python: 243 | runs-on: windows-latest 244 | needs: [build-windows-extension] 245 | steps: 246 | - uses: actions/checkout@v3 247 | - name: Download workflow artifacts 248 | uses: actions/download-artifact@v3 249 | with: 250 | name: sqlite-fastrand-windows 251 | path: dist/debug/ 252 | - uses: actions/setup-python@v3 253 | - run: pip install wheel 254 | - run: make python 255 | - run: make datasette 256 | - uses: actions/upload-artifact@v3 257 | with: 258 | name: sqlite-fastrand-windows-wheels 259 | path: dist/debug/wheels/*.whl 260 | test-windows: 261 | runs-on: windows-latest 262 | needs: [build-windows-extension, build-windows-python] 263 | env: 264 | DENO_DIR: deno_cache 265 | steps: 266 | - uses: actions/checkout@v3 267 | - uses: actions/download-artifact@v3 268 | with: 269 | name: sqlite-fastrand-windows 270 | path: dist/debug/ 271 | - uses: actions/download-artifact@v3 272 | with: 273 | name: sqlite-fastrand-windows 274 | path: npm/sqlite-fastrand-windows-x64/lib 275 | - uses: actions/download-artifact@v3 276 | with: 277 | name: sqlite-fastrand-windows-wheels 278 | path: dist/debug/ 279 | - run: pip install --find-links dist/debug/ sqlite_fastrand 280 | - run: make test-loadable 281 | - run: make test-python 282 | # for test-npm 283 | - uses: actions/setup-node@v3 284 | with: 285 | cache: "npm" 286 | cache-dependency-path: npm/sqlite-fastrand/package.json 287 | - run: npm install 288 | working-directory: npm/sqlite-fastrand 289 | - run: make test-npm 290 | # for test-deno 291 | - uses: denoland/setup-deno@v1 292 | with: 293 | deno-version: v1.30 294 | - name: Cache Deno dependencies 295 | uses: actions/cache@v3 296 | with: 297 | path: ${{ env.DENO_DIR }} 298 | key: ${{ runner.os }}-${{ hashFiles('deno/deno.lock') }} 299 | - run: make test-deno 300 | env: 301 | DENO_SQLITE_FASTRAND_PATH: ${{ github.workspace }}/dist/debug/fastrand0 302 | upload_test_pypi: 303 | if: ${{ contains(github.event.head_commit.message, '@test_pypi') }} 304 | needs: [test-ubuntu, test-macos, test-windows, build-macos-arm-python] 305 | runs-on: ubuntu-latest 306 | steps: 307 | - uses: actions/download-artifact@v3 308 | with: 309 | name: sqlite-fastrand-windows-wheels 310 | path: dist 311 | - uses: actions/download-artifact@v3 312 | with: 313 | name: sqlite-fastrand-ubuntu-wheels 314 | path: dist 315 | - uses: actions/download-artifact@v3 316 | with: 317 | name: sqlite-fastrand-macos-wheels 318 | path: dist 319 | - uses: actions/download-artifact@v3 320 | with: 321 | name: sqlite-fastrand-macos-arm-wheels 322 | path: dist 323 | - uses: pypa/gh-action-pypi-publish@release/v1 324 | with: 325 | password: ${{ secrets.TEST_PYPI_API_TOKEN }} 326 | repository_url: https://test.pypi.org/legacy/ 327 | skip_existing: true 328 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | use sqlite_loadable::api::ValueType; 2 | use sqlite_loadable::{api, define_scalar_function, define_scalar_function_with_aux, Result}; 3 | use sqlite_loadable::{prelude::*, Error}; 4 | 5 | use fastrand::Rng; 6 | use std::cell::{Ref, RefCell}; 7 | use std::iter::repeat_with; 8 | use std::ops::Range; 9 | use std::rc::Rc; 10 | 11 | enum BtwnValues<'a> { 12 | Range(&'a *mut sqlite3_value, &'a *mut sqlite3_value), 13 | From(&'a *mut sqlite3_value), 14 | To(&'a *mut sqlite3_value), 15 | Full, 16 | } 17 | 18 | fn calculate_btwn_values(values: &[*mut sqlite3_value]) -> Result { 19 | let a = values.get(0); 20 | let b = values.get(1); 21 | return match (a, b) { 22 | (Some(a), Some(b)) => { 23 | match ( 24 | api::value_type(a) == ValueType::Null, 25 | api::value_type(b) == ValueType::Null, 26 | ) { 27 | (true, true) => Ok(BtwnValues::Full), 28 | (false, true) => Ok(BtwnValues::From(a)), 29 | (false, false) => Ok(BtwnValues::Range(a, b)), 30 | (true, false) => Ok(BtwnValues::To(b)), 31 | } 32 | } 33 | (None, None) => Ok(BtwnValues::Full), 34 | (None, Some(_)) => Err(Error::new_message( 35 | "sqlite-fastrand internal error: argv[1] provided but not argv[0]", 36 | )), 37 | (Some(a), None) => { 38 | if api::value_type(a) == ValueType::Null { 39 | Ok(BtwnValues::Full) 40 | } else { 41 | Ok(BtwnValues::From(a)) 42 | } 43 | } 44 | }; 45 | } 46 | 47 | pub fn fastrand_version( 48 | context: *mut sqlite3_context, 49 | _values: &[*mut sqlite3_value], 50 | ) -> Result<()> { 51 | api::result_text(context, format!("v{}", env!("CARGO_PKG_VERSION")))?; 52 | Ok(()) 53 | } 54 | 55 | pub fn fastrand_debug(context: *mut sqlite3_context, _values: &[*mut sqlite3_value]) -> Result<()> { 56 | api::result_text( 57 | context, 58 | format!( 59 | "Version: v{} 60 | Source: {} 61 | ", 62 | env!("CARGO_PKG_VERSION"), 63 | env!("GIT_HASH") 64 | ), 65 | )?; 66 | Ok(()) 67 | } 68 | 69 | fn rng_borrow_or_err(rng: &Rc>) -> Result> { 70 | match rng.try_borrow() { 71 | Ok(rng) => Ok(rng), 72 | Err(err) => Err(Error::new_message( 73 | format!("internal sqlite-fastrand error, could not borrow shared RNG: {err}").as_str(), 74 | )), 75 | } 76 | } 77 | 78 | pub fn fastrand_seed_set( 79 | context: *mut sqlite3_context, 80 | values: &[*mut sqlite3_value], 81 | rng: &Rc>, 82 | ) -> Result<()> { 83 | let seed: u64 = api::value_int64( 84 | values 85 | .get(0) 86 | .ok_or_else(|| Error::new_message("expected seed as 1st argument"))?, 87 | ) 88 | .try_into() 89 | .map_err(|e| { 90 | Error::new_message(format!("seed must be an usigned 64 bit integer: {e}").as_str()) 91 | })?; 92 | rng.borrow_mut().seed(seed); 93 | api::result_bool(context, true); 94 | Ok(()) 95 | } 96 | 97 | pub fn fastrand_seed_get( 98 | context: *mut sqlite3_context, 99 | _values: &[*mut sqlite3_value], 100 | rng: &Rc>, 101 | ) -> Result<()> { 102 | api::result_text(context, rng_borrow_or_err(rng)?.get_seed().to_string())?; 103 | Ok(()) 104 | } 105 | 106 | pub fn fastrand_int( 107 | context: *mut sqlite3_context, 108 | values: &[*mut sqlite3_value], 109 | rng: &Rc>, 110 | ) -> Result<()> { 111 | let i = match calculate_btwn_values(values)? { 112 | BtwnValues::Range(start, end) => { 113 | let range: Range = std::ops::Range { 114 | start: api::value_int(start), 115 | end: api::value_int(end), 116 | }; 117 | if range.is_empty() { 118 | return Err("fuk".into()); 119 | } 120 | rng_borrow_or_err(rng)?.i32(range) 121 | } 122 | BtwnValues::From(start) => { 123 | let range = std::ops::RangeFrom { 124 | start: api::value_int(start), 125 | }; 126 | rng_borrow_or_err(rng)?.i32(range) 127 | } 128 | BtwnValues::To(end) => { 129 | let range = std::ops::RangeTo { 130 | end: api::value_int(end), 131 | }; 132 | rng_borrow_or_err(rng)?.i32(range) 133 | } 134 | BtwnValues::Full => rng_borrow_or_err(rng)?.i32(..), 135 | }; 136 | api::result_int(context, i); 137 | Ok(()) 138 | } 139 | 140 | pub fn fastrand_int64( 141 | context: *mut sqlite3_context, 142 | values: &[*mut sqlite3_value], 143 | rng: &Rc>, 144 | ) -> Result<()> { 145 | let i = match calculate_btwn_values(values)? { 146 | BtwnValues::Range(start, end) => { 147 | let range: Range = std::ops::Range { 148 | start: api::value_int64(start), 149 | end: api::value_int64(end), 150 | }; 151 | if range.is_empty() { 152 | return Err("fuk".into()); 153 | } 154 | rng_borrow_or_err(rng)?.i64(range) 155 | } 156 | BtwnValues::From(start) => { 157 | let range = std::ops::RangeFrom { 158 | start: api::value_int64(start), 159 | }; 160 | rng_borrow_or_err(rng)?.i64(range) 161 | } 162 | BtwnValues::To(end) => { 163 | let range = std::ops::RangeTo { 164 | end: api::value_int64(end), 165 | }; 166 | rng_borrow_or_err(rng)?.i64(range) 167 | } 168 | BtwnValues::Full => rng_borrow_or_err(rng)?.i64(..), 169 | }; 170 | api::result_int64(context, i); 171 | Ok(()) 172 | } 173 | 174 | pub fn fastrand_double( 175 | context: *mut sqlite3_context, 176 | _values: &[*mut sqlite3_value], 177 | rng: &Rc>, 178 | ) -> Result<()> { 179 | api::result_double(context, rng_borrow_or_err(rng)?.f64()); 180 | Ok(()) 181 | } 182 | 183 | pub fn fastrand_blob( 184 | context: *mut sqlite3_context, 185 | values: &[*mut sqlite3_value], 186 | rng: &Rc>, 187 | ) -> Result<()> { 188 | let n: usize = api::value_int64( 189 | values 190 | .get(0) 191 | .ok_or_else(|| Error::new_message("expected N as 1st argument"))?, 192 | ) as usize; 193 | let rng = rng_borrow_or_err(rng)?; 194 | let bytes: Vec = repeat_with(|| rng.u8(..)).take(n).collect(); 195 | api::result_blob(context, bytes.as_slice()); 196 | Ok(()) 197 | } 198 | 199 | pub fn fastrand_bool( 200 | context: *mut sqlite3_context, 201 | _values: &[*mut sqlite3_value], 202 | rng: &Rc>, 203 | ) -> Result<()> { 204 | api::result_bool(context, rng_borrow_or_err(rng)?.bool()); 205 | Ok(()) 206 | } 207 | 208 | pub fn fastrand_alphabetic( 209 | context: *mut sqlite3_context, 210 | _values: &[*mut sqlite3_value], 211 | rng: &Rc>, 212 | ) -> Result<()> { 213 | api::result_text(context, rng_borrow_or_err(rng)?.alphabetic().to_string())?; 214 | Ok(()) 215 | } 216 | 217 | pub fn fastrand_alphanumeric( 218 | context: *mut sqlite3_context, 219 | _values: &[*mut sqlite3_value], 220 | rng: &Rc>, 221 | ) -> Result<()> { 222 | api::result_text(context, rng_borrow_or_err(rng)?.alphanumeric().to_string())?; 223 | Ok(()) 224 | } 225 | 226 | pub fn fastrand_lowercase( 227 | context: *mut sqlite3_context, 228 | _values: &[*mut sqlite3_value], 229 | rng: &Rc>, 230 | ) -> Result<()> { 231 | api::result_text(context, rng_borrow_or_err(rng)?.lowercase().to_string())?; 232 | Ok(()) 233 | } 234 | 235 | pub fn fastrand_uppercase( 236 | context: *mut sqlite3_context, 237 | _values: &[*mut sqlite3_value], 238 | rng: &Rc>, 239 | ) -> Result<()> { 240 | api::result_text(context, rng_borrow_or_err(rng)?.uppercase().to_string())?; 241 | Ok(()) 242 | } 243 | 244 | pub fn fastrand_digit( 245 | context: *mut sqlite3_context, 246 | values: &[*mut sqlite3_value], 247 | rng: &Rc>, 248 | ) -> Result<()> { 249 | let base: u32 = api::value_int64( 250 | values 251 | .get(0) 252 | .ok_or_else(|| Error::new_message("expected base as 1st argument"))?, 253 | ) 254 | .try_into() 255 | .map_err(|e| { 256 | Error::new_message(format!("base must be an unsigned 32-bit integer: {e}").as_str()) 257 | })?; 258 | match base { 259 | 1..=35 => api::result_text(context, rng_borrow_or_err(rng)?.digit(base).to_string())?, 260 | _ => { 261 | return Err(Error::new_message( 262 | "base must be greater than 0 and less than 26", 263 | )) 264 | } 265 | } 266 | 267 | Ok(()) 268 | } 269 | 270 | #[sqlite_entrypoint] 271 | pub fn sqlite3_fastrand_init(db: *mut sqlite3) -> Result<()> { 272 | let flags = FunctionFlags::empty(); 273 | let rng = Rc::new(RefCell::new(Rng::new())); 274 | 275 | define_scalar_function( 276 | db, 277 | "fastrand_version", 278 | 0, 279 | fastrand_version, 280 | FunctionFlags::UTF8 | FunctionFlags::DETERMINISTIC, 281 | )?; 282 | define_scalar_function( 283 | db, 284 | "fastrand_debug", 285 | 0, 286 | fastrand_debug, 287 | FunctionFlags::UTF8 | FunctionFlags::DETERMINISTIC, 288 | )?; 289 | 290 | define_scalar_function_with_aux( 291 | db, 292 | "fastrand_seed_get", 293 | 0, 294 | fastrand_seed_get, 295 | flags, 296 | Rc::clone(&rng), 297 | )?; 298 | define_scalar_function_with_aux( 299 | db, 300 | "fastrand_seed_set", 301 | 1, 302 | fastrand_seed_set, 303 | flags, 304 | Rc::clone(&rng), 305 | )?; 306 | 307 | define_scalar_function_with_aux(db, "fastrand_int", 0, fastrand_int, flags, Rc::clone(&rng))?; 308 | define_scalar_function_with_aux(db, "fastrand_int", 1, fastrand_int, flags, Rc::clone(&rng))?; 309 | define_scalar_function_with_aux(db, "fastrand_int", 2, fastrand_int, flags, Rc::clone(&rng))?; 310 | define_scalar_function_with_aux( 311 | db, 312 | "fastrand_int64", 313 | 0, 314 | fastrand_int64, 315 | flags, 316 | Rc::clone(&rng), 317 | )?; 318 | define_scalar_function_with_aux( 319 | db, 320 | "fastrand_int64", 321 | 1, 322 | fastrand_int64, 323 | flags, 324 | Rc::clone(&rng), 325 | )?; 326 | define_scalar_function_with_aux( 327 | db, 328 | "fastrand_int64", 329 | 2, 330 | fastrand_int64, 331 | flags, 332 | Rc::clone(&rng), 333 | )?; 334 | define_scalar_function_with_aux( 335 | db, 336 | "fastrand_double", 337 | 0, 338 | fastrand_double, 339 | flags, 340 | Rc::clone(&rng), 341 | )?; 342 | define_scalar_function_with_aux( 343 | db, 344 | "fastrand_blob", 345 | 1, 346 | fastrand_blob, 347 | flags, 348 | Rc::clone(&rng), 349 | )?; 350 | 351 | define_scalar_function_with_aux( 352 | db, 353 | "fastrand_bool", 354 | 0, 355 | fastrand_bool, 356 | flags, 357 | Rc::clone(&rng), 358 | )?; 359 | 360 | define_scalar_function_with_aux( 361 | db, 362 | "fastrand_alphabetic", 363 | 0, 364 | fastrand_alphabetic, 365 | flags, 366 | Rc::clone(&rng), 367 | )?; 368 | define_scalar_function_with_aux( 369 | db, 370 | "fastrand_alphanumeric", 371 | 0, 372 | fastrand_alphanumeric, 373 | flags, 374 | Rc::clone(&rng), 375 | )?; 376 | define_scalar_function_with_aux( 377 | db, 378 | "fastrand_uppercase", 379 | 0, 380 | fastrand_uppercase, 381 | flags, 382 | Rc::clone(&rng), 383 | )?; 384 | define_scalar_function_with_aux( 385 | db, 386 | "fastrand_lowercase", 387 | 0, 388 | fastrand_lowercase, 389 | flags, 390 | Rc::clone(&rng), 391 | )?; 392 | 393 | define_scalar_function_with_aux( 394 | db, 395 | "fastrand_digit", 396 | 1, 397 | fastrand_digit, 398 | flags, 399 | Rc::clone(&rng), 400 | )?; 401 | Ok(()) 402 | } 403 | -------------------------------------------------------------------------------- /.github/workflows/release.yaml: -------------------------------------------------------------------------------- 1 | name: "Release" 2 | on: 3 | release: 4 | types: [published] 5 | workflow_dispatch: 6 | permissions: 7 | contents: read 8 | jobs: 9 | build-ubuntu-extension: 10 | name: Build ubuntu 11 | runs-on: ubuntu-20.04 12 | steps: 13 | - uses: actions/checkout@v2 14 | - uses: actions/cache@v3 15 | with: 16 | path: | 17 | ~/.cargo/bin/ 18 | ~/.cargo/registry/index/ 19 | ~/.cargo/registry/cache/ 20 | ~/.cargo/git/db/ 21 | target/ 22 | key: ${{ runner.os }}-cargo-${{ hashFiles('**/Cargo.lock') }} 23 | - uses: actions-rs/toolchain@v1 24 | with: 25 | toolchain: stable 26 | - run: make loadable-release 27 | - name: Upload artifacts 28 | uses: actions/upload-artifact@v2 29 | with: 30 | name: sqlite-fastrand-ubuntu 31 | path: dist/release/fastrand0.so 32 | build-ubuntu-python: 33 | runs-on: ubuntu-20.04 34 | needs: [build-ubuntu-extension] 35 | steps: 36 | - uses: actions/checkout@v3 37 | - name: Download workflow artifacts 38 | uses: actions/download-artifact@v3 39 | with: 40 | name: sqlite-fastrand-ubuntu 41 | path: dist/release/ 42 | - uses: actions/setup-python@v3 43 | - run: pip install wheel 44 | - run: make python-release 45 | - run: make datasette-release 46 | - uses: actions/upload-artifact@v3 47 | with: 48 | name: sqlite-fastrand-ubuntu-wheels 49 | path: dist/release/wheels/*.whl 50 | build-macos-extension: 51 | name: Build macos-latest 52 | runs-on: macos-latest 53 | steps: 54 | - uses: actions/checkout@v2 55 | - uses: actions/cache@v3 56 | with: 57 | path: | 58 | ~/.cargo/bin/ 59 | ~/.cargo/registry/index/ 60 | ~/.cargo/registry/cache/ 61 | ~/.cargo/git/db/ 62 | target/ 63 | key: ${{ runner.os }}-cargo-${{ hashFiles('**/Cargo.lock') }} 64 | - uses: actions-rs/toolchain@v1 65 | with: 66 | toolchain: stable 67 | - run: make loadable-release 68 | - name: Upload artifacts 69 | uses: actions/upload-artifact@v2 70 | with: 71 | name: sqlite-fastrand-macos 72 | path: dist/release/fastrand0.dylib 73 | build-macos-python: 74 | runs-on: macos-latest 75 | needs: [build-macos-extension] 76 | steps: 77 | - uses: actions/checkout@v3 78 | - name: Download workflow artifacts 79 | uses: actions/download-artifact@v3 80 | with: 81 | name: sqlite-fastrand-macos 82 | path: dist/release/ 83 | - uses: actions/setup-python@v3 84 | - run: pip install wheel 85 | - run: make python-release 86 | - run: make datasette-release 87 | - uses: actions/upload-artifact@v3 88 | with: 89 | name: sqlite-fastrand-macos-wheels 90 | path: dist/release/wheels/*.whl 91 | build-macos-arm-extension: 92 | name: Build macos-latest with arm 93 | runs-on: macos-latest 94 | steps: 95 | - uses: actions/checkout@v3 96 | - uses: actions/cache@v3 97 | with: 98 | path: | 99 | ~/.cargo/bin/ 100 | ~/.cargo/registry/index/ 101 | ~/.cargo/registry/cache/ 102 | ~/.cargo/git/db/ 103 | target/ 104 | key: ${{ runner.os }}-cargo-${{ hashFiles('**/Cargo.lock') }} 105 | - uses: actions-rs/toolchain@v1 106 | with: 107 | toolchain: stable 108 | - run: rustup target add aarch64-apple-darwin 109 | - run: make loadable-release target=aarch64-apple-darwin 110 | - name: Upload artifacts 111 | uses: actions/upload-artifact@v3 112 | with: 113 | name: sqlite-fastrand-macos-arm 114 | path: dist/release/fastrand0.dylib 115 | build-macos-arm-python: 116 | runs-on: macos-latest 117 | needs: [build-macos-arm-extension] 118 | steps: 119 | - uses: actions/checkout@v3 120 | - name: Download workflow artifacts 121 | uses: actions/download-artifact@v3 122 | with: 123 | name: sqlite-fastrand-macos-arm 124 | path: dist/release/ 125 | - uses: actions/setup-python@v3 126 | - run: pip install wheel 127 | - run: make python-release IS_MACOS_ARM=1 128 | - run: make datasette-release 129 | - uses: actions/upload-artifact@v3 130 | with: 131 | name: sqlite-fastrand-macos-arm-wheels 132 | path: dist/release/wheels/*.whl 133 | build-windows-extension: 134 | name: Build windows-latest 135 | runs-on: windows-latest 136 | steps: 137 | - uses: actions/checkout@v2 138 | - uses: actions/cache@v3 139 | with: 140 | path: | 141 | ~/.cargo/bin/ 142 | ~/.cargo/registry/index/ 143 | ~/.cargo/registry/cache/ 144 | ~/.cargo/git/db/ 145 | target/ 146 | key: ${{ runner.os }}-cargo-${{ hashFiles('**/Cargo.lock') }} 147 | - uses: actions-rs/toolchain@v1 148 | with: 149 | toolchain: stable 150 | - run: make loadable-release 151 | - name: Upload artifacts 152 | uses: actions/upload-artifact@v2 153 | with: 154 | name: sqlite-fastrand-windows 155 | path: dist/release/fastrand0.dll 156 | build-windows-python: 157 | runs-on: windows-latest 158 | needs: [build-windows-extension] 159 | steps: 160 | - uses: actions/checkout@v3 161 | - name: Download workflow artifacts 162 | uses: actions/download-artifact@v3 163 | with: 164 | name: sqlite-fastrand-windows 165 | path: dist/release/ 166 | - uses: actions/setup-python@v3 167 | - run: pip install wheel 168 | - run: make python-release 169 | - run: make datasette-release 170 | - uses: actions/upload-artifact@v3 171 | with: 172 | name: sqlite-fastrand-windows-wheels 173 | path: dist/release/wheels/*.whl 174 | build-datasette-sqlite-utils: 175 | runs-on: ubuntu-20.04 176 | steps: 177 | - uses: actions/checkout@v3 178 | - uses: actions/setup-python@v3 179 | - run: pip install wheel build 180 | - run: make datasette-release sqlite-utils-release 181 | - uses: actions/upload-artifact@v3 182 | with: 183 | name: sqlite-fastrand-datasette-sqlite-utils-wheels 184 | path: dist/release/wheels/*.whl 185 | upload-crate: 186 | runs-on: ubuntu-latest 187 | steps: 188 | - uses: actions/checkout@v2 189 | - uses: actions-rs/toolchain@v1 190 | with: 191 | toolchain: stable 192 | - run: cargo publish 193 | env: 194 | CARGO_REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }} 195 | upload-extensions: 196 | name: Upload release assets 197 | needs: 198 | [ 199 | build-macos-extension, 200 | build-macos-arm-extension, 201 | build-ubuntu-extension, 202 | build-windows-extension, 203 | ] 204 | permissions: 205 | contents: write 206 | runs-on: ubuntu-latest 207 | steps: 208 | - uses: actions/checkout@v2 209 | - uses: actions/download-artifact@v2 210 | - uses: asg017/upload-spm@main 211 | id: upload-spm 212 | with: 213 | name: sqlite-fastrand 214 | github-token: ${{ secrets.GITHUB_TOKEN }} 215 | platforms: | 216 | linux-x86_64: sqlite-fastrand-ubuntu/* 217 | macos-x86_64: sqlite-fastrand-macos/* 218 | macos-aarch64: sqlite-fastrand-macos-arm/* 219 | windows-x86_64: sqlite-fastrand-windows/* 220 | upload_pypi: 221 | needs: 222 | [ 223 | build-ubuntu-python, 224 | build-macos-python, 225 | build-macos-arm-python, 226 | build-windows-python, 227 | build-datasette-sqlite-utils, 228 | ] 229 | runs-on: ubuntu-latest 230 | steps: 231 | - uses: actions/download-artifact@v3 232 | with: 233 | name: sqlite-fastrand-windows-wheels 234 | path: dist 235 | - uses: actions/download-artifact@v3 236 | with: 237 | name: sqlite-fastrand-ubuntu-wheels 238 | path: dist 239 | - uses: actions/download-artifact@v3 240 | with: 241 | name: sqlite-fastrand-macos-wheels 242 | path: dist 243 | - uses: actions/download-artifact@v3 244 | with: 245 | name: sqlite-fastrand-macos-arm-wheels 246 | path: dist 247 | - uses: actions/download-artifact@v3 248 | with: 249 | name: sqlite-fastrand-datasette-sqlite-utils-wheels 250 | path: dist 251 | - uses: pypa/gh-action-pypi-publish@release/v1 252 | with: 253 | password: ${{ secrets.PYPI_API_TOKEN }} 254 | skip_existing: true 255 | upload-deno: 256 | name: Upload Deno release assets 257 | needs: 258 | [ 259 | build-macos-extension, 260 | build-macos-arm-extension, 261 | build-ubuntu-extension, 262 | build-windows-extension, 263 | ] 264 | permissions: 265 | contents: write 266 | runs-on: ubuntu-latest 267 | steps: 268 | - uses: actions/checkout@v3 269 | - name: Download workflow artifacts 270 | uses: actions/download-artifact@v2 271 | - uses: actions/github-script@v6 272 | with: 273 | github-token: ${{ secrets.GITHUB_TOKEN }} 274 | script: | 275 | const script = require('.github/workflows/upload-deno-assets.js') 276 | await script({github, context}) 277 | upload-npm: 278 | needs: 279 | [ 280 | build-macos-extension, 281 | build-macos-arm-extension, 282 | build-ubuntu-extension, 283 | build-windows-extension, 284 | ] 285 | runs-on: ubuntu-latest 286 | steps: 287 | - uses: actions/checkout@v3 288 | - name: Download workflow artifacts 289 | uses: actions/download-artifact@v2 290 | - run: | 291 | cp sqlite-fastrand-ubuntu/fastrand0.so npm/sqlite-fastrand-linux-x64/lib/fastrand0.so 292 | cp sqlite-fastrand-macos/fastrand0.dylib npm/sqlite-fastrand-darwin-x64/lib/fastrand0.dylib 293 | cp sqlite-fastrand-macos-arm/fastrand0.dylib npm/sqlite-fastrand-darwin-arm64/lib/fastrand0.dylib 294 | cp sqlite-fastrand-windows/fastrand0.dll npm/sqlite-fastrand-windows-x64/lib/fastrand0.dll 295 | - name: Install node 296 | uses: actions/setup-node@v3 297 | with: 298 | node-version: "16" 299 | registry-url: "https://registry.npmjs.org" 300 | - name: Publish NPM sqlite-fastrand-linux-x64 301 | working-directory: npm/sqlite-fastrand-linux-x64 302 | run: npm publish --access public 303 | env: 304 | NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} 305 | - name: Publish NPM sqlite-fastrand-darwin-x64 306 | working-directory: npm/sqlite-fastrand-darwin-x64 307 | run: npm publish --access public 308 | env: 309 | NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} 310 | - name: Publish NPM sqlite-fastrand-darwin-arm64 311 | working-directory: npm/sqlite-fastrand-darwin-arm64 312 | run: npm publish --access public 313 | env: 314 | NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} 315 | - name: Publish NPM sqlite-fastrand-windows-x64 316 | working-directory: npm/sqlite-fastrand-windows-x64 317 | run: npm publish --access public 318 | env: 319 | NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} 320 | - name: Publish NPM sqlite-fastrand 321 | working-directory: npm/sqlite-fastrand 322 | run: npm publish --access public 323 | env: 324 | NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} 325 | upload-gem: 326 | needs: 327 | [ 328 | build-macos-extension, 329 | build-macos-arm-extension, 330 | build-ubuntu-extension, 331 | build-windows-extension, 332 | ] 333 | permissions: 334 | contents: write 335 | runs-on: ubuntu-latest 336 | steps: 337 | - uses: actions/checkout@v2 338 | - uses: actions/download-artifact@v2 339 | - uses: ruby/setup-ruby@v1 340 | with: 341 | ruby-version: 3.2 342 | - run: | 343 | rm bindings/ruby/lib/*.{dylib,so,dll} || true 344 | cp sqlite-fastrand-macos/*.dylib bindings/ruby/lib 345 | gem -C bindings/ruby build -o x86_64-darwin.gem sqlite_fastrand.gemspec 346 | env: 347 | PLATFORM: x86_64-darwin 348 | - run: | 349 | rm bindings/ruby/lib/*.{dylib,so,dll} || true 350 | cp sqlite-fastrand-macos-arm/*.dylib bindings/ruby/lib 351 | gem -C bindings/ruby build -o arm64-darwin.gem sqlite_fastrand.gemspec 352 | env: 353 | PLATFORM: arm64-darwin 354 | - run: | 355 | rm bindings/ruby/lib/*.{dylib,so,dll} || true 356 | cp sqlite-fastrand-ubuntu/*.so bindings/ruby/lib 357 | gem -C bindings/ruby build -o x86_64-linux.gem sqlite_fastrand.gemspec 358 | env: 359 | PLATFORM: x86_64-linux 360 | - run: | 361 | rm bindings/ruby/lib/*.{dylib,so,dll} || true 362 | cp sqlite-fastrand-windows/*.dll bindings/ruby/lib 363 | gem -C bindings/ruby build -o ${{ env.PLATFORM }}.gem sqlite_fastrand.gemspec 364 | env: 365 | PLATFORM: x64-mingw32 366 | - run: | 367 | gem push bindings/ruby/x86_64-linux.gem 368 | gem push bindings/ruby/x86_64-darwin.gem 369 | gem push bindings/ruby/arm64-darwin.gem 370 | gem push bindings/ruby/x64-mingw32.gem 371 | env: 372 | GEM_HOST_API_KEY: ${{ secrets.GEM_HOST_API_KEY }} 373 | --------------------------------------------------------------------------------