Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

adding FromCSVToList annotation #42

Merged
merged 6 commits into from
Sep 25, 2023
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 1 addition & 2 deletions .github/workflows/build.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,9 @@ jobs:
fail-fast: false
matrix:
python-version:
- 3.7
- 3.8
- 3.9
- '3.10'
- 3.11
steps:
- uses: actions/checkout@v2
with:
Expand Down
2 changes: 1 addition & 1 deletion .pylint-license-header
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
"""
Copyright 2021 Adobe
Copyright 2023 Adobe
All Rights Reserved.

NOTICE: Adobe permits you to use, modify, and distribute this file in accordance
Expand Down
29 changes: 29 additions & 0 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -250,6 +250,35 @@ if you desire better validation for list, set, or dict fields, this must most li
Additionally, lists, sets, and dicts will ignore null values from the database. Therefore you must provide default
values for these fields when used or else validation will fail.

Added annotations when using DbMapResultModel
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
When using the ``DbMapResultModel`` mapper, there are some additional annotations that may be used to help with
mapping. These annotations are not required, but may be helpful in some cases.

* FromCSVToList - this annotation will convert a comma separated string into a list. This is useful when you have
a column containing a csv or a query that uses ``group_concat`` to combine multiple rows into a single row. This
annotation may be used on any field that is a list. For example:

.. code-block:: python

from dysql.pydantic_mappers import DbMapResultModel, FromCSVToList

class CsvModel(DbMapResultModel):
id: int
name: str
# This annotation will convert the string into a list of ints
list_from_string_int: FromCSVToList[List[int]]
# This annotation will convert the string into a list of strings
list_from_string: FromCSVToList[List[str]]
# This annotation will convert the string into a list of ints or None if the string is null or empty
list_from_string_int_nullable: FromCSVToList[List[int] | None]
# This annotation will convert the string into a list of strings or None if the string is null or empty
list_from_string_nullable: FromCSVToList[List[str] | None]

# if using python < 3.9, you can use typing.Union instead of the pipe operator
# list_from_string_nullable: FromCSVToList[Union[List[str],None]]
tamagoko marked this conversation as resolved.
Show resolved Hide resolved


@sqlquery
~~~~~~~~~
This is for making SQL ``select`` calls. An optional mapper may be specified to
Expand Down
31 changes: 31 additions & 0 deletions dysql/annotations.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
"""
Copyright 2023 Adobe
All Rights Reserved.

NOTICE: Adobe permits you to use, modify, and distribute this file in accordance
with the terms of the Adobe license agreement accompanying it.
"""

from typing import TypeVar, Annotated

from pydantic import BeforeValidator

# pylint: disable=invalid-name
T = TypeVar('T')


def _transform_csv(value: str) -> T:
if not value:
return None

if isinstance(value, str):
return list(map(str.strip, value.split(',')))

if isinstance(value, list):
return value
# if we don't have a string or type T we aren't going to be able to transform it
return [value]


# Annotation that helps transform a CSV string into a list of type T
FromCSVToList = Annotated[T, BeforeValidator(_transform_csv)]
61 changes: 61 additions & 0 deletions dysql/test/test_annotations.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
"""
Copyright 2023 Adobe
All Rights Reserved.

NOTICE: Adobe permits you to use, modify, and distribute this file in accordance
with the terms of the Adobe license agreement accompanying it.
"""
from typing import List, Union

import pytest
from pydantic import BaseModel, ValidationError

from dysql.annotations import FromCSVToList


class StrCSVModel(BaseModel):
values: FromCSVToList[List[str]]


class IntCSVModel(BaseModel):
values: FromCSVToList[List[int]]


class NullableStrCSVModel(BaseModel):
values: FromCSVToList[Union[List[str], None]]


class NullableIntCSVModel(BaseModel):
values: FromCSVToList[Union[List[int], None]]


@pytest.mark.parametrize('cls, values, expected', [
(StrCSVModel, '1,2,3', ['1', '2', '3']),
(StrCSVModel, 'a,b', ['a', 'b']),
(StrCSVModel, 'a', ['a']),
(NullableStrCSVModel, '', None),
(NullableStrCSVModel, None, None),
(StrCSVModel, ['a', 'b'], ['a', 'b']),
(StrCSVModel, ['a', 'b', 'c'], ['a', 'b', 'c']),
(IntCSVModel, '1,2,3', [1, 2, 3]),
(IntCSVModel, '1', [1]),
(NullableIntCSVModel, '', None),
(NullableIntCSVModel, None, None),
(IntCSVModel, ['1', '2', '3'], [1, 2, 3]),
(IntCSVModel, ['1', '2', '3', 4, 5], [1, 2, 3, 4, 5])
])
def test_from_csv_to_list(cls, values, expected):
assert expected == cls(values=values).values


@pytest.mark.parametrize('cls, values', [
(StrCSVModel, ''),
(StrCSVModel, None),
(IntCSVModel, 'a,b,c'),
(IntCSVModel, ''),
(IntCSVModel, None),
(IntCSVModel, ['a', 'b', 'c']),
])
def test_from_csv_to_list_invalid(cls, values):
with pytest.raises(ValidationError):
cls(values=values)
11 changes: 5 additions & 6 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
from setuptools import setup, find_packages


BASE_VERSION = '2.0'
BASE_VERSION = '3.0'
SOURCE_DIR = os.path.dirname(
os.path.abspath(__file__)
)
Expand Down Expand Up @@ -76,13 +76,12 @@ def get_version():
platforms=['Any'],
packages=find_packages(exclude=('*test*',)),
zip_safe=False,
install_requires=(
install_requires=[
# SQLAlchemy 2+ is not yet submitted
'sqlalchemy<2',
),
extras_require={
'pydantic': ['pydantic>2'],
},
# now using features only found in pydantic 2+
'pydantic>=2',
],
classifiers=[
'Development Status :: 4 - Beta',
'License :: OSI Approved :: MIT License',
Expand Down
Loading