-
Notifications
You must be signed in to change notification settings - Fork 262
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
Fix sqlalchemy default values for insert and update queries #266
Closed
Closed
Changes from all commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
28adcf5
fix sqlalchemy defaults
ckkz-it 71f4616
add tests for column defaults when inserting
ckkz-it 9e34f53
cover default callable case
ckkz-it bd5af23
fix default column value test for mysql and sqlite
ckkz-it 62c3ab8
refactor default params mixin, add support for aiomysql and aiosqlite
ckkz-it 0272630
fix tests running with asyncpg and aiopg in one run (when sharing sam…
ckkz-it c9fe054
fix linting
ckkz-it f6d053e
Merge branch 'master' into sqlalchemy-defaults
ckkz-it 54246eb
Merge branch 'master' into sqlalchemy-defaults
ckkz-it 0a45b44
Merge branch 'master' into sqlalchemy-defaults
ckkz-it File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,33 @@ | ||
import typing | ||
|
||
from sqlalchemy import ColumnDefault | ||
from sqlalchemy.engine.default import DefaultDialect | ||
|
||
|
||
class ConstructDefaultParamsMixin: | ||
""" | ||
A mixin to support column default values for insert queries for asyncpg, | ||
aiomysql and aiosqlite | ||
""" | ||
|
||
prefetch: typing.List | ||
dialect: DefaultDialect | ||
|
||
def construct_params( | ||
self, | ||
params: typing.Optional[typing.Mapping] = None, | ||
_group_number: typing.Any = None, | ||
_check: bool = True, | ||
) -> typing.Dict: | ||
pd = super().construct_params(params, _group_number, _check) # type: ignore | ||
|
||
for column in self.prefetch: | ||
pd[column.key] = self._exec_default(column.default) | ||
|
||
return pd | ||
|
||
def _exec_default(self, default: ColumnDefault) -> typing.Any: | ||
if default.is_callable: | ||
return default.arg(self.dialect) | ||
else: | ||
return default.arg |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -70,6 +70,20 @@ def process_result_value(self, value, dialect): | |
sqlalchemy.Column("price", sqlalchemy.Numeric(precision=30, scale=20)), | ||
) | ||
|
||
# Used to test column default values | ||
default_values = sqlalchemy.Table( | ||
"default_values", | ||
metadata, | ||
sqlalchemy.Column("id", sqlalchemy.Integer, primary_key=True), | ||
sqlalchemy.Column("with_default", sqlalchemy.Integer, default=42), | ||
sqlalchemy.Column( | ||
"with_callable_default", | ||
sqlalchemy.String(length=100), | ||
default=lambda: "default_value", | ||
), | ||
sqlalchemy.Column("without_default", sqlalchemy.Integer), | ||
) | ||
|
||
|
||
@pytest.fixture(autouse=True, scope="module") | ||
def create_test_database(): | ||
|
@@ -651,6 +665,84 @@ async def test_json_field(database_url): | |
assert results[0]["data"] == {"text": "hello", "boolean": True, "int": 1} | ||
|
||
|
||
@pytest.mark.parametrize("database_url", DATABASE_URLS) | ||
@async_adapter | ||
async def test_insert_with_scalar_default(database_url): | ||
""" | ||
Test insert with scalar column default value | ||
""" | ||
|
||
async with Database(database_url) as database: | ||
async with database.transaction(force_rollback=True): | ||
query = default_values.insert() | ||
values = {"without_default": 1} | ||
await database.execute(query, values) | ||
|
||
query = default_values.select().order_by(default_values.c.id.desc()) | ||
result = await database.fetch_one(query=query) | ||
|
||
assert result["with_default"] == 42 | ||
assert result["without_default"] == values["without_default"] | ||
|
||
|
||
@pytest.mark.parametrize("database_url", DATABASE_URLS) | ||
@async_adapter | ||
async def test_insert_default_values_with_no_values_called(database_url): | ||
""" | ||
Test insert default values without calling ``values()`` on insert and | ||
without passing ``values`` to ``execute()``. | ||
""" | ||
|
||
async with Database(database_url) as database: | ||
async with database.transaction(force_rollback=True): | ||
query = default_values.insert() | ||
await database.execute(query) | ||
|
||
query = default_values.select().order_by(default_values.c.id.desc()) | ||
result = await database.fetch_one(query=query) | ||
|
||
assert result["with_default"] == 42 | ||
assert result["without_default"] is None | ||
|
||
|
||
@pytest.mark.parametrize("database_url", DATABASE_URLS) | ||
@async_adapter | ||
async def test_insert_default_values_with_overriden_default(database_url): | ||
""" | ||
Test if we provide value for a column having default value, the first one | ||
should be set, not default one. | ||
""" | ||
|
||
async with Database(database_url) as database: | ||
async with database.transaction(force_rollback=True): | ||
query = default_values.insert() | ||
values = {"with_default": 5} | ||
await database.execute(query, values) | ||
|
||
query = default_values.select().order_by(default_values.c.id.desc()) | ||
result = await database.fetch_one(query=query) | ||
|
||
assert result["with_default"] == values["with_default"] | ||
|
||
|
||
@pytest.mark.parametrize("database_url", DATABASE_URLS) | ||
@async_adapter | ||
async def test_insert_callable_default(database_url): | ||
""" | ||
Test insert with column having callable default. | ||
""" | ||
|
||
async with Database(database_url) as database: | ||
async with database.transaction(force_rollback=True): | ||
query = default_values.insert() | ||
await database.execute(query) | ||
|
||
query = default_values.select().order_by(default_values.c.id.desc()) | ||
result = await database.fetch_one(query=query) | ||
|
||
assert result["with_callable_default"] == "default_value" | ||
|
||
|
||
@pytest.mark.parametrize("database_url", DATABASE_URLS) | ||
@async_adapter | ||
async def test_custom_field(database_url): | ||
|
@@ -917,6 +1009,7 @@ async def run_database_queries(): | |
async with database: | ||
|
||
async def db_lookup(): | ||
|
||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. left \n |
||
await database.fetch_one("SELECT pg_sleep(1)") | ||
|
||
await asyncio.gather(db_lookup(), db_lookup()) | ||
|
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Seems strange to call this
APGCompiler_psycopg2
, given that the db backend used for postgres in databases isasyncpg
, notpsycopg2
.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
this is how aiopg calls it
https://github.com/encode/databases/blob/master/databases/backends/aiopg.py#L32#L35
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Right but that's because aiopg is just a wrapper around psycopg2, asyncpg is not.