url
stringlengths
53
56
repository_url
stringclasses
1 value
labels_url
stringlengths
67
70
comments_url
stringlengths
62
65
events_url
stringlengths
60
63
html_url
stringlengths
41
46
id
int64
450k
1.69B
node_id
stringlengths
18
32
number
int64
1
2.72k
title
stringlengths
1
209
user
dict
labels
list
state
stringclasses
1 value
locked
bool
2 classes
assignee
null
assignees
sequence
milestone
null
comments
sequence
created_at
unknown
updated_at
unknown
closed_at
unknown
author_association
stringclasses
3 values
active_lock_reason
stringclasses
2 values
body
stringlengths
0
104k
reactions
dict
timeline_url
stringlengths
62
65
performed_via_github_app
null
state_reason
stringclasses
2 values
draft
bool
2 classes
pull_request
dict
https://api.github.com/repos/coleifer/peewee/issues/2619
https://api.github.com/repos/coleifer/peewee
https://api.github.com/repos/coleifer/peewee/issues/2619/labels{/name}
https://api.github.com/repos/coleifer/peewee/issues/2619/comments
https://api.github.com/repos/coleifer/peewee/issues/2619/events
https://github.com/coleifer/peewee/issues/2619
1,381,400,756
I_kwDOAA7yGM5SVoC0
2,619
test_murmur_hash fails on s390x architecture
{ "login": "carlwgeorge", "id": 12187228, "node_id": "MDQ6VXNlcjEyMTg3MjI4", "avatar_url": "https://avatars.githubusercontent.com/u/12187228?v=4", "gravatar_id": "", "url": "https://api.github.com/users/carlwgeorge", "html_url": "https://github.com/carlwgeorge", "followers_url": "https://api.github.com/users/carlwgeorge/followers", "following_url": "https://api.github.com/users/carlwgeorge/following{/other_user}", "gists_url": "https://api.github.com/users/carlwgeorge/gists{/gist_id}", "starred_url": "https://api.github.com/users/carlwgeorge/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/carlwgeorge/subscriptions", "organizations_url": "https://api.github.com/users/carlwgeorge/orgs", "repos_url": "https://api.github.com/users/carlwgeorge/repos", "events_url": "https://api.github.com/users/carlwgeorge/events{/privacy}", "received_events_url": "https://api.github.com/users/carlwgeorge/received_events", "type": "User", "site_admin": false }
[]
closed
false
null
[]
null
[ "What does `platform.machine()` return on that hardware, out of curiosity? I'm sure this is just an endianness thing, so we can just add a conditional to skip the test.", "```\r\n>>> platform.machine()\r\n's390x'\r\n```", "Just FYI I tagged a new release, 3.15.3." ]
"2022-09-21T19:32:25"
"2022-09-22T02:56:57"
"2022-09-21T22:59:02"
CONTRIBUTOR
null
While running the tests on the s390x architecture for a Fedora build, I'm seeing this failure. ``` ====================================================================== FAIL: test_murmur_hash (tests.sqlite.TestMurmurHash.test_murmur_hash) ---------------------------------------------------------------------- Traceback (most recent call last): File "/builddir/build/BUILD/peewee-3.15.2/tests/sqlite.py", line 1576, in test_murmur_hash self.assertHash('testkey', 2871421366) File "/builddir/build/BUILD/peewee-3.15.2/tests/sqlite.py", line 1573, in assertHash self.assertEqual(cursor.fetchone()[0], e) AssertionError: 3876111420 != 2871421366 ---------------------------------------------------------------------- ``` This passes on all the other architectures that Fedora builds for (i686, x86_64, aarch64, ppc64le). I was able to reproduce this error in the following environments: - [Fedora 38](https://koji.fedoraproject.org/koji/taskinfo?taskID=92255140), Python 3.11.0~rc2, sqlite 3.39.3 - [Fedora 37](https://koji.fedoraproject.org/koji/taskinfo?taskID=92254905), Python 3.11.0~rc2, sqlite 3.39.2 - [Fedora 36](https://koji.fedoraproject.org/koji/taskinfo?taskID=92254910), Python 3.10.6, sqlite 3.36.0 - [Fedora 35](https://koji.fedoraproject.org/koji/taskinfo?taskID=92254914), Python 3.10.6, sqlite 3.36.0 - [RHEL 9](https://koji.fedoraproject.org/koji/taskinfo?taskID=92254798), Python 3.9.10, sqlite 3.34.1
{ "url": "https://api.github.com/repos/coleifer/peewee/issues/2619/reactions", "total_count": 0, "+1": 0, "-1": 0, "laugh": 0, "hooray": 0, "confused": 0, "heart": 0, "rocket": 0, "eyes": 0 }
https://api.github.com/repos/coleifer/peewee/issues/2619/timeline
null
completed
null
null
https://api.github.com/repos/coleifer/peewee/issues/2618
https://api.github.com/repos/coleifer/peewee
https://api.github.com/repos/coleifer/peewee/issues/2618/labels{/name}
https://api.github.com/repos/coleifer/peewee/issues/2618/comments
https://api.github.com/repos/coleifer/peewee/issues/2618/events
https://github.com/coleifer/peewee/issues/2618
1,380,459,748
I_kwDOAA7yGM5SSCTk
2,618
Pwiz exporting of postgres materialized view
{ "login": "surfer190", "id": 3285222, "node_id": "MDQ6VXNlcjMyODUyMjI=", "avatar_url": "https://avatars.githubusercontent.com/u/3285222?v=4", "gravatar_id": "", "url": "https://api.github.com/users/surfer190", "html_url": "https://github.com/surfer190", "followers_url": "https://api.github.com/users/surfer190/followers", "following_url": "https://api.github.com/users/surfer190/following{/other_user}", "gists_url": "https://api.github.com/users/surfer190/gists{/gist_id}", "starred_url": "https://api.github.com/users/surfer190/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/surfer190/subscriptions", "organizations_url": "https://api.github.com/users/surfer190/orgs", "repos_url": "https://api.github.com/users/surfer190/repos", "events_url": "https://api.github.com/users/surfer190/events{/privacy}", "received_events_url": "https://api.github.com/users/surfer190/received_events", "type": "User", "site_admin": false }
[]
closed
false
null
[]
null
[ "Do you see your materialized view when running:\r\n\r\n```sql\r\nselect viewname, definition from pg_catalog.pg_views \r\nwhere schemaname = 'public' order by tablename; -- change schema name if differs\r\n```", "Oh wait, nevermind, I see that they're listed separately in `pg_catalog.pg_matviews`.", "For now I'm going to hold off on implementing this, as our standard way of introspecting the columns associated with a table (or non-materialized view) does not seem to work with materialized views. With regular tables or views, we can run something like:\r\n\r\n```sql\r\nselect column_name, is_nullable, data_type, column_default\r\nfrom information_schema.columns\r\nwhere table_name = 'the table or view name'\r\n```\r\n\r\nUnfortunately, it looks like the process for introspecting a materialized view is different, see: https://stackoverflow.com/questions/39179253/postgresql-get-materialized-view-column-metadata\r\n\r\nFor now you'll just want to create these manually.", "If the view you are manually defining does not have a primary key - read about [models without a primary key](https://docs.peewee-orm.com/en/latest/peewee/models.html#models-without-a-primary-key)\r\n\r\neg.\r\n\r\n class MyMaterializedView(BaseModel):\r\n ...\r\n \r\n class Meta:\r\n primary_key = False\r\n" ]
"2022-09-21T07:29:25"
"2022-09-22T18:53:08"
"2022-09-21T14:29:31"
NONE
null
Pwiz exports an existing db into models that can be written to a file. The [documentation mentions that the `-v` flag](https://docs.peewee-orm.com/en/latest/peewee/playhouse.html?highlight=generating%20models#pwiz-a-model-generator) can be used to export views. I tried using `pwiz` with the `-v` flag and a materialized view I have was not exported. In a [previous issue](https://github.com/coleifer/peewee/issues/1052) it was mentioned that peewee does not generate the DDL (data definition language) for the creation of views. So the correct course of action is to manually define the model for the view?
{ "url": "https://api.github.com/repos/coleifer/peewee/issues/2618/reactions", "total_count": 0, "+1": 0, "-1": 0, "laugh": 0, "hooray": 0, "confused": 0, "heart": 0, "rocket": 0, "eyes": 0 }
https://api.github.com/repos/coleifer/peewee/issues/2618/timeline
null
completed
null
null
https://api.github.com/repos/coleifer/peewee/issues/2617
https://api.github.com/repos/coleifer/peewee
https://api.github.com/repos/coleifer/peewee/issues/2617/labels{/name}
https://api.github.com/repos/coleifer/peewee/issues/2617/comments
https://api.github.com/repos/coleifer/peewee/issues/2617/events
https://github.com/coleifer/peewee/issues/2617
1,380,039,487
I_kwDOAA7yGM5SQbs_
2,617
test_insert_behavior fails on Python 3.11
{ "login": "carlwgeorge", "id": 12187228, "node_id": "MDQ6VXNlcjEyMTg3MjI4", "avatar_url": "https://avatars.githubusercontent.com/u/12187228?v=4", "gravatar_id": "", "url": "https://api.github.com/users/carlwgeorge", "html_url": "https://github.com/carlwgeorge", "followers_url": "https://api.github.com/users/carlwgeorge/followers", "following_url": "https://api.github.com/users/carlwgeorge/following{/other_user}", "gists_url": "https://api.github.com/users/carlwgeorge/gists{/gist_id}", "starred_url": "https://api.github.com/users/carlwgeorge/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/carlwgeorge/subscriptions", "organizations_url": "https://api.github.com/users/carlwgeorge/orgs", "repos_url": "https://api.github.com/users/carlwgeorge/repos", "events_url": "https://api.github.com/users/carlwgeorge/events{/privacy}", "received_events_url": "https://api.github.com/users/carlwgeorge/received_events", "type": "User", "site_admin": false }
[]
closed
false
null
[]
null
[ "I wonder if this is a regression in the standard lib sqlite3. Is it possible for you to also try pip installing `pysqlite3` and see if the test passes? Peewee should try to use pysqlite3, you can check by running:\r\n\r\n```\r\nfrom peewee import sqlite3\r\nprint(sqlite3)\r\n```\r\n\r\nThis should hopefully be pysqlite3.", "Trying to install pysqlite3 with pip seems to fail, even though it says success.\r\n\r\n```\r\n(py311) [root@f37-container:~/peewee]# pip install pysqlite3\r\nCollecting pysqlite3\r\n Using cached pysqlite3-0.4.7.tar.gz (40 kB)\r\n Preparing metadata (setup.py) ... done\r\nBuilding wheels for collected packages: pysqlite3\r\n Building wheel for pysqlite3 (setup.py) ... done\r\n WARNING: Legacy build of wheel for 'pysqlite3' created no files.\r\n Command arguments: /root/peewee/py311/bin/python3.11 -u -c '\r\n exec(compile('\"'\"''\"'\"''\"'\"'\r\n # This is <pip-setuptools-caller> -- a caller that pip uses to run setup.py\r\n #\r\n # - It imports setuptools before invoking setup.py, to enable projects that directly\r\n # import from `distutils.core` to work with newer packaging standards.\r\n # - It provides a clear error message when setuptools is not installed.\r\n # - It sets `sys.argv[0]` to the underlying `setup.py`, when invoking `setup.py` so\r\n # setuptools doesn'\"'\"'t think the script is `-c`. This avoids the following warning:\r\n # manifest_maker: standard file '\"'\"'-c'\"'\"' not found\".\r\n # - It generates a shim setup.py, for handling setup.cfg-only projects.\r\n import os, sys, tokenize\r\n \r\n try:\r\n import setuptools\r\n except ImportError as error:\r\n print(\r\n \"ERROR: Can not execute `setup.py` since setuptools is not available in \"\r\n \"the build environment.\",\r\n file=sys.stderr,\r\n )\r\n sys.exit(1)\r\n \r\n __file__ = %r\r\n sys.argv[0] = __file__\r\n \r\n if os.path.exists(__file__):\r\n filename = __file__\r\n with tokenize.open(__file__) as f:\r\n setup_py_code = f.read()\r\n else:\r\n filename = \"<auto-generated setuptools caller>\"\r\n setup_py_code = \"from setuptools import setup; setup()\"\r\n \r\n exec(compile(setup_py_code, filename, \"exec\"))\r\n '\"'\"''\"'\"''\"'\"' % ('\"'\"'/tmp/pip-install-kkm14zbf/pysqlite3_fce9f2061a1141be9cb19473624dd0c8/setup.py'\"'\"',), \"<pip-setuptools-caller>\", \"exec\"))' bdist_wheel -d /tmp/pip-wheel-am9z47vw\r\n Command output: [use --verbose to show]\r\n Running setup.py clean for pysqlite3\r\nFailed to build pysqlite3\r\nInstalling collected packages: pysqlite3\r\n Running setup.py install for pysqlite3 ... done\r\nSuccessfully installed pysqlite3\r\n(py311) [root@f37-container:~/peewee]# pip list\r\nPackage Version\r\n---------- -------\r\nCython 0.29.32\r\npip 22.2.2\r\nsetuptools 65.3.0\r\nwheel 0.37.1\r\n```", "Hmm, I'm not sure what to try besides:\r\n\r\n```\r\ngit clone https://github.com/coleifer/pysqlite3\r\ncd pysqlite3\r\npython setup.py build\r\npython setup.py install\r\n```\r\n\r\nThat at least may give an indication of the issue?", "It doesn't seem pysqlite3 likes Python 3.11.\r\n\r\n```\r\n(py311) [root@f37-container:~/pysqlite3]# python setup.py build\r\nrunning build\r\nrunning build_py\r\ncreating build\r\ncreating build/lib.linux-x86_64-cpython-311\r\ncreating build/lib.linux-x86_64-cpython-311/pysqlite3\r\ncopying pysqlite3/__init__.py -> build/lib.linux-x86_64-cpython-311/pysqlite3\r\ncopying pysqlite3/dbapi2.py -> build/lib.linux-x86_64-cpython-311/pysqlite3\r\nrunning build_ext\r\nBuilds a C extension linking against libsqlite3 library\r\nbuilding 'pysqlite3._sqlite3' extension\r\ncreating build/temp.linux-x86_64-cpython-311\r\ncreating build/temp.linux-x86_64-cpython-311/src\r\ngcc -Wsign-compare -DDYNAMIC_ANNOTATIONS_ENABLED=1 -DNDEBUG -O2 -fexceptions -g -grecord-gcc-switches -pipe -Wall -Werror=format-security -Wp,-D_FORTIFY_SOURCE=2 -Wp,-D_GLIBCXX_ASSERTIONS -fstack-protector-strong -m64 -mtune=generic -fasynchronous-unwind-tables -fstack-clash-protection -fcf-protection -D_GNU_SOURCE -fPIC -fwrapv -O2 -fexceptions -g -grecord-gcc-switches -pipe -Wall -Werror=format-security -Wp,-D_FORTIFY_SOURCE=2 -Wp,-D_GLIBCXX_ASSERTIONS -fstack-protector-strong -m64 -mtune=generic -fasynchronous-unwind-tables -fstack-clash-protection -fcf-protection -D_GNU_SOURCE -fPIC -fwrapv -O2 -fexceptions -g -grecord-gcc-switches -pipe -Wall -Werror=format-security -Wp,-D_FORTIFY_SOURCE=2 -Wp,-D_GLIBCXX_ASSERTIONS -fstack-protector-strong -m64 -mtune=generic -fasynchronous-unwind-tables -fstack-clash-protection -fcf-protection -D_GNU_SOURCE -fPIC -fwrapv -fPIC -DMODULE_NAME=\\\"pysqlite3.dbapi2\\\" -I/usr/include -I/root/peewee/py311/include -I/usr/include/python3.11 -c src/blob.c -o build/temp.linux-x86_64-cpython-311/src/blob.o\r\ngcc -Wsign-compare -DDYNAMIC_ANNOTATIONS_ENABLED=1 -DNDEBUG -O2 -fexceptions -g -grecord-gcc-switches -pipe -Wall -Werror=format-security -Wp,-D_FORTIFY_SOURCE=2 -Wp,-D_GLIBCXX_ASSERTIONS -fstack-protector-strong -m64 -mtune=generic -fasynchronous-unwind-tables -fstack-clash-protection -fcf-protection -D_GNU_SOURCE -fPIC -fwrapv -O2 -fexceptions -g -grecord-gcc-switches -pipe -Wall -Werror=format-security -Wp,-D_FORTIFY_SOURCE=2 -Wp,-D_GLIBCXX_ASSERTIONS -fstack-protector-strong -m64 -mtune=generic -fasynchronous-unwind-tables -fstack-clash-protection -fcf-protection -D_GNU_SOURCE -fPIC -fwrapv -O2 -fexceptions -g -grecord-gcc-switches -pipe -Wall -Werror=format-security -Wp,-D_FORTIFY_SOURCE=2 -Wp,-D_GLIBCXX_ASSERTIONS -fstack-protector-strong -m64 -mtune=generic -fasynchronous-unwind-tables -fstack-clash-protection -fcf-protection -D_GNU_SOURCE -fPIC -fwrapv -fPIC -DMODULE_NAME=\\\"pysqlite3.dbapi2\\\" -I/usr/include -I/root/peewee/py311/include -I/usr/include/python3.11 -c src/cache.c -o build/temp.linux-x86_64-cpython-311/src/cache.o\r\ngcc -Wsign-compare -DDYNAMIC_ANNOTATIONS_ENABLED=1 -DNDEBUG -O2 -fexceptions -g -grecord-gcc-switches -pipe -Wall -Werror=format-security -Wp,-D_FORTIFY_SOURCE=2 -Wp,-D_GLIBCXX_ASSERTIONS -fstack-protector-strong -m64 -mtune=generic -fasynchronous-unwind-tables -fstack-clash-protection -fcf-protection -D_GNU_SOURCE -fPIC -fwrapv -O2 -fexceptions -g -grecord-gcc-switches -pipe -Wall -Werror=format-security -Wp,-D_FORTIFY_SOURCE=2 -Wp,-D_GLIBCXX_ASSERTIONS -fstack-protector-strong -m64 -mtune=generic -fasynchronous-unwind-tables -fstack-clash-protection -fcf-protection -D_GNU_SOURCE -fPIC -fwrapv -O2 -fexceptions -g -grecord-gcc-switches -pipe -Wall -Werror=format-security -Wp,-D_FORTIFY_SOURCE=2 -Wp,-D_GLIBCXX_ASSERTIONS -fstack-protector-strong -m64 -mtune=generic -fasynchronous-unwind-tables -fstack-clash-protection -fcf-protection -D_GNU_SOURCE -fPIC -fwrapv -fPIC -DMODULE_NAME=\\\"pysqlite3.dbapi2\\\" -I/usr/include -I/root/peewee/py311/include -I/usr/include/python3.11 -c src/connection.c -o build/temp.linux-x86_64-cpython-311/src/connection.o\r\nsrc/connection.c: In function ‘_pysqlite_step_callback’:\r\nsrc/connection.c:725:31: warning: implicit declaration of function ‘_PyObject_CallNoArg’; did you mean ‘PyObject_CallNoArgs’? [-Wimplicit-function-declaration]\r\n 725 | *aggregate_instance = _PyObject_CallNoArg(aggregate_class);\r\n | ^~~~~~~~~~~~~~~~~~~\r\n | PyObject_CallNoArgs\r\nsrc/connection.c:725:29: warning: assignment to ‘PyObject *’ {aka ‘struct _object *’} from ‘int’ makes pointer from integer without a cast [-Wint-conversion]\r\n 725 | *aggregate_instance = _PyObject_CallNoArg(aggregate_class);\r\n | ^\r\nsrc/connection.c: In function ‘_progress_handler’:\r\nsrc/connection.c:1175:9: warning: assignment to ‘PyObject *’ {aka ‘struct _object *’} from ‘int’ makes pointer from integer without a cast [-Wint-conversion]\r\n 1175 | ret = _PyObject_CallNoArg((PyObject*)user_arg);\r\n | ^\r\ngcc -Wsign-compare -DDYNAMIC_ANNOTATIONS_ENABLED=1 -DNDEBUG -O2 -fexceptions -g -grecord-gcc-switches -pipe -Wall -Werror=format-security -Wp,-D_FORTIFY_SOURCE=2 -Wp,-D_GLIBCXX_ASSERTIONS -fstack-protector-strong -m64 -mtune=generic -fasynchronous-unwind-tables -fstack-clash-protection -fcf-protection -D_GNU_SOURCE -fPIC -fwrapv -O2 -fexceptions -g -grecord-gcc-switches -pipe -Wall -Werror=format-security -Wp,-D_FORTIFY_SOURCE=2 -Wp,-D_GLIBCXX_ASSERTIONS -fstack-protector-strong -m64 -mtune=generic -fasynchronous-unwind-tables -fstack-clash-protection -fcf-protection -D_GNU_SOURCE -fPIC -fwrapv -O2 -fexceptions -g -grecord-gcc-switches -pipe -Wall -Werror=format-security -Wp,-D_FORTIFY_SOURCE=2 -Wp,-D_GLIBCXX_ASSERTIONS -fstack-protector-strong -m64 -mtune=generic -fasynchronous-unwind-tables -fstack-clash-protection -fcf-protection -D_GNU_SOURCE -fPIC -fwrapv -fPIC -DMODULE_NAME=\\\"pysqlite3.dbapi2\\\" -I/usr/include -I/root/peewee/py311/include -I/usr/include/python3.11 -c src/cursor.c -o build/temp.linux-x86_64-cpython-311/src/cursor.o\r\ngcc -Wsign-compare -DDYNAMIC_ANNOTATIONS_ENABLED=1 -DNDEBUG -O2 -fexceptions -g -grecord-gcc-switches -pipe -Wall -Werror=format-security -Wp,-D_FORTIFY_SOURCE=2 -Wp,-D_GLIBCXX_ASSERTIONS -fstack-protector-strong -m64 -mtune=generic -fasynchronous-unwind-tables -fstack-clash-protection -fcf-protection -D_GNU_SOURCE -fPIC -fwrapv -O2 -fexceptions -g -grecord-gcc-switches -pipe -Wall -Werror=format-security -Wp,-D_FORTIFY_SOURCE=2 -Wp,-D_GLIBCXX_ASSERTIONS -fstack-protector-strong -m64 -mtune=generic -fasynchronous-unwind-tables -fstack-clash-protection -fcf-protection -D_GNU_SOURCE -fPIC -fwrapv -O2 -fexceptions -g -grecord-gcc-switches -pipe -Wall -Werror=format-security -Wp,-D_FORTIFY_SOURCE=2 -Wp,-D_GLIBCXX_ASSERTIONS -fstack-protector-strong -m64 -mtune=generic -fasynchronous-unwind-tables -fstack-clash-protection -fcf-protection -D_GNU_SOURCE -fPIC -fwrapv -fPIC -DMODULE_NAME=\\\"pysqlite3.dbapi2\\\" -I/usr/include -I/root/peewee/py311/include -I/usr/include/python3.11 -c src/microprotocols.c -o build/temp.linux-x86_64-cpython-311/src/microprotocols.o\r\ngcc -Wsign-compare -DDYNAMIC_ANNOTATIONS_ENABLED=1 -DNDEBUG -O2 -fexceptions -g -grecord-gcc-switches -pipe -Wall -Werror=format-security -Wp,-D_FORTIFY_SOURCE=2 -Wp,-D_GLIBCXX_ASSERTIONS -fstack-protector-strong -m64 -mtune=generic -fasynchronous-unwind-tables -fstack-clash-protection -fcf-protection -D_GNU_SOURCE -fPIC -fwrapv -O2 -fexceptions -g -grecord-gcc-switches -pipe -Wall -Werror=format-security -Wp,-D_FORTIFY_SOURCE=2 -Wp,-D_GLIBCXX_ASSERTIONS -fstack-protector-strong -m64 -mtune=generic -fasynchronous-unwind-tables -fstack-clash-protection -fcf-protection -D_GNU_SOURCE -fPIC -fwrapv -O2 -fexceptions -g -grecord-gcc-switches -pipe -Wall -Werror=format-security -Wp,-D_FORTIFY_SOURCE=2 -Wp,-D_GLIBCXX_ASSERTIONS -fstack-protector-strong -m64 -mtune=generic -fasynchronous-unwind-tables -fstack-clash-protection -fcf-protection -D_GNU_SOURCE -fPIC -fwrapv -fPIC -DMODULE_NAME=\\\"pysqlite3.dbapi2\\\" -I/usr/include -I/root/peewee/py311/include -I/usr/include/python3.11 -c src/module.c -o build/temp.linux-x86_64-cpython-311/src/module.o\r\ngcc -Wsign-compare -DDYNAMIC_ANNOTATIONS_ENABLED=1 -DNDEBUG -O2 -fexceptions -g -grecord-gcc-switches -pipe -Wall -Werror=format-security -Wp,-D_FORTIFY_SOURCE=2 -Wp,-D_GLIBCXX_ASSERTIONS -fstack-protector-strong -m64 -mtune=generic -fasynchronous-unwind-tables -fstack-clash-protection -fcf-protection -D_GNU_SOURCE -fPIC -fwrapv -O2 -fexceptions -g -grecord-gcc-switches -pipe -Wall -Werror=format-security -Wp,-D_FORTIFY_SOURCE=2 -Wp,-D_GLIBCXX_ASSERTIONS -fstack-protector-strong -m64 -mtune=generic -fasynchronous-unwind-tables -fstack-clash-protection -fcf-protection -D_GNU_SOURCE -fPIC -fwrapv -O2 -fexceptions -g -grecord-gcc-switches -pipe -Wall -Werror=format-security -Wp,-D_FORTIFY_SOURCE=2 -Wp,-D_GLIBCXX_ASSERTIONS -fstack-protector-strong -m64 -mtune=generic -fasynchronous-unwind-tables -fstack-clash-protection -fcf-protection -D_GNU_SOURCE -fPIC -fwrapv -fPIC -DMODULE_NAME=\\\"pysqlite3.dbapi2\\\" -I/usr/include -I/root/peewee/py311/include -I/usr/include/python3.11 -c src/prepare_protocol.c -o build/temp.linux-x86_64-cpython-311/src/prepare_protocol.o\r\nsrc/prepare_protocol.c: In function ‘pysqlite_prepare_protocol_setup_types’:\r\nsrc/prepare_protocol.c:81:43: error: lvalue required as left operand of assignment\r\n 81 | Py_TYPE(&pysqlite_PrepareProtocolType)= &PyType_Type;\r\n | ^\r\nerror: command '/usr/bin/gcc' failed with exit code 1\r\n```\r\n\r\nThis is with gcc 12.2.1 if that matters.", "Thank you, I'll investigate tomorrow. I only wanted to check because we've found a different regression in the 3.11 sqlite3.", "Thanks, I appreciate it. Let me know if I can try any other scenarios to pin it down. Fedora packages multiple Python runtimes and it's easy to spin up various Fedora versions in containers to try different combinations of things.", "I tried one more combination that might be interesting to you. Using Fedora 36 with Python 3.10.6 and sqlite 3.36.0, I was able to reproduce the same error but with a stack trace this time.\r\n\r\n```\r\n======================================================================\r\nERROR: test_insert_behavior (tests.sqlite.TestSqliteReturningConfig)\r\n----------------------------------------------------------------------\r\nTraceback (most recent call last):\r\n File \"/root/peewee/peewee.py\", line 3221, in execute_sql\r\n cursor.execute(sql, params or ())\r\nsqlite3.OperationalError: database table is locked\r\n\r\nDuring handling of the above exception, another exception occurred:\r\n\r\nTraceback (most recent call last):\r\n File \"/root/peewee/tests/base.py\", line 246, in tearDown\r\n self.database.drop_tables(self.requires, safe=True)\r\n File \"/root/peewee/peewee.py\", line 3417, in drop_tables\r\n model.drop_table(**kwargs)\r\n File \"/root/peewee/peewee.py\", line 6845, in drop_table\r\n cls._schema.drop_all(safe, drop_sequences, **options)\r\n File \"/root/peewee/peewee.py\", line 5949, in drop_all\r\n self.drop_table(safe, **options)\r\n File \"/root/peewee/peewee.py\", line 5818, in drop_table\r\n self.database.execute(self._drop_table(safe=safe, **options))\r\n File \"/root/peewee/peewee.py\", line 3234, in execute\r\n return self.execute_sql(sql, params, commit=commit)\r\n File \"/root/peewee/peewee.py\", line 3218, in execute_sql\r\n with __exception_wrapper__:\r\n File \"/root/peewee/peewee.py\", line 2994, in __exit__\r\n reraise(new_type, new_type(exc_value, *exc_args), traceback)\r\n File \"/root/peewee/peewee.py\", line 191, in reraise\r\n raise value.with_traceback(tb)\r\n File \"/root/peewee/peewee.py\", line 3221, in execute_sql\r\n cursor.execute(sql, params or ())\r\npeewee.OperationalError: database table is locked\r\n\r\n======================================================================\r\nFAIL: test_insert_behavior (tests.sqlite.TestSqliteReturningConfig)\r\n----------------------------------------------------------------------\r\nTraceback (most recent call last):\r\n File \"/root/peewee/tests/sqlite.py\", line 2506, in test_insert_behavior\r\n self.assertEqual(iq.execute(), 2)\r\nAssertionError: 0 != 2\r\n\r\n----------------------------------------------------------------------\r\n```\r\n\r\nIn this environment I was able to pip install pysqlite3, and it caused the tests to pass.", "I think you're right about this being a regression. I spun up a Fedora 36 container with Python 3.10.5, and the tests pass there (without pysqlite3). I think something changed between 3.10.5 and 3.10.6 that is also in 3.11.0rc2.", "cc @erlend-aasland if you see this", "> cc @erlend-aasland if you see this\n\nThanks for the heads-up; highly appreciated. I'll take a look as soon as I am back at my laptop.", "I'll try to get a minimal reproduction -- it looks at first glance like an issue with the `cursor.rowcount`. Compiling python 3.11 now and will update here once I've figured out how to reproduce this w/stdlib sqlite3 (if indeed that's the culprit).", "Well it's very strange and I'm not at all sure now that it's a regression. It looks to do in part with cached statements and the use of `returning`. In all likelihood it may be that the behavior of Python 3.11 is correct, but I'll leave that to you to determine @erlend-aasland.\r\n\r\nHere is what the test is doing:\r\n\r\n```python\r\nimport sqlite3\r\n\r\nconn = sqlite3.connect(':memory:')\r\nconn.execute('create table \"t1\" (\"id\" integer not null primary key, '\r\n '\"col\" text not null)')\r\n \r\ncurs = conn.execute('insert into \"t1\" (\"col\") values (?), (?) returning \"id\"',\r\n ('u1', 'u2'))\r\ncurs.fetchall() # Here we consume the cursor during the test.\r\n\r\n# Same query as above.\r\ncurs = conn.execute('insert into \"t1\" (\"col\") values (?), (?) returning \"id\"',\r\n ('u3', 'u4'))\r\nassert curs.rowcount == 2\r\n```\r\n\r\nThe thing that threw me off trying to replicate, however, is that during that first insert query, the returned rowcount is actually 0 on Python < 3.11:\r\n\r\n```python\r\n# For example, on python 3.7, the following raises no assertion errors:\r\n# ... create table, same as above ...\r\ncurs = conn.execute('insert into \"t1\" (\"col\") values (?), (?) returning \"id\"',\r\n ('u1', 'u2'))\r\nassert curs.rowcount == 0 # Here the rowcount is 0 (!!)\r\ncurs.fetchall() # Here we consume the cursor during the test.\r\nassert curs.rowcount == 0 # Here the rowcount is STILL 0\r\n\r\n# Same query as above.\r\ncurs = conn.execute('insert into \"t1\" (\"col\") values (?), (?) returning \"id\"',\r\n ('u3', 'u4'))\r\nassert curs.rowcount == 2 # Here the rowcount is 2\r\n```\r\n\r\nOn, e.g. Python 3.7 -- if we do *not* consume the cursor in between the executions, then the second insert's rowcount is also 0:\r\n\r\n```python\r\n# For example, on python 3.7, the following raises no assertion errors:\r\n# ... create table, same as above ...\r\ncurs = conn.execute('insert into \"t1\" (\"col\") values (?), (?) returning \"id\"',\r\n ('u1', 'u2'))\r\nassert curs.rowcount == 0 # Here the rowcount is 0 (!!)\r\n\r\n# Same query as above.\r\ncurs = conn.execute('insert into \"t1\" (\"col\") values (?), (?) returning \"id\"',\r\n ('u3', 'u4'))\r\nassert curs.rowcount == 0 # Here the rowcount is also 0\r\n```\r\n\r\nOn Python 3.11, though, the rowcount is always `0`:\r\n\r\n```python\r\n# On python 3.11, the following raises no assertion errors:\r\n# ... create table, same as above ...\r\ncurs = conn.execute('insert into \"t1\" (\"col\") values (?), (?) returning \"id\"',\r\n ('u1', 'u2'))\r\nassert curs.rowcount == 0 # Here the rowcount is 0\r\ncurs.fetchall() # Here we consume the cursor during the test.\r\n\r\n# Same query as above.\r\ncurs = conn.execute('insert into \"t1\" (\"col\") values (?), (?) returning \"id\"',\r\n ('u3', 'u4'))\r\nassert curs.rowcount == 0 # Here the rowcount is also 0\r\n```\r\n\r\n----------------------------------------------------------------\r\n\r\nIt seems like my test unintentionally revealed some inconsistency in the way the rowcount is being handled, and possibly there is some interplay in the way the statement cache works, because of the way it manifests differently during the second execution.", "@carlwgeorge - I've put in a very minimal skip directive to get your build passing for now: 49a64bd23591cd96f8ba832646ccac3256481325\r\n\r\nI also have pysqlite3 fixed-up and working on `master`, thanks for sharing those tracebacks with me.\r\n\r\n**Update:** I've removed the faulty assertions in light of sqlite3's behavior checked directly in my comment below - commit 73335396e0336332832e52d4d7272b7d1ed9e794", "Looks like this has to do with how Sqlite itself handles `sqlite3_changes()` interface when the insert query has a RETURNING clause:\r\n\r\n```c\r\n#include <stdio.h>\r\n#include <sqlite3.h>\r\n\r\nint main(int argc, char *argv[]) {\r\n sqlite3 *db;\r\n sqlite3_stmt *stmt;\r\n\r\n sqlite3_open(\":memory:\", &db);\r\n sqlite3_exec(db, \"create table t1 (id integer not null primary key, col text not null);\", NULL, NULL, NULL);\r\n sqlite3_prepare_v2(db, \"insert into t1 (col) values (?), (?) returning id\", -1, &stmt, NULL);\r\n sqlite3_bind_text(stmt, 1, \"u1\", -1, NULL);\r\n sqlite3_bind_text(stmt, 2, \"u2\", -1, NULL);\r\n int rc = sqlite3_step(stmt);\r\n printf(\"changes: %d\\n\", sqlite3_changes(db));\r\n if (rc != SQLITE_DONE) {\r\n do {\r\n printf(\"%d\\n\", sqlite3_column_int(stmt, 0));\r\n rc = sqlite3_step(stmt);\r\n } while (rc != SQLITE_DONE);\r\n }\r\n printf(\"changes: %d\\n\", sqlite3_changes(db));\r\n}\r\n```\r\n\r\nOutput is:\r\n\r\n```\r\nchanges: 0\r\n1\r\n2\r\nchanges: 2\r\n```", "I'm going to close this as it seems that, if anything, Python 3.11 has it correct and the test was only passing due to a side-effect (as far as I can tell) of the statement cache. The faulty assertions are removed from our tests.", "Thank you so much for the quick investigation and resolution for this. I've added 73335396e0336332832e52d4d7272b7d1ed9e794 as a patch to the Fedora package update I'm working on.", "Sorry for not getting back to you, Charles! (I've spent most of the last two weeks on the road, with very fragmented online precence.)\r\n\r\nYeah, the INSERT/UPDATE ... RETURNING thing! We had an issue about that in CPython some months ago. Fixed in `main` (and possibly also backported to 3.11 and 3.10).", "FWIW, here's what I used to debug the related issues:\r\n\r\n- https://gist.github.com/erlend-aasland/98b41dab6cc51c1082c70eef3659d8d1\r\n- https://gist.github.com/erlend-aasland/5e48b920d882e04f911fe7871fd5ccd9\r\n\r\nI don't like the sqlite3_changes() API... :)", "Hope you had a nice adventure, thanks for the links on the debug scripts. I came to the same conclusion as you, which was that we can't determine the modified rowcount until everything returned by `RETURNING` has been stepped-through." ]
"2022-09-20T21:55:03"
"2022-10-03T13:14:13"
"2022-09-21T14:32:26"
CONTRIBUTOR
null
While running the tests with Python 3.11.0rc2, I'm seeing this failure. ``` FAIL: test_insert_behavior (tests.sqlite.TestSqliteReturningConfig.test_insert_behavior) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/carl/development/peewee/tests/sqlite.py", line 2506, in test_insert_behavior self.assertEqual(iq.execute(), 2) AssertionError: 0 != 2 ``` Steps to reproduce on Fedora 36 or 37: ``` dnf -y install gcc git-core sqlite-devel python3.11-devel git clone https://github.com/coleifer/peewee.git cd peewee python3.11 -m venv py311 . py311/bin/activate pip install cython python setup.py install python setup.py build_ext -i python runtests.py ``` EDIT: Forgot to include the exact versions involved. Let me know if others are needed. F36: python3.11-3.11.0~rc2-1.fc36 sqlite-3.36.0-5.fc36 F37: python3-3.11.0~rc2-1.fc37 sqlite-3.39.2-2.fc37
{ "url": "https://api.github.com/repos/coleifer/peewee/issues/2617/reactions", "total_count": 0, "+1": 0, "-1": 0, "laugh": 0, "hooray": 0, "confused": 0, "heart": 0, "rocket": 0, "eyes": 0 }
https://api.github.com/repos/coleifer/peewee/issues/2617/timeline
null
completed
null
null
https://api.github.com/repos/coleifer/peewee/issues/2616
https://api.github.com/repos/coleifer/peewee
https://api.github.com/repos/coleifer/peewee/issues/2616/labels{/name}
https://api.github.com/repos/coleifer/peewee/issues/2616/comments
https://api.github.com/repos/coleifer/peewee/issues/2616/events
https://github.com/coleifer/peewee/issues/2616
1,376,901,892
I_kwDOAA7yGM5SEdsE
2,616
Add operator overloading for joins
{ "login": "valq7711", "id": 11394363, "node_id": "MDQ6VXNlcjExMzk0MzYz", "avatar_url": "https://avatars.githubusercontent.com/u/11394363?v=4", "gravatar_id": "", "url": "https://api.github.com/users/valq7711", "html_url": "https://github.com/valq7711", "followers_url": "https://api.github.com/users/valq7711/followers", "following_url": "https://api.github.com/users/valq7711/following{/other_user}", "gists_url": "https://api.github.com/users/valq7711/gists{/gist_id}", "starred_url": "https://api.github.com/users/valq7711/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/valq7711/subscriptions", "organizations_url": "https://api.github.com/users/valq7711/orgs", "repos_url": "https://api.github.com/users/valq7711/repos", "events_url": "https://api.github.com/users/valq7711/events{/privacy}", "received_events_url": "https://api.github.com/users/valq7711/received_events", "type": "User", "site_admin": false }
[]
closed
false
null
[]
null
[ "Sorry, that's not going to work, as we overload those already for the creation of expressions. This would require treating expression objects differently in the context of the `.join()` method. The way you've got `.on()` and the absence of parentheses presents even more difficulties.", "Sorry, but I don't see the problem. \r\n`User.t` - `t` - is not the field, but magic model self-reference, so it doesn't overlap with field-expressions\r\n\r\nHere is dirty but working example to demonstrate the concept:\r\n```python\r\nimport os\r\nfrom peewee import *\r\nimport datetime\r\n\r\nfp = os.path.join(os.path.dirname(__file__), 'my_database.db')\r\n\r\n\r\ndb = SqliteDatabase(fp)\r\n\r\n\r\nclass ModelRef:\r\n def __init__(self, cls):\r\n self._cls = cls\r\n self._right = None\r\n self._join_type = None\r\n self._on = None\r\n\r\n def __and__(self, model_to_join):\r\n self._join_type = JOIN.INNER\r\n self._right = model_to_join\r\n return self\r\n\r\n def on(self, expression):\r\n self._on = expression\r\n return self\r\n\r\n def __call__(self):\r\n return (\r\n self._right._cls,\r\n self._join_type,\r\n self._right._on,\r\n )\r\n\r\n\r\nclass BaseModel(Model):\r\n\r\n # should be @classproperty\r\n @classmethod\r\n def t(cls):\r\n return ModelRef(cls)\r\n\r\n class Meta:\r\n database = db\r\n\r\n\r\nclass User(BaseModel):\r\n username = CharField(unique=True)\r\n\r\n\r\nclass Tweet(BaseModel):\r\n user = ForeignKeyField(User, backref='tweets')\r\n message = TextField()\r\n created_date = DateTimeField(default=datetime.datetime.now)\r\n is_published = BooleanField(default=True)\r\n\r\n\r\nquery = (\r\n User\r\n .select(User, Tweet)\r\n .join(*(\r\n User.t()\r\n & Tweet.t().on(Tweet.user == User.id)\r\n )())\r\n)\r\n\r\nprint(query)\r\n\r\n```", "@coleifer so it only requires proper `ModelRef` implementation and `isinstance(dest, ModelRef)`-logic in `ModelSelect.join`-method" ]
"2022-09-18T00:10:17"
"2022-09-19T17:33:53"
"2022-09-18T13:34:16"
NONE
null
@coleifer Hi! Thank you for great project! So I have an idea: ```python query = (Foo .select(...) .join( Foo.t & Bar.t.on(...) # INNER JOIN + Baz.t.on(), # LEFT JOIN # switch to Foo-context (notice comma above) Foo.t & Whatever.t.on(...) ... ) .where(...)) ```
{ "url": "https://api.github.com/repos/coleifer/peewee/issues/2616/reactions", "total_count": 0, "+1": 0, "-1": 0, "laugh": 0, "hooray": 0, "confused": 0, "heart": 0, "rocket": 0, "eyes": 0 }
https://api.github.com/repos/coleifer/peewee/issues/2616/timeline
null
completed
null
null
https://api.github.com/repos/coleifer/peewee/issues/2615
https://api.github.com/repos/coleifer/peewee
https://api.github.com/repos/coleifer/peewee/issues/2615/labels{/name}
https://api.github.com/repos/coleifer/peewee/issues/2615/comments
https://api.github.com/repos/coleifer/peewee/issues/2615/events
https://github.com/coleifer/peewee/issues/2615
1,360,858,256
I_kwDOAA7yGM5RHQyQ
2,615
Expression syntax should properly handle chained expressions like `a <= expr <= b`
{ "login": "jonashaag", "id": 175722, "node_id": "MDQ6VXNlcjE3NTcyMg==", "avatar_url": "https://avatars.githubusercontent.com/u/175722?v=4", "gravatar_id": "", "url": "https://api.github.com/users/jonashaag", "html_url": "https://github.com/jonashaag", "followers_url": "https://api.github.com/users/jonashaag/followers", "following_url": "https://api.github.com/users/jonashaag/following{/other_user}", "gists_url": "https://api.github.com/users/jonashaag/gists{/gist_id}", "starred_url": "https://api.github.com/users/jonashaag/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/jonashaag/subscriptions", "organizations_url": "https://api.github.com/users/jonashaag/orgs", "repos_url": "https://api.github.com/users/jonashaag/repos", "events_url": "https://api.github.com/users/jonashaag/events{/privacy}", "received_events_url": "https://api.github.com/users/jonashaag/received_events", "type": "User", "site_admin": false }
[]
closed
false
null
[]
null
[ "I don't know that we're able to do this, actually:\r\n\r\n```python\r\nIn [1]: class Expr(object):\r\n ...: def __init__(self, lhs, op, rhs):\r\n ...: self.lhs, self.op, self.rhs = lhs, op, rhs\r\n ...: def __str__(self):\r\n ...: return '%s %s %s' % (self.lhs, self.op, self.rhs)\r\n ...: def __le__(self, other):\r\n ...: return Expr(self, '<=', other)\r\n ...: def __ge__(self, other):\r\n ...: return Expr(self, '>=', other)\r\n ...: \r\n\r\nIn [2]: e = Expr(None, None, None)\r\n\r\nIn [3]: print(2 <= e <= 5)\r\nNone None None <= 5\r\n```\r\n\r\nSee how the first comparison (2 <= e) is lost?\r\n\r\nThe best you can get is to use parentheses, but the semantics change and will not be correct:\r\n\r\n```python\r\nIn [5]: print((2 <= e) <= 5)\r\nNone None None >= 2 <= 5\r\n```\r\n\r\nAnyways, you should probably be using `.between()` anyways, as some databases are able to optimize this:\r\n\r\n```python\r\nM.select(M.id).where(M.id.between(2, 3))\r\n```\r\n", "Indeed, this is impossible to implement in Python. I'm surprised.\r\n\r\n```\r\n>>> dis.disassemble((lambda: x <= y < z).__code__)\r\n 1 0 LOAD_GLOBAL 0 (x)\r\n 2 LOAD_GLOBAL 1 (y)\r\n 4 DUP_TOP\r\n 6 ROT_THREE\r\n 8 COMPARE_OP 1 (<=)\r\n 10 JUMP_IF_FALSE_OR_POP 9 (to 18)\r\n 12 LOAD_GLOBAL 2 (z)\r\n 14 COMPARE_OP 0 (<)\r\n 16 RETURN_VALUE\r\n >> 18 ROT_TWO\r\n 20 POP_TOP\r\n 22 RETURN_VALUE\r\n```\r\n\r\nThe result of one of the comparisons will always be ignored (8 -> 10 -> 18 => second comparison never executed; or 8 -> 10 -> 12 => result of first comparison is dropped).", "Thank you for your comment Jonas, very nice debugging and a better explanation than the one I provided." ]
"2022-09-03T13:29:53"
"2022-09-04T16:24:57"
"2022-09-04T15:18:59"
CONTRIBUTOR
null
IMO Peewee should support chained expressions like `a <= expr <= b` or raise an error. ```py # M = my model. # As expected, there are 3 objects with id <= 3. In [33]: list(M.select(M.id).where(M.id <= 3).tuples()) Out[33]: [(1,), (2,), (3,)] # Unexpected: Ignores the first constraint. In [34]: list(M.select(M.id).where(2 <= M.id <= 3).tuples()) Out[34]: [(1,), (2,), (3,)] ```
{ "url": "https://api.github.com/repos/coleifer/peewee/issues/2615/reactions", "total_count": 0, "+1": 0, "-1": 0, "laugh": 0, "hooray": 0, "confused": 0, "heart": 0, "rocket": 0, "eyes": 0 }
https://api.github.com/repos/coleifer/peewee/issues/2615/timeline
null
completed
null
null
https://api.github.com/repos/coleifer/peewee/issues/2614
https://api.github.com/repos/coleifer/peewee
https://api.github.com/repos/coleifer/peewee/issues/2614/labels{/name}
https://api.github.com/repos/coleifer/peewee/issues/2614/comments
https://api.github.com/repos/coleifer/peewee/issues/2614/events
https://github.com/coleifer/peewee/issues/2614
1,360,532,538
I_kwDOAA7yGM5RGBQ6
2,614
Add Example for Idiomatic Message Queue Pattern
{ "login": "zackees", "id": 6856673, "node_id": "MDQ6VXNlcjY4NTY2NzM=", "avatar_url": "https://avatars.githubusercontent.com/u/6856673?v=4", "gravatar_id": "", "url": "https://api.github.com/users/zackees", "html_url": "https://github.com/zackees", "followers_url": "https://api.github.com/users/zackees/followers", "following_url": "https://api.github.com/users/zackees/following{/other_user}", "gists_url": "https://api.github.com/users/zackees/gists{/gist_id}", "starred_url": "https://api.github.com/users/zackees/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/zackees/subscriptions", "organizations_url": "https://api.github.com/users/zackees/orgs", "repos_url": "https://api.github.com/users/zackees/repos", "events_url": "https://api.github.com/users/zackees/events{/privacy}", "received_events_url": "https://api.github.com/users/zackees/received_events", "type": "User", "site_admin": false }
[]
closed
false
null
[]
null
[ "I'm not going to do your homework for you, but there is a ton of discussion on this on the web. Some of it depends on what database you use, postgres probably being the most commonly discussed.\r\n\r\n* https://github.com/que-rb/que - https://github.com/que-rb/que/blob/master/lib/que/poller.rb#L60-L113\r\n* https://github.com/QueueClassic/queue_classic - https://github.com/QueueClassic/queue_classic/blob/master/lib/queue_classic/queue.rb#L92-L111", "If you're looking for something simpler, you can always refer to this, which is Peewee-specific:\r\n\r\nhttps://github.com/coleifer/huey/blob/master/huey/contrib/sql_huey.py", "> I'm not going to do your homework for you, but there is a ton of discussion on this on the web.\r\n\r\nDude, I've been a software developer for nearly 20 years in embedded land. It's possible one can be a novice to databases and also not a student, at the same time." ]
"2022-09-02T19:17:55"
"2022-09-02T22:04:49"
"2022-09-02T19:40:25"
NONE
null
Hi there. Great piece of software. I'm a novice at databases which has brought me to this solution. I'm looking for examples on the internet for how to use Peewee to implement a Message Queue. The challenges here is that the message queue is highly sensitive to locking multiple entries in the queue so that they can be processed. As the items are processed their entries to have status updates so that in the case of a power failure, the system has enough information to pick up where it left off. It looks like the `atomic` functionality will do what I need it to. But as a novice I lack the knowledge on whether my solution will be proper enough. Or whether there is some hidden, large grain implicit table lock that won't show a problem until the point of launch when the database starts getting hot. I believe it would really help PeeWee's adoption if a simple, performant Message Queue implementation was added to the examples. This would allow dumb people like me to build off an idiomatic implementation and incrementally add features until it's satisfies the requirements. Thanks again!
{ "url": "https://api.github.com/repos/coleifer/peewee/issues/2614/reactions", "total_count": 0, "+1": 0, "-1": 0, "laugh": 0, "hooray": 0, "confused": 0, "heart": 0, "rocket": 0, "eyes": 0 }
https://api.github.com/repos/coleifer/peewee/issues/2614/timeline
null
completed
null
null
https://api.github.com/repos/coleifer/peewee/issues/2613
https://api.github.com/repos/coleifer/peewee
https://api.github.com/repos/coleifer/peewee/issues/2613/labels{/name}
https://api.github.com/repos/coleifer/peewee/issues/2613/comments
https://api.github.com/repos/coleifer/peewee/issues/2613/events
https://github.com/coleifer/peewee/issues/2613
1,352,445,776
I_kwDOAA7yGM5QnK9Q
2,613
AttributeError when calling len of model
{ "login": "ghost", "id": 10137, "node_id": "MDQ6VXNlcjEwMTM3", "avatar_url": "https://avatars.githubusercontent.com/u/10137?v=4", "gravatar_id": "", "url": "https://api.github.com/users/ghost", "html_url": "https://github.com/ghost", "followers_url": "https://api.github.com/users/ghost/followers", "following_url": "https://api.github.com/users/ghost/following{/other_user}", "gists_url": "https://api.github.com/users/ghost/gists{/gist_id}", "starred_url": "https://api.github.com/users/ghost/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/ghost/subscriptions", "organizations_url": "https://api.github.com/users/ghost/orgs", "repos_url": "https://api.github.com/users/ghost/repos", "events_url": "https://api.github.com/users/ghost/events{/privacy}", "received_events_url": "https://api.github.com/users/ghost/received_events", "type": "User", "site_admin": false }
[]
closed
false
null
[]
null
[ "This looks like some issue with your debugger / pycharm. The `__len__()` / `count` behavior is covered by unit tests. `peewee.fn` is an instance of `Function` and implements some magic -- possibly your debugger is shadowing the `fn` name. Not sure.", "I think that must be something to do with it. I tried renaming global 'fn' to 'fn_p' in peewee.py and it succeeded, so it does seem to being overwritten. I've tried tracing this through a bit and it seems that during the initialisation of the `SqliteExtDatabase` the registering of the cython rank functions results in the global fn being overwritten. I cannot understand how this would be happening. " ]
"2022-08-26T15:52:45"
"2022-08-26T17:56:00"
"2022-08-26T15:56:58"
NONE
null
I'm getting an AttributeError when I call len on my Model class. Weirdly this occurs when I run a test in the pycharm debugger but not when I run the same test outside the debugger. Python Version 3.10.4 Peewee Version 3.15.1 ``` ../../src/stores/fs.py:79: in rows return len(self.model) ../../venv/lib/python3.10/site-packages/peewee.py:6366: in __len__ return self.select().count() ../../venv/lib/python3.10/site-packages/peewee.py:1931: in inner return method(self, database, *args, **kwargs) _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <peewee.ModelSelect object at 0x1112fdf30> database = <playhouse.apsw_ext.APSWDatabase object at 0x10f42bb50> clear_limit = False @database_required def count(self, database, clear_limit=False): clone = self.order_by().alias('_wrapped') if clear_limit: clone._limit = clone._offset = None try: if clone._having is None and clone._group_by is None and \ clone._windows is None and clone._distinct is None and \ clone._simple_distinct is not True: clone = clone.select(SQL('1')) except AttributeError: print("AttributeError") pass print(f"2211 peewee - {fn.__name__}") print(dir(fn)) > return Select([clone], [fn.COUNT(SQL('1'))]).scalar(database) E AttributeError: 'builtin_function_or_method' object has no attribute 'COUNT' ../../venv/lib/python3.10/site-packages/peewee.py:2214: AttributeError ``` Instead of calling `len(model)` I am successfully able to run `len(model.select())` but `model.select().count()` raises the AttributeError. Not sure if this is helpful, but I tried putting a print message in the ModelSelect.count() function ``` print(f"2211 peewee - {fn.__name__}") return Select([clone], [fn.COUNT(SQL('1'))]).scalar(database) ``` Which in failing debug mode outputs ``` 2211 peewee - peewee_rank ``` Otherwise this outputs ``` 2211 peewee - <function Function.__getattr__.<locals>.decorator at 0x1120352d0> ``` I can provide more info if needed.
{ "url": "https://api.github.com/repos/coleifer/peewee/issues/2613/reactions", "total_count": 0, "+1": 0, "-1": 0, "laugh": 0, "hooray": 0, "confused": 0, "heart": 0, "rocket": 0, "eyes": 0 }
https://api.github.com/repos/coleifer/peewee/issues/2613/timeline
null
completed
null
null
https://api.github.com/repos/coleifer/peewee/issues/2612
https://api.github.com/repos/coleifer/peewee
https://api.github.com/repos/coleifer/peewee/issues/2612/labels{/name}
https://api.github.com/repos/coleifer/peewee/issues/2612/comments
https://api.github.com/repos/coleifer/peewee/issues/2612/events
https://github.com/coleifer/peewee/issues/2612
1,352,421,939
I_kwDOAA7yGM5QnFIz
2,612
Pylint complains that subclasses of `ColumnBase` leave `__iter__()` unimplemented
{ "login": "jborman-exos", "id": 94395044, "node_id": "U_kgDOBaBapA", "avatar_url": "https://avatars.githubusercontent.com/u/94395044?v=4", "gravatar_id": "", "url": "https://api.github.com/users/jborman-exos", "html_url": "https://github.com/jborman-exos", "followers_url": "https://api.github.com/users/jborman-exos/followers", "following_url": "https://api.github.com/users/jborman-exos/following{/other_user}", "gists_url": "https://api.github.com/users/jborman-exos/gists{/gist_id}", "starred_url": "https://api.github.com/users/jborman-exos/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/jborman-exos/subscriptions", "organizations_url": "https://api.github.com/users/jborman-exos/orgs", "repos_url": "https://api.github.com/users/jborman-exos/repos", "events_url": "https://api.github.com/users/jborman-exos/events{/privacy}", "received_events_url": "https://api.github.com/users/jborman-exos/received_events", "type": "User", "site_admin": false }
[]
closed
false
null
[]
null
[ "No problem, fixed." ]
"2022-08-26T15:29:49"
"2022-08-26T15:51:10"
"2022-08-26T15:51:10"
NONE
null
Related to the fix released for #2606, running pylint over a local subclass of `ColumnBase` raises the following: ``` Method '__iter__' is abstract in class 'ColumnBase' but is not overridden (abstract-method) ``` Raising `NotimplementedError` implies that a concrete class is meant to implement this abstract method. According to the python [docs](https://docs.python.org/3/library/exceptions.html#NotImplementedError), if `__iter__` is never to be implemented on a subclass of `ColumnBase`, then it should be set to `None`
{ "url": "https://api.github.com/repos/coleifer/peewee/issues/2612/reactions", "total_count": 0, "+1": 0, "-1": 0, "laugh": 0, "hooray": 0, "confused": 0, "heart": 0, "rocket": 0, "eyes": 0 }
https://api.github.com/repos/coleifer/peewee/issues/2612/timeline
null
completed
null
null
https://api.github.com/repos/coleifer/peewee/issues/2611
https://api.github.com/repos/coleifer/peewee
https://api.github.com/repos/coleifer/peewee/issues/2611/labels{/name}
https://api.github.com/repos/coleifer/peewee/issues/2611/comments
https://api.github.com/repos/coleifer/peewee/issues/2611/events
https://github.com/coleifer/peewee/pull/2611
1,352,331,434
PR_kwDOAA7yGM493uqO
2,611
Add `SelectBase.scalars()`
{ "login": "ilyakamens", "id": 3293811, "node_id": "MDQ6VXNlcjMyOTM4MTE=", "avatar_url": "https://avatars.githubusercontent.com/u/3293811?v=4", "gravatar_id": "", "url": "https://api.github.com/users/ilyakamens", "html_url": "https://github.com/ilyakamens", "followers_url": "https://api.github.com/users/ilyakamens/followers", "following_url": "https://api.github.com/users/ilyakamens/following{/other_user}", "gists_url": "https://api.github.com/users/ilyakamens/gists{/gist_id}", "starred_url": "https://api.github.com/users/ilyakamens/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/ilyakamens/subscriptions", "organizations_url": "https://api.github.com/users/ilyakamens/orgs", "repos_url": "https://api.github.com/users/ilyakamens/repos", "events_url": "https://api.github.com/users/ilyakamens/events{/privacy}", "received_events_url": "https://api.github.com/users/ilyakamens/received_events", "type": "User", "site_admin": false }
[]
closed
false
null
[]
null
[ "There are a few issues with your patch - it consumes the entire cursor in one go and returns a list, when it would probably be better suited to use a generator. Similarly, it is not carrying through the `database` parameter. I will implement a similar patch and merge it.", "Thank you!" ]
"2022-08-26T14:17:06"
"2022-11-20T16:09:05"
"2022-08-26T14:31:51"
CONTRIBUTOR
null
Mr. Leifer, thanks for creating and maintaining such a great library. We've used peewee at Propel since 2015. This PR adds `SelectBase.scalars()`, which is something we've wanted for a while. `scalar()` is very convenient, and we thought something similar for multiple values would be too. I've proposed `scalars()` as the name, but would be happy to settle on something else if you prefer. Thanks for considering.
{ "url": "https://api.github.com/repos/coleifer/peewee/issues/2611/reactions", "total_count": 0, "+1": 0, "-1": 0, "laugh": 0, "hooray": 0, "confused": 0, "heart": 0, "rocket": 0, "eyes": 0 }
https://api.github.com/repos/coleifer/peewee/issues/2611/timeline
null
null
false
{ "url": "https://api.github.com/repos/coleifer/peewee/pulls/2611", "html_url": "https://github.com/coleifer/peewee/pull/2611", "diff_url": "https://github.com/coleifer/peewee/pull/2611.diff", "patch_url": "https://github.com/coleifer/peewee/pull/2611.patch", "merged_at": null }
https://api.github.com/repos/coleifer/peewee/issues/2610
https://api.github.com/repos/coleifer/peewee
https://api.github.com/repos/coleifer/peewee/issues/2610/labels{/name}
https://api.github.com/repos/coleifer/peewee/issues/2610/comments
https://api.github.com/repos/coleifer/peewee/issues/2610/events
https://github.com/coleifer/peewee/issues/2610
1,351,681,427
I_kwDOAA7yGM5QkQWT
2,610
Operator does not exist: json = json?
{ "login": "andycasey", "id": 504436, "node_id": "MDQ6VXNlcjUwNDQzNg==", "avatar_url": "https://avatars.githubusercontent.com/u/504436?v=4", "gravatar_id": "", "url": "https://api.github.com/users/andycasey", "html_url": "https://github.com/andycasey", "followers_url": "https://api.github.com/users/andycasey/followers", "following_url": "https://api.github.com/users/andycasey/following{/other_user}", "gists_url": "https://api.github.com/users/andycasey/gists{/gist_id}", "starred_url": "https://api.github.com/users/andycasey/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/andycasey/subscriptions", "organizations_url": "https://api.github.com/users/andycasey/orgs", "repos_url": "https://api.github.com/users/andycasey/repos", "events_url": "https://api.github.com/users/andycasey/events{/privacy}", "received_events_url": "https://api.github.com/users/andycasey/received_events", "type": "User", "site_admin": false }
[]
closed
false
null
[]
null
[ "Sorry, I just found #2504. Closing." ]
"2022-08-26T02:59:56"
"2022-08-26T03:06:52"
"2022-08-26T03:06:52"
NONE
null
👋🏻 thanks for peewee, it's awesome. I'm having troubles with `playhouse.postgres_ext.JSONField`. The minimum reproducible code is: ```python from playhouse.postgres_ext import * database = PostgresqlExtDatabase(...) class DataProduct(Model): class Meta: database = database id = AutoField() release = TextField() filetype = TextField() kwargs = JSONField() DataProduct.create_table() dp, created = DataProduct.get_or_create( release="new", filetype="some", kwargs={"version": 3.14} ) ``` This raises the following exception: ``` .../peewee.py in execute_sql(self, sql, params, commit) 3142 cursor = self.cursor(commit) 3143 try: -> 3144 cursor.execute(sql, params or ()) 3145 except Exception: 3146 if self.autorollback and not self.in_transaction(): ProgrammingError: operator does not exist: json = json LINE 1: ...ND ("t1"."filetype" = 'some')) AND ("t1"."kwargs" = CAST('{"... ^ HINT: No operator matches the given name and argument types. You might need to add explicit type casts. ``` I have the following relevant versions: - `peewee`: 3.14.4 - `psycopg2`: 2.9.1 - PostgreSQL: 12.2 What am I doing wrong here? Edit: the equivalent code works fine when I am using `playhouse.sqlite_ext.SqliteExtDatabase`.
{ "url": "https://api.github.com/repos/coleifer/peewee/issues/2610/reactions", "total_count": 0, "+1": 0, "-1": 0, "laugh": 0, "hooray": 0, "confused": 0, "heart": 0, "rocket": 0, "eyes": 0 }
https://api.github.com/repos/coleifer/peewee/issues/2610/timeline
null
completed
null
null
https://api.github.com/repos/coleifer/peewee/issues/2609
https://api.github.com/repos/coleifer/peewee
https://api.github.com/repos/coleifer/peewee/issues/2609/labels{/name}
https://api.github.com/repos/coleifer/peewee/issues/2609/comments
https://api.github.com/repos/coleifer/peewee/issues/2609/events
https://github.com/coleifer/peewee/issues/2609
1,351,468,945
I_kwDOAA7yGM5QjceR
2,609
[MySQL] [playhouse] [JSONField] contains() on the JSONField causes error: Incorrect arguments to ESCAPE
{ "login": "recipe", "id": 1947600, "node_id": "MDQ6VXNlcjE5NDc2MDA=", "avatar_url": "https://avatars.githubusercontent.com/u/1947600?v=4", "gravatar_id": "", "url": "https://api.github.com/users/recipe", "html_url": "https://github.com/recipe", "followers_url": "https://api.github.com/users/recipe/followers", "following_url": "https://api.github.com/users/recipe/following{/other_user}", "gists_url": "https://api.github.com/users/recipe/gists{/gist_id}", "starred_url": "https://api.github.com/users/recipe/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/recipe/subscriptions", "organizations_url": "https://api.github.com/users/recipe/orgs", "repos_url": "https://api.github.com/users/recipe/repos", "events_url": "https://api.github.com/users/recipe/events{/privacy}", "received_events_url": "https://api.github.com/users/recipe/received_events", "type": "User", "site_admin": false }
[]
closed
false
null
[]
null
[ "The query seems to work fine for the `name` column but it does not appear to be working with the JSON type.\r\n\r\n```python\r\nReg.insert_many(\r\n [\r\n {\"id\": 1, \"name\": \"bar \\\\ 1\", \"message\": [\"a \\\\ b\"]},\r\n {\"id\": 2, \"name\": \"bar\", \"message\": [\"a \\\\\\\\ b\"]},\r\n ]\r\n).execute()\r\n\r\nkey = \"\\\\\"\r\n\r\n# This query against the name column works fine.\r\nquery = Reg.select(Reg.name).where(Reg.name.contains(key))\r\nprint('name like')\r\nfor r in query:\r\n print(r.name)\r\n\r\n# This query against the message (json) column does not.\r\nquery = Reg.select(Reg.name).where(Reg.message.contains(key))\r\nprint('message like')\r\nfor r in query: # peewee.OperationalError: (1210, 'Incorrect arguments to ESCAPE')\r\n print(r.name)\r\n```\r\n\r\nFurthermore, I think using `LIKE` against a JSON data-type is probably not something advisable. Are you using MySQL from Oracle, or MariaDB? It might be better in any case to use the built-in JSON functions or extract the text value from the JSON object and query it that way.\r\n\r\n```python\r\n\r\n# This works just fine:\r\nquery = Reg.select(Reg.name).where(fn.json_extract(Reg.message, '$[0]').contains(key))\r\n\r\n# SELECT `t1`.`name` FROM `reg` AS `t1`\r\n# WHERE (json_extract(`t1`.`message`, '$[0]') LIKE '%\\\\%' ESCAPE '\\')\r\nfor r in query: # works fine.\r\n print(r.name)\r\n```\r\n\r\nBasically, I think you're misusing the JSON data-type and should instead either:\r\n\r\n1. Use a plain TEXT / LONGTEXT column to store the json data, or\r\n2. Use the JSON functions to extract the text value first, then do the LIKE", "@coleifer Using the `LIKE` with JSON field in the MySQL is still a valid solution when we want to include keywords in some generic search functionality, especially when we have to find bad characters in heterogeneous JSON documents by specific signature to replace in the database migrations. My example above was simplified just for the test.", "In addition to this if we even used the `TEXT` field to keep JSON data we would write the following:\r\n```python\r\n#!/usr/bin/env python\r\n\r\nimport json\r\nfrom peewee import *\r\n\r\n\r\ndb = MySQLDatabase(\r\n \"db\", host=\"localhost\", port=3306, user=\"user\", password=\"password\"\r\n)\r\n\r\n\r\nclass JsonTextField(TextField):\r\n def db_value(self, value):\r\n if value is not None:\r\n return json.dumps(value)\r\n\r\n def python_value(self, value):\r\n if value is not None:\r\n return json.loads(value)\r\n\r\n\r\nclass t1(Model):\r\n id = IntegerField(primary_key=True)\r\n name = CharField(255)\r\n message = JsonTextField()\r\n\r\n class Meta:\r\n database = db\r\n db_table = \"t1\"\r\n\r\n\r\ndb.connect()\r\ndb.create_tables([t1])\r\nt1.truncate_table()\r\nt1.insert_many(\r\n [\r\n {\"id\": 1, \"name\": \"bar\", \"message\": [\"a \\\\ b\"]},\r\n {\"id\": 2, \"name\": \"bar\", \"message\": [\"a \\\\\\\\ b\"]},\r\n ]\r\n).execute()\r\n\r\nkey = \"\\\\\"\r\n\r\nquery = t1.select(t1.name).where(t1.name.contains(key) | t1.message.contains(key))\r\n\r\nprint(query)\r\nfor r in query:\r\n print(r)\r\n\r\n```\r\n\r\nIt produces the same error:\r\n```sql\r\nSELECT `t1`.`name` FROM `t1` AS `t1` WHERE ((`t1`.`name` LIKE '%\\\\\\\\%' ESCAPE '\\\\') OR (`t1`.`message` LIKE '\\\"%\\\\\\\\\\\\\\\\%\\\"' ESCAPE '\\\"\\\\\\\\\\\"'))\r\n```", "Aha, thank you for your persistence -- I spotted the bug. The escape sequence is being handled by the Json converter, which dumps these strings as json and creates invalid escapes.\r\n\r\nThis should be fixed in master now.", "3.15.2 released now, which contains this fix." ]
"2022-08-25T21:29:17"
"2022-08-26T14:09:46"
"2022-08-26T02:36:40"
NONE
null
Having the following script that replicates the issue: ```python #!/usr/bin/env python from peewee import * from playhouse import mysql_ext db = MySQLDatabase( "db", host="localhost", port=3306, user="user", password="password" ) class t1(Model): id = IntegerField(primary_key=True) name = CharField(255) message = mysql_ext.JSONField() class Meta: database = db db_table = "t1" db.connect() db.create_tables([t1]) t1.truncate_table() t1.insert_many( [ {"id": 1, "name": "bar", "message": ["a \\ b"]}, {"id": 2, "name": "bar", "message": ["a \\\\ b"]}, ] ).execute() key = "\\" query = t1.select(t1.name).where(t1.name.contains(key) | t1.message.contains(key)) print(query) # SELECT `t1`.`name` FROM `t1` AS `t1` WHERE ((`t1`.`name` LIKE '%\\%' ESCAPE '\') OR (`t1`.`message` LIKE '"%\\\\%"' ESCAPE '"\\"')) for r in query: # peewee.OperationalError: (1210, 'Incorrect arguments to ESCAPE') print(r) ``` It produces invalid query: ```sql SELECT `t1`.`name` FROM `t1` AS `t1` WHERE ((`t1`.`name` LIKE '%\\\\%' ESCAPE '\\') OR (`t1`.`message` LIKE '\"%\\\\%\"' ESCAPE '\"\\\\\"')) ``` We are currently using the version 3.14.4, however the same issue is in the latest. ``` pip freeze | grep peewee peewee==3.15.1 ```
{ "url": "https://api.github.com/repos/coleifer/peewee/issues/2609/reactions", "total_count": 0, "+1": 0, "-1": 0, "laugh": 0, "hooray": 0, "confused": 0, "heart": 0, "rocket": 0, "eyes": 0 }
https://api.github.com/repos/coleifer/peewee/issues/2609/timeline
null
completed
null
null
https://api.github.com/repos/coleifer/peewee/issues/2608
https://api.github.com/repos/coleifer/peewee
https://api.github.com/repos/coleifer/peewee/issues/2608/labels{/name}
https://api.github.com/repos/coleifer/peewee/issues/2608/comments
https://api.github.com/repos/coleifer/peewee/issues/2608/events
https://github.com/coleifer/peewee/issues/2608
1,347,249,931
I_kwDOAA7yGM5QTWcL
2,608
Consider exposing the underlying query in `prefetch()`
{ "login": "ilyakamens", "id": 3293811, "node_id": "MDQ6VXNlcjMyOTM4MTE=", "avatar_url": "https://avatars.githubusercontent.com/u/3293811?v=4", "gravatar_id": "", "url": "https://api.github.com/users/ilyakamens", "html_url": "https://github.com/ilyakamens", "followers_url": "https://api.github.com/users/ilyakamens/followers", "following_url": "https://api.github.com/users/ilyakamens/following{/other_user}", "gists_url": "https://api.github.com/users/ilyakamens/gists{/gist_id}", "starred_url": "https://api.github.com/users/ilyakamens/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/ilyakamens/subscriptions", "organizations_url": "https://api.github.com/users/ilyakamens/orgs", "repos_url": "https://api.github.com/users/ilyakamens/repos", "events_url": "https://api.github.com/users/ilyakamens/events{/privacy}", "received_events_url": "https://api.github.com/users/ilyakamens/received_events", "type": "User", "site_admin": false }
[]
closed
false
null
[]
null
[ "Prefetch does not expose a query because the results are not composed of a single query, but rather `k` queries for however many tables are being prefetched. Dependent rows are iterated and an in-memory map is built for efficiently assigning them to their parent model instance/row. They're not able to be composed like your usual peewee queries.\r\n\r\nAlso note, I'd advise profiling to make sure `prefetch()` is actually faster in your case. It will likely come down to the ratio of the sizes of your outermost -> innermost loops whether it even provides a speedup or not.", "What's the value of `pq.query` before it's wrapped in a list [here](https://github.com/coleifer/peewee/blob/b36aea92d5c111278a9d0649afab89f9f1ffe0ac/peewee.py#L7934)?", "These lines are more relevant https://github.com/coleifer/peewee/blob/b36aea92d5c111278a9d0649afab89f9f1ffe0ac/peewee.py#L7927-L7932 but that is the outermost query, which has already been consumed and all the cached row instances in its CursorWrapper have their related child-instances populated, and so-on down the chain." ]
"2022-08-23T02:45:53"
"2022-08-23T13:16:01"
"2022-08-23T12:51:34"
CONTRIBUTOR
null
Mr. Leifer, Thanks for creating and maintaining such a great library. We've used it at Propel since August 18, 2015 starting with version 2.6.2. I'd like to use `prefetch()` to avoid N+1 queries, but am having trouble doing so because `prefetch()` returns a list instead of a query. We use peewee queries (e.g., `User.select().where(...)`) as part of a generalized data migration system. Here's what some of the code in that system looks like: ```python if checkpoint: checkpoint_id = self.checkpoint_to_id(checkpoint) query = query.where(query.model.id > checkpoint_id) rows = list(query.order_by(query.model.id).limit(batch_size)) modified = pool.imap(lambda row: self._migrate_row(row, dry_run), rows) ``` As you can see, a list of peewee models is difficult to integrate into this API. Would you consider some kind of non-breaking API change to enable access to the underlying `prefetch()` query? Something like `prefetch_query()`, or perhaps a `kwarg` like `query=True` (or whatever you're amenable to)? I'd also be happy to submit a PR. Thanks again.
{ "url": "https://api.github.com/repos/coleifer/peewee/issues/2608/reactions", "total_count": 0, "+1": 0, "-1": 0, "laugh": 0, "hooray": 0, "confused": 0, "heart": 0, "rocket": 0, "eyes": 0 }
https://api.github.com/repos/coleifer/peewee/issues/2608/timeline
null
completed
null
null
https://api.github.com/repos/coleifer/peewee/issues/2607
https://api.github.com/repos/coleifer/peewee
https://api.github.com/repos/coleifer/peewee/issues/2607/labels{/name}
https://api.github.com/repos/coleifer/peewee/issues/2607/comments
https://api.github.com/repos/coleifer/peewee/issues/2607/events
https://github.com/coleifer/peewee/issues/2607
1,346,108,983
I_kwDOAA7yGM5QO_43
2,607
Declarative table partitioning (Postgres)
{ "login": "foobarto", "id": 271036, "node_id": "MDQ6VXNlcjI3MTAzNg==", "avatar_url": "https://avatars.githubusercontent.com/u/271036?v=4", "gravatar_id": "", "url": "https://api.github.com/users/foobarto", "html_url": "https://github.com/foobarto", "followers_url": "https://api.github.com/users/foobarto/followers", "following_url": "https://api.github.com/users/foobarto/following{/other_user}", "gists_url": "https://api.github.com/users/foobarto/gists{/gist_id}", "starred_url": "https://api.github.com/users/foobarto/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/foobarto/subscriptions", "organizations_url": "https://api.github.com/users/foobarto/orgs", "repos_url": "https://api.github.com/users/foobarto/repos", "events_url": "https://api.github.com/users/foobarto/events{/privacy}", "received_events_url": "https://api.github.com/users/foobarto/received_events", "type": "User", "site_admin": false }
[]
closed
false
null
[]
null
[ "Here's an example. You can use `Meta.table_settings`:\r\n\r\nhttps://github.com/coleifer/peewee/blob/master/tests/schema.py#L433-L448\r\n\r\n```python\r\n def test_table_settings(self):\r\n class KVSettings(TestModel):\r\n key = TextField(primary_key=True)\r\n value = TextField()\r\n timestamp = TimestampField()\r\n class Meta:\r\n database = self.database\r\n table_settings = ('PARTITION BY RANGE (timestamp)',\r\n 'WITHOUT ROWID')\r\n self.assertCreateTable(KVSettings, [\r\n ('CREATE TABLE \"kv_settings\" ('\r\n '\"key\" TEXT NOT NULL PRIMARY KEY, '\r\n '\"value\" TEXT NOT NULL, '\r\n '\"timestamp\" INTEGER NOT NULL) '\r\n 'PARTITION BY RANGE (timestamp) '\r\n 'WITHOUT ROWID')])\r\n```\r\n\r\nDoc of model metadata options (scroll to table): http://docs.peewee-orm.com/en/latest/peewee/models.html#model-options-and-table-metadata" ]
"2022-08-22T09:35:41"
"2022-08-22T12:11:00"
"2022-08-22T12:10:32"
NONE
null
I'm trying to figure out how to create a table with [declarative partitioning in Postgres](https://www.postgresql.org/docs/current/ddl-partitioning.html) so the syntax looks like this: ```sql CREATE TABLE measurement ( city_id int not null, logdate date not null, peaktemp int, unitsales int ) PARTITION BY RANGE (logdate); ``` And also individual partitions, like so: ```sql CREATE TABLE measurement_y2006m02 PARTITION OF measurement FOR VALUES FROM ('2006-02-01') TO ('2006-03-01'); CREATE TABLE measurement_y2006m03 PARTITION OF measurement FOR VALUES FROM ('2006-03-01') TO ('2006-04-01'); ``` I guess either could be done with raw SQL but I'm wondering if at very least there is any way to use the `Meta` on the model to append the `PARTITION BY RANGE` when using `db.create_tables()`.
{ "url": "https://api.github.com/repos/coleifer/peewee/issues/2607/reactions", "total_count": 0, "+1": 0, "-1": 0, "laugh": 0, "hooray": 0, "confused": 0, "heart": 0, "rocket": 0, "eyes": 0 }
https://api.github.com/repos/coleifer/peewee/issues/2607/timeline
null
completed
null
null
https://api.github.com/repos/coleifer/peewee/issues/2606
https://api.github.com/repos/coleifer/peewee
https://api.github.com/repos/coleifer/peewee/issues/2606/labels{/name}
https://api.github.com/repos/coleifer/peewee/issues/2606/comments
https://api.github.com/repos/coleifer/peewee/issues/2606/events
https://github.com/coleifer/peewee/issues/2606
1,343,503,900
I_kwDOAA7yGM5QFD4c
2,606
iterating or extending `Function` produces an infinite loop
{ "login": "joshkaplan", "id": 5589260, "node_id": "MDQ6VXNlcjU1ODkyNjA=", "avatar_url": "https://avatars.githubusercontent.com/u/5589260?v=4", "gravatar_id": "", "url": "https://api.github.com/users/joshkaplan", "html_url": "https://github.com/joshkaplan", "followers_url": "https://api.github.com/users/joshkaplan/followers", "following_url": "https://api.github.com/users/joshkaplan/following{/other_user}", "gists_url": "https://api.github.com/users/joshkaplan/gists{/gist_id}", "starred_url": "https://api.github.com/users/joshkaplan/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/joshkaplan/subscriptions", "organizations_url": "https://api.github.com/users/joshkaplan/orgs", "repos_url": "https://api.github.com/users/joshkaplan/repos", "events_url": "https://api.github.com/users/joshkaplan/events{/privacy}", "received_events_url": "https://api.github.com/users/joshkaplan/received_events", "type": "User", "site_admin": false }
[]
closed
false
null
[]
null
[ "We don't want to raise an IndexError since it is not inherently an iterable type, so I'm going with NotImplementedError for now.", "3.15.2 released now, which contains this fix." ]
"2022-08-18T19:12:16"
"2022-08-26T14:10:05"
"2022-08-18T19:30:19"
NONE
null
### Problem Both of these examples produce an infinite loop: ```python3 import peewee pwf = peewee.fn.count() # example 1: for i in pwf: print(f'hello {str(i)}') # example 2: x = [] x.extend(pwf) ``` The offending code is `ColumnBase.__getitem__`: https://github.com/coleifer/peewee/blob/master/peewee.py#L1236-L1242 I'm not sure if this only applies to `Function`, or if it affects all non-slice `ColumnBase` classes. For context, we did run into this in a real-world use-case. ### Expected Behavior I'm not 100% sure, but at the very least this probably should `raise` rather than infinitely loop, which is worse because it is silent and effectively a memory leak. ### Proposed Solutions _(Disclaimer: I'm not deeply familiar with `peewee`'s internals, so this is more directional than a fully thought-out solution.)_ From the [Python docs](https://docs.python.org/3/reference/datamodel.html#object.__getitem__): > Note [for](https://docs.python.org/3/reference/compound_stmts.html#for) loops expect that an [IndexError](https://docs.python.org/3/library/exceptions.html#IndexError) will be raised for illegal indexes to allow proper detection of the end of the sequence. So if raising in all non-slice cases doesn't make sense, perhaps just raising an `IndexError` at the appropriate time (e.g. after 1 loop)?
{ "url": "https://api.github.com/repos/coleifer/peewee/issues/2606/reactions", "total_count": 0, "+1": 0, "-1": 0, "laugh": 0, "hooray": 0, "confused": 0, "heart": 0, "rocket": 0, "eyes": 0 }
https://api.github.com/repos/coleifer/peewee/issues/2606/timeline
null
completed
null
null
https://api.github.com/repos/coleifer/peewee/issues/2605
https://api.github.com/repos/coleifer/peewee
https://api.github.com/repos/coleifer/peewee/issues/2605/labels{/name}
https://api.github.com/repos/coleifer/peewee/issues/2605/comments
https://api.github.com/repos/coleifer/peewee/issues/2605/events
https://github.com/coleifer/peewee/issues/2605
1,341,043,315
I_kwDOAA7yGM5P7rJz
2,605
allow non-atomic get_or_create?
{ "login": "mayli", "id": 822628, "node_id": "MDQ6VXNlcjgyMjYyOA==", "avatar_url": "https://avatars.githubusercontent.com/u/822628?v=4", "gravatar_id": "", "url": "https://api.github.com/users/mayli", "html_url": "https://github.com/mayli", "followers_url": "https://api.github.com/users/mayli/followers", "following_url": "https://api.github.com/users/mayli/following{/other_user}", "gists_url": "https://api.github.com/users/mayli/gists{/gist_id}", "starred_url": "https://api.github.com/users/mayli/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/mayli/subscriptions", "organizations_url": "https://api.github.com/users/mayli/orgs", "repos_url": "https://api.github.com/users/mayli/repos", "events_url": "https://api.github.com/users/mayli/events{/privacy}", "received_events_url": "https://api.github.com/users/mayli/received_events", "type": "User", "site_admin": false }
[]
closed
false
null
[]
null
[ "You are welcome to write your own implementation and place it on a `Base` model class you use." ]
"2022-08-17T01:14:30"
"2022-08-17T12:45:51"
"2022-08-17T12:45:51"
NONE
null
The current [get_or_create](https://github.com/coleifer/peewee/blob/eeff376be5af089e7d3849284a1c1d71b5df215f/peewee.py#L6626-L6627) requires the db supports `atomic()`, which is not necessary in most cases. Is it possible add a parameter to allow non-atomic `get_or_create`?
{ "url": "https://api.github.com/repos/coleifer/peewee/issues/2605/reactions", "total_count": 0, "+1": 0, "-1": 0, "laugh": 0, "hooray": 0, "confused": 0, "heart": 0, "rocket": 0, "eyes": 0 }
https://api.github.com/repos/coleifer/peewee/issues/2605/timeline
null
completed
null
null
https://api.github.com/repos/coleifer/peewee/issues/2604
https://api.github.com/repos/coleifer/peewee
https://api.github.com/repos/coleifer/peewee/issues/2604/labels{/name}
https://api.github.com/repos/coleifer/peewee/issues/2604/comments
https://api.github.com/repos/coleifer/peewee/issues/2604/events
https://github.com/coleifer/peewee/issues/2604
1,338,361,492
I_kwDOAA7yGM5PxcaU
2,604
TypeError: super(type, obj): obj must be an instance or subtype of type
{ "login": "jramosss", "id": 52583728, "node_id": "MDQ6VXNlcjUyNTgzNzI4", "avatar_url": "https://avatars.githubusercontent.com/u/52583728?v=4", "gravatar_id": "", "url": "https://api.github.com/users/jramosss", "html_url": "https://github.com/jramosss", "followers_url": "https://api.github.com/users/jramosss/followers", "following_url": "https://api.github.com/users/jramosss/following{/other_user}", "gists_url": "https://api.github.com/users/jramosss/gists{/gist_id}", "starred_url": "https://api.github.com/users/jramosss/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/jramosss/subscriptions", "organizations_url": "https://api.github.com/users/jramosss/orgs", "repos_url": "https://api.github.com/users/jramosss/repos", "events_url": "https://api.github.com/users/jramosss/events{/privacy}", "received_events_url": "https://api.github.com/users/jramosss/received_events", "type": "User", "site_admin": false }
[]
closed
false
null
[]
null
[ "`get()` is a classmethod. Check out the following:\r\n\r\n```python\r\nclass BaseModel(Model):\r\n @classmethod\r\n def get(cls, *query, **filters):\r\n print('get() called on base.')\r\n return super(BaseModel, cls).get(*query, **filters)\r\n class Meta:\r\n database = db\r\n\r\nclass User(BaseModel):\r\n username = TextField()\r\n\r\ndb.create_tables([User])\r\nUser.create(username='u1')\r\nprint(User.get(User.username == 'u1').username)\r\nprint(User.get(username='u1').username)\r\n```\r\n\r\nOutput:\r\n\r\n```\r\nget() called on base.\r\nu1\r\nget() called on base.\r\nu1\r\n```" ]
"2022-08-14T22:10:15"
"2022-08-15T11:24:19"
"2022-08-15T11:24:18"
NONE
null
I'm trying to define a base model class for all my models, so i can get type hints when i execute model.get(). This is my code ```py class BaseModel(models.Model): created_at: datetime = models.DateTimeField(default=datetime.now(tz=timezone.utc)) def get(self, *query, **filters) -> Self: return super().get(*query, **filters) class Meta: database = db ``` but when i try to do `user = User.get(User.username == "test")` i get the following error: ``` Traceback (most recent call last): File "/home/shuls/Documents/weas/proyectos/truco2/.venv/lib/python3.10/site-packages/uvicorn/protocols/http/h11_impl.py", line 403, in run_asgi result = await app(self.scope, self.receive, self.send) File "/home/shuls/Documents/weas/proyectos/truco2/.venv/lib/python3.10/site-packages/uvicorn/middleware/proxy_headers.py", line 78, in __call__ return await self.app(scope, receive, send) File "/home/shuls/Documents/weas/proyectos/truco2/.venv/lib/python3.10/site-packages/fastapi/applications.py", line 269, in __call__ await super().__call__(scope, receive, send) File "/home/shuls/Documents/weas/proyectos/truco2/.venv/lib/python3.10/site-packages/starlette/applications.py", line 124, in __call__ await self.middleware_stack(scope, receive, send) File "/home/shuls/Documents/weas/proyectos/truco2/.venv/lib/python3.10/site-packages/starlette/middleware/errors.py", line 184, in __call__ raise exc File "/home/shuls/Documents/weas/proyectos/truco2/.venv/lib/python3.10/site-packages/starlette/middleware/errors.py", line 162, in __call__ await self.app(scope, receive, _send) File "/home/shuls/Documents/weas/proyectos/truco2/.venv/lib/python3.10/site-packages/starlette/exceptions.py", line 93, in __call__ raise exc File "/home/shuls/Documents/weas/proyectos/truco2/.venv/lib/python3.10/site-packages/starlette/exceptions.py", line 82, in __call__ await self.app(scope, receive, sender) File "/home/shuls/Documents/weas/proyectos/truco2/.venv/lib/python3.10/site-packages/fastapi/middleware/asyncexitstack.py", line 21, in __call__ raise e File "/home/shuls/Documents/weas/proyectos/truco2/.venv/lib/python3.10/site-packages/fastapi/middleware/asyncexitstack.py", line 18, in __call__ await self.app(scope, receive, send) File "/home/shuls/Documents/weas/proyectos/truco2/.venv/lib/python3.10/site-packages/starlette/routing.py", line 670, in __call__ await route.handle(scope, receive, send) File "/home/shuls/Documents/weas/proyectos/truco2/.venv/lib/python3.10/site-packages/starlette/routing.py", line 266, in handle await self.app(scope, receive, send) File "/home/shuls/Documents/weas/proyectos/truco2/.venv/lib/python3.10/site-packages/starlette/routing.py", line 65, in app response = await func(request) File "/home/shuls/Documents/weas/proyectos/truco2/.venv/lib/python3.10/site-packages/fastapi/routing.py", line 227, in app raw_response = await run_endpoint_function( File "/home/shuls/Documents/weas/proyectos/truco2/.venv/lib/python3.10/site-packages/fastapi/routing.py", line 160, in run_endpoint_function return await dependant.call(**values) File "/home/shuls/Documents/weas/proyectos/truco2/./routers/sample_routers.py", line 12, in read_root user = User.get(User.username == "test") File "/home/shuls/Documents/weas/proyectos/truco2/./db/models.py", line 31, in get return super(BaseModel, self).get(*query, **filters) TypeError: super(type, obj): obj must be an instance or subtype of type ``` OS: ubuntu 20.04 LTS Python version: 3.10.6 pewee version: 3.15.1
{ "url": "https://api.github.com/repos/coleifer/peewee/issues/2604/reactions", "total_count": 0, "+1": 0, "-1": 0, "laugh": 0, "hooray": 0, "confused": 0, "heart": 0, "rocket": 0, "eyes": 0 }
https://api.github.com/repos/coleifer/peewee/issues/2604/timeline
null
completed
null
null
https://api.github.com/repos/coleifer/peewee/issues/2603
https://api.github.com/repos/coleifer/peewee
https://api.github.com/repos/coleifer/peewee/issues/2603/labels{/name}
https://api.github.com/repos/coleifer/peewee/issues/2603/comments
https://api.github.com/repos/coleifer/peewee/issues/2603/events
https://github.com/coleifer/peewee/pull/2603
1,331,022,867
PR_kwDOAA7yGM48xSuf
2,603
Added special expressions to boolean field
{ "login": "alteralt", "id": 109542778, "node_id": "U_kgDOBod9eg", "avatar_url": "https://avatars.githubusercontent.com/u/109542778?v=4", "gravatar_id": "", "url": "https://api.github.com/users/alteralt", "html_url": "https://github.com/alteralt", "followers_url": "https://api.github.com/users/alteralt/followers", "following_url": "https://api.github.com/users/alteralt/following{/other_user}", "gists_url": "https://api.github.com/users/alteralt/gists{/gist_id}", "starred_url": "https://api.github.com/users/alteralt/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/alteralt/subscriptions", "organizations_url": "https://api.github.com/users/alteralt/orgs", "repos_url": "https://api.github.com/users/alteralt/repos", "events_url": "https://api.github.com/users/alteralt/events{/privacy}", "received_events_url": "https://api.github.com/users/alteralt/received_events", "type": "User", "site_admin": false }
[]
closed
false
null
[]
null
[ "Going to pass for now, thanks." ]
"2022-08-07T13:52:35"
"2022-08-07T15:33:50"
"2022-08-07T15:33:50"
NONE
null
Added an expression so that in the request instead of: ```python Model.select().where(Model.boolean_field == True) ```` To write: ```python Model.select().where(Model.boolean_field.is_true()) ```` The same expression already exists: https://github.com/alteralt/peewee/blob/b8c629bc100c4886c5b87b6eb62cce66c84a0d9c/peewee.py#L1197
{ "url": "https://api.github.com/repos/coleifer/peewee/issues/2603/reactions", "total_count": 0, "+1": 0, "-1": 0, "laugh": 0, "hooray": 0, "confused": 0, "heart": 0, "rocket": 0, "eyes": 0 }
https://api.github.com/repos/coleifer/peewee/issues/2603/timeline
null
null
false
{ "url": "https://api.github.com/repos/coleifer/peewee/pulls/2603", "html_url": "https://github.com/coleifer/peewee/pull/2603", "diff_url": "https://github.com/coleifer/peewee/pull/2603.diff", "patch_url": "https://github.com/coleifer/peewee/pull/2603.patch", "merged_at": null }
https://api.github.com/repos/coleifer/peewee/issues/2602
https://api.github.com/repos/coleifer/peewee
https://api.github.com/repos/coleifer/peewee/issues/2602/labels{/name}
https://api.github.com/repos/coleifer/peewee/issues/2602/comments
https://api.github.com/repos/coleifer/peewee/issues/2602/events
https://github.com/coleifer/peewee/issues/2602
1,331,017,694
I_kwDOAA7yGM5PVbfe
2,602
Using `Case().alias` with join
{ "login": "cc00010", "id": 92562933, "node_id": "U_kgDOBYRl9Q", "avatar_url": "https://avatars.githubusercontent.com/u/92562933?v=4", "gravatar_id": "", "url": "https://api.github.com/users/cc00010", "html_url": "https://github.com/cc00010", "followers_url": "https://api.github.com/users/cc00010/followers", "following_url": "https://api.github.com/users/cc00010/following{/other_user}", "gists_url": "https://api.github.com/users/cc00010/gists{/gist_id}", "starred_url": "https://api.github.com/users/cc00010/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/cc00010/subscriptions", "organizations_url": "https://api.github.com/users/cc00010/orgs", "repos_url": "https://api.github.com/users/cc00010/repos", "events_url": "https://api.github.com/users/cc00010/events{/privacy}", "received_events_url": "https://api.github.com/users/cc00010/received_events", "type": "User", "site_admin": false }
[]
closed
false
null
[]
null
[ "What I'm expecting is this:\r\n```json\r\n{\r\n \"attached_file\": { \"file_name\": \"test.jpg\", \"file_url\": null }\r\n}\r\n```\r\nnot this:\r\n```json\r\n{\r\n \"attached_file\": { \"file_name\": \"test.jpg\" }\r\n \"file_url\": null\r\n}\r\n```\r\n\r\nI think Peewee should automatically handle such \"calls\":\r\n```python3\r\nCase(...).alias(AttachedFile.file_url)\r\n```", "I note one strange thing about your example -- why is there a circular foreign-key between AttachedFile and Article? Also there seems to be no fk between User and Article, though that's referenced in your example. Overall I think everything is behaving very normally in the following example:\r\n\r\n```python\r\nclass AttachedFile(Base):\r\n file_name = TextField() # this is public\r\n file_url = TextField() # but this field requires users to be subscribed\r\n\r\nclass Article(Base):\r\n attached_file = ForeignKeyField(AttachedFile)\r\n\r\nclass User(Base):\r\n username = TextField\r\n\r\nclass Subscription(Base):\r\n user = ForeignKeyField(User)\r\n\r\ndb.create_tables([AttachedFile, Article, User, Subscription])\r\n\r\nu1, u2, u3 = [User.create(username=u) for u in ('u1', 'u2', 'u3')]\r\nSubscription.create(user=u3)\r\n\r\naf1 = AttachedFile.create(file_name='af1', file_url='https://af1')\r\naf2 = AttachedFile.create(file_name='af2', file_url='https://af2')\r\n\r\na1 = Article.create(attached_file=af1)\r\na2 = Article.create(attached_file=af2)\r\n\r\ndef show_attached(uid):\r\n sub_cte = Subscription.select().where(Subscription.user == uid).cte('sub_cte')\r\n sel = (AttachedFile.id,\r\n AttachedFile.file_name,\r\n Case(fn.EXISTS(sub_cte.select()),\r\n [(False, None)],\r\n AttachedFile.file_url).alias('file_url'))\r\n q = (Article\r\n .select(*sel)\r\n .join_from(Article, AttachedFile)\r\n .with_cte(sub_cte))\r\n return q\r\n\r\n# For user-2 there is no subscription, so file url is None:\r\nfor row in show_attached(u2.id):\r\n print(row.attached_file.file_name, row.file_url)\r\n\r\n# For user-3 there is a subscription, so file url is shown:\r\nfor row in show_attached(u3.id):\r\n print(row.attached_file.file_name, row.file_url)\r\n```\r\n\r\nIt sounds like the crux of the issue is that you want the `file_url` patched onto the related `AttachedFile` instance? Unfortunately, Peewee does not have a way to specify which model in the model-graph the aliased `Case` should be applied-to. Why not select from `AttachedFile`, though, since that seems to be the only data you're interested in? Alternatively, you can handle setting the attributes yourself when serializing or iterating. Lastly, you can use the `.objects()` query-chaining method to apply all selected columns onto the `Article`, or use `.dicts()` to get a flat dictionary of the selected data.\r\n\r\nHere's how I would do it, though:\r\n\r\n```python\r\n q = (AttachedFile\r\n .select(*sel)\r\n .join_from(AttachedFile, Article)\r\n .with_cte(sub_cte))\r\n\r\n...\r\n\r\nfor row in show_attached(u3.id):\r\n print(row.file_name, row.file_url)\r\n```\r\n\r\nI do agree it would be nice to support a way to specify which model an arbitrary expression gets bound-to, but that would require some new APIs as I believe a great many existing implementations rely on the current behavior, and in 12 years this is the first time this has been requested. So I am going to hold-off for now, but will give it some thought and post here if anything should change.", ">I note one strange thing about your example -- why is there a circular foreign-key between AttachedFile and Article? Also there seems to be no fk between User and Article, though that's referenced in your example. Overall I think everything is behaving very normally in the following example:\r\n\r\nYeah, that piece of code is just to give some context.\r\n\r\nThanks for the detailed answer! I'll try that.", "Added a new little helper in `master` eeff376be5af089e7d3849284a1c1d71b5df215f that allows you to specify the target model for a column-like. So your example:\r\n\r\n```python\r\ndef show_attached(uid):\r\n sub_cte = Subscription.select().where(Subscription.user == uid).cte('sub_cte')\r\n sel = (AttachedFile.id,\r\n AttachedFile.file_name,\r\n Case(fn.EXISTS(sub_cte.select()),\r\n [(False, None)],\r\n AttachedFile.file_url).alias('file_url').bind_to(AttachedFile)) # Note the .bind_to() here.\r\n q = (Article\r\n .select(*sel)\r\n .join_from(Article, AttachedFile)\r\n .with_cte(sub_cte))\r\n return q\r\n\r\n# Note the file_url is now on attached_file!\r\nfor row in show_attached(u2.id):\r\n print(row.attached_file.file_name, row.attached_file.file_url)\r\n\r\n# For user-3 there is a subscription, so file url is shown:\r\nfor row in show_attached(u3.id):\r\n print(row.attached_file.file_name, row.attached_file.file_url)\r\n```", "@coleifer That's what I need, but shouldn't it just be like:\r\n\r\n```python3 \r\nCase(...).alias(AttachedFile.file_url) # conditional `file_url`\r\n# and \r\nValue('https://...').alias(AttachedFile.file_url) # replace the value of `file_url`\r\n# and\r\n(AttachedFile.file_size / 1000).alias(AttachedFile.file_size) # convert KB to MB\r\n```\r\nit just looks more compact and dynamic. I think it doesn't break anything, right?", "`to_bind` would be extra here as `AttachedFile` already tells Peewee the model we want to bind.\r\n\r\nAnd also we will be able to pass model columns into the `alias` method:\r\n```python3\r\nArticle.select(Value('it is a value').alias(Article.title))\r\n```\r\ninstead of \"hard coding\" the column names:\r\n```python3\r\nArticle.select(Value('it is a value').alias('title'))\r\n```\r\nor it can be used like this (It looks a bit strange, but it's very useful in some cases):\r\n```python3\r\nArticle.select(AttachedFile.file_name.alias(Article.title))\r\n```", "Let me think about it for a bit this morning.", "So the benefit of using `.bind_to()` is that you can specify the destination model in a multi-model query *regardless* of whether the alias corresponds to a field. For example, from the tests:\r\n\r\nhttps://github.com/coleifer/peewee/commit/eeff376be5af089e7d3849284a1c1d71b5df215f#diff-969c0712020e8472d8d78ae32190692cc1e8a3e16dc17f6977c8f87a1328adb7R4896-R4904\r\n\r\nIn the above, we alias a Case expression to a name that does not correspond to a field, and also specify that it should be applied on the related `User` instance.\r\n\r\nIf `Alias()` is extended to support a field/column as the destination, then we lose this functionality.\r\n\r\nI think I'm going to leave it as-is for now, even though it is more verbose in your particular examples." ]
"2022-08-07T13:32:53"
"2022-08-12T13:30:38"
"2022-08-08T14:00:31"
NONE
null
Let's say I have the following models: ```python3 class AttachedFile(Model): article = ForeignKeyField(Article) file_name = StringField() # this is public file_url = StringField() # but this field requires users to be subscribed class Article(Model): # ... attached_file = ForeignKeyField(AttachedFile) # ... class User(Model): # ... class Subscription(Model): # ... user = ForeignKeyField(User) # ... ``` So what I'm trying to do is to "hide" the `article.attached_file.file_url` field if the user doesn't have a subscription. So: ```python3 user_id = 3 # dummy id sub_cte = (Subscription.select() .where(Subscription.user == user_id).cte('sub_cte')) article_fields = [ AttachedFile.id, AttachedFile.file_name, Case(fn.EXISTS(sub_cte.select()), [(False, None)], AttachedFile.file_url).alias("file_url") # <- HERE IS THE PROBLEM ] target_article = (Article.select(*article_fields) .join_from(Article, User) .join_from(Article, AttachedFile) .with_cte(sub_cte) .get_or_none()) if target_article is not None: print(target_article.attached_file.file_url) ``` Now the `file_id` belongs to `target_article` not to the `target_article.attached_file`, and the structure of `target_article` is not what I want. I even tried this: ```python3 Case(...).alias(AttachedFile.file_url) # or Case(...).alias('"t1"."file_url"') ``` But it's raising an error. What I CANNOT do: - not using cte's - using subqueries - manually setting `target_article.attached_file.file_url`
{ "url": "https://api.github.com/repos/coleifer/peewee/issues/2602/reactions", "total_count": 0, "+1": 0, "-1": 0, "laugh": 0, "hooray": 0, "confused": 0, "heart": 0, "rocket": 0, "eyes": 0 }
https://api.github.com/repos/coleifer/peewee/issues/2602/timeline
null
completed
null
null
https://api.github.com/repos/coleifer/peewee/issues/2601
https://api.github.com/repos/coleifer/peewee
https://api.github.com/repos/coleifer/peewee/issues/2601/labels{/name}
https://api.github.com/repos/coleifer/peewee/issues/2601/comments
https://api.github.com/repos/coleifer/peewee/issues/2601/events
https://github.com/coleifer/peewee/issues/2601
1,327,769,676
I_kwDOAA7yGM5PJChM
2,601
fn.Max Usage
{ "login": "NAN-CForadas", "id": 98823081, "node_id": "U_kgDOBePrqQ", "avatar_url": "https://avatars.githubusercontent.com/u/98823081?v=4", "gravatar_id": "", "url": "https://api.github.com/users/NAN-CForadas", "html_url": "https://github.com/NAN-CForadas", "followers_url": "https://api.github.com/users/NAN-CForadas/followers", "following_url": "https://api.github.com/users/NAN-CForadas/following{/other_user}", "gists_url": "https://api.github.com/users/NAN-CForadas/gists{/gist_id}", "starred_url": "https://api.github.com/users/NAN-CForadas/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/NAN-CForadas/subscriptions", "organizations_url": "https://api.github.com/users/NAN-CForadas/orgs", "repos_url": "https://api.github.com/users/NAN-CForadas/repos", "events_url": "https://api.github.com/users/NAN-CForadas/events{/privacy}", "received_events_url": "https://api.github.com/users/NAN-CForadas/received_events", "type": "User", "site_admin": false }
[]
closed
false
null
[]
null
[ "```\r\nclass BaseModel(Model):\r\n class Meta:\r\n database = db\r\n```", "Please post on StackOverflow in the future. Questions like this are not appropriate to the issue tracker.\r\n\r\nDocs: http://docs.peewee-orm.com/en/latest/peewee/query_operators.html#sql-functions\r\n\r\nYour specific error is because your `Review.__str__` method, which you're calling when you iterate over your query results and print them, does a database lookup. Since you did not select the related column (`review_status_type`) we weren't able to look up the status and hence could not print. The error even states ReviewStatusTypeDoesNotExist...\r\n\r\nHere's the copy/paste answer you probably are looking for:\r\n\r\n```python\r\ndescription = 'NAN63831511'\r\n\r\n# Single value.\r\nmax_ver = (Review\r\n .select(fn.Max(Review.version))\r\n .where(Review.description == description)\r\n .scalar())\r\n```", "Thank you, much appreciated." ]
"2022-08-03T20:44:24"
"2022-08-04T00:04:01"
"2022-08-03T21:11:25"
NONE
null
If I run this in pgsql 'SELECT Max("t1"."version") FROM "reviews" AS "t1" WHERE ("t1"."description" = 'NAN63831511');' I get: ``` psql (14.4, server 13.6) Type "help" for help. qualintel=# SELECT Max("t1"."version") FROM "reviews" AS "t1" WHERE ("t1"."description" = 'NAN63831511'); max ----- 2 (1 row) qualintel=# ``` but if I run it in Python, I get: ``` description = 'NAN63831511' query = Review.select(fn.Max(Review.version)).where(Review.description == description).execute() for q in query: print(q) --------------------------------------------------------------------------- ReviewStatusTypeDoesNotExist Traceback (most recent call last) Input In [10], in <cell line: 1>() 1 for q in query: ----> 2 print(q) File ~/PycharmProjects/pee-wee-testing/models.py:224, in Review.__str__(self) 223 def __str__(self): --> 224 return f"description: {self.description}, review_status_type: {self.review_status_type}" \ 225 f"user: {self.user}, version: {self.version}" File ~/PycharmProjects/pee-wee-testing/venv/lib/python3.10/site-packages/peewee.py:4486, in ForeignKeyAccessor.__get__(self, instance, instance_type) 4484 def __get__(self, instance, instance_type=None): 4485 if instance is not None: -> 4486 return self.get_rel_instance(instance) 4487 return self.field File ~/PycharmProjects/pee-wee-testing/venv/lib/python3.10/site-packages/peewee.py:4481, in ForeignKeyAccessor.get_rel_instance(self, instance) 4479 return instance.__rel__.get(self.name, value) 4480 elif not self.field.null and self.field.lazy_load: -> 4481 raise self.rel_model.DoesNotExist 4482 return value ReviewStatusTypeDoesNotExist: ``` my models look like this: ``` lass ReviewStatusType(BaseModel): description = CharField(unique=True, index=True, null=False, help_text='Review Status Type') class Meta: table_name = 'review_status_types' class Review(BaseModel): description = CharField(index=True, null=False, help_text='AScope File# and Revision') review_status_type = ForeignKeyField(column_name='review_status_type_id', field='id', model=ReviewStatusType, help_text='Related review status type id') user = ForeignKeyField(column_name='user_id', field='id', model=User, help_text='Related user id') version = IntegerField(null=True, help_text='Version number of review') file_no = CharField(index=True, null=True, default='', help_text='File# e.g. NAN0000000') external_id = CharField(index=True, null=True, default='', help_text='External id e.g. AScope id') class Meta: table_name = 'reviews' ``` what am I doing wrong?
{ "url": "https://api.github.com/repos/coleifer/peewee/issues/2601/reactions", "total_count": 0, "+1": 0, "-1": 0, "laugh": 0, "hooray": 0, "confused": 0, "heart": 0, "rocket": 0, "eyes": 0 }
https://api.github.com/repos/coleifer/peewee/issues/2601/timeline
null
completed
null
null
https://api.github.com/repos/coleifer/peewee/issues/2600
https://api.github.com/repos/coleifer/peewee
https://api.github.com/repos/coleifer/peewee/issues/2600/labels{/name}
https://api.github.com/repos/coleifer/peewee/issues/2600/comments
https://api.github.com/repos/coleifer/peewee/issues/2600/events
https://github.com/coleifer/peewee/issues/2600
1,322,912,657
I_kwDOAA7yGM5O2guR
2,600
How to create enum in peewee ?
{ "login": "raoehtesham79", "id": 108576451, "node_id": "U_kgDOBni-ww", "avatar_url": "https://avatars.githubusercontent.com/u/108576451?v=4", "gravatar_id": "", "url": "https://api.github.com/users/raoehtesham79", "html_url": "https://github.com/raoehtesham79", "followers_url": "https://api.github.com/users/raoehtesham79/followers", "following_url": "https://api.github.com/users/raoehtesham79/following{/other_user}", "gists_url": "https://api.github.com/users/raoehtesham79/gists{/gist_id}", "starred_url": "https://api.github.com/users/raoehtesham79/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/raoehtesham79/subscriptions", "organizations_url": "https://api.github.com/users/raoehtesham79/orgs", "repos_url": "https://api.github.com/users/raoehtesham79/repos", "events_url": "https://api.github.com/users/raoehtesham79/events{/privacy}", "received_events_url": "https://api.github.com/users/raoehtesham79/received_events", "type": "User", "site_admin": false }
[]
closed
false
null
[]
null
[ "#630 \r\n\r\nhttps://gist.github.com/b1naryth1ef/607e92dc8c1748a06b5d", "Thanks for your response . I have seen this method . This is also not working." ]
"2022-07-30T06:11:42"
"2022-07-30T11:56:35"
"2022-07-30T11:35:16"
NONE
null
I am trying to create enum data type in peewee model but there is not such thing in peewee . Kindly, please help me to sort out this. Here is an example , what I want: class travel_mode(enum.Enum): Air = 1 Sea = 2 NA = 3 but how to use it in peewee model
{ "url": "https://api.github.com/repos/coleifer/peewee/issues/2600/reactions", "total_count": 1, "+1": 1, "-1": 0, "laugh": 0, "hooray": 0, "confused": 0, "heart": 0, "rocket": 0, "eyes": 0 }
https://api.github.com/repos/coleifer/peewee/issues/2600/timeline
null
completed
null
null
https://api.github.com/repos/coleifer/peewee/issues/2599
https://api.github.com/repos/coleifer/peewee
https://api.github.com/repos/coleifer/peewee/issues/2599/labels{/name}
https://api.github.com/repos/coleifer/peewee/issues/2599/comments
https://api.github.com/repos/coleifer/peewee/issues/2599/events
https://github.com/coleifer/peewee/issues/2599
1,318,439,007
I_kwDOAA7yGM5Olchf
2,599
How to access _database from query?
{ "login": "mkmoisen", "id": 2534631, "node_id": "MDQ6VXNlcjI1MzQ2MzE=", "avatar_url": "https://avatars.githubusercontent.com/u/2534631?v=4", "gravatar_id": "", "url": "https://api.github.com/users/mkmoisen", "html_url": "https://github.com/mkmoisen", "followers_url": "https://api.github.com/users/mkmoisen/followers", "following_url": "https://api.github.com/users/mkmoisen/following{/other_user}", "gists_url": "https://api.github.com/users/mkmoisen/gists{/gist_id}", "starred_url": "https://api.github.com/users/mkmoisen/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/mkmoisen/subscriptions", "organizations_url": "https://api.github.com/users/mkmoisen/orgs", "repos_url": "https://api.github.com/users/mkmoisen/repos", "events_url": "https://api.github.com/users/mkmoisen/events{/privacy}", "received_events_url": "https://api.github.com/users/mkmoisen/received_events", "type": "User", "site_admin": false }
[]
closed
false
null
[]
null
[ "Presumably you would know something about the database that's executing the queries, right? Or is this library restricted to operating on queries in absence of any other context? The `_database` attr is fine to use, I don't anticipate it changing any time soon.", "@coleifer \r\n\r\nI'm writing a library that is to be used by other applications. The library doesn't know what database the user will use.\r\n\r\nI need different behavior for postgres vs mysql. This function will return the updated result set if it is in postgres, or it will query the updated table and return the result if it is mysql.\r\n\r\nI can use the `_database` attribute, but I suppose I would rather not rely on a private attribute if possible.\r\n\r\nA Database Proxy cannot be used for this case, could it?", "Check out this example from the `playhouse` on how I've differentiated functionality by db: https://github.com/coleifer/peewee/blob/master/playhouse/kv.py#L16-L56\r\n\r\nI would recommend using `_database` and then looking up the corresponding property, e.g. `if query._database.returning_clause:`. Common properties are listed in the `class Database(...):` in peewee.py." ]
"2022-07-26T15:52:00"
"2022-07-26T17:15:45"
"2022-07-26T16:37:07"
NONE
null
I have a library function that needs to check the information about the `db` before taking action on a query: ``` def execute_update(query): if _is_returning_supported(query._database): return _execute_returning_dml(query) return _execute_nonreturning_update(query) ``` So far the only way I know how to do it is by requiring the `db` to be passed as a parameter to my function, or by accessing the private `query._database`. Is there another way? If not, can we add a public member?
{ "url": "https://api.github.com/repos/coleifer/peewee/issues/2599/reactions", "total_count": 0, "+1": 0, "-1": 0, "laugh": 0, "hooray": 0, "confused": 0, "heart": 0, "rocket": 0, "eyes": 0 }
https://api.github.com/repos/coleifer/peewee/issues/2599/timeline
null
completed
null
null
https://api.github.com/repos/coleifer/peewee/issues/2598
https://api.github.com/repos/coleifer/peewee
https://api.github.com/repos/coleifer/peewee/issues/2598/labels{/name}
https://api.github.com/repos/coleifer/peewee/issues/2598/comments
https://api.github.com/repos/coleifer/peewee/issues/2598/events
https://github.com/coleifer/peewee/issues/2598
1,314,384,949
I_kwDOAA7yGM5OV-w1
2,598
Composite Foreign Key
{ "login": "mkmoisen", "id": 2534631, "node_id": "MDQ6VXNlcjI1MzQ2MzE=", "avatar_url": "https://avatars.githubusercontent.com/u/2534631?v=4", "gravatar_id": "", "url": "https://api.github.com/users/mkmoisen", "html_url": "https://github.com/mkmoisen", "followers_url": "https://api.github.com/users/mkmoisen/followers", "following_url": "https://api.github.com/users/mkmoisen/following{/other_user}", "gists_url": "https://api.github.com/users/mkmoisen/gists{/gist_id}", "starred_url": "https://api.github.com/users/mkmoisen/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/mkmoisen/subscriptions", "organizations_url": "https://api.github.com/users/mkmoisen/orgs", "repos_url": "https://api.github.com/users/mkmoisen/repos", "events_url": "https://api.github.com/users/mkmoisen/events{/privacy}", "received_events_url": "https://api.github.com/users/mkmoisen/received_events", "type": "User", "site_admin": false }
[]
closed
false
null
[]
null
[ "You can add a constraint to the table in the following manner:\r\n\r\n```python\r\nclass Post(Model):\r\n author = TextField()\r\n title = TextField()\r\n class Meta:\r\n database = db\r\n primary_key = CompositeKey('author', 'title')\r\n\r\nclass Comment(Model):\r\n post_author = TextField()\r\n post_title = TextField()\r\n comment = TextField()\r\n class Meta:\r\n constraints = [\r\n SQL('foreign key (post_author, post_title) references post(author, title)'),\r\n ]\r\n database = db\r\n depends_on = [Post] # Since no explicit FK field, this ensures tables created in proper order.\r\n\r\ndb.create_tables([Post, Comment])\r\n\r\np1 = Post.create(author='a1', title='t1')\r\np2 = Post.create(author='a2', title='t2')\r\nComment.create(post_author=p1.author, post_title=p1.title, comment='p1-c')\r\nComment.create(post_author=p2.author, post_title=p2.title, comment='p2-c')\r\nwith db.atomic():\r\n try:\r\n Comment.create(post_author='a1', post_title='tx', comment='p1-x')\r\n except IntegrityError:\r\n print('received expected integrity error.')\r\nwith db.atomic():\r\n try:\r\n Comment.create(post_author='ax', post_title='t1', comment='p1-x')\r\n except IntegrityError:\r\n print('received expected integrity error.')\r\n\r\ndb.drop_tables([Post, Comment])\r\n```\r\n\r\nSee the table of supported Model metadata options:\r\n\r\nhttp://docs.peewee-orm.com/en/latest/peewee/models.html#model-options-and-table-metadata" ]
"2022-07-22T06:15:12"
"2022-07-22T13:35:36"
"2022-07-22T13:35:36"
NONE
null
The docs [state](https://www.bookstack.cn/read/peewee-orm-3.13.1-en/spilt.5.c7972b36e7689f24.md): > Peewee does not support the concept of a “composite foreign-key” I assume the reason is because it makes the ORM joins complicated. However, I simply need to create a composite foreign-key in the database in order to maintain referential integrity for a particular use case. I will never need to join on these two columns through the ORM. How can I instruct peewee to create a composite foreign-key at the database level, while defining my Model?
{ "url": "https://api.github.com/repos/coleifer/peewee/issues/2598/reactions", "total_count": 0, "+1": 0, "-1": 0, "laugh": 0, "hooray": 0, "confused": 0, "heart": 0, "rocket": 0, "eyes": 0 }
https://api.github.com/repos/coleifer/peewee/issues/2598/timeline
null
completed
null
null
https://api.github.com/repos/coleifer/peewee/issues/2597
https://api.github.com/repos/coleifer/peewee
https://api.github.com/repos/coleifer/peewee/issues/2597/labels{/name}
https://api.github.com/repos/coleifer/peewee/issues/2597/comments
https://api.github.com/repos/coleifer/peewee/issues/2597/events
https://github.com/coleifer/peewee/pull/2597
1,312,720,259
PR_kwDOAA7yGM4703bh
2,597
Modify the incorrect description of the document
{ "login": "sunmd01", "id": 9304859, "node_id": "MDQ6VXNlcjkzMDQ4NTk=", "avatar_url": "https://avatars.githubusercontent.com/u/9304859?v=4", "gravatar_id": "", "url": "https://api.github.com/users/sunmd01", "html_url": "https://github.com/sunmd01", "followers_url": "https://api.github.com/users/sunmd01/followers", "following_url": "https://api.github.com/users/sunmd01/following{/other_user}", "gists_url": "https://api.github.com/users/sunmd01/gists{/gist_id}", "starred_url": "https://api.github.com/users/sunmd01/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/sunmd01/subscriptions", "organizations_url": "https://api.github.com/users/sunmd01/orgs", "repos_url": "https://api.github.com/users/sunmd01/repos", "events_url": "https://api.github.com/users/sunmd01/events{/privacy}", "received_events_url": "https://api.github.com/users/sunmd01/received_events", "type": "User", "site_admin": false }
[]
closed
false
null
[]
null
[ "I'll see about rewording this later. The docs are trying to show what the available options are, and their default values." ]
"2022-07-21T06:26:54"
"2022-07-21T11:53:54"
"2022-07-21T11:53:54"
NONE
null
null
{ "url": "https://api.github.com/repos/coleifer/peewee/issues/2597/reactions", "total_count": 0, "+1": 0, "-1": 0, "laugh": 0, "hooray": 0, "confused": 0, "heart": 0, "rocket": 0, "eyes": 0 }
https://api.github.com/repos/coleifer/peewee/issues/2597/timeline
null
null
false
{ "url": "https://api.github.com/repos/coleifer/peewee/pulls/2597", "html_url": "https://github.com/coleifer/peewee/pull/2597", "diff_url": "https://github.com/coleifer/peewee/pull/2597.diff", "patch_url": "https://github.com/coleifer/peewee/pull/2597.patch", "merged_at": null }
https://api.github.com/repos/coleifer/peewee/issues/2596
https://api.github.com/repos/coleifer/peewee
https://api.github.com/repos/coleifer/peewee/issues/2596/labels{/name}
https://api.github.com/repos/coleifer/peewee/issues/2596/comments
https://api.github.com/repos/coleifer/peewee/issues/2596/events
https://github.com/coleifer/peewee/issues/2596
1,308,203,850
I_kwDOAA7yGM5N-ZtK
2,596
how use MATCH AGAINST
{ "login": "danil-cpu", "id": 78954394, "node_id": "MDQ6VXNlcjc4OTU0Mzk0", "avatar_url": "https://avatars.githubusercontent.com/u/78954394?v=4", "gravatar_id": "", "url": "https://api.github.com/users/danil-cpu", "html_url": "https://github.com/danil-cpu", "followers_url": "https://api.github.com/users/danil-cpu/followers", "following_url": "https://api.github.com/users/danil-cpu/following{/other_user}", "gists_url": "https://api.github.com/users/danil-cpu/gists{/gist_id}", "starred_url": "https://api.github.com/users/danil-cpu/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/danil-cpu/subscriptions", "organizations_url": "https://api.github.com/users/danil-cpu/orgs", "repos_url": "https://api.github.com/users/danil-cpu/repos", "events_url": "https://api.github.com/users/danil-cpu/events{/privacy}", "received_events_url": "https://api.github.com/users/danil-cpu/received_events", "type": "User", "site_admin": false }
[]
closed
false
null
[]
null
[ "You can use the helper in `playhouse.mysql_ext`:\r\n\r\n```python\r\nfrom playhouse.mysql_ext import Match\r\n\r\nmatch = Match((Script.title, Script.description), 'some word', 'with query expansion')\r\nScript.select(Script, match.alias('score'))\r\n```\r\n\r\nAlternatively, if you want to just build the expression manually, you can write a helper function to make this less tedious:\r\n\r\n```python\r\nfrom peewee import *\r\nfrom peewee import NodeList # Not exported by default\r\n\r\nclass Note(Model):\r\n title = TextField()\r\n body = TextField()\r\n\r\ndef match(word):\r\n match = fn.MATCH(Note.title, Note.body)\r\n against = fn.AGAINST(NodeList(('word', SQL('with query expansion'))))\r\n return NodeList((match, against))\r\n\r\n# in select\r\nNote.select(Note, match('some word').alias('score'))\r\n\r\n# in where\r\nNote.select().where(match('some other words'))\r\n```", "http://docs.peewee-orm.com/en/latest/peewee/playhouse.html#mysql-extensions" ]
"2022-07-18T16:25:20"
"2022-07-18T21:47:26"
"2022-07-18T21:46:26"
NONE
null
```MySQL SELECT id, title, description, MATCH (title, description) AGAINST ('word' WITH QUERY EXPANSION) AS score FROM `script` ORDER BY score DESC``` how use query in MySQL peewee?
{ "url": "https://api.github.com/repos/coleifer/peewee/issues/2596/reactions", "total_count": 2, "+1": 0, "-1": 0, "laugh": 0, "hooray": 0, "confused": 0, "heart": 2, "rocket": 0, "eyes": 0 }
https://api.github.com/repos/coleifer/peewee/issues/2596/timeline
null
completed
null
null
https://api.github.com/repos/coleifer/peewee/issues/2595
https://api.github.com/repos/coleifer/peewee
https://api.github.com/repos/coleifer/peewee/issues/2595/labels{/name}
https://api.github.com/repos/coleifer/peewee/issues/2595/comments
https://api.github.com/repos/coleifer/peewee/issues/2595/events
https://github.com/coleifer/peewee/issues/2595
1,307,421,644
I_kwDOAA7yGM5N7avM
2,595
Long running processes using peewee eventually fail
{ "login": "petersn", "id": 214862, "node_id": "MDQ6VXNlcjIxNDg2Mg==", "avatar_url": "https://avatars.githubusercontent.com/u/214862?v=4", "gravatar_id": "", "url": "https://api.github.com/users/petersn", "html_url": "https://github.com/petersn", "followers_url": "https://api.github.com/users/petersn/followers", "following_url": "https://api.github.com/users/petersn/following{/other_user}", "gists_url": "https://api.github.com/users/petersn/gists{/gist_id}", "starred_url": "https://api.github.com/users/petersn/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/petersn/subscriptions", "organizations_url": "https://api.github.com/users/petersn/orgs", "repos_url": "https://api.github.com/users/petersn/repos", "events_url": "https://api.github.com/users/petersn/events{/privacy}", "received_events_url": "https://api.github.com/users/petersn/received_events", "type": "User", "site_admin": false }
[]
closed
false
null
[]
null
[ "You need to understand how Peewee manages connections -- peewee creates a connection-per-thread and will not automatically reconnect if that connection should get closed by the server. Why? What if you were in the middle of a transaction or had uncommitted changes -- we don't want to silently lose those.\r\n\r\nSo what you need to do is ensure you are opening and closing your connections properly. Here's an example:\r\n\r\n```python\r\n\r\ndb = PostgresqlExtDatabase(...)\r\n\r\ndef long_running_task():\r\n while True:\r\n db.connect()\r\n # do some work with the database\r\n db.close()\r\n\r\n # wait for more work to do.\r\n```\r\n\r\nMy suggestions are: \r\n\r\n* open the connection for the short periods of time when you actually need it, close when done\r\n* use a connection pool with the above if the overhead of opening/closing connections is an issue" ]
"2022-07-18T05:23:25"
"2022-07-18T13:36:56"
"2022-07-18T13:36:56"
NONE
null
Hello folks, apologies if this issue is a duplicate. I've now seen several services I've written using peewee eventually fail after some time, varying from a few days to a couple months, with an error like: ``` Traceback (most recent call last): File "/usr/local/lib/python3.8/site-packages/peewee.py", line 3175, in execute_sql cursor = self.cursor(commit) File "/usr/local/lib/python3.8/site-packages/playhouse/postgres_ext.py", line 484, in cursor return self._state.conn.cursor() psycopg2.InterfaceError: connection already closed ``` It appears that peewee never recovers -- after this error occurs all following attempts to use the database via peewee fail as above. But when I restart the long running process it immediately works fine, and postgres itself is working fine. The connection itself is created as: ``` db = playhouse.postgres_ext.PostgresqlExtDatabase("postgres url", autorollback=True) class BaseModel(peewee.Model): class Meta: database = db ``` ... and then thereafter I use peewee in ways that should presumably be bog-standard. peewee version: 3.14.10 python version: 3.8.12 Apologies that this isn't the most recent version of peewee. I'd try to reproduce this issue with the most recent version, but by its very nature (failing after months) it's hard to reproduce. I realize that the above report is extremely vague and hard to work from, and quite plausibly this isn't peewee's fault. I can try to provide whatever information would be helpful to diagnose, if needed. Thanks.
{ "url": "https://api.github.com/repos/coleifer/peewee/issues/2595/reactions", "total_count": 0, "+1": 0, "-1": 0, "laugh": 0, "hooray": 0, "confused": 0, "heart": 0, "rocket": 0, "eyes": 0 }
https://api.github.com/repos/coleifer/peewee/issues/2595/timeline
null
completed
null
null
https://api.github.com/repos/coleifer/peewee/issues/2594
https://api.github.com/repos/coleifer/peewee
https://api.github.com/repos/coleifer/peewee/issues/2594/labels{/name}
https://api.github.com/repos/coleifer/peewee/issues/2594/comments
https://api.github.com/repos/coleifer/peewee/issues/2594/events
https://github.com/coleifer/peewee/pull/2594
1,307,076,643
PR_kwDOAA7yGM47hdg4
2,594
docs: Fix a few typos
{ "login": "timgates42", "id": 47873678, "node_id": "MDQ6VXNlcjQ3ODczNjc4", "avatar_url": "https://avatars.githubusercontent.com/u/47873678?v=4", "gravatar_id": "", "url": "https://api.github.com/users/timgates42", "html_url": "https://github.com/timgates42", "followers_url": "https://api.github.com/users/timgates42/followers", "following_url": "https://api.github.com/users/timgates42/following{/other_user}", "gists_url": "https://api.github.com/users/timgates42/gists{/gist_id}", "starred_url": "https://api.github.com/users/timgates42/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/timgates42/subscriptions", "organizations_url": "https://api.github.com/users/timgates42/orgs", "repos_url": "https://api.github.com/users/timgates42/repos", "events_url": "https://api.github.com/users/timgates42/events{/privacy}", "received_events_url": "https://api.github.com/users/timgates42/received_events", "type": "User", "site_admin": false }
[]
closed
false
null
[]
null
[]
"2022-07-17T11:59:50"
"2022-07-17T21:43:30"
"2022-07-17T21:43:30"
NONE
null
There are small typos in: - docs/peewee/query_examples.rst - peewee.py - tests/model_save.py - tests/postgres_helpers.py Fixes: - Should read `hierarchy` rather than `heirarchy`. - Should read `existent` rather than `existant`. - Should read `dictionary` rather than `dictioary`. - Should read `denormalization` rather than `denormalisation`. Semi-automated pull request generated by https://github.com/timgates42/meticulous/blob/master/docs/NOTE.md
{ "url": "https://api.github.com/repos/coleifer/peewee/issues/2594/reactions", "total_count": 0, "+1": 0, "-1": 0, "laugh": 0, "hooray": 0, "confused": 0, "heart": 0, "rocket": 0, "eyes": 0 }
https://api.github.com/repos/coleifer/peewee/issues/2594/timeline
null
null
false
{ "url": "https://api.github.com/repos/coleifer/peewee/pulls/2594", "html_url": "https://github.com/coleifer/peewee/pull/2594", "diff_url": "https://github.com/coleifer/peewee/pull/2594.diff", "patch_url": "https://github.com/coleifer/peewee/pull/2594.patch", "merged_at": null }
https://api.github.com/repos/coleifer/peewee/issues/2593
https://api.github.com/repos/coleifer/peewee
https://api.github.com/repos/coleifer/peewee/issues/2593/labels{/name}
https://api.github.com/repos/coleifer/peewee/issues/2593/comments
https://api.github.com/repos/coleifer/peewee/issues/2593/events
https://github.com/coleifer/peewee/pull/2593
1,305,279,402
PR_kwDOAA7yGM47brpf
2,593
Run CI tests with latest stable Python version
{ "login": "pylipp", "id": 10617122, "node_id": "MDQ6VXNlcjEwNjE3MTIy", "avatar_url": "https://avatars.githubusercontent.com/u/10617122?v=4", "gravatar_id": "", "url": "https://api.github.com/users/pylipp", "html_url": "https://github.com/pylipp", "followers_url": "https://api.github.com/users/pylipp/followers", "following_url": "https://api.github.com/users/pylipp/following{/other_user}", "gists_url": "https://api.github.com/users/pylipp/gists{/gist_id}", "starred_url": "https://api.github.com/users/pylipp/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/pylipp/subscriptions", "organizations_url": "https://api.github.com/users/pylipp/orgs", "repos_url": "https://api.github.com/users/pylipp/repos", "events_url": "https://api.github.com/users/pylipp/events{/privacy}", "received_events_url": "https://api.github.com/users/pylipp/received_events", "type": "User", "site_admin": false }
[]
closed
false
null
[]
null
[ "0f1a49202b72b18074032efa56e42d4aeef95cce" ]
"2022-07-14T20:54:58"
"2022-07-15T00:10:00"
"2022-07-15T00:09:59"
NONE
null
In order to increase confidence in the compatibility of peewee.
{ "url": "https://api.github.com/repos/coleifer/peewee/issues/2593/reactions", "total_count": 0, "+1": 0, "-1": 0, "laugh": 0, "hooray": 0, "confused": 0, "heart": 0, "rocket": 0, "eyes": 0 }
https://api.github.com/repos/coleifer/peewee/issues/2593/timeline
null
null
false
{ "url": "https://api.github.com/repos/coleifer/peewee/pulls/2593", "html_url": "https://github.com/coleifer/peewee/pull/2593", "diff_url": "https://github.com/coleifer/peewee/pull/2593.diff", "patch_url": "https://github.com/coleifer/peewee/pull/2593.patch", "merged_at": null }
https://api.github.com/repos/coleifer/peewee/issues/2592
https://api.github.com/repos/coleifer/peewee
https://api.github.com/repos/coleifer/peewee/issues/2592/labels{/name}
https://api.github.com/repos/coleifer/peewee/issues/2592/comments
https://api.github.com/repos/coleifer/peewee/issues/2592/events
https://github.com/coleifer/peewee/issues/2592
1,302,711,241
I_kwDOAA7yGM5NpcvJ
2,592
Default values for columns missing in table creation statement with sqlite
{ "login": "SandaruKasa", "id": 50824690, "node_id": "MDQ6VXNlcjUwODI0Njkw", "avatar_url": "https://avatars.githubusercontent.com/u/50824690?v=4", "gravatar_id": "", "url": "https://api.github.com/users/SandaruKasa", "html_url": "https://github.com/SandaruKasa", "followers_url": "https://api.github.com/users/SandaruKasa/followers", "following_url": "https://api.github.com/users/SandaruKasa/following{/other_user}", "gists_url": "https://api.github.com/users/SandaruKasa/gists{/gist_id}", "starred_url": "https://api.github.com/users/SandaruKasa/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/SandaruKasa/subscriptions", "organizations_url": "https://api.github.com/users/SandaruKasa/orgs", "repos_url": "https://api.github.com/users/SandaruKasa/repos", "events_url": "https://api.github.com/users/SandaruKasa/events{/privacy}", "received_events_url": "https://api.github.com/users/SandaruKasa/received_events", "type": "User", "site_admin": false }
[]
closed
false
null
[]
null
[ "It seems you have not read this part of the documentation: http://docs.peewee-orm.com/en/latest/peewee/models.html#default-field-values\r\n\r\n> Remember: when using the default parameter, the values are set by Peewee rather than being a part of the actual table and column definition.", "Huh, a peculiar design choice.\r\n\r\nIs there a way to propagate the default value to the table then?", ">Link him the docs.\r\n>\r\n>Still doesn't read it.\r\n\r\n@SandaruKasa ... come on.\r\n\r\n>The database can also provide the default value for a field. While peewee does not explicitly provide an API for setting a server-side default value, you can use the constraints parameter to specify the server default:\r\n>\r\n>```\r\n>class Message(Model):\r\n> context = TextField()\r\n> timestamp = DateTimeField(constraints=[SQL('DEFAULT CURRENT_TIMESTAMP')])\r\n>```\r\n" ]
"2022-07-12T23:12:26"
"2022-07-13T12:50:39"
"2022-07-13T12:50:39"
NONE
null
Python: 3.10 peewee: 3.8.2, 3.15.1 ```python import peewee import logging logging.basicConfig(level=logging.DEBUG) class Test(peewee.Model): test = peewee.IntegerField(default=1) class Meta: database = peewee.SqliteDatabase("test.sqlite3") Test.create_table() ``` gives the following output: ``` DEBUG:peewee:('CREATE TABLE IF NOT EXISTS "test" ("id" INTEGER NOT NULL PRIMARY KEY, "test" INTEGER NOT NULL)', []) ``` But I'm pretty sure it should be << "test" INTEGER NOT NULL **DEFAULT 1** >> P.S. Thank you for this amazing library
{ "url": "https://api.github.com/repos/coleifer/peewee/issues/2592/reactions", "total_count": 0, "+1": 0, "-1": 0, "laugh": 0, "hooray": 0, "confused": 0, "heart": 0, "rocket": 0, "eyes": 0 }
https://api.github.com/repos/coleifer/peewee/issues/2592/timeline
null
completed
null
null
https://api.github.com/repos/coleifer/peewee/issues/2591
https://api.github.com/repos/coleifer/peewee
https://api.github.com/repos/coleifer/peewee/issues/2591/labels{/name}
https://api.github.com/repos/coleifer/peewee/issues/2591/comments
https://api.github.com/repos/coleifer/peewee/issues/2591/events
https://github.com/coleifer/peewee/issues/2591
1,302,033,145
I_kwDOAA7yGM5Nm3L5
2,591
Test test_changelog_jsonfield failing in Fedora 37
{ "login": "vkrizan", "id": 7695766, "node_id": "MDQ6VXNlcjc2OTU3NjY=", "avatar_url": "https://avatars.githubusercontent.com/u/7695766?v=4", "gravatar_id": "", "url": "https://api.github.com/users/vkrizan", "html_url": "https://github.com/vkrizan", "followers_url": "https://api.github.com/users/vkrizan/followers", "following_url": "https://api.github.com/users/vkrizan/following{/other_user}", "gists_url": "https://api.github.com/users/vkrizan/gists{/gist_id}", "starred_url": "https://api.github.com/users/vkrizan/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/vkrizan/subscriptions", "organizations_url": "https://api.github.com/users/vkrizan/orgs", "repos_url": "https://api.github.com/users/vkrizan/repos", "events_url": "https://api.github.com/users/vkrizan/events{/privacy}", "received_events_url": "https://api.github.com/users/vkrizan/received_events", "type": "User", "site_admin": false }
[]
closed
false
null
[]
null
[ "Yes, this was fixed here: 4741e9f07d2f0fccee3a4731bc03093ef56e26f5\r\n\r\nThe regression is due to a change in the way Sqlite 3.39.0 propagates subtypes from columns in subqueries. \r\n\r\n* https://sqlite.org/src/info/\r\n* https://sqlite.org/forum/forumpost/9c94b6188e", "Is it possible to skip that single test with `runtests.py`, or would you suggest for us to wait for a new version?", "I pushed a new release, 3.15.1, which contains the patch.", "Thank you very much Charles!" ]
"2022-07-12T13:02:28"
"2022-07-12T13:24:35"
"2022-07-12T13:14:17"
NONE
null
Hello, I'm building an RPM package for new Fedora 37 (rawhide) and it fails on `test_changelog_jsonfield` test. ``` FAIL: test_changelog_jsonfield (tests.sqlite_changelog.TestChangeLog.test_changelog_jsonfield) ---------------------------------------------------------------------- Traceback (most recent call last): File "/builddir/build/BUILD/peewee-3.15.0/tests/base.py", line 260, in inner method(self) File "/builddir/build/BUILD/peewee-3.15.0/tests/sqlite_changelog.py", line 161, in test_changelog_jsonfield self.assertChanges([ File "/builddir/build/BUILD/peewee-3.15.0/tests/sqlite_changelog.py", line 64, in assertChanges self.assertEqual(accum, changes) AssertionError: Lists differ: [('IN[25 chars]one, '{"k1":"v1"}']}), ('INSERT', 'ct2', {'dat[74 chars]']})] != [('IN[25 chars]one, {'k1': 'v1'}]}), ('INSERT', 'ct2', {'data[73 chars]']})] First differing element 0: ('INSERT', 'ct2', {'data': [None, '{"k1":"v1"}']}) ('INSERT', 'ct2', {'data': [None, {'k1': 'v1'}]}) - [('INSERT', 'ct2', {'data': [None, '{"k1":"v1"}']}), ? -- ^ ^ ^ - + [('INSERT', 'ct2', {'data': [None, {'k1': 'v1'}]}), ? + ^ ^^ ^ - ('INSERT', 'ct2', {'data': [None, '["i0","i1","i2"]']}), ? -- ^ ^ ^ ^ ^ - + ('INSERT', 'ct2', {'data': [None, ['i0', 'i1', 'i2']]}), ? + ^ ^^ ^ ^^ ^ ('INSERT', 'ct2', {'data': [None, 'hello']})] ---------------------------------------------------------------------- ``` https://kojipkgs.fedoraproject.org//work/tasks/8448/89418448/build.log Build env has this installed: ``` annobin-docs-10.78-1.fc37.noarch annobin-plugin-gcc-10.78-1.fc37.x86_64 cpp-12.1.1-3.fc37.x86_64 expat-2.4.8-1.fc37.x86_64 gcc-12.1.1-3.fc37.x86_64 gcc-plugin-annobin-12.1.1-3.fc37.x86_64 glibc-devel-2.35.9000-28.fc37.x86_64 glibc-headers-x86-2.35.9000-28.fc37.noarch kernel-headers-5.19.0-0.rc6.git0.1.fc37.x86_64 libb2-0.98.1-6.fc37.x86_64 libmpc-1.2.1-4.fc36.x86_64 libpq-14.3-1.fc37.x86_64 libxcrypt-devel-4.4.28-1.fc37.x86_64 mpdecimal-2.5.1-3.fc36.x86_64 python-pip-wheel-22.0.4-4.fc37.noarch python-rpm-macros-3.11-1.fc37.noarch python-setuptools-wheel-62.6.0-1.fc37.noarch python3-3.11.0~b4-1.fc37.x86_64 python3-Cython-0.29.30-2.fc37.x86_64 python3-apsw-3.38.5.r1-2.fc37.x86_64 python3-babel-2.10.3-2.fc37.noarch python3-charset-normalizer-2.1.0-1.fc37.noarch python3-click-8.1.2-2.fc37.noarch python3-devel-3.11.0~b4-1.fc37.x86_64 python3-docutils-0.17.1-3.fc37.noarch python3-flask-1:2.1.2-2.fc37.noarch python3-idna-3.3-3.fc37.noarch python3-imagesize-1.2.0-8.fc37.noarch python3-itsdangerous-2.0.1-4.fc37.noarch python3-jinja2-3.0.3-4.fc37.noarch python3-libs-3.11.0~b4-1.fc37.x86_64 python3-markupsafe-2.1.1-2.fc37.x86_64 python3-packaging-21.3-4.fc37.noarch python3-psycopg2-2.9.3-5.fc37.x86_64 python3-pygments-2.12.0-3.fc37.noarch python3-pyparsing-2.4.7-12.fc37.noarch python3-pysocks-1.7.1-14.fc37.noarch python3-pytz-2022.1-2.fc37.noarch python3-requests-2.27.1-5.fc37.noarch python3-rpm-generators-13-1.fc37.noarch python3-rpm-macros-3.11-1.fc37.noarch python3-setuptools-62.6.0-1.fc37.noarch python3-six-1.16.0-7.fc37.noarch python3-snowballstemmer-2.2.0-1.fc37.noarch python3-sphinx-1:4.5.0-3.fc37.noarch python3-sphinx-theme-alabaster-0.7.12-15.fc37.noarch python3-sphinxcontrib-applehelp-1.0.2-9.fc37.noarch python3-sphinxcontrib-devhelp-1.0.2-9.fc37.noarch python3-sphinxcontrib-htmlhelp-2.0.0-6.fc37.noarch python3-sphinxcontrib-jsmath-1.0.1-17.fc37.noarch python3-sphinxcontrib-qthelp-1.0.3-10.fc37.noarch python3-sphinxcontrib-serializinghtml-1.1.5-5.fc37.noarch python3-urllib3-1.26.9-3.fc37.noarch python3-werkzeug-2.0.3-2.fc37.noarch sqlcipher-4.4.3-4.fc36.x86_64 sqlcipher-devel-4.4.3-4.fc36.x86_64 sqlite-3.39.0-1.fc37.x86_64 sqlite-devel-3.39.0-1.fc37.x86_64 ``` Can you please have a look? Thank you.
{ "url": "https://api.github.com/repos/coleifer/peewee/issues/2591/reactions", "total_count": 0, "+1": 0, "-1": 0, "laugh": 0, "hooray": 0, "confused": 0, "heart": 0, "rocket": 0, "eyes": 0 }
https://api.github.com/repos/coleifer/peewee/issues/2591/timeline
null
completed
null
null
https://api.github.com/repos/coleifer/peewee/issues/2590
https://api.github.com/repos/coleifer/peewee
https://api.github.com/repos/coleifer/peewee/issues/2590/labels{/name}
https://api.github.com/repos/coleifer/peewee/issues/2590/comments
https://api.github.com/repos/coleifer/peewee/issues/2590/events
https://github.com/coleifer/peewee/pull/2590
1,300,519,555
PR_kwDOAA7yGM47Lvyk
2,590
Update variable name to match CTE
{ "login": "genchev99", "id": 40357617, "node_id": "MDQ6VXNlcjQwMzU3NjE3", "avatar_url": "https://avatars.githubusercontent.com/u/40357617?v=4", "gravatar_id": "", "url": "https://api.github.com/users/genchev99", "html_url": "https://github.com/genchev99", "followers_url": "https://api.github.com/users/genchev99/followers", "following_url": "https://api.github.com/users/genchev99/following{/other_user}", "gists_url": "https://api.github.com/users/genchev99/gists{/gist_id}", "starred_url": "https://api.github.com/users/genchev99/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/genchev99/subscriptions", "organizations_url": "https://api.github.com/users/genchev99/orgs", "repos_url": "https://api.github.com/users/genchev99/repos", "events_url": "https://api.github.com/users/genchev99/events{/privacy}", "received_events_url": "https://api.github.com/users/genchev99/received_events", "type": "User", "site_admin": false }
[]
closed
false
null
[]
null
[ "Thanks!" ]
"2022-07-11T10:33:55"
"2022-07-11T12:01:42"
"2022-07-11T12:01:34"
CONTRIBUTOR
null
null
{ "url": "https://api.github.com/repos/coleifer/peewee/issues/2590/reactions", "total_count": 0, "+1": 0, "-1": 0, "laugh": 0, "hooray": 0, "confused": 0, "heart": 0, "rocket": 0, "eyes": 0 }
https://api.github.com/repos/coleifer/peewee/issues/2590/timeline
null
null
false
{ "url": "https://api.github.com/repos/coleifer/peewee/pulls/2590", "html_url": "https://github.com/coleifer/peewee/pull/2590", "diff_url": "https://github.com/coleifer/peewee/pull/2590.diff", "patch_url": "https://github.com/coleifer/peewee/pull/2590.patch", "merged_at": "2022-07-11T12:01:34" }
https://api.github.com/repos/coleifer/peewee/issues/2589
https://api.github.com/repos/coleifer/peewee
https://api.github.com/repos/coleifer/peewee/issues/2589/labels{/name}
https://api.github.com/repos/coleifer/peewee/issues/2589/comments
https://api.github.com/repos/coleifer/peewee/issues/2589/events
https://github.com/coleifer/peewee/issues/2589
1,299,968,799
I_kwDOAA7yGM5Ne_Mf
2,589
InterfaceError: connection already closed
{ "login": "Olegt0rr", "id": 25399456, "node_id": "MDQ6VXNlcjI1Mzk5NDU2", "avatar_url": "https://avatars.githubusercontent.com/u/25399456?v=4", "gravatar_id": "", "url": "https://api.github.com/users/Olegt0rr", "html_url": "https://github.com/Olegt0rr", "followers_url": "https://api.github.com/users/Olegt0rr/followers", "following_url": "https://api.github.com/users/Olegt0rr/following{/other_user}", "gists_url": "https://api.github.com/users/Olegt0rr/gists{/gist_id}", "starred_url": "https://api.github.com/users/Olegt0rr/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/Olegt0rr/subscriptions", "organizations_url": "https://api.github.com/users/Olegt0rr/orgs", "repos_url": "https://api.github.com/users/Olegt0rr/repos", "events_url": "https://api.github.com/users/Olegt0rr/events{/privacy}", "received_events_url": "https://api.github.com/users/Olegt0rr/received_events", "type": "User", "site_admin": false }
[]
closed
false
null
[]
null
[ "Since it passed this part of code as `False`\r\n```python\r\ndef cursor(self, commit=None):\r\n if self.is_closed():\r\n if self.autoconnect:\r\n self.connect()\r\n else:\r\n raise InterfaceError('Error, database connection not opened.')\r\n ...\r\n```\r\n\r\nIt seems that `self.is_closed()` returns wrong value", "Can you provide a short reproduction of the issue?", "The reproduction can't be short, cause I'm using Docker Swarm and it seems to be killing idle connections between nodes. At least I can't explain these connectivity issues any other way.\r\n\r\nBut anyway peewee should reconnect properly in this situation.\r\n", ">It seems that self.is_closed() returns wrong value\r\n\r\n`is_closed()` refers to the presence or absence of a connection -- but does not indicate the health of that connection.\r\n\r\n>and it seems to be killing idle connections between nodes\r\n\r\nIf this is, in fact, what is happening, then you probably want to review your use of connections -- especially the pool (which implies potential long-idle connections if you have low traffic to the db).\r\n\r\nDo you have a way to reliably detect when a connection has been closed? Check the code for `playhouse.pool._PooledPostgresqlDatabase._is_closed()`. When a connection is checked-out from the connection pool, the pool will use the above to test whether the connection is live and usable. This means that if you are checking out a connection from the pool (by using `db.connect()`), Peewee checks to see if that connection can be used before returning it to you. So you may want to review your connection management, specifically when you check-out and return conns to the pool.\r\n\r\nIf the above check is *not* detecting the \"connection already closed\" error, however (though this seems very unlikely to me) you can try subclassing and extending the `PooledPostgresqlExtDatabase` with a better check.\r\n\r\nMy sense, however, is that you're probably checking out connections and then letting them sit idle for a long time without returning them to the pool. Thus they never receive the health checks.\r\n\r\nLastly, Peewee does not automatically reconnect upon receiving this InterfaceError.", "Oh, you can also use `db.is_connection_usable()`, which has db-specific implementations for checking whether the underlying connection is in good shape.", "It's not clear. Just read the texts\r\n\r\nFirst you're checking `is_closed` and receive False. It means NOT CLOSED.\r\nThen you're trying to execute statement and receive `connection already closed`. It means it CLOSED.\r\n\r\nIf the connection is unusable, why don't you check `db.is_connection_usable()` with autoconnect option? \r\n\r\n```python\r\ndef cursor(self, commit=None):\r\n if self.is_connection_usable():\r\n if self.autoconnect:\r\n self.connect()\r\n else:\r\n raise InterfaceError('Error, database connection not opened.')\r\n ...\r\n```", "`is_closed()` refers to the internal state of Peewee -- whether we have a connection or not. I get that it's confusing, but we also don't want to just blindly autoconnect in the event that the connection is killed at some random time -- what if you were in the middle of a transaction, or had uncommitted changes?\r\n\r\nSimilarly, `autoconnect` does not refer to automatically reconnecting in the event of some error -- rather it means that you don't have to explicitly call `connect()` when you want to start querying the database.\r\n\r\nWe don't check whether the connection is usable because that would add overhead to every single query executed by Peewee. Internally Peewee gets a cursor for each query it executes. The approach taken by peewee is to open the connection and keep it until `close()` is called. This is slightly different for the pool -- the pool will obviously retain connections and check whether they are usable only when they are initially checked-out.\r\n\r\nAs I stated earlier, I suggest checking up on your use of connections." ]
"2022-07-10T17:04:03"
"2022-07-14T12:34:30"
"2022-07-11T15:40:58"
NONE
null
Autoconnect is not working :( ## Code ```python from playhouse.pool import PooledPostgresqlExtDatabase database = PooledPostgresqlExtDatabase( ... autoconnect=True, ) ``` ## Traceback ```python InterfaceError: connection already closed ... File "peewee.py", line 6609, in get_or_create return query.get(), False File "peewee.py", line 7024, in get return clone.execute(database)[0] File "peewee.py", line 1927, in inner return method(self, database, *args, **kwargs) File "peewee.py", line 1998, in execute return self._execute(database) File "peewee.py", line 2171, in _execute cursor = database.execute(self) File "playhouse/postgres_ext.py", line 494, in execute cursor = self.execute_sql(sql, params, commit=commit) File "peewee.py", line 3204, in execute_sql self.commit() File "peewee.py", line 2970, in __exit__ reraise(new_type, new_type(exc_value, *exc_args), traceback) File "peewee.py", line 191, in reraise raise value.with_traceback(tb) File "peewee.py", line 3195, in execute_sql cursor = self.cursor(commit) File "playhouse/postgres_ext.py", line 484, in cursor return self._state.conn.cursor() ``` ## Versions ``` psycopg2==2.9.3 peewee==3.15.0 ```
{ "url": "https://api.github.com/repos/coleifer/peewee/issues/2589/reactions", "total_count": 0, "+1": 0, "-1": 0, "laugh": 0, "hooray": 0, "confused": 0, "heart": 0, "rocket": 0, "eyes": 0 }
https://api.github.com/repos/coleifer/peewee/issues/2589/timeline
null
completed
null
null
https://api.github.com/repos/coleifer/peewee/issues/2588
https://api.github.com/repos/coleifer/peewee
https://api.github.com/repos/coleifer/peewee/issues/2588/labels{/name}
https://api.github.com/repos/coleifer/peewee/issues/2588/comments
https://api.github.com/repos/coleifer/peewee/issues/2588/events
https://github.com/coleifer/peewee/issues/2588
1,297,840,905
I_kwDOAA7yGM5NW3sJ
2,588
Snowflake Support
{ "login": "sfc-gh-pmonteiro", "id": 82128106, "node_id": "MDQ6VXNlcjgyMTI4MTA2", "avatar_url": "https://avatars.githubusercontent.com/u/82128106?v=4", "gravatar_id": "", "url": "https://api.github.com/users/sfc-gh-pmonteiro", "html_url": "https://github.com/sfc-gh-pmonteiro", "followers_url": "https://api.github.com/users/sfc-gh-pmonteiro/followers", "following_url": "https://api.github.com/users/sfc-gh-pmonteiro/following{/other_user}", "gists_url": "https://api.github.com/users/sfc-gh-pmonteiro/gists{/gist_id}", "starred_url": "https://api.github.com/users/sfc-gh-pmonteiro/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/sfc-gh-pmonteiro/subscriptions", "organizations_url": "https://api.github.com/users/sfc-gh-pmonteiro/orgs", "repos_url": "https://api.github.com/users/sfc-gh-pmonteiro/repos", "events_url": "https://api.github.com/users/sfc-gh-pmonteiro/events{/privacy}", "received_events_url": "https://api.github.com/users/sfc-gh-pmonteiro/received_events", "type": "User", "site_admin": false }
[]
closed
false
null
[]
null
[ "http://docs.peewee-orm.com/en/latest/peewee/database.html#adding-a-new-database-driver\r\n\r\nLooks like there's a driver with dbapi support so hopefully it will be rather easy.\r\n\r\nhttps://docs.snowflake.com/en/user-guide/python-connector.html" ]
"2022-07-07T17:46:48"
"2022-07-07T17:59:24"
"2022-07-07T17:52:01"
NONE
null
I really like this ORM but it lacks Snowflake support. I'm a python seasoned developer and willing to help Peewee support Snowflake. What is the best way to support this project? Is there any documentation on adding support to new DBs?
{ "url": "https://api.github.com/repos/coleifer/peewee/issues/2588/reactions", "total_count": 0, "+1": 0, "-1": 0, "laugh": 0, "hooray": 0, "confused": 0, "heart": 0, "rocket": 0, "eyes": 0 }
https://api.github.com/repos/coleifer/peewee/issues/2588/timeline
null
completed
null
null
https://api.github.com/repos/coleifer/peewee/issues/2587
https://api.github.com/repos/coleifer/peewee
https://api.github.com/repos/coleifer/peewee/issues/2587/labels{/name}
https://api.github.com/repos/coleifer/peewee/issues/2587/comments
https://api.github.com/repos/coleifer/peewee/issues/2587/events
https://github.com/coleifer/peewee/issues/2587
1,297,116,231
I_kwDOAA7yGM5NUGxH
2,587
sqlite_ext / apsw bm25 search AND regex select
{ "login": "inktrap", "id": 1449471, "node_id": "MDQ6VXNlcjE0NDk0NzE=", "avatar_url": "https://avatars.githubusercontent.com/u/1449471?v=4", "gravatar_id": "", "url": "https://api.github.com/users/inktrap", "html_url": "https://github.com/inktrap", "followers_url": "https://api.github.com/users/inktrap/followers", "following_url": "https://api.github.com/users/inktrap/following{/other_user}", "gists_url": "https://api.github.com/users/inktrap/gists{/gist_id}", "starred_url": "https://api.github.com/users/inktrap/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/inktrap/subscriptions", "organizations_url": "https://api.github.com/users/inktrap/orgs", "repos_url": "https://api.github.com/users/inktrap/repos", "events_url": "https://api.github.com/users/inktrap/events{/privacy}", "received_events_url": "https://api.github.com/users/inktrap/received_events", "type": "User", "site_admin": false }
[]
closed
false
null
[]
null
[ "Facetting is typically done on the set of search results anyways, so this seems like an application for `in_`, may it be a matching regex or some attribute value that is more commonly used for facetting.\r\n\r\nI haven't looked at it in detail but I guess sqlite_ext does a phrase search (and won't tokenize my input and just assume some operator) and thus I have to query it per-term (which is a good thing) and combine the results. But all of that is out of peewee's scope. The point is that I'll have to combine/process the search results anyways if I want a query language with operators.", "You don't need to re-select, just write: \r\n\r\n```\r\nquery = (ItemIndex\r\n .search_bm25(search_query, with_score=True)\r\n .where(ItemIndex.content.regexp(search_regex)))\r\n```\r\n\r\nAlso, Peewee provides a `regexp_function` already and the parameter is a boolean - not a callable.\r\n\r\nExample:\r\n\r\n```python\r\ndb = SqliteExtDatabase(':memory:', regexp_function=True)\r\n\r\nclass Idx(FTS5Model):\r\n name = SearchField(unindexed=True)\r\n content = SearchField()\r\n class Meta:\r\n database = db\r\n\r\ndb.create_tables([Idx])\r\n\r\nIdx.insert_many([\r\n ('item1', 'item1 alpha'),\r\n ('item2', 'item2 beta'),\r\n ('item1-1', 'item1-1 alpha epsilon'),\r\n ('item1-2', 'item1-2 alpha sigma'),\r\n ('item1-3', 'item1-3 alpha rho'),\r\n ('item1-4', 'item1-4 alpha tau'),\r\n]).execute()\r\n\r\n\r\nquery = (Idx\r\n .search_bm25('alpha', with_score=True)\r\n .where(Idx.content.regexp('item1-[123]')))\r\nfor row in query:\r\n print(row.name, row.content)\r\n\r\n# item1-1 item1-1 alpha epsilon\r\n# item1-2 item1-2 alpha sigma\r\n# item1-3 item1-3 alpha rho\r\n```", "Yes, this is clear to me now because i read more docs. Thanks for the examples and your help! Appreciate it!" ]
"2022-07-07T09:47:58"
"2022-07-11T18:50:13"
"2022-07-07T12:57:10"
NONE
null
I would like to combine a ranked search via sqlite-ext (bm25) on a set of documents where the content matches a regexp. It is basicly a filter, not only documents that match the search *term* are returned, but those that match the *regex* **and** (then) the search term. Suppose I have this model: ``` from playhouse.sqlite_ext import FTS5Model, RowIDField, SearchField class ItemIndex(FTS5Model): rowid = RowIDField() content = SearchField() class Meta: database = db options = {"tokenize": "porter"} ``` And a regex function like this: ``` import re from playhouse.sqlite_ext import (SqliteExtDatabase) def search(expr, item): return re.search(expr, item) is not None db = SqliteExtDatabase("db.db", regexp_function=search) ``` Then I'll just create the table and while the functions work individually: ``` query = ItemIndex.search_bm25(search_query, with_score=True) query = ItemIndex.select().where(ItemIndex.content.regexp(search_regex)) ``` I can't chain or combine them. Seems like the search result doesn't support select and select result don't support searches. ``` ItemIndex.search_bm25(search_query, with_score=True) .select() .where(ItemIndex.content.regexp(search_regex)) ``` ``` peewee.OperationalError: near "FROM": syntax error ``` This is similar with apsw. And the other way around I'll just get `AttributeError: 'ModelSelect' object has no attribute 'search_bm25'` which I expected. I tried to use `intersect` but then I'll get different error messages, depending on wether I'll turn scoring off or not and depending on calling `execute()` of the search query before intersecting. I don't think intersect is ment to work with search results but with another select-object anyways. So the last idea is to get the IDs via search, then select via regex and then refine via `.in_(value)` where `value` is the list of IDs. Then somehow get the ranking info back. That seems inefficient but doable. How would you approach this?
{ "url": "https://api.github.com/repos/coleifer/peewee/issues/2587/reactions", "total_count": 0, "+1": 0, "-1": 0, "laugh": 0, "hooray": 0, "confused": 0, "heart": 0, "rocket": 0, "eyes": 0 }
https://api.github.com/repos/coleifer/peewee/issues/2587/timeline
null
completed
null
null
https://api.github.com/repos/coleifer/peewee/issues/2586
https://api.github.com/repos/coleifer/peewee
https://api.github.com/repos/coleifer/peewee/issues/2586/labels{/name}
https://api.github.com/repos/coleifer/peewee/issues/2586/comments
https://api.github.com/repos/coleifer/peewee/issues/2586/events
https://github.com/coleifer/peewee/issues/2586
1,295,611,195
I_kwDOAA7yGM5NOXU7
2,586
Select-query side effect
{ "login": "pylipp", "id": 10617122, "node_id": "MDQ6VXNlcjEwNjE3MTIy", "avatar_url": "https://avatars.githubusercontent.com/u/10617122?v=4", "gravatar_id": "", "url": "https://api.github.com/users/pylipp", "html_url": "https://github.com/pylipp", "followers_url": "https://api.github.com/users/pylipp/followers", "following_url": "https://api.github.com/users/pylipp/following{/other_user}", "gists_url": "https://api.github.com/users/pylipp/gists{/gist_id}", "starred_url": "https://api.github.com/users/pylipp/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/pylipp/subscriptions", "organizations_url": "https://api.github.com/users/pylipp/orgs", "repos_url": "https://api.github.com/users/pylipp/repos", "events_url": "https://api.github.com/users/pylipp/events{/privacy}", "received_events_url": "https://api.github.com/users/pylipp/received_events", "type": "User", "site_admin": false }
[]
closed
false
null
[]
null
[ "When you write:\r\n\r\n`return selection or model.select()`\r\n\r\nPython needs to determine if `selection` is truth-y, so it calls its `__len__()` method to see if it's empty. This causes the query to be evaluated. The better way to do this is:\r\n\r\n`return selection if selection is not None else model.select()`" ]
"2022-07-06T10:19:50"
"2022-07-06T12:31:13"
"2022-07-06T12:31:12"
NONE
null
In my application I have a function that accepts an optional `ModelSelect` argument. If it is not set, `model.select()` shall be used. The line `selection or model.select()` causes an SQL query to be executed. Why is this (side) effect? I looked at the [docs](http://docs.peewee-orm.com/en/latest/peewee/querying.html#selecting-multiple-records) but could not find any hint. ```python from peewee import SqliteDatabase, CharField, Model import logging logger = logging.getLogger("peewee") logger.addHandler(logging.StreamHandler()) logger.setLevel(logging.DEBUG) db = SqliteDatabase(":memory:") class User(Model): name = CharField() class Meta: database = db def some_logic(model, selection=None): return selection or model.select() def main(): db.create_tables([User]) User.insert_many([{"name": n} for n in "abcdef"]).execute() logger.warning(0) selection = User.select() logger.warning(1) selection = some_logic(User, selection) logger.warning(2) main() ``` The log output is ``` ('CREATE TABLE IF NOT EXISTS "user" ("id" INTEGER NOT NULL PRIMARY KEY, "name" VARCHAR(255) NOT NULL)', []) ('INSERT INTO "user" ("name") VALUES (?), (?), (?), (?), (?), (?)', ['a', 'b', 'c', 'd', 'e', 'f']) 0 1 ('SELECT "t1"."id", "t1"."name" FROM "user" AS "t1"', []) 2 ```
{ "url": "https://api.github.com/repos/coleifer/peewee/issues/2586/reactions", "total_count": 0, "+1": 0, "-1": 0, "laugh": 0, "hooray": 0, "confused": 0, "heart": 0, "rocket": 0, "eyes": 0 }
https://api.github.com/repos/coleifer/peewee/issues/2586/timeline
null
completed
null
null
https://api.github.com/repos/coleifer/peewee/issues/2585
https://api.github.com/repos/coleifer/peewee
https://api.github.com/repos/coleifer/peewee/issues/2585/labels{/name}
https://api.github.com/repos/coleifer/peewee/issues/2585/comments
https://api.github.com/repos/coleifer/peewee/issues/2585/events
https://github.com/coleifer/peewee/pull/2585
1,292,266,047
PR_kwDOAA7yGM46wHA9
2,585
Update database.rst
{ "login": "inktrap", "id": 1449471, "node_id": "MDQ6VXNlcjE0NDk0NzE=", "avatar_url": "https://avatars.githubusercontent.com/u/1449471?v=4", "gravatar_id": "", "url": "https://api.github.com/users/inktrap", "html_url": "https://github.com/inktrap", "followers_url": "https://api.github.com/users/inktrap/followers", "following_url": "https://api.github.com/users/inktrap/following{/other_user}", "gists_url": "https://api.github.com/users/inktrap/gists{/gist_id}", "starred_url": "https://api.github.com/users/inktrap/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/inktrap/subscriptions", "organizations_url": "https://api.github.com/users/inktrap/orgs", "repos_url": "https://api.github.com/users/inktrap/repos", "events_url": "https://api.github.com/users/inktrap/events{/privacy}", "received_events_url": "https://api.github.com/users/inktrap/received_events", "type": "User", "site_admin": false }
[]
closed
false
null
[]
null
[ "Thanks, I merged a roughly equivalent patch." ]
"2022-07-03T10:18:24"
"2022-07-11T18:49:14"
"2022-07-05T13:46:21"
NONE
null
If the apsw **reference is rendered,** the text reads (emphasis mine): > Peewee also comes with an alternate SQLite database that uses **apsw, an advanced sqlite driver**, an advanced Python SQLite driver. I know that the idea is to describe the reference without relying on the self-description of the reference, but in this case they are (almost)identical. Another way would be to shorten the ref to just apsw, if restructured text permits that.
{ "url": "https://api.github.com/repos/coleifer/peewee/issues/2585/reactions", "total_count": 0, "+1": 0, "-1": 0, "laugh": 0, "hooray": 0, "confused": 0, "heart": 0, "rocket": 0, "eyes": 0 }
https://api.github.com/repos/coleifer/peewee/issues/2585/timeline
null
null
false
{ "url": "https://api.github.com/repos/coleifer/peewee/pulls/2585", "html_url": "https://github.com/coleifer/peewee/pull/2585", "diff_url": "https://github.com/coleifer/peewee/pull/2585.diff", "patch_url": "https://github.com/coleifer/peewee/pull/2585.patch", "merged_at": null }
https://api.github.com/repos/coleifer/peewee/issues/2584
https://api.github.com/repos/coleifer/peewee
https://api.github.com/repos/coleifer/peewee/issues/2584/labels{/name}
https://api.github.com/repos/coleifer/peewee/issues/2584/comments
https://api.github.com/repos/coleifer/peewee/issues/2584/events
https://github.com/coleifer/peewee/issues/2584
1,285,880,995
I_kwDOAA7yGM5MpPyj
2,584
CockroachDB is not automatically setting server_version in all cases
{ "login": "arel", "id": 153497, "node_id": "MDQ6VXNlcjE1MzQ5Nw==", "avatar_url": "https://avatars.githubusercontent.com/u/153497?v=4", "gravatar_id": "", "url": "https://api.github.com/users/arel", "html_url": "https://github.com/arel", "followers_url": "https://api.github.com/users/arel/followers", "following_url": "https://api.github.com/users/arel/following{/other_user}", "gists_url": "https://api.github.com/users/arel/gists{/gist_id}", "starred_url": "https://api.github.com/users/arel/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/arel/subscriptions", "organizations_url": "https://api.github.com/users/arel/orgs", "repos_url": "https://api.github.com/users/arel/repos", "events_url": "https://api.github.com/users/arel/events{/privacy}", "received_events_url": "https://api.github.com/users/arel/received_events", "type": "User", "site_admin": false }
[]
closed
false
null
[]
null
[ "This is now resolve, thanks for the report. In the meantime you can alternatively use the database itself as a context-manager, which ensures a connection is created and wraps the block in a transaction (assuming this is for module-scope type initialization or whatever), e.g.\r\n\r\n```python\r\nwith db:\r\n ...\r\n```" ]
"2022-06-27T14:19:03"
"2022-06-27T17:23:59"
"2022-06-27T17:22:02"
NONE
null
I am occasionally seeing the error message below that is not especially self-explanatory. ``` 158 def atomic(self, system_time=None, priority=None): --> 159 if self.server_version < NESTED_TX_MIN_VERSION: 160 return _crdb_atomic(self, system_time, priority) 161 return super(CockroachDatabase, self).atomic(system_time, priority) TypeError: '<' not supported between instances of 'NoneType' and 'int' ``` I am using CockroachDB. The `server_version` is set when a connection is opened, which `atomic()` normally does. But in line 159 of `cockroachdb.py`, it's assumed `server_version` has already been set before calling `super(...).atomic()`. https://github.com/coleifer/peewee/blob/49792e4eac5268c752375d34bbb63828708b592b/playhouse/cockroachdb.py#L159 To reproduce the error: ```python from playhouse.db_url import connect db = connect("cockroachdb://username:password@gcp-us-east1.cockroachlabs.cloud:26257/defaultdb...") with db.atomic(): # raises error pass ``` I do not see this error if I use the `PostgresqlDatabase` class (e.g., when I change the schema of the datatbase url only). ```python from playhouse.db_url import connect db = connect("postgresql://username:password@gcp-us-east1.cockroachlabs.cloud:26257/defaultdb...") # same other than schema with db.atomic(): # no error pass ``` I am using peewee version `3.14.10`.
{ "url": "https://api.github.com/repos/coleifer/peewee/issues/2584/reactions", "total_count": 0, "+1": 0, "-1": 0, "laugh": 0, "hooray": 0, "confused": 0, "heart": 0, "rocket": 0, "eyes": 0 }
https://api.github.com/repos/coleifer/peewee/issues/2584/timeline
null
completed
null
null
https://api.github.com/repos/coleifer/peewee/issues/2583
https://api.github.com/repos/coleifer/peewee
https://api.github.com/repos/coleifer/peewee/issues/2583/labels{/name}
https://api.github.com/repos/coleifer/peewee/issues/2583/comments
https://api.github.com/repos/coleifer/peewee/issues/2583/events
https://github.com/coleifer/peewee/issues/2583
1,285,844,119
I_kwDOAA7yGM5MpGyX
2,583
Rollback doesn't work inside of Jupyter Notebook
{ "login": "NAN-CForadas", "id": 98823081, "node_id": "U_kgDOBePrqQ", "avatar_url": "https://avatars.githubusercontent.com/u/98823081?v=4", "gravatar_id": "", "url": "https://api.github.com/users/NAN-CForadas", "html_url": "https://github.com/NAN-CForadas", "followers_url": "https://api.github.com/users/NAN-CForadas/followers", "following_url": "https://api.github.com/users/NAN-CForadas/following{/other_user}", "gists_url": "https://api.github.com/users/NAN-CForadas/gists{/gist_id}", "starred_url": "https://api.github.com/users/NAN-CForadas/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/NAN-CForadas/subscriptions", "organizations_url": "https://api.github.com/users/NAN-CForadas/orgs", "repos_url": "https://api.github.com/users/NAN-CForadas/repos", "events_url": "https://api.github.com/users/NAN-CForadas/events{/privacy}", "received_events_url": "https://api.github.com/users/NAN-CForadas/received_events", "type": "User", "site_admin": false }
[]
closed
false
null
[]
null
[ "Your error handling code looks good to me. I cannot think of what might be causing this, as it seems to be working fine on my side:\r\n\r\n![scr1656348894883](https://user-images.githubusercontent.com/119974/175994871-73e0a6a4-ebbc-4470-a085-b67210e402ae.png)\r\n\r\nIt also works when swapping `PooledPostgresDatabase`.", "moving **txn.rollback()** to the first line under the **execpt:** fixed it for me.\r\n```\r\ntry:\r\n pass\r\nexcept Exception as exc:\r\n txn.rollback()\r\n e = traceback.format_exc()\r\n print(f\"<p>Error: {exc}</p>{e}\")\r\n query_failed = True\r\n```" ]
"2022-06-27T13:53:27"
"2022-06-29T18:57:26"
"2022-06-27T16:56:04"
NONE
null
I keep getting ```cursor.execute(sql, params or ()) psycopg2.errors.InFailedSqlTransaction: current transaction is aborted, commands ignored until end of transaction block ``` even though I have queries inside try: except: blocks ``` def get_random_user(): with db.atomic() as txn: query_failed = False try: user = User.select().order_by(fn.Random()).limit(1).execute()[0] except: # catch *all* exceptions e = traceback.format_exc() print( "<p>Error: %s</p>" % e) txn.rollback() query_failed = True if query_failed: print('Get random user failed') else: return user print(get_random_user()) ``` The only way to reset the database from not issuing the error is to restart the Jupyter Notebook kernal and start from scratch. Any thoughts or ideas, I think I have the error trapping/rollback setup properly? Thank you
{ "url": "https://api.github.com/repos/coleifer/peewee/issues/2583/reactions", "total_count": 0, "+1": 0, "-1": 0, "laugh": 0, "hooray": 0, "confused": 0, "heart": 0, "rocket": 0, "eyes": 0 }
https://api.github.com/repos/coleifer/peewee/issues/2583/timeline
null
completed
null
null
https://api.github.com/repos/coleifer/peewee/issues/2582
https://api.github.com/repos/coleifer/peewee
https://api.github.com/repos/coleifer/peewee/issues/2582/labels{/name}
https://api.github.com/repos/coleifer/peewee/issues/2582/comments
https://api.github.com/repos/coleifer/peewee/issues/2582/events
https://github.com/coleifer/peewee/issues/2582
1,284,912,309
I_kwDOAA7yGM5MljS1
2,582
Weird query operator behavior
{ "login": "wpnbos", "id": 33165624, "node_id": "MDQ6VXNlcjMzMTY1NjI0", "avatar_url": "https://avatars.githubusercontent.com/u/33165624?v=4", "gravatar_id": "", "url": "https://api.github.com/users/wpnbos", "html_url": "https://github.com/wpnbos", "followers_url": "https://api.github.com/users/wpnbos/followers", "following_url": "https://api.github.com/users/wpnbos/following{/other_user}", "gists_url": "https://api.github.com/users/wpnbos/gists{/gist_id}", "starred_url": "https://api.github.com/users/wpnbos/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/wpnbos/subscriptions", "organizations_url": "https://api.github.com/users/wpnbos/orgs", "repos_url": "https://api.github.com/users/wpnbos/repos", "events_url": "https://api.github.com/users/wpnbos/events{/privacy}", "received_events_url": "https://api.github.com/users/wpnbos/received_events", "type": "User", "site_admin": false }
[]
closed
false
null
[]
null
[ "I have no idea what these screenshots are supposed to show. Post a self-contained, self-explanatory code snippet.", "Possibly this is to do with floating point precision. You need to use numeric / decimal field for prices.", "Confirmed this is floating point stuff.\r\n\r\n```\r\nIn [1]: from peewee import *\r\n\r\nIn [2]: db = PostgresqlDatabase('peewee_test')\r\n\r\nIn [3]: class K(Model):\r\n ...: price = FloatField()\r\n ...: name = TextField()\r\n ...: class Meta:\r\n ...: database = db\r\n ...: \r\n\r\nIn [4]: db.create_tables([K])\r\n\r\nIn [5]: K.create(price=123.45, name='12345')\r\nOut[5]: <K: 1>\r\n\r\nIn [6]: K.create(price=123.44, name='12344')\r\nOut[6]: <K: 2>\r\n\r\nIn [7]: K.create(price=123.46, name='12346')\r\nOut[7]: <K: 3>\r\n\r\nIn [8]: K.select().where(K.price < 123.45).tuples()[:]\r\nOut[8]: [(1, 123.45, '12345'), (2, 123.44, '12344')]\r\n\r\nIn [9]: K.select().where(K.price >= 123.45).tuples()[:]\r\nOut[9]: [(3, 123.46, '12346')]\r\n```\r\n\r\nNext time submit code like ^^", "> \r\n\r\nThanks a lot! I changed my FloatFields to DecimalFields and I can confirm that this remedied my issue. \r\n\r\nMy sincerest apologies for the lazy issue. I'll make sure to post self-contained, self-explanatory code snippets next time." ]
"2022-06-26T13:21:17"
"2022-06-26T14:43:23"
"2022-06-26T13:42:24"
NONE
null
<img width="482" alt="image" src="https://user-images.githubusercontent.com/33165624/175815958-5a702699-c45e-457b-9399-68daeff3c4d8.png"> <img width="476" alt="image" src="https://user-images.githubusercontent.com/33165624/175815980-dba5b463-a9c0-45d8-ae7c-f9e183621754.png"> It would seem the query operators here just don't work properly. I'm using a Postgres database, both fields are of type `real`.
{ "url": "https://api.github.com/repos/coleifer/peewee/issues/2582/reactions", "total_count": 0, "+1": 0, "-1": 0, "laugh": 0, "hooray": 0, "confused": 0, "heart": 0, "rocket": 0, "eyes": 0 }
https://api.github.com/repos/coleifer/peewee/issues/2582/timeline
null
completed
null
null
https://api.github.com/repos/coleifer/peewee/issues/2581
https://api.github.com/repos/coleifer/peewee
https://api.github.com/repos/coleifer/peewee/issues/2581/labels{/name}
https://api.github.com/repos/coleifer/peewee/issues/2581/comments
https://api.github.com/repos/coleifer/peewee/issues/2581/events
https://github.com/coleifer/peewee/issues/2581
1,276,480,600
I_kwDOAA7yGM5MFYxY
2,581
Possible bug with distinct count
{ "login": "sayanarijit", "id": 11632726, "node_id": "MDQ6VXNlcjExNjMyNzI2", "avatar_url": "https://avatars.githubusercontent.com/u/11632726?v=4", "gravatar_id": "", "url": "https://api.github.com/users/sayanarijit", "html_url": "https://github.com/sayanarijit", "followers_url": "https://api.github.com/users/sayanarijit/followers", "following_url": "https://api.github.com/users/sayanarijit/following{/other_user}", "gists_url": "https://api.github.com/users/sayanarijit/gists{/gist_id}", "starred_url": "https://api.github.com/users/sayanarijit/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/sayanarijit/subscriptions", "organizations_url": "https://api.github.com/users/sayanarijit/orgs", "repos_url": "https://api.github.com/users/sayanarijit/repos", "events_url": "https://api.github.com/users/sayanarijit/events{/privacy}", "received_events_url": "https://api.github.com/users/sayanarijit/received_events", "type": "User", "site_admin": false }
[]
closed
false
null
[]
null
[ "This is because Peewee wraps any query that executes a `.count()`, so the actual sql that peewee ends up executing looks like:\r\n\r\n```sql\r\n-- Post.select(Post.author_id).distinct().count()\r\nSELECT COUNT(1) FROM (\r\n SELECT DISTINCT \"t1\".\"user_id\" FROM \"tweet\" AS \"t1\"\r\n) AS \"_wrapped\"\r\n```\r\n\r\nThe second example, however, Peewee does not infer that there is important information it is supposed to capture inside the selected columns, and so we end up with:\r\n\r\n```sql\r\n-- Post.select(Post.author_id.distinct()).count()\r\nSELECT COUNT(1) FROM (SELECT 1 FROM \"tweet\" AS \"t1\") AS \"_wrapped\"\r\n```\r\n\r\nSo what you should do is either:\r\n\r\n* `Post.select(Post.author_id).distinct().count()`\r\n* `Post.select(fn.COUNT(Post.author_id.distinct())).scalar()`" ]
"2022-06-20T07:18:41"
"2022-06-20T14:26:28"
"2022-06-20T14:26:05"
NONE
null
I think we encountered a bug with the `.count()` method when applied on distinct column. To reproduce: ```python actual_qry = Post.select(Post.author_id).distinct() buggy_qry = Post.select(Post.author_id.distinct()) actual_qry.sql() == buggy_qry.sql() # True actual_qry.count() == buggy_qry.count() # False ```
{ "url": "https://api.github.com/repos/coleifer/peewee/issues/2581/reactions", "total_count": 1, "+1": 1, "-1": 0, "laugh": 0, "hooray": 0, "confused": 0, "heart": 0, "rocket": 0, "eyes": 0 }
https://api.github.com/repos/coleifer/peewee/issues/2581/timeline
null
completed
null
null
https://api.github.com/repos/coleifer/peewee/issues/2580
https://api.github.com/repos/coleifer/peewee
https://api.github.com/repos/coleifer/peewee/issues/2580/labels{/name}
https://api.github.com/repos/coleifer/peewee/issues/2580/comments
https://api.github.com/repos/coleifer/peewee/issues/2580/events
https://github.com/coleifer/peewee/issues/2580
1,275,666,732
I_kwDOAA7yGM5MCSEs
2,580
test_sqlite_isolation fails with Python 3.11
{ "login": "mgorny", "id": 110765, "node_id": "MDQ6VXNlcjExMDc2NQ==", "avatar_url": "https://avatars.githubusercontent.com/u/110765?v=4", "gravatar_id": "", "url": "https://api.github.com/users/mgorny", "html_url": "https://github.com/mgorny", "followers_url": "https://api.github.com/users/mgorny/followers", "following_url": "https://api.github.com/users/mgorny/following{/other_user}", "gists_url": "https://api.github.com/users/mgorny/gists{/gist_id}", "starred_url": "https://api.github.com/users/mgorny/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/mgorny/subscriptions", "organizations_url": "https://api.github.com/users/mgorny/orgs", "repos_url": "https://api.github.com/users/mgorny/repos", "events_url": "https://api.github.com/users/mgorny/events{/privacy}", "received_events_url": "https://api.github.com/users/mgorny/received_events", "type": "User", "site_admin": false }
[]
closed
false
null
[]
null
[ "I don't see anything in the python 3.11 changelog that looks promising, any ideas?", "I'm going to try bisecting it.", "And here it is:\r\n\r\nhttps://github.com/python/cpython/commit/3df0fc89bc2714f5ef03e36a926bc795dcd5e05a\r\n\r\n```\r\ncommit 3df0fc89bc2714f5ef03e36a926bc795dcd5e05a\r\nAuthor: Erlend Egeberg Aasland <erlend.aasland@innova.no>\r\nDate: Wed Aug 25 12:28:47 2021 +0200\r\n\r\n bpo-44976: Lazy creation of sqlite3 result rows (GH-27884)\r\n\r\n Modules/_sqlite/cursor.c | 84 +++++++++++++++++-------------------------------\r\n Modules/_sqlite/cursor.h | 3 --\r\n 2 files changed, 29 insertions(+), 58 deletions(-)\r\n```", "Thanks @mgorny very nice! My sense is that this may be a bug in `sqlite3` (cc @erlend-aasland if you see this).", "Can you report this on the CPython bug tracker? Please include a minimal (bare-bones) reproducer and as much information about your environment as possible.\r\n\r\nThanks!", "Sure I'll report and send a test if it's indeed a cpython issue. My sense is that it is but I'll let you know early next week ", "Great, thanks.\r\n\r\nFYI, beta 4 is over-due, but is currently on hold bco. release blockers. I've notified the RM about this (possible) issue; if we could pin-point a minimal reproducer pretty quick, we could add this to the beta 4 release blockers, so we'd get a fix in the upcoming (b4) release.\r\n\r\nI've tried to create a repro, but it's a little bit hard, since I've never used peewee, and I don't know its internal workings :( ", "No worries, I'll take a look tomorrow (Mon) morning and let you know asap. Thx!", "Welp, I have managed to reproduce and think it has something to do with cursor garbage collection. Something quite strange is going on that I haven't so far experienced in all the time I've used Python. Here's what I've observed with peewee:\r\n\r\n* Peewee test fails when run by itself\r\n* If I insert a breakpoint right before line 461 and then \"continue\", the test is passing(?)\r\n* If I insert a breakpoint right before line 461 and then \"next\", the test fails(?)\r\n* If I insert a time.sleep(1) right before line 461, the test fails\r\n\r\nExample of breakpoint + continue -> passing:\r\n\r\n```\r\n> /home/charles/tmp/py311/src/peewee/tests/db_tests.py(461)test_sqlite_isolation()\r\n-> curs = new_db.execute_sql('SELECT COUNT(*) FROM users')\r\n(Pdb) c\r\n.\r\n----------------------------------------------------------------------\r\nRan 1 test in 1.122s\r\n```\r\n\r\nExample of breakpoint + next -> fails again:\r\n\r\n```\r\n> /home/charles/tmp/py311/src/peewee/tests/db_tests.py(461)test_sqlite_isolation()\r\n-> curs = new_db.execute_sql('SELECT COUNT(*) FROM users')\r\n(Pdb) n\r\n> /home/charles/tmp/py311/src/peewee/tests/db_tests.py(462)test_sqlite_isolation()\r\n-> self.assertEqual(curs.fetchone()[0], 0)\r\n(Pdb) n\r\nTypeError: 'NoneType' object is not subscriptable\r\n```\r\n\r\nI cannot understand why it is passing when there's a breakpoint and then I select \"continue\" but using \"next\" makes it fail again!\r\n\r\n-------------------------------------------------------------------\r\n\r\n### Repro with stdlib sqlite3\r\n\r\nHere is my repro. It took a while to get it to reproduce, but I had a feeling it had something to do (possibly) with garbage collection or cursors. Keeping the cursors around in memory seems to cause the problem to manifest, but if you comment-out the line indicated below then the tests will pass. Note that Peewee doesn't do anything weird like keep the cursors in memory, this was just the first way I've been able to successfully reproduce the issue. @erlend-aasland \r\n\r\n```\r\nimport glob\r\nimport os\r\nimport sqlite3\r\n\r\nfilename = '/tmp/test.db'\r\nfor f in glob.glob(filename + '*'):\r\n os.unlink(f) # Cleanup anything from prev run(s).\r\n\r\nCURSORS = {}\r\n\r\ndef sql(conn, sql, *params):\r\n curs = conn.cursor()\r\n curs.execute(sql, params)\r\n CURSORS[id(sql)] = curs # COMMENT THIS OUT AND TEST WILL PASS.\r\n return curs\r\n\r\n# Set up database w/some sample rows. Peewee sets isolation-level to None as we\r\n# want to manage all transaction state ourselves, rather than use sqlite3's\r\n# somewhat unusual semantics.\r\ndb = sqlite3.connect(filename, isolation_level=None)\r\ndb.execute('create table users (id integer not null primary key, '\r\n 'username text not null)')\r\nsql(db, 'insert into users (username) values (?), (?), (?)', 'u1', 'u2', 'u3')\r\ndb.commit()\r\n\r\n# On 2nd connection verify rows are visible, then delete them.\r\nnew_db2 = sqlite3.connect(filename, isolation_level=None)\r\nassert sql(new_db2, 'select count(*) from users').fetchone()[0] == 3\r\nassert sql(new_db2, 'delete from users').rowcount == 3\r\n\r\n# Back in original connection, create 2 new users.\r\nsql(db, 'begin')\r\nsql(db, 'insert into users (username) values (?)', 'u4')\r\nsql(db, 'insert into users (username) values (?)', 'u5')\r\n\r\n# 2nd connection cannot see uncommitted changes.\r\n# NOTE: this is the line that fails.\r\nassert sql(new_db2, 'select count(*) from users').fetchone()[0] == 0\r\n\r\n# Original conn can see its own changes.\r\nassert sql(db, 'select count(*) from users').fetchone()[0] == 2\r\ndb.commit()\r\n\r\n# Now the 2nd conn can see the changes.\r\nassert sql(new_db2, 'select count(*) from users').fetchone()[0] == 2\r\n```\r\n\r\nLastly, just as a sanity-check, the above script runs without error on Python 2.7, 3.6, 3.9 and 3.10 -- it only fails on 3.11.0b3.", "@erlend-aasland - I've created a new ticket on the CPython issue tracker, linked above python/cpython#94028 . As I mentioned on the cpython issue, this really is bizarre:\r\n\r\n>What is doubly-confusing about this error is that, when the failure occurs, the SQL being executed should definitely NOT be returning `None` from the call to `fetchone()`. If the table did not exist, we would get a different error from Sqlite. If the table does exist and we just can't see any rows, then we should be getting `0` (or possibly `2`) as the test asserts. Instead, the `fetchone()` is returning `None`.", "Since this seems to me quite definitively a CPython / sqlite3 issue, I will close here.", "Thanks a lot for your investigations, @coleifer! I've marked python/cpython#94028 as a release blocker. Hopefully we'll find a solution within the next few days.", "I have a fix for this in python/cpython#94042. If you have the possibility to test the fix before I merge it, I'd appreciate it, @mgorny.", "I can confirm that applying this patch to cpython causes peewee tests to pass.", "(I've applied it on top of 3.11.0b3)", "Great, thank you!", "Thank you both @mgorny and @erlend-aasland for the help finding and fixing this.", "FYI, the fix has been merged and will appear in the upcoming beta 4 release." ]
"2022-06-18T05:05:45"
"2022-06-21T11:40:28"
"2022-06-20T14:45:58"
NONE
null
When running tests with Python 3.11.0b3, I get the following failure: ```pytb $ python runtests.py Unable to import APSW extension tests, skipping. Unable to import CockroachDB tests, skipping. Unable to import sqlite C extension tests, skipping. Unable to import mysql-connector, skipping mysql_ext tests. Unable to import postgres extension tests, skipping. Unable to import SQLCipher extension tests, skipping. Unable to import sqlite extension tests, skipping. .s.....................s..................................s.....................sss...........................................s.......ss.....................................s........ssss............................................s...................................s.........................................................................s..................................................................................................................................................................ssss........................................ss.............................s..................s...........ss............s...s.........s....ss......s..............s..............................................................ss.......................E............ssssssss.....................................sss.......ssssssssssssss.....s..................s..ss.............................. ====================================================================== ERROR: test_sqlite_isolation (tests.db_tests.TestSqliteIsolation.test_sqlite_isolation) ---------------------------------------------------------------------- Traceback (most recent call last): File "/tmp/peewee/tests/db_tests.py", line 461, in test_sqlite_isolation self.assertEqual(curs.fetchone()[0], 0) ~~~~~~~~~~~~~~~^^^ TypeError: 'NoneType' object is not subscriptable ---------------------------------------------------------------------- Ran 894 tests in 5.487s FAILED (errors=1, skipped=65) ```
{ "url": "https://api.github.com/repos/coleifer/peewee/issues/2580/reactions", "total_count": 0, "+1": 0, "-1": 0, "laugh": 0, "hooray": 0, "confused": 0, "heart": 0, "rocket": 0, "eyes": 0 }
https://api.github.com/repos/coleifer/peewee/issues/2580/timeline
null
completed
null
null
https://api.github.com/repos/coleifer/peewee/issues/2579
https://api.github.com/repos/coleifer/peewee
https://api.github.com/repos/coleifer/peewee/issues/2579/labels{/name}
https://api.github.com/repos/coleifer/peewee/issues/2579/comments
https://api.github.com/repos/coleifer/peewee/issues/2579/events
https://github.com/coleifer/peewee/issues/2579
1,274,565,143
I_kwDOAA7yGM5L-FIX
2,579
How to return one to many records on single query
{ "login": "duc-codecomplete", "id": 45530722, "node_id": "MDQ6VXNlcjQ1NTMwNzIy", "avatar_url": "https://avatars.githubusercontent.com/u/45530722?v=4", "gravatar_id": "", "url": "https://api.github.com/users/duc-codecomplete", "html_url": "https://github.com/duc-codecomplete", "followers_url": "https://api.github.com/users/duc-codecomplete/followers", "following_url": "https://api.github.com/users/duc-codecomplete/following{/other_user}", "gists_url": "https://api.github.com/users/duc-codecomplete/gists{/gist_id}", "starred_url": "https://api.github.com/users/duc-codecomplete/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/duc-codecomplete/subscriptions", "organizations_url": "https://api.github.com/users/duc-codecomplete/orgs", "repos_url": "https://api.github.com/users/duc-codecomplete/repos", "events_url": "https://api.github.com/users/duc-codecomplete/events{/privacy}", "received_events_url": "https://api.github.com/users/duc-codecomplete/received_events", "type": "User", "site_admin": false }
[]
closed
false
null
[]
null
[ "This is fundamental to how relational databases operate, I'm not sure what to tell you, it's not magic. The docs describe some approaches, however, which you may check out: http://docs.peewee-orm.com/en/latest/peewee/relationships.html#avoiding-the-n-1-problem" ]
"2022-06-17T04:51:27"
"2022-06-17T12:53:53"
"2022-06-17T12:53:53"
NONE
null
I have users and tweets table, 1 user has many tweets, 1 tweet belongs to an user ``` class User(BaseModel): class Meta: db_table = 'users' uuid = UUIDField(primary_key=True) email = CharField() class Tweet(BaseModel): class Meta: db_table = 'tweets' uuid = UUIDField(primary_key=True) content = TextField() user = ForeignKeyField(User, backref='tweets', related_name='tweets') ``` For get Tweet, it"s return with user, no problem `tweets = (Tweet.select().join(User)) ` ``` [ { "uuid": "74dbadc6-7fa9-44cf-92cc-236f4605721f", "content": "meow", "user": { "uuid": "5bb50b91-c7da-4b25-8f9c-2ffb39d4235b", "email": "duc.nguyen@codecomplete.jp" } }, { "uuid": "a4da5282-6f5f-4ad9-aec6-d8813ba1f2e8", "content": "hiss", "user": { "uuid": "5bb50b91-c7da-4b25-8f9c-2ffb39d4235b", "email": "duc.nguyen@codecomplete.jp" } }, { "uuid": "556748ee-9ac8-4ed0-9dac-0b760ae4349b", "content": "purr", "user": { "uuid": "5bb50b91-c7da-4b25-8f9c-2ffb39d4235b", "email": "duc.nguyen@codecomplete.jp" } }, { "uuid": "e8ba2c18-59ac-4968-98e0-e4ce58ee5094", "content": "woof", "user": { "uuid": "6835d471-acd9-46d4-b73c-c6ccab91d547", "email": "duc.nguyen1@codecomplete.jp" } }, { "uuid": "7584c092-906d-41e3-84a0-ee6b8f3d88f9", "content": "whine", "user": { "uuid": "6835d471-acd9-46d4-b73c-c6ccab91d547", "email": "duc.nguyen1@codecomplete.jp" } } ] ``` but when I try to get all user with tweets, it"s not working `users = User.select(User, Tweet).join(Tweet) ` ``` [ { "uuid": "5bb50b91-c7da-4b25-8f9c-2ffb39d4235b", "email": "duc.nguyen@codecomplete.jp" }, { "uuid": "5bb50b91-c7da-4b25-8f9c-2ffb39d4235b", "email": "duc.nguyen@codecomplete.jp" }, { "uuid": "5bb50b91-c7da-4b25-8f9c-2ffb39d4235b", "email": "duc.nguyen@codecomplete.jp" }, { "uuid": "6835d471-acd9-46d4-b73c-c6ccab91d547", "email": "duc.nguyen1@codecomplete.jp" }, { "uuid": "6835d471-acd9-46d4-b73c-c6ccab91d547", "email": "duc.nguyen1@codecomplete.jp" } ] ``` my expect: ``` [ { "uuid": "5bb50b91-c7da-4b25-8f9c-2ffb39d4235b", "email": "duc.nguyen@codecomplete.jp", "tweets": [ { ... }, { ... } ] }, .... ] ```
{ "url": "https://api.github.com/repos/coleifer/peewee/issues/2579/reactions", "total_count": 0, "+1": 0, "-1": 0, "laugh": 0, "hooray": 0, "confused": 0, "heart": 0, "rocket": 0, "eyes": 0 }
https://api.github.com/repos/coleifer/peewee/issues/2579/timeline
null
completed
null
null
https://api.github.com/repos/coleifer/peewee/issues/2578
https://api.github.com/repos/coleifer/peewee
https://api.github.com/repos/coleifer/peewee/issues/2578/labels{/name}
https://api.github.com/repos/coleifer/peewee/issues/2578/comments
https://api.github.com/repos/coleifer/peewee/issues/2578/events
https://github.com/coleifer/peewee/issues/2578
1,270,082,911
I_kwDOAA7yGM5Ls-1f
2,578
local variable 'model_attr' referenced before assignment
{ "login": "marcpearson", "id": 17986835, "node_id": "MDQ6VXNlcjE3OTg2ODM1", "avatar_url": "https://avatars.githubusercontent.com/u/17986835?v=4", "gravatar_id": "", "url": "https://api.github.com/users/marcpearson", "html_url": "https://github.com/marcpearson", "followers_url": "https://api.github.com/users/marcpearson/followers", "following_url": "https://api.github.com/users/marcpearson/following{/other_user}", "gists_url": "https://api.github.com/users/marcpearson/gists{/gist_id}", "starred_url": "https://api.github.com/users/marcpearson/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/marcpearson/subscriptions", "organizations_url": "https://api.github.com/users/marcpearson/orgs", "repos_url": "https://api.github.com/users/marcpearson/repos", "events_url": "https://api.github.com/users/marcpearson/events{/privacy}", "received_events_url": "https://api.github.com/users/marcpearson/received_events", "type": "User", "site_admin": false }
[]
closed
false
null
[]
null
[ "I can't replicate the exception -- I agree that it looks like there may be a bug there, but I'm not sure how to trigger it. The following all work just fine:\r\n\r\n```python\r\nclass TestDjangoFilterRegression(ModelTestCase):\r\n requires = [User, Tweet]\r\n\r\n def test_django_filter_regression(self):\r\n a, b, c = [User.create(username=u) for u in 'abc']\r\n Tweet.create(user=a, content='a1')\r\n Tweet.create(user=a, content='a2')\r\n Tweet.create(user=b, content='b1')\r\n\r\n query = User.filter(username='a')\r\n self.assertEqual(sorted([u.username for u in query]), ['a'])\r\n\r\n query = User.filter(username__in=('a', 'c', 'x'))\r\n self.assertEqual(sorted([u.username for u in query]), ['a', 'c'])\r\n\r\n query = Tweet.filter(user__username='a')\r\n self.assertEqual(sorted([t.content for t in query]), ['a1', 'a2'])\r\n\r\n query = Tweet.filter(user__username__in=('a', 'c'))\r\n self.assertEqual(sorted([t.content for t in query]), ['a1', 'a2'])\r\n```", "I think you need to have 3 level relations like this\r\n\r\n```\r\nclass Hour(Model):\r\n project = ForeignKeyField(Project, backref=\"hours\")\r\n\r\nclass Project(Model):\r\n client = ForeignKeyField(Client, backref=\"projects\")\r\n\r\nclass Client(Model):\r\n```\r\n\r\nWhen i want to filter all the hours (of all projects) for a specific client, i can filter the hours with a Django criteria 'project__client=1' in previous version without error. The criteria is coming from the URL for a backend call\r\n\r\nI hope this will help you\r\n\r\n N.B I do my best to write in english, i'm a french speaker. Sorry if is not sound good ! \r\n\r\n\r\n\r\n\r\n", "I'm still unable to replicate the issue: https://github.com/coleifer/peewee/blob/master/tests/regressions.py#L1705-L1710 -- this is traversing 2 relationships. That unit test covers quite a few scenarios.\r\n\r\nIf you can produce a failing test in the above case, or write a new one that demonstrates the issue, I will gladly reopen.", "Could you give me some advise how to set the project to run tests. I'll take a look and try to reproduce the error. Thanks !", "A git checkout and executing «runtest.py regressions» seem to do the job. I will print a comment in every step to check if your regressions tests invoke every possible situation of convert_dict_to_node. Does it seem a good idea ?", "Presumably if you are able to replicate the exception locally with your own code, you can communicate to me what is different about it vs the tests, or how to modify the tests to replicate it...", "Finally figured it out, will post a fix shortly.", "Glad you found it ! You're right on. My query is using already joined relations too. Thanks for your help and the incoming release" ]
"2022-06-13T23:54:07"
"2022-06-16T17:02:31"
"2022-06-16T14:17:58"
NONE
null
Hi I updated my project to version 3.14.10 and receive this error. The error come from the convert_dict_to_node function. From my observation, i think the code is missing the assignation to model_attr in the for piece in key.split('__'): `def convert_dict_to_node(self, qdict): accum = [] joins = [] fks = (ForeignKeyField, BackrefAccessor) for key, value in sorted(qdict.items()): curr = self.model if '__' in key and key.rsplit('__', 1)[1] in DJANGO_MAP: key, op = key.rsplit('__', 1) op = DJANGO_MAP[op] elif value is None: op = DJANGO_MAP['is'] else: op = DJANGO_MAP['eq'] if '__' not in key: # Handle simplest case. This avoids joining over-eagerly when a # direct FK lookup is all that is required. model_attr = getattr(curr, key) else: for piece in key.split('__'): model_attr = getattr(curr, piece) <============================== Maybe this line is needed for dest, attr, _, _ in self._joins.get(curr, ()): if attr == piece or (isinstance(dest, ModelAlias) and dest.alias == piece): curr = dest break else: model_attr = getattr(curr, piece) if value is not None and isinstance(model_attr, fks): curr = model_attr.rel_model joins.append(model_attr) accum.append(op(model_attr, value)) return accum, joins` With this new line my code work as before with the version 2.10.2 Thanks in advance
{ "url": "https://api.github.com/repos/coleifer/peewee/issues/2578/reactions", "total_count": 0, "+1": 0, "-1": 0, "laugh": 0, "hooray": 0, "confused": 0, "heart": 0, "rocket": 0, "eyes": 0 }
https://api.github.com/repos/coleifer/peewee/issues/2578/timeline
null
completed
null
null
https://api.github.com/repos/coleifer/peewee/issues/2577
https://api.github.com/repos/coleifer/peewee
https://api.github.com/repos/coleifer/peewee/issues/2577/labels{/name}
https://api.github.com/repos/coleifer/peewee/issues/2577/comments
https://api.github.com/repos/coleifer/peewee/issues/2577/events
https://github.com/coleifer/peewee/issues/2577
1,268,083,091
I_kwDOAA7yGM5LlWmT
2,577
How get inserted row count from Model.insert_many() with postgres?
{ "login": "MichaelLan", "id": 9300072, "node_id": "MDQ6VXNlcjkzMDAwNzI=", "avatar_url": "https://avatars.githubusercontent.com/u/9300072?v=4", "gravatar_id": "", "url": "https://api.github.com/users/MichaelLan", "html_url": "https://github.com/MichaelLan", "followers_url": "https://api.github.com/users/MichaelLan/followers", "following_url": "https://api.github.com/users/MichaelLan/following{/other_user}", "gists_url": "https://api.github.com/users/MichaelLan/gists{/gist_id}", "starred_url": "https://api.github.com/users/MichaelLan/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/MichaelLan/subscriptions", "organizations_url": "https://api.github.com/users/MichaelLan/orgs", "repos_url": "https://api.github.com/users/MichaelLan/repos", "events_url": "https://api.github.com/users/MichaelLan/events{/privacy}", "received_events_url": "https://api.github.com/users/MichaelLan/received_events", "type": "User", "site_admin": false }
[]
closed
false
null
[]
null
[ "This is a relatively recent addition:\r\n\r\nhttp://docs.peewee-orm.com/en/latest/peewee/api.html#Insert.as_rowcount\r\n\r\n```python\r\niq = User.insert_many([(u,) for u in ('u1', 'u2', 'u3')])\r\niq = iq.returning()\r\nassert iq.as_rowcount().execute() == 3\r\n```", "I tried it, but not work, I am using postgress and peewee 3.14.10\r\n![image](https://user-images.githubusercontent.com/9300072/173393554-5092c491-5c94-4182-ab62-862c22043f3c.png)\r\n\r\n", ">This is a relatively recent addition:" ]
"2022-06-10T22:56:28"
"2022-06-13T16:55:36"
"2022-06-11T15:52:34"
NONE
null
null
{ "url": "https://api.github.com/repos/coleifer/peewee/issues/2577/reactions", "total_count": 0, "+1": 0, "-1": 0, "laugh": 0, "hooray": 0, "confused": 0, "heart": 0, "rocket": 0, "eyes": 0 }
https://api.github.com/repos/coleifer/peewee/issues/2577/timeline
null
completed
null
null
https://api.github.com/repos/coleifer/peewee/issues/2576
https://api.github.com/repos/coleifer/peewee
https://api.github.com/repos/coleifer/peewee/issues/2576/labels{/name}
https://api.github.com/repos/coleifer/peewee/issues/2576/comments
https://api.github.com/repos/coleifer/peewee/issues/2576/events
https://github.com/coleifer/peewee/pull/2576
1,263,442,200
PR_kwDOAA7yGM45QFte
2,576
Correct Model.select retreiving method in docs
{ "login": "sofienekhiari", "id": 64355269, "node_id": "MDQ6VXNlcjY0MzU1MjY5", "avatar_url": "https://avatars.githubusercontent.com/u/64355269?v=4", "gravatar_id": "", "url": "https://api.github.com/users/sofienekhiari", "html_url": "https://github.com/sofienekhiari", "followers_url": "https://api.github.com/users/sofienekhiari/followers", "following_url": "https://api.github.com/users/sofienekhiari/following{/other_user}", "gists_url": "https://api.github.com/users/sofienekhiari/gists{/gist_id}", "starred_url": "https://api.github.com/users/sofienekhiari/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/sofienekhiari/subscriptions", "organizations_url": "https://api.github.com/users/sofienekhiari/orgs", "repos_url": "https://api.github.com/users/sofienekhiari/repos", "events_url": "https://api.github.com/users/sofienekhiari/events{/privacy}", "received_events_url": "https://api.github.com/users/sofienekhiari/received_events", "type": "User", "site_admin": false }
[]
closed
false
null
[]
null
[ "Wrong. It's correct." ]
"2022-06-07T14:59:32"
"2022-06-07T17:58:05"
"2022-06-07T17:34:56"
NONE
null
I believe there's a mistake in here :)
{ "url": "https://api.github.com/repos/coleifer/peewee/issues/2576/reactions", "total_count": 0, "+1": 0, "-1": 0, "laugh": 0, "hooray": 0, "confused": 0, "heart": 0, "rocket": 0, "eyes": 0 }
https://api.github.com/repos/coleifer/peewee/issues/2576/timeline
null
null
false
{ "url": "https://api.github.com/repos/coleifer/peewee/pulls/2576", "html_url": "https://github.com/coleifer/peewee/pull/2576", "diff_url": "https://github.com/coleifer/peewee/pull/2576.diff", "patch_url": "https://github.com/coleifer/peewee/pull/2576.patch", "merged_at": null }
https://api.github.com/repos/coleifer/peewee/issues/2575
https://api.github.com/repos/coleifer/peewee
https://api.github.com/repos/coleifer/peewee/issues/2575/labels{/name}
https://api.github.com/repos/coleifer/peewee/issues/2575/comments
https://api.github.com/repos/coleifer/peewee/issues/2575/events
https://github.com/coleifer/peewee/issues/2575
1,260,945,222
I_kwDOAA7yGM5LKH9G
2,575
whether `conn` was append to PooledDatabase._connections?
{ "login": "chmberl", "id": 8245990, "node_id": "MDQ6VXNlcjgyNDU5OTA=", "avatar_url": "https://avatars.githubusercontent.com/u/8245990?v=4", "gravatar_id": "", "url": "https://api.github.com/users/chmberl", "html_url": "https://github.com/chmberl", "followers_url": "https://api.github.com/users/chmberl/followers", "following_url": "https://api.github.com/users/chmberl/following{/other_user}", "gists_url": "https://api.github.com/users/chmberl/gists{/gist_id}", "starred_url": "https://api.github.com/users/chmberl/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/chmberl/subscriptions", "organizations_url": "https://api.github.com/users/chmberl/orgs", "repos_url": "https://api.github.com/users/chmberl/repos", "events_url": "https://api.github.com/users/chmberl/events{/privacy}", "received_events_url": "https://api.github.com/users/chmberl/received_events", "type": "User", "site_admin": false }
[]
closed
false
null
[]
null
[ "found the reason", "\r\nI made a mistake" ]
"2022-06-05T02:54:19"
"2022-06-05T03:13:13"
"2022-06-05T03:11:39"
NONE
null
where to `conn` append to `self._connections`? Why is _connections always empty after I set max_connections? my db url is postgresqlext+pool://xxx:xxx@localhost:5432/netket?max_connections=5&stale_timeout=300
{ "url": "https://api.github.com/repos/coleifer/peewee/issues/2575/reactions", "total_count": 0, "+1": 0, "-1": 0, "laugh": 0, "hooray": 0, "confused": 0, "heart": 0, "rocket": 0, "eyes": 0 }
https://api.github.com/repos/coleifer/peewee/issues/2575/timeline
null
completed
null
null
https://api.github.com/repos/coleifer/peewee/issues/2574
https://api.github.com/repos/coleifer/peewee
https://api.github.com/repos/coleifer/peewee/issues/2574/labels{/name}
https://api.github.com/repos/coleifer/peewee/issues/2574/comments
https://api.github.com/repos/coleifer/peewee/issues/2574/events
https://github.com/coleifer/peewee/issues/2574
1,260,196,814
I_kwDOAA7yGM5LHRPO
2,574
run test for MySQL 8.0 failed
{ "login": "siddontang", "id": 1080370, "node_id": "MDQ6VXNlcjEwODAzNzA=", "avatar_url": "https://avatars.githubusercontent.com/u/1080370?v=4", "gravatar_id": "", "url": "https://api.github.com/users/siddontang", "html_url": "https://github.com/siddontang", "followers_url": "https://api.github.com/users/siddontang/followers", "following_url": "https://api.github.com/users/siddontang/following{/other_user}", "gists_url": "https://api.github.com/users/siddontang/gists{/gist_id}", "starred_url": "https://api.github.com/users/siddontang/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/siddontang/subscriptions", "organizations_url": "https://api.github.com/users/siddontang/orgs", "repos_url": "https://api.github.com/users/siddontang/repos", "events_url": "https://api.github.com/users/siddontang/events{/privacy}", "received_events_url": "https://api.github.com/users/siddontang/received_events", "type": "User", "site_admin": false }
[]
closed
false
null
[]
null
[ "That's alright, we test using MariaDB." ]
"2022-06-03T17:59:29"
"2022-06-10T13:56:04"
"2022-06-10T13:56:03"
NONE
null
Hi, I tried to run the test for MySQL 8.0 as `python3 ./runtests.py -e mysql --mysql-user=root --mysql-port=3306`, but met some test failed, like: ``` ERROR: test_for_update_nested (tests.models.TestForUpdateIntegration) ---------------------------------------------------------------------- Traceback (most recent call last): File "/Users/tangliu/eng/show/peewee/peewee.py", line 3160, in execute_sql cursor.execute(sql, params or ()) File "/opt/homebrew/lib/python3.9/site-packages/pymysql/cursors.py", line 148, in execute result = self._query(query) File "/opt/homebrew/lib/python3.9/site-packages/pymysql/cursors.py", line 310, in _query conn.query(q) File "/opt/homebrew/lib/python3.9/site-packages/pymysql/connections.py", line 548, in query self._affected_rows = self._read_query_result(unbuffered=unbuffered) File "/opt/homebrew/lib/python3.9/site-packages/pymysql/connections.py", line 775, in _read_query_result result.read() File "/opt/homebrew/lib/python3.9/site-packages/pymysql/connections.py", line 1156, in read first_packet = self.connection._read_packet() File "/opt/homebrew/lib/python3.9/site-packages/pymysql/connections.py", line 725, in _read_packet packet.raise_for_error() File "/opt/homebrew/lib/python3.9/site-packages/pymysql/protocol.py", line 221, in raise_for_error err.raise_mysql_exception(self._data) File "/opt/homebrew/lib/python3.9/site-packages/pymysql/err.py", line 143, in raise_mysql_exception raise errorclass(errno, errval) pymysql.err.OperationalError: (1093, "You can't specify target table 'users' for update in FROM clause") ...... Ran 891 tests in 32.490s FAILED (failures=4, errors=3, skipped=105) ```
{ "url": "https://api.github.com/repos/coleifer/peewee/issues/2574/reactions", "total_count": 0, "+1": 0, "-1": 0, "laugh": 0, "hooray": 0, "confused": 0, "heart": 0, "rocket": 0, "eyes": 0 }
https://api.github.com/repos/coleifer/peewee/issues/2574/timeline
null
completed
null
null
https://api.github.com/repos/coleifer/peewee/issues/2573
https://api.github.com/repos/coleifer/peewee
https://api.github.com/repos/coleifer/peewee/issues/2573/labels{/name}
https://api.github.com/repos/coleifer/peewee/issues/2573/comments
https://api.github.com/repos/coleifer/peewee/issues/2573/events
https://github.com/coleifer/peewee/issues/2573
1,256,166,237
I_kwDOAA7yGM5K35Nd
2,573
Question: How to make the default value of two different datetime fields match?
{ "login": "jonathanmach", "id": 12788052, "node_id": "MDQ6VXNlcjEyNzg4MDUy", "avatar_url": "https://avatars.githubusercontent.com/u/12788052?v=4", "gravatar_id": "", "url": "https://api.github.com/users/jonathanmach", "html_url": "https://github.com/jonathanmach", "followers_url": "https://api.github.com/users/jonathanmach/followers", "following_url": "https://api.github.com/users/jonathanmach/following{/other_user}", "gists_url": "https://api.github.com/users/jonathanmach/gists{/gist_id}", "starred_url": "https://api.github.com/users/jonathanmach/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/jonathanmach/subscriptions", "organizations_url": "https://api.github.com/users/jonathanmach/orgs", "repos_url": "https://api.github.com/users/jonathanmach/repos", "events_url": "https://api.github.com/users/jonathanmach/events{/privacy}", "received_events_url": "https://api.github.com/users/jonathanmach/received_events", "type": "User", "site_admin": false }
[]
closed
false
null
[]
null
[ "Probably the easiest way is to override the `save()` method:\r\n\r\n```python\r\nclass BaseModel(...):\r\n def save(self, *args, **kwargs):\r\n self.updated_at = dt.now(tz)\r\n if not self.created_at: self.created_at = self.updated_at\r\n return super(BaseModel, self).save(*args, **kwargs)\r\n```", "Thanks!\r\nApparently, this won't work when using `Model.insert()`, since it would require a database-level default (`DEFAULT CURRENT_TIMESTAMP`).\r\nBut in order to have a database-level default, we would need to get rid of the Peewee default value, which then would break the logic for `Model.create()`.", ">which then would break the logic for Model.create().\r\n\r\nThat doesn't sound correct to me.", "You are right, sorry!\r\nI think what broke my tests was that `db.evolve()` won't detect the new `constraints=[SQL('DEFAULT CURRENT_TIMESTAMP')]` param.\r\nIs it expected? I just checked [the docs](https://docs.peewee-orm.com/en/latest/peewee/models.html?highlight=CURRENT_TIMESTAMP#some-fields-take-special-parameters) but didn't find anything stating it wouldn't be detected by `db.evolve()`.", "I don't know what evolve is. It's not part of this library. Database-provided defaults work just fine with peewee, as do python-side defaults.", "Sorry @coleifer, I thought peewee db evolve was part of this library. Thanks very much for your help!" ]
"2022-06-01T14:36:01"
"2022-06-08T08:28:43"
"2022-06-01T15:19:30"
CONTRIBUTOR
null
Hi all! How to make the default value of two different datetime fields match? Say I have the following `BaseModel`: ```python class BaseModel(Model): id = CharField(primary_key=True, default=lambda: shortuuid.uuid()) created_at = DateTimeTZField(default=lambda: dt.now(tz)) updated_at = DateTimeTZField(default=lambda: dt.now(tz)) ``` Now, when the object is created/instantiated, the values in `created_at` and `updated_at` will have slightly different timestamps (which is completely understandable). **What would be the ideal approach to make sure they match 100% when an object is first created?** I initially tried using `DateTimeTZField(constraints=[SQL('DEFAULT CURRENT_TIMESTAMP')])` instead, but when creating a new record (eg: `BaseModel.create()`), Peewee will try to insert `created_at` and `updated_at` as `NULL`, which will override the DB server default. Then I thought that maybe I could use `pre_init` or `pre_save` signals to explicitly set `instance.updated_at = instance.created_at`, which works, but I thought there might be a better way to accomplish this. Thank you in advance!
{ "url": "https://api.github.com/repos/coleifer/peewee/issues/2573/reactions", "total_count": 0, "+1": 0, "-1": 0, "laugh": 0, "hooray": 0, "confused": 0, "heart": 0, "rocket": 0, "eyes": 0 }
https://api.github.com/repos/coleifer/peewee/issues/2573/timeline
null
completed
null
null
https://api.github.com/repos/coleifer/peewee/issues/2572
https://api.github.com/repos/coleifer/peewee
https://api.github.com/repos/coleifer/peewee/issues/2572/labels{/name}
https://api.github.com/repos/coleifer/peewee/issues/2572/comments
https://api.github.com/repos/coleifer/peewee/issues/2572/events
https://github.com/coleifer/peewee/issues/2572
1,255,723,056
I_kwDOAA7yGM5K2NAw
2,572
The index is created with the wrong name
{ "login": "daveusa31", "id": 81916132, "node_id": "MDQ6VXNlcjgxOTE2MTMy", "avatar_url": "https://avatars.githubusercontent.com/u/81916132?v=4", "gravatar_id": "", "url": "https://api.github.com/users/daveusa31", "html_url": "https://github.com/daveusa31", "followers_url": "https://api.github.com/users/daveusa31/followers", "following_url": "https://api.github.com/users/daveusa31/following{/other_user}", "gists_url": "https://api.github.com/users/daveusa31/gists{/gist_id}", "starred_url": "https://api.github.com/users/daveusa31/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/daveusa31/subscriptions", "organizations_url": "https://api.github.com/users/daveusa31/orgs", "repos_url": "https://api.github.com/users/daveusa31/repos", "events_url": "https://api.github.com/users/daveusa31/events{/privacy}", "received_events_url": "https://api.github.com/users/daveusa31/received_events", "type": "User", "site_admin": false }
[]
closed
false
null
[]
null
[ "Try this:\r\n\r\n```python\r\nclass CryptoTransaction(peewee.Model):\r\n currency = peewee.CharField(default=\"usdt\", index=True, max_length=255)\r\n hash = peewee.CharField(unique=True)\r\n\r\n class Meta:\r\n db_table = \"crypto_transaction\"\r\n database = peewee.SqliteDatabase(':memory:')\r\n legacy_table_names = False\r\n```\r\n\r\nThis gives the following output:\r\n\r\n```\r\ncrypto_transaction\r\ncrypto_transaction_hash\r\n['crypto_transaction_currency', 'crypto_transaction_hash']\r\n```\r\n\r\n`make_index_name` doesn't know about model classes or whether they use old or new-style table names, so it just uses the table name itself. I cannot change the default index-name generation without breaking compatibility.\r\n```" ]
"2022-06-01T11:18:54"
"2022-06-01T13:00:48"
"2022-06-01T13:00:48"
NONE
null
The index is created with the wrong name ```python import peewee from playhouse.migrate import make_index_name class CryptoTransaction(peewee.Model): currency = peewee.CharField(default="usdt", index=True, max_length=255) hash = peewee.CharField(unique=True) class Meta: db_table = "crypto_transaction" database = peewee.SqliteDatabase(':memory:') for model in [CryptoTransaction]: model.create_table() print(CryptoTransaction._meta.table_name) # crypto_transaction print(make_index_name(CryptoTransaction._meta.table_name, [CryptoTransaction.hash.column_name])) # crypto_transaction_hash print([index.name for index in CryptoTransaction._meta.database.get_indexes(CryptoTransaction._meta.table_name)]) # ['cryptotransaction_currency', 'cryptotransaction_hash'] ``` There is such a code. Using the make_index_name function, it is expected that the index name is crypto_transaction_hash. And when creating a model, the index name is generated in its own way
{ "url": "https://api.github.com/repos/coleifer/peewee/issues/2572/reactions", "total_count": 0, "+1": 0, "-1": 0, "laugh": 0, "hooray": 0, "confused": 0, "heart": 0, "rocket": 0, "eyes": 0 }
https://api.github.com/repos/coleifer/peewee/issues/2572/timeline
null
completed
null
null
https://api.github.com/repos/coleifer/peewee/issues/2571
https://api.github.com/repos/coleifer/peewee
https://api.github.com/repos/coleifer/peewee/issues/2571/labels{/name}
https://api.github.com/repos/coleifer/peewee/issues/2571/comments
https://api.github.com/repos/coleifer/peewee/issues/2571/events
https://github.com/coleifer/peewee/issues/2571
1,253,189,231
I_kwDOAA7yGM5KsiZv
2,571
Problems using both Window() and dicts() in window functions
{ "login": "aox-lei", "id": 8756622, "node_id": "MDQ6VXNlcjg3NTY2MjI=", "avatar_url": "https://avatars.githubusercontent.com/u/8756622?v=4", "gravatar_id": "", "url": "https://api.github.com/users/aox-lei", "html_url": "https://github.com/aox-lei", "followers_url": "https://api.github.com/users/aox-lei/followers", "following_url": "https://api.github.com/users/aox-lei/following{/other_user}", "gists_url": "https://api.github.com/users/aox-lei/gists{/gist_id}", "starred_url": "https://api.github.com/users/aox-lei/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/aox-lei/subscriptions", "organizations_url": "https://api.github.com/users/aox-lei/orgs", "repos_url": "https://api.github.com/users/aox-lei/repos", "events_url": "https://api.github.com/users/aox-lei/events{/privacy}", "received_events_url": "https://api.github.com/users/aox-lei/received_events", "type": "User", "site_admin": false }
[]
closed
false
null
[]
null
[ "Yes, aliases must be used when you want to have Python identifiers or dict keys. Peewee tries to determine the column name to use based on whatever the cursor indicates, but when you have an expression (like `SUM(\"t1\".\"value\") OVER \"w\"`) then Peewee's column-name code can't really figure out what to call it." ]
"2022-05-30T23:36:22"
"2022-05-31T13:49:22"
"2022-05-31T13:49:22"
NONE
null
version: 3.14.10 in the documentation example: http://docs.peewee-orm.com/en/latest/peewee/querying.html#reusing-window-definitions ``` win = Window(order_by=[Sample.id]) query = Sample.select( Sample.counter, Sample.value, fn.LEAD(Sample.value).over(win), fn.LAG(Sample.value).over(win), fn.SUM(Sample.value).over(win) ).window(win) # Include our window definition in query. for row in query.tuples(): print(row) # counter value lead() lag() sum() # 1 10. 20. NULL 10. # 1 20. 1. 10. 30. # 2 1. 3. 20. 31. # 2 3. 100. 1. 34. # 3 100. NULL 3. 134. ``` If using dicts(), the field name becomes `value") OVER w` If namedtuples() is used, raise ValueError: Type names and field names must be valid identifiers: 'value") OVER w' If alias is specified for each field, it can be used normally
{ "url": "https://api.github.com/repos/coleifer/peewee/issues/2571/reactions", "total_count": 0, "+1": 0, "-1": 0, "laugh": 0, "hooray": 0, "confused": 0, "heart": 0, "rocket": 0, "eyes": 0 }
https://api.github.com/repos/coleifer/peewee/issues/2571/timeline
null
completed
null
null
https://api.github.com/repos/coleifer/peewee/issues/2570
https://api.github.com/repos/coleifer/peewee
https://api.github.com/repos/coleifer/peewee/issues/2570/labels{/name}
https://api.github.com/repos/coleifer/peewee/issues/2570/comments
https://api.github.com/repos/coleifer/peewee/issues/2570/events
https://github.com/coleifer/peewee/issues/2570
1,252,991,969
I_kwDOAA7yGM5KryPh
2,570
Return dict from scalar
{ "login": "strmwalker", "id": 9069856, "node_id": "MDQ6VXNlcjkwNjk4NTY=", "avatar_url": "https://avatars.githubusercontent.com/u/9069856?v=4", "gravatar_id": "", "url": "https://api.github.com/users/strmwalker", "html_url": "https://github.com/strmwalker", "followers_url": "https://api.github.com/users/strmwalker/followers", "following_url": "https://api.github.com/users/strmwalker/following{/other_user}", "gists_url": "https://api.github.com/users/strmwalker/gists{/gist_id}", "starred_url": "https://api.github.com/users/strmwalker/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/strmwalker/subscriptions", "organizations_url": "https://api.github.com/users/strmwalker/orgs", "repos_url": "https://api.github.com/users/strmwalker/repos", "events_url": "https://api.github.com/users/strmwalker/events{/privacy}", "received_events_url": "https://api.github.com/users/strmwalker/received_events", "type": "User", "site_admin": false }
[]
closed
false
null
[]
null
[]
"2022-05-30T17:34:46"
"2022-05-30T17:58:52"
"2022-05-30T17:58:52"
NONE
null
I have some analytical queries that look like this: ```python import peewee as pw query = Model.select( pw.fn.COUNT(Model.field).alias('name') ) ``` and because I am usually passing result further as dict, I have to do it like this: ```python import peewee_async manager = peewee_async.Manager() result = (await manager.execute(query.dicts())[0] ``` What I'd like to have is and option to write something like this: ```python result = await manager.execute(query.scalar(as_dict=True)) ``` I'd be happy to contribute the PR if this is a valid request
{ "url": "https://api.github.com/repos/coleifer/peewee/issues/2570/reactions", "total_count": 0, "+1": 0, "-1": 0, "laugh": 0, "hooray": 0, "confused": 0, "heart": 0, "rocket": 0, "eyes": 0 }
https://api.github.com/repos/coleifer/peewee/issues/2570/timeline
null
completed
null
null
https://api.github.com/repos/coleifer/peewee/issues/2569
https://api.github.com/repos/coleifer/peewee
https://api.github.com/repos/coleifer/peewee/issues/2569/labels{/name}
https://api.github.com/repos/coleifer/peewee/issues/2569/comments
https://api.github.com/repos/coleifer/peewee/issues/2569/events
https://github.com/coleifer/peewee/issues/2569
1,251,899,393
I_kwDOAA7yGM5KnngB
2,569
Getting Type object has no attribute _meta. on create_tables
{ "login": "Waayway", "id": 43408024, "node_id": "MDQ6VXNlcjQzNDA4MDI0", "avatar_url": "https://avatars.githubusercontent.com/u/43408024?v=4", "gravatar_id": "", "url": "https://api.github.com/users/Waayway", "html_url": "https://github.com/Waayway", "followers_url": "https://api.github.com/users/Waayway/followers", "following_url": "https://api.github.com/users/Waayway/following{/other_user}", "gists_url": "https://api.github.com/users/Waayway/gists{/gist_id}", "starred_url": "https://api.github.com/users/Waayway/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/Waayway/subscriptions", "organizations_url": "https://api.github.com/users/Waayway/orgs", "repos_url": "https://api.github.com/users/Waayway/repos", "events_url": "https://api.github.com/users/Waayway/events{/privacy}", "received_events_url": "https://api.github.com/users/Waayway/received_events", "type": "User", "site_admin": false }
[]
closed
false
null
[]
null
[ "You're extending peewee.ModelBase for some reason: `class baseModel(peewee.ModelBase):`\r\n\r\nChange that to `class baseModel(peewee.Model)` and you'll be set.", "It now gives me a slightly different error\r\n```\r\nAttributeError: 'NoneType' object has no attribute '_meta'\r\n```", "Found the issue, i had the manytomany fields model=None" ]
"2022-05-29T14:08:04"
"2022-05-29T20:52:35"
"2022-05-29T17:13:14"
NONE
null
Th error i'm getting is, `AttributeError: type object 'Chat' has no attribute '_meta'. Did you mean: 'Meta'?` Where Chat is random between the tables i'm making. My code is ``` import peewee from peewee import * from .database import db class baseModel(peewee.ModelBase): class Meta: database = db class User(baseModel): id = peewee.CharField(unique=True) username = peewee.CharField() email = peewee.CharField(unique=True) password = peewee.CharField() server_ids = peewee.ManyToManyField(model=None) friend_ids = peewee.ManyToManyField(model=None) class Server(baseModel): id = peewee.CharField(unique=True) title = peewee.CharField() icon = peewee.CharField() chat_ids = peewee.ManyToManyField(model=None) class Chat(baseModel): id = peewee.CharField(unique=True) title = peewee.CharField() description = peewee.CharField() server_id = peewee.ForeignKeyField(model=None) user_ids = peewee.ManyToManyField(model=None) message_ids = peewee.ManyToManyField(model=None) class Message(baseModel): id = peewee.CharField(unique=True) content = peewee.CharField() send_time = peewee.DateTimeField() sender_id = peewee.ForeignKeyField(model=None) chat_id = peewee.ForeignKeyField(model=None) def create_tables(): with db: db.create_tables([User,Server,Chat,Message]) ``` And it always fails on the last line. Version of Peewee i'm running is 3.14.10 And Python 3.10
{ "url": "https://api.github.com/repos/coleifer/peewee/issues/2569/reactions", "total_count": 0, "+1": 0, "-1": 0, "laugh": 0, "hooray": 0, "confused": 0, "heart": 0, "rocket": 0, "eyes": 0 }
https://api.github.com/repos/coleifer/peewee/issues/2569/timeline
null
completed
null
null
https://api.github.com/repos/coleifer/peewee/issues/2568
https://api.github.com/repos/coleifer/peewee
https://api.github.com/repos/coleifer/peewee/issues/2568/labels{/name}
https://api.github.com/repos/coleifer/peewee/issues/2568/comments
https://api.github.com/repos/coleifer/peewee/issues/2568/events
https://github.com/coleifer/peewee/issues/2568
1,250,987,691
I_kwDOAA7yGM5KkI6r
2,568
ORM traversal does not reflect updates
{ "login": "aiqc", "id": 74990642, "node_id": "MDQ6VXNlcjc0OTkwNjQy", "avatar_url": "https://avatars.githubusercontent.com/u/74990642?v=4", "gravatar_id": "", "url": "https://api.github.com/users/aiqc", "html_url": "https://github.com/aiqc", "followers_url": "https://api.github.com/users/aiqc/followers", "following_url": "https://api.github.com/users/aiqc/following{/other_user}", "gists_url": "https://api.github.com/users/aiqc/gists{/gist_id}", "starred_url": "https://api.github.com/users/aiqc/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/aiqc/subscriptions", "organizations_url": "https://api.github.com/users/aiqc/orgs", "repos_url": "https://api.github.com/users/aiqc/repos", "events_url": "https://api.github.com/users/aiqc/events{/privacy}", "received_events_url": "https://api.github.com/users/aiqc/received_events", "type": "User", "site_admin": false }
[]
closed
false
null
[]
null
[ "Okay, so when I query the object directly with `select()`, it does indeed show as being updated.\r\n\r\nHowever, when accessing the object through a relationship that existed prior to the update(), the update() is not reflected. That is what was throwing me off.\r\n\r\n---\r\n\r\nThere is only 1 Label\r\n```python\r\n>>> list(orm.Label.select())\r\n[<Label: 1>]\r\n```\r\n\r\n```python\r\n>>> tf_bin_tab = some query\r\n>>> tf_bin_tab.some_operation_that_updates_label()\r\n\r\n>>> tf_bin_tab.splitset.label.__dict__ #<-- why isn't traversing the rels running a new query?\r\n{'__data__': {'id': 1,\r\n 'time_created': '2022-05-27 13:02:48.587761-04:00',\r\n 'time_updated': '2022-05-27 13:02:48.587782-04:00', #<--- unchanged, why?\r\n 'name': None,\r\n 'version': None,\r\n 'description': None,\r\n 'columns': ['object'],\r\n 'column_count': 1,\r\n 'unique_classes': ['R', 'M'],\r\n 'fitted_labelcoder': None, #<--- unchanged, why?\r\n 'dataset': 1},\r\n '_dirty': set(),\r\n '__rel__': {}}\r\n[0]\r\n```\r\n\r\nAccessing it via a fresh query\r\n```python\r\n>>> tf_bin_tab = some query\r\n>>> tf_bin_tab.some_operation_that_updates_label()\r\n\r\n>>> orm.Label.select()[0].__dict__\r\n{'__data__': {'id': 1,\r\n 'time_created': '2022-05-27 13:02:48.587761-04:00',\r\n 'time_updated': '2022-05-27 13:02:48.889901-04:00', #<--- changed, as expected\r\n 'name': None,\r\n 'version': None,\r\n 'description': None,\r\n 'columns': ['object'],\r\n 'column_count': 1,\r\n 'unique_classes': ['R', 'M'],\r\n 'fitted_labelcoder': [LabelBinarizer()], #<--- changed, as expected\r\n 'dataset': 1},\r\n '_dirty': set(),\r\n '__rel__': {}}\r\n```", "Okay, and if I do a fresh query of the related object, and access it - then it too bears the updates\r\n\r\n```python\r\norm.Splitset.select()[0].label.__dict__\r\n{'__data__': {'id': 1,\r\n 'time_created': '2022-05-27 13:02:48.587761-04:00',\r\n 'time_updated': '2022-05-27 13:02:48.889901-04:00', #<--- changed, as expected\r\n 'name': None,\r\n 'version': None,\r\n 'description': None,\r\n 'columns': ['object'],\r\n 'column_count': 1,\r\n 'unique_classes': ['R', 'M'],\r\n 'fitted_labelcoder': [LabelBinarizer()], #<--- changed, as expected\r\n 'dataset': 1},\r\n '_dirty': set(),\r\n '__rel__': {}}\r\n```\r\n\r\nSo it looks like the querysets are stale in that they don't reflect the update. Is this to be expected?", "Seems like the crux of the question is this:\r\n\r\n```python\r\n>>> tf_bin_tab.splitset.label.__dict__ #<-- why isn't traversing the rels running a new query?\r\n```\r\n\r\nIf you access the related object, Peewee caches the instance in-memory so that future accesses do not repeat the query. If you update the object somewhere else (e.g. not the in-memory instance) then the cached one will not show the update. Peewee is an active record orm so this is expected.\r\n\r\nExample:\r\n\r\n```python\r\ndb = SqliteDatabase(':memory:')\r\n\r\nclass Base(Model):\r\n class Meta: database = db\r\n\r\nclass User(Base):\r\n username = TextField()\r\n\r\nclass Tweet(Base):\r\n user = ForeignKeyField(User)\r\n content = TextField()\r\n\r\ndb.create_tables([User, Tweet])\r\n\r\nu = User.create(username='u')\r\nTweet.create(user=u, content='t1')\r\n\r\n# Demonstrate the way related objects work:\r\nt = Tweet.get()\r\nt.user.username = 'ux'\r\nt.user.save()\r\n\r\nassert u.username == 'u'\r\n\r\nu = User.get()\r\nassert u.username == 'ux'\r\n```" ]
"2022-05-27T16:54:45"
"2022-05-29T00:14:02"
"2022-05-29T00:14:02"
NONE
null
UPDATE: see next comment below --- I am using the auto-incrementing id provided implicitly by BaseModel. `save()` is working for my `Fold` object, but not my `Label` object. I am puzzled as to why because there is nothing different about their Models. ## Models ```python from playhouse.sqlite_ext import SqliteExtDatabase, JSONField from playhouse.signals import Model, pre_save from peewee import CharField, IntegerField, BlobField, BooleanField, FloatField, \ DateTimeField, ForeignKeyField, DeferredForeignKey class BaseModel(Model): time_created = DateTimeField() time_updated = DateTimeField() class Meta: database = SqliteExtDatabase(path, pragmas={}) class Fold(BaseModel): fold_index = IntegerField() samples = JSONField() fitted_labelcoder = PickleField(null=True) #<--- field in question class Label(BaseModel): columns = JSONField() column_count = IntegerField() fitted_labelcoder = PickleField(null=True) #<--- field in question ``` ## Script ```python if (fold is not None): fitted_encoders = fold.fitted_labelcoder item = fold else: fitted_encoders = label.fitted_labelcoder item = label labelcoder = labelcoders[-1] if (fitted_encoders is None): samples_train = samples[key_train] fitted_encoders, _ = utils.encoding.fit_labels( arr_labels=label_array, samples_train=samples_train, labelcoder=labelcoder ) # Save the fit for decoding and inference. item.fitted_labelcoder = fitted_encoders item.save() # `Fold` saves just fine, but `Label` does not # I can print `item.fitted_labelcoder` and it doesn't show None. # tried `label.save` instead of "item" # tried `label.update(fitted_labelcoder=fitted_encoders) ``` ## Troubleshooting I've been using peewee for 2 years, but I am scratching my head as to why it's not working: - Verified that the created vs updated timestamps are identical... so no update is happening, which rules out the attribute being overwritten back to `None` somewhere else in the script too - Verified that the attribute is not overwritten back to None later in the script. - Tried on peewee == `3.14.3` and `3.14.10` - Tried `instance.update(field=value)` instead of `instance.save` - Tried changing class name from `BaseModel` to `ModelBase` - Tried deleting the empty pragmas dict - Verified that both models are using the same db connection - Verified that the object I am trying to save bears the `<Model: Label>` class. - Verified that there is no `pre_save` funny business going on - Deleted/ recreated the db and its tables several times
{ "url": "https://api.github.com/repos/coleifer/peewee/issues/2568/reactions", "total_count": 0, "+1": 0, "-1": 0, "laugh": 0, "hooray": 0, "confused": 0, "heart": 0, "rocket": 0, "eyes": 0 }
https://api.github.com/repos/coleifer/peewee/issues/2568/timeline
null
completed
null
null
https://api.github.com/repos/coleifer/peewee/issues/2567
https://api.github.com/repos/coleifer/peewee
https://api.github.com/repos/coleifer/peewee/issues/2567/labels{/name}
https://api.github.com/repos/coleifer/peewee/issues/2567/comments
https://api.github.com/repos/coleifer/peewee/issues/2567/events
https://github.com/coleifer/peewee/issues/2567
1,250,814,909
I_kwDOAA7yGM5Kjeu9
2,567
peewee 连接 postgresql 问题
{ "login": "MataSong", "id": 39507705, "node_id": "MDQ6VXNlcjM5NTA3NzA1", "avatar_url": "https://avatars.githubusercontent.com/u/39507705?v=4", "gravatar_id": "", "url": "https://api.github.com/users/MataSong", "html_url": "https://github.com/MataSong", "followers_url": "https://api.github.com/users/MataSong/followers", "following_url": "https://api.github.com/users/MataSong/following{/other_user}", "gists_url": "https://api.github.com/users/MataSong/gists{/gist_id}", "starred_url": "https://api.github.com/users/MataSong/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/MataSong/subscriptions", "organizations_url": "https://api.github.com/users/MataSong/orgs", "repos_url": "https://api.github.com/users/MataSong/repos", "events_url": "https://api.github.com/users/MataSong/events{/privacy}", "received_events_url": "https://api.github.com/users/MataSong/received_events", "type": "User", "site_admin": false }
[]
closed
false
null
[]
null
[ "http://docs.peewee-orm.com/en/latest/peewee/models.html#model-options-and-table-metadata\r\n\r\n```\r\nclass BaseModel(Model):\r\n class Meta:\r\n schema = 'myschema'\r\n```" ]
"2022-05-27T14:09:17"
"2022-05-27T14:44:10"
"2022-05-27T14:44:09"
NONE
null
peewee 在连接 postgresql 数据库时,如何选择 schema 模式呢?
{ "url": "https://api.github.com/repos/coleifer/peewee/issues/2567/reactions", "total_count": 0, "+1": 0, "-1": 0, "laugh": 0, "hooray": 0, "confused": 0, "heart": 0, "rocket": 0, "eyes": 0 }
https://api.github.com/repos/coleifer/peewee/issues/2567/timeline
null
completed
null
null
https://api.github.com/repos/coleifer/peewee/issues/2566
https://api.github.com/repos/coleifer/peewee
https://api.github.com/repos/coleifer/peewee/issues/2566/labels{/name}
https://api.github.com/repos/coleifer/peewee/issues/2566/comments
https://api.github.com/repos/coleifer/peewee/issues/2566/events
https://github.com/coleifer/peewee/issues/2566
1,250,777,008
I_kwDOAA7yGM5KjVew
2,566
使用peewee连接postgresql数据库
{ "login": "MataSong", "id": 39507705, "node_id": "MDQ6VXNlcjM5NTA3NzA1", "avatar_url": "https://avatars.githubusercontent.com/u/39507705?v=4", "gravatar_id": "", "url": "https://api.github.com/users/MataSong", "html_url": "https://github.com/MataSong", "followers_url": "https://api.github.com/users/MataSong/followers", "following_url": "https://api.github.com/users/MataSong/following{/other_user}", "gists_url": "https://api.github.com/users/MataSong/gists{/gist_id}", "starred_url": "https://api.github.com/users/MataSong/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/MataSong/subscriptions", "organizations_url": "https://api.github.com/users/MataSong/orgs", "repos_url": "https://api.github.com/users/MataSong/repos", "events_url": "https://api.github.com/users/MataSong/events{/privacy}", "received_events_url": "https://api.github.com/users/MataSong/received_events", "type": "User", "site_admin": false }
[]
closed
false
null
[]
null
[]
"2022-05-27T13:34:59"
"2022-05-27T14:08:08"
"2022-05-27T14:08:08"
NONE
null
定义表名不生效。 `class PostgresCustomTableDataInfo(Model): """ custom_table_data 表 """ _id = CharField(primary_key=True) activity_id = CharField() custom_table_id = CharField() mapping_custom_table_chinese_name = CharField() data_list = ArrayField() class Mete: database = DatabaseProxy() table_name = 'custom_table_data'` `class PostgresCustomTableDataDao(PostgresDao): """ pg数据库 custom_table_data 表 """ def __init__(self, db_name: str): super().__init__() self.custom_table_data_db = PostgresqlDatabase(db_name, **self.postgres_instance) def create_tables(self): self.custom_table_data_db.connect() self.custom_table_data_db.bind([PostgresCustomTableDataInfo]) self.custom_table_data_db.create_tables([PostgresCustomTableDataInfo])` `PostgresCustomTableDataDao('test').create_tables()` 创建表后得到 PostgresCustomTableDataInfo 表名,而不是 custom_table_data 表名
{ "url": "https://api.github.com/repos/coleifer/peewee/issues/2566/reactions", "total_count": 0, "+1": 0, "-1": 0, "laugh": 0, "hooray": 0, "confused": 0, "heart": 0, "rocket": 0, "eyes": 0 }
https://api.github.com/repos/coleifer/peewee/issues/2566/timeline
null
completed
null
null
https://api.github.com/repos/coleifer/peewee/issues/2565
https://api.github.com/repos/coleifer/peewee
https://api.github.com/repos/coleifer/peewee/issues/2565/labels{/name}
https://api.github.com/repos/coleifer/peewee/issues/2565/comments
https://api.github.com/repos/coleifer/peewee/issues/2565/events
https://github.com/coleifer/peewee/issues/2565
1,249,534,666
I_kwDOAA7yGM5KemLK
2,565
pwiz doesn't find installed psycopg (peewee.ImproperlyConfigured: Postgres driver not installed!)
{ "login": "NAN-CForadas", "id": 98823081, "node_id": "U_kgDOBePrqQ", "avatar_url": "https://avatars.githubusercontent.com/u/98823081?v=4", "gravatar_id": "", "url": "https://api.github.com/users/NAN-CForadas", "html_url": "https://github.com/NAN-CForadas", "followers_url": "https://api.github.com/users/NAN-CForadas/followers", "following_url": "https://api.github.com/users/NAN-CForadas/following{/other_user}", "gists_url": "https://api.github.com/users/NAN-CForadas/gists{/gist_id}", "starred_url": "https://api.github.com/users/NAN-CForadas/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/NAN-CForadas/subscriptions", "organizations_url": "https://api.github.com/users/NAN-CForadas/orgs", "repos_url": "https://api.github.com/users/NAN-CForadas/repos", "events_url": "https://api.github.com/users/NAN-CForadas/events{/privacy}", "received_events_url": "https://api.github.com/users/NAN-CForadas/received_events", "type": "User", "site_admin": false }
[]
closed
false
null
[]
null
[ "Sorry, I installed psycopg not psycopg2. Please excuse me!", "You probably want to use `psycopg2` or `psycopg2-binary` as those are better supported by Peewee and can coexist alongside your install of `psycopg==3`." ]
"2022-05-26T12:54:28"
"2022-05-26T12:57:00"
"2022-05-26T12:56:51"
NONE
null
System Software Overview: macOS Monterey System Version: macOS 12.3.1 (21E258) Kernel Version: Darwin 21.4.0 Python 3.10.4 ```% python -m pwiz -H $HOSTNAME -p 5432 -e postgresql -v $DATABASE Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/runpy.py", line 196, in _run_module_as_main return _run_code(code, main_globals, None, File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/runpy.py", line 86, in _run_code exec(code, run_globals) File "pee-wee-testing/venv/lib/python3.10/site-packages/pwiz.py", line 222, in <module> introspector = make_introspector(engine, database, **connect) File "pee-wee-testing/venv/lib/python3.10/site-packages/pwiz.py", line 52, in make_introspector return Introspector.from_database(db, schema=schema) File "pee-wee-testing/venv/lib/python3.10/site-packages/playhouse/reflection.py", line 501, in from_database metadata = PostgresqlMetadata(database) File "pee-wee-testing/venv/lib/python3.10/site-packages/playhouse/reflection.py", line 264, in __init__ cursor = self.execute('select oid, typname, format_type(oid, NULL)' File "pee-wee-testing/venv/lib/python3.10/site-packages/playhouse/reflection.py", line 165, in execute return self.database.execute_sql(sql, params) File "pee-wee-testing/venv/lib/python3.10/site-packages/peewee.py", line 3175, in execute_sql cursor = self.cursor(commit) File "pee-wee-testing/venv/lib/python3.10/site-packages/peewee.py", line 3159, in cursor self.connect() File "pee-wee-testing/venv/lib/python3.10/site-packages/peewee.py", line 3113, in connect self._state.set_connection(self._connect()) File "pee-wee-testing/venv/lib/python3.10/site-packages/peewee.py", line 3812, in _connect raise ImproperlyConfigured('Postgres driver not installed!') peewee.ImproperlyConfigured: Postgres driver not installed! ``` ``` (venv) (base) pee-wee-testing % pip freeze click==8.1.3 Flask==2.1.2 itsdangerous==2.1.2 Jinja2==3.1.2 MarkupSafe==2.1.1 peewee==3.14.10 psycopg==3.0.14 Werkzeug==2.1.2 ```
{ "url": "https://api.github.com/repos/coleifer/peewee/issues/2565/reactions", "total_count": 0, "+1": 0, "-1": 0, "laugh": 0, "hooray": 0, "confused": 0, "heart": 0, "rocket": 0, "eyes": 0 }
https://api.github.com/repos/coleifer/peewee/issues/2565/timeline
null
completed
null
null
https://api.github.com/repos/coleifer/peewee/issues/2564
https://api.github.com/repos/coleifer/peewee
https://api.github.com/repos/coleifer/peewee/issues/2564/labels{/name}
https://api.github.com/repos/coleifer/peewee/issues/2564/comments
https://api.github.com/repos/coleifer/peewee/issues/2564/events
https://github.com/coleifer/peewee/issues/2564
1,238,068,067
I_kwDOAA7yGM5Jy2tj
2,564
peewee.IntegrityError: NOT NULL constraint failed
{ "login": "umangapathak999", "id": 43605107, "node_id": "MDQ6VXNlcjQzNjA1MTA3", "avatar_url": "https://avatars.githubusercontent.com/u/43605107?v=4", "gravatar_id": "", "url": "https://api.github.com/users/umangapathak999", "html_url": "https://github.com/umangapathak999", "followers_url": "https://api.github.com/users/umangapathak999/followers", "following_url": "https://api.github.com/users/umangapathak999/following{/other_user}", "gists_url": "https://api.github.com/users/umangapathak999/gists{/gist_id}", "starred_url": "https://api.github.com/users/umangapathak999/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/umangapathak999/subscriptions", "organizations_url": "https://api.github.com/users/umangapathak999/orgs", "repos_url": "https://api.github.com/users/umangapathak999/repos", "events_url": "https://api.github.com/users/umangapathak999/events{/privacy}", "received_events_url": "https://api.github.com/users/umangapathak999/received_events", "type": "User", "site_admin": false }
[]
closed
false
null
[]
null
[ "SOLVED!\r\n\r\nI solved the problem. Nothing was wrong with the code. Just needed to remigrate my database. For those experiencing similar problem, script below tends to work:\r\n```\r\ndb.connect()\r\n\r\nmodels = [\r\n User\r\n]\r\n\r\ndb.drop_tables(models)\r\n\r\ndb.create_tables(models)\r\n```\r\n`db` is an instance of peewee database initialization." ]
"2022-05-17T04:58:38"
"2022-05-17T06:54:20"
"2022-05-17T06:54:19"
NONE
null
I want to set some fields to be nullable in User Model Here is my base model: ``` db = SqliteDatabase(DBConfig.DB_NAME) class BaseModel(Model): class Meta: database = db ``` Here is my User model: ``` class User(BaseModel): id = BigAutoField() name = CharField() email = CharField(unique=True) mobile_number = CharField(max_length=20, unique=True) avatar = CharField(null=True, default=None) two_factor_secret = CharField(null=True, default=None, unique=True) created_at = DateTimeField(default=datetime.now) ``` Here is what I tried to create a user and where the said problem is occurring: ``` user = User.create(name="Test", email="test@email.com", mobile_number="9876543210") ``` If I pass avatar and two_factor_secret, the model works without any problem. The error I get while not passing avatar and tow_factor_secret values: ``` peewee.IntegrityError: NOT NULL constraint failed: user.avatar ``` If any further detail is required, I am happy to provide it.
{ "url": "https://api.github.com/repos/coleifer/peewee/issues/2564/reactions", "total_count": 0, "+1": 0, "-1": 0, "laugh": 0, "hooray": 0, "confused": 0, "heart": 0, "rocket": 0, "eyes": 0 }
https://api.github.com/repos/coleifer/peewee/issues/2564/timeline
null
completed
null
null
https://api.github.com/repos/coleifer/peewee/issues/2563
https://api.github.com/repos/coleifer/peewee
https://api.github.com/repos/coleifer/peewee/issues/2563/labels{/name}
https://api.github.com/repos/coleifer/peewee/issues/2563/comments
https://api.github.com/repos/coleifer/peewee/issues/2563/events
https://github.com/coleifer/peewee/issues/2563
1,226,986,578
I_kwDOAA7yGM5JIlRS
2,563
select_extend(): allow Model parameters
{ "login": "morrissimo", "id": 782829, "node_id": "MDQ6VXNlcjc4MjgyOQ==", "avatar_url": "https://avatars.githubusercontent.com/u/782829?v=4", "gravatar_id": "", "url": "https://api.github.com/users/morrissimo", "html_url": "https://github.com/morrissimo", "followers_url": "https://api.github.com/users/morrissimo/followers", "following_url": "https://api.github.com/users/morrissimo/following{/other_user}", "gists_url": "https://api.github.com/users/morrissimo/gists{/gist_id}", "starred_url": "https://api.github.com/users/morrissimo/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/morrissimo/subscriptions", "organizations_url": "https://api.github.com/users/morrissimo/orgs", "repos_url": "https://api.github.com/users/morrissimo/repos", "events_url": "https://api.github.com/users/morrissimo/events{/privacy}", "received_events_url": "https://api.github.com/users/morrissimo/received_events", "type": "User", "site_admin": false }
[]
closed
false
null
[]
null
[ "Thanks, this was an accidental omission, and is now resolved." ]
"2022-05-05T17:40:24"
"2022-05-25T14:50:20"
"2022-05-25T14:49:52"
NONE
null
My use case: incremental construction a query, usually via a subclass that leverages a superclass helper method. I'd like to keep the select() definition as built by the super class, but allow the subclass to extend the select targets (and JOINs, etc) _without_ having to resort to something like this: ```python class Base: @classmethod def build_query(cls): return cls.select(cls).join_from(cls, SomeOtherClass) class Subclass(Base): @classmethod def build_query(cls): qs = super().build_query() qs = qs.select_extend( *cls._meta.fields.values(), *YetAnotherClass._meta.fields.values(), ).join_from(cls, YetAnotherClass) return qs ``` With the proposed change to `select_extend()`, the above code would look like: ```python class Base: @classmethod def build_query(cls): return cls.select(cls).join_from(cls, SomeOtherClass) class Subclass(Base): @classmethod def build_query(cls): qs = super().build_query() return qs.select_extend(cls, YetAnotherClass).join_from(cls, YetAnotherClass) ``` Granted, I have no idea what the LOE looks like - but it _smells_ like a potential easy win for readability. Alternatively: there's a more correct way to do this and I've simply veered off the path ;)
{ "url": "https://api.github.com/repos/coleifer/peewee/issues/2563/reactions", "total_count": 0, "+1": 0, "-1": 0, "laugh": 0, "hooray": 0, "confused": 0, "heart": 0, "rocket": 0, "eyes": 0 }
https://api.github.com/repos/coleifer/peewee/issues/2563/timeline
null
completed
null
null
https://api.github.com/repos/coleifer/peewee/issues/2562
https://api.github.com/repos/coleifer/peewee
https://api.github.com/repos/coleifer/peewee/issues/2562/labels{/name}
https://api.github.com/repos/coleifer/peewee/issues/2562/comments
https://api.github.com/repos/coleifer/peewee/issues/2562/events
https://github.com/coleifer/peewee/issues/2562
1,217,760,621
I_kwDOAA7yGM5IlY1t
2,562
Fast way to check if record exists
{ "login": "ghost", "id": 10137, "node_id": "MDQ6VXNlcjEwMTM3", "avatar_url": "https://avatars.githubusercontent.com/u/10137?v=4", "gravatar_id": "", "url": "https://api.github.com/users/ghost", "html_url": "https://github.com/ghost", "followers_url": "https://api.github.com/users/ghost/followers", "following_url": "https://api.github.com/users/ghost/following{/other_user}", "gists_url": "https://api.github.com/users/ghost/gists{/gist_id}", "starred_url": "https://api.github.com/users/ghost/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/ghost/subscriptions", "organizations_url": "https://api.github.com/users/ghost/orgs", "repos_url": "https://api.github.com/users/ghost/repos", "events_url": "https://api.github.com/users/ghost/events{/privacy}", "received_events_url": "https://api.github.com/users/ghost/received_events", "type": "User", "site_admin": false }
[]
closed
false
null
[]
null
[ "You can add an index via `sqlite3 mydb-file` and adding it there. The sqlite docs have plenty of info on creating indexes. To do it via peewee you can:\r\n\r\n* Main doc http://docs.peewee-orm.com/en/latest/peewee/models.html#indexes-and-constraints\r\n* add it to the field definition, e.g. `my_field = IntegerField(index=True)`\r\n* add it to the model class' Meta.indexes \r\n* use [modelindex apis](http://docs.peewee-orm.com/en/latest/peewee/api.html#ModelIndex)\r\n* use `db.execute_sql()` directly to create the index\r\n\r\nYou can call `ModelClass._schema.create_indexes(safe=True)` after adding the index.\r\n\r\nBut for what you're trying to do specifically, a bloom filter is probably a better option.", "If I understand you correctly:\r\n\r\nRetrieve all rows from first_table that exist in the second_table, based on a shared value in common_column:\r\n```\r\nselect * from first_table\r\nwhere exists (\r\n select 1\r\n from second_table\r\n where first_table.common_column = second_table.common_column\r\n)\r\n```\r\n\r\nIn peewee:\r\n\r\n FirstTable.select().where(\r\n fn.exists(second_table.select().where(\r\n FirstTable.common_column == SecondTable.common_column\r\n ))\r\n )\r\n\r\nYou can change this to `not exists` to retrieve all rows from first_table that are missing in second_table. In peewee that would be `~fn.exists`" ]
"2022-04-27T18:56:06"
"2022-04-29T15:24:34"
"2022-04-27T20:55:03"
NONE
null
First of all I am sorry in advance for the naive question. I have an application which needs to iterate over a large number of entries and test each and every one against the sqlite peewee database to see if the value exists in a specific column. Unfortunately this means tons of queries and this turns out to be slow. I came across the index option and tried to index the desired column with a migration but I haven't seen any speed differences. Is any special syntax required to make use of an index? I haven't been able to find an example.
{ "url": "https://api.github.com/repos/coleifer/peewee/issues/2562/reactions", "total_count": 0, "+1": 0, "-1": 0, "laugh": 0, "hooray": 0, "confused": 0, "heart": 0, "rocket": 0, "eyes": 0 }
https://api.github.com/repos/coleifer/peewee/issues/2562/timeline
null
completed
null
null
https://api.github.com/repos/coleifer/peewee/issues/2561
https://api.github.com/repos/coleifer/peewee
https://api.github.com/repos/coleifer/peewee/issues/2561/labels{/name}
https://api.github.com/repos/coleifer/peewee/issues/2561/comments
https://api.github.com/repos/coleifer/peewee/issues/2561/events
https://github.com/coleifer/peewee/issues/2561
1,217,498,585
I_kwDOAA7yGM5IkY3Z
2,561
Count Filter is not Working
{ "login": "weaverjess", "id": 87557577, "node_id": "MDQ6VXNlcjg3NTU3NTc3", "avatar_url": "https://avatars.githubusercontent.com/u/87557577?v=4", "gravatar_id": "", "url": "https://api.github.com/users/weaverjess", "html_url": "https://github.com/weaverjess", "followers_url": "https://api.github.com/users/weaverjess/followers", "following_url": "https://api.github.com/users/weaverjess/following{/other_user}", "gists_url": "https://api.github.com/users/weaverjess/gists{/gist_id}", "starred_url": "https://api.github.com/users/weaverjess/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/weaverjess/subscriptions", "organizations_url": "https://api.github.com/users/weaverjess/orgs", "repos_url": "https://api.github.com/users/weaverjess/repos", "events_url": "https://api.github.com/users/weaverjess/events{/privacy}", "received_events_url": "https://api.github.com/users/weaverjess/received_events", "type": "User", "site_admin": false }
[]
closed
false
null
[]
null
[ "It's not `fn.filter()` -- you want `fn.COUNT(EventModel.id).filter(EventModel.status == 'cancelled')`\r\n\r\nThis is not a peewee issue, but rather an issue in incorrectly translating SQL to peewee APIs.", "That's exactly what I have... except it's BookingModel, not EventModel. It doesn't work. Apologies for the title being slightly off. Updated.\r\n\r\n@coleifer ", "To clarify:\r\n\r\n```python\r\npeewee.fn.COUNT(BookingModel.id).filter(BookingModel.status != 'cancelled')\r\n```\r\ndoes not work.", "Works fine for me:\r\n\r\n```python\r\nclass Person(Model):\r\n name = TextField()\r\n class Meta:\r\n database = db\r\n\r\nclass Pet(Model):\r\n person = ForeignKeyField(Person)\r\n animal = CharField()\r\n class Meta:\r\n database = db\r\n\r\ndb.create_tables([Person, Pet])\r\n\r\np1 = Person.create(name='Cat Lady')\r\np2 = Person.create(name='Dog Owner')\r\np3 = Person.create(name='Animal Lover')\r\nPet.create(person=p1, animal='Cat 1-1')\r\nPet.create(person=p1, animal='Cat 1-2')\r\nPet.create(person=p2, animal='Dog 2-1')\r\nPet.create(person=p2, animal='Dog 2-2')\r\nPet.create(person=p3, animal='Cat 3-1')\r\nPet.create(person=p3, animal='Dog 3-1')\r\nPet.create(person=p3, animal='Dog 3-2')\r\nPet.create(person=p3, animal='Fish 3-1')\r\n\r\nquery = (Person\r\n .select(Person.name,\r\n fn.COUNT(Pet.id).filter(Pet.animal.startswith('Cat')).alias('cats'),\r\n fn.COUNT(Pet.id).filter(Pet.animal.startswith('Dog')).alias('dogs'),\r\n fn.COUNT(Pet.id).alias('total_pets'))\r\n .join(Pet, JOIN.LEFT_OUTER)\r\n .group_by(Person.name))\r\nfor p in query:\r\n print(p.name, 'cats:', p.cats, 'dogs:', p.dogs, 'all:', p.total_pets)\r\n```\r\n\r\nPrints\r\n\r\n```\r\nAnimal Lover cats: 1 dogs: 2 all: 4\r\nCat Lady cats: 2 dogs: 0 all: 2\r\nDog Owner cats: 0 dogs: 2 all: 2\r\n```" ]
"2022-04-27T15:11:13"
"2022-04-27T15:37:24"
"2022-04-27T15:17:54"
NONE
null
Referencing: https://stackoverflow.com/questions/60067772/from-rows-to-columns-using-peewee-orm Event:Booking is a 1:many relationship. I have a situation where I want to pull all Events that are still bookable just to generate a list. ```python n_bookings = peewee.fn.COUNT(BookingModel.id) query = EventModel.select(EventModel, n_bookings.filter(BookingModel.status != 'cancelled').alias('count')).join( BookingModel, peewee.JOIN.FULL_OUTER, on=(BookingModel.event_id == EventModel.id) ).group_by( EventModel ).having( having ).where( select_where ).order_by( EventModel.start_time.asc(), EventModel.id.asc() ).limit(canary_limit) ``` While appending on a filter doesn't break anything, it also seems to do nothing, as it is still counting bookings with a status of "cancelled".
{ "url": "https://api.github.com/repos/coleifer/peewee/issues/2561/reactions", "total_count": 0, "+1": 0, "-1": 0, "laugh": 0, "hooray": 0, "confused": 0, "heart": 0, "rocket": 0, "eyes": 0 }
https://api.github.com/repos/coleifer/peewee/issues/2561/timeline
null
completed
null
null
https://api.github.com/repos/coleifer/peewee/issues/2560
https://api.github.com/repos/coleifer/peewee
https://api.github.com/repos/coleifer/peewee/issues/2560/labels{/name}
https://api.github.com/repos/coleifer/peewee/issues/2560/comments
https://api.github.com/repos/coleifer/peewee/issues/2560/events
https://github.com/coleifer/peewee/issues/2560
1,213,244,589
I_kwDOAA7yGM5IUKSt
2,560
peewee.OperationalError: (1061, "Duplicate key name 'fqcmodel_date_'") ?
{ "login": "jekoie", "id": 6836400, "node_id": "MDQ6VXNlcjY4MzY0MDA=", "avatar_url": "https://avatars.githubusercontent.com/u/6836400?v=4", "gravatar_id": "", "url": "https://api.github.com/users/jekoie", "html_url": "https://github.com/jekoie", "followers_url": "https://api.github.com/users/jekoie/followers", "following_url": "https://api.github.com/users/jekoie/following{/other_user}", "gists_url": "https://api.github.com/users/jekoie/gists{/gist_id}", "starred_url": "https://api.github.com/users/jekoie/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/jekoie/subscriptions", "organizations_url": "https://api.github.com/users/jekoie/orgs", "repos_url": "https://api.github.com/users/jekoie/repos", "events_url": "https://api.github.com/users/jekoie/events{/privacy}", "received_events_url": "https://api.github.com/users/jekoie/received_events", "type": "User", "site_admin": false }
[]
closed
false
null
[]
null
[ "peewee crate table in safe mode don't work at all????\r\n![image](https://user-images.githubusercontent.com/6836400/164888113-8776e544-9687-4f79-8245-fd8f7219d8da.png)\r\n", "@jekoie You are supposed to do it like this:\r\n\r\n```\r\nclass BaseModel(Model):\r\n class Meta:\r\n database = db\r\n\r\nclass FQCModel(BaseModel):\r\n date_ = DateTimeField(default=datetime.datetime.now, help_text=\"日期\", verbose_name=\"日期\", index=True, formats=\"%Y-%m-%d %H:%M:%S\")\r\n\r\ndb.create_tables([FQCModel])\r\n```\r\n", "MySQL does not support create index if not exists, if I recall correctly. So you probably need to check yourself beforehand.", "You can get the list of existing tables and indexes:\r\n\r\n* http://docs.peewee-orm.com/en/latest/peewee/api.html#Database.get_tables\r\n* http://docs.peewee-orm.com/en/latest/peewee/api.html#Database.get_indexes", "@coleifer My Model is Ok, The real problem is `peewee` can't judge if the table already exist, so in I call `db.create_tables([FQCModel], safe=True)` again , it will be throw error.", "You meant to reply to mkmoisen I believe.\r\n\r\nHere is my comment, again:\r\n\r\nMySQL does not support create index if not exists, if I recall correctly. So you probably need to check yourself beforehand.\r\n\r\nAnd:\r\n\r\nYou can get the list of existing tables and indexes:\r\n\r\n http://docs.peewee-orm.com/en/latest/peewee/api.html#Database.get_tables\r\n http://docs.peewee-orm.com/en/latest/peewee/api.html#Database.get_indexes\r\n\r\n@jekoie you can always write your own method that checks for existence before trying to create the table." ]
"2022-04-23T08:36:06"
"2022-04-25T10:52:31"
"2022-04-23T16:52:18"
NONE
null
I use peewee create a table and connect to mysql, but it run failed? `peewee.OperationalError: (1061, "Duplicate key name 'fqcmodel_date_'")` ```python class FQCModel(Model): date_ = DateTimeField(default=datetime.datetime.now, help_text="日期", verbose_name="日期", index=True, formats="%Y-%m-%d %H:%M:%S") ```
{ "url": "https://api.github.com/repos/coleifer/peewee/issues/2560/reactions", "total_count": 0, "+1": 0, "-1": 0, "laugh": 0, "hooray": 0, "confused": 0, "heart": 0, "rocket": 0, "eyes": 0 }
https://api.github.com/repos/coleifer/peewee/issues/2560/timeline
null
completed
null
null
https://api.github.com/repos/coleifer/peewee/issues/2559
https://api.github.com/repos/coleifer/peewee
https://api.github.com/repos/coleifer/peewee/issues/2559/labels{/name}
https://api.github.com/repos/coleifer/peewee/issues/2559/comments
https://api.github.com/repos/coleifer/peewee/issues/2559/events
https://github.com/coleifer/peewee/issues/2559
1,208,005,244
I_kwDOAA7yGM5IALJ8
2,559
Model.create(...) possibly corrupting other items
{ "login": "peepo5", "id": 72892531, "node_id": "MDQ6VXNlcjcyODkyNTMx", "avatar_url": "https://avatars.githubusercontent.com/u/72892531?v=4", "gravatar_id": "", "url": "https://api.github.com/users/peepo5", "html_url": "https://github.com/peepo5", "followers_url": "https://api.github.com/users/peepo5/followers", "following_url": "https://api.github.com/users/peepo5/following{/other_user}", "gists_url": "https://api.github.com/users/peepo5/gists{/gist_id}", "starred_url": "https://api.github.com/users/peepo5/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/peepo5/subscriptions", "organizations_url": "https://api.github.com/users/peepo5/orgs", "repos_url": "https://api.github.com/users/peepo5/repos", "events_url": "https://api.github.com/users/peepo5/events{/privacy}", "received_events_url": "https://api.github.com/users/peepo5/received_events", "type": "User", "site_admin": false }
[]
closed
false
null
[]
null
[ "If you are able to write a unit-test or very small script that replicates the issue I will take a look.", "I'd suggest logging SQL and running the problematic code, then feel free to paste the resulting SQL here in this issue.\r\n\r\n```python\r\n# at top of your main python module add this\r\nimport logging\r\nlogger = logging.getLogger('peewee')\r\nlogger.addHandler(logging.StreamHandler())\r\nlogger.setLevel(logging.DEBUG)\r\n```\r\n\r\nThen you can examine the SQL being executed when you hit your issue.", "I was just about to ask if I should log the sql, you caught me before I could ask, I will check the code soon. Also, I do not understand why you closed this issue when the issue is still active, I understand you may want a clean repository but it is misrepresentative of the issue status. Anyways, will check it soon and return insights.", "In absence of a traceback or a clear indication this is a Peewee issue, I tend to close stuff like this until it's proven to be a peewee problem (as it seems to me this is very likely user error). Fundamental things like inserts and atomic updates are very well-tested across sqlite/mysql/postgres/cockroachdb.", "Alright, I guess I understand.\r\n\r\nFor the issue, I ran the logging code, however the terminal was giving me quite a lot due to my scheduled tasks, however, apart from the selects, here is what I got for the insert logs.\r\n\r\nPerson 1\r\n```SQL\r\n('INSERT INTO \"user\" (\"discord_id\", \"telegram_id\", \"last_seen_username\", \"last_seen_discriminator\", \"last_seen_pfp\", \"subscription_warning_level\", \"telegram_code\", \"telegram_url\", \"pre_payment\", \"pre_payment_amount_payed_usd\") VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)', ['937789306049802303', '', 'Farami', '3606', '', 0, '9591092', '', '', Decimal('0')])\r\n('INSERT INTO \"payment\" (\"discord_id\", \"subtype\", \"ms_initiated\", \"amount_payed_usd\", \"coinpayments_id\", \"coupon_used\") VALUES (?, ?, ?, ?, ?, ?)', ['937789306049802303', 'htfbot', 1650385811538, '0', '', ''])\r\n```\r\n\r\nPerson 2\r\n```SQL\r\n('INSERT INTO \"user\" (\"discord_id\", \"telegram_id\", \"last_seen_username\", \"last_seen_discriminator\", \"last_seen_pfp\", \"subscription_warning_level\", \"telegram_code\", \"telegram_url\", \"pre_payment\", \"pre_payment_amount_payed_usd\") VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)', ['485777016923226133', '', 'ati', '4675', '', 0, '9591092', '', '', Decimal('0')])\r\n('INSERT INTO \"payment\" (\"discord_id\", \"subtype\", \"ms_initiated\", \"amount_payed_usd\", \"coinpayments_id\", \"coupon_used\") VALUES (?, ?, ?, ?, ?, ?)', ['485777016923226133', 'htfbot', 1650385933012, '0', '', ''])\r\n```\r\n\r\nPerson x (overtaking all other data)\r\n```SQL\r\n('INSERT INTO \"user\" (\"discord_id\", \"telegram_id\", \"last_seen_username\", \"last_seen_discriminator\", \"last_seen_pfp\", \"subscription_warning_level\", \"telegram_code\", \"telegram_url\", \"pre_payment\", \"pre_payment_amount_payed_usd\") VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)', ['915560264353587211', '', 'friendly frog', '0661', '', 0, '8070074', '', '', Decimal('0')])\r\n('INSERT INTO \"payment\" (\"discord_id\", \"subtype\", \"ms_initiated\", \"amount_payed_usd\", \"coinpayments_id\", \"coupon_used\") VALUES (?, ?, ?, ?, ?, ?)', ['485777016923226133', 'htfbot', 1650385933012, '0', '', ''])\r\n```\r\n\r\nIf these provide no reason for the issue, let me know what other steps I can take, thanks (or if I should provide select queries).", "I think I found something, payment insert for person x is not correct, i will have to check if i pasted correctly however. But just a bit of conversation - which operation can permanently change all future inserts? Seems like a weird thing. Also when I access the model fields directly they change to be the same. Confusing. I will check around for logic errors and will try to find something.", "Alright I think I found the problem of the issue. It is when using:\r\n\r\nuser = User.get_or_none(...)\r\n\r\nAnd then doing an update operation on that user like\r\n\r\nuser.update(...)\r\n\r\nI think it effects all the users instead of one as seen below.\r\n\r\n('UPDATE \"user\" SET \"last_seen_username\" = ?, \"last_seen_discriminator\" = ?, \"last_seen_pfp\" = ?', ['friendly frog', '0661', 'https://cdn.discordapp.com/avatars/915534564353587210/4a4e597510bcsfddf8f6d57c3543ee6fd'])\r\n\r\n---\r\n\r\nI feel like the functionality should be different. It would be nice to be able to get an item with get_or_none and then do operations on it without an extra .where.", "Looking at the wrapper docs, I see there is item.delete_instance(...) but not item.update_instance(...) would be nice to have the second", "You should probably use the more idiomatic `save()` instead of `update()`:\r\n\r\n```python\r\nuser = User.get_or_none(...)\r\nif user is not None:\r\n user.last_seen... = xyz\r\n user.save()\r\n```", "@peepopoggers If you prefer the SQL style over the ORM style:\r\n\r\n User.update(foo='bar').where(id=user.id)\r\n \r\nBut if you prefer the ORM style use the regular `save` like Coleifer mentioned." ]
"2022-04-19T08:49:35"
"2022-04-20T16:01:51"
"2022-04-19T12:54:52"
NONE
null
I have a database where I store user information. I have an API endpoint using quart (async flask) where I can submit information to be put in a database. I have a weird bug however, where for some reason when I use my discord account's data, it updates every other user's data to be the same (except for discord_id which is primary key and also payments linked to that id) and also replaces any further inserts. This may be a logic error, or could possibly be a peewee error somehow. Here is an example of how data is changed. #### Example 1 Discriminator on insert for person 1: 3606 Discriminator on insert for person x: 0661 Discriminators after person x inserted: 0232, 0232 #### Example 2 So I thought it was some indexing issue so I tried this: Discriminator on insert for person 1: 3606 Discriminator on insert for person 2: 0434 Discriminators after person x inserted: 3606, 0434 Discriminator on insert for person x: 0232 Discriminators after person x inserted: 0232, 0232, 0232 This is very confusing to me, as the code to create a new user replaces the data of other users. As you see, person 2 does not change person 1 but person x does. However, this gets even more confusing, as when person 2 is inserted after person x, person 2 has the same data (except for primary key) as person x. ### Possible reasons - Person x has "()" in their username, which is put in the database (EDIT: after changing my username, nothing changed) - Person x is my current user (logic error in code as access token effects somehow?) - Past that I do not know ### Relevant code (mind my spaghet code) ```py @QUART.route(API_PRE + "add_payment", methods=["POST"]) async def add_payment(): """ Add a new payment to existing or new user. """ if request.method == "POST": request_parameters = await request.get_json(force=True, silent=True) discord_id = request_parameters["discord_id"] amount_payed_usd = request_parameters["amount_payed_usd"] subtype = request_parameters["subtype"] pre_payment = request_parameters["pre_payment"] if ( request_parameters["discord_access_token"] is not None and discord_id is not None and amount_payed_usd is not None and subtype is not None and pre_payment is not None ): try: member = Member(request_parameters["discord_access_token"], MAIN_BOT) if member.is_manager == True: user_data = MAIN_BOT.get_data_from_id(discord_id) last_seen_username = user_data["user"]["username"] print(last_seen_username) last_seen_discriminator = user_data["user"]["discriminator"] print(last_seen_discriminator) # get pfp URL if user_data["user"]["avatar"] is None: last_seen_pfp = "" else: last_seen_pfp = f"https://cdn.discordapp.com/avatars/{discord_id}/{user_data['user']['avatar']}" # find or add user user = User.get_or_none(User.discord_id == discord_id) if user is None: # suspect code user = User.create( discord_id=discord_id, last_seen_username=last_seen_username, last_seen_discriminator=last_seen_discriminator, last_seen_pfp=last_seen_pfp, ) debug(f"NEW USER ADDED BY MANAGER ADDITION ({discord_id})") print(vars(user)) if pre_payment == True: # pre-payment logic update_q = User.select(User.discord_id==discord_id).update(pre_payment=True, pre_payment_amount_payed_usd=amount_payed_usd) update_q.execute() debug(f"ADDING PRE-PAYMENT ({subtype}) FOR {discord_id}") else: # non pre-payment logic Payment.create( discord_id=discord_id, subtype=subtype, ms_initiated=current_milli_time(), amount_payed_usd=amount_payed_usd, ) debug(f"PAYMENT COMPLETED (NOT PRE-PAYMENT) ({subtype}) for user {discord_id}") return jsonify(is_error=False) else: return jsonify(is_error=True, error_msg="You do not have the permission to use this endpoint") except Exception as error: MAIN_BOT.error_to_developer(error, "add_payment()") return jsonify(is_error=True, error_msg="Could not add payment (User Discord ID may be invalid)") else: return jsonify(is_error=True, error_msg="Required data not passed (access token)") ``` The only two operations here are .create and .update, but the the .update is, first of all, not even run when the bad operation happens (as I do not pass pre_payment as true), but also the update is on a .select(). The only suspect code I see to make a difference is the User.create(...) clause. Also for further reference, "access token" is a token that managers pass to the API via a web interface (which is checked for appropriate roles), checked by the Member class creation, however this is never referenced again past role check By the way, it is not an issue about data creation, but one about possible data corruption either by my own error or peewee error, however I cannot conclude anything from this, but I would appreciate any support, thank you.
{ "url": "https://api.github.com/repos/coleifer/peewee/issues/2559/reactions", "total_count": 0, "+1": 0, "-1": 0, "laugh": 0, "hooray": 0, "confused": 0, "heart": 0, "rocket": 0, "eyes": 0 }
https://api.github.com/repos/coleifer/peewee/issues/2559/timeline
null
completed
null
null
https://api.github.com/repos/coleifer/peewee/issues/2558
https://api.github.com/repos/coleifer/peewee
https://api.github.com/repos/coleifer/peewee/issues/2558/labels{/name}
https://api.github.com/repos/coleifer/peewee/issues/2558/comments
https://api.github.com/repos/coleifer/peewee/issues/2558/events
https://github.com/coleifer/peewee/issues/2558
1,187,379,589
I_kwDOAA7yGM5GxfmF
2,558
Index of Get Failed Row on insert_many
{ "login": "weaverjess", "id": 87557577, "node_id": "MDQ6VXNlcjg3NTU3NTc3", "avatar_url": "https://avatars.githubusercontent.com/u/87557577?v=4", "gravatar_id": "", "url": "https://api.github.com/users/weaverjess", "html_url": "https://github.com/weaverjess", "followers_url": "https://api.github.com/users/weaverjess/followers", "following_url": "https://api.github.com/users/weaverjess/following{/other_user}", "gists_url": "https://api.github.com/users/weaverjess/gists{/gist_id}", "starred_url": "https://api.github.com/users/weaverjess/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/weaverjess/subscriptions", "organizations_url": "https://api.github.com/users/weaverjess/orgs", "repos_url": "https://api.github.com/users/weaverjess/repos", "events_url": "https://api.github.com/users/weaverjess/events{/privacy}", "received_events_url": "https://api.github.com/users/weaverjess/received_events", "type": "User", "site_admin": false }
[]
closed
false
null
[]
null
[ "Either your db will tell you or it won't. Beyond that it's not really something peewee can figure out." ]
"2022-03-31T01:54:54"
"2022-03-31T02:41:24"
"2022-03-31T02:41:24"
NONE
null
Is there anyway to receive the index of a failed row on insert_many? This could be very useful for helping have feedback to users for which row in a bulk request has failed, and thus caused the whole transaction to be thrown out.
{ "url": "https://api.github.com/repos/coleifer/peewee/issues/2558/reactions", "total_count": 0, "+1": 0, "-1": 0, "laugh": 0, "hooray": 0, "confused": 0, "heart": 0, "rocket": 0, "eyes": 0 }
https://api.github.com/repos/coleifer/peewee/issues/2558/timeline
null
completed
null
null
https://api.github.com/repos/coleifer/peewee/issues/2557
https://api.github.com/repos/coleifer/peewee
https://api.github.com/repos/coleifer/peewee/issues/2557/labels{/name}
https://api.github.com/repos/coleifer/peewee/issues/2557/comments
https://api.github.com/repos/coleifer/peewee/issues/2557/events
https://github.com/coleifer/peewee/issues/2557
1,184,153,406
I_kwDOAA7yGM5GlL8-
2,557
Sqlite Memory DB gets closed after `with db` context manager
{ "login": "mkmoisen", "id": 2534631, "node_id": "MDQ6VXNlcjI1MzQ2MzE=", "avatar_url": "https://avatars.githubusercontent.com/u/2534631?v=4", "gravatar_id": "", "url": "https://api.github.com/users/mkmoisen", "html_url": "https://github.com/mkmoisen", "followers_url": "https://api.github.com/users/mkmoisen/followers", "following_url": "https://api.github.com/users/mkmoisen/following{/other_user}", "gists_url": "https://api.github.com/users/mkmoisen/gists{/gist_id}", "starred_url": "https://api.github.com/users/mkmoisen/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/mkmoisen/subscriptions", "organizations_url": "https://api.github.com/users/mkmoisen/orgs", "repos_url": "https://api.github.com/users/mkmoisen/repos", "events_url": "https://api.github.com/users/mkmoisen/events{/privacy}", "received_events_url": "https://api.github.com/users/mkmoisen/received_events", "type": "User", "site_admin": false }
[]
closed
false
null
[]
null
[ "In-memory databases are ephemeral and only last for the lifetime of the connection. This is by design.", "Hi @coleifer \r\n\r\nIn SQLAlchemy it doesn't behave this way. \r\n\r\nORM style:\r\n\r\n```\r\n\r\nwith Session() as session:\r\n session.execute(insert(User).values(name='foo'))\r\n session.commit()\r\n\r\n\r\nwith Session() as session:\r\n result = session.execute(select(User))\r\n print(result.scalars().one().name)\r\n\r\n```\r\n\r\nCore style:\r\n\r\n```\r\nwith engine.connect() as conn:\r\n conn.execute(insert(User).values(name='foo'))\r\n conn.commit()\r\n\r\nwith engine.connect() as conn:\r\n result = conn.execute(select(User))\r\n print(result.fetchall()[0])\r\n```", "SQLAlchemy doesn't event destroy the DB when you call `close`:\r\n\r\n```\r\n\r\nfrom sqlalchemy import create_engine, text\r\n\r\nengine = create_engine(\"sqlite+pysqlite:///:memory:\", echo=True, future=True)\r\n\r\nconn = engine.connect()\r\n\r\nconn.execute(text('create table foo (c1 int)'))\r\nconn.execute(text(\"insert into foo values (1)\"))\r\nconn.commit()\r\n\r\nconn.close()\r\n\r\nconn = engine.connect()\r\nconn.execute(text('select c1 from foo')).fetchall()\r\n```", "I think this approach makes sense. It is common to use Sqlite in memory for testing.\r\n\r\nIf the behavior is to \"actually\" close the database this makes it all but impossible to use in-memory sqlite for this use case.\r\n\r\nE.g. if you are using the flask request style:\r\n\r\n```\r\n@app.before_request\r\ndef before_request():\r\n database.connect()\r\n\r\n@app.after_request\r\ndef after_request(response):\r\n database.close()\r\n return response\r\n```\r\n\r\nThis works fine for all databases, except for SQLite in memory.", "There are other gotcha's when using an in-memory sqlite database, such as that it is specific to the connection, so it doesn't work in multi-thread environments either (based on how Peewee by default uses thread-per-connection (although this can be overridden, see threadsafe param [here](http://docs.peewee-orm.com/en/latest/peewee/api.html#Database))).\r\n\r\nAs I said, this is by design. Many other testers assume, when using in-mem db, that it starts as a blank slate every time. If you want `close()` to no-op, then just subclass and override. Alternatively use a named temporary file instead of an in-memory db." ]
"2022-03-29T00:48:21"
"2022-03-29T18:11:22"
"2022-03-29T12:35:34"
NONE
null
Calling `with db` on a SqliteDatabase(':memory:') will end up closing the database after the context manager exits. The code for this is [here](https://github.com/coleifer/peewee/blob/master/peewee.py#L3098). This will result in destroying the database, such that it will be a brand new database next time it is used. I think that for in memory `SqliteDatabase` the connection should never be closed unless the user calls `db.close()` explicitly. Actually I'm not sure if it should even be closed in that case. Maybe it would be best to only close on `__del__` ? Can we modify `SqliteDatabase` to override `__exit__` and avoid calling `self.close()` if it is an in memory database? I'm not sure if there is a way to take a db.connection() and determine if it is in-memory. If not, then the SqliteDatabase constructor could set a flag like `self._in_memory = database == ':memory:'`. ``` from peewee import SqliteDatabase, Model, CharField from peewee import SQL # doesn't matter whether you use autoconnect=True or False db = SqliteDatabase(':memory:', pragmas={'foreign_keys': 'ON'}) class BaseModel(Model): class Meta: database = db class User(BaseModel): email = CharField(max_length=30, null=False, unique=True) with db: db.create_tables([User]) result = db.execute(SQL("select name from sqlite_schema where type = 'table' and name not like 'sqlite_%'")) tables = list(result) print(tables) assert tables[0] == ('user',) # The in memory database has now been closed. Next time we call `with db:` there will be no tables: with db: result = db.execute(SQL("select name from sqlite_schema where type = 'table' and name not like 'sqlite_%'")) tables = list(result) print(tables) # The table is now missing assert not tables ```
{ "url": "https://api.github.com/repos/coleifer/peewee/issues/2557/reactions", "total_count": 0, "+1": 0, "-1": 0, "laugh": 0, "hooray": 0, "confused": 0, "heart": 0, "rocket": 0, "eyes": 0 }
https://api.github.com/repos/coleifer/peewee/issues/2557/timeline
null
completed
null
null
https://api.github.com/repos/coleifer/peewee/issues/2556
https://api.github.com/repos/coleifer/peewee
https://api.github.com/repos/coleifer/peewee/issues/2556/labels{/name}
https://api.github.com/repos/coleifer/peewee/issues/2556/comments
https://api.github.com/repos/coleifer/peewee/issues/2556/events
https://github.com/coleifer/peewee/issues/2556
1,182,588,195
I_kwDOAA7yGM5GfN0j
2,556
Insert from_select Mysql returns number of rows affected, instead of lastrowid/pk
{ "login": "mkmoisen", "id": 2534631, "node_id": "MDQ6VXNlcjI1MzQ2MzE=", "avatar_url": "https://avatars.githubusercontent.com/u/2534631?v=4", "gravatar_id": "", "url": "https://api.github.com/users/mkmoisen", "html_url": "https://github.com/mkmoisen", "followers_url": "https://api.github.com/users/mkmoisen/followers", "following_url": "https://api.github.com/users/mkmoisen/following{/other_user}", "gists_url": "https://api.github.com/users/mkmoisen/gists{/gist_id}", "starred_url": "https://api.github.com/users/mkmoisen/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/mkmoisen/subscriptions", "organizations_url": "https://api.github.com/users/mkmoisen/orgs", "repos_url": "https://api.github.com/users/mkmoisen/repos", "events_url": "https://api.github.com/users/mkmoisen/events{/privacy}", "received_events_url": "https://api.github.com/users/mkmoisen/received_events", "type": "User", "site_admin": false }
[]
closed
false
null
[]
null
[ "\r\nUsing the pymysql driver, we can access the lastrowid for both regular inserts and insert_from style:\r\n\r\n```\r\nconn = pymysql.cononect(user='mysql', password='mysql', database='mysql')\r\ncur = conn.cursor()\r\n\r\ncur.execute(\"insert into users (name) values ('a')\")\r\nprint(cur.lastrowid)\r\n\r\ncur.execute(\"insert into users (name) select 'b'\")\r\nprint(cur.lastrowid)\r\n```", "The reason for this behavior is because `_WriteQuery._execute` checks if the insert has a RETURNING clause (only available on Postgresql), and then calls `_WriteQuery.handle_result` which returns `database.rows_affected(cursor)`. Because of this implementation, it will always return the number of rows affected for MySQL.\r\n\r\nI have a proposal to have mysql return a cursor while making this backwards compatible with the current api. \r\n\r\nIf mysql users want to return the lastrowid from a INSERT ... SELECT, they should add a `.returning(Users.id)`. Today, this will fail of course because RETURNING isn't supported. The proposal is that if an insert is on mysql and contains _returning, peewee will strip the RETURNING clause, execute the SQL, but return either the cursor (like postgresql) or the lastrowid, instead of the rows affected.\r\n\r\nThere are many ways to do it. Here is one:\r\n\r\n```\r\n def execute_returning(self, database):\r\n if self._cursor_wrapper is None:\r\n if database.returning_clause:\r\n cursor = database.execute(self)\r\n self._cursor_wrapper = self._get_cursor_wrapper(cursor)\r\n else:\r\n self._returning = None\r\n cursor = database.execute(self)\r\n self._cursor_wrapper = MysqlInsertFromSelectCursorWrapper(cursor)\r\n return self._cursor_wrapper\r\n```\r\n\r\nThis MysqlInsertFromSelectCursorWrapper would basically do this:\r\n\r\n```\r\n\r\nclass MysqlInsertFromSelectCursorWrapper(CursorWrapper):\r\n def iterator():\r\n yield (self.cursor.lastrowid,)\r\n \r\n```\r\n", "This behavior was changed in commit ab4337669 / 3.12.0 - https://github.com/coleifer/peewee/releases/tag/3.12.0 -- the issue #2026 shows one user asking how to get the affected rowcount when doing a bulk insert. So it seems you cannot please everyone. I think this may be particularly relevant for users who are writing UPSERT type bulk queries. At any rate, I do agree that making this be Peewee's default behavior in such cases may have been a little premature.\r\n\r\nI think what I'm going to do is this:\r\n\r\n* revert the logic in the above commit so that INSERT queries on non-returning DBs will return last-insert-id by default (for \"simple\" inserts as well as bulk)\r\n* add a new flag that users can append to their INSERTs if they prefer to receive the rowcount instead.\r\n\r\nNote that Sqlite also now supports the RETURNING clause, but for backwards-compatibility we do not return the cursor or append the RETURNING clause for Sqlite automatically at the moment (explicitly specifying returning works fine w/sqlite, though).", "Hi @coleifer , that sound fine to me. Thank you.\r\n\r\nI suppose the only issue is that the API is different when using postgresql compared to when using mysql. However I don't think this is too big of an issue, SQLAlchemy also has a different API for postgres cursors vs mysql cursors.\r\n\r\nThanks for letting me know about sqlite, I was under the impression it did not support RETURNING. I'll be adding that change to my framework.\r\n\r\n---\r\n\r\nIncidentally, apparently MariaDB [supports RETURNING](https://mariadb.com/kb/en/insertreturning/). MariaDB is \"compatible\" with MySQL and even uses the same python database driver (such as pymysql or mysql-connector etc). Have you tried Peewee with MariaDB? I don't have MariaDB installed, but would be curious to know if the pymsql/etc drivers are able to handle support for RETURNING.\r\n\r\nIf the drivers do support RETURNING, peewee will work so long as the user manually adds .returning(Users), right?\r\n\r\nOff the top of your head, do you know if I would be able to detect if a user is using MariaDB? I'm writing a framework on top of peewee. I use the following to check for different databases, which won't work for MariaDB:\r\n\r\n is_postgres = isinstance(db, PostgresqlDatabase)\r\n is_mysql = isinstance(db, MySQLDatabase)\r\n", "I do notice, however, that the value of `cursor.lastrowid` is not quite correct when doing an INSERT FROM on MariaDB with pymysql -- perhaps that may have something to do with the original change, although I didn't mention it anywhere if that's the case (dammit).\r\n\r\nExample script:\r\n\r\n```python\r\n\r\n#... insert 4 rows into a table named \"reg\" ...\r\nReg.insert_many([{'name': 'reg%s' % i} for i in range(1, 5)]).execute()\r\n\r\nquery = Reg.select(Reg.name)\r\nlastrow = User.insert_from(query, ['username']).execute()\r\nprint(lastrow) # prints 1 !!\r\nfor row in User:\r\n print(row.id, row.username)\r\n# 1 reg1\r\n# 2 reg2\r\n# 3 reg3\r\n# 4 reg4 <-- this is the last row id, presumably?\r\n```\r\n\r\nTo make sure there were no bugs elsewhere I dropped a print statement into the `InsertQuery.handle_result` to print the value of `cursor.lastrowid`, and confirmed that pymysql is indeed returning `1` in this case.\r\n\r\nSo possibly this is a mariadb/oracle mysql difference, as it sounded like you were getting the actual last inserted id (4) as opposed to 1?\r\n\r\n-----------------------------\r\n\r\nAlso to respond to your new post, yes, Peewee works seamlessly with the new RETURNING syntax on MariaDB. It has the additional benefit of being useful when using a non-integer primary key.", ">Off the top of your head, do you know if I would be able to detect if a user is using MariaDB?\r\n\r\nSure:\r\n\r\n```python\r\nconn = db.connection() # Get db-api2 conn\r\nprint(conn.server_version) # or\r\nprint(conn.get_server_info())\r\n# 5.5.5-10.7.3-MariaDB-1:10.7.3+maria~bullseye-log\r\n```", "5f6a2ed should resolve the issue by restoring the original behavior (returning last-id by default).", "Hi @coleifer \r\n\r\nThanks for the change.\r\n\r\nRegarding Sqlite:\r\n\r\n> Note that Sqlite also now supports the RETURNING clause, but for backwards-compatibility we do not return the cursor or append the RETURNING clause for Sqlite automatically at the moment (explicitly specifying returning works fine w/sqlite, though).\r\n\r\nI wonder, would it be OK to check the version of sqlite and then set db.returning_clause accordingly for the user?\r\n\r\nYou could add the following to `SqliteDatabase.__init__`:\r\n\r\n self.returning_clause = sqlite3.sqlite_version >= '3.35.0'\r\n\r\n[The SQLite release notes](https://www.sqlite.org/changes.html) say that support for RETURNING was added in 3.35.0.", ">I wonder, would it be OK to check the version of sqlite and then set db.returning_clause accordingly for the user?\r\n\r\nThere were just enough \"gotcha's\" with this that I have chosen not to do it yet automatically - especially as most sqlite users are dynamically linking against their system sqlite which likely to be quite old. Setting `db.returning_clause = True` yourself on SqliteDatabase is quite simple if you do a sqlite version check (as your snippet shows).\r\n\r\nThere were also some issues with the way the sqlite query compiler was handling the result. Namely, I recall that if you were using Sqlite and specified a RETURNING clause, you *HAD* to step through all the results in order to get the query to execute fully (relevant to bulk inserts/updates/deletes). If you left the result cursor un-stepped-through I recall it could cause quite a bit of strange results.", "8c80725cdfc745a082325006c14c50b90de8354d -- this is the commit I reverted. The commit text mentions another issue:\r\n\r\n>This caused some unexpected issues when the returning cursor was not\r\n>consumed (e.g. within a savepoint), that cause the savepoint to not \r\n>able to be released. Since this is backwards-incompatible, I am going to\r\n>roll it back for now.", "I think those issues *may* have been resolved in a more recent release than the 3.35 one (and may be also related to this error message mismatch regarding 3.35 and 3.36: https://github.com/coleifer/pysqlite3/issues/34 ).", "Relevant sqlite forum link: https://www.sqlite.org/forum/forumpost/e5e99c6497b3ecb9", "Hi @coleifer \r\n\r\nThanks for the links. \r\n\r\nThat foreign key constraint error message bug in sqlite3 is unfortunate. \r\n\r\nI'm writing a library that uses peewee. I wanted to automatically add a returning clause if the database supported it.\r\n\r\nI think it might be best for me to assume that sqlite users don't have access to RETURNING for the time being.\r\n", "The issue with the query execution I believe is fixed in 3.36 and is far more concerning than the error code. So if you check for 3.36 or newer it may be safe to use returning everywhere.\r\n\r\nI'm going to revisit that patch and see how things are looking when I can find some free time." ]
"2022-03-27T16:38:01"
"2022-03-28T22:21:08"
"2022-03-28T00:16:40"
NONE
null
Using an insert_from with mysql will always return the number of rows inserted, instead of returning the lastrowid. Postgresql instead will return a result cursor from which you can derive the lastrowid. So if we use the insert_from style with MySQL there is no way to obtain the lastrowid using the public API. In Mysql: ``` # this will correctly return the lastrowid/pk: Users.insert(name='foo').execute() # this will always return 1, instead of the lastrowid/pk. Users.insert_from( Select(columns=['a']), ['name'] ).execute() ``` With Postgresql, the behavior is different, presumably because postgresql will automatically add a returning (which is not available in mysql). ``` # This will return the PK, same as mysql: Users.insert(name='foo').execute() # This returns ModelTupleCursorWrapper res = Users.insert_from( Select(columns=['a']), ['name'] ).execute() # get the pk print(list(res)[0][0]) # let's get rid of the RETURNING clause, and the behavior is the same as mysql, which is to return 1: res = Users.insert_from( Select(columns=['a']), ['name'] ).returning().execute() ```
{ "url": "https://api.github.com/repos/coleifer/peewee/issues/2556/reactions", "total_count": 0, "+1": 0, "-1": 0, "laugh": 0, "hooray": 0, "confused": 0, "heart": 0, "rocket": 0, "eyes": 0 }
https://api.github.com/repos/coleifer/peewee/issues/2556/timeline
null
completed
null
null
https://api.github.com/repos/coleifer/peewee/issues/2555
https://api.github.com/repos/coleifer/peewee
https://api.github.com/repos/coleifer/peewee/issues/2555/labels{/name}
https://api.github.com/repos/coleifer/peewee/issues/2555/comments
https://api.github.com/repos/coleifer/peewee/issues/2555/events
https://github.com/coleifer/peewee/issues/2555
1,180,347,356
I_kwDOAA7yGM5GWqvc
2,555
Some issues about "(2006, "MySQL server has gone away (BrokenPipeError(32, 'Broken pipe'))"
{ "login": "czf0613", "id": 46845934, "node_id": "MDQ6VXNlcjQ2ODQ1OTM0", "avatar_url": "https://avatars.githubusercontent.com/u/46845934?v=4", "gravatar_id": "", "url": "https://api.github.com/users/czf0613", "html_url": "https://github.com/czf0613", "followers_url": "https://api.github.com/users/czf0613/followers", "following_url": "https://api.github.com/users/czf0613/following{/other_user}", "gists_url": "https://api.github.com/users/czf0613/gists{/gist_id}", "starred_url": "https://api.github.com/users/czf0613/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/czf0613/subscriptions", "organizations_url": "https://api.github.com/users/czf0613/orgs", "repos_url": "https://api.github.com/users/czf0613/repos", "events_url": "https://api.github.com/users/czf0613/events{/privacy}", "received_events_url": "https://api.github.com/users/czf0613/received_events", "type": "User", "site_admin": false }
[]
closed
false
null
[]
null
[ "Peewees pool and database implementation rely on connection-per-thread. This works well with regular python and gevent, but not with asyncio. Asyncio needs \"connection per asyncio context\" or behind a thread pool.", "> Peewees pool and database implementation rely on connection-per-thread. This works well with regular python and gevent, but not with asyncio. Asyncio needs \"connection per asyncio context\" or behind a thread pool.\r\n\r\nWell......is there any idea to avoid this problem? asyncio is really important in FastAPI......", "@czf0613 If your particular use case really needs async, I think you'll have to use sqlalchemy instead of peewee. \r\n\r\nHowever, for the most applications, async python will not run faster than sync python. If your use case doesn't require async, you can use FastAPI in regular mode by not defining your functions as async def if I remember correctly.\r\n\r\n" ]
"2022-03-25T05:01:17"
"2022-03-25T18:53:32"
"2022-03-25T11:42:10"
NONE
null
I am using FastAPI as my backend framework. And I also noticed this problem solution in chatpter "framework integration", which shows: ``` python # This hook ensures that a connection is opened to handle any queries # generated by the request. @app.on_event("startup") def startup(): db.connect() # This hook ensures that the connection is closed when we've finished # processing the request. @app.on_event("shutdown") def shutdown(): if not db.is_closed(): db.close() ``` I followed this instruction but still get the same error, "peewee.OperationalError: (2006, "MySQL server has gone away (BrokenPipeError(32, 'Broken pipe'))")". I also get another error like "peewee.InterfaceError: (0, '')". Did I make any mistakes? Maybe it's not compatible with connection pool? Here is the piece of code that I configure the database: ```python from playhouse.pool import PooledMySQLDatabase db = PooledMySQLDatabase( 'xxxx', max_connections=32, stale_timeout=60, user='xxxxxxxxxxxxx', password='xxxxxxxxxxx', host='xxxxxxxx', port=3306, charset='utf8' ) class BaseModel(Model): class Meta: database = db ``` Looking forward to your reply, thanks a million!
{ "url": "https://api.github.com/repos/coleifer/peewee/issues/2555/reactions", "total_count": 0, "+1": 0, "-1": 0, "laugh": 0, "hooray": 0, "confused": 0, "heart": 0, "rocket": 0, "eyes": 0 }
https://api.github.com/repos/coleifer/peewee/issues/2555/timeline
null
completed
null
null
https://api.github.com/repos/coleifer/peewee/issues/2554
https://api.github.com/repos/coleifer/peewee
https://api.github.com/repos/coleifer/peewee/issues/2554/labels{/name}
https://api.github.com/repos/coleifer/peewee/issues/2554/comments
https://api.github.com/repos/coleifer/peewee/issues/2554/events
https://github.com/coleifer/peewee/issues/2554
1,176,740,789
I_kwDOAA7yGM5GI6O1
2,554
Missing parametter `seen` in docstring
{ "login": "Seluj78", "id": 4641317, "node_id": "MDQ6VXNlcjQ2NDEzMTc=", "avatar_url": "https://avatars.githubusercontent.com/u/4641317?v=4", "gravatar_id": "", "url": "https://api.github.com/users/Seluj78", "html_url": "https://github.com/Seluj78", "followers_url": "https://api.github.com/users/Seluj78/followers", "following_url": "https://api.github.com/users/Seluj78/following{/other_user}", "gists_url": "https://api.github.com/users/Seluj78/gists{/gist_id}", "starred_url": "https://api.github.com/users/Seluj78/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/Seluj78/subscriptions", "organizations_url": "https://api.github.com/users/Seluj78/orgs", "repos_url": "https://api.github.com/users/Seluj78/repos", "events_url": "https://api.github.com/users/Seluj78/events{/privacy}", "received_events_url": "https://api.github.com/users/Seluj78/received_events", "type": "User", "site_admin": false }
[]
closed
false
null
[]
null
[ "That's used internally to avoid cycles in graph when recursing. Ignore.", "Could you maybe rename it `_seen` and note it in the docstring just in case ? :) So you don't have other questions ;)" ]
"2022-03-22T12:53:24"
"2022-03-22T12:56:19"
"2022-03-22T12:55:20"
NONE
null
As `seen` here (lol) https://github.com/coleifer/peewee/blob/a6198b96f475a2ee9687f36eda1cbb539907c56a/playhouse/shortcuts.py#L14-L32 Cheers!
{ "url": "https://api.github.com/repos/coleifer/peewee/issues/2554/reactions", "total_count": 0, "+1": 0, "-1": 0, "laugh": 0, "hooray": 0, "confused": 0, "heart": 0, "rocket": 0, "eyes": 0 }
https://api.github.com/repos/coleifer/peewee/issues/2554/timeline
null
completed
null
null
https://api.github.com/repos/coleifer/peewee/issues/2553
https://api.github.com/repos/coleifer/peewee
https://api.github.com/repos/coleifer/peewee/issues/2553/labels{/name}
https://api.github.com/repos/coleifer/peewee/issues/2553/comments
https://api.github.com/repos/coleifer/peewee/issues/2553/events
https://github.com/coleifer/peewee/issues/2553
1,170,815,295
I_kwDOAA7yGM5FyTk_
2,553
Select specific columns from Model alias
{ "login": "conqp", "id": 3766192, "node_id": "MDQ6VXNlcjM3NjYxOTI=", "avatar_url": "https://avatars.githubusercontent.com/u/3766192?v=4", "gravatar_id": "", "url": "https://api.github.com/users/conqp", "html_url": "https://github.com/conqp", "followers_url": "https://api.github.com/users/conqp/followers", "following_url": "https://api.github.com/users/conqp/following{/other_user}", "gists_url": "https://api.github.com/users/conqp/gists{/gist_id}", "starred_url": "https://api.github.com/users/conqp/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/conqp/subscriptions", "organizations_url": "https://api.github.com/users/conqp/orgs", "repos_url": "https://api.github.com/users/conqp/repos", "events_url": "https://api.github.com/users/conqp/events{/privacy}", "received_events_url": "https://api.github.com/users/conqp/received_events", "type": "User", "site_admin": false }
[]
closed
false
null
[]
null
[ "Are you able to produce a small or concise demonstration of the issue, as you see it? Also note that it's probably a bad idea to override the `select()` method on a model class as that method is used by other functions -- better to call it something else that doesn't conflict with such a common method.", "I think I understand after typing out my own implementation. Here is my example, which I'll be referring to:\r\n\r\n```python\r\nclass File(Base):\r\n filename = TextField()\r\n data = BlobField(default=b'')\r\n\r\nclass User(Base):\r\n username = TextField()\r\n profile = ForeignKeyField(File, null=True, lazy_load=False, backref='user_profiles')\r\n backup = ForeignKeyField(File, null=True, lazy_load=False, backref='user_backups')\r\n\r\ndb.create_tables([User, File])\r\n\r\nf1 = File.create(filename='profile-pic.jpg')\r\nf2 = File.create(filename='backup.json')\r\nuser = User.create(username='u1', profile=f1, backup=f2)\r\n\r\nProfileFile = File.alias()\r\nBackupFile = File.alias()\r\n\r\nquery = (User\r\n .select(User, ProfileFile.filename, BackupFile.filename)\r\n .join_from(User, ProfileFile, on=(User.profile == ProfileFile.id))\r\n .join_from(User, BackupFile, on=(User.backup == BackupFile.id))\r\n .order_by(User.username))\r\n\r\nfor user in query:\r\n print(user.username, user.profile.filename, user.backup.filename)\r\n```\r\n\r\nThe issue, as I understand it, is that you want to encapsulate the list of fields selected from the file aliases. The issue is that those `meta_fields()` returns references to the fields on the `File` - not the columns on the specific alias.\r\n\r\nWorkarounds:\r\n\r\n```python\r\nclass File(Base):\r\n filename = TextField()\r\n data = BlobField(default=b'')\r\n\r\n def meta_fields(self):\r\n return [getattr(self, f) for f in ['id', 'filename']]\r\n\r\n...\r\n\r\nquery = (User\r\n .select(\r\n User,\r\n *ProfileFile.meta_fields(ProfileFile),\r\n *BackupFile.meta_fields(BackupFile))\r\n .join_from(User, ProfileFile, on=(User.profile == ProfileFile.id))\r\n .join_from(User, BackupFile, on=(User.backup == BackupFile.id))\r\n .order_by(User.username))\r\n```\r\n\r\nThe above ensures that the fields are referenced to the alias.\r\n\r\nOr alternatively you can use your specific model alias class, as you've done.\r\n\r\nBut if you are returning the field instances from the model itself, there's no way for peewee to know which alias they are intended to reference.", "Fair enough.\r\n\r\n> But if you are returning the field instances from the model itself, there's no way for peewee to know which alias they are intended to reference.\r\n\r\nNot with the current implementation, indeed. That's why the `ModelAlias` may better be off as a subclass of the given model, that converts its fields into appropriate `FieldAlias`es. This way, the `ModelAlias` could preserve all functionality of the encapsulated model." ]
"2022-03-16T10:21:12"
"2022-03-16T13:19:07"
"2022-03-16T13:11:51"
CONTRIBUTOR
null
I have a use case where I need to join two foreign keys with the same table: ```python class Configuration(CustomerModel): """Customer configuration for charts.""" name = HTMLCharField(255) description = HTMLCharField(255, null=True) ... logo = ForeignKeyField( File, column_name='logo', null=True, lazy_load=False) dummy_picture = ForeignKeyField( File, column_name='dummy_picture', null=True, lazy_load=False) @classmethod def select(cls, *args, cascade: bool = False) -> Select: """Selects records.""" if not cascade: return super().select(*args) logo_file = File.alias() logo_file_db_file = FileDBFile.alias() dummy_picture_file = File.alias() dummy_picture_file_db_file = FileDBFile.alias() return super().select( cls, Colors, logo_file, *logo_file_db_file.meta_fields(), dummy_picture_file, *dummy_picture_file_db_file.meta_fields(), *args, cascade=cascade ).join_from( cls, Colors ).join_from( cls, logo_file, on=cls.logo == logo_file.id, join_type=JOIN.LEFT_OUTER ).join( logo_file_db_file, join_type=JOIN.LEFT_OUTER).join_from( cls, dummy_picture_file, on=cls.dummy_picture == dummy_picture_file.id, join_type=JOIN.LEFT_OUTER ).join( dummy_picture_file_db_file, join_type=JOIN.LEFT_OUTER ) ``` However, I do only want to select certain fields of the respective aliases. In this case it is because I reference a file database, which also contains a BLOB field with the data, that I don't need and just want the metadata. Here's the appropriate model: ```python class File(FileDBModel): """A file entry.""" bytes = BlobField() mimetype = CharField(255) sha256sum = FixedCharField(64) size = BigIntegerField() # File size in bytes. created = DateTimeField(default=datetime.now) last_access = DateTimeField(null=True, default=None) accessed = IntegerField(default=0) ... @classmethod def meta_fields(cls) -> Iterable[Field]: """Returns an iterable of metadata fields.""" return ( cls.id, cls.mimetype, cls.sha256sum, cls.size, cls.created, cls.last_access, cls.accessed ) ``` However, when I do a select on the respective fields, I get an error: ```python >>> File.select(*File.meta_fields()).get() <File: 61805ba3947f7bb245084540d05bf025709ee26678c5a069fcc8f37d8a2fb51f> >>> alias = File.alias() >>> alias.select(*alias.meta_fields()).get() Traceback (most recent call last): File "/usr/local/lib/python3.9/dist-packages/peewee.py", line 3160, in execute_sql cursor.execute(sql, params or ()) File "/usr/lib/python3/dist-packages/pymysql/cursors.py", line 170, in execute result = self._query(query) File "/usr/lib/python3/dist-packages/pymysql/cursors.py", line 328, in _query conn.query(q) File "/usr/lib/python3/dist-packages/pymysql/connections.py", line 517, in query self._affected_rows = self._read_query_result(unbuffered=unbuffered) File "/usr/lib/python3/dist-packages/pymysql/connections.py", line 732, in _read_query_result result.read() File "/usr/lib/python3/dist-packages/pymysql/connections.py", line 1075, in read first_packet = self.connection._read_packet() File "/usr/lib/python3/dist-packages/pymysql/connections.py", line 684, in _read_packet packet.check_error() File "/usr/lib/python3/dist-packages/pymysql/protocol.py", line 220, in check_error err.raise_mysql_exception(self._data) File "/usr/lib/python3/dist-packages/pymysql/err.py", line 109, in raise_mysql_exception raise errorclass(errno, errval) pymysql.err.InternalError: (1054, "Unknown column 't1.id' in 'field list'") During handling of the above exception, another exception occurred: Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/local/lib/python3.9/dist-packages/peewee.py", line 6933, in get return clone.execute(database)[0] File "/usr/local/lib/python3.9/dist-packages/peewee.py", line 1911, in inner return method(self, database, *args, **kwargs) File "/usr/local/lib/python3.9/dist-packages/peewee.py", line 1982, in execute return self._execute(database) File "/usr/local/lib/python3.9/dist-packages/peewee.py", line 2155, in _execute cursor = database.execute(self) File "/usr/local/lib/python3.9/dist-packages/peewee.py", line 3173, in execute return self.execute_sql(sql, params, commit=commit) File "/usr/local/lib/python3.9/dist-packages/peeweeplus-1.19.dev28+g607d1d2-py3.9.egg/peeweeplus/database.py", line 26, in execute_sql return super().execute_sql(*args, **kwargs) File "/usr/local/lib/python3.9/dist-packages/peewee.py", line 3167, in execute_sql self.commit() File "/usr/local/lib/python3.9/dist-packages/peewee.py", line 2933, in __exit__ reraise(new_type, new_type(exc_value, *exc_args), traceback) File "/usr/local/lib/python3.9/dist-packages/peewee.py", line 191, in reraise raise value.with_traceback(tb) File "/usr/local/lib/python3.9/dist-packages/peewee.py", line 3160, in execute_sql cursor.execute(sql, params or ()) File "/usr/lib/python3/dist-packages/pymysql/cursors.py", line 170, in execute result = self._query(query) File "/usr/lib/python3/dist-packages/pymysql/cursors.py", line 328, in _query conn.query(q) File "/usr/lib/python3/dist-packages/pymysql/connections.py", line 517, in query self._affected_rows = self._read_query_result(unbuffered=unbuffered) File "/usr/lib/python3/dist-packages/pymysql/connections.py", line 732, in _read_query_result result.read() File "/usr/lib/python3/dist-packages/pymysql/connections.py", line 1075, in read first_packet = self.connection._read_packet() File "/usr/lib/python3/dist-packages/pymysql/connections.py", line 684, in _read_packet packet.check_error() File "/usr/lib/python3/dist-packages/pymysql/protocol.py", line 220, in check_error err.raise_mysql_exception(self._data) File "/usr/lib/python3/dist-packages/pymysql/err.py", line 109, in raise_mysql_exception raise errorclass(errno, errval) peewee.InternalError: (1054, "Unknown column 't1.id' in 'field list'") >>> alias.select(*File.meta_fields()).get() Traceback (most recent call last): File "/usr/local/lib/python3.9/dist-packages/peewee.py", line 3160, in execute_sql cursor.execute(sql, params or ()) File "/usr/lib/python3/dist-packages/pymysql/cursors.py", line 170, in execute result = self._query(query) File "/usr/lib/python3/dist-packages/pymysql/cursors.py", line 328, in _query conn.query(q) File "/usr/lib/python3/dist-packages/pymysql/connections.py", line 517, in query self._affected_rows = self._read_query_result(unbuffered=unbuffered) File "/usr/lib/python3/dist-packages/pymysql/connections.py", line 732, in _read_query_result result.read() File "/usr/lib/python3/dist-packages/pymysql/connections.py", line 1075, in read first_packet = self.connection._read_packet() File "/usr/lib/python3/dist-packages/pymysql/connections.py", line 684, in _read_packet packet.check_error() File "/usr/lib/python3/dist-packages/pymysql/protocol.py", line 220, in check_error err.raise_mysql_exception(self._data) File "/usr/lib/python3/dist-packages/pymysql/err.py", line 109, in raise_mysql_exception raise errorclass(errno, errval) pymysql.err.InternalError: (1054, "Unknown column 't1.id' in 'field list'") During handling of the above exception, another exception occurred: Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/usr/local/lib/python3.9/dist-packages/peewee.py", line 6933, in get return clone.execute(database)[0] File "/usr/local/lib/python3.9/dist-packages/peewee.py", line 1911, in inner return method(self, database, *args, **kwargs) File "/usr/local/lib/python3.9/dist-packages/peewee.py", line 1982, in execute return self._execute(database) File "/usr/local/lib/python3.9/dist-packages/peewee.py", line 2155, in _execute cursor = database.execute(self) File "/usr/local/lib/python3.9/dist-packages/peewee.py", line 3173, in execute return self.execute_sql(sql, params, commit=commit) File "/usr/local/lib/python3.9/dist-packages/peeweeplus-1.19.dev28+g607d1d2-py3.9.egg/peeweeplus/database.py", line 26, in execute_sql return super().execute_sql(*args, **kwargs) File "/usr/local/lib/python3.9/dist-packages/peewee.py", line 3167, in execute_sql self.commit() File "/usr/local/lib/python3.9/dist-packages/peewee.py", line 2933, in __exit__ reraise(new_type, new_type(exc_value, *exc_args), traceback) File "/usr/local/lib/python3.9/dist-packages/peewee.py", line 191, in reraise raise value.with_traceback(tb) File "/usr/local/lib/python3.9/dist-packages/peewee.py", line 3160, in execute_sql cursor.execute(sql, params or ()) File "/usr/lib/python3/dist-packages/pymysql/cursors.py", line 170, in execute result = self._query(query) File "/usr/lib/python3/dist-packages/pymysql/cursors.py", line 328, in _query conn.query(q) File "/usr/lib/python3/dist-packages/pymysql/connections.py", line 517, in query self._affected_rows = self._read_query_result(unbuffered=unbuffered) File "/usr/lib/python3/dist-packages/pymysql/connections.py", line 732, in _read_query_result result.read() File "/usr/lib/python3/dist-packages/pymysql/connections.py", line 1075, in read first_packet = self.connection._read_packet() File "/usr/lib/python3/dist-packages/pymysql/connections.py", line 684, in _read_packet packet.check_error() File "/usr/lib/python3/dist-packages/pymysql/protocol.py", line 220, in check_error err.raise_mysql_exception(self._data) File "/usr/lib/python3/dist-packages/pymysql/err.py", line 109, in raise_mysql_exception raise errorclass(errno, errval) peewee.InternalError: (1054, "Unknown column 't1.id' in 'field list'") >>> ``` Am I doing something wrong here, or is this a bug? **Update** I just noticed that everything works, if I select the fields manually: ```python3 >>> alias.select(alias.id, alias.sha256sum).get() <File: 000003349b2482b0c96176f8bcf8eb6111f2f78b1c17f8078003475635bd1061> ``` And the ModelAlias does not seem to resolve the fields to field aliases: ```python >>> alias.meta_fields() (<AutoField: File.id>, <CharField: File.mimetype>, <FixedCharField: File.sha256sum>, <BigIntegerField: File.size>, <DateTimeField: File.created>, <DateTimeField: File.last_access>, <IntegerField: File.accessed>) >>> ``` Manually specifying the field aliases everywhere in the code would blow up my code significantly and create code duplication as the meta fields are always the same field. Is there a way to get the appropriate field aliases programmatically from the ModelAlias? **Workaround** I managed to fix the issue by subclassing `ModelAlias`: ```python class FileModelAlias(ModelAlias): """Alias type for File model.""" def meta_fields(self) -> Iterable[FieldAlias]: """Returns an iterable of metadata field aliases.""" return ( self.id, self.mimetype, self.sha256sum, self.size, self.created, self.last_access, self.accessed ) ``` ```python class File(FileDBModel): """A file entry.""" bytes = BlobField() mimetype = CharField(255) sha256sum = FixedCharField(64) size = BigIntegerField() # File size in bytes. created = DateTimeField(default=datetime.now) last_access = DateTimeField(null=True, default=None) accessed = IntegerField(default=0) .... @classmethod def alias(cls, alias: Optional[str] = None) -> FileModelAlias: """Return a file model alias.""" return FileModelAlias(cls, alias) ``` However, it does not feel too comfortable digging that deep into peewee's internals to get something this basic done. I think the issue lies with the `__getattr__` delegation of `ModelAlias` to the wrapped model. Maybe it should bind classmethods of the model not to the model, but to itself. Otoh this may create circular recursions in `__getattr__`. I'm going to investigate this further.
{ "url": "https://api.github.com/repos/coleifer/peewee/issues/2553/reactions", "total_count": 0, "+1": 0, "-1": 0, "laugh": 0, "hooray": 0, "confused": 0, "heart": 0, "rocket": 0, "eyes": 0 }
https://api.github.com/repos/coleifer/peewee/issues/2553/timeline
null
completed
null
null
https://api.github.com/repos/coleifer/peewee/issues/2552
https://api.github.com/repos/coleifer/peewee
https://api.github.com/repos/coleifer/peewee/issues/2552/labels{/name}
https://api.github.com/repos/coleifer/peewee/issues/2552/comments
https://api.github.com/repos/coleifer/peewee/issues/2552/events
https://github.com/coleifer/peewee/issues/2552
1,167,452,061
I_kwDOAA7yGM5Fleed
2,552
Will it support async?
{ "login": "Chise1", "id": 47511274, "node_id": "MDQ6VXNlcjQ3NTExMjc0", "avatar_url": "https://avatars.githubusercontent.com/u/47511274?v=4", "gravatar_id": "", "url": "https://api.github.com/users/Chise1", "html_url": "https://github.com/Chise1", "followers_url": "https://api.github.com/users/Chise1/followers", "following_url": "https://api.github.com/users/Chise1/following{/other_user}", "gists_url": "https://api.github.com/users/Chise1/gists{/gist_id}", "starred_url": "https://api.github.com/users/Chise1/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/Chise1/subscriptions", "organizations_url": "https://api.github.com/users/Chise1/orgs", "repos_url": "https://api.github.com/users/Chise1/repos", "events_url": "https://api.github.com/users/Chise1/events{/privacy}", "received_events_url": "https://api.github.com/users/Chise1/received_events", "type": "User", "site_admin": false }
[]
closed
false
null
[]
null
[]
"2022-03-13T01:46:36"
"2022-03-13T02:29:11"
"2022-03-13T02:29:11"
NONE
null
null
{ "url": "https://api.github.com/repos/coleifer/peewee/issues/2552/reactions", "total_count": 0, "+1": 0, "-1": 0, "laugh": 0, "hooray": 0, "confused": 0, "heart": 0, "rocket": 0, "eyes": 0 }
https://api.github.com/repos/coleifer/peewee/issues/2552/timeline
null
completed
null
null
https://api.github.com/repos/coleifer/peewee/issues/2551
https://api.github.com/repos/coleifer/peewee
https://api.github.com/repos/coleifer/peewee/issues/2551/labels{/name}
https://api.github.com/repos/coleifer/peewee/issues/2551/comments
https://api.github.com/repos/coleifer/peewee/issues/2551/events
https://github.com/coleifer/peewee/issues/2551
1,165,407,621
I_kwDOAA7yGM5FdrWF
2,551
Missing TableFunction
{ "login": "AA-Stargazer", "id": 78987858, "node_id": "MDQ6VXNlcjc4OTg3ODU4", "avatar_url": "https://avatars.githubusercontent.com/u/78987858?v=4", "gravatar_id": "", "url": "https://api.github.com/users/AA-Stargazer", "html_url": "https://github.com/AA-Stargazer", "followers_url": "https://api.github.com/users/AA-Stargazer/followers", "following_url": "https://api.github.com/users/AA-Stargazer/following{/other_user}", "gists_url": "https://api.github.com/users/AA-Stargazer/gists{/gist_id}", "starred_url": "https://api.github.com/users/AA-Stargazer/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/AA-Stargazer/subscriptions", "organizations_url": "https://api.github.com/users/AA-Stargazer/orgs", "repos_url": "https://api.github.com/users/AA-Stargazer/repos", "events_url": "https://api.github.com/users/AA-Stargazer/events{/privacy}", "received_events_url": "https://api.github.com/users/AA-Stargazer/received_events", "type": "User", "site_admin": false }
[]
closed
false
null
[]
null
[ "I imported traceback to sqlite3_ext.py, and added \"traceback.print_exc()\" to except statement, this is what gave:\r\n File \"C:\\Users\\Enesu\\AppData\\Local\\Packages\\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\\LocalCache\\local-packages\\Python39\\site-packages\\playhouse\\sqlite_ext.py\", line 22, in <module>\r\n from playhouse._sqlite_ext import (\r\nModuleNotFoundError: No module named 'playhouse._sqlite_ext'", "You need to compile the c extension to use those.", "the .pyx files?\r\nis GCC works on them?", "read the docs... http://docs.peewee-orm.com/en/latest/peewee/installation.html", "Thank you very much for both solution and fast response." ]
"2022-03-10T15:57:03"
"2022-03-10T16:51:49"
"2022-03-10T16:22:15"
NONE
null
I'm trying to use the table function from "from playhouse.sqlite_ext import TableFunction" but it gives this error: `Traceback (most recent call last): File ".../main5.py", line 46, in <module> from playhouse.sqlite_ext import TableFunction ImportError: cannot import name 'TableFunction' from 'playhouse.sqlite_ext' (C:\Users\Enesu\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\playhouse\sqlite_ext.py)` I tried to look at the sqlite_ext.py file and also couldn't find TableFunction. But I could find the class TableFunction in the _sqlite_ext.pyx file. I don't know how to solve this, so I thought it would be good to submit it here. If I've done something wrong, sorry for that, it's my first time. Oh, and 1 more thing, in the sqlite_ext.py file, there is a try-except statement for importing. Maybe 1 of the files is the problem and it causes all other modules to not get imported try: from playhouse._sqlite_ext import ( backup, backup_to_file, Blob, ConnectionHelper, register_bloomfilter, register_hash_functions, register_rank_functions, sqlite_get_db_status, sqlite_get_status, TableFunction, ZeroBlob, ) CYTHON_SQLITE_EXTENSIONS = True except ImportError: CYTHON_SQLITE_EXTENSIONS = False
{ "url": "https://api.github.com/repos/coleifer/peewee/issues/2551/reactions", "total_count": 0, "+1": 0, "-1": 0, "laugh": 0, "hooray": 0, "confused": 0, "heart": 0, "rocket": 0, "eyes": 0 }
https://api.github.com/repos/coleifer/peewee/issues/2551/timeline
null
completed
null
null
https://api.github.com/repos/coleifer/peewee/issues/2550
https://api.github.com/repos/coleifer/peewee
https://api.github.com/repos/coleifer/peewee/issues/2550/labels{/name}
https://api.github.com/repos/coleifer/peewee/issues/2550/comments
https://api.github.com/repos/coleifer/peewee/issues/2550/events
https://github.com/coleifer/peewee/issues/2550
1,162,443,102
I_kwDOAA7yGM5FSXle
2,550
PostgreSQL with pg8000?
{ "login": "andy47", "id": 782758, "node_id": "MDQ6VXNlcjc4Mjc1OA==", "avatar_url": "https://avatars.githubusercontent.com/u/782758?v=4", "gravatar_id": "", "url": "https://api.github.com/users/andy47", "html_url": "https://github.com/andy47", "followers_url": "https://api.github.com/users/andy47/followers", "following_url": "https://api.github.com/users/andy47/following{/other_user}", "gists_url": "https://api.github.com/users/andy47/gists{/gist_id}", "starred_url": "https://api.github.com/users/andy47/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/andy47/subscriptions", "organizations_url": "https://api.github.com/users/andy47/orgs", "repos_url": "https://api.github.com/users/andy47/repos", "events_url": "https://api.github.com/users/andy47/events{/privacy}", "received_events_url": "https://api.github.com/users/andy47/received_events", "type": "User", "site_admin": false }
[]
closed
false
null
[]
null
[ "I'm not familiar with pg8000, but you can consult the docs on adding a new database implementation:\r\n\r\nhttp://docs.peewee-orm.com/en/latest/peewee/database.html#adding-a-new-database-driver", "Thanks, I'll take a look.", "Also I'm not too familiar with the new mac stuff but its probably fairly easy to compile psycopg2 and save yourself a lot of hassle. I've built it myself on linux many times." ]
"2022-03-08T09:49:48"
"2022-03-08T21:11:48"
"2022-03-08T13:49:25"
NONE
null
I'm developing on an Apple Silicon Mac. At the moment there isn't a way to install a binary wheel for psycopg2. So I'm looking at alternative PostgreSQL driver modules and the one that seems to work is [pg8000](https://github.com/tlocke/pg8000). Is there a way in PeeWee to substitute psycopg2 with pg8000 as the underlying PostgreSQL db-api module? I looked through the documentation but the only references I can find are to psycopg2.
{ "url": "https://api.github.com/repos/coleifer/peewee/issues/2550/reactions", "total_count": 0, "+1": 0, "-1": 0, "laugh": 0, "hooray": 0, "confused": 0, "heart": 0, "rocket": 0, "eyes": 0 }
https://api.github.com/repos/coleifer/peewee/issues/2550/timeline
null
completed
null
null
https://api.github.com/repos/coleifer/peewee/issues/2549
https://api.github.com/repos/coleifer/peewee
https://api.github.com/repos/coleifer/peewee/issues/2549/labels{/name}
https://api.github.com/repos/coleifer/peewee/issues/2549/comments
https://api.github.com/repos/coleifer/peewee/issues/2549/events
https://github.com/coleifer/peewee/issues/2549
1,161,684,490
I_kwDOAA7yGM5FPeYK
2,549
TestFKMigrationRegression fails with error in view notes_public: no such table: main.note
{ "login": "vkrizan", "id": 7695766, "node_id": "MDQ6VXNlcjc2OTU3NjY=", "avatar_url": "https://avatars.githubusercontent.com/u/7695766?v=4", "gravatar_id": "", "url": "https://api.github.com/users/vkrizan", "html_url": "https://github.com/vkrizan", "followers_url": "https://api.github.com/users/vkrizan/followers", "following_url": "https://api.github.com/users/vkrizan/following{/other_user}", "gists_url": "https://api.github.com/users/vkrizan/gists{/gist_id}", "starred_url": "https://api.github.com/users/vkrizan/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/vkrizan/subscriptions", "organizations_url": "https://api.github.com/users/vkrizan/orgs", "repos_url": "https://api.github.com/users/vkrizan/repos", "events_url": "https://api.github.com/users/vkrizan/events{/privacy}", "received_events_url": "https://api.github.com/users/vkrizan/received_events", "type": "User", "site_admin": false }
[]
closed
false
null
[]
null
[ "CI is green: https://github.com/coleifer/peewee/actions/runs/1847421994\r\n\r\nHowever by reordering the tests I was able to reproduce a similar traceback. Let me put together a fix. Thanks for the report.", "Uploaded a new release, 3.14.10, which contains the fix. Thanks again.", "Thank you as well.\r\nI'm gonna package the new version..." ]
"2022-03-07T17:04:43"
"2022-03-08T09:31:43"
"2022-03-07T17:18:59"
NONE
null
TestFKMigrationRegression test_fk_migration is failing during build in Fedora 37. https://koji.fedoraproject.org/koji/taskinfo?taskID=83790023 ``` ====================================================================== ERROR: test_fk_migration (tests.regressions.TestFKMigrationRegression) ---------------------------------------------------------------------- Traceback (most recent call last): File "/builddir/build/BUILD/peewee-3.14.9/peewee.py", line 3160, in execute_sql cursor.execute(sql, params or ()) sqlite3.OperationalError: error in view notes_public: no such table: main.note During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/builddir/build/BUILD/peewee-3.14.9/tests/regressions.py", line 1364, in test_fk_migration migrate(migrator.drop_column( File "/builddir/build/BUILD/peewee-3.14.9/playhouse/migrate.py", line 886, in migrate operation.run() File "/builddir/build/BUILD/peewee-3.14.9/playhouse/migrate.py", line 164, in run self._handle_result(method(*self.args, **kwargs)) File "/builddir/build/BUILD/peewee-3.14.9/playhouse/migrate.py", line 155, in _handle_result result.run() File "/builddir/build/BUILD/peewee-3.14.9/playhouse/migrate.py", line 164, in run self._handle_result(method(*self.args, **kwargs)) File "/builddir/build/BUILD/peewee-3.14.9/playhouse/migrate.py", line 158, in _handle_result self._handle_result(item) File "/builddir/build/BUILD/peewee-3.14.9/playhouse/migrate.py", line 155, in _handle_result result.run() File "/builddir/build/BUILD/peewee-3.14.9/playhouse/migrate.py", line 164, in run self._handle_result(method(*self.args, **kwargs)) File "/builddir/build/BUILD/peewee-3.14.9/playhouse/migrate.py", line 153, in _handle_result self.execute(result) File "/builddir/build/BUILD/peewee-3.14.9/playhouse/migrate.py", line 149, in execute self.migrator.database.execute(node) File "/builddir/build/BUILD/peewee-3.14.9/peewee.py", line 3173, in execute return self.execute_sql(sql, params, commit=commit) File "/builddir/build/BUILD/peewee-3.14.9/peewee.py", line 3157, in execute_sql with __exception_wrapper__: File "/builddir/build/BUILD/peewee-3.14.9/peewee.py", line 2933, in __exit__ reraise(new_type, new_type(exc_value, *exc_args), traceback) File "/builddir/build/BUILD/peewee-3.14.9/peewee.py", line 191, in reraise raise value.with_traceback(tb) File "/builddir/build/BUILD/peewee-3.14.9/peewee.py", line 3160, in execute_sql cursor.execute(sql, params or ()) peewee.OperationalError: error in view notes_public: no such table: main.note ====================================================================== Unable to import sqlite C extension tests, skipping. Unable to import mysql-connector, skipping mysql_ext tests. Postgresql test database "peewee_test" not found, skipping the postgres_ext tests. Unable to import SQLCipher extension tests, skipping. Unable to import sqlite extension tests, skipping. ERROR: test_get_views (tests.db_tests.TestIntrospection) ---------------------------------------------------------------------- Traceback (most recent call last): File "/builddir/build/BUILD/peewee-3.14.9/peewee.py", line 3160, in execute_sql cursor.execute(sql, params or ()) sqlite3.OperationalError: table notes_public already exists During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/builddir/build/BUILD/peewee-3.14.9/tests/base.py", line 260, in inner method(self) File "/builddir/build/BUILD/peewee-3.14.9/tests/db_tests.py", line 604, in test_get_views assertViews([ File "/builddir/build/BUILD/peewee-3.14.9/tests/db_tests.py", line 580, in assertViews self.database.execute_sql('CREATE VIEW notes_public AS ' File "/builddir/build/BUILD/peewee-3.14.9/peewee.py", line 3157, in execute_sql with __exception_wrapper__: File "/builddir/build/BUILD/peewee-3.14.9/peewee.py", line 2933, in __exit__ reraise(new_type, new_type(exc_value, *exc_args), traceback) File "/builddir/build/BUILD/peewee-3.14.9/peewee.py", line 191, in reraise raise value.with_traceback(tb) File "/builddir/build/BUILD/peewee-3.14.9/peewee.py", line 3160, in execute_sql cursor.execute(sql, params or ()) peewee.OperationalError: table notes_public already exists ---------------------------------------------------------------------- Ran 923 tests in 6.697s FAILED (errors=2, skipped=96) ``` ([full build.log](https://github.com/coleifer/peewee/files/8199480/build.log)) Could it be racing? Env: ``` python3 x86_64 3.10.2-3.fc36 sqlcipher x86_64 4.4.3-4.fc36 sqlite x86_64 3.36.0-5.fc36 ``` Thank you.
{ "url": "https://api.github.com/repos/coleifer/peewee/issues/2549/reactions", "total_count": 0, "+1": 0, "-1": 0, "laugh": 0, "hooray": 0, "confused": 0, "heart": 0, "rocket": 0, "eyes": 0 }
https://api.github.com/repos/coleifer/peewee/issues/2549/timeline
null
completed
null
null
https://api.github.com/repos/coleifer/peewee/issues/2548
https://api.github.com/repos/coleifer/peewee
https://api.github.com/repos/coleifer/peewee/issues/2548/labels{/name}
https://api.github.com/repos/coleifer/peewee/issues/2548/comments
https://api.github.com/repos/coleifer/peewee/issues/2548/events
https://github.com/coleifer/peewee/issues/2548
1,161,324,311
I_kwDOAA7yGM5FOGcX
2,548
issue inserting list of dicts as JSON binary into model
{ "login": "bgriffen", "id": 2667869, "node_id": "MDQ6VXNlcjI2Njc4Njk=", "avatar_url": "https://avatars.githubusercontent.com/u/2667869?v=4", "gravatar_id": "", "url": "https://api.github.com/users/bgriffen", "html_url": "https://github.com/bgriffen", "followers_url": "https://api.github.com/users/bgriffen/followers", "following_url": "https://api.github.com/users/bgriffen/following{/other_user}", "gists_url": "https://api.github.com/users/bgriffen/gists{/gist_id}", "starred_url": "https://api.github.com/users/bgriffen/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/bgriffen/subscriptions", "organizations_url": "https://api.github.com/users/bgriffen/orgs", "repos_url": "https://api.github.com/users/bgriffen/repos", "events_url": "https://api.github.com/users/bgriffen/events{/privacy}", "received_events_url": "https://api.github.com/users/bgriffen/received_events", "type": "User", "site_admin": false }
[]
closed
false
null
[]
null
[ "I'm not sure, this is working for me:\r\n\r\n```python\r\nfrom peewee import *\r\nfrom playhouse.postgres_ext import *\r\n\r\ndb = PostgresqlExtDatabase('peewee_test')\r\n\r\nclass Reg(Model):\r\n key = CharField()\r\n value = BinaryJSONField()\r\n class Meta:\r\n database = db\r\n\r\ndb.drop_tables([Reg])\r\ndb.create_tables([Reg])\r\n\r\ndata = [{'k1': 'v1', 'k2': 'v2'}]\r\nReg.get_or_create(key='k1', value=data)\r\n\r\ndb.drop_tables([Reg])\r\n```", "I just tried your simple list but all my other code the same and it inserted, but my list from my example doesn't when I replaced it. Is it something about those numeric values (e.g. precision?)\r\n\r\n**Update** - ok it works with one element, but not all three :'(. A multi-element list should be fine isn't it? \r\n\r\ne.g. `data = [{'x': 123, 'y': 123},{'x': 123, 'y': 123},{'x': 123, 'y': 123}]`\r\n\r\n**Update 2** - when I changed to just `.create(**q)` it works, `get_or_create` doesn't seem to work for my list for some strange reason.\r\n\r\nVery strange... here is the full error if it helps?\r\n\r\n```python\r\nFile text.py:173, in insert_update_ai_label(short_name, labels, model_name)\r\n 171 q = {\"gcs_name\":short_name,\"labels\":labels,\"model_id\":mout.id}\r\n 172 print(q)\r\n--> 173 qout,_ = bm.TblLabelByAI.get_or_create(**q)\r\n 174 return ql,q\r\n\r\nFile ~/miniforge3/lib/python3.8/site-packages/peewee.py:6538, in Model.get_or_create(cls, **kwargs)\r\n 6535 query = query.where(getattr(cls, field) == value)\r\n 6537 try:\r\n-> 6538 return query.get(), False\r\n 6539 except cls.DoesNotExist:\r\n 6540 try:\r\n\r\nFile ~/miniforge3/lib/python3.8/site-packages/peewee.py:6953, in BaseModelSelect.get(self, database)\r\n 6951 clone._cursor_wrapper = None\r\n 6952 try:\r\n-> 6953 return clone.execute(database)[0]\r\n 6954 except IndexError:\r\n 6955 sql, params = clone.sql()\r\n\r\nFile ~/miniforge3/lib/python3.8/site-packages/peewee.py:1911, in database_required.<locals>.inner(self, database, *args, **kwargs)\r\n 1908 if not database:\r\n 1909 raise InterfaceError('Query must be bound to a database in order '\r\n 1910 'to call \"%s\".' % method.__name__)\r\n-> 1911 return method(self, database, *args, **kwargs)\r\n\r\nFile ~/miniforge3/lib/python3.8/site-packages/peewee.py:1982, in BaseQuery.execute(self, database)\r\n 1980 @database_required\r\n 1981 def execute(self, database):\r\n-> 1982 return self._execute(database)\r\n\r\nFile ~/miniforge3/lib/python3.8/site-packages/peewee.py:2155, in SelectBase._execute(self, database)\r\n 2153 def _execute(self, database):\r\n 2154 if self._cursor_wrapper is None:\r\n-> 2155 cursor = database.execute(self)\r\n 2156 self._cursor_wrapper = self._get_cursor_wrapper(cursor)\r\n 2157 return self._cursor_wrapper\r\n\r\nFile ~/miniforge3/lib/python3.8/site-packages/playhouse/postgres_ext.py:494, in PostgresqlExtDatabase.execute(self, query, commit, named_cursor, array_size, **context_options)\r\n 492 if named_cursor:\r\n 493 commit = __named_cursor__\r\n--> 494 cursor = self.execute_sql(sql, params, commit=commit)\r\n 495 if named_cursor:\r\n 496 cursor = FetchManyCursor(cursor, array_size)\r\n\r\nFile ~/miniforge3/lib/python3.8/site-packages/peewee.py:3167, in Database.execute_sql(self, sql, params, commit)\r\n 3165 else:\r\n 3166 if commit and not self.in_transaction():\r\n-> 3167 self.commit()\r\n 3168 return cursor\r\n\r\nFile ~/miniforge3/lib/python3.8/site-packages/peewee.py:2933, in ExceptionWrapper.__exit__(self, exc_type, exc_value, traceback)\r\n 2931 new_type = self.exceptions[exc_type.__name__]\r\n 2932 exc_args = exc_value.args\r\n-> 2933 reraise(new_type, new_type(exc_value, *exc_args), traceback)\r\n\r\nFile ~/miniforge3/lib/python3.8/site-packages/peewee.py:191, in reraise(tp, value, tb)\r\n 189 def reraise(tp, value, tb=None):\r\n 190 if value.__traceback__ is not tb:\r\n--> 191 raise value.with_traceback(tb)\r\n 192 raise value\r\n\r\nFile ~/miniforge3/lib/python3.8/site-packages/peewee.py:3160, in Database.execute_sql(self, sql, params, commit)\r\n 3158 cursor = self.cursor(commit)\r\n 3159 try:\r\n-> 3160 cursor.execute(sql, params or ())\r\n 3161 except Exception:\r\n 3162 if self.autorollback and not self.in_transaction():\r\n\r\nProgrammingError: operator does not exist: jsonb = record\r\nLINE 1: ...imagename.jpg') AND (\"t1\".\"labels\" = (CAST('{...\r\n ^\r\nHINT: No operator matches the given name and argument types. You might need to add explicit type casts.\r\n```", "I think I see the issue -- Peewee treats top-level lists a little differently when used in expressions.\r\n\r\nThis workaround should work:\r\n\r\n```python\r\nfrom psycopg2.extras import Json\r\n\r\ndata = [{'x': 123, 'y': 123},{'x': 123, 'y': 123},{'x': 123, 'y': 123}]\r\ndata = Json(data)\r\n```" ]
"2022-03-07T12:00:23"
"2022-03-10T14:26:14"
"2022-03-07T14:44:55"
NONE
null
I have a simple list of dicts I want to insert into my LabelModel table in my postgres DB ```python l = [{'label': 'A', 'x': 132.56338500976562, 'y': 333.7539367675781, 'width': 183.78598022460938, 'height': 404.6580505371094, 'score': 0.9848693609237671}, {'label': 'B', 'x': 179.97842407226562, 'y': 367.101318359375, 'width': 127.43386840820312, 'height': 59.047882080078125, 'score': 0.965998113155365}, {'label': 'C', 'x': 431.1368408203125, 'y': 365.9712219238281, 'width': 127.59616088867188, 'height': 60.77362060546875, 'score': 0.9622131586074829}] ``` ```python from playhouse.postgres_ext import BinaryJSONField class TblLabelByAI(BaseModel): name = pw.TextField() labels = BinaryJSONField() modified_at = pw.DateField(default=datetime.datetime.utcnow) ``` ```python q = {"imagename":"testname","labels":l} TblLabelByAI.get_or_create(**q) ``` Is there any reason I get the following: ```bash ProgrammingError: operator does not exist: jsonb = record LINE 1: ...imagename.jpg') AND ("t1"."labels" = (CAST('{... ^ HINT: No operator matches the given name and argument types. You might need to add explicit type casts. ``` Peewee: 3.14.9 Python 3.8 @coleifer - amazing work btw
{ "url": "https://api.github.com/repos/coleifer/peewee/issues/2548/reactions", "total_count": 0, "+1": 0, "-1": 0, "laugh": 0, "hooray": 0, "confused": 0, "heart": 0, "rocket": 0, "eyes": 0 }
https://api.github.com/repos/coleifer/peewee/issues/2548/timeline
null
completed
null
null
https://api.github.com/repos/coleifer/peewee/issues/2547
https://api.github.com/repos/coleifer/peewee
https://api.github.com/repos/coleifer/peewee/issues/2547/labels{/name}
https://api.github.com/repos/coleifer/peewee/issues/2547/comments
https://api.github.com/repos/coleifer/peewee/issues/2547/events
https://github.com/coleifer/peewee/issues/2547
1,161,205,220
I_kwDOAA7yGM5FNpXk
2,547
Buggy SQL syntax is produced when trying to JOIN two fields from same model
{ "login": "lapinvert", "id": 3294841, "node_id": "MDQ6VXNlcjMyOTQ4NDE=", "avatar_url": "https://avatars.githubusercontent.com/u/3294841?v=4", "gravatar_id": "", "url": "https://api.github.com/users/lapinvert", "html_url": "https://github.com/lapinvert", "followers_url": "https://api.github.com/users/lapinvert/followers", "following_url": "https://api.github.com/users/lapinvert/following{/other_user}", "gists_url": "https://api.github.com/users/lapinvert/gists{/gist_id}", "starred_url": "https://api.github.com/users/lapinvert/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/lapinvert/subscriptions", "organizations_url": "https://api.github.com/users/lapinvert/orgs", "repos_url": "https://api.github.com/users/lapinvert/repos", "events_url": "https://api.github.com/users/lapinvert/events{/privacy}", "received_events_url": "https://api.github.com/users/lapinvert/received_events", "type": "User", "site_admin": false }
[]
closed
false
null
[]
null
[ "You're almost there. Just join on the aliases themselves as opposed to .join(Parent...\r\n\r\n```\r\nDad = Adult.alias()\r\nMom = Adult.alias()\r\nquery = (\r\n Children.select(Children, Dad, Mom)\r\n .join(Dad, on=(Children.dad == Dad.id))\r\n .switch(Children)\r\n .join(Mom, on=(Children.mom == Mom.id))\r\n)\r\n```" ]
"2022-03-07T10:25:17"
"2022-03-07T14:41:25"
"2022-03-07T14:41:24"
NONE
null
``` Adult(Model): name = CharField() Children(Model): name = CharField() dad = ForeignKeyField(Adult, backref='children_as_dad') mom = ForeignKeyField(Adult, backref='children_as_mom') Dad = Adult.alias() Mom = Adult.alias() query = ( Children.select(Children, Dad, Mom) .join(Adult, on=(Children.dad == Dad.id)) .switch(Children) .join(Adult, on=(Children.mom == Mom.id)) ) print(query) ``` I want to select all children along with their two parents in a single query, but the output query is really weird: ``` ('SELECT "t1"."id", "t1"."dad_id", "t1"."mom_id", "t2"."id", "t2"."name", "t3"."id", "t3"."name", FROM "children" AS "t1" INNER JOIN "adult" AS "t4" ON ("t1"."dad_id" = "t2"."id") INNER JOIN "adult" AS "t4" ON ("t1"."mom_id" = "t3"."id") ``` executing it results in Exception, because of those `t4`s which should be `t2` and `t3` respectively. I am using peewee `3.14.9` and sqlite. Is that a bug, or what am I doing wrong?
{ "url": "https://api.github.com/repos/coleifer/peewee/issues/2547/reactions", "total_count": 0, "+1": 0, "-1": 0, "laugh": 0, "hooray": 0, "confused": 0, "heart": 0, "rocket": 0, "eyes": 0 }
https://api.github.com/repos/coleifer/peewee/issues/2547/timeline
null
completed
null
null
https://api.github.com/repos/coleifer/peewee/issues/2546
https://api.github.com/repos/coleifer/peewee
https://api.github.com/repos/coleifer/peewee/issues/2546/labels{/name}
https://api.github.com/repos/coleifer/peewee/issues/2546/comments
https://api.github.com/repos/coleifer/peewee/issues/2546/events
https://github.com/coleifer/peewee/issues/2546
1,160,998,758
I_kwDOAA7yGM5FM29m
2,546
Alias should have a public `name` property
{ "login": "mkmoisen", "id": 2534631, "node_id": "MDQ6VXNlcjI1MzQ2MzE=", "avatar_url": "https://avatars.githubusercontent.com/u/2534631?v=4", "gravatar_id": "", "url": "https://api.github.com/users/mkmoisen", "html_url": "https://github.com/mkmoisen", "followers_url": "https://api.github.com/users/mkmoisen/followers", "following_url": "https://api.github.com/users/mkmoisen/following{/other_user}", "gists_url": "https://api.github.com/users/mkmoisen/gists{/gist_id}", "starred_url": "https://api.github.com/users/mkmoisen/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/mkmoisen/subscriptions", "organizations_url": "https://api.github.com/users/mkmoisen/orgs", "repos_url": "https://api.github.com/users/mkmoisen/repos", "events_url": "https://api.github.com/users/mkmoisen/events{/privacy}", "received_events_url": "https://api.github.com/users/mkmoisen/received_events", "type": "User", "site_admin": false }
[]
closed
false
null
[]
null
[ "Added `name` property.", "Hi @coleifer , thanks for adding these.\r\n\r\nI'm writing a library that depends on peewee.\r\n\r\nDo you think it would be sensible to simply require the new 3.14.10 version of peewee, and use the new `Alias.name`, `ModelSelect.selected_columns`, `ModelSelect.left_outer_join`, etc. directly? \r\n\r\nMy only concern is if a user wants to use an older version of peewee and will not want to use my framework. I'm not sure if this is a valid concern today with the popularity of virtual environments. \r\n\r\nIf it is a valid concern, is there anything wrong with my library simply monkey patching these attributes onto peewee?", "I don't attempt to collect any stats on what versions people are running or downloading, so it's hard to say. I don't make any attempt to support people on 2.x, but as far as whether people use the latest and upgrade frequently, I couldn't say. I think monkeypatching is probably just fine if you insist on using the new apis." ]
"2022-03-07T07:17:16"
"2022-03-07T18:39:37"
"2022-03-07T14:40:17"
NONE
null
I believe that the only way to check the name of an `Alias` object is to access the private `._alias` attribute. May we please add a public accessor to this? I think it should be `name`, just like the `Field` API. This is what I have to do now, which is a bit inconvenient: ``` columns = [ Tweet.id, Tweet.content, User.username.alias('who') ] # ... for column in columns: if isinstance(column, Field): print(column.name) elif isinstance(column, Alias): print(column._alias) ``` --- It would be better if Alias had a `name`: ``` for column in columns: print(column.name) ``` Thank you
{ "url": "https://api.github.com/repos/coleifer/peewee/issues/2546/reactions", "total_count": 0, "+1": 0, "-1": 0, "laugh": 0, "hooray": 0, "confused": 0, "heart": 0, "rocket": 0, "eyes": 0 }
https://api.github.com/repos/coleifer/peewee/issues/2546/timeline
null
completed
null
null
https://api.github.com/repos/coleifer/peewee/issues/2545
https://api.github.com/repos/coleifer/peewee
https://api.github.com/repos/coleifer/peewee/issues/2545/labels{/name}
https://api.github.com/repos/coleifer/peewee/issues/2545/comments
https://api.github.com/repos/coleifer/peewee/issues/2545/events
https://github.com/coleifer/peewee/issues/2545
1,160,992,650
I_kwDOAA7yGM5FM1eK
2,545
ModelSelect public method to return list of columns in the SELECT
{ "login": "mkmoisen", "id": 2534631, "node_id": "MDQ6VXNlcjI1MzQ2MzE=", "avatar_url": "https://avatars.githubusercontent.com/u/2534631?v=4", "gravatar_id": "", "url": "https://api.github.com/users/mkmoisen", "html_url": "https://github.com/mkmoisen", "followers_url": "https://api.github.com/users/mkmoisen/followers", "following_url": "https://api.github.com/users/mkmoisen/following{/other_user}", "gists_url": "https://api.github.com/users/mkmoisen/gists{/gist_id}", "starred_url": "https://api.github.com/users/mkmoisen/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/mkmoisen/subscriptions", "organizations_url": "https://api.github.com/users/mkmoisen/orgs", "repos_url": "https://api.github.com/users/mkmoisen/repos", "events_url": "https://api.github.com/users/mkmoisen/events{/privacy}", "received_events_url": "https://api.github.com/users/mkmoisen/received_events", "type": "User", "site_admin": false }
[]
closed
false
null
[]
null
[ "Added `selected_columns` as a property." ]
"2022-03-07T07:10:11"
"2022-03-07T14:38:53"
"2022-03-07T14:38:42"
NONE
null
Unless I am mistaken, there is no public way to get the list of columns in the select. The only way I see is to call the private `._returning` attribute. Can we please add public access for this? SQLAlchemy has `selected_columns` in 1.3/1.4. In previous versions you could use the `.c` which returned a list of selected columns. ``` query = Tweet.select( Tweet.id, Tweet.content, User.username ).join(User) selected_columns = query._returning print(selected_columns) ```
{ "url": "https://api.github.com/repos/coleifer/peewee/issues/2545/reactions", "total_count": 0, "+1": 0, "-1": 0, "laugh": 0, "hooray": 0, "confused": 0, "heart": 0, "rocket": 0, "eyes": 0 }
https://api.github.com/repos/coleifer/peewee/issues/2545/timeline
null
completed
null
null
https://api.github.com/repos/coleifer/peewee/issues/2544
https://api.github.com/repos/coleifer/peewee
https://api.github.com/repos/coleifer/peewee/issues/2544/labels{/name}
https://api.github.com/repos/coleifer/peewee/issues/2544/comments
https://api.github.com/repos/coleifer/peewee/issues/2544/events
https://github.com/coleifer/peewee/issues/2544
1,160,753,236
I_kwDOAA7yGM5FL7BU
2,544
Peewee Is there any performance benefit to using the Query Builder over the ORM's dict/nametuple functions?
{ "login": "mkmoisen", "id": 2534631, "node_id": "MDQ6VXNlcjI1MzQ2MzE=", "avatar_url": "https://avatars.githubusercontent.com/u/2534631?v=4", "gravatar_id": "", "url": "https://api.github.com/users/mkmoisen", "html_url": "https://github.com/mkmoisen", "followers_url": "https://api.github.com/users/mkmoisen/followers", "following_url": "https://api.github.com/users/mkmoisen/following{/other_user}", "gists_url": "https://api.github.com/users/mkmoisen/gists{/gist_id}", "starred_url": "https://api.github.com/users/mkmoisen/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/mkmoisen/subscriptions", "organizations_url": "https://api.github.com/users/mkmoisen/orgs", "repos_url": "https://api.github.com/users/mkmoisen/repos", "events_url": "https://api.github.com/users/mkmoisen/events{/privacy}", "received_events_url": "https://api.github.com/users/mkmoisen/received_events", "type": "User", "site_admin": false }
[]
closed
false
null
[]
null
[ "You'll have to profile it yourself, as it probably depends quite a bit on what types of queries you are executing. If you are really concerned about performance, using your database's python driver directly is going to be the fastest, of course. But you're using Python, so it's probably a somewhat mis-placed effort, to try to micro-optimize at this layer." ]
"2022-03-06T23:52:08"
"2022-03-07T14:19:41"
"2022-03-07T14:19:41"
NONE
null
I know that when the ORM returns python model objects, there is some overhead that we can eliminate by calling `.dicts()` or `.namedtuples`(). Is there any performance benefit to using the [query builder API](https://docs.peewee-orm.com/en/latest/peewee/query_builder.html) to return dicts/namedtuples, in comparison to returning dicts/namedtuples from the ORM API? (I was going to ask this on stackoverflow but figured performance questions like this were not appropriate there). Thank you.
{ "url": "https://api.github.com/repos/coleifer/peewee/issues/2544/reactions", "total_count": 0, "+1": 0, "-1": 0, "laugh": 0, "hooray": 0, "confused": 0, "heart": 0, "rocket": 0, "eyes": 0 }
https://api.github.com/repos/coleifer/peewee/issues/2544/timeline
null
completed
null
null
https://api.github.com/repos/coleifer/peewee/issues/2543
https://api.github.com/repos/coleifer/peewee
https://api.github.com/repos/coleifer/peewee/issues/2543/labels{/name}
https://api.github.com/repos/coleifer/peewee/issues/2543/comments
https://api.github.com/repos/coleifer/peewee/issues/2543/events
https://github.com/coleifer/peewee/issues/2543
1,160,677,687
I_kwDOAA7yGM5FLok3
2,543
Add SELECT columns to a preexisting query/ModelSelect
{ "login": "mkmoisen", "id": 2534631, "node_id": "MDQ6VXNlcjI1MzQ2MzE=", "avatar_url": "https://avatars.githubusercontent.com/u/2534631?v=4", "gravatar_id": "", "url": "https://api.github.com/users/mkmoisen", "html_url": "https://github.com/mkmoisen", "followers_url": "https://api.github.com/users/mkmoisen/followers", "following_url": "https://api.github.com/users/mkmoisen/following{/other_user}", "gists_url": "https://api.github.com/users/mkmoisen/gists{/gist_id}", "starred_url": "https://api.github.com/users/mkmoisen/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/mkmoisen/subscriptions", "organizations_url": "https://api.github.com/users/mkmoisen/orgs", "repos_url": "https://api.github.com/users/mkmoisen/repos", "events_url": "https://api.github.com/users/mkmoisen/events{/privacy}", "received_events_url": "https://api.github.com/users/mkmoisen/received_events", "type": "User", "site_admin": false }
[]
closed
false
null
[]
null
[ "Looking through the source code, I see I can do this work around by accessing a private attribute:\r\n\r\n```\r\nquery = Tweet.select(Tweet.id)\r\nquery._returning.append(Tweet.content)\r\n```\r\n\r\nBut I would rather not rely on the private attribute. ", "Nevermind, I found it:\r\n\r\n```\r\nquery = Tweet.select(Tweet.id)\r\nquery = query.select_extend(Tweet.content)\r\n```" ]
"2022-03-06T18:09:36"
"2022-03-06T18:24:47"
"2022-03-06T18:24:47"
NONE
null
If I already have a preexisting Peewee query (ModelSelect), is it possible to add a column to the SELECT statement of the query? E.g: ``` query = Tweet.select(Tweet.id) # query.add_select_column(Tweet.content) # how to do this ? ``` I think it might be useful to have the `select` function of the ModelSelect return a query with a modified SELECT statement; the same thing that `where` and `join` do. Today, the `select` function returns a new query from the base model, so it is not too useful: ``` >>> query = Tweet.select(Tweet.id) >>> print(query.select(Tweet.contents).sql()) ('SELECT "t1"."contents" FROM "tweet" AS "t1"', []) ```
{ "url": "https://api.github.com/repos/coleifer/peewee/issues/2543/reactions", "total_count": 0, "+1": 0, "-1": 0, "laugh": 0, "hooray": 0, "confused": 0, "heart": 0, "rocket": 0, "eyes": 0 }
https://api.github.com/repos/coleifer/peewee/issues/2543/timeline
null
completed
null
null
https://api.github.com/repos/coleifer/peewee/issues/2542
https://api.github.com/repos/coleifer/peewee
https://api.github.com/repos/coleifer/peewee/issues/2542/labels{/name}
https://api.github.com/repos/coleifer/peewee/issues/2542/comments
https://api.github.com/repos/coleifer/peewee/issues/2542/events
https://github.com/coleifer/peewee/issues/2542
1,159,193,750
I_kwDOAA7yGM5FF-SW
2,542
filter IN is not working
{ "login": "tjengbudi", "id": 3039807, "node_id": "MDQ6VXNlcjMwMzk4MDc=", "avatar_url": "https://avatars.githubusercontent.com/u/3039807?v=4", "gravatar_id": "", "url": "https://api.github.com/users/tjengbudi", "html_url": "https://github.com/tjengbudi", "followers_url": "https://api.github.com/users/tjengbudi/followers", "following_url": "https://api.github.com/users/tjengbudi/following{/other_user}", "gists_url": "https://api.github.com/users/tjengbudi/gists{/gist_id}", "starred_url": "https://api.github.com/users/tjengbudi/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/tjengbudi/subscriptions", "organizations_url": "https://api.github.com/users/tjengbudi/orgs", "repos_url": "https://api.github.com/users/tjengbudi/repos", "events_url": "https://api.github.com/users/tjengbudi/events{/privacy}", "received_events_url": "https://api.github.com/users/tjengbudi/received_events", "type": "User", "site_admin": false }
[]
closed
false
null
[]
null
[ "You also contacted me via my personal site. Then opened an issue on GH. Please in the future use stackoverflow for basic questions like this.\r\n\r\nWorks fine, by the way:\r\n\r\n```python\r\nfrom peewee import *\r\n\r\ndb = SqliteDatabase(':memory:')\r\n\r\nclass Reg(Model):\r\n key = TextField()\r\n class Meta:\r\n database = db\r\n\r\ndb.create_tables([Reg])\r\n\r\nfor i in range(10):\r\n Reg.create(key='k%s' % i)\r\n\r\n\r\nquery = Reg.select().where(Reg.key.in_(['k1', 'k3', 'k5']))\r\nfor row in query:\r\n print(row.key)\r\n```\r\n\r\nOutput:\r\n\r\n```\r\nk1\r\nk3\r\nk5\r\n```" ]
"2022-03-04T03:11:47"
"2022-03-04T13:24:45"
"2022-03-04T13:24:45"
NONE
null
hello, i try to use filter IN in peewee. but the generated code is not right for example i want to select * from item where itemid in (abc, def) but the peewee is create without "()" so the peewee will create select * from item where itemid in abd, def it will raised the error in mysql. could you help me about this?
{ "url": "https://api.github.com/repos/coleifer/peewee/issues/2542/reactions", "total_count": 0, "+1": 0, "-1": 0, "laugh": 0, "hooray": 0, "confused": 0, "heart": 0, "rocket": 0, "eyes": 0 }
https://api.github.com/repos/coleifer/peewee/issues/2542/timeline
null
completed
null
null
https://api.github.com/repos/coleifer/peewee/issues/2541
https://api.github.com/repos/coleifer/peewee
https://api.github.com/repos/coleifer/peewee/issues/2541/labels{/name}
https://api.github.com/repos/coleifer/peewee/issues/2541/comments
https://api.github.com/repos/coleifer/peewee/issues/2541/events
https://github.com/coleifer/peewee/issues/2541
1,158,194,020
I_kwDOAA7yGM5FCKNk
2,541
query error
{ "login": "wbzdssm", "id": 31335322, "node_id": "MDQ6VXNlcjMxMzM1MzIy", "avatar_url": "https://avatars.githubusercontent.com/u/31335322?v=4", "gravatar_id": "", "url": "https://api.github.com/users/wbzdssm", "html_url": "https://github.com/wbzdssm", "followers_url": "https://api.github.com/users/wbzdssm/followers", "following_url": "https://api.github.com/users/wbzdssm/following{/other_user}", "gists_url": "https://api.github.com/users/wbzdssm/gists{/gist_id}", "starred_url": "https://api.github.com/users/wbzdssm/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/wbzdssm/subscriptions", "organizations_url": "https://api.github.com/users/wbzdssm/orgs", "repos_url": "https://api.github.com/users/wbzdssm/repos", "events_url": "https://api.github.com/users/wbzdssm/events{/privacy}", "received_events_url": "https://api.github.com/users/wbzdssm/received_events", "type": "User", "site_admin": false }
[]
closed
false
null
[]
null
[]
"2022-03-03T09:50:45"
"2022-03-03T13:42:58"
"2022-03-03T13:42:58"
NONE
null
I think I found a bug, when some fields do not exist in the model, I use the .select query to return None, but when I use scaler(as_tuple=Ture), it returns a row of correct data, I don't know if this is in line with expected; My table is not created with model, there is no table created with model, and the query is not returning any errors
{ "url": "https://api.github.com/repos/coleifer/peewee/issues/2541/reactions", "total_count": 0, "+1": 0, "-1": 0, "laugh": 0, "hooray": 0, "confused": 0, "heart": 0, "rocket": 0, "eyes": 0 }
https://api.github.com/repos/coleifer/peewee/issues/2541/timeline
null
completed
null
null
https://api.github.com/repos/coleifer/peewee/issues/2540
https://api.github.com/repos/coleifer/peewee
https://api.github.com/repos/coleifer/peewee/issues/2540/labels{/name}
https://api.github.com/repos/coleifer/peewee/issues/2540/comments
https://api.github.com/repos/coleifer/peewee/issues/2540/events
https://github.com/coleifer/peewee/issues/2540
1,157,572,991
I_kwDOAA7yGM5E_yl_
2,540
.get() Raises IndexError which Results in Noisy Stack Trace
{ "login": "mkmoisen", "id": 2534631, "node_id": "MDQ6VXNlcjI1MzQ2MzE=", "avatar_url": "https://avatars.githubusercontent.com/u/2534631?v=4", "gravatar_id": "", "url": "https://api.github.com/users/mkmoisen", "html_url": "https://github.com/mkmoisen", "followers_url": "https://api.github.com/users/mkmoisen/followers", "following_url": "https://api.github.com/users/mkmoisen/following{/other_user}", "gists_url": "https://api.github.com/users/mkmoisen/gists{/gist_id}", "starred_url": "https://api.github.com/users/mkmoisen/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/mkmoisen/subscriptions", "organizations_url": "https://api.github.com/users/mkmoisen/orgs", "repos_url": "https://api.github.com/users/mkmoisen/repos", "events_url": "https://api.github.com/users/mkmoisen/events{/privacy}", "received_events_url": "https://api.github.com/users/mkmoisen/received_events", "type": "User", "site_admin": false }
[]
closed
false
null
[]
null
[ "I'm going to pass for now." ]
"2022-03-02T18:58:11"
"2022-03-02T19:13:59"
"2022-03-02T19:13:59"
NONE
null
Performing `.get()` for a row that does not exist will result in a verbose stack trace that starts with an IndexError. I think it would look a bit cleaner if the IndexError did not print in the stack trace. If you agree, I would be happy to make the PR. Let me know. ``` Tweet.get(Tweet.id==0) ``` Results in: ``` Traceback (most recent call last): File "C:\test\lib\site-packages\peewee.py", line 6933, in get return clone.execute(database)[0] File "C:\test\lib\site-packages\peewee.py", line 4306, in __getitem__ return self.row_cache[item] IndexError: list index out of range During handling of the above exception, another exception occurred: Traceback (most recent call last): File "<stdin>", line 1, in <module> File "C:\test\lib\site-packages\peewee.py", line 6485, in get return sq.get() File "C:\test\lib\site-packages\peewee.py", line 6936, in get raise self.model.DoesNotExist('%s instance matching query does ' __main__.TweetDoesNotExist: <Model: Tweet> instance matching query does not exist: SQL: SELECT "t1"."id", "t1"."content", "t1"."timestamp", "t1"."user_id" FROM "tweet" AS "t1" WHERE ("t1"."id" = ?) LIMIT ? OFFSET ? Params: [0, 1, 0] ``` ----- We could remove the IndexError from this stack trace by changing the following: ``` def get(self, database=None): clone = self.paginate(1, 1) clone._cursor_wrapper = None try: return clone.execute(database)[0] except IndexError: sql, params = clone.sql() raise self.model.DoesNotExist('%s instance matching query does ' 'not exist:\nSQL: %s\nParams: %s' % (clone.model, sql, params)) ``` to: ``` def get(self, database=None): clone = self.paginate(1, 1) clone._cursor_wrapper = None result = clone.execute(database) if not result: sql, params = clone.sql() raise self.model.DoesNotExist('%s instance matching query does ' 'not exist:\nSQL: %s\nParams: %s' % (clone.model, sql, params)) return result[0] ``` This change results in the following clean stack trace: ``` >>> Tweet.get(Tweet.id==0) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "C:\test\lib\site-packages\peewee.py", line 6485, in get return sq.get() File "C:\test\lib\site-packages\peewee.py", line 6935, in get raise self.model.DoesNotExist('%s instance matching query does ' __main__.TweetDoesNotExist: <Model: Tweet> instance matching query does not exist: SQL: SELECT "t1"."id", "t1"."content", "t1"."timestamp", "t1"."user_id" FROM "tweet" AS "t1" WHERE ("t1"."id" = ?) LIMIT ? OFFSET ? Params: [0, 1, 0] ```
{ "url": "https://api.github.com/repos/coleifer/peewee/issues/2540/reactions", "total_count": 0, "+1": 0, "-1": 0, "laugh": 0, "hooray": 0, "confused": 0, "heart": 0, "rocket": 0, "eyes": 0 }
https://api.github.com/repos/coleifer/peewee/issues/2540/timeline
null
completed
null
null
https://api.github.com/repos/coleifer/peewee/issues/2539
https://api.github.com/repos/coleifer/peewee
https://api.github.com/repos/coleifer/peewee/issues/2539/labels{/name}
https://api.github.com/repos/coleifer/peewee/issues/2539/comments
https://api.github.com/repos/coleifer/peewee/issues/2539/events
https://github.com/coleifer/peewee/issues/2539
1,157,274,927
I_kwDOAA7yGM5E-p0v
2,539
My query should return data ,but the result is sql; What should I do?
{ "login": "wbzdssm", "id": 31335322, "node_id": "MDQ6VXNlcjMxMzM1MzIy", "avatar_url": "https://avatars.githubusercontent.com/u/31335322?v=4", "gravatar_id": "", "url": "https://api.github.com/users/wbzdssm", "html_url": "https://github.com/wbzdssm", "followers_url": "https://api.github.com/users/wbzdssm/followers", "following_url": "https://api.github.com/users/wbzdssm/following{/other_user}", "gists_url": "https://api.github.com/users/wbzdssm/gists{/gist_id}", "starred_url": "https://api.github.com/users/wbzdssm/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/wbzdssm/subscriptions", "organizations_url": "https://api.github.com/users/wbzdssm/orgs", "repos_url": "https://api.github.com/users/wbzdssm/repos", "events_url": "https://api.github.com/users/wbzdssm/events{/privacy}", "received_events_url": "https://api.github.com/users/wbzdssm/received_events", "type": "User", "site_admin": false }
[]
closed
false
null
[]
null
[ "Read the documentation. Follow the quickstart. Try iterating over your `query`.\r\n\r\nPost questions on stackoverflow.", "@wbzdssm When I use `scalar` it returns data.\r\n\r\nWhat is `FunctionName`, is that a table?\r\n\r\nPlease add a reproducible example.", "> FunctionName\r\n\r\nyes , it' a table; ", "@wbzdssm Can you add a reproducible example?\r\n\r\nYou can use the sqllite's in memory for convenience.\r\n\r\n```\r\n\r\n\r\nfrom peewee import *\r\n\r\ndb = SqliteDatabase(':memory:')\r\n\r\nclass BaseModel(Model):\r\n class Meta:\r\n database = db\r\n\r\n\r\nclass FunctionName(BaseModel):\r\n name = TextField()\r\n\r\n\r\ndb.create_tables([FunctionName])\r\n\r\nfunction_name = FunctionName.create(name='foo')\r\n\r\nquery = FunctionName.select(\r\n fn.MAX(FunctionName.name)\r\n).where(\r\n FunctionName.id == function_name.id\r\n).group_by(\r\n FunctionName.id\r\n).scalar(as_tuple=True)\r\n\r\nprint(query)\r\n```\r\n\r\nThis will output `('foo',)` as expected.", "tks" ]
"2022-03-02T14:31:42"
"2022-03-22T11:22:19"
"2022-03-02T14:39:40"
NONE
null
My query should return data ,but the result is sql; What should I do? sql just like: query = FunctionName.select( *query_fileds ).where( *cond ).group_by( FunctionName.appid ).scalar(as_tuple=True)
{ "url": "https://api.github.com/repos/coleifer/peewee/issues/2539/reactions", "total_count": 0, "+1": 0, "-1": 0, "laugh": 0, "hooray": 0, "confused": 0, "heart": 0, "rocket": 0, "eyes": 0 }
https://api.github.com/repos/coleifer/peewee/issues/2539/timeline
null
completed
null
null
https://api.github.com/repos/coleifer/peewee/issues/2538
https://api.github.com/repos/coleifer/peewee
https://api.github.com/repos/coleifer/peewee/issues/2538/labels{/name}
https://api.github.com/repos/coleifer/peewee/issues/2538/comments
https://api.github.com/repos/coleifer/peewee/issues/2538/events
https://github.com/coleifer/peewee/issues/2538
1,157,155,433
I_kwDOAA7yGM5E-Mpp
2,538
How to lazily declare a database connection?
{ "login": "jorgecarleitao", "id": 2772607, "node_id": "MDQ6VXNlcjI3NzI2MDc=", "avatar_url": "https://avatars.githubusercontent.com/u/2772607?v=4", "gravatar_id": "", "url": "https://api.github.com/users/jorgecarleitao", "html_url": "https://github.com/jorgecarleitao", "followers_url": "https://api.github.com/users/jorgecarleitao/followers", "following_url": "https://api.github.com/users/jorgecarleitao/following{/other_user}", "gists_url": "https://api.github.com/users/jorgecarleitao/gists{/gist_id}", "starred_url": "https://api.github.com/users/jorgecarleitao/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/jorgecarleitao/subscriptions", "organizations_url": "https://api.github.com/users/jorgecarleitao/orgs", "repos_url": "https://api.github.com/users/jorgecarleitao/repos", "events_url": "https://api.github.com/users/jorgecarleitao/events{/privacy}", "received_events_url": "https://api.github.com/users/jorgecarleitao/received_events", "type": "User", "site_admin": false }
[]
closed
false
null
[]
null
[ "If you had read the docs you would have found:\r\n\r\n* http://docs.peewee-orm.com/en/latest/peewee/database.html#run-time-database-configuration\r\n* http://docs.peewee-orm.com/en/latest/peewee/database.html#dynamically-defining-a-database\r\n* http://docs.peewee-orm.com/en/latest/peewee/database.html#setting-the-database-at-run-time", "Sorry for the noise." ]
"2022-03-02T12:52:10"
"2022-03-02T14:33:30"
"2022-03-02T13:01:43"
NONE
null
The idiom ```python from peewee import * db = ... class BaseModel(Model): class Meta: database = db ``` found in the guide, docs, etc. suggests that we have to either write the db credentials on the source code or read the credentials from environment on the root of the module (i.e. executed when we `import` the module). However, database connections, and in particular secrets, are often only available after importing a module. Two examples: * when the secrets are stored on a secret vault and we need to query said vault to retrieve the DB user/password, which we may want to read asynchronously, or every X days if the secret rotates. * in CLI applications, where the secret may be inputted by the user as a CLI parameter or terminal input Is there a "standard" or recommended idiom for these use cases? Ideally a way whereby we do not have to write something like ```python def get_models(username, password): db = ... username, password class BaseModel(Model): class Meta: database = db ``` and then import each of the models into the module (or something). More generally, is there a way to decouple database-specific properties from the creation of the ORM models?
{ "url": "https://api.github.com/repos/coleifer/peewee/issues/2538/reactions", "total_count": 1, "+1": 1, "-1": 0, "laugh": 0, "hooray": 0, "confused": 0, "heart": 0, "rocket": 0, "eyes": 0 }
https://api.github.com/repos/coleifer/peewee/issues/2538/timeline
null
completed
null
null
https://api.github.com/repos/coleifer/peewee/issues/2537
https://api.github.com/repos/coleifer/peewee
https://api.github.com/repos/coleifer/peewee/issues/2537/labels{/name}
https://api.github.com/repos/coleifer/peewee/issues/2537/comments
https://api.github.com/repos/coleifer/peewee/issues/2537/events
https://github.com/coleifer/peewee/pull/2537
1,155,725,918
PR_kwDOAA7yGM4zv6-R
2,537
add GitHub URL for PyPi
{ "login": "andriyor", "id": 11459840, "node_id": "MDQ6VXNlcjExNDU5ODQw", "avatar_url": "https://avatars.githubusercontent.com/u/11459840?v=4", "gravatar_id": "", "url": "https://api.github.com/users/andriyor", "html_url": "https://github.com/andriyor", "followers_url": "https://api.github.com/users/andriyor/followers", "following_url": "https://api.github.com/users/andriyor/following{/other_user}", "gists_url": "https://api.github.com/users/andriyor/gists{/gist_id}", "starred_url": "https://api.github.com/users/andriyor/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/andriyor/subscriptions", "organizations_url": "https://api.github.com/users/andriyor/orgs", "repos_url": "https://api.github.com/users/andriyor/repos", "events_url": "https://api.github.com/users/andriyor/events{/privacy}", "received_events_url": "https://api.github.com/users/andriyor/received_events", "type": "User", "site_admin": false }
[]
closed
false
null
[]
null
[]
"2022-03-01T19:28:34"
"2022-03-01T20:10:48"
"2022-03-01T20:10:48"
NONE
null
Warehouse now uses the project_urls provided to display links in the sidebar on [this screen](https://pypi.org/project/requests/), as well as including them in API responses to help the automation tool find the source code for Requests. Docs: [packaging.python.org/en/latest/guides/distributing-packages-using-setuptools/#project-urls](https://packaging.python.org/en/latest/guides/distributing-packages-using-setuptools/#project-urls)
{ "url": "https://api.github.com/repos/coleifer/peewee/issues/2537/reactions", "total_count": 0, "+1": 0, "-1": 0, "laugh": 0, "hooray": 0, "confused": 0, "heart": 0, "rocket": 0, "eyes": 0 }
https://api.github.com/repos/coleifer/peewee/issues/2537/timeline
null
null
false
{ "url": "https://api.github.com/repos/coleifer/peewee/pulls/2537", "html_url": "https://github.com/coleifer/peewee/pull/2537", "diff_url": "https://github.com/coleifer/peewee/pull/2537.diff", "patch_url": "https://github.com/coleifer/peewee/pull/2537.patch", "merged_at": null }
https://api.github.com/repos/coleifer/peewee/issues/2536
https://api.github.com/repos/coleifer/peewee
https://api.github.com/repos/coleifer/peewee/issues/2536/labels{/name}
https://api.github.com/repos/coleifer/peewee/issues/2536/comments
https://api.github.com/repos/coleifer/peewee/issues/2536/events
https://github.com/coleifer/peewee/issues/2536
1,153,904,574
I_kwDOAA7yGM5Exy--
2,536
bulk_update for datetime fail
{ "login": "LLjiahai", "id": 30220658, "node_id": "MDQ6VXNlcjMwMjIwNjU4", "avatar_url": "https://avatars.githubusercontent.com/u/30220658?v=4", "gravatar_id": "", "url": "https://api.github.com/users/LLjiahai", "html_url": "https://github.com/LLjiahai", "followers_url": "https://api.github.com/users/LLjiahai/followers", "following_url": "https://api.github.com/users/LLjiahai/following{/other_user}", "gists_url": "https://api.github.com/users/LLjiahai/gists{/gist_id}", "starred_url": "https://api.github.com/users/LLjiahai/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/LLjiahai/subscriptions", "organizations_url": "https://api.github.com/users/LLjiahai/orgs", "repos_url": "https://api.github.com/users/LLjiahai/repos", "events_url": "https://api.github.com/users/LLjiahai/events{/privacy}", "received_events_url": "https://api.github.com/users/LLjiahai/received_events", "type": "User", "site_admin": false }
[]
closed
false
null
[]
null
[ "Im always surprised people can take the time to open the issue and then completely fail to explain their actual issue.", "oh my god stupid thing to do,When I try to use \"bulk_update\" function update mysql_db datetime field, it doesn't take effect", "It works fine for me:\r\n\r\n```python\r\nclass Reg(Model):\r\n key = CharField()\r\n timestamp = DateTimeField()\r\n\r\n# Create 3 objects w/timestamp of Mar 1, 2, and 3rd.\r\nregs = [Reg.create(key='k%s' % i, timestamp=dt(2022, 3, i))\r\n for i in (1, 2, 3)]\r\n\r\n# Change timestamps to be Apr 1, 2, and 3.\r\nfor reg in regs:\r\n reg.timestamp = reg.timestamp.replace(month=4)\r\n\r\n# Perform update.\r\nReg.bulk_update(regs, fields=[Reg.key, Reg.timestamp])\r\n\r\n# Verify timestamps updated correctly.\r\nfor reg in Reg.select().order_by(Reg.key):\r\n print(reg.key, reg.timestamp)\r\n```\r\n\r\nOutput\r\n\r\n```\r\nk1 2022-04-01 00:00:00\r\nk2 2022-04-02 00:00:00\r\nk3 2022-04-03 00:00:00\r\n```" ]
"2022-02-28T10:17:13"
"2022-02-28T14:30:43"
"2022-02-28T12:42:03"
NONE
null
![aaa](https://user-images.githubusercontent.com/30220658/155965562-7511c03e-5de1-4df0-91b1-805303546976.png)
{ "url": "https://api.github.com/repos/coleifer/peewee/issues/2536/reactions", "total_count": 0, "+1": 0, "-1": 0, "laugh": 0, "hooray": 0, "confused": 0, "heart": 0, "rocket": 0, "eyes": 0 }
https://api.github.com/repos/coleifer/peewee/issues/2536/timeline
null
completed
null
null
https://api.github.com/repos/coleifer/peewee/issues/2535
https://api.github.com/repos/coleifer/peewee
https://api.github.com/repos/coleifer/peewee/issues/2535/labels{/name}
https://api.github.com/repos/coleifer/peewee/issues/2535/comments
https://api.github.com/repos/coleifer/peewee/issues/2535/events
https://github.com/coleifer/peewee/issues/2535
1,150,740,149
I_kwDOAA7yGM5Elua1
2,535
Flask-Admin Peewee Contribution Issue
{ "login": "mkmoisen", "id": 2534631, "node_id": "MDQ6VXNlcjI1MzQ2MzE=", "avatar_url": "https://avatars.githubusercontent.com/u/2534631?v=4", "gravatar_id": "", "url": "https://api.github.com/users/mkmoisen", "html_url": "https://github.com/mkmoisen", "followers_url": "https://api.github.com/users/mkmoisen/followers", "following_url": "https://api.github.com/users/mkmoisen/following{/other_user}", "gists_url": "https://api.github.com/users/mkmoisen/gists{/gist_id}", "starred_url": "https://api.github.com/users/mkmoisen/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/mkmoisen/subscriptions", "organizations_url": "https://api.github.com/users/mkmoisen/orgs", "repos_url": "https://api.github.com/users/mkmoisen/repos", "events_url": "https://api.github.com/users/mkmoisen/events{/privacy}", "received_events_url": "https://api.github.com/users/mkmoisen/received_events", "type": "User", "site_admin": false }
[]
closed
false
null
[]
null
[ "This belongs on the flask-admin repo.", "@coleifer Thanks, I will add it there. Would you be able to comment on this part:\r\n\r\nWould there be any harm to wrapping calls from inside of flask-admin with code that opens/closes a connection, if the user is opening a connection from `app.before_request`?\r\n\r\nE.g.\r\n\r\n```\r\ndef @app.get('/tweets/'):\r\n with db:\r\n return jsonify(Tweet.select()), 200\r\n\r\n@app.before_request\r\ndef before():\r\n db.connect()\r\n\r\n@app.after_request\r\ndef after():\r\n db.close()\r\n\r\n\r\n```" ]
"2022-02-25T18:35:30"
"2022-02-25T18:52:18"
"2022-02-25T18:48:08"
NONE
null
Sorry if this is the wrong repo to put this in, I wasn't sure if creating this issue in flask-admin made sense. The Peewee contribution to Flask-Admin assumes that a connection to the database has already been opened in `app.before_request`. If a connection has not been opened in `app.before_request`, and the db's `autoconnect=False`, then this will result in a lot of `peewee.InterfaceError: Error, database connection not opened.` errors. The only way to prevent this is to subclass `ModelView` and wrap `get_one`, `get_list`, `create_model`, `update_model`, `delete_model`, and `action_delete` with code that opens/closes the connection and calls `super()`. This is easy, not a big deal. However handling foreign key select drop downs and ajax call backs is a bit harder. Because the `QueryAjaxModelLoader`, `SelectQueryField`, and `ModelSelectField` classes are hard coded and not polymorphic, I had to subclass and copy and paste some code before I could wrap it with code that opens/closes the connection. This isn't great because whenever there is an upgrade I have manually diff it and update the code. I have two suggestions. Would you please take a look and let me know what you think? ---- Would it make sense to wrap all the calls to the database from flask-admin/peewee contribution with code that opens/closes the connection? I'm not sure if this poses any kind of backwards compatibility issues for people who open connections in `app.before_request`. For example the following opens a save point: with db: with db: # opens save point here list(Tweet.select()) --- If that is not a good approach, could we make the `ModelView` more polymorphic? I think there will be more benefits to this approach aside from my use case, as it would make it much easier to customize the behavior. Today there is no simple way to customize the `ModelSelectField`, for example, due to this lack of polymorphism. The `ModelConverter` class could instead look like this: ``` class ModelConverter: select_query_field_class = SelectQueryField # make this polymorphic model_select_field_class = ModelSelectField # make this polymorphic def handle_foreign_key(self, model, field, **kwargs): if field.null: kwargs['allow_blank'] = True if field.choices is not None: field_obj = self.select_query_field_class(query=field.choices, **kwargs) # polymorphic call else: field_obj = self.model_select_field_class(model=field.rel_model, **kwargs) # polymorphic call return FieldInfo(field.name, field_obj) ``` If it was polymorphic, then I wouldn't need to copy paste this whole function just to swap out the class names. The only thing I would need to do is subclass ModelSelect/SelectQueryField and wrap with calls to open/close the db. What I have to do today is copy paste the whole `handle_foreign_key` over and then change only the class names. In addition, if you do it this way, someone could subclass ModelSelectField to restrict the query based on user or route or something. In general the polymorphic approach opens up more avenues for customization. Thank you.
{ "url": "https://api.github.com/repos/coleifer/peewee/issues/2535/reactions", "total_count": 0, "+1": 0, "-1": 0, "laugh": 0, "hooray": 0, "confused": 0, "heart": 0, "rocket": 0, "eyes": 0 }
https://api.github.com/repos/coleifer/peewee/issues/2535/timeline
null
completed
null
null
https://api.github.com/repos/coleifer/peewee/issues/2534
https://api.github.com/repos/coleifer/peewee
https://api.github.com/repos/coleifer/peewee/issues/2534/labels{/name}
https://api.github.com/repos/coleifer/peewee/issues/2534/comments
https://api.github.com/repos/coleifer/peewee/issues/2534/events
https://github.com/coleifer/peewee/issues/2534
1,149,020,930
I_kwDOAA7yGM5EfKsC
2,534
Accept NoneType value as a default; Verify arguments while initializing the model object
{ "login": "hung3a8", "id": 52038546, "node_id": "MDQ6VXNlcjUyMDM4NTQ2", "avatar_url": "https://avatars.githubusercontent.com/u/52038546?v=4", "gravatar_id": "", "url": "https://api.github.com/users/hung3a8", "html_url": "https://github.com/hung3a8", "followers_url": "https://api.github.com/users/hung3a8/followers", "following_url": "https://api.github.com/users/hung3a8/following{/other_user}", "gists_url": "https://api.github.com/users/hung3a8/gists{/gist_id}", "starred_url": "https://api.github.com/users/hung3a8/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/hung3a8/subscriptions", "organizations_url": "https://api.github.com/users/hung3a8/orgs", "repos_url": "https://api.github.com/users/hung3a8/repos", "events_url": "https://api.github.com/users/hung3a8/events{/privacy}", "received_events_url": "https://api.github.com/users/hung3a8/received_events", "type": "User", "site_admin": false }
[]
closed
false
null
[]
null
[ "The first issue -- sorry this is not something I intend to change. Just write a wrapper or a classmethod constructor that does the validation if you want.\r\n\r\n>In peewee.Metadata.add_field, fields with default=None are passed, and their values are set to the pythonic default values (not sure how to call it) like '' for CharField.\r\n\r\nThis doesn't sound right to me at all.\r\n\r\n```python\r\nclass User(Model):\r\n username = CharField()\r\n password = CharField()\r\n email = CharField(null=True)\r\n class Meta:\r\n database = db\r\n\r\ndb.create_tables([User])\r\n\r\nu = User(username='foo', password='secret')\r\nprint(u.username, u.password, u.email)\r\nu.save()\r\n\r\nu = User.get(User.username == 'foo')\r\nprint(u.username, u.password, u.email)\r\n```\r\n\r\nThis correctly initializes email to None and stores it as None. It is also None when read back from the db:\r\n\r\n```\r\n$ python x.py \r\nfoo secret None\r\nfoo secret None\r\n```" ]
"2022-02-24T08:54:48"
"2022-02-25T01:11:09"
"2022-02-25T01:11:09"
NONE
null
In [`peewee.Model.__init__`](https://github.com/coleifer/peewee/blob/528e014c640e0743c7a34069ca31754d79cc3de5/peewee.py#L6321), we set the values for the fields like this: ```python for k in kwargs: setattr(self, k, kwargs[k]) ``` Let's say I am working on a `User` model with some fields like `username` or `password`, but somewhere in my code, I accidentally create an object like this: ```python user = User(usernam='hung3a8', password='secret') ``` As you can see, I accidentally passed `usernam` instead of `username`. But as Peewee automatically set a new attribute for this arg instead of raising any kind of errors, which makes debugging becomes an actual hell. So instead of searching for the typo, maybe we should have a proper argument validation, or set those required fields as arguments and optional fields with default values as optional arguments (just like Django ORM and SQLAlchemy). --- For some reason, `Field(default=None, null=True)` doesn't set the field value to `None`. In [`peewee.Metadata.add_field`](https://github.com/coleifer/peewee/blob/master/peewee.py#L6043), fields with `default=None` are passed, and their values are set to the pythonic default values (not sure how to call it) like `''` for CharField. Even though we can set `NoneType` value for the field while initializing the object, doing that repetitively is troublesome. For example, with the same `User` model from the previous issue, now I also have a field called `email`, which is not required and nullable. While we can set it like this: ```python user = User(username='hung3a8', password='secret', email=None) ``` Doing like this is much more cleaner: ```python user = User(username='hung3a8', password='secret') # We wont need to care about `email` anymore if the default value is set to None. ```
{ "url": "https://api.github.com/repos/coleifer/peewee/issues/2534/reactions", "total_count": 0, "+1": 0, "-1": 0, "laugh": 0, "hooray": 0, "confused": 0, "heart": 0, "rocket": 0, "eyes": 0 }
https://api.github.com/repos/coleifer/peewee/issues/2534/timeline
null
completed
null
null
https://api.github.com/repos/coleifer/peewee/issues/2533
https://api.github.com/repos/coleifer/peewee
https://api.github.com/repos/coleifer/peewee/issues/2533/labels{/name}
https://api.github.com/repos/coleifer/peewee/issues/2533/comments
https://api.github.com/repos/coleifer/peewee/issues/2533/events
https://github.com/coleifer/peewee/issues/2533
1,147,602,268
I_kwDOAA7yGM5EZwVc
2,533
Add and_, or_ functions ?
{ "login": "mkmoisen", "id": 2534631, "node_id": "MDQ6VXNlcjI1MzQ2MzE=", "avatar_url": "https://avatars.githubusercontent.com/u/2534631?v=4", "gravatar_id": "", "url": "https://api.github.com/users/mkmoisen", "html_url": "https://github.com/mkmoisen", "followers_url": "https://api.github.com/users/mkmoisen/followers", "following_url": "https://api.github.com/users/mkmoisen/following{/other_user}", "gists_url": "https://api.github.com/users/mkmoisen/gists{/gist_id}", "starred_url": "https://api.github.com/users/mkmoisen/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/mkmoisen/subscriptions", "organizations_url": "https://api.github.com/users/mkmoisen/orgs", "repos_url": "https://api.github.com/users/mkmoisen/repos", "events_url": "https://api.github.com/users/mkmoisen/events{/privacy}", "received_events_url": "https://api.github.com/users/mkmoisen/received_events", "type": "User", "site_admin": false }
[]
closed
false
null
[]
null
[ "Peewee doesn't need these - you can just `from operator import or_` and use that directly." ]
"2022-02-23T03:58:24"
"2022-02-23T14:04:41"
"2022-02-23T14:04:41"
NONE
null
Would you consider adding a public `and_` and `or_` function to peewee? SQLAlchemy has this which helps readability, compared to the bitwise operators. ``` User.select().join( Tweet, JOIN.OUTER_JOIN, on=(Tweet.user == User.id) ).where( User.id == 123, or_( Tweet.id.is_null(), Tweet.timestamp > datetime.now() - timedelta(hours=1) ) ) ``` vs ``` User.select().join( Tweet, JOIN.OUTER_JOIN, on=(Tweet.user == User.id) ).where( User.id == 123, ( (Tweet.id.is_null()) | (Tweet.timestamp > datetime.now() - timedelta(hours=1)) ) ) ``` The bitwise style can be especially hard to read when you have some complicated, multi nesting where clause with many ands and ors. I noticed you already do this logic in in `where` and `orwhere` functions in `peewee.py`. Something like the following should suffice: ``` def or_(*expressions): return reduce(operator.or_, expressions) def and_(*expressions): return reduce(operator.and_, expressions) ```
{ "url": "https://api.github.com/repos/coleifer/peewee/issues/2533/reactions", "total_count": 0, "+1": 0, "-1": 0, "laugh": 0, "hooray": 0, "confused": 0, "heart": 0, "rocket": 0, "eyes": 0 }
https://api.github.com/repos/coleifer/peewee/issues/2533/timeline
null
completed
null
null
https://api.github.com/repos/coleifer/peewee/issues/2532
https://api.github.com/repos/coleifer/peewee
https://api.github.com/repos/coleifer/peewee/issues/2532/labels{/name}
https://api.github.com/repos/coleifer/peewee/issues/2532/comments
https://api.github.com/repos/coleifer/peewee/issues/2532/events
https://github.com/coleifer/peewee/pull/2532
1,147,261,095
PR_kwDOAA7yGM4zTbiL
2,532
Add better support for left_outer_join convenience function
{ "login": "mkmoisen", "id": 2534631, "node_id": "MDQ6VXNlcjI1MzQ2MzE=", "avatar_url": "https://avatars.githubusercontent.com/u/2534631?v=4", "gravatar_id": "", "url": "https://api.github.com/users/mkmoisen", "html_url": "https://github.com/mkmoisen", "followers_url": "https://api.github.com/users/mkmoisen/followers", "following_url": "https://api.github.com/users/mkmoisen/following{/other_user}", "gists_url": "https://api.github.com/users/mkmoisen/gists{/gist_id}", "starred_url": "https://api.github.com/users/mkmoisen/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/mkmoisen/subscriptions", "organizations_url": "https://api.github.com/users/mkmoisen/orgs", "repos_url": "https://api.github.com/users/mkmoisen/repos", "events_url": "https://api.github.com/users/mkmoisen/events{/privacy}", "received_events_url": "https://api.github.com/users/mkmoisen/received_events", "type": "User", "site_admin": false }
[]
closed
false
null
[]
null
[ "Thanks, looks good!" ]
"2022-02-22T18:56:37"
"2022-02-23T14:23:29"
"2022-02-23T14:23:19"
NONE
null
The `Source` class has a `left_outer_join` convenience function which calls `join`. However, unlike `join`, the `left_outer_join` function is not overridden in `Select` and `ModelSelect`. Currently, this means that doing `User.select().left_outer_join(Tweet)` returns a `Join` object, not a `ModelSelect`. This is inconsistent with `User.select().join(Tweet)` which returns a `ModelSelect`. For example the following fails today because there is no `switch` function defined on the `Join` object: Tweet.select().left_outer_join(User).switch The `Join` object also has no `where`, `sql`, or `execute` functions, which effectively means this `left_outer_join` function cannot be used today. --- This PR adds the `left_outer_join` convenience function to the `Select` and `ModelSelect` classes. --- One thing to consider is whether or not it might be better to name this `outerjoin` instead of `left_outer_join`. `outerjoin` would be [consistent with SQLAlchemy](https://docs.sqlalchemy.org/en/14/core/selectable.html#sqlalchemy.sql.expression.FromClause.outerjoin) if that was desirable. Or perhaps just shorten `left_outer_join` to `outer_join` or `left_join`. If you wanted to, I think it *might* be safe to rename this function without breaking backwards compatibility. Because the current Tweet.select().left_outer_join(User) is returning a `Join` object which cannot be used in any context at least that I can think of. E.g., it has no execute(), where(), sql() functions. ---- I added a test for this which is passing. However I found that a few other tests are failing, my guess is that they were already failing before this change. Thee following failed for me: test_close_stale (tests.pool.TestPooledDatabase), test_timestamp_field_from_ts (tests.fields.TestTimestampField), test_timestamp_field_parts (tests.fields.TestTimestampField) .
{ "url": "https://api.github.com/repos/coleifer/peewee/issues/2532/reactions", "total_count": 0, "+1": 0, "-1": 0, "laugh": 0, "hooray": 0, "confused": 0, "heart": 0, "rocket": 0, "eyes": 0 }
https://api.github.com/repos/coleifer/peewee/issues/2532/timeline
null
null
false
{ "url": "https://api.github.com/repos/coleifer/peewee/pulls/2532", "html_url": "https://github.com/coleifer/peewee/pull/2532", "diff_url": "https://github.com/coleifer/peewee/pull/2532.diff", "patch_url": "https://github.com/coleifer/peewee/pull/2532.patch", "merged_at": "2022-02-23T14:23:19" }
https://api.github.com/repos/coleifer/peewee/issues/2531
https://api.github.com/repos/coleifer/peewee
https://api.github.com/repos/coleifer/peewee/issues/2531/labels{/name}
https://api.github.com/repos/coleifer/peewee/issues/2531/comments
https://api.github.com/repos/coleifer/peewee/issues/2531/events
https://github.com/coleifer/peewee/issues/2531
1,146,962,375
I_kwDOAA7yGM5EXUHH
2,531
How contribute to project ?
{ "login": "ParfaitD9", "id": 79906637, "node_id": "MDQ6VXNlcjc5OTA2NjM3", "avatar_url": "https://avatars.githubusercontent.com/u/79906637?v=4", "gravatar_id": "", "url": "https://api.github.com/users/ParfaitD9", "html_url": "https://github.com/ParfaitD9", "followers_url": "https://api.github.com/users/ParfaitD9/followers", "following_url": "https://api.github.com/users/ParfaitD9/following{/other_user}", "gists_url": "https://api.github.com/users/ParfaitD9/gists{/gist_id}", "starred_url": "https://api.github.com/users/ParfaitD9/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/ParfaitD9/subscriptions", "organizations_url": "https://api.github.com/users/ParfaitD9/orgs", "repos_url": "https://api.github.com/users/ParfaitD9/repos", "events_url": "https://api.github.com/users/ParfaitD9/events{/privacy}", "received_events_url": "https://api.github.com/users/ParfaitD9/received_events", "type": "User", "site_admin": false }
[]
closed
false
null
[]
null
[ "#peewee on libera.chat (IRC) is probably the best place, but it's fairly quiet and mostly used for helping answer questions or troubleshooting issues. To contribute you just need the following:\r\n\r\n* have an idea for how to improve the library\r\n* implement it (optionally checking here to see if the improvement is wanted/desirable)\r\n* notify maintainers about improvements", "Thanks for the reply.\n\nLe mar. 22 févr. 2022 à 3:20 PM, Charles Leifer ***@***.***>\na écrit :\n\n> Closed #2531 <https://github.com/coleifer/peewee/issues/2531>.\n>\n> —\n> Reply to this email directly, view it on GitHub\n> <https://github.com/coleifer/peewee/issues/2531#event-6118428127>, or\n> unsubscribe\n> <https://github.com/notifications/unsubscribe-auth/ATBUOTIBGYLOM2BRCEMKEFLU4OLSZANCNFSM5PBQJOAQ>\n> .\n> You are receiving this because you authored the thread.Message ID:\n> ***@***.***>\n>\n" ]
"2022-02-22T14:11:34"
"2022-02-22T16:35:19"
"2022-02-22T14:20:16"
NONE
null
I just want to know how to contribute to the project. I'm very interested.
{ "url": "https://api.github.com/repos/coleifer/peewee/issues/2531/reactions", "total_count": 0, "+1": 0, "-1": 0, "laugh": 0, "hooray": 0, "confused": 0, "heart": 0, "rocket": 0, "eyes": 0 }
https://api.github.com/repos/coleifer/peewee/issues/2531/timeline
null
completed
null
null
https://api.github.com/repos/coleifer/peewee/issues/2530
https://api.github.com/repos/coleifer/peewee
https://api.github.com/repos/coleifer/peewee/issues/2530/labels{/name}
https://api.github.com/repos/coleifer/peewee/issues/2530/comments
https://api.github.com/repos/coleifer/peewee/issues/2530/events
https://github.com/coleifer/peewee/issues/2530
1,146,059,384
I_kwDOAA7yGM5ET3p4
2,530
Memory Caching Question
{ "login": "mkmoisen", "id": 2534631, "node_id": "MDQ6VXNlcjI1MzQ2MzE=", "avatar_url": "https://avatars.githubusercontent.com/u/2534631?v=4", "gravatar_id": "", "url": "https://api.github.com/users/mkmoisen", "html_url": "https://github.com/mkmoisen", "followers_url": "https://api.github.com/users/mkmoisen/followers", "following_url": "https://api.github.com/users/mkmoisen/following{/other_user}", "gists_url": "https://api.github.com/users/mkmoisen/gists{/gist_id}", "starred_url": "https://api.github.com/users/mkmoisen/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/mkmoisen/subscriptions", "organizations_url": "https://api.github.com/users/mkmoisen/orgs", "repos_url": "https://api.github.com/users/mkmoisen/repos", "events_url": "https://api.github.com/users/mkmoisen/events{/privacy}", "received_events_url": "https://api.github.com/users/mkmoisen/received_events", "type": "User", "site_admin": false }
[]
closed
false
null
[]
null
[ "So peewee select queries are not executed until iterated over (although explicitly calling `execute()` on a Select query *will* execute it, returning a cursor wrapper, but that's kinda beside the point).\r\n\r\nHowever, this code *only* issues and executes a single query:\r\n\r\n```python\r\nquery = Tweet.select().limit(50)\r\n\r\n# Query is executed here.\r\nfor tweet in query:\r\n ...\r\n\r\n# These iterations and other operations do not re-execute the query.\r\nfor tweet in query:\r\n ...\r\n\r\ntweets = list(query)\r\n\r\nfirst_tweet = query[0]\r\n...\r\n```\r\n\r\nDuring the first iteration the resulting rows are cached, in memory, so that subsequent iterations and even indexing will not hit the database again. This is what is meant by caching in Peewee -- rows are cached so that the query result can be operated on more than just a single-shot iteration.\r\n\r\nIf, however, you are processing a ton of rows iteratively and all you need is a single iteration, you can save memory by using `.iterator()`. When using `.iterator()`, attempting to iterate over the query a second time will yield no rows/no data.\r\n\r\nI'm not sure why you are coercing it to a list - that should be unnecessary in any case, since simply iterating and re-iterating the query will not yield additional executions.", "I'm just coercing to a list for demonstration purposes. In terms of forcing the select to execute, calling `list(Tweet.select())` is the same as `for tweet in Tweet.select():`.\r\n\r\nIf I need to load all the rows into memory anyways to accomplish some task, is there any benefit to calling `iterator()`? I'm pretty sure the answer is no, right?\r\n\r\nFor example, there is no benefit to calling `iterator()` in this this REST API example:\r\n\r\n```\r\n@app.get('/tweets/')\r\ndef get_tweets():\r\n tweets = Tweet.select().iterator()\r\n return TweetSchema.dump(tweets, many=True)\r\n\r\n```\r\n\r\nIs that right?\r\n", "No there's no reason to worry about it unless, like the docs say, you intend to iterate over so many rows that memory usage would become an issue." ]
"2022-02-21T17:20:50"
"2022-02-21T19:23:17"
"2022-02-21T18:43:32"
NONE
null
Not a bug, just a question. In the documentation it states the following: > Subsequent iterations of the same query will not hit the database as the results are cached. To disable this behavior (to reduce memory usage), call Select.iterator() when iterating. I'm not clear in what circumstances I would want to call `iterator()` to reduce memory consumption. In my web app I am commonly doing something like the following: ``` @app.get('/tweets/') def get_tweets(): tweets = list(Tweet.select()) # as opposed to list(Tweet.select().iterator()) return TweetSchema.dump(tweets, many=True) ``` Am I using twice as much memory as required if I do `tweets = list(Tweet.select())` compared to `tweets = list(Tweet.select().iterator())` ? I don't think so, because of the following shows that it is by reference, not by value: ``` sel = Tweet.select() tweets = list(sel) assert sel[0] is tweets[0] assert id(sel[0]) == id(tweets[0]) ```
{ "url": "https://api.github.com/repos/coleifer/peewee/issues/2530/reactions", "total_count": 0, "+1": 0, "-1": 0, "laugh": 0, "hooray": 0, "confused": 0, "heart": 0, "rocket": 0, "eyes": 0 }
https://api.github.com/repos/coleifer/peewee/issues/2530/timeline
null
completed
null
null
https://api.github.com/repos/coleifer/peewee/issues/2529
https://api.github.com/repos/coleifer/peewee
https://api.github.com/repos/coleifer/peewee/issues/2529/labels{/name}
https://api.github.com/repos/coleifer/peewee/issues/2529/comments
https://api.github.com/repos/coleifer/peewee/issues/2529/events
https://github.com/coleifer/peewee/pull/2529
1,145,289,456
PR_kwDOAA7yGM4zM9J-
2,529
Fix count_queries to prevent couting pool events as queries.
{ "login": "mkmoisen", "id": 2534631, "node_id": "MDQ6VXNlcjI1MzQ2MzE=", "avatar_url": "https://avatars.githubusercontent.com/u/2534631?v=4", "gravatar_id": "", "url": "https://api.github.com/users/mkmoisen", "html_url": "https://github.com/mkmoisen", "followers_url": "https://api.github.com/users/mkmoisen/followers", "following_url": "https://api.github.com/users/mkmoisen/following{/other_user}", "gists_url": "https://api.github.com/users/mkmoisen/gists{/gist_id}", "starred_url": "https://api.github.com/users/mkmoisen/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/mkmoisen/subscriptions", "organizations_url": "https://api.github.com/users/mkmoisen/orgs", "repos_url": "https://api.github.com/users/mkmoisen/repos", "events_url": "https://api.github.com/users/mkmoisen/events{/privacy}", "received_events_url": "https://api.github.com/users/mkmoisen/received_events", "type": "User", "site_admin": false }
[]
closed
false
null
[]
null
[ "Thanks, merged an equivalent patch.", "Thanks. Is there any way to get the query execution time?\r\n\r\nOne of the nice things about django is that `connection.queries` stores the execution time of the query, so for example you can log all queries that take longer than 2 seconds:\r\n\r\n from django.db import connection\r\n for query in connection.queries:\r\n if query.time > 2: # I cannot remember if it is query.time or maybe query[1]\r\n log_expensive_query(query)\r\n\r\n(Actually this is only true in Django when debug mode is true which you shouldn't do in production. So in prod you have to write some custom middleware, I haven't tried that.)", "You should really be using your databases built-in slow query logger for that.", "While that is true, I do find the django connection.queries execution time useful while in development. \r\n\r\nI have my nonprod middleware dump connection.queries and I will visually check the time of each query to make sure I didn't forget an index for example. \r\n\r\nThe alternative is to switch over to a psql shell and select from pg_stat_statements, and typing out the where clause to return only the relevant SQL. It's not too convenient compared to just reading the output of the django connection.queries.\r\n\r\n---\r\n\r\nWould you be open to adding timing execution to peewee? If you are, I believe the following change to `execute_sql` is backwards compatible. The logger emits a tuple of length 3 instead of length 2.\r\n\r\n\r\n\r\n```\r\n def execute_sql(self, sql, params=None, commit=SENTINEL):\r\n if commit is SENTINEL:\r\n if self.in_transaction():\r\n commit = False\r\n elif self.commit_select:\r\n commit = True\r\n else:\r\n commit = not sql[:6].lower().startswith('select')\r\n\r\n with __exception_wrapper__:\r\n cursor = self.cursor(commit)\r\n start_time = datetime.datetime.now()\r\n try:\r\n cursor.execute(sql, params or ())\r\n except Exception:\r\n if self.autorollback and not self.in_transaction():\r\n self.rollback()\r\n raise\r\n else:\r\n if commit and not self.in_transaction():\r\n self.commit()\r\n finally:\r\n end_time = datetime.datetime.now()\r\n\r\n logger.debug((sql, params, (end_time - start_time).total_seconds()))\r\n\r\n return cursor\r\n```", "If you are insistent on wanting this in your Python code, then I suggest subclassing Database or implementing a mixin class and wrapping `execute_sql()` with whatever timing logic you want." ]
"2022-02-21T03:58:43"
"2022-02-21T18:34:52"
"2022-02-21T13:25:52"
NONE
null
When using the `count_queries()` function from the `playhouse.test_utils`, it does not give the expected count when you use a Pool. It includes things like opening a connection or returning the connection to the pool as a query. The solution is to simply include log records from "peewee" not from "peewee.pool". I've tested this PR only on my local postgresql. Here is a demonstration of the bug: ``` from peewee import SQL from playhouse.pool import PooledPostgresqlExtDatabase from playhouse.test_utils import count_queries db = PooledPostgresqlExtDatabase( 'test', user='test', password='test', max_connections=1, autoconnect=False, ) with count_queries() as counter: with db: db.execute(SQL('select 1')) assert counter.count == 4 for query in counter.get_queries(): print(query) ``` Here are the 4 queries recorded for me, instead of the expected 1. ``` <LogRecord: peewee.pool, 10, C:\test\lib\site-packages\playhouse\pool.py, 130, "No connection available in pool."> <LogRecord: peewee.pool, 10, C:\test\lib\site-packages\playhouse\pool.py, 159, "Created new connection %s."> <LogRecord: peewee, 10, C:\test\lib\site-packages\peewee.py, 3148, "('select 1', [])"> <LogRecord: peewee.pool, 10, C:\test\lib\site-packages\playhouse\pool.py, 186, "Returning %s to pool."> ``` The solution here is very simple, just make sure to only include logs emitted by "peewee" and nothing else (such as "peewee.pool").
{ "url": "https://api.github.com/repos/coleifer/peewee/issues/2529/reactions", "total_count": 0, "+1": 0, "-1": 0, "laugh": 0, "hooray": 0, "confused": 0, "heart": 0, "rocket": 0, "eyes": 0 }
https://api.github.com/repos/coleifer/peewee/issues/2529/timeline
null
null
false
{ "url": "https://api.github.com/repos/coleifer/peewee/pulls/2529", "html_url": "https://github.com/coleifer/peewee/pull/2529", "diff_url": "https://github.com/coleifer/peewee/pull/2529.diff", "patch_url": "https://github.com/coleifer/peewee/pull/2529.patch", "merged_at": null }
https://api.github.com/repos/coleifer/peewee/issues/2528
https://api.github.com/repos/coleifer/peewee
https://api.github.com/repos/coleifer/peewee/issues/2528/labels{/name}
https://api.github.com/repos/coleifer/peewee/issues/2528/comments
https://api.github.com/repos/coleifer/peewee/issues/2528/events
https://github.com/coleifer/peewee/pull/2528
1,143,396,343
PR_kwDOAA7yGM4zGgQQ
2,528
Add support for conditionally inserting a single row.
{ "login": "mkmoisen", "id": 2534631, "node_id": "MDQ6VXNlcjI1MzQ2MzE=", "avatar_url": "https://avatars.githubusercontent.com/u/2534631?v=4", "gravatar_id": "", "url": "https://api.github.com/users/mkmoisen", "html_url": "https://github.com/mkmoisen", "followers_url": "https://api.github.com/users/mkmoisen/followers", "following_url": "https://api.github.com/users/mkmoisen/following{/other_user}", "gists_url": "https://api.github.com/users/mkmoisen/gists{/gist_id}", "starred_url": "https://api.github.com/users/mkmoisen/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/mkmoisen/subscriptions", "organizations_url": "https://api.github.com/users/mkmoisen/orgs", "repos_url": "https://api.github.com/users/mkmoisen/repos", "events_url": "https://api.github.com/users/mkmoisen/events{/privacy}", "received_events_url": "https://api.github.com/users/mkmoisen/received_events", "type": "User", "site_admin": false }
[]
closed
false
null
[]
null
[ "I'm going to pass for now, thanks.", "Hi @coleifer would you have another suggestion for being able to accomplish the insert myself?\r\n\r\nI came up with this but do not like it. Is there a better way?\r\n\r\n```\r\nTweet.insert_from(\r\n peewee.Select(\r\n columns=['my_tweet', user, datetime.now()] # Necessary to manually add default values like datetime.now()\r\n ).where(\r\n ~fn.EXISTS(\r\n Tweet.select().where(\r\n Tweet.user == user,\r\n Tweet.timestamp > datetime.now() - timedelta(hours=1)\r\n ) \r\n )\r\n ),\r\n [Tweet.content, Tweet.user, Tweet.timestamp]\r\n)\r\n```", "I'd suggest just wrapping it up in a helper method on a BaseModel class you keep in your library:\r\n\r\n```python\r\n\r\nclass BaseModel(Model):\r\n @classmethod\r\n def insert_where(cls, data, *where):\r\n fields, values = zip(*data.items())\r\n sq = Select(columns=values).where(~fn.EXISTS(cls.select().where(*where)))\r\n return cls.insert_from(sq, fields)\r\n\r\nins = Tweet.insert_where({\r\n Tweet.content: 'my_tweet',\r\n Tweet.user: user,\r\n Tweet.timestamp: datetime.now()},\r\n (Tweet.user == user) & (Tweet.timestamp > datetime.now() - timedelta(hours=1)))\r\n```", "Sweet, thank you.", "I've gone ahead and thrown this into the `playhouse.shortcuts` module, which would result in:\r\n\r\n```python\r\nfrom playhouse import shortcuts\r\n\r\nclass BaseModel(Model):\r\n @classmethod\r\n def insert_where(cls, data, *where):\r\n return shortcuts.insert_where(cls, data, *where)\r\n```", "Hi @coleifer \r\n\r\nThank you. I have a few suggestions. Please let me know what you think.\r\n\r\n1) Automatically provide default values like `.insert`\r\n2) Change the API to resemble `.insert(**insert)`.\r\n3) Change the API to to return the PK like `.insert()`.\r\n3) Allow the user to specify the entire WHERE clause (to do EXISTS or NOT EXISTS on same or *different* table)\r\n\r\n\r\nHere is the function that I've been using this weekend for my application:\r\n\r\n```\r\n @classmethod\r\n def insert_where(cls, where=None, **insert):\r\n for field, default in cls._meta.defaults.items():\r\n if field.name not in insert:\r\n val = default\r\n if callable_(val):\r\n val = val()\r\n insert[field.name] = val\r\n\r\n fields, values = zip(*insert.items())\r\n\r\n cursor = cls.insert_from(\r\n Select(columns=values).where(\r\n where\r\n ),\r\n fields\r\n ).execute()\r\n\r\n return cls._meta.database.last_insert_id(cursor, Insert.SIMPLE)\r\n```\r\n\r\nThis let's me use it in the following way:\r\n\r\n```\r\n# Only allow insert to Tweet if the User is a paid subscriber and not a free user:\r\ntweet_id = Tweet.insert_where(\r\n content=\"my tweet\", user=user, \r\n where=fn.EXISTS(User.select().where(User.id == user, User.subscriber_type == 'PAID'))\r\n)\r\n\r\n# Same thing but using a NOT EXISTS\r\ntweet_id = Tweet.insert_where(\r\n content=\"my tweet\", user=user,\r\n where=~fn.EXISTS(User.select().where(User.id == user, User.subscriber_type == 'FREE'))\r\n)\r\n\r\n# Show how a empty `where` still works as expected:\r\nwhere = None\r\nif user_type != 'admin':\r\n where = ~fn.EXISTS(Tweet.select().where(Tweet.timestamp > now() - timedelta(hours=1)))\r\n\r\ntweet_id = Tweet.insert_where(\r\n content=\"my tweet\", user=user,\r\n where=where\r\n)\r\n\r\n```\r\n\r\nI like this API because it closely resembles `Tweet.insert`, insofar as you can pass the column=value pairs via **insert, and it also returns the primary key just like `Tweet.insert().execute()`.\r\n\r\nThis also automatically provides default values like `Tweet.insert`. \r\n\r\nThe `where=None` is nice because sometimes you might want to conditionally build up the where clause, but have nothing to build. For example if the user is an admin, you can still call insert_where with where=None and it will just do a normal insert.", "Adding the defaults and providing more flexibility definitely seems fine to me. Check out 23ae5d2c576651db4c50775ef3e8051776223a86 -- I'm still returning the query rather than executing it, since that is the common pattern in Peewee. But most of the other changes you described are present." ]
"2022-02-18T16:51:20"
"2022-07-27T03:31:55"
"2022-02-18T19:21:23"
NONE
null
Hello, This PR enables conditional insertion of a single row, with default values automatically provided, in a single trip to the database. Would you be willing to support this syntactic sugar? In this example, we are conditionally inserting a Tweet, so long as the User has not already tweeted in the last hour, via a single trip to the DB: from datetime import datetime, timedelta from peewee import SQL, fn user = User.create(username='Matthew') Tweet.insert( content='my tweet', user=user, ).where( ~fn.EXISTS( Tweet.select(SQL('1')).where( Tweet.user == user, Tweet.timestamp > datetime.now() - timedelta(hours=1) ) ) ) This would translate into the following SQL (Note the replacement of VALUES with SELECT) INSERT INTO tweet ( timestamp, -- note that timestamp default value is automatically provided content, user_id ) SELECT %s, %s, %s WHERE NOT EXISTS ( SELECT 1 FROM tweet WHERE user_id = %s AND timestamp > %s ) [datetime.datetime(2022, 2, 17, 23, 49, 57, 299578), 'my tweet', 1, 1, datetime.datetime(2022, 2, 17, 22, 49, 57, 299578)] ---- This PR is a POC with minimal code changes to get this working. You could either use this PR or redo it yourself according to your preference. I could add some documentation or tests to beef up this PR later if you are on board with the idea. I've tested both cases where it successfully inserts and returns the PK or when it does not insert and returns None instead. ---- You might wonder what the point of this is since you could just do it like the following: if not Tweet.select(Tweet.id).where(Tweet.user == user, Tweet.timestamp > datetime.now() - timedelta(hours=1)).exists(): Tweet.insert(...) # or Tweet.create() The main problem with this is that it requires two remote calls to the database. The secondary issue is that it has a race condition when another thread modifies the User row after the exists() check and before the Tweet.insert. (Actually, my solution also has a race condition - I think - but it is a much smaller window, by an order of magnitude, compared to using two remote calls). ----- The only other way to accomplish this right now that I've figured out is a bit ugly and doesn't compute default values. Tweet.insert_from( peewee.Select( columns=['my_tweet', user, datetime.now()] # Necessary to manually add default values like datetime.now() ).where( ~fn.EXISTS( Tweet.select().where( Tweet.user == user, Tweet.timestamp > datetime.now() - timedelta(hours=1) ) ) ), [Tweet.content, Tweet.user, Tweet.timestamp] ) # get the PK back results = list(_.execute()) if results: print(results[0]))
{ "url": "https://api.github.com/repos/coleifer/peewee/issues/2528/reactions", "total_count": 0, "+1": 0, "-1": 0, "laugh": 0, "hooray": 0, "confused": 0, "heart": 0, "rocket": 0, "eyes": 0 }
https://api.github.com/repos/coleifer/peewee/issues/2528/timeline
null
null
false
{ "url": "https://api.github.com/repos/coleifer/peewee/pulls/2528", "html_url": "https://github.com/coleifer/peewee/pull/2528", "diff_url": "https://github.com/coleifer/peewee/pull/2528.diff", "patch_url": "https://github.com/coleifer/peewee/pull/2528.patch", "merged_at": null }
https://api.github.com/repos/coleifer/peewee/issues/2527
https://api.github.com/repos/coleifer/peewee
https://api.github.com/repos/coleifer/peewee/issues/2527/labels{/name}
https://api.github.com/repos/coleifer/peewee/issues/2527/comments
https://api.github.com/repos/coleifer/peewee/issues/2527/events
https://github.com/coleifer/peewee/issues/2527
1,139,014,641
I_kwDOAA7yGM5D4_vx
2,527
Child Table's FK is set to None only if Joining to Parent and Selecting Column from Parent
{ "login": "mkmoisen", "id": 2534631, "node_id": "MDQ6VXNlcjI1MzQ2MzE=", "avatar_url": "https://avatars.githubusercontent.com/u/2534631?v=4", "gravatar_id": "", "url": "https://api.github.com/users/mkmoisen", "html_url": "https://github.com/mkmoisen", "followers_url": "https://api.github.com/users/mkmoisen/followers", "following_url": "https://api.github.com/users/mkmoisen/following{/other_user}", "gists_url": "https://api.github.com/users/mkmoisen/gists{/gist_id}", "starred_url": "https://api.github.com/users/mkmoisen/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/mkmoisen/subscriptions", "organizations_url": "https://api.github.com/users/mkmoisen/orgs", "repos_url": "https://api.github.com/users/mkmoisen/repos", "events_url": "https://api.github.com/users/mkmoisen/events{/privacy}", "received_events_url": "https://api.github.com/users/mkmoisen/received_events", "type": "User", "site_admin": false }
[]
closed
false
null
[]
null
[ "Also, the `.dicts()` and `.objects()` work fine and return the correct non-None value:\r\n\r\n.objects() is fine:\r\n\r\n```\r\nbar = list(\r\n Bar.select(\r\n Bar.foo_id,\r\n Foo.name,\r\n ).join(\r\n Foo, on=(Bar.foo_id == Foo.id)\r\n ).objects()\r\n)[0]\r\n\r\nassert bar.foo_id == foo.id\r\n```\r\n\r\n.dicts() is also fine:\r\n\r\n```\r\nbar = list(\r\n Bar.select(\r\n Bar.foo_id,\r\n Foo.name,\r\n ).join(\r\n Foo, on=(Bar.foo_id == Foo.id)\r\n ).dicts()\r\n)[0]\r\n\r\nassert bar['foo'] == foo.id\r\n```\r\n", "It seems you have missed something very fundamental, which is explained in the relationships docs: http://docs.peewee-orm.com/en/latest/peewee/relationships.html \r\n\r\nSpecifically: http://docs.peewee-orm.com/en/latest/peewee/relationships.html#selecting-from-multiple-sources\r\n\r\nAlso please do not use \"foo\" and \"bar\" as these have no context. Let's use \"User\" (for foo) and \"Tweet\" (for bar):\r\n\r\n ```python\r\n\r\n# Here is what you are trying to do:\r\nu = User.create(name='user')\r\nTweet.create(user=u, content='tweet-1')\r\nTweet.create(user=u, content='tweet-2')\r\n\r\nquery = (Tweet\r\n .select(Tweet, User)\r\n .join(User))\r\n```\r\n\r\nHere is where you went wrong:\r\n\r\n```python\r\nfor tweet in query:\r\n # Note that the related user-data is stored in tweet.user!\r\n print(tweet.user.name, tweet.content)\r\n```\r\n\r\nThe other thing is your foreign-key is named \"foo\" (or \"user\" in my example) but you are selecting `foo_id` -- no need to do that, nor should you be joining on it. Just use the fk name:\r\n\r\n```python\r\nquery = (Tweet\r\n .select(Tweet.content, User.id, User.name)\r\n .join(User, on=(Tweet.user == User.id)))\r\n\r\nfor tweet in query:\r\n print(tweet.user.id, tweet.user.name, tweet.content)\r\n```", "Hi @coleifer ,\r\n\r\nApologies if I am misinterpreting something, but my understanding is that you are suggesting to always join to the parent User table in order to access the foreign key. This is not optimal in the case when you only need to return the foreign key from the Tweet child table, because there is no need to do a relatively expensive database join in this case. \r\n\r\nIn peewee, if I don't join to the parent User table, I must access the foreign key via `tweet.user_id`. The alternative, `tweet.user.id` will result in a N+1 query.\r\n\r\nIf I do join to the parent table, I must access the foreign key via `tweet.user.id` (this will not result in N+1). The alternative, `tweet.user_id` will return None. So this `tweet.user_id` is inconsistent depending on if we join or not.\r\n\r\n-----\r\n\r\n```\r\nu = User.create(username='user') # I'm using username here which is the same in the documentation\r\nTweet.create(user=u, content='tweet-1')\r\nTweet.create(user=u, content='tweet-2')\r\n```\r\n\r\nLet's say I have a `GET /tweets/` REST API, and I simply want to select all tweets and return the FK.\r\n\r\nPlease assume the following:\r\n\r\n* My Tweet model has a lot of extra columns, and I only want to return the id, content, and user_id columns from the Tweet table.\r\n* I have no need to join to the User table because I just want to return the FK column. Joining is not necessary here since I am returning no other columns from the User table.\r\n\r\n```\r\ntweets = list(\r\n Tweet.select(\r\n Tweet.id,\r\n Tweet.content, \r\n Tweet.user,\r\n )\r\n)\r\n```\r\n\r\nHere, if I enter `tweet.user.id`, it will generate a new select, one for each tweet, which I do not want:\r\n\r\n```\r\n>>>response = [{'id': tweet.id, 'content': tweet.content, 'user_id': tweet.user.id} for tweet in tweets]\r\n\r\n('SELECT \"t1\".\"id\", \"t1\".\"username\" FROM \"user\" AS \"t1\" WHERE (\"t1\".\"id\" = %s) LIMIT %s OFFSET %s', [1, 1, 0])\r\n('SELECT \"t1\".\"id\", \"t1\".\"username\" FROM \"user\" AS \"t1\" WHERE (\"t1\".\"id\" = %s) LIMIT %s OFFSET %s', [1, 1, 0])\r\n```\r\n\r\nIf instead I enter `tweet.user_id`, it behaves as expected; no N+1 problem and I get the correct value.\r\n\r\n```\r\n>>> response = [{'id': tweet.id, 'content': tweet.content, 'user_id': tweet.user_id} for tweet in tweets]\r\n>>> # No N+1 problem\r\n```\r\n\r\nIf I understand you correctly, your advice is to join to the User table and then access it via `tweet.user.id`. However, this is not ideal since I have no need to do a join. It would be more optimal to skip the join and access via `tweet.user_id`.\r\n\r\n-----\r\n\r\nNow let's say my requirement has changed, and in my REST API I need to return the User's username. Now it is OK for me to join to the User table, whereas previously there was no need to do so.\r\n\r\nHowever, if I change my code to join to the User table, I have to remember to change the select column to `User.id` from `Tweet.user` or else the `tweet.user` (and `tweet.user_id`) will both return None.\r\n", "In your initial example you were using a JOIN, but yes if all you need is the user ID then you can access it from `tweet.user_id` without incurring any penalty.\r\n\r\n```python\r\n\r\n# No problem, 1 query.\r\nquery = Tweet.select(Tweet.id, Tweet.user, Tweet.content)\r\nprint([(row.id, row.user_id, row.content) for row in query])\r\n\r\n# No problem, still 1 query.\r\nquery = (Tweet\r\n .select(Tweet.id, Tweet.user, Tweet.content, User.id, User.username)\r\n .join(User))\r\nprint([(row.id, row.user_id, row.content) for row in query])\r\n\r\n# No problem, still 1 query.\r\nquery = (Tweet\r\n .select(Tweet.id, Tweet.user, Tweet.content, User.id, User.username)\r\n .join(User))\r\nprint([(row.id, row.user_id, row.content, row.user.username) for row in query])\r\n```\r\n\r\nAlternatively, if you want all attrs just patched onto the Tweet object (relationships not traversed):\r\n\r\n```python\r\n# No problem, still 1 query.\r\nquery = (Tweet\r\n .select(Tweet.id, Tweet.user, Tweet.content, User.username)\r\n .join(User)\r\n .objects()) # Add .objects()\r\nprint([(row.id, row.user_id, row.content, row.username) for row in query])\r\n```", "If we don't join, we can include `Tweet.user` and can then access `row.user_id`.\r\n\r\nIf we do join, we must include `User.id` in order to access `row.user_id`. Failing to include `User.id` will result in `row.user_id` being set to None. \r\n\r\nIt works when you don't join but doesn't when you join. It is inconsistent, right?\r\n\r\n-----\r\n\r\nCase 1: No Join, include Tweet.user: `row.user_id` is not None as expected:\r\n\r\n```\r\nquery = Tweet.select(Tweet.id, Tweet.user, Tweet.content)\r\nprint([(row.id, row.user_id, row.content) for row in query])\r\n```\r\n\r\nCase 2: Join, do NOT include User.id: `tweet.user_id` is now None. It is inconsistent with Case 1.\r\n\r\n```\r\nquery = (Tweet\r\n .select(Tweet.id, Tweet.user, Tweet.content, User.username)\r\n .join(User))\r\nprint([(row.id, row.user_id, row.content) for row in query])\r\n# row.user_id is None here - not consistent with Case 1\r\n```\r\n\r\nCase 3: Join, must include `User.id` in order for `tweet.user_id` to not be None:\r\n\r\n```\r\nquery = (Tweet\r\n .select(Tweet.id, Tweet.user, Tweet.content, User.id, User.username)\r\n .join(User))\r\nprint([(row.id, row.user_id, row.content) for row in query])\r\n```\r\n\r\nDoes it make sense?", "This has to do with the way that Peewee rebuilds the model graph. I may take a look at changing it but I don't really consider it a big deal as the workarounds are quite simple." ]
"2022-02-15T17:42:32"
"2022-02-18T19:20:40"
"2022-02-16T17:57:32"
NONE
null
A child table's foreign key is set to None when you do both of the following: 1) join it to the parent table 2) and when you select a non-pk column from the parent table (as opposed to the entire parent table or selecting just the pk column) If you join to the parent table but select no column from the parent table, the child model's foreign key is set to the correct value. Here is the setup: ``` from peewee import PostgresqlDatabase, Model, CharField, ForeignKeyField import logging logger = logging.getLogger('peewee') logger.addHandler(logging.StreamHandler()) logger.setLevel(logging.DEBUG) db = PostgresqlDatabase('test', user='test', password='test') class BaseModel(Model): class Meta: database = db class Foo(BaseModel): name = CharField(max_length=32, null=False) class Bar(BaseModel): name = CharField(max_length=32, null=False) foo = ForeignKeyField(Foo, null=False) db.create_tables([Foo, Bar]) foo = Foo.create(name='a') bar = Bar.create(name='b', foo=foo) ``` Here is the apparent bug: ``` bar = list( Bar.select( Bar.foo_id, Foo.name, # select just 1 column from Foo ).join( Foo, on=(Bar.foo_id == Foo.id) ) )[0] assert bar.foo_id is None ``` bar.foo_id is None. It is only None if you add the `Foo.name` to the select list. If you remove `Foo.name` from the select list, the proper non-None value is returned. Edit: If you add `Foo.id` or just `Foo` to the select list, then bar.foo_id is correctly populated. Moreover if you don't add `Bar.foo_id` and just include `Foo.id` into the select, then the resulting bar.foo_id is also correctly populated The query that is being generated correctly selects `foo_id` from foo, however it is not being added to the object: ('SELECT "t1"."foo_id", "t2"."name" FROM "bar" AS "t1" INNER JOIN "foo" AS "t2" ON ("t1"."foo_id" = "t2"."id")', []) All of these other queries work as expected. The bar.foo_id is populated and not null ``` bar = list( Bar.select( Bar.foo_id ) )[0] assert bar.foo_id == foo.id bar = list( Bar.select( Bar.foo_id, ).join( Foo, on=(Bar.foo_id == Foo.id) ) )[0] ``` Edit: I noticed that if I select `Foo.id` or the entire `Foo` instead of `Foo.name`, it works as expected: bar = list( Bar.select( Bar.foo_id, Foo # selecting the entire Foo works ).join( Foo, on=(Bar.foo_id == Foo.id) ) )[0] assert bar.foo_id == foo.id bar = list( Bar.select( Bar.foo_id, Foo.id # selecting just the Foo.id also works ).join( Foo, on=(Bar.foo_id == Foo.id) ) )[0] assert bar.foo_id == foo.id ``` It even works if I just select Foo.id, not Bar.foo_id: bar = list( Bar.select( Foo.id ).join( Foo, on=(Bar.foo_id == Foo.id) ) )[0] assert bar.foo_id == foo.id
{ "url": "https://api.github.com/repos/coleifer/peewee/issues/2527/reactions", "total_count": 0, "+1": 0, "-1": 0, "laugh": 0, "hooray": 0, "confused": 0, "heart": 0, "rocket": 0, "eyes": 0 }
https://api.github.com/repos/coleifer/peewee/issues/2527/timeline
null
completed
null
null
https://api.github.com/repos/coleifer/peewee/issues/2526
https://api.github.com/repos/coleifer/peewee
https://api.github.com/repos/coleifer/peewee/issues/2526/labels{/name}
https://api.github.com/repos/coleifer/peewee/issues/2526/comments
https://api.github.com/repos/coleifer/peewee/issues/2526/events
https://github.com/coleifer/peewee/issues/2526
1,138,042,299
I_kwDOAA7yGM5D1SW7
2,526
Does using `with db:` in a context manager open the database and start a transaction?
{ "login": "mkmoisen", "id": 2534631, "node_id": "MDQ6VXNlcjI1MzQ2MzE=", "avatar_url": "https://avatars.githubusercontent.com/u/2534631?v=4", "gravatar_id": "", "url": "https://api.github.com/users/mkmoisen", "html_url": "https://github.com/mkmoisen", "followers_url": "https://api.github.com/users/mkmoisen/followers", "following_url": "https://api.github.com/users/mkmoisen/following{/other_user}", "gists_url": "https://api.github.com/users/mkmoisen/gists{/gist_id}", "starred_url": "https://api.github.com/users/mkmoisen/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/mkmoisen/subscriptions", "organizations_url": "https://api.github.com/users/mkmoisen/orgs", "repos_url": "https://api.github.com/users/mkmoisen/repos", "events_url": "https://api.github.com/users/mkmoisen/events{/privacy}", "received_events_url": "https://api.github.com/users/mkmoisen/received_events", "type": "User", "site_admin": false }
[]
closed
false
null
[]
null
[ "Correct. Doc:\r\n\r\nhttp://docs.peewee-orm.com/en/latest/peewee/api.html#Database.__enter__\r\n\r\nIf you just want to do the open/close without the tx, you can:\r\n\r\nhttp://docs.peewee-orm.com/en/latest/peewee/api.html#Database.connection_context", "Hi @coleifer , thank you. Is the following statement correct:\r\n\r\nThe following issues 3 round trips to the database:\r\n\r\n with db:\r\n Foo.create(name='bar')\r\n\r\nWhereas the following issues just 1 round trip to the database:\r\n\r\n with db.connection_context():\r\n Foo.create(name='bar')\r\n\r\n", "Not necessarily, no - depends on what database you're using. You have to establish a connection, first of all (though you can use the [pool](http://docs.peewee-orm.com/en/latest/peewee/database.html#connection-pooling) to save cost of setup/teardown). After that, both of them must send the INSERT, retrieve the new row primary-key and commit (at some point). The first example commits when the context manager exits. The second commits immediately after issuing the INSERT. So they're pretty much exactly the same - the difference is just where the commit happens.", "Hi @coleifer ,\r\n\r\nIn SQLAlchemy, we can achieve a true autocommit with one-trip to the database, not three.\r\n\r\n```\r\nconn = engine.connect().execution_options(isolation_level='AUTOCOMMIT')\r\nconn.execute(text('insert into bar values (2)'))\r\n```\r\n\r\nHere are the postgresql logs, showing only one `statement`:\r\n\r\n```\r\n2023-02-11 17:48:56.682 PST [64992] DEBUG: StartTransaction(1) name: unnamed; blockState: DEFAULT; state: INPROGRESS, xid/subid/cid: 0/1/0\r\n2023-02-11 17:48:56.683 PST [64992] LOG: statement: insert into bar values (2)\r\n2023-02-11 17:48:56.683 PST [64992] DEBUG: CommitTransaction(1) name: unnamed; blockState: STARTED; state: INPROGRESS, xid/subid/cid: 34260/1/0 (used)\r\n```\r\n\r\n\r\nWith Peewee, there does not appear to be a way to perform a true autocommit with one trip to the database.\r\n\r\n```\r\ndb.execute_sql('insert into bar values (3)')\r\n```\r\n\r\nHere are the postgresql logs, showing 3 `statement`s:\r\n\r\n```\r\n2023-02-11 17:50:27.616 PST [62684] DEBUG: StartTransaction(1) name: unnamed; blockState: DEFAULT; state: INPROGRESS, xid/subid/cid: 0/1/0\r\n2023-02-11 17:50:27.616 PST [62684] LOG: statement: BEGIN\r\n2023-02-11 17:50:27.616 PST [62684] LOG: duration: 0.129 ms\r\n2023-02-11 17:50:27.616 PST [62684] LOG: statement: insert into bar values (3)\r\n2023-02-11 17:50:27.616 PST [62684] LOG: duration: 0.141 ms\r\n2023-02-11 17:50:27.617 PST [62684] LOG: statement: COMMIT\r\n2023-02-11 17:50:27.617 PST [62684] DEBUG: CommitTransaction(1) name: unnamed; blockState: END; state: INPROGRESS, xid/subid/cid: 34261/1/1\r\n```\r\n\r\n\r\n\r\n", "Would you be open to supporting the one-trip autocommit? It should be simple, as the [DB-API](https://peps.python.org/pep-0249/#autocommit) specifies the 'autocommit' parameter. For example in psycopg2 you simply do:\r\n\r\n```\r\nconn = psycopg2.connect(...)\r\nconn.autocommit = True\r\nconn.execute('insert into bar values (1)')\r\n```\r\n\r\nThere could be an API like:\r\n\r\n with db.autocommit():\r\n db.execute_sql('insert into bar values (2)')\r\n \r\nAnd this `autocommit` could be implemented similar to your `manual_commit`, except that it adds a `autocommit = True`.\r\n \r\nI would be happy to add a PR if you think this might be useful to add.", "This is a good observation and an unfortunate knock-on effect of Peewee relying, under-the-hood, on the db-api 2.0 semantics of psycopg2. The db-api 2.0 spec creates an implicit transaction every time you query (except when disabled by setting the isolation level to autocommit), only committing under certain conditions. This is obnoxious, so Peewee provides autocommit-*like* semantics on top of the db-api 2.0 stuff.\r\n\r\nCurrently, setting the isolation level to autocommit can be done like this:\r\n\r\n```\r\nfrom psycopg2 import extensions\r\n\r\ndb = PostgresqlDatabase(..., isolation_level=extensions.ISOLATION_LEVEL_AUTOCOMMIT)\r\n```\r\n\r\nThe database will now run in autocommit-mode for \"top-level\" queries, but the behavior is not intuitive because Peewee still assumes psycopg2 is following the \"db-api rules\" -- these imply we still need to issue commits for all top-level queries to simulate autocommit.\r\n\r\nIn order to get \"true\" autocommit with psycopg2, while retaining support for the `atomic()` / etc transaction-management controls, it is necessary to implement explicit `begin()` / `commit()` / `rollback()` to provide \"autocommit-aware\" versions of these methods.\r\n\r\nIt may be worth investigating switching our psycopg2 transaction management to being fully managed by Peewee, as we currently do (in-part) for sqlite. I've got an experimental patch for this here if you want to try it out: 69678447d843939721ac9f2a8e0179841349858e - it treats psycopg2 (and sqlite) as being in autocommit-mode.\r\n\r\nThere may be some obscure bugs for users who were coloring outside the lines w/psycopg2 and Peewee to accomplish similar things, so this would likely be a big change even if the \"typical\" uses wouldn't be affected. I'll probably need to switch the default `execute_sql()` stuff back to assuming db-api, so as not to screw things up for any users of 3rd-party drivers... Otherwise, I think the changes are OK.\r\n\r\nThe implication of this would be, then, that the following code would not (explicitly) begin or commit at any point and each query would run the same as if you had run it in `psql`, that is, in autocommit-mode.\r\n\r\n```\r\ndb = PostgresqlDatabase('my_db')\r\nclass MyModel(db.Model):\r\n value = IntegerField()\r\ndb.create_tables([MyModel])\r\nMyModel.create(value=1)\r\nassert len(MyModel) == 1\r\n```\r\n\r\nWhile the decorators and everything else continue to work as well, e.g.:\r\n\r\n```\r\nwith db.atomic() as txn:\r\n MyModel.create(value=2)\r\n txn.rollback()\r\nassert len(MyModel) == 1\r\n```", "Just a note - I did not observe any meaningful timing differences when running the test suite between the previous behavior and the new behavior. I've added some additional changes to switch our pymysql/mysql-connector to autocommit as well: cc730660bb4aec06eb97d18be258897e310a02b6" ]
"2022-02-15T01:03:44"
"2023-02-12T05:01:23"
"2022-02-15T12:52:59"
NONE
null
Not a bug, just question. The `Database` class has the following code: ``` def __enter__(self): if self.is_closed(): self.connect() ctx = self.atomic() self._state.ctx.append(ctx) ctx.__enter__() return self def __exit__(self, exc_type, exc_val, exc_tb): ctx = self._state.ctx.pop() try: ctx.__exit__(exc_type, exc_val, exc_tb) finally: if not self._state.ctx: self.close() ``` Am I correct that this means the following: with db: foo = Foo.create(name='bar') baz = Bar.create(foo=foo) Will open a connection, open a transaction, perform the inserts, commit the transaction, and close the connection? ---- This is the behavior that I am looking for most of the time. However I suppose it would be nice on occasion to to have the autocommit feature work, in order to save 2 calls to the database (the begin, and the commit): with db: foo = Foo.create(name='bar') Here, I just want to 1) open a connection, 2) auto-commit a a Foo in a single trip to the database and 3) close the connection, instead of the two additional calls to the database in order to open and close a transaction. Is there a way to accomplish this? For example this might be a nice syntax: with db(autocommit=True): foo = Foo.create(name='bar')
{ "url": "https://api.github.com/repos/coleifer/peewee/issues/2526/reactions", "total_count": 0, "+1": 0, "-1": 0, "laugh": 0, "hooray": 0, "confused": 0, "heart": 0, "rocket": 0, "eyes": 0 }
https://api.github.com/repos/coleifer/peewee/issues/2526/timeline
null
completed
null
null
https://api.github.com/repos/coleifer/peewee/issues/2525
https://api.github.com/repos/coleifer/peewee
https://api.github.com/repos/coleifer/peewee/issues/2525/labels{/name}
https://api.github.com/repos/coleifer/peewee/issues/2525/comments
https://api.github.com/repos/coleifer/peewee/issues/2525/events
https://github.com/coleifer/peewee/issues/2525
1,135,609,272
I_kwDOAA7yGM5DsAW4
2,525
RecursionError: maximum recursion depth exceeded while calling a Python object
{ "login": "tekumara", "id": 125105, "node_id": "MDQ6VXNlcjEyNTEwNQ==", "avatar_url": "https://avatars.githubusercontent.com/u/125105?v=4", "gravatar_id": "", "url": "https://api.github.com/users/tekumara", "html_url": "https://github.com/tekumara", "followers_url": "https://api.github.com/users/tekumara/followers", "following_url": "https://api.github.com/users/tekumara/following{/other_user}", "gists_url": "https://api.github.com/users/tekumara/gists{/gist_id}", "starred_url": "https://api.github.com/users/tekumara/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/tekumara/subscriptions", "organizations_url": "https://api.github.com/users/tekumara/orgs", "repos_url": "https://api.github.com/users/tekumara/repos", "events_url": "https://api.github.com/users/tekumara/events{/privacy}", "received_events_url": "https://api.github.com/users/tekumara/received_events", "type": "User", "site_admin": false }
[]
closed
false
null
[]
null
[ "Can you please share the schema (which can be dumped from the sqlite3 utility)?\r\n\r\n```\r\necho \".schema\" | sqlite3 my_db.db > schema.sql\r\n```\r\n\r\nI didn't believe it was possible to have circular foreign-key dependencies with Sqlite, so I'm not sure how to replicate this.", "```\r\nCREATE TABLE flow_run_state (\r\n\tid CHAR(36) NOT NULL,\r\n\tflow_run_id CHAR(36) NOT NULL,\r\n\tCONSTRAINT pk_flow_run_state PRIMARY KEY (id),\r\n\tCONSTRAINT fk_flow_run_state__flow_run_id__flow_run FOREIGN KEY(flow_run_id) REFERENCES flow_run (id) ON DELETE cascade\r\n);\r\n\r\nCREATE TABLE flow_run (\r\n\tid CHAR(36) NOT NULL,\r\n\tstate_id CHAR(36) NOT NULL,\r\n\tCONSTRAINT pk_flow_run PRIMARY KEY (id),\r\n\tCONSTRAINT fk_flow_run__state_id__flow_run_state FOREIGN KEY(state_id) REFERENCES flow_run_state (id) ON DELETE SET NULL\r\n);\r\n```", "Is that even a valid schema in Sqlite? I suppose it probably works if you disable foreign-key validation (pragma foreign_keys=0) but if foreign-keys are enabled I was unable to insert into either table. Furthermore you have an ON DELETE SET NULL instruction on a non-nullable column. What is the provenance of this schema? Seems broken in several ways, to be honest.\r\n\r\nThank you for providing some sql to replicate the issue, nonetheless.", "The code will now drop a warning if it encounters a circular dependency, but should proceed and generate the correct(ish) code (excluding issues with the validity of the schema overall).", "Thanks @coleifer!\r\n\r\nThe schema above is a minimal example (irrelevant fields are removed) I derived from the Prefect orion database, see [here](https://github.com/PrefectHQ/prefect/blob/7562a89/src/prefect/orion/database/orm_models.py#L396)", "Yeah, I figured it was something like that. There's never a good reason to be using a cyclical foreign-key, but it does happen so we might as well support it.", "There's a new peewee (3.14.9) on pypi now that contains the fix.", "Fantastic thank you for the fast fix @coleifer I can confirm it works! 🙌 " ]
"2022-02-13T10:22:15"
"2022-02-16T01:46:06"
"2022-02-14T12:26:36"
NONE
null
When two tables have foreign keys that reference each other: ``` Traceback (most recent call last): File "/Users/tekumara/.local/bin/sqlite_web", line 8, in <module> sys.exit(main()) File "/Users/tekumara/.local/pipx/venvs/sqlite-web/lib/python3.7/site-packages/sqlite_web/sqlite_web.py", line 841, in main initialize_app(args[0], options.read_only, password, options.url_prefix) File "/Users/tekumara/.local/pipx/venvs/sqlite-web/lib/python3.7/site-packages/sqlite_web/sqlite_web.py", line 812, in initialize_app dataset = SqliteDataSet('sqlite:///%s' % filename, bare_fields=True) File "/Users/tekumara/.local/pipx/venvs/sqlite-web/lib/python3.7/site-packages/playhouse/dataset.py", line 48, in __init__ **kwargs) File "/Users/tekumara/.local/pipx/venvs/sqlite-web/lib/python3.7/site-packages/playhouse/reflection.py", line 764, in generate_models _create_model(table, models) File "/Users/tekumara/.local/pipx/venvs/sqlite-web/lib/python3.7/site-packages/playhouse/reflection.py", line 688, in _create_model _create_model(dest, models) File "/Users/tekumara/.local/pipx/venvs/sqlite-web/lib/python3.7/site-packages/playhouse/reflection.py", line 688, in _create_model _create_model(dest, models) File "/Users/tekumara/.local/pipx/venvs/sqlite-web/lib/python3.7/site-packages/playhouse/reflection.py", line 688, in _create_model _create_model(dest, models) [Previous line repeated 989 more times] File "/Users/tekumara/.local/pipx/venvs/sqlite-web/lib/python3.7/site-packages/playhouse/reflection.py", line 684, in _create_model for foreign_key in database.foreign_keys[table]: RecursionError: maximum recursion depth exceeded while calling a Python object ``` peewee 3.14.8
{ "url": "https://api.github.com/repos/coleifer/peewee/issues/2525/reactions", "total_count": 0, "+1": 0, "-1": 0, "laugh": 0, "hooray": 0, "confused": 0, "heart": 0, "rocket": 0, "eyes": 0 }
https://api.github.com/repos/coleifer/peewee/issues/2525/timeline
null
completed
null
null
https://api.github.com/repos/coleifer/peewee/issues/2524
https://api.github.com/repos/coleifer/peewee
https://api.github.com/repos/coleifer/peewee/issues/2524/labels{/name}
https://api.github.com/repos/coleifer/peewee/issues/2524/comments
https://api.github.com/repos/coleifer/peewee/issues/2524/events
https://github.com/coleifer/peewee/issues/2524
1,128,316,262
I_kwDOAA7yGM5DQL1m
2,524
Default rule is not being applied in SQL
{ "login": "AnitaErnszt", "id": 56001200, "node_id": "MDQ6VXNlcjU2MDAxMjAw", "avatar_url": "https://avatars.githubusercontent.com/u/56001200?v=4", "gravatar_id": "", "url": "https://api.github.com/users/AnitaErnszt", "html_url": "https://github.com/AnitaErnszt", "followers_url": "https://api.github.com/users/AnitaErnszt/followers", "following_url": "https://api.github.com/users/AnitaErnszt/following{/other_user}", "gists_url": "https://api.github.com/users/AnitaErnszt/gists{/gist_id}", "starred_url": "https://api.github.com/users/AnitaErnszt/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/AnitaErnszt/subscriptions", "organizations_url": "https://api.github.com/users/AnitaErnszt/orgs", "repos_url": "https://api.github.com/users/AnitaErnszt/repos", "events_url": "https://api.github.com/users/AnitaErnszt/events{/privacy}", "received_events_url": "https://api.github.com/users/AnitaErnszt/received_events", "type": "User", "site_admin": false }
[]
closed
false
null
[]
null
[ ">I need to make sure these default rules are also applied in SQL.\r\n\r\nThat's done by adding an explicit constraint:\r\n\r\n```python\r\ndefault_0 = IntegerField(constraints=[SQL('default 0')])\r\n```\r\n\r\nPlease consult the docs. I don't write them for fun.\r\n\r\nhttp://docs.peewee-orm.com/en/latest/peewee/models.html#default-field-values" ]
"2022-02-09T10:04:11"
"2022-02-09T14:17:00"
"2022-02-09T14:17:00"
NONE
null
When creating new table the default constraints are not applied in SQL. Example: ``` class Test(BaseModel): not_nullable = CharField() unique = CharField(null=True, unique=True) default_true = BooleanField(default=True) default_0 = IntegerField(default=0) ``` If I run print_table_sql(Test) I get below, which is seems to be the SQL statement executed. ``` class Test(BaseModel): not_nullable = CharField() unique = CharField(null=True, unique=True) default_true = BooleanField(default=True) default_0 = IntegerField(default=0) ``` I need to make sure these default rules are also applied in SQL. Is there something I'm missing? If there's no straightforward way of doing this what's the best way to get the default values out of the models? Edit: Managed to get the defaults using below code. Is there a better way to achieve the same? ``` for model in models: for name, field in model._meta.__dict__["fields"].items(): print(field.default) ```
{ "url": "https://api.github.com/repos/coleifer/peewee/issues/2524/reactions", "total_count": 0, "+1": 0, "-1": 0, "laugh": 0, "hooray": 0, "confused": 0, "heart": 0, "rocket": 0, "eyes": 0 }
https://api.github.com/repos/coleifer/peewee/issues/2524/timeline
null
completed
null
null
https://api.github.com/repos/coleifer/peewee/issues/2523
https://api.github.com/repos/coleifer/peewee
https://api.github.com/repos/coleifer/peewee/issues/2523/labels{/name}
https://api.github.com/repos/coleifer/peewee/issues/2523/comments
https://api.github.com/repos/coleifer/peewee/issues/2523/events
https://github.com/coleifer/peewee/issues/2523
1,124,194,538
I_kwDOAA7yGM5DAdjq
2,523
Transaction not working with migrate
{ "login": "BobBDE", "id": 16068649, "node_id": "MDQ6VXNlcjE2MDY4NjQ5", "avatar_url": "https://avatars.githubusercontent.com/u/16068649?v=4", "gravatar_id": "", "url": "https://api.github.com/users/BobBDE", "html_url": "https://github.com/BobBDE", "followers_url": "https://api.github.com/users/BobBDE/followers", "following_url": "https://api.github.com/users/BobBDE/following{/other_user}", "gists_url": "https://api.github.com/users/BobBDE/gists{/gist_id}", "starred_url": "https://api.github.com/users/BobBDE/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/BobBDE/subscriptions", "organizations_url": "https://api.github.com/users/BobBDE/orgs", "repos_url": "https://api.github.com/users/BobBDE/repos", "events_url": "https://api.github.com/users/BobBDE/events{/privacy}", "received_events_url": "https://api.github.com/users/BobBDE/received_events", "type": "User", "site_admin": false }
[]
closed
false
null
[]
null
[ "Are you using MySQL? It's quite possible your database does not support transaction DDL.", "Transactions are working fine with the migrator generally, I assume this is down to your database not supporting it:\r\n\r\n```python\r\nclass Reg(Model):\r\n key = TextField()\r\n class Meta:\r\n database = db\r\n\r\ndb.drop_tables([Reg])\r\ndb.create_tables([Reg])\r\n\r\nmigrator = SqliteMigrator(db)\r\nwith db.atomic() as txn:\r\n migrate(migrator.add_column('reg', 'new_col', TextField(default='')))\r\n\r\n print([x.name for x in db.get_columns('reg')])\r\n txn.rollback()\r\n\r\nprint([x.name for x in db.get_columns('reg')])\r\ndb.drop_tables([Reg])\r\n```\r\n\r\nThis correctly prints:\r\n\r\n```\r\n['id', 'key', 'new_col']\r\n['id', 'key']\r\n```", "Indeed, mysql doesn't support rollback for DDL, I didn't know that. \r\n\r\nIt wasn't a peewee problem, sorry for the bothering\r\n\r\nThank you for your answer :) " ]
"2022-02-04T13:16:52"
"2022-02-08T13:10:30"
"2022-02-04T14:28:51"
NONE
null
Hello, I have a problem with the peewee migration. I can't make transactions work with the migrate. It is always committed, I can't rollback. It should be possible as the documentation says in the warning section here: https://docs.peewee-orm.com/en/latest/peewee/playhouse.html#example-usage Here is an exemple code where the rollback does nothing and the alter table is commit. ```migrator = MySQLMigrator(db) with db.atomic() as txn: migrate(migrator.add_column("table_name", 'new_column', CharField(default=''))) # this should rollback the migrate txn.rollback() ``` When I reach the ```txn.rollback()``` the action is already committed and I can see the new column in my table. The rollback does nothing. Is there something I do wrong ? I do use transaction in other senario like basic CRUD operation and thoses works as expected. I'm using peewee v3.14.8
{ "url": "https://api.github.com/repos/coleifer/peewee/issues/2523/reactions", "total_count": 0, "+1": 0, "-1": 0, "laugh": 0, "hooray": 0, "confused": 0, "heart": 0, "rocket": 0, "eyes": 0 }
https://api.github.com/repos/coleifer/peewee/issues/2523/timeline
null
completed
null
null
https://api.github.com/repos/coleifer/peewee/issues/2522
https://api.github.com/repos/coleifer/peewee
https://api.github.com/repos/coleifer/peewee/issues/2522/labels{/name}
https://api.github.com/repos/coleifer/peewee/issues/2522/comments
https://api.github.com/repos/coleifer/peewee/issues/2522/events
https://github.com/coleifer/peewee/issues/2522
1,122,956,949
I_kwDOAA7yGM5C7vaV
2,522
Temporary Database in SQLite
{ "login": "RAbraham", "id": 214189, "node_id": "MDQ6VXNlcjIxNDE4OQ==", "avatar_url": "https://avatars.githubusercontent.com/u/214189?v=4", "gravatar_id": "", "url": "https://api.github.com/users/RAbraham", "html_url": "https://github.com/RAbraham", "followers_url": "https://api.github.com/users/RAbraham/followers", "following_url": "https://api.github.com/users/RAbraham/following{/other_user}", "gists_url": "https://api.github.com/users/RAbraham/gists{/gist_id}", "starred_url": "https://api.github.com/users/RAbraham/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/RAbraham/subscriptions", "organizations_url": "https://api.github.com/users/RAbraham/orgs", "repos_url": "https://api.github.com/users/RAbraham/repos", "events_url": "https://api.github.com/users/RAbraham/events{/privacy}", "received_events_url": "https://api.github.com/users/RAbraham/received_events", "type": "User", "site_admin": false }
[]
closed
false
null
[]
null
[ "Peewee has excellent documentation, here:\r\n\r\nhttp://docs.peewee-orm.com/en/latest/index.html\r\n\r\nI suggest searching that for the string ':memory:', for example. ", "`SqliteDatabase(':memory:')`", "Hi,\r\nThanks for your quick response.\r\nI think what I want may not be satisfied by the ':memory' config value. I'd like a temporary table which is slightly different and a different option than an `in memory` database which I think will be created by `SqliteDatabase(':memory:')`\r\n\r\nFrom the above sqlite documentation:\r\n\r\n> The sole difference is that a \":memory:\" database must remain in memory at all times whereas parts of a temporary database might be flushed to disk if the database becomes large or if SQLite comes under memory pressure.\r\n\r\nTherefore, there are different options in sqlite\r\n- For a pure in-memory database, it's ` sqlite3.connect(\":memory:\")` which is what `SqliteDatabase(':memory:')` is a wrapper for?\r\n- For a temporary database, it's `sqlite3.connect(\"\")`, unless `SqliteDatabase(':memory:')` creates a temporary table and not an in memory table? I did read the documentation a bit before I posted. so if I have missed this part, I apologize.", "I was not aware of this usage. In that case I'd recommend just using Python's tempfile facilities to initialize it with a named temp file, or explicitly mark the database as not being deferred:\r\n\r\n```python\r\ndb = SqliteDatabase('')\r\ndb.deferred = False\r\n```", "I'll try that. Thank you very much. " ]
"2022-02-03T11:15:15"
"2022-02-07T20:34:58"
"2022-02-03T12:21:02"
NONE
null
Hi, How do I create a temporary SQLite database[1] using `peewee`? In Python, I would normally create it like this with an empty string ```python import sqlite3 db = sqlite3.connect("") ``` [1] - Section 'Temporary Databases' at https://www.sqlite.org/inmemorydb.html
{ "url": "https://api.github.com/repos/coleifer/peewee/issues/2522/reactions", "total_count": 0, "+1": 0, "-1": 0, "laugh": 0, "hooray": 0, "confused": 0, "heart": 0, "rocket": 0, "eyes": 0 }
https://api.github.com/repos/coleifer/peewee/issues/2522/timeline
null
completed
null
null
https://api.github.com/repos/coleifer/peewee/issues/2521
https://api.github.com/repos/coleifer/peewee
https://api.github.com/repos/coleifer/peewee/issues/2521/labels{/name}
https://api.github.com/repos/coleifer/peewee/issues/2521/comments
https://api.github.com/repos/coleifer/peewee/issues/2521/events
https://github.com/coleifer/peewee/pull/2521
1,118,448,106
PR_kwDOAA7yGM4xybeb
2,521
Added optional use_column_names instead of field names in model_to_dict
{ "login": "deduble", "id": 32467847, "node_id": "MDQ6VXNlcjMyNDY3ODQ3", "avatar_url": "https://avatars.githubusercontent.com/u/32467847?v=4", "gravatar_id": "", "url": "https://api.github.com/users/deduble", "html_url": "https://github.com/deduble", "followers_url": "https://api.github.com/users/deduble/followers", "following_url": "https://api.github.com/users/deduble/following{/other_user}", "gists_url": "https://api.github.com/users/deduble/gists{/gist_id}", "starred_url": "https://api.github.com/users/deduble/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/deduble/subscriptions", "organizations_url": "https://api.github.com/users/deduble/orgs", "repos_url": "https://api.github.com/users/deduble/repos", "events_url": "https://api.github.com/users/deduble/events{/privacy}", "received_events_url": "https://api.github.com/users/deduble/received_events", "type": "User", "site_admin": false }
[]
closed
false
null
[]
null
[ "I'll pass on this, thanks." ]
"2022-01-30T07:52:37"
"2022-01-30T14:51:17"
"2022-01-30T14:51:17"
NONE
null
I am using this in model_to_dict in jobs because it makes the created python object keys consistent with the database column names when communicating through web apps. Despite column names are not case sensitive when querying, language mediums are, so it goes hand in hand with pwiz db_model.py tool. I didn't know what to do with backrefs though, hence left those lines.
{ "url": "https://api.github.com/repos/coleifer/peewee/issues/2521/reactions", "total_count": 0, "+1": 0, "-1": 0, "laugh": 0, "hooray": 0, "confused": 0, "heart": 0, "rocket": 0, "eyes": 0 }
https://api.github.com/repos/coleifer/peewee/issues/2521/timeline
null
null
false
{ "url": "https://api.github.com/repos/coleifer/peewee/pulls/2521", "html_url": "https://github.com/coleifer/peewee/pull/2521", "diff_url": "https://github.com/coleifer/peewee/pull/2521.diff", "patch_url": "https://github.com/coleifer/peewee/pull/2521.patch", "merged_at": null }
https://api.github.com/repos/coleifer/peewee/issues/2520
https://api.github.com/repos/coleifer/peewee
https://api.github.com/repos/coleifer/peewee/issues/2520/labels{/name}
https://api.github.com/repos/coleifer/peewee/issues/2520/comments
https://api.github.com/repos/coleifer/peewee/issues/2520/events
https://github.com/coleifer/peewee/issues/2520
1,116,972,546
I_kwDOAA7yGM5Ck6YC
2,520
[Question] How to select row with most recent date per user?
{ "login": "loynoir", "id": 78727408, "node_id": "MDQ6VXNlcjc4NzI3NDA4", "avatar_url": "https://avatars.githubusercontent.com/u/78727408?v=4", "gravatar_id": "", "url": "https://api.github.com/users/loynoir", "html_url": "https://github.com/loynoir", "followers_url": "https://api.github.com/users/loynoir/followers", "following_url": "https://api.github.com/users/loynoir/following{/other_user}", "gists_url": "https://api.github.com/users/loynoir/gists{/gist_id}", "starred_url": "https://api.github.com/users/loynoir/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/loynoir/subscriptions", "organizations_url": "https://api.github.com/users/loynoir/orgs", "repos_url": "https://api.github.com/users/loynoir/repos", "events_url": "https://api.github.com/users/loynoir/events{/privacy}", "received_events_url": "https://api.github.com/users/loynoir/received_events", "type": "User", "site_admin": false }
[]
closed
false
null
[]
null
[ "Post your questions on stackoverflow or irc. This is the issue tracker." ]
"2022-01-28T03:51:37"
"2022-01-28T13:50:40"
"2022-01-28T13:50:40"
NONE
null
### Question Hi, sir. What's the peewee way, to select row with most recent date per user? ### Input id | user | val -- | -- | -- 1 | jane | 11 2 | john | 21 3 | bob | 32 4 | bob | 31 5 | john | 22 ### Output id | user | val -- | -- | -- 1 | jane | 11 4 | bob | 31 5 | john | 22 <details> <summary>Prepare Code</summary> <p> ```python from peewee import SqliteDatabase, Model, TextField, IntegerField from playhouse.sqlite_ext import AutoIncrementField db = SqliteDatabase( "./foobar.db", pragmas={ "journal_mode": "wal", "cache_size": -1 * 64000, "foreign_keys": 1, "ignore_check_constraints": 0, "synchronous": 0, }, ) class Score(Model): id = AutoIncrementField() user = TextField() val = IntegerField() class Meta: database = db db.connect() db.create_tables([Score]) for [user, val] in [ ["jane", 11], ["john", 21], ["bob", 32], ["bob", 31], ["john", 22], ]: Score.create(user=user, val=val) ``` </p> </details> <details> <summary></summary> <p> Maybe keep same order as user field? id | user | val -- | -- | -- 1 | jane | 11 5 | john | 31 4 | bob | 22 </p> </details> Thanks.
{ "url": "https://api.github.com/repos/coleifer/peewee/issues/2520/reactions", "total_count": 0, "+1": 0, "-1": 0, "laugh": 0, "hooray": 0, "confused": 0, "heart": 0, "rocket": 0, "eyes": 0 }
https://api.github.com/repos/coleifer/peewee/issues/2520/timeline
null
completed
null
null