Skip to content

Commit

Permalink
feat: JSONB column
Browse files Browse the repository at this point in the history
  • Loading branch information
etimberg committed Aug 2, 2021
1 parent b965097 commit 3dd211e
Show file tree
Hide file tree
Showing 4 changed files with 72 additions and 1 deletion.
5 changes: 4 additions & 1 deletion src/ormar_postgres_extensions/__init__.py
Original file line number Diff line number Diff line change
@@ -1 +1,4 @@
from .fields import PostgresUUID # noqa: F401
from .fields import ( # noqa: F401
PostgresJSONB,
PostgresUUID,
)
1 change: 1 addition & 0 deletions src/ormar_postgres_extensions/fields/__init__.py
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
from .jsonb import PostgresJSONB # noqa: F401
from .uuid import PostgresUUID # noqa: F401
19 changes: 19 additions & 0 deletions src/ormar_postgres_extensions/fields/jsonb.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
from typing import Any

import ormar
from sqlalchemy.dialects import postgresql
from sqlalchemy.types import TypeDecorator


class PostgresJSONBTypeDecorator(TypeDecorator):
impl = postgresql.JSONB


class PostgresJSONB(ormar.JSON):
"""
Custom JSON field uses a native PG JSONB type
"""

@classmethod
def get_column_type(cls, **kwargs: Any) -> PostgresJSONBTypeDecorator:
return PostgresJSONBTypeDecorator()
48 changes: 48 additions & 0 deletions tests/fields/test_jsonb.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import json
from typing import Optional

import ormar
import pytest

from ormar_postgres_extensions.fields import PostgresJSONB
from tests.database import (
database,
metadata,
)


class JSONBTestModel(ormar.Model):
class Meta:
database = database
metadata = metadata

id: int = ormar.Integer(primary_key=True)
data: dict = PostgresJSONB()


class NullableJSONBTestModel(ormar.Model):
class Meta:
database = database
metadata = metadata

id: int = ormar.Integer(primary_key=True)
data: Optional[dict] = PostgresJSONB(nullable=True)


@pytest.mark.asyncio
async def test_create_model_with_jsonb(db):
created = await JSONBTestModel(data=json.dumps(dict(foo="bar"))).save()
assert created.data == {"foo": "bar"}

# Confirm the model got saved to the DB by querying it back
found = await JSONBTestModel.objects.get()
assert found.data == {"foo": "bar"}


@pytest.mark.asyncio
async def test_create_model_with_nullable_jsonb(db):
created = await NullableJSONBTestModel().save()
assert created.data is None

found = await NullableJSONBTestModel.objects.get()
assert found.data is None

0 comments on commit 3dd211e

Please sign in to comment.