Compare commits

..
154 changed files with 2552 additions and 652755 deletions

View file

@ -1,52 +0,0 @@
name: Set up `velofy`
description: Install R, `uv`, `nox`, and `pre-commit`
runs:
using: composite
steps:
- name: Install R via system packages
shell: bash
run: |
apt-get update
apt-get install --no-install-recommends \
r-base-dev \
r-cran-forecast \
r-cran-zoo \
-y
# Built wheels (e.g., `rpy2`) and Python versions, keyed by their pins
# => Only the "lint" job in ci.yaml saves the cache
- name: Restore the `uv` cache
id: uv-cache
uses: actions/cache/restore@v4
with:
path: |
~/.cache/uv
~/.local/share/uv/python
key: uv-${{ runner.os }}-${{ hashFiles('uv.lock', 'pyproject.toml') }}
restore-keys: uv-${{ runner.os }}-
# Tell the "lint" job in ci.yaml the key and if it must save the cache
- name: Remember the `uv` cache key and if it was restored exactly
shell: bash
run: |
echo "UV_CACHE_KEY=${{ steps.uv-cache.outputs.cache-primary-key }}" >> "$FORGEJO_ENV"
echo "UV_CACHE_HIT=${{ steps.uv-cache.outputs.cache-hit }}" >> "$FORGEJO_ENV"
# All `SUPPORTED_PYTHONS` from the "classifiers" in pyproject.toml
# => `nox` would otherwise pick the system's Python without headers
- name: Install `uv` and all supported Python versions
shell: bash
run: |
curl -LsSf https://astral.sh/uv/0.13.10/install.sh | sh
echo "$HOME/.local/bin" >> "$FORGEJO_PATH"
"$HOME/.local/bin/uv" python install $(grep -oP 'Programming Language :: Python :: \K3\.\d+' pyproject.toml)
# The jobs only use `nox` and `pre-commit` from the develop environment
# => The `nox` sessions install `velofy` and its dependencies themselves
- name: Install `nox` and `pre-commit`
shell: bash
run: '"$HOME/.local/bin/uv" sync --locked --only-group dev'

View file

@ -1,2 +0,0 @@
Merge branch '${HeadBranch}' into ${BaseBranch}
${ReviewedOn}

View file

@ -1,117 +0,0 @@
name: CI
# Run on every push, which also covers pull requests from this repository
on:
push:
# Use `bash` instead of the container's default `sh`
defaults:
run:
shell: bash
# Same variables as in `.env` on `nehemiah`, the main development machine
env:
DATABASE_URI: postgresql://user:password@postgres:5432/db
GOOGLE_MAPS_API_KEY: AIzaDummyKeyForTests # Fake key to mock the Google API
R_LIBS: /usr/lib/R/site-library
UV_NO_SYNC: "1" # Keep `uv run` from installing all groups (see the setup action)
UV_PYTHON_PREFERENCE: only-managed # Only uv's Python has the headers to build `rpy2`
jobs:
lint:
name: Lint
runs-on: debian-13
# Stop hanging jobs (e.g., a test waiting for a database lock)
timeout-minutes: 20
# Throwaway database, reachable from the job as host `postgres`
services: &database
postgres:
image: postgres:17
env:
POSTGRES_USER: user
POSTGRES_PASSWORD: password
POSTGRES_DB: db
# Start the steps only once the database accepts connections
options: >-
--health-cmd "pg_isready --username=user --dbname=db"
--health-interval 2s
--health-timeout 5s
--health-retries 15
steps:
- uses: actions/checkout@v6
with:
fetch-depth: 0 # Fetch all branches with their history for the next step
- name: Ensure feature branches contain no merge commits
if: forgejo.ref_name != 'develop' && forgejo.ref_name != 'main'
run: "! git rev-list --merges origin/develop..HEAD | grep ."
- uses: ./.forgejo/actions/setup
- name: Ensure `nox -s format` changes nothing
run: uv run nox -s format && git diff --exit-code
- name: Lint the source files
run: uv run nox -s lint
- name: Test the code snippets in the docstrings with `xdoctest`
run: uv run nox -s test-docstrings
- name: Run the `pre-commit` hooks not covered by `nox`
run: uv run pre-commit run --all-files --show-diff-on-failure
env:
SKIP: local-format,local-lint,local-test,local-test-docstrings,local-test-types,no-commit-to-branch
# Only this job saves the `uv` cache that ./.forgejo/actions/setup restores
# => Keep only what is expensive to rebuild, not wheels that are cheap to download
- name: Shrink the `uv` cache
if: env.UV_CACHE_HIT != 'true'
run: uv cache prune --ci
- name: Save the `uv` cache
if: env.UV_CACHE_HIT != 'true'
uses: actions/cache/save@v4
with:
path: |
~/.cache/uv
~/.local/share/uv/python
key: ${{ env.UV_CACHE_KEY }}
tests:
name: Tests (${{ matrix.session }})
runs-on: debian-13
# Stop hanging jobs (e.g., a test waiting for a database lock)
timeout-minutes: 20
# Run the sessions in parallel, each with its own database
strategy:
matrix:
session:
- test
- test-types
# One job per non-main Python version listed in the "classifiers"
# in pyproject.toml => Keep in sync manually
- test-with-3.15
# Same database as in the "lint" job
services: *database
steps:
- uses: actions/checkout@v6
- uses: ./.forgejo/actions/setup
- name: Run the `nox` session
run: uv run nox -s ${{ matrix.session }}

View file

@ -1,92 +0,0 @@
# Mechanical commits that `git blame` skips
# => Enable locally with `git config blame.ignoreRevsFile .git-blame-ignore-revs`
# Use double quotes
ea8f1a13e34bfce01ea66951311e5f5fb5ab967f
# Use the `sa` alias for `sqlalchemy` everywhere
e30b3efbe8fc719f7d1d5bef32c69df67884f4d7
# Use `sa.func` instead of importing `func`
78e052b668d029204daeb17d0ded3938156f1f2b
# Import the `postgresql` dialect as `psql`
9d3af5e44719c88e4115c429d38e9e795de5bf05
# Import `sqlalchemy.ext.hybrid` as `sa_hybrid`
0b2a1197a2b089120f66ae2c8c365fac983192f4
# Use builtin generics and `X | None`
c6518f6b39386a7c803d0c2792fdae6d61436064
# Import `typing` as `t` ...
9c3b52befb51f91026accb9d4d3e0874ef6c3d23
# Use the `nox` module import
f0c617955bc8e9d46cd4126e0a334f1a28cc7849
# Import `datetime` as `dt` everywhere
5ca16ae47c63c06ac67b11908f813a544c377670
# Import `googlemaps` as `gm` everywhere
d660f0cc4ed6d9e62d0fe7c6d618322d57a1b049
# Import `geopy.distance` as `geo_distance` everywhere
07660ecff980932d082f82c43575fbfafc1172fe
# Import `click.testing` as `cli_testing`
07e90b7851e3c585270edf84b94fbb2998e51c46
# Import `statsmodels.tsa.api` as `tsa`
9b844b16e777ef643ea20f93f9fe415ecc51ff20
# Import `rpy2.rinterface_lib.callbacks` as `r_callbacks`
8bca30c83630a7136cba9c427d6bcc1dbffb2b7a
# Import `rpy2.robjects.packages` as `r_packages`
e9743eaa013362cd4e79b19dd7dd0c25ede11e73
# Import `alembic.command` as `alembic_cmd`
dc45c689c40ccfe98c2148f9ba08612612121083
# Import `alembic.config` as `alembic_config`
de5e49b497cc8f5904637fa5d913e2f8b331f2e8
# Import `velofy.config` as `pkg_config` everywhere
cf2534f41e9e535b8f68a38bb3e0ebadf3fb19b3
# Capitalize the explanations after "=>"
0090145b654c098cc464aed757e6c1fdda7487bd
# Remove periods from one-sentence comments
049a5f6f62e05f08ffdcb6ce90c1f07ec3042871
# Break multi-line comments before conjunctions
2f1afd459fe73c2ab4136acaa1f87ecf64212e9f
# Put identifiers in comments into backticks
ff7f705bc831734bbab63a43fd78a11121696bc5
# Reword the comments in `velofy.db`
1413d08ed9115501fa2757b97de23525581d9acf
# Reword the comments in `velofy.forecasts`
9b8fe8b8fd41e920954ce4cda5b2fd5e70b44185
# Reword the comments in the rest of `velofy`
0f6970922623a7bda82b78bb48d5fb05646e7d45
# Reword the comments in the test suite
bca4250b4d9512dde4f67996f21f4c4bc9c18387
# Reword the comments in the config files
51f68743e537a9ffa744f47e65313485b0ecd3c5
# Explain the "why" in a few more comments
f90f263dab12013cc1353381e6ee3258df5e9176
# Refer to sources with "See:" in comments
c18fc2ba59ed9286336da113604a98f423cbc32f
# Put the `ruff` per-file ignores on separate lines
47a22f9587f94fa5bc2705302a3e29dca3701dcf

14
.github/workflows/tests.yml vendored Normal file
View file

@ -0,0 +1,14 @@
name: CI
on: push
jobs:
tests:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/setup-python@v1
with:
python-version: 3.8
architecture: x64
- run: pip install nox==2020.5.24
- run: pip install poetry==1.0.10
- run: nox

5
.gitignore vendored
View file

@ -1,7 +1,4 @@
.cache/
**/*.egg-info/
.env
.idea/
**/.ipynb_checkpoints/
*.egg-info/
.python-version
.venv/

3
.gitmodules vendored
View file

@ -1,3 +0,0 @@
[submodule "research/papers/demand-forecasting"]
path = research/papers/demand-forecasting
url = ssh://git@git.webartifex.de/alexander/velofy-forecasting.git

View file

@ -1,109 +1,38 @@
# Hooks run by `git commit` and `git merge`,
# installed with `uv run nox -s init-project`
# Used by a plain `pre-commit install`
default_install_hook_types:
- pre-commit
- pre-merge-commit
# Used if a hook does not specify stages
default_stages:
- pre-commit
default_stages: [commit] # only used if a hook does not specify stages
fail_fast: true
repos:
# Format, lint, and test with the `nox` sessions
- repo: local
# Run the local formatting, linting, and testing tool chains.
- repo: local
hooks:
# `require_serial: true`
# => Parallel runs would recreate the same `nox` environment
- id: local-format
name: Format the source files
entry: uv run nox -s format --
language: unsupported
stages: [pre-commit]
- id: local-pre-commit-checks
name: Run code formatters and linters
entry: poetry run nox -s pre-commit --
language: system
stages: [commit]
types: [python]
require_serial: true
- id: local-lint
name: Lint the source files
entry: uv run nox -s lint --
language: unsupported
stages: [pre-commit]
- id: local-pre-merge-checks
name: Run the entire test suite
entry: poetry run nox -s pre-merge --
language: system
stages: [merge-commit, push]
types: [python]
require_serial: true
- id: local-test
name: Run the test suite
entry: uv run nox -s test
language: unsupported
stages: [pre-merge-commit]
pass_filenames: false # => No `--` at the end of the "entry"
always_run: true
require_serial: true
- id: local-test-docstrings
name: Run the doctests
entry: uv run nox -s test-docstrings
language: unsupported
stages: [pre-merge-commit]
pass_filenames: false # => No `--` at the end of the "entry"
always_run: true
require_serial: true
- id: local-test-types
name: Check the type annotations at runtime
entry: uv run nox -s test-types
language: unsupported
stages: [pre-merge-commit]
pass_filenames: false # => No `--` at the end of the "entry"
always_run: true
require_serial: true
# Keep requirements.txt in sync with uv.lock
- repo: https://github.com/astral-sh/uv-pre-commit
rev: 0.13.10
# Enable hooks provided by the pre-commit project to
# enforce rules that local tools could not that easily.
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v3.2.0
hooks:
- id: uv-export
args:
- --extra=research
- --no-default-groups
- --no-emit-project
- --frozen
- --quiet
- --output-file=requirements.txt
# Generic checks that the "local" tools can not cover
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v6.0.0
hooks:
- id: check-added-large-files
args: [--maxkb=100]
exclude: ^requirements\.txt$ # Large because of the hashes
- id: check-builtin-literals
- id: check-case-conflict
- id: check-builtin-literals
- id: check-merge-conflict
- id: check-toml
- id: check-yaml
- id: end-of-file-fixer
stages: [commit] # overwrite the default
- id: mixed-line-ending
args: [--fix=no]
- id: no-commit-to-branch
args: [--branch, main]
- id: trailing-whitespace
stages: [commit] # overwrite the default

View file

@ -1,4 +1,4 @@
Copyright (c) 2020 Alexander Hess [alexander@webartifex.de]
Copyright (c) 2020 Alexander Hess [alexander@webartifex.biz]
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal

View file

@ -1,81 +1,16 @@
# Urban Meal Delivery
This repository holds code
analyzing the data of an undisclosed urban meal delivery platform (UDP)
analyzing the data of an undisclosed urban meal delivery platform
operating in France from January 2016 to January 2017.
The goal is to
optimize the platform's delivery process involving independent couriers.
## Structure
The analysis is structured into the following stages
The analysis is structured into three aspects
that iteratively build on each other.
## Real-time Demand Forecasting
### Data Cleaning
## Predictive Routing
The UDP provided its raw data as a PostgreSQL dump.
This [notebook](research/01_clean_data.ipynb)
cleans the data extensively
and maps them onto the [ORM models](src/velofy/db)
defined in the `velofy` package
that is developed in the [src/](src) folder
and contains all source code to drive the analyses.
Due to a non-disclosure agreement with the UDP,
neither the raw nor the cleaned data are published as of now.
However, previews of the data can be seen throughout the [research/](research) folder.
### Tactical Demand Forecasting
Before any optimizations of the UDP's operations are done,
a **demand forecasting** system for *tactical* purposes is implemented.
To achieve that, the cities first undergo a **gridification** step
where each *pickup* location is assigned into a pixel on a "checker board"-like grid.
The main part of the source code that implements that is in this [file](src/velofy/db/grids.py#L60).
Visualizations of the various grids can be found in the [visualizations/](research/visualizations) folder
and in this [notebook](research/03_grid_visualizations.ipynb).
Then, demand is aggregated on a per-pixel level
and different kinds of order time series are generated.
The latter are the input to different kinds of forecasting `*Model`s.
They all have in common that they predict demand into the *short-term* future (e.g., one hour)
and are thus used for tactical purposes, in particular predictive routing (cf., next section).
The details of how this works can be found in the first academic paper
published in the context of this research project
and titled "*Real-time Demand Forecasting for an Urban Delivery Platform*"
(cf., the [repository](https://code.webartifex.de/alexander/velofy-forecasting) with the LaTeX files).
All demand forecasting related code is in the [forecasts/](src/velofy/forecasts) sub-package.
### Predictive Routing
### Shift & Capacity Planning
## Installation & Contribution
To play with the code developed for the analyses,
you can clone the project with [git](https://git-scm.com/)
and install the contained `velofy` package
and all its dependencies
in a [virtual environment](https://docs.python.org/3/tutorial/venv.html)
with [uv](https://docs.astral.sh/uv/):
`git clone ssh://git@git.webartifex.de/alexander/velofy.git`
and
`uv sync --extra research`
The `--extra` option is necessary as the non-develop dependencies
are structured in the [pyproject.toml](pyproject.toml) file
into dependencies related to only the `velofy` source code package
and dependencies used to run the [Jupyter](https://jupyter.org/) environment
with the analyses.
Contributions are welcome.
Use the [issues](https://code.webartifex.de/alexander/velofy/issues) tab.
The project is licensed under the [MIT license](LICENSE.txt).
## Shift & Capacity Planning

View file

@ -1,44 +0,0 @@
[alembic]
file_template = rev_%%(year)d%%(month).2d%%(day).2d_%%(hour).2d_%%(rev)s_%%(slug)s
script_location = %(here)s/migrations
[post_write_hooks]
hooks=black
black.type=console_scripts
black.entrypoint=black
# The following is taken from the default alembic.ini file.
[loggers]
keys = root,sqlalchemy,alembic
[handlers]
keys = console
[formatters]
keys = generic
[logger_root]
level = WARN
handlers = console
qualname =
[logger_sqlalchemy]
level = WARN
handlers =
qualname = sqlalchemy.engine
[logger_alembic]
level = INFO
handlers =
qualname = alembic
[handler_console]
class = StreamHandler
args = (sys.stderr,)
level = NOTSET
formatter = generic
[formatter_generic]
format = %(levelname)-5.5s [%(name)s] %(message)s
datefmt = %H:%M:%S

View file

@ -1,15 +1,15 @@
"""Configure sphinx."""
import velofy
import urban_meal_delivery as umd
project = velofy.__pkg_name__
author = velofy.__author__
project_copyright = f"2020, {author}"
version = release = velofy.__version__
project = umd.__pkg_name__
author = umd.__author__
copyright = f'2020, {author}' # pylint:disable=redefined-builtin
version = release = umd.__version__
extensions = [
"sphinx.ext.autodoc",
"sphinx.ext.napoleon",
"sphinx_autodoc_typehints",
'sphinx.ext.autodoc',
'sphinx.ext.napoleon',
'sphinx_autodoc_typehints',
]

View file

@ -9,7 +9,7 @@ Urban Meal Delivery
reference
This is the documentation for the `velofy` package
This is the documentation for the `urban-meal-delivery` package
that contains all the source code
used in a research project
residing in this `repository`_.
@ -25,13 +25,13 @@ All other software is automatically installed (cf., next section).
Installation
------------
The `velofy` package is installed
The `urban-meal-delivery` package is installed
only after cloning the `repository`_.
It is *not* available on `PyPI`_ via `pip`_.
.. code-block:: console
$ git clone ssh://git@git.webartifex.de/alexander/velofy.git
$ git clone https://github.com/webartifex/urban-meal-delivery.git
Use `poetry`_ to install the package
with its dependencies into a `virtual environment`_,
@ -91,5 +91,5 @@ You can use them to choose among the different tasks you want to achieve.
.. _poetry: https://python-poetry.org/docs/
.. _pypi: https://pypi.org/
.. _python: https://docs.python.org/3/
.. _repository: https://code.webartifex.de/alexander/velofy
.. _repository: https://github.com/webartifex/urban-meal-delivery
.. _virtual environment: https://docs.python.org/3/tutorial/venv.html

View file

@ -1,4 +0,0 @@
# Database Migrations
This project uses [alembic](https://alembic.sqlalchemy.org/en/latest)
to run the database migrations

View file

@ -1,47 +0,0 @@
"""Configure Alembic's migration environment."""
import os
from logging import config as log_config
import sqlalchemy as sa
from alembic import context
from velofy import config as pkg_config
from velofy import db
# Disable the --sql option, a.k.a, the "offline mode"
if context.is_offline_mode():
msg = "The --sql option is not implemented in this project"
raise NotImplementedError(msg)
# Set up the default Python logger from the alembic.ini file
log_config.fileConfig(context.config.config_file_name)
def include_object(obj, _name, type_, _reflected, _compare_to):
"""Only include the clean schema into --autogenerate migrations."""
return not (
type_ in {"table", "column"}
and hasattr(obj, "schema") # => Fix for rare edge case
and obj.schema != pkg_config.CLEAN_SCHEMA
)
# Without a `pool`, the `connection` really closes after the migrations
engine = sa.create_engine(pkg_config.DATABASE_URI, poolclass=sa.pool.NullPool)
test_schema = f"_{pkg_config.CLEAN_SCHEMA}" if os.getenv("TESTING") else ""
with engine.connect() as connection:
context.configure(
connection=connection,
include_object=include_object,
target_metadata=db.Base.metadata,
version_table=f"{pkg_config.ALEMBIC_TABLE}{test_schema}",
version_table_schema=pkg_config.ALEMBIC_TABLE_SCHEMA,
)
with context.begin_transaction():
context.run_migrations()

View file

@ -1,28 +0,0 @@
"""${message}."""
import os
import sqlalchemy as sa
from alembic import op
${imports if imports else ""}
from velofy import configuration
revision = ${repr(up_revision)}
down_revision = ${repr(down_revision)}
branch_labels = ${repr(branch_labels)}
depends_on = ${repr(depends_on)}
config = configuration.make_config("testing" if os.getenv("TESTING") else "production")
def upgrade():
"""Upgrade to the next revision."""
${upgrades if upgrades else "pass"}
def downgrade():
"""Downgrade to the previous revision."""
${downgrades if downgrades else "pass"}

View file

@ -1,807 +0,0 @@
"""Create the database from scratch."""
import os
import sqlalchemy as sa
from alembic import op
from sqlalchemy.dialects import postgresql as psql
from velofy import configuration
revision = "f11cd76d2f45"
down_revision = None
branch_labels = None
depends_on = None
config = configuration.make_config("testing" if os.getenv("TESTING") else "production")
def upgrade():
"""Upgrade to the next revision."""
op.execute(f"CREATE SCHEMA {config.CLEAN_SCHEMA};")
op.create_table(
"cities",
sa.Column("id", sa.SmallInteger(), autoincrement=False, nullable=False),
sa.Column("name", sa.Unicode(length=10), nullable=False),
sa.Column("kml", sa.UnicodeText(), nullable=False),
sa.Column("center_latitude", psql.DOUBLE_PRECISION(), nullable=False),
sa.Column("center_longitude", psql.DOUBLE_PRECISION(), nullable=False),
sa.Column("northeast_latitude", psql.DOUBLE_PRECISION(), nullable=False),
sa.Column("northeast_longitude", psql.DOUBLE_PRECISION(), nullable=False),
sa.Column("southwest_latitude", psql.DOUBLE_PRECISION(), nullable=False),
sa.Column("southwest_longitude", psql.DOUBLE_PRECISION(), nullable=False),
sa.Column("initial_zoom", sa.SmallInteger(), nullable=False),
sa.PrimaryKeyConstraint("id", name=op.f("pk_cities")),
*(
[
sa.ForeignKeyConstraint(
["id"],
[f"{config.ORIGINAL_SCHEMA}.cities.id"],
name=op.f("pk_cities_sanity"),
onupdate="RESTRICT",
ondelete="RESTRICT",
),
]
if not config.TESTING
else []
),
schema=config.CLEAN_SCHEMA,
)
op.create_table(
"couriers",
sa.Column("id", sa.Integer(), autoincrement=False, nullable=False),
sa.Column("created_at", sa.DateTime(), nullable=False),
sa.Column("vehicle", sa.Unicode(length=10), nullable=False),
sa.Column("speed", psql.DOUBLE_PRECISION(), nullable=False),
sa.Column("capacity", sa.SmallInteger(), nullable=False),
sa.Column("pay_per_hour", sa.SmallInteger(), nullable=False),
sa.Column("pay_per_order", sa.SmallInteger(), nullable=False),
sa.CheckConstraint(
"vehicle IN ('bicycle', 'motorcycle')",
name=op.f("ck_couriers_on_available_vehicle_types"),
),
sa.CheckConstraint(
"0 <= capacity AND capacity <= 200",
name=op.f("ck_couriers_on_capacity_under_200_liters"),
),
sa.CheckConstraint(
"0 <= pay_per_hour AND pay_per_hour <= 1500",
name=op.f("ck_couriers_on_realistic_pay_per_hour"),
),
sa.CheckConstraint(
"0 <= pay_per_order AND pay_per_order <= 650",
name=op.f("ck_couriers_on_realistic_pay_per_order"),
),
sa.CheckConstraint(
"0 <= speed AND speed <= 30",
name=op.f("ck_couriers_on_realistic_speed"),
),
sa.PrimaryKeyConstraint("id", name=op.f("pk_couriers")),
*(
[
sa.ForeignKeyConstraint(
["id"],
[f"{config.ORIGINAL_SCHEMA}.couriers.id"],
name=op.f("pk_couriers_sanity"),
onupdate="RESTRICT",
ondelete="RESTRICT",
),
]
if not config.TESTING
else []
),
schema=config.CLEAN_SCHEMA,
)
op.create_table(
"customers",
sa.Column("id", sa.Integer(), autoincrement=False, nullable=False),
sa.PrimaryKeyConstraint("id", name=op.f("pk_customers")),
schema=config.CLEAN_SCHEMA,
)
op.create_table(
"addresses",
sa.Column("id", sa.Integer(), autoincrement=False, nullable=False),
sa.Column("primary_id", sa.Integer(), nullable=False),
sa.Column("created_at", sa.DateTime(), nullable=False),
sa.Column("place_id", sa.Unicode(length=120), nullable=False),
sa.Column("latitude", psql.DOUBLE_PRECISION(), nullable=False),
sa.Column("longitude", psql.DOUBLE_PRECISION(), nullable=False),
sa.Column("city_id", sa.SmallInteger(), nullable=False),
sa.Column("city", sa.Unicode(length=25), nullable=False),
sa.Column("zip_code", sa.Integer(), nullable=False),
sa.Column("street", sa.Unicode(length=80), nullable=False),
sa.Column("floor", sa.SmallInteger(), nullable=True),
sa.CheckConstraint(
"-180 <= longitude AND longitude <= 180",
name=op.f("ck_addresses_on_longitude_between_180_degrees"),
),
sa.CheckConstraint(
"-90 <= latitude AND latitude <= 90",
name=op.f("ck_addresses_on_latitude_between_90_degrees"),
),
sa.CheckConstraint(
"0 <= floor AND floor <= 40",
name=op.f("ck_addresses_on_realistic_floor"),
),
sa.CheckConstraint(
"30000 <= zip_code AND zip_code <= 99999",
name=op.f("ck_addresses_on_valid_zip_code"),
),
sa.ForeignKeyConstraint(
["city_id"],
[f"{config.CLEAN_SCHEMA}.cities.id"],
name=op.f("fk_addresses_to_cities_via_city_id"),
onupdate="RESTRICT",
ondelete="RESTRICT",
),
sa.ForeignKeyConstraint(
["primary_id"],
[f"{config.CLEAN_SCHEMA}.addresses.id"],
name=op.f("fk_addresses_to_addresses_via_primary_id"),
onupdate="RESTRICT",
ondelete="RESTRICT",
),
sa.PrimaryKeyConstraint("id", name=op.f("pk_addresses")),
*(
[
sa.ForeignKeyConstraint(
["id"],
[f"{config.ORIGINAL_SCHEMA}.addresses.id"],
name=op.f("pk_addresses_sanity"),
onupdate="RESTRICT",
ondelete="RESTRICT",
),
]
if not config.TESTING
else []
),
schema=config.CLEAN_SCHEMA,
)
op.create_index(
op.f("ix_addresses_on_city_id"),
"addresses",
["city_id"],
unique=False,
schema=config.CLEAN_SCHEMA,
)
op.create_index(
op.f("ix_addresses_on_place_id"),
"addresses",
["place_id"],
unique=False,
schema=config.CLEAN_SCHEMA,
)
op.create_index(
op.f("ix_addresses_on_primary_id"),
"addresses",
["primary_id"],
unique=False,
schema=config.CLEAN_SCHEMA,
)
op.create_index(
op.f("ix_addresses_on_zip_code"),
"addresses",
["zip_code"],
unique=False,
schema=config.CLEAN_SCHEMA,
)
op.create_table(
"restaurants",
sa.Column("id", sa.SmallInteger(), autoincrement=False, nullable=False),
sa.Column("created_at", sa.DateTime(), nullable=False),
sa.Column("name", sa.Unicode(length=45), nullable=False),
sa.Column("address_id", sa.Integer(), nullable=False),
sa.Column("estimated_prep_duration", sa.SmallInteger(), nullable=False),
sa.CheckConstraint(
"0 <= estimated_prep_duration AND estimated_prep_duration <= 2400",
name=op.f("ck_restaurants_on_realistic_estimated_prep_duration"),
),
sa.ForeignKeyConstraint(
["address_id"],
[f"{config.CLEAN_SCHEMA}.addresses.id"],
name=op.f("fk_restaurants_to_addresses_via_address_id"),
onupdate="RESTRICT",
ondelete="RESTRICT",
),
sa.PrimaryKeyConstraint("id", name=op.f("pk_restaurants")),
*(
[
sa.ForeignKeyConstraint(
["id"],
[f"{config.ORIGINAL_SCHEMA}.businesses.id"],
name=op.f("pk_restaurants_sanity"),
onupdate="RESTRICT",
ondelete="RESTRICT",
),
]
if not config.TESTING
else []
),
schema=config.CLEAN_SCHEMA,
)
op.create_index(
op.f("ix_restaurants_on_address_id"),
"restaurants",
["address_id"],
unique=False,
schema=config.CLEAN_SCHEMA,
)
op.create_table(
"orders",
sa.Column("id", sa.Integer(), autoincrement=False, nullable=False),
sa.Column("delivery_id", sa.Integer(), nullable=True),
sa.Column("customer_id", sa.Integer(), nullable=False),
sa.Column("placed_at", sa.DateTime(), nullable=False),
sa.Column("ad_hoc", sa.Boolean(), nullable=False),
sa.Column("scheduled_delivery_at", sa.DateTime(), nullable=True),
sa.Column("scheduled_delivery_at_corrected", sa.Boolean(), nullable=True),
sa.Column("first_estimated_delivery_at", sa.DateTime(), nullable=True),
sa.Column("cancelled", sa.Boolean(), nullable=False),
sa.Column("cancelled_at", sa.DateTime(), nullable=True),
sa.Column("cancelled_at_corrected", sa.Boolean(), nullable=True),
sa.Column("sub_total", sa.Integer(), nullable=False),
sa.Column("delivery_fee", sa.SmallInteger(), nullable=False),
sa.Column("total", sa.Integer(), nullable=False),
sa.Column("restaurant_id", sa.SmallInteger(), nullable=False),
sa.Column("restaurant_notified_at", sa.DateTime(), nullable=True),
sa.Column("restaurant_notified_at_corrected", sa.Boolean(), nullable=True),
sa.Column("restaurant_confirmed_at", sa.DateTime(), nullable=True),
sa.Column("restaurant_confirmed_at_corrected", sa.Boolean(), nullable=True),
sa.Column("estimated_prep_duration", sa.Integer(), nullable=True),
sa.Column("estimated_prep_duration_corrected", sa.Boolean(), nullable=True),
sa.Column("estimated_prep_buffer", sa.Integer(), nullable=False),
sa.Column("courier_id", sa.Integer(), nullable=True),
sa.Column("dispatch_at", sa.DateTime(), nullable=True),
sa.Column("dispatch_at_corrected", sa.Boolean(), nullable=True),
sa.Column("courier_notified_at", sa.DateTime(), nullable=True),
sa.Column("courier_notified_at_corrected", sa.Boolean(), nullable=True),
sa.Column("courier_accepted_at", sa.DateTime(), nullable=True),
sa.Column("courier_accepted_at_corrected", sa.Boolean(), nullable=True),
sa.Column("utilization", sa.SmallInteger(), nullable=False),
sa.Column("pickup_address_id", sa.Integer(), nullable=False),
sa.Column("reached_pickup_at", sa.DateTime(), nullable=True),
sa.Column("pickup_at", sa.DateTime(), nullable=True),
sa.Column("pickup_at_corrected", sa.Boolean(), nullable=True),
sa.Column("pickup_not_confirmed", sa.Boolean(), nullable=True),
sa.Column("left_pickup_at", sa.DateTime(), nullable=True),
sa.Column("left_pickup_at_corrected", sa.Boolean(), nullable=True),
sa.Column("delivery_address_id", sa.Integer(), nullable=False),
sa.Column("reached_delivery_at", sa.DateTime(), nullable=True),
sa.Column("delivery_at", sa.DateTime(), nullable=True),
sa.Column("delivery_at_corrected", sa.Boolean(), nullable=True),
sa.Column("delivery_not_confirmed", sa.Boolean(), nullable=True),
sa.Column("courier_waited_at_delivery", sa.Boolean(), nullable=True),
sa.Column("logged_delivery_distance", sa.SmallInteger(), nullable=True),
sa.Column("logged_avg_speed", psql.DOUBLE_PRECISION(), nullable=True),
sa.Column("logged_avg_speed_distance", sa.SmallInteger(), nullable=True),
sa.CheckConstraint(
"0 <= estimated_prep_buffer AND estimated_prep_buffer <= 900",
name=op.f("ck_orders_on_estimated_prep_buffer_between_0_and_900"),
),
sa.CheckConstraint(
"0 <= estimated_prep_duration AND estimated_prep_duration <= 2700",
name=op.f("ck_orders_on_estimated_prep_duration_between_0_and_2700"),
),
sa.CheckConstraint(
"0 <= utilization AND utilization <= 100",
name=op.f("ck_orders_on_utilization_between_0_and_100"),
),
sa.CheckConstraint(
"(cancelled_at IS NULL AND cancelled_at_corrected IS NULL) OR (cancelled_at IS NULL AND cancelled_at_corrected IS TRUE) OR (cancelled_at IS NOT NULL AND cancelled_at_corrected IS NOT NULL)", # noqa:E501
name=op.f("ck_orders_on_corrections_only_for_set_value_1"),
),
sa.CheckConstraint(
"(courier_accepted_at IS NULL AND courier_accepted_at_corrected IS NULL) OR (courier_accepted_at IS NULL AND courier_accepted_at_corrected IS TRUE) OR (courier_accepted_at IS NOT NULL AND courier_accepted_at_corrected IS NOT NULL)", # noqa:E501
name=op.f("ck_orders_on_corrections_only_for_set_value_7"),
),
sa.CheckConstraint(
"(courier_notified_at IS NULL AND courier_notified_at_corrected IS NULL) OR (courier_notified_at IS NULL AND courier_notified_at_corrected IS TRUE) OR (courier_notified_at IS NOT NULL AND courier_notified_at_corrected IS NOT NULL)", # noqa:E501
name=op.f("ck_orders_on_corrections_only_for_set_value_6"),
),
sa.CheckConstraint(
"(delivery_at IS NULL AND delivery_at_corrected IS NULL) OR (delivery_at IS NULL AND delivery_at_corrected IS TRUE) OR (delivery_at IS NOT NULL AND delivery_at_corrected IS NOT NULL)", # noqa:E501
name=op.f("ck_orders_on_corrections_only_for_set_value_10"),
),
sa.CheckConstraint(
"(dispatch_at IS NULL AND dispatch_at_corrected IS NULL) OR (dispatch_at IS NULL AND dispatch_at_corrected IS TRUE) OR (dispatch_at IS NOT NULL AND dispatch_at_corrected IS NOT NULL)", # noqa:E501
name=op.f("ck_orders_on_corrections_only_for_set_value_5"),
),
sa.CheckConstraint(
"(estimated_prep_duration IS NULL AND estimated_prep_duration_corrected IS NULL) OR (estimated_prep_duration IS NULL AND estimated_prep_duration_corrected IS TRUE) OR (estimated_prep_duration IS NOT NULL AND estimated_prep_duration_corrected IS NOT NULL)", # noqa:E501
name=op.f("ck_orders_on_corrections_only_for_set_value_4"),
),
sa.CheckConstraint(
"(left_pickup_at IS NULL AND left_pickup_at_corrected IS NULL) OR (left_pickup_at IS NULL AND left_pickup_at_corrected IS TRUE) OR (left_pickup_at IS NOT NULL AND left_pickup_at_corrected IS NOT NULL)", # noqa:E501
name=op.f("ck_orders_on_corrections_only_for_set_value_9"),
),
sa.CheckConstraint(
"(pickup_at IS NULL AND pickup_at_corrected IS NULL) OR (pickup_at IS NULL AND pickup_at_corrected IS TRUE) OR (pickup_at IS NOT NULL AND pickup_at_corrected IS NOT NULL)", # noqa:E501
name=op.f("ck_orders_on_corrections_only_for_set_value_8"),
),
sa.CheckConstraint(
"(restaurant_confirmed_at IS NULL AND restaurant_confirmed_at_corrected IS NULL) OR (restaurant_confirmed_at IS NULL AND restaurant_confirmed_at_corrected IS TRUE) OR (restaurant_confirmed_at IS NOT NULL AND restaurant_confirmed_at_corrected IS NOT NULL)", # noqa:E501
name=op.f("ck_orders_on_corrections_only_for_set_value_3"),
),
sa.CheckConstraint(
"(restaurant_notified_at IS NULL AND restaurant_notified_at_corrected IS NULL) OR (restaurant_notified_at IS NULL AND restaurant_notified_at_corrected IS TRUE) OR (restaurant_notified_at IS NOT NULL AND restaurant_notified_at_corrected IS NOT NULL)", # noqa:E501
name=op.f("ck_orders_on_corrections_only_for_set_value_2"),
),
sa.CheckConstraint(
"(scheduled_delivery_at IS NULL AND scheduled_delivery_at_corrected IS NULL) OR (scheduled_delivery_at IS NULL AND scheduled_delivery_at_corrected IS TRUE) OR (scheduled_delivery_at IS NOT NULL AND scheduled_delivery_at_corrected IS NOT NULL)", # noqa:E501
name=op.f("ck_orders_on_corrections_only_for_set_value_0"),
),
sa.CheckConstraint(
"(ad_hoc IS TRUE AND scheduled_delivery_at IS NULL) OR (ad_hoc IS FALSE AND scheduled_delivery_at IS NOT NULL)", # noqa:E501
name=op.f("ck_orders_on_either_ad_hoc_or_scheduled_order"),
),
sa.CheckConstraint(
"NOT (EXTRACT(EPOCH FROM scheduled_delivery_at - placed_at) < 1800)",
name=op.f("ck_orders_on_scheduled_orders_not_within_30_minutes"),
),
sa.CheckConstraint(
"NOT (ad_hoc IS FALSE AND ((EXTRACT(HOUR FROM scheduled_delivery_at) <= 11 AND NOT (EXTRACT(HOUR FROM scheduled_delivery_at) = 11 AND EXTRACT(MINUTE FROM scheduled_delivery_at) = 45)) OR EXTRACT(HOUR FROM scheduled_delivery_at) > 22))", # noqa:E501
name=op.f("ck_orders_on_scheduled_orders_within_business_hours"),
),
sa.CheckConstraint(
"NOT (ad_hoc IS TRUE AND (EXTRACT(HOUR FROM placed_at) < 11 OR EXTRACT(HOUR FROM placed_at) > 22))", # noqa:E501
name=op.f("ck_orders_on_ad_hoc_orders_within_business_hours"),
),
sa.CheckConstraint(
"NOT (cancelled IS FALSE AND cancelled_at IS NOT NULL)",
name=op.f("ck_orders_on_only_cancelled_orders_may_have_cancelled_at"),
),
sa.CheckConstraint(
"NOT (cancelled IS TRUE AND delivery_at IS NOT NULL)",
name=op.f("ck_orders_on_cancelled_orders_must_not_be_delivered"),
),
sa.CheckConstraint(
"cancelled_at > courier_accepted_at",
name=op.f("ck_orders_on_ordered_timestamps_16"),
),
sa.CheckConstraint(
"cancelled_at > courier_notified_at",
name=op.f("ck_orders_on_ordered_timestamps_15"),
),
sa.CheckConstraint(
"cancelled_at > delivery_at",
name=op.f("ck_orders_on_ordered_timestamps_21"),
),
sa.CheckConstraint(
"cancelled_at > dispatch_at",
name=op.f("ck_orders_on_ordered_timestamps_14"),
),
sa.CheckConstraint(
"cancelled_at > left_pickup_at",
name=op.f("ck_orders_on_ordered_timestamps_19"),
),
sa.CheckConstraint(
"cancelled_at > pickup_at",
name=op.f("ck_orders_on_ordered_timestamps_18"),
),
sa.CheckConstraint(
"cancelled_at > reached_delivery_at",
name=op.f("ck_orders_on_ordered_timestamps_20"),
),
sa.CheckConstraint(
"cancelled_at > reached_pickup_at",
name=op.f("ck_orders_on_ordered_timestamps_17"),
),
sa.CheckConstraint(
"cancelled_at > restaurant_confirmed_at",
name=op.f("ck_orders_on_ordered_timestamps_13"),
),
sa.CheckConstraint(
"cancelled_at > restaurant_notified_at",
name=op.f("ck_orders_on_ordered_timestamps_12"),
),
sa.CheckConstraint(
"courier_accepted_at < delivery_at",
name=op.f("ck_orders_on_ordered_timestamps_42"),
),
sa.CheckConstraint(
"courier_accepted_at < left_pickup_at",
name=op.f("ck_orders_on_ordered_timestamps_40"),
),
sa.CheckConstraint(
"courier_accepted_at < pickup_at",
name=op.f("ck_orders_on_ordered_timestamps_39"),
),
sa.CheckConstraint(
"courier_accepted_at < reached_delivery_at",
name=op.f("ck_orders_on_ordered_timestamps_41"),
),
sa.CheckConstraint(
"courier_accepted_at < reached_pickup_at",
name=op.f("ck_orders_on_ordered_timestamps_38"),
),
sa.CheckConstraint(
"courier_notified_at < courier_accepted_at",
name=op.f("ck_orders_on_ordered_timestamps_32"),
),
sa.CheckConstraint(
"courier_notified_at < delivery_at",
name=op.f("ck_orders_on_ordered_timestamps_37"),
),
sa.CheckConstraint(
"courier_notified_at < left_pickup_at",
name=op.f("ck_orders_on_ordered_timestamps_35"),
),
sa.CheckConstraint(
"courier_notified_at < pickup_at",
name=op.f("ck_orders_on_ordered_timestamps_34"),
),
sa.CheckConstraint(
"courier_notified_at < reached_delivery_at",
name=op.f("ck_orders_on_ordered_timestamps_36"),
),
sa.CheckConstraint(
"courier_notified_at < reached_pickup_at",
name=op.f("ck_orders_on_ordered_timestamps_33"),
),
sa.CheckConstraint(
"dispatch_at < courier_accepted_at",
name=op.f("ck_orders_on_ordered_timestamps_26"),
),
sa.CheckConstraint(
"dispatch_at < courier_notified_at",
name=op.f("ck_orders_on_ordered_timestamps_25"),
),
sa.CheckConstraint(
"dispatch_at < delivery_at",
name=op.f("ck_orders_on_ordered_timestamps_31"),
),
sa.CheckConstraint(
"dispatch_at < left_pickup_at",
name=op.f("ck_orders_on_ordered_timestamps_29"),
),
sa.CheckConstraint(
"dispatch_at < pickup_at",
name=op.f("ck_orders_on_ordered_timestamps_28"),
),
sa.CheckConstraint(
"dispatch_at < reached_delivery_at",
name=op.f("ck_orders_on_ordered_timestamps_30"),
),
sa.CheckConstraint(
"dispatch_at < reached_pickup_at",
name=op.f("ck_orders_on_ordered_timestamps_27"),
),
sa.CheckConstraint(
"estimated_prep_buffer % 60 = 0",
name=op.f("ck_orders_on_estimated_prep_buffer_must_be_whole_minutes"),
),
sa.CheckConstraint(
"estimated_prep_duration % 60 = 0",
name=op.f("ck_orders_on_estimated_prep_duration_must_be_whole_minutes"),
),
sa.CheckConstraint(
"left_pickup_at < delivery_at",
name=op.f("ck_orders_on_ordered_timestamps_51"),
),
sa.CheckConstraint(
"left_pickup_at < reached_delivery_at",
name=op.f("ck_orders_on_ordered_timestamps_50"),
),
sa.CheckConstraint(
"pickup_at < delivery_at",
name=op.f("ck_orders_on_ordered_timestamps_49"),
),
sa.CheckConstraint(
"pickup_at < left_pickup_at",
name=op.f("ck_orders_on_ordered_timestamps_47"),
),
sa.CheckConstraint(
"pickup_at < reached_delivery_at",
name=op.f("ck_orders_on_ordered_timestamps_48"),
),
sa.CheckConstraint(
"placed_at < cancelled_at",
name=op.f("ck_orders_on_ordered_timestamps_2"),
),
sa.CheckConstraint(
"placed_at < courier_accepted_at",
name=op.f("ck_orders_on_ordered_timestamps_7"),
),
sa.CheckConstraint(
"placed_at < courier_notified_at",
name=op.f("ck_orders_on_ordered_timestamps_6"),
),
sa.CheckConstraint(
"placed_at < delivery_at",
name=op.f("ck_orders_on_ordered_timestamps_11"),
),
sa.CheckConstraint(
"placed_at < dispatch_at",
name=op.f("ck_orders_on_ordered_timestamps_5"),
),
sa.CheckConstraint(
"placed_at < first_estimated_delivery_at",
name=op.f("ck_orders_on_ordered_timestamps_1"),
),
sa.CheckConstraint(
"placed_at < left_pickup_at",
name=op.f("ck_orders_on_ordered_timestamps_9"),
),
sa.CheckConstraint(
"placed_at < reached_delivery_at",
name=op.f("ck_orders_on_ordered_timestamps_10"),
),
sa.CheckConstraint(
"placed_at < reached_pickup_at",
name=op.f("ck_orders_on_ordered_timestamps_8"),
),
sa.CheckConstraint(
"placed_at < restaurant_confirmed_at",
name=op.f("ck_orders_on_ordered_timestamps_4"),
),
sa.CheckConstraint(
"placed_at < restaurant_notified_at",
name=op.f("ck_orders_on_ordered_timestamps_3"),
),
sa.CheckConstraint(
"placed_at < scheduled_delivery_at",
name=op.f("ck_orders_on_ordered_timestamps_0"),
),
sa.CheckConstraint(
"reached_delivery_at < delivery_at",
name=op.f("ck_orders_on_ordered_timestamps_52"),
),
sa.CheckConstraint(
"reached_pickup_at < delivery_at",
name=op.f("ck_orders_on_ordered_timestamps_46"),
),
sa.CheckConstraint(
"reached_pickup_at < left_pickup_at",
name=op.f("ck_orders_on_ordered_timestamps_44"),
),
sa.CheckConstraint(
"reached_pickup_at < pickup_at",
name=op.f("ck_orders_on_ordered_timestamps_43"),
),
sa.CheckConstraint(
"reached_pickup_at < reached_delivery_at",
name=op.f("ck_orders_on_ordered_timestamps_45"),
),
sa.CheckConstraint(
"restaurant_confirmed_at < pickup_at",
name=op.f("ck_orders_on_ordered_timestamps_24"),
),
sa.CheckConstraint(
"restaurant_notified_at < pickup_at",
name=op.f("ck_orders_on_ordered_timestamps_23"),
),
sa.CheckConstraint(
"restaurant_notified_at < restaurant_confirmed_at",
name=op.f("ck_orders_on_ordered_timestamps_22"),
),
sa.CheckConstraint(
"(pickup_at IS NULL AND pickup_not_confirmed IS NULL) OR (pickup_at IS NOT NULL AND pickup_not_confirmed IS NOT NULL)", # noqa:E501
name=op.f("pickup_not_confirmed_only_if_pickup"),
),
sa.CheckConstraint(
"(delivery_at IS NULL AND delivery_not_confirmed IS NULL) OR (delivery_at IS NOT NULL AND delivery_not_confirmed IS NOT NULL)", # noqa:E501
name=op.f("delivery_not_confirmed_only_if_delivery"),
),
sa.CheckConstraint(
"(delivery_at IS NULL AND courier_waited_at_delivery IS NULL) OR (delivery_at IS NOT NULL AND courier_waited_at_delivery IS NOT NULL)", # noqa:E501
name=op.f("courier_waited_at_delivery_only_if_delivery"),
),
sa.ForeignKeyConstraint(
["courier_id"],
[f"{config.CLEAN_SCHEMA}.couriers.id"],
name=op.f("fk_orders_to_couriers_via_courier_id"),
onupdate="RESTRICT",
ondelete="RESTRICT",
),
sa.ForeignKeyConstraint(
["customer_id"],
[f"{config.CLEAN_SCHEMA}.customers.id"],
name=op.f("fk_orders_to_customers_via_customer_id"),
onupdate="RESTRICT",
ondelete="RESTRICT",
),
sa.ForeignKeyConstraint(
["delivery_address_id"],
[f"{config.CLEAN_SCHEMA}.addresses.id"],
name=op.f("fk_orders_to_addresses_via_delivery_address_id"),
onupdate="RESTRICT",
ondelete="RESTRICT",
),
sa.ForeignKeyConstraint(
["pickup_address_id"],
[f"{config.CLEAN_SCHEMA}.addresses.id"],
name=op.f("fk_orders_to_addresses_via_pickup_address_id"),
onupdate="RESTRICT",
ondelete="RESTRICT",
),
sa.ForeignKeyConstraint(
["restaurant_id"],
[f"{config.CLEAN_SCHEMA}.restaurants.id"],
name=op.f("fk_orders_to_restaurants_via_restaurant_id"),
onupdate="RESTRICT",
ondelete="RESTRICT",
),
sa.PrimaryKeyConstraint("id", name=op.f("pk_orders")),
*(
[
sa.ForeignKeyConstraint(
["id"],
[f"{config.ORIGINAL_SCHEMA}.orders.id"],
name=op.f("pk_orders_sanity"),
onupdate="RESTRICT",
ondelete="RESTRICT",
),
sa.ForeignKeyConstraint(
["delivery_id"],
[f"{config.ORIGINAL_SCHEMA}.deliveries.id"],
name=op.f("pk_deliveries_sanity"),
onupdate="RESTRICT",
ondelete="RESTRICT",
),
]
if not config.TESTING
else []
),
schema=config.CLEAN_SCHEMA,
)
op.create_index(
op.f("ix_orders_on_cancelled"),
"orders",
["cancelled"],
unique=False,
schema=config.CLEAN_SCHEMA,
)
op.create_index(
op.f("ix_orders_on_cancelled_at_corrected"),
"orders",
["cancelled_at_corrected"],
unique=False,
schema=config.CLEAN_SCHEMA,
)
op.create_index(
op.f("ix_orders_on_courier_accepted_at_corrected"),
"orders",
["courier_accepted_at_corrected"],
unique=False,
schema=config.CLEAN_SCHEMA,
)
op.create_index(
op.f("ix_orders_on_courier_id"),
"orders",
["courier_id"],
unique=False,
schema=config.CLEAN_SCHEMA,
)
op.create_index(
op.f("ix_orders_on_courier_notified_at_corrected"),
"orders",
["courier_notified_at_corrected"],
unique=False,
schema=config.CLEAN_SCHEMA,
)
op.create_index(
op.f("ix_orders_on_customer_id"),
"orders",
["customer_id"],
unique=False,
schema=config.CLEAN_SCHEMA,
)
op.create_index(
op.f("ix_orders_on_delivery_address_id"),
"orders",
["delivery_address_id"],
unique=False,
schema=config.CLEAN_SCHEMA,
)
op.create_index(
op.f("ix_orders_on_delivery_at_corrected"),
"orders",
["delivery_at_corrected"],
unique=False,
schema=config.CLEAN_SCHEMA,
)
op.create_index(
op.f("ix_orders_on_delivery_id"),
"orders",
["delivery_id"],
unique=True,
schema=config.CLEAN_SCHEMA,
)
op.create_index(
op.f("ix_orders_on_dispatch_at_corrected"),
"orders",
["dispatch_at_corrected"],
unique=False,
schema=config.CLEAN_SCHEMA,
)
op.create_index(
op.f("ix_orders_on_estimated_prep_buffer"),
"orders",
["estimated_prep_buffer"],
unique=False,
schema=config.CLEAN_SCHEMA,
)
op.create_index(
op.f("ix_orders_on_estimated_prep_duration"),
"orders",
["estimated_prep_duration"],
unique=False,
schema=config.CLEAN_SCHEMA,
)
op.create_index(
op.f("ix_orders_on_estimated_prep_duration_corrected"),
"orders",
["estimated_prep_duration_corrected"],
unique=False,
schema=config.CLEAN_SCHEMA,
)
op.create_index(
op.f("ix_orders_on_left_pickup_at_corrected"),
"orders",
["left_pickup_at_corrected"],
unique=False,
schema=config.CLEAN_SCHEMA,
)
op.create_index(
op.f("ix_orders_on_pickup_address_id"),
"orders",
["pickup_address_id"],
unique=False,
schema=config.CLEAN_SCHEMA,
)
op.create_index(
op.f("ix_orders_on_pickup_at_corrected"),
"orders",
["pickup_at_corrected"],
unique=False,
schema=config.CLEAN_SCHEMA,
)
op.create_index(
op.f("ix_orders_on_placed_at"),
"orders",
["placed_at"],
unique=False,
schema=config.CLEAN_SCHEMA,
)
op.create_index(
op.f("ix_orders_on_restaurant_confirmed_at_corrected"),
"orders",
["restaurant_confirmed_at_corrected"],
unique=False,
schema=config.CLEAN_SCHEMA,
)
op.create_index(
op.f("ix_orders_on_restaurant_id"),
"orders",
["restaurant_id"],
unique=False,
schema=config.CLEAN_SCHEMA,
)
op.create_index(
op.f("ix_orders_on_restaurant_notified_at_corrected"),
"orders",
["restaurant_notified_at_corrected"],
unique=False,
schema=config.CLEAN_SCHEMA,
)
op.create_index(
op.f("ix_orders_on_scheduled_delivery_at"),
"orders",
["scheduled_delivery_at"],
unique=False,
schema=config.CLEAN_SCHEMA,
)
op.create_index(
op.f("ix_orders_on_scheduled_delivery_at_corrected"),
"orders",
["scheduled_delivery_at_corrected"],
unique=False,
schema=config.CLEAN_SCHEMA,
)
def downgrade():
"""Downgrade to the previous revision."""
op.execute(f"DROP SCHEMA {config.CLEAN_SCHEMA} CASCADE;")

View file

@ -1,176 +0,0 @@
"""Add pixel grid."""
import os
import sqlalchemy as sa
from alembic import op
from velofy import configuration
revision = "888e352d7526"
down_revision = "f11cd76d2f45"
branch_labels = None
depends_on = None
config = configuration.make_config("testing" if os.getenv("TESTING") else "production")
def upgrade():
"""Upgrade to the next revision."""
op.create_table(
"grids",
sa.Column("id", sa.SmallInteger(), autoincrement=True, nullable=False),
sa.Column("city_id", sa.SmallInteger(), nullable=False),
sa.Column("side_length", sa.SmallInteger(), nullable=True),
sa.PrimaryKeyConstraint("id", name=op.f("pk_grids")),
sa.ForeignKeyConstraint(
["city_id"],
[f"{config.CLEAN_SCHEMA}.cities.id"],
name=op.f("fk_grids_to_cities_via_city_id"),
onupdate="RESTRICT",
ondelete="RESTRICT",
),
sa.UniqueConstraint(
"city_id",
"side_length",
name=op.f("uq_grids_on_city_id_side_length"),
),
# This `UniqueConstraint` is needed by the `addresses_pixels` table below
sa.UniqueConstraint("id", "city_id", name=op.f("uq_grids_on_id_city_id")),
schema=config.CLEAN_SCHEMA,
)
op.create_table(
"pixels",
sa.Column("id", sa.Integer(), autoincrement=True, nullable=False),
sa.Column("grid_id", sa.SmallInteger(), nullable=False),
sa.Column("n_x", sa.SmallInteger(), nullable=False),
sa.Column("n_y", sa.SmallInteger(), nullable=False),
sa.CheckConstraint("0 <= n_x", name=op.f("ck_pixels_on_n_x_is_positive")),
sa.CheckConstraint("0 <= n_y", name=op.f("ck_pixels_on_n_y_is_positive")),
sa.ForeignKeyConstraint(
["grid_id"],
[f"{config.CLEAN_SCHEMA}.grids.id"],
name=op.f("fk_pixels_to_grids_via_grid_id"),
onupdate="RESTRICT",
ondelete="RESTRICT",
),
sa.PrimaryKeyConstraint("id", name=op.f("pk_pixels")),
sa.UniqueConstraint(
"grid_id",
"n_x",
"n_y",
name=op.f("uq_pixels_on_grid_id_n_x_n_y"),
),
sa.UniqueConstraint("id", "grid_id", name=op.f("uq_pixels_on_id_grid_id")),
schema=config.CLEAN_SCHEMA,
)
op.create_index(
op.f("ix_pixels_on_grid_id"),
"pixels",
["grid_id"],
unique=False,
schema=config.CLEAN_SCHEMA,
)
op.create_index(
op.f("ix_pixels_on_n_x"),
"pixels",
["n_x"],
unique=False,
schema=config.CLEAN_SCHEMA,
)
op.create_index(
op.f("ix_pixels_on_n_y"),
"pixels",
["n_y"],
unique=False,
schema=config.CLEAN_SCHEMA,
)
# This `UniqueConstraint` is needed by the `addresses_pixels` table below
op.create_unique_constraint(
"uq_addresses_on_id_city_id",
"addresses",
["id", "city_id"],
schema=config.CLEAN_SCHEMA,
)
op.create_table(
"addresses_pixels",
sa.Column("address_id", sa.Integer(), nullable=False),
sa.Column("city_id", sa.SmallInteger(), nullable=False),
sa.Column("grid_id", sa.SmallInteger(), nullable=False),
sa.Column("pixel_id", sa.Integer(), nullable=False),
sa.ForeignKeyConstraint(
["address_id", "city_id"],
[
f"{config.CLEAN_SCHEMA}.addresses.id",
f"{config.CLEAN_SCHEMA}.addresses.city_id",
],
name=op.f("fk_addresses_pixels_to_addresses_via_address_id_city_id"),
onupdate="RESTRICT",
ondelete="RESTRICT",
),
sa.ForeignKeyConstraint(
["grid_id", "city_id"],
[
f"{config.CLEAN_SCHEMA}.grids.id",
f"{config.CLEAN_SCHEMA}.grids.city_id",
],
name=op.f("fk_addresses_pixels_to_grids_via_grid_id_city_id"),
onupdate="RESTRICT",
ondelete="RESTRICT",
),
sa.ForeignKeyConstraint(
["pixel_id", "grid_id"],
[
f"{config.CLEAN_SCHEMA}.pixels.id",
f"{config.CLEAN_SCHEMA}.pixels.grid_id",
],
name=op.f("fk_addresses_pixels_to_pixels_via_pixel_id_grid_id"),
onupdate="RESTRICT",
ondelete="RESTRICT",
),
sa.PrimaryKeyConstraint(
"address_id",
"pixel_id",
name=op.f("pk_addresses_pixels"),
),
sa.UniqueConstraint(
"address_id",
"grid_id",
name=op.f("uq_addresses_pixels_on_address_id_grid_id"),
),
schema=config.CLEAN_SCHEMA,
)
def downgrade():
"""Downgrade to the previous revision."""
op.drop_table("addresses_pixels", schema=config.CLEAN_SCHEMA)
op.drop_constraint(
"uq_addresses_on_id_city_id",
"addresses",
type_=None,
schema=config.CLEAN_SCHEMA,
)
op.drop_index(
op.f("ix_pixels_on_n_y"),
table_name="pixels",
schema=config.CLEAN_SCHEMA,
)
op.drop_index(
op.f("ix_pixels_on_n_x"),
table_name="pixels",
schema=config.CLEAN_SCHEMA,
)
op.drop_index(
op.f("ix_pixels_on_grid_id"),
table_name="pixels",
schema=config.CLEAN_SCHEMA,
)
op.drop_table("pixels", schema=config.CLEAN_SCHEMA)
op.drop_table("grids", schema=config.CLEAN_SCHEMA)

View file

@ -1,93 +0,0 @@
"""Add demand forecasting."""
import os
import sqlalchemy as sa
from alembic import op
from sqlalchemy.dialects import postgresql as psql
from velofy import configuration
revision = "e40623e10405"
down_revision = "888e352d7526"
branch_labels = None
depends_on = None
config = configuration.make_config("testing" if os.getenv("TESTING") else "production")
def upgrade():
"""Upgrade to the next revision."""
op.create_table(
"forecasts",
sa.Column("id", sa.Integer(), autoincrement=True, nullable=False),
sa.Column("pixel_id", sa.Integer(), nullable=False),
sa.Column("start_at", sa.DateTime(), nullable=False),
sa.Column("time_step", sa.SmallInteger(), nullable=False),
sa.Column("training_horizon", sa.SmallInteger(), nullable=False),
sa.Column("method", sa.Unicode(length=20), nullable=False),
sa.Column("prediction", psql.DOUBLE_PRECISION(), nullable=False),
sa.PrimaryKeyConstraint("id", name=op.f("pk_forecasts")),
sa.ForeignKeyConstraint(
["pixel_id"],
[f"{config.CLEAN_SCHEMA}.pixels.id"],
name=op.f("fk_forecasts_to_pixels_via_pixel_id"),
onupdate="RESTRICT",
ondelete="RESTRICT",
),
sa.CheckConstraint(
"""
NOT (
EXTRACT(HOUR FROM start_at) < 11
OR
EXTRACT(HOUR FROM start_at) > 22
)
""",
name=op.f("ck_forecasts_on_start_at_must_be_within_operating_hours"),
),
sa.CheckConstraint(
"CAST(EXTRACT(MINUTES FROM start_at) AS INTEGER) % 15 = 0",
name=op.f("ck_forecasts_on_start_at_minutes_must_be_quarters_of_the_hour"),
),
sa.CheckConstraint(
"CAST(EXTRACT(MICROSECONDS FROM start_at) AS INTEGER) % 1000000 = 0",
name=op.f("ck_forecasts_on_start_at_allows_no_microseconds"),
),
sa.CheckConstraint(
"EXTRACT(SECONDS FROM start_at) = 0",
name=op.f("ck_forecasts_on_start_at_allows_no_seconds"),
),
sa.CheckConstraint(
"time_step > 0",
name=op.f("ck_forecasts_on_time_step_must_be_positive"),
),
sa.CheckConstraint(
"training_horizon > 0",
name=op.f("ck_forecasts_on_training_horizon_must_be_positive"),
),
sa.UniqueConstraint(
"pixel_id",
"start_at",
"time_step",
"training_horizon",
"method",
name=op.f(
"uq_forecasts_on_pixel_id_start_at_time_step_training_horizon_method",
),
),
schema=config.CLEAN_SCHEMA,
)
op.create_index(
op.f("ix_forecasts_on_pixel_id"),
"forecasts",
["pixel_id"],
unique=False,
schema=config.CLEAN_SCHEMA,
)
def downgrade():
"""Downgrade to the previous revision."""
op.drop_table("forecasts", schema=config.CLEAN_SCHEMA)

View file

@ -1,134 +0,0 @@
"""Add confidence intervals to forecasts."""
import os
import sqlalchemy as sa
from alembic import op
from sqlalchemy.dialects import postgresql as psql
from velofy import configuration
revision = "26711cd3f9b9"
down_revision = "e40623e10405"
branch_labels = None
depends_on = None
config = configuration.make_config("testing" if os.getenv("TESTING") else "production")
def upgrade():
"""Upgrade to the next revision."""
op.alter_column(
"forecasts",
"method",
new_column_name="model",
schema=config.CLEAN_SCHEMA,
)
op.add_column(
"forecasts",
sa.Column("low80", psql.DOUBLE_PRECISION(), nullable=True),
schema=config.CLEAN_SCHEMA,
)
op.add_column(
"forecasts",
sa.Column("high80", psql.DOUBLE_PRECISION(), nullable=True),
schema=config.CLEAN_SCHEMA,
)
op.add_column(
"forecasts",
sa.Column("low95", psql.DOUBLE_PRECISION(), nullable=True),
schema=config.CLEAN_SCHEMA,
)
op.add_column(
"forecasts",
sa.Column("high95", psql.DOUBLE_PRECISION(), nullable=True),
schema=config.CLEAN_SCHEMA,
)
op.create_check_constraint(
op.f("ck_forecasts_on_ci_upper_and_lower_bounds"),
"forecasts",
"""
NOT (
low80 IS NULL AND high80 IS NOT NULL
OR
low80 IS NOT NULL AND high80 IS NULL
OR
low95 IS NULL AND high95 IS NOT NULL
OR
low95 IS NOT NULL AND high95 IS NULL
)
""",
schema=config.CLEAN_SCHEMA,
)
op.create_check_constraint(
op.f("prediction_must_be_within_ci"),
"forecasts",
"""
NOT (
prediction < low80
OR
prediction < low95
OR
prediction > high80
OR
prediction > high95
)
""",
schema=config.CLEAN_SCHEMA,
)
op.create_check_constraint(
op.f("ci_upper_bound_greater_than_lower_bound"),
"forecasts",
"""
NOT (
low80 > high80
OR
low95 > high95
)
""",
schema=config.CLEAN_SCHEMA,
)
op.create_check_constraint(
op.f("ci95_must_be_wider_than_ci80"),
"forecasts",
"""
NOT (
low80 < low95
OR
high80 > high95
)
""",
schema=config.CLEAN_SCHEMA,
)
def downgrade():
"""Downgrade to the previous revision."""
op.alter_column(
"forecasts",
"model",
new_column_name="method",
schema=config.CLEAN_SCHEMA,
)
op.drop_column(
"forecasts",
"low80",
schema=config.CLEAN_SCHEMA,
)
op.drop_column(
"forecasts",
"high80",
schema=config.CLEAN_SCHEMA,
)
op.drop_column(
"forecasts",
"low95",
schema=config.CLEAN_SCHEMA,
)
op.drop_column(
"forecasts",
"high95",
schema=config.CLEAN_SCHEMA,
)

Some files were not shown because too many files have changed in this diff Show more