sqla-fancy-core 0.2.0__tar.gz → 1.0.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of sqla-fancy-core might be problematic. Click here for more details.

@@ -0,0 +1,29 @@
1
+ name: Python package
2
+
3
+ on: [push]
4
+
5
+ jobs:
6
+ build:
7
+ runs-on: ubuntu-latest
8
+ strategy:
9
+ matrix:
10
+ python-version: ["3.8", "3.9", "3.10", "3.11", "3.12", "3.13"]
11
+
12
+ steps:
13
+ - uses: actions/checkout@v3
14
+ - name: Set up Python ${{ matrix.python-version }}
15
+ uses: actions/setup-python@v4
16
+ with:
17
+ python-version: ${{ matrix.python-version }}
18
+ - name: Install dependencies
19
+ run: |
20
+ pip install -e ".[test]"
21
+ - name: Lint with flake8
22
+ run: |
23
+ # stop the build if there are Python syntax errors or undefined names
24
+ flake8 sqla_fancy_core --count --select=E9,F63,F7,F82 --show-source --statistics
25
+ # exit-zero treats all errors as warnings. The GitHub editor is 127 chars wide
26
+ flake8 sqla_fancy_core --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics
27
+ - name: Test with pytest
28
+ run: |
29
+ pytest
@@ -0,0 +1,160 @@
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ .Python
11
+ build/
12
+ develop-eggs/
13
+ dist/
14
+ downloads/
15
+ eggs/
16
+ .eggs/
17
+ lib/
18
+ lib64/
19
+ parts/
20
+ sdist/
21
+ var/
22
+ wheels/
23
+ share/python-wheels/
24
+ *.egg-info/
25
+ .installed.cfg
26
+ *.egg
27
+ MANIFEST
28
+
29
+ # PyInstaller
30
+ # Usually these files are written by a python script from a template
31
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
32
+ *.manifest
33
+ *.spec
34
+
35
+ # Installer logs
36
+ pip-log.txt
37
+ pip-delete-this-directory.txt
38
+
39
+ # Unit test / coverage reports
40
+ htmlcov/
41
+ .tox/
42
+ .nox/
43
+ .coverage
44
+ .coverage.*
45
+ .cache
46
+ nosetests.xml
47
+ coverage.xml
48
+ *.cover
49
+ *.py,cover
50
+ .hypothesis/
51
+ .pytest_cache/
52
+ cover/
53
+
54
+ # Translations
55
+ *.mo
56
+ *.pot
57
+
58
+ # Django stuff:
59
+ *.log
60
+ local_settings.py
61
+ db.sqlite3
62
+ db.sqlite3-journal
63
+
64
+ # Flask stuff:
65
+ instance/
66
+ .webassets-cache
67
+
68
+ # Scrapy stuff:
69
+ .scrapy
70
+
71
+ # Sphinx documentation
72
+ docs/_build/
73
+
74
+ # PyBuilder
75
+ .pybuilder/
76
+ target/
77
+
78
+ # Jupyter Notebook
79
+ .ipynb_checkpoints
80
+
81
+ # IPython
82
+ profile_default/
83
+ ipython_config.py
84
+
85
+ # pyenv
86
+ # For a library or package, you might want to ignore these files since the code is
87
+ # intended to run in multiple environments; otherwise, check them in:
88
+ # .python-version
89
+
90
+ # pipenv
91
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
92
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
93
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
94
+ # install all needed dependencies.
95
+ #Pipfile.lock
96
+
97
+ # poetry
98
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
99
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
100
+ # commonly ignored for libraries.
101
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
102
+ #poetry.lock
103
+
104
+ # pdm
105
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
106
+ #pdm.lock
107
+ # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
108
+ # in version control.
109
+ # https://pdm.fming.dev/#use-with-ide
110
+ .pdm.toml
111
+
112
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
113
+ __pypackages__/
114
+
115
+ # Celery stuff
116
+ celerybeat-schedule
117
+ celerybeat.pid
118
+
119
+ # SageMath parsed files
120
+ *.sage.py
121
+
122
+ # Environments
123
+ .env
124
+ .venv
125
+ env/
126
+ venv/
127
+ ENV/
128
+ env.bak/
129
+ venv.bak/
130
+
131
+ # Spyder project settings
132
+ .spyderproject
133
+ .spyproject
134
+
135
+ # Rope project settings
136
+ .ropeproject
137
+
138
+ # mkdocs documentation
139
+ /site
140
+
141
+ # mypy
142
+ .mypy_cache/
143
+ .dmypy.json
144
+ dmypy.json
145
+
146
+ # Pyre type checker
147
+ .pyre/
148
+
149
+ # pytype static type analyzer
150
+ .pytype/
151
+
152
+ # Cython debug symbols
153
+ cython_debug/
154
+
155
+ # PyCharm
156
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
157
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
158
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
159
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
160
+ #.idea/
@@ -0,0 +1,192 @@
1
+ Metadata-Version: 2.4
2
+ Name: sqla-fancy-core
3
+ Version: 1.0.0
4
+ Summary: SQLAlchemy core, but fancier
5
+ Project-URL: Homepage, https://github.com/sayanarijit/sqla-fancy-core
6
+ Author-email: Arijit Basu <sayanarijit@gmail.com>
7
+ Maintainer-email: Arijit Basu <sayanarijit@gmail.com>
8
+ License: MIT License
9
+
10
+ Copyright (c) 2023 Arijit Basu
11
+
12
+ Permission is hereby granted, free of charge, to any person obtaining a copy
13
+ of this software and associated documentation files (the "Software"), to deal
14
+ in the Software without restriction, including without limitation the rights
15
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
16
+ copies of the Software, and to permit persons to whom the Software is
17
+ furnished to do so, subject to the following conditions:
18
+
19
+ The above copyright notice and this permission notice shall be included in all
20
+ copies or substantial portions of the Software.
21
+
22
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
23
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
24
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
25
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
26
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
27
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
28
+ SOFTWARE.
29
+ License-File: LICENSE
30
+ Keywords: sql,sqlalchemy,sqlalchemy-core
31
+ Classifier: Intended Audience :: Developers
32
+ Classifier: License :: OSI Approved :: MIT License
33
+ Classifier: Programming Language :: Python :: 3
34
+ Requires-Python: >=3.7
35
+ Requires-Dist: sqlalchemy
36
+ Provides-Extra: test
37
+ Requires-Dist: flake8; extra == 'test'
38
+ Requires-Dist: pydantic; extra == 'test'
39
+ Requires-Dist: pytest; extra == 'test'
40
+ Description-Content-Type: text/markdown
41
+
42
+ # sqla-fancy-core
43
+
44
+ SQLAlchemy core, but fancier.
45
+
46
+ ### Basic Usage
47
+
48
+ ```python
49
+ import sqlalchemy as sa
50
+ from sqla_fancy_core import TableFactory
51
+
52
+ tf = TableFactory()
53
+
54
+ # Define a table
55
+ class Author:
56
+
57
+ id = tf.auto_id()
58
+ name = tf.string("name")
59
+ created_at = tf.created_at()
60
+ updated_at = tf.updated_at()
61
+
62
+ Table = tf("author")
63
+
64
+ # Or define it without losing type hints
65
+ class Book:
66
+ id = tf(sa.Column("id", sa.Integer, primary_key=True, autoincrement=True))
67
+ title = tf(sa.Column("title", sa.String(255), nullable=False))
68
+ author_id = tf(sa.Column("author_id", sa.Integer, sa.ForeignKey(Author.id)))
69
+ created_at = tf(
70
+ sa.Column(
71
+ "created_at",
72
+ sa.DateTime,
73
+ nullable=False,
74
+ server_default=sa.func.now(),
75
+ )
76
+ )
77
+ updated_at = tf(
78
+ sa.Column(
79
+ "updated_at",
80
+ sa.DateTime,
81
+ nullable=False,
82
+ server_default=sa.func.now(),
83
+ onupdate=sa.func.now(),
84
+ )
85
+ )
86
+
87
+ Table = tf(sa.Table("book", sa.MetaData()))
88
+
89
+ # Create the tables
90
+ engine = sa.create_engine("sqlite:///:memory:")
91
+ tf.metadata.create_all(engine)
92
+
93
+ with engine.connect() as conn:
94
+ # Insert author
95
+ qry = (
96
+ sa.insert(Author.Table)
97
+ .values({Author.name: "John Doe"})
98
+ .returning(Author.id)
99
+ )
100
+ author = next(conn.execute(qry).mappings())
101
+ author_id = author[Author.id]
102
+ assert author_id == 1
103
+
104
+ # Insert book
105
+ qry = (
106
+ sa.insert(Book.Table)
107
+ .values({Book.title: "My Book", Book.author_id: author_id})
108
+ .returning(Book.id)
109
+ )
110
+ book = next(conn.execute(qry).mappings())
111
+ assert book[Book.id] == 1
112
+
113
+ # Query the data
114
+ qry = sa.select(Author.name, Book.title).join(
115
+ Book.Table,
116
+ Book.author_id == Author.id,
117
+ )
118
+ result = conn.execute(qry).fetchall()
119
+ assert result == [("John Doe", "My Book")], result
120
+
121
+ # Create the tables
122
+ engine = sa.create_engine("sqlite:///:memory:")
123
+ tf.metadata.create_all(engine)
124
+
125
+ with engine.connect() as conn:
126
+ # Insert author
127
+ qry = (
128
+ sa.insert(Author.Table)
129
+ .values({Author.name: "John Doe"})
130
+ .returning(Author.id)
131
+ )
132
+ author = next(conn.execute(qry).mappings())
133
+ author_id = author[Author.id]
134
+ assert author_id == 1
135
+
136
+ # Insert book
137
+ qry = (
138
+ sa.insert(Book.Table)
139
+ .values({Book.title: "My Book", Book.author_id: author_id})
140
+ .returning(Book.id)
141
+ )
142
+ book = next(conn.execute(qry).mappings())
143
+ assert book[Book.id] == 1
144
+
145
+ # Query the data
146
+ qry = sa.select(Author.name, Book.title).join(
147
+ Book.Table,
148
+ Book.author_id == Author.id,
149
+ )
150
+ result = conn.execute(qry).fetchall()
151
+ assert result == [("John Doe", "My Book")], result
152
+ ```
153
+
154
+ ### With Pydantic Validation
155
+
156
+ ```python
157
+ from typing import Any
158
+ import sqlalchemy as sa
159
+ from pydantic import BaseModel, Field
160
+
161
+ from sqla_fancy_core import TableFactory
162
+
163
+ tf = TableFactory()
164
+
165
+ def field(col, default: Any = ...) -> Field:
166
+ return col.info["kwargs"]["field"](default)
167
+
168
+ # Define a table
169
+ class User:
170
+ name = tf(
171
+ sa.Column("name", sa.String),
172
+ field=lambda default: Field(default, max_length=5),
173
+ )
174
+ Table = tf("author")
175
+
176
+ # Define a pydantic schema
177
+ class CreateUser(BaseModel):
178
+ name: str = field(User.name)
179
+
180
+ # Define a pydantic schema
181
+ class UpdateUser(BaseModel):
182
+ name: str | None = field(User.name, None)
183
+
184
+ assert CreateUser(name="John").model_dump() == {"name": "John"}
185
+ assert UpdateUser(name="John").model_dump() == {"name": "John"}
186
+ assert UpdateUser().model_dump(exclude_unset=True) == {}
187
+
188
+ with pytest.raises(ValueError):
189
+ CreateUser()
190
+ with pytest.raises(ValueError):
191
+ UpdateUser(name="John Doe")
192
+ ```
@@ -0,0 +1,151 @@
1
+ # sqla-fancy-core
2
+
3
+ SQLAlchemy core, but fancier.
4
+
5
+ ### Basic Usage
6
+
7
+ ```python
8
+ import sqlalchemy as sa
9
+ from sqla_fancy_core import TableFactory
10
+
11
+ tf = TableFactory()
12
+
13
+ # Define a table
14
+ class Author:
15
+
16
+ id = tf.auto_id()
17
+ name = tf.string("name")
18
+ created_at = tf.created_at()
19
+ updated_at = tf.updated_at()
20
+
21
+ Table = tf("author")
22
+
23
+ # Or define it without losing type hints
24
+ class Book:
25
+ id = tf(sa.Column("id", sa.Integer, primary_key=True, autoincrement=True))
26
+ title = tf(sa.Column("title", sa.String(255), nullable=False))
27
+ author_id = tf(sa.Column("author_id", sa.Integer, sa.ForeignKey(Author.id)))
28
+ created_at = tf(
29
+ sa.Column(
30
+ "created_at",
31
+ sa.DateTime,
32
+ nullable=False,
33
+ server_default=sa.func.now(),
34
+ )
35
+ )
36
+ updated_at = tf(
37
+ sa.Column(
38
+ "updated_at",
39
+ sa.DateTime,
40
+ nullable=False,
41
+ server_default=sa.func.now(),
42
+ onupdate=sa.func.now(),
43
+ )
44
+ )
45
+
46
+ Table = tf(sa.Table("book", sa.MetaData()))
47
+
48
+ # Create the tables
49
+ engine = sa.create_engine("sqlite:///:memory:")
50
+ tf.metadata.create_all(engine)
51
+
52
+ with engine.connect() as conn:
53
+ # Insert author
54
+ qry = (
55
+ sa.insert(Author.Table)
56
+ .values({Author.name: "John Doe"})
57
+ .returning(Author.id)
58
+ )
59
+ author = next(conn.execute(qry).mappings())
60
+ author_id = author[Author.id]
61
+ assert author_id == 1
62
+
63
+ # Insert book
64
+ qry = (
65
+ sa.insert(Book.Table)
66
+ .values({Book.title: "My Book", Book.author_id: author_id})
67
+ .returning(Book.id)
68
+ )
69
+ book = next(conn.execute(qry).mappings())
70
+ assert book[Book.id] == 1
71
+
72
+ # Query the data
73
+ qry = sa.select(Author.name, Book.title).join(
74
+ Book.Table,
75
+ Book.author_id == Author.id,
76
+ )
77
+ result = conn.execute(qry).fetchall()
78
+ assert result == [("John Doe", "My Book")], result
79
+
80
+ # Create the tables
81
+ engine = sa.create_engine("sqlite:///:memory:")
82
+ tf.metadata.create_all(engine)
83
+
84
+ with engine.connect() as conn:
85
+ # Insert author
86
+ qry = (
87
+ sa.insert(Author.Table)
88
+ .values({Author.name: "John Doe"})
89
+ .returning(Author.id)
90
+ )
91
+ author = next(conn.execute(qry).mappings())
92
+ author_id = author[Author.id]
93
+ assert author_id == 1
94
+
95
+ # Insert book
96
+ qry = (
97
+ sa.insert(Book.Table)
98
+ .values({Book.title: "My Book", Book.author_id: author_id})
99
+ .returning(Book.id)
100
+ )
101
+ book = next(conn.execute(qry).mappings())
102
+ assert book[Book.id] == 1
103
+
104
+ # Query the data
105
+ qry = sa.select(Author.name, Book.title).join(
106
+ Book.Table,
107
+ Book.author_id == Author.id,
108
+ )
109
+ result = conn.execute(qry).fetchall()
110
+ assert result == [("John Doe", "My Book")], result
111
+ ```
112
+
113
+ ### With Pydantic Validation
114
+
115
+ ```python
116
+ from typing import Any
117
+ import sqlalchemy as sa
118
+ from pydantic import BaseModel, Field
119
+
120
+ from sqla_fancy_core import TableFactory
121
+
122
+ tf = TableFactory()
123
+
124
+ def field(col, default: Any = ...) -> Field:
125
+ return col.info["kwargs"]["field"](default)
126
+
127
+ # Define a table
128
+ class User:
129
+ name = tf(
130
+ sa.Column("name", sa.String),
131
+ field=lambda default: Field(default, max_length=5),
132
+ )
133
+ Table = tf("author")
134
+
135
+ # Define a pydantic schema
136
+ class CreateUser(BaseModel):
137
+ name: str = field(User.name)
138
+
139
+ # Define a pydantic schema
140
+ class UpdateUser(BaseModel):
141
+ name: str | None = field(User.name, None)
142
+
143
+ assert CreateUser(name="John").model_dump() == {"name": "John"}
144
+ assert UpdateUser(name="John").model_dump() == {"name": "John"}
145
+ assert UpdateUser().model_dump(exclude_unset=True) == {}
146
+
147
+ with pytest.raises(ValueError):
148
+ CreateUser()
149
+ with pytest.raises(ValueError):
150
+ UpdateUser(name="John Doe")
151
+ ```
@@ -0,0 +1,35 @@
1
+ [project]
2
+ name = 'sqla-fancy-core'
3
+ version = '1.0.0'
4
+ description = 'SQLAlchemy core, but fancier'
5
+ readme = 'README.md'
6
+ requires-python = ">=3.7"
7
+ license = { file = "LICENSE" }
8
+ keywords = ["sql", "sqlalchemy", "sqlalchemy-core"]
9
+ authors = [{ name = "Arijit Basu", email = "sayanarijit@gmail.com" }]
10
+ maintainers = [{ name = "Arijit Basu", email = "sayanarijit@gmail.com" }]
11
+ classifiers = [
12
+ # Indicate who your project is intended for
13
+ "Intended Audience :: Developers",
14
+
15
+
16
+ # Pick your license as you wish
17
+ "License :: OSI Approved :: MIT License",
18
+
19
+ # Specify the Python versions you support here. In particular, ensure
20
+ # that you indicate you support Python 3. These classifiers are *not*
21
+ # checked by "pip install". See instead "python_requires" below.
22
+ "Programming Language :: Python :: 3",
23
+ ]
24
+
25
+ dependencies = ["sqlalchemy"]
26
+
27
+ [project.optional-dependencies]
28
+ test = ["pytest", "flake8", "pydantic"]
29
+
30
+ [project.urls]
31
+ "Homepage" = "https://github.com/sayanarijit/sqla-fancy-core"
32
+
33
+ [build-system]
34
+ requires = ["hatchling"]
35
+ build-backend = "hatchling.build"
@@ -1,13 +1,18 @@
1
1
  """SQLAlchemy core, but fancier."""
2
2
 
3
+ from typing import Optional, Union, overload
4
+
3
5
  import sqlalchemy as sa
4
6
 
5
7
 
6
8
  class TableFactory:
7
9
  """A factory for creating SQLAlchemy columns with default values."""
8
10
 
9
- def __init__(self):
11
+ def __init__(self, metadata: Optional[sa.MetaData] = None):
10
12
  """Initialize the factory with default values."""
13
+ if metadata is None:
14
+ metadata = sa.MetaData()
15
+ self.metadata = metadata
11
16
  self.c = []
12
17
 
13
18
  def col(self, *args, **kwargs) -> sa.Column:
@@ -66,7 +71,7 @@ class TableFactory:
66
71
  def false(self, name: str, *args, **kwargs):
67
72
  return self.boolean(name, default=False, *args, **kwargs)
68
73
 
69
- def foreign_key(self, name: str, ref: str | sa.Column, *args, **kwargs):
74
+ def foreign_key(self, name: str, ref: Union[str, sa.Column], *args, **kwargs):
70
75
  return self.col(name, sa.ForeignKey(ref), *args, **kwargs)
71
76
 
72
77
  def enum(self, name: str, enum: type, *args, **kwargs) -> sa.Column:
@@ -130,7 +135,25 @@ class TableFactory:
130
135
  def created_at(self, name="created_at", *args, **kwargs) -> sa.Column:
131
136
  return self.datetime(name, default=sa.func.now(), *args, **kwargs)
132
137
 
133
- def __call__(self, name, metadata, *args, **kwargs):
134
- cols = self.c
135
- self.c = []
136
- return sa.Table(name, metadata, *args, *cols, **kwargs)
138
+ @overload
139
+ def __call__(self, arg1: str, *args, **kwargs) -> sa.Table: ...
140
+ @overload
141
+ def __call__(self, arg1: sa.Column, *args, **kwargs) -> sa.Column: ...
142
+ @overload
143
+ def __call__(self, arg1: sa.Table, *args, **kwargs) -> sa.Table: ...
144
+ def __call__(self, arg1, *args, **kwargs):
145
+ if isinstance(arg1, str):
146
+ cols = self.c
147
+ self.c = []
148
+ return sa.Table(arg1, self.metadata, *args, *cols, **kwargs)
149
+ elif isinstance(arg1, sa.Column):
150
+ arg1.info["args"] = args
151
+ arg1.info["kwargs"] = kwargs
152
+ self.c.append(arg1)
153
+ return arg1
154
+ elif isinstance(arg1, sa.Table):
155
+ cols = self.c
156
+ self.c = []
157
+ return sa.Table(arg1.name, self.metadata, *args, *cols, **kwargs)
158
+ else:
159
+ raise TypeError(f"Expected a string or Column, got {type(arg1).__name__}")
File without changes
@@ -0,0 +1,42 @@
1
+ from typing import Optional
2
+
3
+ import pytest
4
+
5
+
6
+ def test_field():
7
+ from typing import Any
8
+
9
+ import sqlalchemy as sa
10
+ from pydantic import BaseModel, Field
11
+
12
+ from sqla_fancy_core import TableFactory
13
+
14
+ tf = TableFactory()
15
+
16
+ def field(col, default: Any = ...) -> Field:
17
+ return col.info["kwargs"]["field"](default)
18
+
19
+ # Define a table
20
+ class User:
21
+ name = tf(
22
+ sa.Column("name", sa.String),
23
+ field=lambda default: Field(default, max_length=5),
24
+ )
25
+ Table = tf("author")
26
+
27
+ # Define a pydantic schema
28
+ class CreateUser(BaseModel):
29
+ name: str = field(User.name)
30
+
31
+ # Define a pydantic schema
32
+ class UpdateUser(BaseModel):
33
+ name: Optional[str] = field(User.name, None)
34
+
35
+ assert CreateUser(name="John").model_dump() == {"name": "John"}
36
+ assert UpdateUser(name="John").model_dump() == {"name": "John"}
37
+ assert UpdateUser().model_dump(exclude_unset=True) == {}
38
+
39
+ with pytest.raises(ValueError):
40
+ CreateUser()
41
+ with pytest.raises(ValueError):
42
+ UpdateUser(name="John Doe")