Metadata-Version: 2.5
Name: django-greenplum-updated
Version: 0.1.4
Project-URL: Homepage, https://github.com/Illofalgorn/django-greenplum-updated
Project-URL: Repository, https://github.com/Illofalgorn/django-greenplum-updated
Project-URL: Issues, https://github.com/Illofalgorn/django-greenplum-updated/issues
Requires-Python: >=3.10
Requires-Dist: django>=3.0
Requires-Dist: psycopg2-binary; sys_platform == 'linux'
Requires-Dist: psycopg2; sys_platform != 'linux'
Provides-Extra: test
Requires-Dist: psycopg2-binary; extra == 'test'
Requires-Dist: pytest; extra == 'test'
Requires-Dist: pytest-django; extra == 'test'
Description-Content-Type: text/markdown

# Django-Greenplum

Django ORM backend for [Greenplum](https://greenplum.org/) — a massively parallel PostgreSQL-based database.

Originally authored by [souno](https://github.com/souno).

---

## Requirements

- Python 3.10+
- Django >= 3.0 (tested up to Django 6.0)
- Greenplum 6 or newer (Greenplum 6 ≈ PostgreSQL 9.4, Greenplum 7 ≈ PostgreSQL 12)
- psycopg2 (or psycopg2-binary on Linux)

---

## Installation

You can install the package via `pip` or `uv`:

### Using uv (recommended)

```bash
uv add django-greenplum-updated
```

```python
DATABASES = {
    'default': {
        'ENGINE'  : 'django_greenplum',
        'NAME'    : 'mydb',
        'USER'    : 'gpadmin',
        'PASSWORD': 'secret',
        'HOST'    : '127.0.0.1',
        'PORT'    : '5432',
    }
}
```

---

## Recommended architecture: two databases

Greenplum is a data-warehouse engine and is a poor fit for the metadata-heavy
tables of Django's built-in apps (`admin`, `auth`, `contenttypes`, `sessions`,
`migrations`), which rely on single-column unique keys and frequent `ALTER`s
that Greenplum restricts.

The recommended layout keeps **two** databases:

- `default` — an ordinary database (SQLite/PostgreSQL) for Django itself and
  your application logic.
- `gp` — the Greenplum database that holds your large / analytical **data**
  tables.

A database router sends the right models to the right database:

```python
# settings.py
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',   # or postgresql
        'NAME': BASE_DIR / 'db.sqlite3',
    },
    'gp': {
        'ENGINE'  : 'django_greenplum',
        'NAME'    : 'warehouse',
        'USER'    : 'gpadmin',
        'PASSWORD': 'secret',
        'HOST'    : '127.0.0.1',
        'PORT'    : '5432',
    },
}
DATABASE_ROUTERS = ['myproject.db_routers.GreenplumRouter']
```

```python
# db_routers.py
DATA_APPS = {'analytics'}   # apps whose models live in Greenplum

class GreenplumRouter:
    def db_for_read(self, model, **hints):
        return 'gp' if model._meta.app_label in DATA_APPS else 'default'

    db_for_write = db_for_read

    def allow_relation(self, obj1, obj2, **hints):
        in_gp = {obj1._meta.app_label, obj2._meta.app_label} & DATA_APPS
        if in_gp:
            return obj1._meta.app_label == obj2._meta.app_label
        return None

    def allow_migrate(self, db, app_label, model_name=None, **hints):
        if app_label in DATA_APPS:
            return db == 'gp'
        return db == 'default'
```

Migrate each database explicitly:

```bash
python manage.py migrate                 # default (Django + logic)
python manage.py migrate --database=gp   # Greenplum (data tables)
```

A full working example lives in `tests/example_project`.

### Try it in the browser

The example project ships a small web UI to exercise reads and writes against
Greenplum without opening a shell:

```bash
cd tests/example_project
python manage.py migrate                 # default (Django auth/admin/sessions)
python manage.py migrate --database=gp   # Greenplum (testapp data tables)
python manage.py runserver
```

Then open <http://127.0.0.1:8000/>:

* the **dashboard** lists every data model (`Orders`, `Sales`, `Events`) with
  its live row count read from Greenplum;
* each model page lets you **create** rows (written to Greenplum) and
  **delete** them again, so you can verify data operations end to end;
* the standard Django **admin** (`/admin/`) also has all three models
  registered — run `python manage.py createsuperuser` to use it.

---

## Lossless migrations

Greenplum forbids a number of in-place `ALTER`s that plain PostgreSQL allows —
for example changing the **type** of a column that participates in a primary
key, a unique constraint, or the distribution key. When Django emits such an
`ALTER`, this backend catches Greenplum's refusal and transparently **rebuilds
the table without losing data**:

1. create `new__<table>` with the target schema (same `DISTRIBUTED BY` and
   partitioning),
2. copy every row across (casting the changed columns),
3. drop the original table and rename the new one into its place,
4. re-sync the sequences backing `AutoField` columns so identity values
   continue where they left off.

This happens automatically inside a transaction — if anything fails the whole
change rolls back. No configuration is required.

> **Caveats.** The rebuild uses `DROP TABLE ... CASCADE`, so foreign keys from
> *other* tables pointing at the rebuilt table are not restored (Greenplum does
> not enforce referential integrity across distributed tables anyway). Keep
> such relationships inside the `default` database.

## Partitioning

Greenplum supports table partitioning at the storage level. This backend lets you declare the partition strategy
directly on your Django model as a class attribute.

Import the partition class and assign it to `greenplum_partition`:

```python
from django_greenplum.partition import RangePartition, ListPartition
```

### Range partition — automatic (EVERY)

Splits the table into equal sub-partitions over a continuous range.

```python
class Orders(models.Model):
    order_date = models.DateField()
    amount = models.DecimalField(max_digits=12, decimal_places=2)

    greenplum_partition = RangePartition(
        column='order_date',
        start='2020-01-01',
        end='2026-01-01',
        every='1 month',  # string → INTERVAL '1 month'
        # integer → plain numeric step
    )
```

Generated SQL suffix:

```sql
PARTITION BY RANGE ("order_date")
(START ('2020-01-01') INCLUSIVE END ('2026-01-01') EXCLUSIVE EVERY (INTERVAL '1 month'))
```

### Range partition — manual named partitions

```python
class Events(models.Model):
    event_date = models.DateField()
    description = models.TextField()

    greenplum_partition = RangePartition(
        column='event_date',
        partitions=[
            ('p2023', '2023-01-01', '2024-01-01'),
            ('p2024', '2024-01-01', '2025-01-01'),
            ('p2025', '2025-01-01', '2026-01-01'),
        ],
    )
```

### List partition

```python
class Sales(models.Model):
    region = models.CharField(max_length=20)
    revenue = models.DecimalField(max_digits=14, decimal_places=2)

    greenplum_partition = ListPartition(
        column='region',
        partitions=[
            ('north', ['north', 'northeast']),
            ('south', ['south', 'southeast']),
            ('other', ['west', 'east']),
        ],
    )
```

### RangePartition parameters

| Parameter         | Type                    | Description                                                      |
|-------------------|-------------------------|------------------------------------------------------------------|
| `column`          | `str`                   | Model field name to partition by                                 |
| `start`           | value                   | Inclusive start bound (required with `every`)                    |
| `end`             | value                   | Exclusive end bound (required with `every`)                      |
| `every`           | `str` or `int`          | Step for automatic partitions (`"1 month"`, `"1 year"`, `10`, …) |
| `partitions`      | list of 3-tuples        | Manual named partitions `(name, start, end)`                     |
| `start_inclusive` | `bool` (default `True`) | Whether the start bound is `INCLUSIVE`                           |
| `end_exclusive`   | `bool` (default `True`) | Whether the end bound is `EXCLUSIVE`                             |

`every` and `partitions` are mutually exclusive.

### ListPartition parameters

| Parameter    | Type             | Description                                              |
|--------------|------------------|----------------------------------------------------------|
| `column`     | `str`            | Model field name to partition by                         |
| `partitions` | list of 2-tuples | `(partition_name, [value, value, …])` for each partition |

### Migrations pick up partition changes

The `greenplum_partition` descriptor is registered with Django's migration
framework, so `makemigrations` detects when a partition is **added, changed or
removed** and records it as an `AlterModelOptions` operation (just like any
other model `Meta` option):

```console
$ python manage.py makemigrations
Migrations for 'shop':
  shop/migrations/0002_alter_orders_options.py
    ~ Change Meta options on orders
```

Both `RangePartition` and `ListPartition` are serialized into the generated
migration file, so the partition definition is versioned alongside the rest of
your schema. The partition change itself is applied when the table is created
(or during the lossless table rebuild), not by the `AlterModelOptions`
operation, which only updates migration state.

---

## Notices

1. The primary key is used as the **distribution key** by default. Greenplum requires the distribution key to be part
   of every `UNIQUE` constraint, so `unique=True` on a non-primary-key field is created as a *composite* unique
   `UNIQUE(pk, column)`. This means it does **not** enforce single-column uniqueness on its own — plan your schema
   accordingly.

2. Because of the above limitation, the default Django `admin`, `auth`, `contenttypes` and `sessions` applications
   should live in a separate, non-Greenplum database. See *Recommended architecture: two databases* above.

3. Partition child tables are automatically excluded from Django's model introspection — only the parent (root) table is
   visible.

4. Greenplum 6 and 7 differ in their partition catalogs (`pg_partitions` was removed in Greenplum 7 in favour of the
   native `pg_partitioned_table`). The backend detects partitioning in a version-agnostic way, but full round-trip
   partition *introspection* (reconstructing a `RangePartition`/`ListPartition` from the database) is currently only
   available on Greenplum 6.
