├── tests ├── __init__.py ├── conftest.py ├── test_deltabase_workflow.py ├── test_magic.ipynb └── test_deltabase.py ├── .python-version ├── docs ├── assets │ ├── css │ │ └── extra.css │ ├── logo.png │ ├── favicon.png │ └── banner.svg ├── errors.md ├── checkout.md ├── configure.md ├── delete.md ├── commit.md ├── sql_context.md ├── index.md ├── upsert.md ├── register.md └── connect.md ├── .devcontainer ├── dockerfile └── devcontainer.json ├── .gitignore ├── pyproject.toml ├── mkdocs.yml ├── deltabase ├── magic.py └── __init__.py ├── README.md ├── requirements.txt ├── examples └── magic.ipynb └── LICENSE /tests/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /.python-version: -------------------------------------------------------------------------------- 1 | 3.11.6 2 | -------------------------------------------------------------------------------- /docs/assets/css/extra.css: -------------------------------------------------------------------------------- 1 | :root { 2 | --md-code-font: "Verdana"; 3 | } -------------------------------------------------------------------------------- /docs/assets/logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/uname-n/deltabase/HEAD/docs/assets/logo.png -------------------------------------------------------------------------------- /docs/assets/favicon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/uname-n/deltabase/HEAD/docs/assets/favicon.png -------------------------------------------------------------------------------- /.devcontainer/dockerfile: -------------------------------------------------------------------------------- 1 | ARG VARIANT="3.10-bullseye" 2 | FROM mcr.microsoft.com/vscode/devcontainers/python:0-${VARIANT} 3 | 4 | -------------------------------------------------------------------------------- /tests/conftest.py: -------------------------------------------------------------------------------- 1 | from shutil import rmtree 2 | from os.path import exists 3 | 4 | def pytest_sessionfinish(session, exitstatus): 5 | if exists("test.delta"): rmtree("test.delta") -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .venv/ 2 | *.delta/ 3 | dist 4 | __pycache__ 5 | .pytest_cache 6 | _playground.* 7 | *.db 8 | .DS_Store 9 | docs/build/ 10 | site/ 11 | .env 12 | *.txt 13 | examples/delta -------------------------------------------------------------------------------- /docs/errors.md: -------------------------------------------------------------------------------- 1 | If any errors occur during operations, they are returned by the methods as exceptions. Handle these exceptions to debug or manage issues in your workflows. 2 | 3 | ```python 4 | try: 5 | db.commit(database="mydatabase", table="mytable") 6 | except Exception as e: 7 | print(f"Error: {e}") 8 | ``` 9 | 10 | --- -------------------------------------------------------------------------------- /docs/checkout.md: -------------------------------------------------------------------------------- 1 | To revert to a previous version of a table, use the `checkout` method. This allows you to load historical data or restore a previous state. 2 | 3 | ```python 4 | db.checkout(database="mydatabase", table="mytable", version=1) 5 | db.checkout(database="mydatabase", table="mytable", version="2024-01-01") 6 | db.checkout(database="mydatabase", table="mytable", version=datetime(2024, 1, 1)) 7 | ``` 8 | 9 | --- 10 | -------------------------------------------------------------------------------- /docs/configure.md: -------------------------------------------------------------------------------- 1 | You can configure the Delta instance to output different data formats by setting the `dtype` attribute of the configuration object. The default format is `json`, but you can change it to `polars` for better performance or other formats as needed. 2 | 3 | ```python 4 | from deltabase import delta 5 | 6 | db:delta = delta.connect(path="local_path/mydelta") 7 | db.config.dtype = "polars" 8 | ``` 9 | 10 | --- 11 | -------------------------------------------------------------------------------- /docs/delete.md: -------------------------------------------------------------------------------- 1 | To delete records from a table or remove a table from the SQL context, use the `delete` method. You can delete specific records based on a condition or remove all records. 2 | 3 | ```python 4 | # delete records with sql condition 5 | db.delete(table="mytable", filter="name='bob'") 6 | 7 | # delete records using a lambda function 8 | db.delete(table="mytable", filter=lambda row: row["name"] == "sam") 9 | 10 | # delete table from sql context 11 | db.delete(table="mytable") 12 | ``` 13 | 14 | --- 15 | -------------------------------------------------------------------------------- /docs/commit.md: -------------------------------------------------------------------------------- 1 | To persist changes made in the SQL context back to the delta source, use the `commit` method. You can enforce schema changes or partition your data during the commit process. 2 | 3 | ```python 4 | db.commit(database="mydatabase", table="mytable") 5 | ``` 6 | 7 | --- 8 | 9 | > `#!python db.commit(..., force=True)` 10 | 11 | Force schema changes when committing data to the delta source. 12 | 13 | --- 14 | 15 | > `#!python db.commit(..., partition_by=["job"])` 16 | 17 | Partition the table by one or more columns when committing data. 18 | 19 | --- 20 | -------------------------------------------------------------------------------- /docs/sql_context.md: -------------------------------------------------------------------------------- 1 | You can run SQL queries against your registered tables using the `sql` method. This allows you to interact with your data using standard SQL syntax. 2 | 3 | ```python 4 | db.sql("select * from mytable") 5 | ``` 6 | 7 | --- 8 | 9 | > `#!python db.sql("select * from mytable", dtype="polars")` 10 | 11 | You can specify the output format of the query using the `dtype` parameter, such as `polars` for fast data processing. 12 | 13 | --- 14 | 15 | > `#!python db.sql("select * from mytable", lazy=True)` 16 | 17 | If you prefer to defer execution, you can return a LazyFrame by setting the `lazy` parameter to `True`. 18 | 19 | --- 20 | -------------------------------------------------------------------------------- /.devcontainer/devcontainer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "deltabase", 3 | "build":{ 4 | "dockerfile": "dockerfile", 5 | "context": ".", 6 | "args": { 7 | "VARIANT": "3.11-bullseye" 8 | } 9 | }, 10 | 11 | "features": { 12 | "github-cli": "latest" 13 | }, 14 | 15 | "postCreateCommand": "bash ./.devcontainer/post-install.sh", 16 | 17 | "customizations": { 18 | "vscode": { 19 | "extensions": [ 20 | "ms-vscode.cpptools-themes", 21 | "ms-toolsai.jupyter", 22 | "ms-python.python" 23 | ], 24 | "settings": { 25 | "workbench.colorTheme": "Visual Studio 2017 Dark - C++" 26 | } 27 | } 28 | }, 29 | 30 | "remoteUser": "vscode" 31 | } 32 | -------------------------------------------------------------------------------- /docs/index.md: -------------------------------------------------------------------------------- 1 | # Getting Started 2 | 3 | ## Install 4 | To install **DeltaBase**, run the following command: 5 | ```bash 6 | pip install deltabase 7 | ``` 8 | 9 | ## Quick Start 10 | ```python 11 | from deltabase import delta 12 | 13 | # connect to a delta source 14 | db:delta = delta.connect(path="mydelta") 15 | 16 | # upsert records into a table 17 | db.upsert(table="mytable", primary_key="id", data=[ 18 | {"id": 1, "name": "alice"} 19 | ]) 20 | 21 | # commit table to delta source 22 | db.commit(table="mytable") 23 | 24 | # read records from sql context 25 | result = db.sql("select * from mytable") 26 | print(result) # output: [{"id": 1, "name": "alice"}] 27 | ``` -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [tool.poetry] 2 | name = "deltabase" 3 | version = "1.1.0" 4 | description = "" 5 | authors = ["uname-n "] 6 | readme = "README.md" 7 | packages = [{include = "deltabase"}] 8 | 9 | [tool.poetry.dependencies] 10 | python = "^3.11" 11 | polars = "^1.6.0" 12 | deltalake = "^0.19.0" 13 | ipython = {version="^8.26.0", optional=true} 14 | openai = {version="^1.43.0", optional=true} 15 | 16 | [tool.poetry.group.dev.dependencies] 17 | pytest = "^8.3.2" 18 | mkdocs = "^1.6.0" 19 | mkdocs-material = "^9.5.31" 20 | ipykernel = "^6.29.5" 21 | pandas = "^2.2.2" 22 | 23 | [tool.poetry.extras] 24 | magic = ["ipython"] 25 | ai = ["ipython", "openai"] 26 | 27 | [build-system] 28 | requires = ["poetry-core"] 29 | build-backend = "poetry.core.masonry.api" 30 | -------------------------------------------------------------------------------- /docs/upsert.md: -------------------------------------------------------------------------------- 1 | To insert new records or update existing records in a table, use the `upsert` method. This method allows you to keep your data synchronized while managing schema changes automatically. 2 | 3 | --- 4 | 5 | Insert or update a single record: 6 | 7 | ```python 8 | db.upsert(database="mydatabase", table="mytable", primary_key="id", data={ 9 | "id": 1, 10 | "name": "alice" 11 | }) 12 | ``` 13 | 14 | --- 15 | 16 | Insert or update multiple records at once: 17 | 18 | ```python 19 | db.upsert(database="mydatabase", table="mytable", primary_key="id", data=[ 20 | {"id": 1, "name": "ali"}, 21 | {"id": 2, "name": "bob", "job": "chef"}, 22 | {"id": 3, "name": "sam"}, 23 | ]) 24 | ``` 25 | 26 | --- 27 | 28 | > `#!python db.upsert(..., data=DataFrame([{"id": 1, "name": "ali"}]))` 29 | 30 | You can upsert data directly from a DataFrame. 31 | 32 | --- 33 | 34 | > `#!python db.upsert(..., data=LazyFrame([{"id": 1, "name": "ali"}]))` 35 | 36 | Or, upsert data using a LazyFrame for more efficient operations. 37 | 38 | --- 39 | -------------------------------------------------------------------------------- /docs/register.md: -------------------------------------------------------------------------------- 1 | To load or register a table in the SQL context from a delta source, use the `register` method. You can register tables from the delta source, load a specific version, or register a DataFrame or LazyFrame directly. 2 | 3 | --- 4 | 5 | Register a table from a specific database in the delta source: 6 | 7 | ```python 8 | db.register(database="mydatabase", table="mytable") 9 | ``` 10 | 11 | --- 12 | 13 | > `#!python db.register(..., alias="table")` 14 | 15 | You can assign an alias to the registered table within the SQL context for easier reference. 16 | 17 | --- 18 | 19 | > `#!python db.register(..., version=1)` 20 | 21 | Load a specific version of the table by specifying the version number. 22 | 23 | --- 24 | 25 | > `#!python db.register(..., data=...)` 26 | 27 | Register a DataFrame or LazyFrame directly instead of loading it from the Delta source. 28 | 29 | --- 30 | 31 | > `#!python db.register(..., pyarrow_options={"partitions": [("year", "=", "2021")]})` 32 | 33 | Use `pyarrow_options` to specify partition filters or other advanced options when loading the table. 34 | 35 | --- 36 | -------------------------------------------------------------------------------- /docs/connect.md: -------------------------------------------------------------------------------- 1 | To connect to a delta source instance, use the `connect` method provided by the `delta` class. This method allows you to connect to either a local file path or a remote cloud storage service (such as AWS S3, Azure Data Lake, or Google Cloud Storage). The method returns an instance of the `delta` class, which you can use to manage your Delta tables. 2 | 3 | ```python 4 | from deltabase import delta 5 | 6 | db:delta = delta.connect(path="local_path/mydelta") 7 | ``` 8 | 9 | --- 10 | 11 | > on connect, delta will attempt to load tables if path is local. 12 | 13 | --- 14 | 15 | > `#!python db:delta = delta.connect(path="s3://")` 16 | 17 | You can also connect to a delta source stored in an AWS S3 bucket. Replace `` with the actual bucket name and path. 18 | 19 | --- 20 | 21 | > `#!python db:delta = delta.connect(path="://")` 22 | 23 | For Azure, you can connect to an Azure Data Lake Storage (ADLS) or Azure Blob Storage using the appropriate URI scheme (`az://`, `adl://`, or `abfs[s]://`). 24 | 25 | --- 26 | 27 | > `#!python db:delta = delta.connect(path="gs://")` 28 | 29 | For Google Cloud Storage, use the `gs://` prefix followed by the bucket name and path. 30 | 31 | --- 32 | -------------------------------------------------------------------------------- /mkdocs.yml: -------------------------------------------------------------------------------- 1 | site_name: DeltaBase 2 | 3 | nav: 4 | - Getting Started: index.md 5 | - Connect: connect.md 6 | - Configure: configure.md 7 | - Register: register.md 8 | - Upsert: upsert.md 9 | - SQL Context: sql_context.md 10 | - Delete: delete.md 11 | - Commit: commit.md 12 | - Checkout: checkout.md 13 | - Errors: errors.md 14 | 15 | theme: 16 | name: material 17 | logo: assets/logo.png 18 | favicon: assets/favicon.png 19 | features: 20 | - navigation.sections 21 | - toc.integrate 22 | - navigation.top 23 | - search.suggest 24 | - search.highlight 25 | - content.code.annotate 26 | - content.code.copy 27 | language: en 28 | palette: 29 | # Palette toggle for automatic mode 30 | - media: "(prefers-color-scheme)" 31 | toggle: 32 | icon: material/brightness-auto 33 | name: Switch to light mode 34 | 35 | # Palette toggle for light mode 36 | - media: "(prefers-color-scheme: light)" 37 | scheme: default 38 | toggle: 39 | icon: material/brightness-7 40 | name: Switch to dark mode 41 | primary: blue grey 42 | accent: light blue 43 | 44 | # Palette toggle for dark mode 45 | - media: "(prefers-color-scheme: dark)" 46 | scheme: slate 47 | toggle: 48 | icon: material/brightness-4 49 | name: Switch to system preference 50 | primary: blue grey 51 | accent: light blue 52 | 53 | markdown_extensions: 54 | - pymdownx.highlight: 55 | anchor_linenums: true 56 | line_spans: __span 57 | pygments_lang_class: true 58 | - pymdownx.inlinehilite 59 | - pymdownx.snippets 60 | - pymdownx.superfences 61 | - pymdownx.snippets 62 | - pymdownx.details 63 | - pymdownx.mark 64 | - pymdownx.betterem 65 | -------------------------------------------------------------------------------- /tests/test_deltabase_workflow.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | 3 | from deltabase import delta 4 | 5 | from polars import DataFrame 6 | from os.path import exists 7 | from os import listdir 8 | from time import time 9 | 10 | TIMEOUT = 20 11 | W = 1_000 12 | H = 1_000 13 | 14 | data = lambda w, h: [{"name":f"name_{_}", **{f"field_{n}":n+_ for n in range(w)}} for _ in range(h)] 15 | testing_data = data(W, H) 16 | 17 | @pytest.fixture 18 | def db(): 19 | return delta.connect(path="test.delta") 20 | 21 | def test_connect(db): 22 | assert isinstance(db, delta) 23 | assert db.tables == [] 24 | 25 | def test_add_data(db): 26 | s = time() 27 | err = db.upsert(table="test_table", primary_key="name", data=testing_data) 28 | assert not err, err 29 | e = time() 30 | result = db.sql("select * from test_table", dtype="polars") 31 | 32 | assert isinstance(result, DataFrame) 33 | assert result.shape == (W, H+1) 34 | assert (e-s) < TIMEOUT 35 | 36 | def test_first_commit(db): 37 | err = db.commit("test_table") 38 | assert not err, err 39 | 40 | assert exists("test.delta/default/test_table") 41 | assert len(listdir("test.delta/default/test_table")) == 2 42 | assert len(listdir("test.delta/default/test_table/_delta_log")) == 1 43 | 44 | def test_delete_records(db): 45 | err = db.delete("test_table", filter="field_6 % 2 == 0") 46 | assert not err, err 47 | 48 | result = db.sql("select * from test_table", dtype="polars") 49 | assert 0 < result.shape[0] < W 50 | assert result.shape[1] == H+1 51 | 52 | def test_second_commit(db): 53 | err = db.commit("test_table") 54 | assert not err, err 55 | 56 | assert len(listdir("test.delta/default/test_table")) == 3 57 | assert len(listdir("test.delta/default/test_table/_delta_log")) == 2 58 | 59 | def test_checkout_original_commit(db): 60 | err = db.checkout("test_table", version=1) 61 | assert not err, err 62 | 63 | result = db.sql("select * from test_table", dtype="polars") 64 | 65 | assert isinstance(result, DataFrame) 66 | assert result.shape == (W, H+1) -------------------------------------------------------------------------------- /deltabase/magic.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | 4 | # Copyright 2024 darryl mcculley 5 | 6 | # This program is free software: you can redistribute it and/or modify 7 | # it under the terms of the GNU General Public License as published by 8 | # the Free Software Foundation, either version 3 of the License, or 9 | # any later version. 10 | 11 | # This program is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # GNU General Public License for more details. 15 | 16 | # You should have received a copy of the GNU General Public License 17 | # along with this program. If not, see . 18 | 19 | try: 20 | from IPython.core.magic import Magics, magics_class, cell_magic, line_magic 21 | from IPython.display import Markdown, display 22 | from IPython import get_ipython 23 | except ImportError: 24 | raise ImportError("`deltabase[magic]` package required for magic.") 25 | 26 | from . import delta 27 | 28 | from json import dumps 29 | 30 | @magics_class 31 | class magic (Magics): 32 | def __init__(self, shell, delta:delta): 33 | super(magic, self).__init__(shell) 34 | self.__openai_chat_history = [] 35 | self.delta = delta 36 | 37 | @cell_magic 38 | def sql(self, line, cell): 39 | data = self.delta.sql(query=cell, dtype="polars") 40 | 41 | args = line.split(" ") 42 | if "--table" in line and "--key" in line: 43 | table = args[args.index("--table")+1] 44 | key = args[args.index("--key")+1] 45 | if "--database" in line: database = args[args.index("--upsert")+1] 46 | else: database = "default" 47 | self.delta.upsert(database=database, table=table, primary_key=key, data=data) 48 | 49 | return data 50 | 51 | @cell_magic 52 | def ai(self, line, cell): 53 | try: from openai import OpenAI 54 | except: raise ImportError("`deltabase[ai]` package required for `ai` magic.") 55 | client = OpenAI() 56 | 57 | context = "" 58 | for table in self.delta.tables: 59 | schema = self.delta.schema(table=table) 60 | if schema: context += f"- {table}: {schema}\n" 61 | 62 | messages = [ 63 | {"role": "system", "content": ( 64 | "answer the user's question. " 65 | "below is the data they have access to." 66 | "data can be accessed via sql.\n" 67 | )}, 68 | {"role": "system", "content": f"here is the data available to the user.\n" + context} 69 | ] 70 | 71 | for question, answer in self.__openai_chat_history: 72 | messages.append({"role": "user", "content":question}) 73 | messages.append({"role": "assistant", "content":answer}) 74 | messages.append({"role": "user", "content":cell}) 75 | 76 | if "--debug" in line: return display(Markdown(f"```json\n{dumps(messages, indent=4)}\n```")) 77 | 78 | completion = client.chat.completions.create( 79 | model=self.delta.config.ai_model, 80 | messages=messages 81 | ) 82 | 83 | response = completion.choices[0].message.content 84 | self.__openai_chat_history.append((cell, response)) 85 | return display(Markdown(response)) 86 | 87 | @line_magic 88 | def ai_chat(self, line): 89 | match line: 90 | case "clear": self.__openai_chat_history = [] 91 | case "undo": self.__openai_chat_history.pop() 92 | 93 | def enable(delta:delta): 94 | ipython = get_ipython() 95 | if ipython: ipython.register_magics(magic(ipython, delta)) -------------------------------------------------------------------------------- /tests/test_magic.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": 1, 6 | "metadata": {}, 7 | "outputs": [], 8 | "source": [ 9 | "from deltabase import delta\n", 10 | "\n", 11 | "db:delta = delta.connect(\"path\")" 12 | ] 13 | }, 14 | { 15 | "cell_type": "code", 16 | "execution_count": 2, 17 | "metadata": {}, 18 | "outputs": [], 19 | "source": [ 20 | "db.upsert(\"mytable\", \"id\", {\"id\":1, \"name\":\"jim\"})" 21 | ] 22 | }, 23 | { 24 | "cell_type": "code", 25 | "execution_count": 3, 26 | "metadata": { 27 | "vscode": { 28 | "languageId": "sql" 29 | } 30 | }, 31 | "outputs": [ 32 | { 33 | "data": { 34 | "text/html": [ 35 | "
\n", 42 | "shape: (1, 2)
idname
i64str
1"jim"
" 43 | ], 44 | "text/plain": [ 45 | "shape: (1, 2)\n", 46 | "┌─────┬──────┐\n", 47 | "│ id ┆ name │\n", 48 | "│ --- ┆ --- │\n", 49 | "│ i64 ┆ str │\n", 50 | "╞═════╪══════╡\n", 51 | "│ 1 ┆ jim │\n", 52 | "└─────┴──────┘" 53 | ] 54 | }, 55 | "execution_count": 3, 56 | "metadata": {}, 57 | "output_type": "execute_result" 58 | } 59 | ], 60 | "source": [ 61 | "%%sql --table newtable --key id\n", 62 | "select * from mytable" 63 | ] 64 | }, 65 | { 66 | "cell_type": "code", 67 | "execution_count": 4, 68 | "metadata": {}, 69 | "outputs": [ 70 | { 71 | "data": { 72 | "text/plain": [ 73 | "['mytable', 'newtable']" 74 | ] 75 | }, 76 | "execution_count": 4, 77 | "metadata": {}, 78 | "output_type": "execute_result" 79 | } 80 | ], 81 | "source": [ 82 | "db.tables" 83 | ] 84 | }, 85 | { 86 | "cell_type": "code", 87 | "execution_count": 5, 88 | "metadata": {}, 89 | "outputs": [], 90 | "source": [ 91 | "db.upsert(\"mytable\", \"id\", {\"id\":1, \"name\":\"jimbob\"})\n", 92 | "db.upsert(\"mytabl1\", \"id\", {\"id\":1, \"name\":\"jimbob\"})\n", 93 | "db.upsert(\"mytabl2\", \"id\", {\"id\":1, \"name\":\"jimbob\"})\n", 94 | "db.upsert(\"mytabl3\", \"id\", {\"id\":1, \"name\":\"jimbob\"})\n", 95 | "db.upsert(\"mytabl4\", \"id\", {\"id\":1, \"name\":\"jimbob\"})" 96 | ] 97 | }, 98 | { 99 | "cell_type": "code", 100 | "execution_count": 6, 101 | "metadata": {}, 102 | "outputs": [ 103 | { 104 | "data": { 105 | "text/markdown": [ 106 | "```json\n", 107 | "[\n", 108 | " {\n", 109 | " \"role\": \"system\",\n", 110 | " \"content\": \"answer the user's question. below is the data they have access to.data can be accessed via sql.\\n\"\n", 111 | " },\n", 112 | " {\n", 113 | " \"role\": \"system\",\n", 114 | " \"content\": \"here is the data available to the user.\\n- mytabl1: {'id': , 'name': }\\n- mytabl2: {'id': , 'name': }\\n- mytabl3: {'id': , 'name': }\\n- mytabl4: {'id': , 'name': }\\n- mytable: {'id': , 'name': }\\n- newtable: {'id': , 'name': }\\n\"\n", 115 | " },\n", 116 | " {\n", 117 | " \"role\": \"user\",\n", 118 | " \"content\": \"describe the data available to me.\\n\"\n", 119 | " }\n", 120 | "]\n", 121 | "```" 122 | ], 123 | "text/plain": [ 124 | "" 125 | ] 126 | }, 127 | "metadata": {}, 128 | "output_type": "display_data" 129 | } 130 | ], 131 | "source": [ 132 | "%%ai --debug\n", 133 | "describe the data available to me." 134 | ] 135 | } 136 | ], 137 | "metadata": { 138 | "kernelspec": { 139 | "display_name": ".venv", 140 | "language": "python", 141 | "name": "python3" 142 | }, 143 | "language_info": { 144 | "codemirror_mode": { 145 | "name": "ipython", 146 | "version": 3 147 | }, 148 | "file_extension": ".py", 149 | "mimetype": "text/x-python", 150 | "name": "python", 151 | "nbconvert_exporter": "python", 152 | "pygments_lexer": "ipython3", 153 | "version": "3.12.2" 154 | } 155 | }, 156 | "nbformat": 4, 157 | "nbformat_minor": 2 158 | } 159 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |

2 | banner 3 |

4 | 5 |

6 | documentation (wip) 7 |

8 | 9 | **DeltaBase** is a lightweight, comprehensive solution for managing Delta Tables in both local and cloud environments. Built on the high-performance frameworks [**polars**](https://github.com/pola-rs/polars) and [**deltalake**](https://github.com/delta-io/delta-rs), DeltaBase streamlines data operations with features like upsert, delete, commit, and version control. Designed for data engineers, analysts, and developers, it ensures data consistency, efficient versioning, and seamless integration into your workflows. 10 | 11 | ## Installation 12 | To install **DeltaBase**, run the following command: 13 | ```bash 14 | pip install deltabase 15 | ``` 16 | 17 | ## Quick Start 18 | ```python 19 | from deltabase import delta 20 | 21 | # connect to a delta source 22 | db:delta = delta.connect(path="mydelta") 23 | 24 | # upsert records into a table 25 | db.upsert(table="mytable", primary_key="id", data=[ 26 | {"id": 1, "name": "alice"} 27 | ]) 28 | 29 | # commit table to delta source 30 | db.commit(table="mytable") 31 | 32 | # read records from sql context 33 | result = db.sql("select * from mytable") 34 | print(result) # output: [{"id": 1, "name": "alice"}] 35 | ``` 36 | 37 | See a full example of **DeltaBase** in action [here](https://github.com/uname-n/deltabase/blob/master/examples/magic.ipynb). 38 | 39 | ## Usage 40 | 41 | ### Connecting to a Delta Source 42 | Establish a connection to your Delta source, whether it's a local directory or remote cloud storage. 43 | 44 | ```python 45 | from deltabase import delta 46 | 47 | db = delta.connect(path="local_path/mydelta") 48 | db = delta.connect(path="s3://your-bucket/path") 49 | db = delta.connect(path="az://your-container/path") 50 | db = delta.connect(path="abfs[s]://your-container/path") 51 | ``` 52 | 53 | ### Register Tables 54 | Load tables into the SQL context from the Delta source using the `register` method. You can also register data directly from a DataFrame or specify options like version and alias. 55 | 56 | ```python 57 | # load existing table from delta 58 | db.register(table="mytable") 59 | 60 | # load under an alias 61 | db.register(table="mytable", alias="table_alias") 62 | 63 | # load a specific version 64 | db.register(table="mytable", version=1) 65 | 66 | # load data directly 67 | data = DataFrame([{"id": 1, "name": "Alice"}]) 68 | db.register(table="mytable", data=data) 69 | 70 | # load with pyarrow options 71 | db.register( 72 | table="mytable", 73 | pyarrow_options={"partitions": [("year", "=", "2021")]} 74 | ) 75 | ``` 76 | 77 | ### Running SQL Queries 78 | Execute SQL queries against your registered tables using the `sql` method. 79 | 80 | ```python 81 | # run a query and get the result in json format 82 | result = db.sql("select * from mytable") 83 | 84 | # get the result as a polars dataframe 85 | result = db.sql("select * from mytable", dtype="polars") 86 | 87 | # return a LazyFrame for deferred execution 88 | result = db.sql("select * from mytable", lazy=True) 89 | ``` 90 | 91 | ### Upserting Data 92 | Insert new records or update existing ones using the `upsert` method. It automatically handles schema changes and efficiently synchronizes data. 93 | 94 | ```python 95 | # upsert a single record 96 | db.upsert( 97 | table="mytable", 98 | primary_key="id", 99 | data={"id": 1, "name": "Alice"} 100 | ) 101 | 102 | # upsert multiple records 103 | db.upsert( 104 | table="mytable", 105 | primary_key="id", 106 | data=[ 107 | {"id": 2, "name": "Bob", "job": "Chef"}, 108 | {"id": 3, "name": "Sam"}, 109 | ] 110 | ) 111 | 112 | # upsert dataframes 113 | data = DataFrame([{"id": 4, "name": "Dave"}]) 114 | db.upsert(table="mytable", primary_key="id", data=data) 115 | 116 | # upsert lazyframes 117 | data = LazyFrame([{"id": 5, "name": "Eve"}]) 118 | db.upsert(table="mytable", primary_key="id", data=data) 119 | ``` 120 | 121 | ### Committing Changes 122 | Persist changes made in the SQL context back to the Delta source using the `commit` method. You can enforce schema changes or partition your data during this process. 123 | 124 | 125 | ```python 126 | db.commit(table="mytable") 127 | db.commit(table="mytable", force=True) 128 | db.commit(table="mytable", partition_by=["job"]) 129 | ``` 130 | 131 | ### Deleting Data 132 | Remove records from a table or delete the table from the SQL context using the delete method. 133 | 134 | ```python 135 | # delete records using a sql condition 136 | db.delete(table="mytable", filter="name='Bob'") 137 | 138 | # delete records using a lambda function 139 | db.delete(table="mytable", filter=lambda row: row["name"] == "Sam") 140 | 141 | # delete table from sql context 142 | db.delete(table="mytable") 143 | ``` 144 | 145 | ### Checking Out Previous Versions 146 | Revert to a previous version of a table using the `checkout` method. This is useful for loading historical data or restoring a previous state. 147 | 148 | ```python 149 | # get a specific version by number 150 | db.checkout(table="mytable", version=1) 151 | 152 | # get out a version by date string 153 | db.checkout(table="mytable", version="2024-01-01") 154 | 155 | # get out a version by datetime object 156 | db.checkout(table="mytable", version=datetime(2024, 1, 1)) 157 | ``` 158 | 159 | ### Configuring Output Data Types 160 | Set the output data format by adjusting the `dtype` attribute in the configuration object. The default format is `json`. 161 | 162 | ```python 163 | # set output data type to polars dataframe 164 | db.config.dtype = "polars" 165 | 166 | # run a sql query and get results as polars dataframe 167 | result = db.sql("SELECT * FROM mytable") 168 | ``` 169 | 170 | ### Jupyter Notebook Magic 171 | **DeltaBase** provides magic commands for use in Jupyter notebooks, enhancing your interactive data exploration experience. Magic commands are automatically enabled when you connect to delta source within a notebook. 172 | 173 | #### Using SQL Magic 174 | ```sql 175 | %%sql 176 | select * from mytable 177 | ``` 178 | 179 | #### Using AI Magic 180 | ```sql 181 | %%ai 182 | what data is available to me? 183 | ``` -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | deltalake==0.19.0 ; python_version >= "3.12" and python_version < "4.0" \ 2 | --hash=sha256:0783ce640ee97842280953bd6923200262d29d980b53530f4d796a6e4919d9ee \ 3 | --hash=sha256:12fc8ef76294515324de2bc7b44c92f0491a35d33de362e9352f3a2512102ca4 \ 4 | --hash=sha256:21789d9a2c3979f12acb2deac11a47fb28e140af4be137f4dffee99eefb70239 5 | numpy==2.0.1 ; python_version >= "3.12" and python_version < "4.0" \ 6 | --hash=sha256:08458fbf403bff5e2b45f08eda195d4b0c9b35682311da5a5a0a0925b11b9bd8 \ 7 | --hash=sha256:0fbb536eac80e27a2793ffd787895242b7f18ef792563d742c2d673bfcb75134 \ 8 | --hash=sha256:12f5d865d60fb9734e60a60f1d5afa6d962d8d4467c120a1c0cda6eb2964437d \ 9 | --hash=sha256:15eb4eca47d36ec3f78cde0a3a2ee24cf05ca7396ef808dda2c0ddad7c2bde67 \ 10 | --hash=sha256:173a00b9995f73b79eb0191129f2455f1e34c203f559dd118636858cc452a1bf \ 11 | --hash=sha256:1b902ce0e0a5bb7704556a217c4f63a7974f8f43e090aff03fcf262e0b135e02 \ 12 | --hash=sha256:1f682ea61a88479d9498bf2091fdcd722b090724b08b31d63e022adc063bad59 \ 13 | --hash=sha256:1f87fec1f9bc1efd23f4227becff04bd0e979e23ca50cc92ec88b38489db3b55 \ 14 | --hash=sha256:24a0e1befbfa14615b49ba9659d3d8818a0f4d8a1c5822af8696706fbda7310c \ 15 | --hash=sha256:2c3a346ae20cfd80b6cfd3e60dc179963ef2ea58da5ec074fd3d9e7a1e7ba97f \ 16 | --hash=sha256:36d3a9405fd7c511804dc56fc32974fa5533bdeb3cd1604d6b8ff1d292b819c4 \ 17 | --hash=sha256:3fdabe3e2a52bc4eff8dc7a5044342f8bd9f11ef0934fcd3289a788c0eb10018 \ 18 | --hash=sha256:4127d4303b9ac9f94ca0441138acead39928938660ca58329fe156f84b9f3015 \ 19 | --hash=sha256:4658c398d65d1b25e1760de3157011a80375da861709abd7cef3bad65d6543f9 \ 20 | --hash=sha256:485b87235796410c3519a699cfe1faab097e509e90ebb05dcd098db2ae87e7b3 \ 21 | --hash=sha256:529af13c5f4b7a932fb0e1911d3a75da204eff023ee5e0e79c1751564221a5c8 \ 22 | --hash=sha256:5a3d94942c331dd4e0e1147f7a8699a4aa47dffc11bf8a1523c12af8b2e91bbe \ 23 | --hash=sha256:5daab361be6ddeb299a918a7c0864fa8618af66019138263247af405018b04e1 \ 24 | --hash=sha256:61728fba1e464f789b11deb78a57805c70b2ed02343560456190d0501ba37b0f \ 25 | --hash=sha256:6790654cb13eab303d8402354fabd47472b24635700f631f041bd0b65e37298a \ 26 | --hash=sha256:69ff563d43c69b1baba77af455dd0a839df8d25e8590e79c90fcbe1499ebde42 \ 27 | --hash=sha256:6bf4e6f4a2a2e26655717a1983ef6324f2664d7011f6ef7482e8c0b3d51e82ac \ 28 | --hash=sha256:6e4eeb6eb2fced786e32e6d8df9e755ce5be920d17f7ce00bc38fcde8ccdbf9e \ 29 | --hash=sha256:72dc22e9ec8f6eaa206deb1b1355eb2e253899d7347f5e2fae5f0af613741d06 \ 30 | --hash=sha256:75b4e316c5902d8163ef9d423b1c3f2f6252226d1aa5cd8a0a03a7d01ffc6268 \ 31 | --hash=sha256:7b9853803278db3bdcc6cd5beca37815b133e9e77ff3d4733c247414e78eb8d1 \ 32 | --hash=sha256:7d6fddc5fe258d3328cd8e3d7d3e02234c5d70e01ebe377a6ab92adb14039cb4 \ 33 | --hash=sha256:81b0893a39bc5b865b8bf89e9ad7807e16717f19868e9d234bdaf9b1f1393868 \ 34 | --hash=sha256:8efc84f01c1cd7e34b3fb310183e72fcdf55293ee736d679b6d35b35d80bba26 \ 35 | --hash=sha256:8fae4ebbf95a179c1156fab0b142b74e4ba4204c87bde8d3d8b6f9c34c5825ef \ 36 | --hash=sha256:99d0d92a5e3613c33a5f01db206a33f8fdf3d71f2912b0de1739894668b7a93b \ 37 | --hash=sha256:9adbd9bb520c866e1bfd7e10e1880a1f7749f1f6e5017686a5fbb9b72cf69f82 \ 38 | --hash=sha256:a1e01dcaab205fbece13c1410253a9eea1b1c9b61d237b6fa59bcc46e8e89343 \ 39 | --hash=sha256:a8fc2de81ad835d999113ddf87d1ea2b0f4704cbd947c948d2f5513deafe5a7b \ 40 | --hash=sha256:b83e16a5511d1b1f8a88cbabb1a6f6a499f82c062a4251892d9ad5d609863fb7 \ 41 | --hash=sha256:bb2124fdc6e62baae159ebcfa368708867eb56806804d005860b6007388df171 \ 42 | --hash=sha256:bfc085b28d62ff4009364e7ca34b80a9a080cbd97c2c0630bb5f7f770dae9414 \ 43 | --hash=sha256:cbab9fc9c391700e3e1287666dfd82d8666d10e69a6c4a09ab97574c0b7ee0a7 \ 44 | --hash=sha256:e5eeca8067ad04bc8a2a8731183d51d7cbaac66d86085d5f4766ee6bf19c7f87 \ 45 | --hash=sha256:e9e81fa9017eaa416c056e5d9e71be93d05e2c3c2ab308d23307a8bc4443c368 \ 46 | --hash=sha256:ea2326a4dca88e4a274ba3a4405eb6c6467d3ffbd8c7d38632502eaae3820587 \ 47 | --hash=sha256:eacf3291e263d5a67d8c1a581a8ebbcfd6447204ef58828caf69a5e3e8c75990 \ 48 | --hash=sha256:ec87f5f8aca726117a1c9b7083e7656a9d0d606eec7299cc067bb83d26f16e0c \ 49 | --hash=sha256:f1659887361a7151f89e79b276ed8dff3d75877df906328f14d8bb40bb4f5101 \ 50 | --hash=sha256:f9cf5ea551aec449206954b075db819f52adc1638d46a6738253a712d553c7b4 51 | polars==1.6.0 ; python_version >= "3.12" and python_version < "4.0" \ 52 | --hash=sha256:1c811b772c9476f7f0bb4445a8387d2ab6d86f5e79140b1bfba914a32788d261 \ 53 | --hash=sha256:6d1665c23e3574ebd47a26a5d7b619e6e73e53718c3b0bfd7d08b6a0a4ae7daa \ 54 | --hash=sha256:a166adb429f8ee099c9d803e7470a80c76368437a8b272c67cef9eef6d5e9da1 \ 55 | --hash=sha256:d7e8d5e577883a9755bc3be92ecbf6f20bced68267bdb8bdb440120e905cc19c \ 56 | --hash=sha256:d7f3abf085adf034720b358119c4c8e144bcc2d96010b7e7d0afa11b80da383c \ 57 | --hash=sha256:ffae15ffa80fda5cc3af44a340b565bcf7f2ab6d7854d3f967baf505710c78e2 58 | pyarrow==17.0.0 ; python_version >= "3.12" and python_version < "4.0" \ 59 | --hash=sha256:0071ce35788c6f9077ff9ecba4858108eebe2ea5a3f7cf2cf55ebc1dbc6ee24a \ 60 | --hash=sha256:02dae06ce212d8b3244dd3e7d12d9c4d3046945a5933d28026598e9dbbda1fca \ 61 | --hash=sha256:0b72e87fe3e1db343995562f7fff8aee354b55ee83d13afba65400c178ab2597 \ 62 | --hash=sha256:0cdb0e627c86c373205a2f94a510ac4376fdc523f8bb36beab2e7f204416163c \ 63 | --hash=sha256:13d7a460b412f31e4c0efa1148e1d29bdf18ad1411eb6757d38f8fbdcc8645fb \ 64 | --hash=sha256:1c8856e2ef09eb87ecf937104aacfa0708f22dfeb039c363ec99735190ffb977 \ 65 | --hash=sha256:2e19f569567efcbbd42084e87f948778eb371d308e137a0f97afe19bb860ccb3 \ 66 | --hash=sha256:32503827abbc5aadedfa235f5ece8c4f8f8b0a3cf01066bc8d29de7539532687 \ 67 | --hash=sha256:392bc9feabc647338e6c89267635e111d71edad5fcffba204425a7c8d13610d7 \ 68 | --hash=sha256:42bf93249a083aca230ba7e2786c5f673507fa97bbd9725a1e2754715151a204 \ 69 | --hash=sha256:4beca9521ed2c0921c1023e68d097d0299b62c362639ea315572a58f3f50fd28 \ 70 | --hash=sha256:5984f416552eea15fd9cee03da53542bf4cddaef5afecefb9aa8d1010c335087 \ 71 | --hash=sha256:6b244dc8e08a23b3e352899a006a26ae7b4d0da7bb636872fa8f5884e70acf15 \ 72 | --hash=sha256:757074882f844411fcca735e39aae74248a1531367a7c80799b4266390ae51cc \ 73 | --hash=sha256:75c06d4624c0ad6674364bb46ef38c3132768139ddec1c56582dbac54f2663e2 \ 74 | --hash=sha256:7c7916bff914ac5d4a8fe25b7a25e432ff921e72f6f2b7547d1e325c1ad9d155 \ 75 | --hash=sha256:9b564a51fbccfab5a04a80453e5ac6c9954a9c5ef2890d1bcf63741909c3f8df \ 76 | --hash=sha256:9b8a823cea605221e61f34859dcc03207e52e409ccf6354634143e23af7c8d22 \ 77 | --hash=sha256:9ba11c4f16976e89146781a83833df7f82077cdab7dc6232c897789343f7891a \ 78 | --hash=sha256:a155acc7f154b9ffcc85497509bcd0d43efb80d6f733b0dc3bb14e281f131c8b \ 79 | --hash=sha256:a27532c38f3de9eb3e90ecab63dfda948a8ca859a66e3a47f5f42d1e403c4d03 \ 80 | --hash=sha256:a48ddf5c3c6a6c505904545c25a4ae13646ae1f8ba703c4df4a1bfe4f4006bda \ 81 | --hash=sha256:a5c8b238d47e48812ee577ee20c9a2779e6a5904f1708ae240f53ecbee7c9f07 \ 82 | --hash=sha256:af5ff82a04b2171415f1410cff7ebb79861afc5dae50be73ce06d6e870615204 \ 83 | --hash=sha256:b0c6ac301093b42d34410b187bba560b17c0330f64907bfa4f7f7f2444b0cf9b \ 84 | --hash=sha256:d7d192305d9d8bc9082d10f361fc70a73590a4c65cf31c3e6926cd72b76bc35c \ 85 | --hash=sha256:da1e060b3876faa11cee287839f9cc7cdc00649f475714b8680a05fd9071d545 \ 86 | --hash=sha256:db023dc4c6cae1015de9e198d41250688383c3f9af8f565370ab2b4cb5f62655 \ 87 | --hash=sha256:dc5c31c37409dfbc5d014047817cb4ccd8c1ea25d19576acf1a001fe07f5b420 \ 88 | --hash=sha256:dec8d129254d0188a49f8a1fc99e0560dc1b85f60af729f47de4046015f9b0a5 \ 89 | --hash=sha256:e3343cb1e88bc2ea605986d4b94948716edc7a8d14afd4e2c097232f729758b4 \ 90 | --hash=sha256:edca18eaca89cd6382dfbcff3dd2d87633433043650c07375d095cd3517561d8 \ 91 | --hash=sha256:f1e70de6cb5790a50b01d2b686d54aaf73da01266850b05e3af2a1bc89e16053 \ 92 | --hash=sha256:f553ca691b9e94b202ff741bdd40f6ccb70cdd5fbf65c187af132f1317de6145 \ 93 | --hash=sha256:f7ae2de664e0b158d1607699a16a488de3d008ba99b3a7aa5de1cbc13574d047 \ 94 | --hash=sha256:fa3c246cc58cb5a4a5cb407a18f193354ea47dd0648194e6265bd24177982fe8 95 | -------------------------------------------------------------------------------- /tests/test_deltabase.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | 3 | from deltabase import delta 4 | from polars import DataFrame, LazyFrame 5 | from pandas import DataFrame as PandasDataFrame 6 | 7 | from os.path import exists 8 | from shutil import rmtree 9 | 10 | @pytest.fixture 11 | def db(): 12 | _ = delta.connect(path="test.delta") 13 | yield _ 14 | for table in _.tables: 15 | _._delta__delta_sql_context.unregister(table) 16 | if exists("test.delta"): rmtree("test.delta") 17 | 18 | def test_connect(db): 19 | assert isinstance(db, delta) 20 | assert db.tables == [] 21 | 22 | def test_add_record_dict(db): 23 | err = db.upsert(table="test_table", primary_key="id", data=dict(id=1, name="a")) 24 | assert not err, err 25 | 26 | err = db.upsert(table="test_table", primary_key="id", data=[ 27 | dict(id=2, name="b"), 28 | dict(id=3, name="c"), 29 | ]) 30 | assert not err, err 31 | result = db.sql("select * from test_table", dtype="polars") 32 | 33 | assert isinstance(result, DataFrame) 34 | assert result.shape == (3, 2) 35 | assert set(result["id"].to_list()) == set([1,2,3]) 36 | assert set(result["name"].to_list()) == set(["a","b","c"]) 37 | 38 | def test_add_record_dataframe(db): 39 | err = db.upsert(table="test_table", primary_key="id", data=DataFrame([ 40 | dict(id=2, name="b"), 41 | dict(id=3, name="c"), 42 | ])) 43 | assert not err, err 44 | result = db.sql("select * from test_table", dtype="polars") 45 | 46 | assert isinstance(result, DataFrame) 47 | assert result.shape == (2, 2) 48 | assert set(result["id"].to_list()) == set([2,3]) 49 | assert set(result["name"].to_list()) == set(["b","c"]) 50 | 51 | def test_add_record_lazyframe(db): 52 | err = db.upsert(table="test_table", primary_key="id", data=DataFrame([ 53 | dict(id=2, name="b"), 54 | dict(id=3, name="c"), 55 | ]).lazy()) 56 | assert not err, err 57 | result = db.sql("select * from test_table", dtype="polars") 58 | 59 | assert isinstance(result, DataFrame) 60 | assert result.shape == (2, 2) 61 | assert set(result["id"].to_list()) == set([2,3]) 62 | assert set(result["name"].to_list()) == set(["b","c"]) 63 | 64 | def test_add_mismatch_schema(db): 65 | err = db.upsert(table="test_table", primary_key="id", data=[ 66 | dict(id=2, name="b", job="j"), 67 | dict(id=3, name="c"), 68 | ]) 69 | assert not err, err 70 | result = db.sql("select * from test_table", dtype="polars") 71 | 72 | assert isinstance(result, DataFrame) 73 | assert result.shape == (2, 3) 74 | assert set(result["id"].to_list()) == set([2,3]) 75 | assert set(result["name"].to_list()) == set(["b","c"]) 76 | assert set(result["job"].to_list()) == set(["j", None]) 77 | 78 | def test_update_record(db): 79 | db.upsert(table="test_table", primary_key="id", data=dict(id=2, name="a")) 80 | db.upsert(table="test_table", primary_key="id", data=dict(id=2, name="b")) 81 | result = db.sql("select * from test_table", dtype="polars") 82 | 83 | assert isinstance(result, DataFrame) 84 | assert result.shape == (1, 2) 85 | assert set(result["id"].to_list()) == set([2]) 86 | assert set(result["name"].to_list()) == set(["b"]) 87 | 88 | def test_update_mismatch_schema_record(db): 89 | db.upsert(table="test_table", primary_key="id", data=dict(id=2, name="a")) 90 | db.upsert(table="test_table", primary_key="id", data=[dict(id=2, name="b"), dict(id=3, name="c", job="j")]) 91 | result = db.sql("select * from test_table", dtype="polars") 92 | 93 | assert isinstance(result, DataFrame) 94 | assert result.shape == (2, 3) 95 | assert set(result["id"].to_list()) == set([2, 3]) 96 | assert set(result["name"].to_list()) == set(["b", "c"]) 97 | assert set(result["job"].to_list()) == set([None, "j"]) 98 | 99 | def test_delete_record_sql(db): 100 | db.upsert(table="test_table", primary_key="id", data=dict(id=5, name="a")) 101 | db.upsert(table="test_table", primary_key="id", data=dict(id=6, name="b")) 102 | 103 | err = db.delete(table="test_table", filter="name='a'") 104 | assert not err, err 105 | 106 | result = db.sql("select * from test_table", dtype="polars") 107 | 108 | assert isinstance(result, DataFrame) 109 | assert result.shape == (1, 2) 110 | assert set(result["name"].to_list()) == set(["b"]) 111 | 112 | def test_delete_record_lambda(db): 113 | db.upsert(table="test_table", primary_key="id", data=dict(id=5, name="a")) 114 | db.upsert(table="test_table", primary_key="id", data=dict(id=6, name="b")) 115 | 116 | err = db.delete(table="test_table", filter=lambda row: row["name"] == "a") 117 | assert not err, err 118 | 119 | result = db.sql("select * from test_table", dtype="polars") 120 | 121 | assert isinstance(result, DataFrame) 122 | assert result.shape == (1, 2) 123 | assert set(result["name"].to_list()) == set(["b"]) 124 | 125 | def test_delete_record_wrong_type(db): 126 | db.upsert(table="test_table", primary_key="id", data=dict(id=5, name="a")) 127 | db.upsert(table="test_table", primary_key="id", data=dict(id=6, name="b")) 128 | 129 | err = db.delete(table="test_table", filter=["wrong"]) 130 | assert isinstance(err, Exception) 131 | 132 | def test_schema_override(db): 133 | db.upsert(table="test_table", primary_key="id", data=dict(id=5, name="edward")) 134 | db.commit("test_table") 135 | db.upsert(table="test_table", primary_key="id", data=dict(id=6, name="james", job="chef")) 136 | db.commit("test_table", force=True) 137 | 138 | result = db.sql("select * from test_table", dtype="polars") 139 | assert result.shape == (2, 3) 140 | 141 | def test_commit_and_versioning(db): 142 | err = db.upsert(table="test_table", primary_key="id", data=dict(id=2, name="b")) 143 | assert not err, err 144 | 145 | err = db.commit("test_table") 146 | assert not err, err 147 | 148 | err = db.upsert(table="test_table", primary_key="id", data=dict(id=3, name="c")) 149 | assert not err, err 150 | 151 | result = db.sql("select * from test_table", dtype="polars") 152 | 153 | assert isinstance(result, DataFrame) 154 | assert result.shape == (2, 2) 155 | assert set(result["id"].to_list()) == set([2,3]) 156 | assert set(result["name"].to_list()) == set(["b","c"]) 157 | 158 | err = db.checkout(table="test_table", version=0) 159 | assert not err, err 160 | 161 | result = db.sql("select * from test_table", dtype="polars") 162 | 163 | assert isinstance(result, DataFrame) 164 | assert result.shape == (1, 2) 165 | assert set(result["id"].to_list()) == set([2]) 166 | assert set(result["name"].to_list()) == set(["b"]) 167 | 168 | def test_commit_with_partitions(db): 169 | db.upsert(table="test_table", primary_key="id", data=LazyFrame([dict(id=1, name="alice", job="teacher")])) 170 | db.upsert(table="test_table", primary_key="id", data=LazyFrame([dict(id=2, name="john", job="chef")])) 171 | db.commit("test_table", partition_by=["job"]) 172 | 173 | db.register(table="test_table", pyarrow_options={"partitions": [("job", "=", "chef")]}) 174 | 175 | result = db.sql("select * from test_table", dtype="polars") 176 | 177 | assert isinstance(result, DataFrame) 178 | assert result.shape == (1, 3) 179 | assert result["id"].to_list() == [2] 180 | assert result["name"].to_list() == ["john"] 181 | 182 | def test_register_with_alias(db): 183 | db.upsert(table="test_table", primary_key="id", data=LazyFrame([dict(id=1, name="alice", job="teacher")])) 184 | db.upsert(table="test_table", primary_key="id", data=LazyFrame([dict(id=2, name="john", job="chef")])) 185 | db.commit("test_table") 186 | 187 | db.register(table="test_table", alias="other_table") 188 | 189 | result = db.sql("select * from other_table", dtype="polars") 190 | 191 | assert isinstance(result, DataFrame) 192 | assert result.shape == (2, 3) 193 | assert set(result["id"].to_list()) == set([1,2]) 194 | assert set(result["name"].to_list()) == set(["alice","john"]) 195 | 196 | def test_json_output(db): 197 | db.upsert(table="test_table", primary_key="id", data=dict(id=5, name="a")) 198 | result = db.sql("select * from test_table", dtype="json") 199 | assert isinstance(result, list) 200 | assert isinstance(result[0], dict) 201 | assert result[0] == dict(id=5, name="a") 202 | 203 | def test_override_dtype(db): 204 | db.config.dtype = "polars" 205 | db.upsert(table="test_table", primary_key="id", data=dict(id=5, name="a")) 206 | result = db.sql("select * from test_table") 207 | assert isinstance(result, DataFrame) 208 | 209 | def test_collect_schema(db): 210 | db.config.dtype = "polars" 211 | db.upsert(table="test_table", primary_key="id", data=dict(id=5, name="a")) 212 | schema = db.schema(table="test_table") 213 | assert schema == {'id': int, 'name': str} 214 | -------------------------------------------------------------------------------- /docs/assets/banner.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /deltabase/__init__.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | 4 | # Copyright 2024 darryl mcculley 5 | 6 | # This program is free software: you can redistribute it and/or modify 7 | # it under the terms of the GNU General Public License as published by 8 | # the Free Software Foundation, either version 3 of the License, or 9 | # any later version. 10 | 11 | # This program is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # GNU General Public License for more details. 15 | 16 | # You should have received a copy of the GNU General Public License 17 | # along with this program. If not, see . 18 | 19 | from types import LambdaType 20 | from typing import Any, TypeVar, Type 21 | 22 | from polars import SQLContext, DataFrame, LazyFrame, Schema, sql_expr, scan_delta, struct, coalesce, from_dicts, from_dict, from_pandas 23 | from polars.exceptions import SchemaError 24 | 25 | from deltalake import WriterProperties 26 | from datetime import datetime 27 | from os.path import exists, isdir, join 28 | from os import listdir 29 | 30 | from deltalake.exceptions import TableNotFoundError 31 | 32 | from logging import getLogger 33 | 34 | debugger = getLogger("deltabase") 35 | 36 | T = TypeVar("T", bound="delta") 37 | 38 | class delta_config: 39 | dtype:str="json" 40 | writer_properties:WriterProperties = WriterProperties() 41 | ai_model:str="gpt-4o-mini" 42 | 43 | class delta: 44 | __delta_source:str 45 | __delta_sql_context:SQLContext=SQLContext(frames=[]) 46 | __delta_sql_context_schema:dict[str, Schema]={} 47 | config:delta_config 48 | 49 | @property 50 | def tables(self): 51 | """ list all tables within the sql context. 52 | 53 | returns a list of table names available in the sql context. 54 | 55 | >>> db.tables # output: ["table_1", "table_2"] 56 | """ 57 | return self.__delta_sql_context.tables() 58 | 59 | @classmethod 60 | def connect(cls: Type[T], path:str, config:delta_config=delta_config(), scan_local_dir:bool=True) -> T: 61 | """ connects to a remote source if provided, or local path, sets config, and automatically scans for tables. 62 | 63 | **args**: 64 | - **path**: the file path or uri to connect to, can be a local directory or remote storage. 65 | - **config**: `optional` configuration settings for the delta instance. default is an instance of `delta_config`. 66 | - **scan_local_dir**: `optional` automatically scan for tables when a local directory is provided. default is `true` 67 | 68 | >>> db = delta.connect(path="local_path/mydelta") 69 | >>> db = delta.connect(path="az:///") 70 | >>> db = delta.connect(path="s3:///") 71 | >>> db = delta.connect(path="gs:///") 72 | """ 73 | delta_cls = cls() 74 | delta_cls.__delta_source = path 75 | delta_cls.config = config 76 | 77 | try: from .magic import enable; enable(delta_cls) 78 | except ImportError as e: pass 79 | 80 | if not exists(path) or "://" in path or not scan_local_dir: return delta_cls 81 | 82 | for database in listdir(delta_cls.__delta_source): 83 | path = join(delta_cls.__delta_source, database) 84 | if isdir(path): 85 | for table in listdir(join(delta_cls.__delta_source, database)): 86 | if not table.startswith("."): 87 | table_path = join(delta_cls.__delta_source, database, table) 88 | if exists(table_path): 89 | try: delta_cls.register(database=database, table=table) 90 | except Exception as e: raise e 91 | 92 | return delta_cls 93 | 94 | def register(self, 95 | table:str, 96 | pyarrow_options:dict=None, 97 | alias:str=None, 98 | database:str="default", 99 | version:int|str|datetime=None, 100 | data:DataFrame|LazyFrame=None, 101 | ) -> Exception: 102 | """ registers the provided data, or loads the table from the delta source if no data is provided. 103 | 104 | **args**: 105 | - **table**: the name of the table to register. 106 | - **pyarrow_options**: `optional` options for loading the table using pyarrow. 107 | - **alias**: `optional` an alias to use for the table within the sql context. 108 | - **database**: `optional` the name of the database where the table is located. default is `'default'`. 109 | - **version**: `optional` the version of the table to load, can be an integer, string, or datetime. 110 | - **data**: `optional` a `DataFrame` or `LazyFrame` to register instead of loading from the delta source. 111 | 112 | >>> db.register(database="mydatabase", table="mytable", data=...) 113 | >>> db.register(database="mydatabase", table="mytable", version=1) 114 | >>> db.register(database="mydatabase", table="mytable", alias="mydatabase_mytable") 115 | >>> db.register(database="mydatabase", table="mytable", pyarrow_options={ 116 | >>> "partitions": [("year", "=", "2021")] 117 | >>> }) 118 | """ 119 | table_path = join(self.__delta_source, database, table) 120 | 121 | options = dict() 122 | if pyarrow_options: 123 | options["use_pyarrow"]=True 124 | options["pyarrow_options"] = pyarrow_options 125 | if isinstance(version, int|str|datetime): options["version"] = version 126 | table_name = alias if alias else table 127 | 128 | try: 129 | if data is None: data = scan_delta(table_path, **options) 130 | elif not isinstance(data, (DataFrame, LazyFrame)): 131 | raise TypeError(f"deltabase.register:: provided {type(data)} is not {DataFrame} or {LazyFrame}") 132 | self.__delta_sql_context.register(table_name, data) 133 | self.__delta_sql_context_schema[table_name] = data.collect_schema() 134 | except (TableNotFoundError, FileNotFoundError) as e: return e 135 | 136 | def __sync_data(self, primary_key:str, target_data:LazyFrame, source_data:LazyFrame) -> LazyFrame: 137 | """ performs a full outer join on the primary key and coalesces data to ensure consistency. 138 | 139 | **args**: 140 | - **primary_key**: the primary key on which the join will be performed. 141 | - **target_data**: the target `LazyFrame` containing the data to be updated. 142 | - **source_data**: the source `LazyFrame` containing the data to synchronize with. 143 | 144 | returns a lazyframe containing the synchronized data. 145 | """ 146 | update_data = source_data.join( 147 | target_data, 148 | on=primary_key, 149 | how="full", 150 | suffix="_delta_target", 151 | coalesce=True 152 | ) 153 | 154 | update_data_columns = update_data.collect_schema().names() 155 | 156 | coalesce_columns = [col for col in update_data_columns if "_delta_target" in col] 157 | coalesce_columns_strip = [col.replace("_delta_target", "") for col in coalesce_columns] 158 | 159 | update_data = update_data.with_columns([ 160 | coalesce([f"{col}_delta_target", col]).alias(col) 161 | if f"{col}_delta_target" in update_data_columns else update_data[col] 162 | for col in coalesce_columns_strip 163 | ]).drop(coalesce_columns) 164 | 165 | return update_data 166 | 167 | def upsert(self, 168 | table:str, 169 | primary_key:str, 170 | data:list[dict] | dict | DataFrame | LazyFrame, 171 | database:str="default", 172 | ) -> Exception: 173 | """ updates or inserts records in the specified table, with schema changes handled automatically. changes are reflected in the sql context, but a commit is required to persist them. 174 | 175 | **args**: 176 | - **table**: the name of the table to upsert data into. 177 | - **primary_key**: the primary key used to match records for updates. 178 | - **data**: the data to be upserted, can be a list of dictionaries, a dictionary, `DataFrame`, or `LazyFrame`. 179 | - **database**: `optional` the name of the database where the table is located. default is `'default'`. 180 | 181 | >>> db.upsert(database="mydatabase", table="mytable", primary_key="id", data=...) 182 | """ 183 | if isinstance(data, list) and len(data) > 0 and isinstance(data[0], dict): data = from_dicts(data).lazy() 184 | elif isinstance(data, dict): data = from_dict(data).lazy() 185 | elif isinstance(data, DataFrame): data = data.lazy() 186 | elif isinstance(data, LazyFrame): pass 187 | else: return ValueError(f"'data' was provided as '{type(data)}', type must be 'list[dict]' | 'dict' | 'DataFrame' | 'LazyFrame'") 188 | 189 | if table not in self.tables: 190 | return self.register(database=database, table=table, data=data) 191 | 192 | table_path = join(self.__delta_source, database, table) 193 | 194 | try: 195 | source_data = scan_delta(table_path) 196 | staged_data = self.sql(f"select * from {table}", lazy=True) 197 | source_data = self.__sync_data(primary_key, staged_data, source_data) 198 | except (TableNotFoundError, FileNotFoundError) as e: 199 | source_data = self.sql(f"select * from {table}", lazy=True) 200 | 201 | update_data = self.__sync_data(primary_key, data, source_data) 202 | 203 | return self.register(database=database, table=table, data=update_data) 204 | 205 | def delete(self, table:str, filter:str|LambdaType="*", database:str="default") -> Exception: 206 | """ removes records using a specified sql condition or lambda function. this only affects the sql context and does not delete data from disk or cloud storage. 207 | 208 | **args**: 209 | - **table**: the name of the table from which records will be deleted. 210 | - **filter**: `optional` a sql condition string or lambda function to filter the records to delete. default is `'*'`, which deletes all records. 211 | - **database**: `optional` the name of the database where the table is located. default is `'default'`. 212 | 213 | >>> db.delete(database="mydatabase", table="mytable") 214 | >>> db.delete(database="mydatabase", table="mytable", filter="name='bob'") 215 | >>> db.delete(database="mydatabase", table="mytable", filter=lambda row: row["name"] == "bob") 216 | """ 217 | table_path = join(self.__delta_source, database, table) 218 | if filter == "*": 219 | self.__delta_sql_context.unregister(table_path) 220 | return None 221 | elif isinstance(filter, str): 222 | source_data = self.sql(f"select * from {table}", lazy=True) 223 | filter_data = source_data.filter(~sql_expr(filter)) 224 | elif type(filter) == LambdaType: 225 | source_data = self.sql(f"select * from {table}", lazy=True) 226 | filter_data = source_data.filter( 227 | ~struct(source_data.collect_schema().names()).map_elements(filter, return_dtype=bool) 228 | ) 229 | else: 230 | return ValueError(f"'filter' was provided as '{type(filter)}', type must be 'callable' or 'str'") 231 | 232 | return self.register(database=database, table=table, data=filter_data) 233 | 234 | def sql(self, query:str, lazy:bool=False, dtype:str=None) -> DataFrame | LazyFrame: 235 | """ executes the provided sql query and returns the result as a dataframe or lazyframe. the result type can be specified via the dtype argument. 236 | 237 | **args**: 238 | - **query**: the sql query to execute. 239 | - **lazy**: `optional` returns a lazyframe if set to true. default is `false`. 240 | - **dtype**: `optional` sets the output data type. default is `'json'`. 241 | 242 | >>> db.sql("select * from mytable") 243 | """ 244 | dtype = dtype if dtype else self.config.dtype 245 | if lazy: return self.__delta_sql_context.execute(query) 246 | try: data:DataFrame = self.__delta_sql_context.execute(query).collect() 247 | except SchemaError as e: data:DataFrame = DataFrame( 248 | schema=self.__delta_sql_context.execute(query).collect_schema() 249 | ) 250 | match dtype: 251 | case "polars": return data 252 | case "json": return data.to_dicts() 253 | case _: raise ValueError(f"'dtype' was provided as '{dtype}', type must be one of the following ['polars', 'json']") 254 | 255 | def commit(self, 256 | table:str, 257 | force:bool=False, 258 | partition_by:list[str]=None, 259 | database:str="default", 260 | ) -> Exception: 261 | """ persists the current state of a table in the sql context to the delta source, with optional schema or partitioning options. 262 | 263 | **args**: 264 | - **table**: the name of the table to commit. 265 | - **force**: `optional` force schema changes during the commit. 266 | - **partition_by**: `optional` list of fields to partition by. 267 | - **database**: `optional` name of the database. default is `'default'`. 268 | 269 | >>> db.commit(database="mydatabase", table="mytable") 270 | >>> db.commit(database="mydatabase", table="mytable", force=True) 271 | >>> db.commit(database="mydatabase", table="mytable", partition_by=["job"]) 272 | """ 273 | table_path = join(self.__delta_source, database, table) 274 | data = self.sql(f"select * from {table}", dtype="polars") 275 | 276 | options = {"mode":"overwrite"} 277 | options.setdefault("delta_write_options", {}) 278 | options["delta_write_options"]["writer_properties"] = self.config.writer_properties 279 | 280 | if partition_by: options["delta_write_options"]["partition_by"] = partition_by 281 | if force: options["delta_write_options"]["schema_mode"] = "overwrite" 282 | 283 | try: data.write_delta(table_path, **options) 284 | except Exception as e: return e 285 | 286 | def checkout(self, table:str, version:int|str|datetime, database:str="default") -> Exception: 287 | """ reloads a previous version of a table from the delta source into the sql context. 288 | 289 | **args**: 290 | - **table**: the name of the table to revert. 291 | - **version**: the version to checkout, which can be an integer, string, or datetime. 292 | - **database**: `optional` name of the database. default is `'default'`. 293 | 294 | >>> db.checkout(database="mydatabase", table="mytable", version=1) 295 | """ 296 | return self.register(database=database, table=table, version=version) 297 | 298 | def schema(self, table:str) -> Schema|None: 299 | """ reloads a previous version of a table from the delta source into the sql context. 300 | 301 | **args**: 302 | - **table**: the name of the table. 303 | - **database**: `optional` name of the database. default is `'default'`. 304 | 305 | >>> db.schema(table="mytable") 306 | """ 307 | schema = self.__delta_sql_context_schema.get(table) 308 | if schema: return schema.to_python() 309 | return None 310 | -------------------------------------------------------------------------------- /examples/magic.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": null, 6 | "metadata": {}, 7 | "outputs": [], 8 | "source": [ 9 | "%pip install --upgrade 'deltabase' 'deltabase[magic]' 'deltabase[ai]' requests" 10 | ] 11 | }, 12 | { 13 | "cell_type": "code", 14 | "execution_count": 2, 15 | "metadata": {}, 16 | "outputs": [], 17 | "source": [ 18 | "from deltabase import delta\n", 19 | "\n", 20 | "from polars import DataFrame\n", 21 | "from requests import get" 22 | ] 23 | }, 24 | { 25 | "cell_type": "code", 26 | "execution_count": 3, 27 | "metadata": {}, 28 | "outputs": [], 29 | "source": [ 30 | "db:delta = delta.connect(\"delta\")\n", 31 | "db.config.dtype = \"polars\"" 32 | ] 33 | }, 34 | { 35 | "cell_type": "code", 36 | "execution_count": null, 37 | "metadata": {}, 38 | "outputs": [], 39 | "source": [ 40 | "bulk_data = get(\"https://api.scryfall.com/bulk-data\").json()\n", 41 | "download_uri = next((item['download_uri'] for item in bulk_data['data'] if item['type'] == 'all_cards'), None)\n", 42 | "\n", 43 | "data = get(download_uri).json()\n", 44 | "data = DataFrame(data)" 45 | ] 46 | }, 47 | { 48 | "cell_type": "code", 49 | "execution_count": 5, 50 | "metadata": {}, 51 | "outputs": [], 52 | "source": [ 53 | "err = db.upsert(table=\"colors\", primary_key=\"id\", data=data[[\n", 54 | " \"id\", \"lang\", \"set_name\", \"rarity\", \"colors\"\n", 55 | "]].explode(\"colors\").fill_null(strategy=\"zero\"))\n", 56 | "assert not err, err\n", 57 | "err = db.commit(table=\"colors\", partition_by=[\"lang\", \"set_name\", \"rarity\"])\n", 58 | "assert not err, err\n", 59 | "\n", 60 | "err = db.upsert(table=\"images\", primary_key=\"id\", data=data[[\n", 61 | " \"id\", \"lang\", \"set_name\", \"rarity\", \"image_uris\"\n", 62 | "]].unnest(\"image_uris\").fill_null(strategy=\"zero\"))\n", 63 | "assert not err, err\n", 64 | "err = db.commit(table=\"images\", partition_by=[\"lang\", \"set_name\", \"rarity\"])\n", 65 | "assert not err, err\n", 66 | "\n", 67 | "err = db.upsert(table=\"keywords\", primary_key=\"id\", data=data[[\n", 68 | " \"id\", \"lang\", \"set_name\", \"rarity\", \"keywords\"\n", 69 | "]].explode(\"keywords\").fill_null(strategy=\"zero\"))\n", 70 | "assert not err, err\n", 71 | "err = db.commit(table=\"keywords\", partition_by=[\"lang\", \"set_name\", \"rarity\"])\n", 72 | "assert not err, err\n", 73 | "\n", 74 | "err = db.upsert(table=\"legalities\", primary_key=\"id\", data=data[[\n", 75 | " \"id\", \"lang\", \"set_name\", \"rarity\", \"legalities\"\n", 76 | "]].unnest(\"legalities\").fill_null(strategy=\"zero\"))\n", 77 | "assert not err, err\n", 78 | "err = db.commit(table=\"legalities\", partition_by=[\"lang\", \"set_name\", \"rarity\"])\n", 79 | "assert not err, err\n", 80 | "\n", 81 | "err = db.upsert(table=\"prices\", primary_key=\"id\", data=data[[\n", 82 | " \"id\", \"lang\", \"set_name\", \"rarity\", \"prices\"\n", 83 | "]].unnest(\"prices\").drop(\"usd_etched\").fill_null(strategy=\"zero\"))\n", 84 | "assert not err, err\n", 85 | "err = db.commit(table=\"prices\", partition_by=[\"lang\", \"set_name\", \"rarity\"])\n", 86 | "assert not err, err\n", 87 | "\n", 88 | "err = db.upsert(table=\"produced_mana\", primary_key=\"id\", data=data[[\n", 89 | " \"id\", \"lang\", \"set_name\", \"rarity\", \"produced_mana\"\n", 90 | "]].explode(\"produced_mana\").fill_null(\"zero\"))\n", 91 | "assert not err, err\n", 92 | "err = db.commit(table=\"produced_mana\", partition_by=[\"lang\", \"set_name\", \"rarity\"])\n", 93 | "assert not err, err" 94 | ] 95 | }, 96 | { 97 | "cell_type": "code", 98 | "execution_count": 6, 99 | "metadata": {}, 100 | "outputs": [], 101 | "source": [ 102 | "data = data.drop([\n", 103 | " \"all_parts\",\n", 104 | " \"arena_id\",\n", 105 | " \"artist_ids\",\n", 106 | " \"card_faces\",\n", 107 | " \"cardmarket_id\",\n", 108 | " \"color_identity\",\n", 109 | " \"colors\",\n", 110 | " \"finishes\",\n", 111 | " \"frame_effects\",\n", 112 | " \"games\",\n", 113 | " \"highres_image\",\n", 114 | " \"image_status\",\n", 115 | " \"image_uris\",\n", 116 | " \"keywords\",\n", 117 | " \"layout\",\n", 118 | " \"legalities\",\n", 119 | " \"mtgo_foil_id\",\n", 120 | " \"mtgo_id\",\n", 121 | " \"multiverse_ids\",\n", 122 | " \"object\",\n", 123 | " \"oracle_id\",\n", 124 | " \"oracle_text\",\n", 125 | " \"preview\",\n", 126 | " \"prices\",\n", 127 | " \"printed_name\",\n", 128 | " \"printed_text\",\n", 129 | " \"printed_type_line\",\n", 130 | " \"prints_search_uri\",\n", 131 | " \"produced_mana\",\n", 132 | " \"promo_types\",\n", 133 | " \"purchase_uris\",\n", 134 | " \"related_uris\",\n", 135 | " \"rulings_uri\",\n", 136 | " \"scryfall_set_uri\",\n", 137 | " \"scryfall_uri\",\n", 138 | " \"security_stamp\",\n", 139 | " \"set_search_uri\",\n", 140 | " \"set_uri\",\n", 141 | " \"uri\",\n", 142 | "])\n", 143 | "\n", 144 | "err = db.upsert(table=\"cards\", primary_key=\"id\", data=data.fill_null(\"zero\"))\n", 145 | "assert not err, err\n", 146 | "err = db.commit(table=\"cards\", partition_by=[\"lang\", \"set_name\", \"rarity\"])\n", 147 | "assert not err, err" 148 | ] 149 | }, 150 | { 151 | "cell_type": "code", 152 | "execution_count": 7, 153 | "metadata": {}, 154 | "outputs": [], 155 | "source": [ 156 | "data = db.sql(\"\"\"\n", 157 | "select\n", 158 | " p.id, \n", 159 | " c.name,\n", 160 | " c.set_name,\n", 161 | " c.released_at as release_date,\n", 162 | " cast(p.usd as float) as usd,\n", 163 | "from prices as p\n", 164 | "inner join cards as c on c.id = p.id\n", 165 | "where p.usd != '' and c.lang = 'en'\n", 166 | "order by usd desc\n", 167 | "\"\"\")\n", 168 | "err = db.upsert(table=\"card_value\", primary_key=\"id\", data=data)\n", 169 | "assert not err, err\n", 170 | "err = db.commit(table=\"card_value\", partition_by=[\"set_name\"])\n", 171 | "assert not err, err" 172 | ] 173 | }, 174 | { 175 | "cell_type": "code", 176 | "execution_count": 8, 177 | "metadata": {}, 178 | "outputs": [], 179 | "source": [ 180 | "data = db.sql(\"\"\"\n", 181 | "select\n", 182 | " set_name,\n", 183 | " min(cast(release_date as date)) as release_date,\n", 184 | " sum(usd) as usd,\n", 185 | " count(id) as n_cards,\n", 186 | "from card_value\n", 187 | "group by set_name\n", 188 | "order by usd desc\n", 189 | "\"\"\")\n", 190 | "err = db.upsert(table=\"set_value\", primary_key=\"set_name\", data=data)\n", 191 | "assert not err, err\n", 192 | "err = db.commit(table=\"set_value\")\n", 193 | "assert not err, err" 194 | ] 195 | }, 196 | { 197 | "cell_type": "markdown", 198 | "metadata": {}, 199 | "source": [ 200 | "---" 201 | ] 202 | }, 203 | { 204 | "cell_type": "code", 205 | "execution_count": 9, 206 | "metadata": {}, 207 | "outputs": [ 208 | { 209 | "data": { 210 | "text/markdown": [ 211 | "You have access to the following sets of data related to card games:\n", 212 | "\n", 213 | "1. **Card Values (`card_value`)**: Contains information about individual card values, including identifiers, names, set names, release dates, and their USD prices.\n", 214 | "\n", 215 | "2. **Cards (`cards`)**: Provides detailed attributes of each card, including ID, TCGPlayer ID, name, language, release date, mana cost, converted mana cost (cmc), type, rarity, various boolean flags (e.g., reserved, foil, promo), and attributes like power and toughness.\n", 216 | "\n", 217 | "3. **Colors (`colors`)**: Lists information on card colors, including identifiers, language, rarity, and color specifications.\n", 218 | "\n", 219 | "4. **Images (`images`)**: Contains image URLs for cards, which include different sizes (small, normal, large) and specific formats (PNG, art crop, border crop) alongside their associated metadata like rarity.\n", 220 | "\n", 221 | "5. **Keywords (`keywords`)**: Features keywords associated with cards, giving insight into specific abilities or traits based on language and rarity.\n", 222 | "\n", 223 | "6. **Legalities (`legalities`)**: Specifies the legality of cards in various formats (e.g., standard, modern, commander) based on identifiers, language, rarity, and specific formats.\n", 224 | "\n", 225 | "7. **Prices (`prices`)**: Presents pricing information, including USD prices for normal and foil cards, as well as EURO prices and ticket values.\n", 226 | "\n", 227 | "8. **Produced Mana (`produced_mana`)**: Lists details on mana production for cards, including identifiers, languages, set names, rarity, and the type of mana produced.\n", 228 | "\n", 229 | "9. **Set Values (`set_value`)**: Summarizes data for card sets, detailing the set name, release date, total USD value of the set, and the number of cards in that set.\n", 230 | "\n", 231 | "This data collectively allows you to gain insights into individual cards, their values, legalities, and related multimedia, among other aspects of the card game ecosystem." 232 | ], 233 | "text/plain": [ 234 | "" 235 | ] 236 | }, 237 | "metadata": {}, 238 | "output_type": "display_data" 239 | } 240 | ], 241 | "source": [ 242 | "%%ai\n", 243 | "summarize the data available to me." 244 | ] 245 | }, 246 | { 247 | "cell_type": "code", 248 | "execution_count": 10, 249 | "metadata": {}, 250 | "outputs": [], 251 | "source": [ 252 | "db.register(table=\"card_value\", version=0, alias=\"temp_card_value\")" 253 | ] 254 | }, 255 | { 256 | "cell_type": "code", 257 | "execution_count": 11, 258 | "metadata": {}, 259 | "outputs": [ 260 | { 261 | "data": { 262 | "text/plain": [ 263 | "['card_value',\n", 264 | " 'cards',\n", 265 | " 'colors',\n", 266 | " 'images',\n", 267 | " 'keywords',\n", 268 | " 'legalities',\n", 269 | " 'prices',\n", 270 | " 'produced_mana',\n", 271 | " 'set_value',\n", 272 | " 'temp_card_value']" 273 | ] 274 | }, 275 | "execution_count": 11, 276 | "metadata": {}, 277 | "output_type": "execute_result" 278 | } 279 | ], 280 | "source": [ 281 | "db.tables" 282 | ] 283 | }, 284 | { 285 | "cell_type": "code", 286 | "execution_count": 12, 287 | "metadata": { 288 | "vscode": { 289 | "languageId": "sql" 290 | } 291 | }, 292 | "outputs": [ 293 | { 294 | "data": { 295 | "text/html": [ 296 | "
\n", 303 | "shape: (71_519, 6)
idnameset_namepreviouscurrentdiff
strstrstrf64f64f64
"093e3fc5-b2e0-4376-b8ad-4470e0…"Gratuitous Violence""Conspiracy: Take the Crown"2.142.140.0
"43ab3ff8-91b0-437c-9c4b-e9c103…"Omenspeaker""Conspiracy: Take the Crown"0.060.060.0
"9de3eeae-22a5-4d9c-afd6-1cc441…"Coordinated Assault""Conspiracy: Take the Crown"0.080.080.0
"f9083583-6fa9-4b8a-86bb-59e51a…"Exotic Orchard""Conspiracy: Take the Crown"0.330.330.0
"160d39b0-76c5-4218-97e5-5903f7…"Opaline Unicorn""Conspiracy: Take the Crown"0.090.090.0
"c2c6e29e-261a-4953-bdbe-cce879…"Tamiyo, Field Researcher Emble…"Eldritch Moon Tokens"0.710.710.0
"dbd994fc-f3f0-4c81-86bd-14ca63…"Human""Eldritch Moon Tokens"0.290.290.0
"e44aa879-b63b-497c-9c1b-233395…"Zombie""Eldritch Moon Tokens"0.250.250.0
"11d25bde-a303-4b06-a3e1-4ad642…"Eldrazi Horror""Eldritch Moon Tokens"0.10.10.0
"b8710a30-8314-49ef-b995-bd0545…"Zombie""Eldritch Moon Tokens"0.130.130.0
" 304 | ], 305 | "text/plain": [ 306 | "shape: (71_519, 6)\n", 307 | "┌───────────────────────┬───────────────────────┬──────────────────────┬──────────┬─────────┬──────┐\n", 308 | "│ id ┆ name ┆ set_name ┆ previous ┆ current ┆ diff │\n", 309 | "│ --- ┆ --- ┆ --- ┆ --- ┆ --- ┆ --- │\n", 310 | "│ str ┆ str ┆ str ┆ f64 ┆ f64 ┆ f64 │\n", 311 | "╞═══════════════════════╪═══════════════════════╪══════════════════════╪══════════╪═════════╪══════╡\n", 312 | "│ 093e3fc5-b2e0-4376-b8 ┆ Gratuitous Violence ┆ Conspiracy: Take the ┆ 2.14 ┆ 2.14 ┆ 0.0 │\n", 313 | "│ ad-4470e0… ┆ ┆ Crown ┆ ┆ ┆ │\n", 314 | "│ 43ab3ff8-91b0-437c-9c ┆ Omenspeaker ┆ Conspiracy: Take the ┆ 0.06 ┆ 0.06 ┆ 0.0 │\n", 315 | "│ 4b-e9c103… ┆ ┆ Crown ┆ ┆ ┆ │\n", 316 | "│ 9de3eeae-22a5-4d9c-af ┆ Coordinated Assault ┆ Conspiracy: Take the ┆ 0.08 ┆ 0.08 ┆ 0.0 │\n", 317 | "│ d6-1cc441… ┆ ┆ Crown ┆ ┆ ┆ │\n", 318 | "│ f9083583-6fa9-4b8a-86 ┆ Exotic Orchard ┆ Conspiracy: Take the ┆ 0.33 ┆ 0.33 ┆ 0.0 │\n", 319 | "│ bb-59e51a… ┆ ┆ Crown ┆ ┆ ┆ │\n", 320 | "│ 160d39b0-76c5-4218-97 ┆ Opaline Unicorn ┆ Conspiracy: Take the ┆ 0.09 ┆ 0.09 ┆ 0.0 │\n", 321 | "│ e5-5903f7… ┆ ┆ Crown ┆ ┆ ┆ │\n", 322 | "│ … ┆ … ┆ … ┆ … ┆ … ┆ … │\n", 323 | "│ c2c6e29e-261a-4953-bd ┆ Tamiyo, Field ┆ Eldritch Moon Tokens ┆ 0.71 ┆ 0.71 ┆ 0.0 │\n", 324 | "│ be-cce879… ┆ Researcher Emble… ┆ ┆ ┆ ┆ │\n", 325 | "│ dbd994fc-f3f0-4c81-86 ┆ Human ┆ Eldritch Moon Tokens ┆ 0.29 ┆ 0.29 ┆ 0.0 │\n", 326 | "│ bd-14ca63… ┆ ┆ ┆ ┆ ┆ │\n", 327 | "│ e44aa879-b63b-497c-9c ┆ Zombie ┆ Eldritch Moon Tokens ┆ 0.25 ┆ 0.25 ┆ 0.0 │\n", 328 | "│ 1b-233395… ┆ ┆ ┆ ┆ ┆ │\n", 329 | "│ 11d25bde-a303-4b06-a3 ┆ Eldrazi Horror ┆ Eldritch Moon Tokens ┆ 0.1 ┆ 0.1 ┆ 0.0 │\n", 330 | "│ e1-4ad642… ┆ ┆ ┆ ┆ ┆ │\n", 331 | "│ b8710a30-8314-49ef-b9 ┆ Zombie ┆ Eldritch Moon Tokens ┆ 0.13 ┆ 0.13 ┆ 0.0 │\n", 332 | "│ 95-bd0545… ┆ ┆ ┆ ┆ ┆ │\n", 333 | "└───────────────────────┴───────────────────────┴──────────────────────┴──────────┴─────────┴──────┘" 334 | ] 335 | }, 336 | "execution_count": 12, 337 | "metadata": {}, 338 | "output_type": "execute_result" 339 | } 340 | ], 341 | "source": [ 342 | "%%sql\n", 343 | "select \n", 344 | " c.id, \n", 345 | " c.name, \n", 346 | " c.set_name,\n", 347 | " t.usd as previous,\n", 348 | " c.usd as current,\n", 349 | " (c.usd - t.usd) as diff\n", 350 | "from card_value as c\n", 351 | "inner join temp_card_value as t on c.id = t.id\n", 352 | "order by diff desc;" 353 | ] 354 | }, 355 | { 356 | "cell_type": "code", 357 | "execution_count": 13, 358 | "metadata": { 359 | "vscode": { 360 | "languageId": "sql" 361 | } 362 | }, 363 | "outputs": [], 364 | "source": [ 365 | "db.register(table=\"set_value\", version=0, alias=\"temp_set_value\")" 366 | ] 367 | }, 368 | { 369 | "cell_type": "code", 370 | "execution_count": 14, 371 | "metadata": { 372 | "vscode": { 373 | "languageId": "sql" 374 | } 375 | }, 376 | "outputs": [ 377 | { 378 | "data": { 379 | "text/html": [ 380 | "
\n", 387 | "shape: (537, 4)
set_namepreviouscurrentdiff
strf64f64f64
"Unlimited Edition"26503.526503.50.0
"Limited Edition Beta"22377.6922377.690.0
"Limited Edition Alpha"19426.0719426.070.0
"Arabian Nights"13772.2213772.220.0
"Secret Lair Drop"13739.513739.50.0
"Duel Decks: Sorin vs. Tibalt T…0.120.120.0
"Streets of New Capenna Tokens"0.110.110.0
"Duel Decks: Jace vs. Chandra T…0.10.10.0
"Dominaria United Commander Tok…0.070.070.0
"Assassin's Creed Tokens"0.060.060.0
" 388 | ], 389 | "text/plain": [ 390 | "shape: (537, 4)\n", 391 | "┌─────────────────────────────────┬──────────┬──────────┬──────┐\n", 392 | "│ set_name ┆ previous ┆ current ┆ diff │\n", 393 | "│ --- ┆ --- ┆ --- ┆ --- │\n", 394 | "│ str ┆ f64 ┆ f64 ┆ f64 │\n", 395 | "╞═════════════════════════════════╪══════════╪══════════╪══════╡\n", 396 | "│ Unlimited Edition ┆ 26503.5 ┆ 26503.5 ┆ 0.0 │\n", 397 | "│ Limited Edition Beta ┆ 22377.69 ┆ 22377.69 ┆ 0.0 │\n", 398 | "│ Limited Edition Alpha ┆ 19426.07 ┆ 19426.07 ┆ 0.0 │\n", 399 | "│ Arabian Nights ┆ 13772.22 ┆ 13772.22 ┆ 0.0 │\n", 400 | "│ Secret Lair Drop ┆ 13739.5 ┆ 13739.5 ┆ 0.0 │\n", 401 | "│ … ┆ … ┆ … ┆ … │\n", 402 | "│ Duel Decks: Sorin vs. Tibalt T… ┆ 0.12 ┆ 0.12 ┆ 0.0 │\n", 403 | "│ Streets of New Capenna Tokens ┆ 0.11 ┆ 0.11 ┆ 0.0 │\n", 404 | "│ Duel Decks: Jace vs. Chandra T… ┆ 0.1 ┆ 0.1 ┆ 0.0 │\n", 405 | "│ Dominaria United Commander Tok… ┆ 0.07 ┆ 0.07 ┆ 0.0 │\n", 406 | "│ Assassin's Creed Tokens ┆ 0.06 ┆ 0.06 ┆ 0.0 │\n", 407 | "└─────────────────────────────────┴──────────┴──────────┴──────┘" 408 | ] 409 | }, 410 | "execution_count": 14, 411 | "metadata": {}, 412 | "output_type": "execute_result" 413 | } 414 | ], 415 | "source": [ 416 | "%%sql\n", 417 | "select\n", 418 | " c.set_name,\n", 419 | " t.usd as previous,\n", 420 | " c.usd as current,\n", 421 | " (c.usd - t.usd) as diff\n", 422 | "from set_value as c\n", 423 | "inner join temp_set_value as t on c.set_name = t.set_name\n", 424 | "order by diff desc;" 425 | ] 426 | } 427 | ], 428 | "metadata": { 429 | "kernelspec": { 430 | "display_name": ".venv", 431 | "language": "python", 432 | "name": "python3" 433 | }, 434 | "language_info": { 435 | "codemirror_mode": { 436 | "name": "ipython", 437 | "version": 3 438 | }, 439 | "file_extension": ".py", 440 | "mimetype": "text/x-python", 441 | "name": "python", 442 | "nbconvert_exporter": "python", 443 | "pygments_lexer": "ipython3", 444 | "version": "3.12.2" 445 | } 446 | }, 447 | "nbformat": 4, 448 | "nbformat_minor": 2 449 | } 450 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . --------------------------------------------------------------------------------