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
timestamp[s] | updated_at
timestamp[s] | closed_at
timestamp[s] | 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/2018 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/2018/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/2018/comments | https://api.github.com/repos/coleifer/peewee/issues/2018/events | https://github.com/coleifer/peewee/pull/2018 | 495,540,074 | MDExOlB1bGxSZXF1ZXN0MzE5MDY4NTcw | 2,018 | Update peewee.py | {
"login": "lvhaidong",
"id": 12761304,
"node_id": "MDQ6VXNlcjEyNzYxMzA0",
"avatar_url": "https://avatars.githubusercontent.com/u/12761304?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/lvhaidong",
"html_url": "https://github.com/lvhaidong",
"followers_url": "https://api.github.com/users/lvhaidong/followers",
"following_url": "https://api.github.com/users/lvhaidong/following{/other_user}",
"gists_url": "https://api.github.com/users/lvhaidong/gists{/gist_id}",
"starred_url": "https://api.github.com/users/lvhaidong/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/lvhaidong/subscriptions",
"organizations_url": "https://api.github.com/users/lvhaidong/orgs",
"repos_url": "https://api.github.com/users/lvhaidong/repos",
"events_url": "https://api.github.com/users/lvhaidong/events{/privacy}",
"received_events_url": "https://api.github.com/users/lvhaidong/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"Nope. That's a mysql-only thing.",
"How to set comment in the model, can be described in the database can see the details",
"It is not supported by sqlite or postgres.",
"I am use mysql, which field can be described in the database can see the details",
"Are you averse to adding dv-specific features?",
"> Are you averse to adding dv-specific features?\r\n\r\nNot at all, but they have to be added in such a way that they are compatible. This patch would break hard if a user added help_text on sqlite or postgres. That's not compatible. There are *many* examples of compatibility in peewee -- on conflict handling, window function handling, data-types, etc, etc."
] | 2019-09-19T02:31:17 | 2019-09-28T13:59:11 | 2019-09-19T03:05:29 | NONE | null | Add field comment info | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/2018/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/2018/timeline | null | null | false | {
"url": "https://api.github.com/repos/coleifer/peewee/pulls/2018",
"html_url": "https://github.com/coleifer/peewee/pull/2018",
"diff_url": "https://github.com/coleifer/peewee/pull/2018.diff",
"patch_url": "https://github.com/coleifer/peewee/pull/2018.patch",
"merged_at": null
} |
https://api.github.com/repos/coleifer/peewee/issues/2017 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/2017/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/2017/comments | https://api.github.com/repos/coleifer/peewee/issues/2017/events | https://github.com/coleifer/peewee/issues/2017 | 495,486,548 | MDU6SXNzdWU0OTU0ODY1NDg= | 2,017 | Unable to register or access Sqlite User Defined Functions | {
"login": "amandeep-r",
"id": 39491878,
"node_id": "MDQ6VXNlcjM5NDkxODc4",
"avatar_url": "https://avatars.githubusercontent.com/u/39491878?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/amandeep-r",
"html_url": "https://github.com/amandeep-r",
"followers_url": "https://api.github.com/users/amandeep-r/followers",
"following_url": "https://api.github.com/users/amandeep-r/following{/other_user}",
"gists_url": "https://api.github.com/users/amandeep-r/gists{/gist_id}",
"starred_url": "https://api.github.com/users/amandeep-r/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/amandeep-r/subscriptions",
"organizations_url": "https://api.github.com/users/amandeep-r/orgs",
"repos_url": "https://api.github.com/users/amandeep-r/repos",
"events_url": "https://api.github.com/users/amandeep-r/events{/privacy}",
"received_events_url": "https://api.github.com/users/amandeep-r/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"You need to register the functions, which is not done automatically.\r\n\r\n```python\r\nfrom playhouse.sqlite_udf import median\r\n\r\ndb = SqliteDatabase(':memory:')\r\ndb.register_aggregate(median, 'median') # Will be available on all connections.\r\n```\r\n\r\nIf you want all of the functions/aggregates,\r\n\r\n```python\r\nfrom playhouse.sqlite_udf import register_all\r\n\r\ndb = SqliteDatabase(...)\r\nregister_all(db)\r\n\r\n# Or register just particular groupings, e.g.\r\nfrom playhouse.sqlite_udf import DATE, MATH\r\nfrom playhouse.sqlite_udf import register_groups\r\n\r\nregister_groups(db, DATE, MATH)\r\n```",
"I have tried all three methods and keep getting the same traceback.\r\n\r\n```\r\nfrom peewee import *\r\nfrom database2 import Trial, Datapoint\r\nfrom datetime import datetime as dt\r\nfrom datetime import timedelta\r\nfrom playhouse.sqlite_udf import median\r\n\r\ndb = SqliteDatabase(':memory:')\r\ndb.register_aggregate(median, 'median')\r\n```\r\nI believe I had already included the register_all method in my previous code? \r\n```\r\nfrom peewee import *\r\nfrom database2 import Trial, Datapoint\r\nfrom datetime import datetime as dt\r\nfrom datetime import timedelta\r\nfrom playhouse.sqlite_udf import register_all\r\n\r\ndb = SqliteDatabase('sbir.db')\r\nregister_all(db)\r\n```\r\n\r\n```\r\nfrom peewee import *\r\nfrom database2 import Trial, Datapoint\r\nfrom datetime import datetime as dt\r\nfrom datetime import timedelta\r\nfrom playhouse.sqlite_udf import DATE, MATH\r\nfrom playhouse.sqlite_udf import register_groups\r\n\r\ndb = SqliteDatabase('sbir.db')\r\nregister_groups(db, DATE, MATH)\r\n```\r\n\r\nMy function has remained unchanged each time I ran the above changes. Do you have any other ideas?",
"Works fine for me:\r\n\r\n```python\r\n\r\nIn [1]: from peewee import * \r\n\r\nIn [2]: from playhouse.sqlite_udf import * \r\n\r\nIn [3]: db = SqliteDatabase(':memory:') \r\n\r\nIn [4]: db.register_aggregate(median, 'median') \r\n\r\nIn [5]: class Reg(Model): \r\n ...: value = IntegerField() \r\n ...: class Meta: \r\n ...: database = db \r\n ...: \r\n\r\nIn [6]: Reg.create_table() \r\n\r\nIn [7]: Reg.insert_many([(i,) for i in [1, 5, 3, 6, 4, 2, 9]]).execute() \r\nOut[7]: 7\r\n\r\nIn [8]: Reg.select(fn.median(Reg.value)).scalar() \r\nOut[8]: 4\r\n```",
"Looking at your code, are you sure that your models are bound to the same database that you are registering the aggregate on?\r\n\r\nAlso note this is covered by unit tests, and is not fundamentally broken."
] | 2019-09-18T22:36:05 | 2019-09-19T00:30:37 | 2019-09-18T23:04:53 | NONE | null | Hello, I'm trying to use the median sqlite user defined function. I cloned peewee through git and ran the command, python setup.py build_ext -i , after installing it. I verified that my environment contains squlite3 as well.
In a python terminal I am able to import playhouse._sqlite_udf and playhouse._sqlite_ext with no issue which leads me to believe the cython extensions built correctly.
Upon executing the following code, I get the error:
peewee.OperationalError: no such function: median
The code in question:
```
from peewee import *
from database2 import Trial, Datapoint
from datetime import datetime as dt
from datetime import timedelta
from playhouse.sqlite_udf import *
db = SqliteDatabase('sbir.db')
register_all(db)
def gen_aggregate(timestamp, trial_id, delta_t=20):
delta_t_timedelta = timedelta(minutes=delta_t)
time_initial = timestamp - delta_t_timedelta
time_final = timestamp
query = Datapoint.select(fn.median(Datapoint.pH).alias('pH_median')).where(
Datapoint.trial == trial_id,
Datapoint.timestamp.between(time_initial, time_final)
)
return query
results = gen_aggregate(dt.now(), 1)
print(results)
```
The same results occurs for other sqlite_udf functions but not for the normal ones (such as COUNT).
The traceback is below:
```
Traceback (most recent call last):
File "/home/aman/anaconda3/envs/sbir/lib/python3.7/site-packages/peewee-3.10.0-py3.7-linux-x86_64.egg/peewee.py", line 3002, in execute_sql
cursor.execute(sql, params or ())
sqlite3.OperationalError: no such function: median
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/aman/Code/Babylon-Farm/Babylon-Farm/code/db/db_actions2.py", line 72, in <module>
for entry in results:
File "/home/aman/anaconda3/envs/sbir/lib/python3.7/site-packages/peewee-3.10.0-py3.7-linux-x86_64.egg/peewee.py", line 6651, in __iter__
self.execute()
File "/home/aman/anaconda3/envs/sbir/lib/python3.7/site-packages/peewee-3.10.0-py3.7-linux-x86_64.egg/peewee.py", line 1809, in inner
return method(self, database, *args, **kwargs)
File "/home/aman/anaconda3/envs/sbir/lib/python3.7/site-packages/peewee-3.10.0-py3.7-linux-x86_64.egg/peewee.py", line 1880, in execute
return self._execute(database)
File "/home/aman/anaconda3/envs/sbir/lib/python3.7/site-packages/peewee-3.10.0-py3.7-linux-x86_64.egg/peewee.py", line 2051, in _execute
cursor = database.execute(self)
File "/home/aman/anaconda3/envs/sbir/lib/python3.7/site-packages/peewee-3.10.0-py3.7-linux-x86_64.egg/peewee.py", line 3015, in execute
return self.execute_sql(sql, params, commit=commit)
File "/home/aman/anaconda3/envs/sbir/lib/python3.7/site-packages/peewee-3.10.0-py3.7-linux-x86_64.egg/peewee.py", line 3009, in execute_sql
self.commit()
File "/home/aman/anaconda3/envs/sbir/lib/python3.7/site-packages/peewee-3.10.0-py3.7-linux-x86_64.egg/peewee.py", line 2780, in __exit__
reraise(new_type, new_type(*exc_args), traceback)
File "/home/aman/anaconda3/envs/sbir/lib/python3.7/site-packages/peewee-3.10.0-py3.7-linux-x86_64.egg/peewee.py", line 183, in reraise
raise value.with_traceback(tb)
File "/home/aman/anaconda3/envs/sbir/lib/python3.7/site-packages/peewee-3.10.0-py3.7-linux-x86_64.egg/peewee.py", line 3002, in execute_sql
cursor.execute(sql, params or ())
peewee.OperationalError: no such function: median
```
Please advise. | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/2017/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/2017/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/2016 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/2016/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/2016/comments | https://api.github.com/repos/coleifer/peewee/issues/2016/events | https://github.com/coleifer/peewee/issues/2016 | 495,407,889 | MDU6SXNzdWU0OTU0MDc4ODk= | 2,016 | New field type with custom sql conversion | {
"login": "tclarke",
"id": 8740,
"node_id": "MDQ6VXNlcjg3NDA=",
"avatar_url": "https://avatars.githubusercontent.com/u/8740?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/tclarke",
"html_url": "https://github.com/tclarke",
"followers_url": "https://api.github.com/users/tclarke/followers",
"following_url": "https://api.github.com/users/tclarke/following{/other_user}",
"gists_url": "https://api.github.com/users/tclarke/gists{/gist_id}",
"starred_url": "https://api.github.com/users/tclarke/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/tclarke/subscriptions",
"organizations_url": "https://api.github.com/users/tclarke/orgs",
"repos_url": "https://api.github.com/users/tclarke/repos",
"events_url": "https://api.github.com/users/tclarke/events{/privacy}",
"received_events_url": "https://api.github.com/users/tclarke/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"Bro are you high? Do you english?",
"my phone apparently autocorrected a bunch...nice way to build a community....",
"This might help: https://github.com/coleifer/peewee/blob/master/tests/fields.py#L1134-L1167",
"For those running across this, I extrapolated from the link above. The fix is:\r\n```\r\nr = Select(None, [fn.ST_X(value).alias('x'), fn.ST_Y(value).alias('y')]).first(self.model._meta.database)\r\nreturn r['x'], r['y']\r\n```",
"I would not recommend that, as it implies a query for every value. I'm not sure where or in what context you are executing this additional query.\r\n\r\nIt'd be better to, whenever selecting from this field, to do the conversion automatically. This is where the `db_value()` method comes into play, which is somewhat exemplified in the code I linked.",
"I may have a misunderstanding of what `db_value()` is doing. I thought that it converted values for storing in the database? And `python_value()` converted database values to python values? I'm doing the above in `python_value()` as the representation of the geometry column as returned by SELECT is WKB. The appropriate SELECT to get the components of the field would be something like `SELECT ST_X(bbox),ST_Y(bbox) FROM tablename;` which returns 2 entries for a single column.",
"What you're doing is super inefficient, is what I'm saying. If you run a query that returns 100 rows, you're sending off 100 *additional* queries. Nobody should do this, it's terrible advice and inefficient.\r\n\r\nAnother route is to modify your select so that you grab the values explicitly:\r\n\r\n```python\r\n\r\nquery = MyModel.select(\r\n MyModel, \r\n fn.ST_X(MyModel.bbox).alias('bbox_x'),\r\n fn.ST_Y(MyModel.bbox).alias('bbox_y'))\r\n```",
"I understand that it's inefficient, I'm trying to figure out how to make the ORM do it in a single select and automatically populate the object. The context is something like:\r\n`\r\nclass Bar(Model):\r\n id = IntegerField(primary_key=True)\r\n\r\nclass Foo(Model):\r\n bbox = BoxField() # this is the custom field with the bbox accessor\r\n bar = ForeignKey(Bar, backref=\"foo\")\r\n\r\n# ...\r\ntmp = Bar.get(id=my_bar_id)\r\njson.dumps(model_to_dict(tmp))"
] | 2019-09-18T19:16:36 | 2019-09-19T14:43:41 | 2019-09-18T19:37:44 | NONE | null | I'm using trunk and some coffee I had running with the latest 2.x from pypi is no longer working. I'm implementing a Field for postgis point geometry. My conversation function to python used
```
q=SelectQuery(self.model_type, fn.ST_X(value).alias('x'), fn.ST_Y(value).alias('y'))
r=q.first_row()
return r.x, r.y
```
I can't get your working now. Is there an equivalent? Or a better way? If prefer to have the initial select do the conversation instead of a second select query. | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/2016/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/2016/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/2015 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/2015/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/2015/comments | https://api.github.com/repos/coleifer/peewee/issues/2015/events | https://github.com/coleifer/peewee/issues/2015 | 495,264,546 | MDU6SXNzdWU0OTUyNjQ1NDY= | 2,015 | Peewee Decimal Field Max Digits | {
"login": "MatthewDLove",
"id": 52387297,
"node_id": "MDQ6VXNlcjUyMzg3Mjk3",
"avatar_url": "https://avatars.githubusercontent.com/u/52387297?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/MatthewDLove",
"html_url": "https://github.com/MatthewDLove",
"followers_url": "https://api.github.com/users/MatthewDLove/followers",
"following_url": "https://api.github.com/users/MatthewDLove/following{/other_user}",
"gists_url": "https://api.github.com/users/MatthewDLove/gists{/gist_id}",
"starred_url": "https://api.github.com/users/MatthewDLove/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/MatthewDLove/subscriptions",
"organizations_url": "https://api.github.com/users/MatthewDLove/orgs",
"repos_url": "https://api.github.com/users/MatthewDLove/repos",
"events_url": "https://api.github.com/users/MatthewDLove/events{/privacy}",
"received_events_url": "https://api.github.com/users/MatthewDLove/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"Max digits corresponds to precision\r\nDecimal places corresponds to scale\r\n\r\nI'm not clear in your example whether you're using the \",\" as a thousands-separator or a decimal separator.\r\n\r\nIf unspecified, scale defaults to 5. So your example would be equivalent to:\r\n\r\n```\r\n\"price\" NUMERIC(15, 5) NOT NULL\r\n```\r\n\r\nI have absolutely no issues with this in a simple test-case:\r\n\r\n```python\r\n\r\nclass R(Model):\r\n val = DecimalField(max_digits=15)\r\n\r\nR.create(val=Decimal('100000.000')) # val='100000.000' also works fine.\r\nr = R.get()\r\nprint(r.val) # 100000.00000\r\n```\r\n\r\nSQL for the table:\r\n\r\n```sql\r\nCREATE TABLE IF NOT EXISTS \"r\" (\r\n \"id\" SERIAL NOT NULL PRIMARY KEY,\r\n \"val\" NUMERIC(15, 5) NOT NULL)\r\n```\r\n\r\nSomething is wrong with your schema or the code you've shared, but it appears working fine for me.\r\n\r\n> crypto startup\r\n\r\nnot even once"
] | 2019-09-18T14:30:32 | 2019-09-18T16:06:19 | 2019-09-18T16:06:19 | NONE | null | Hello,
Thank you for this great ORM. I work at a crypto start-up and it's been very useful so far.
We need to store values of monetary transactions, so we implemented a table using the decimal field (underlying table Postgres):
class Order(CustomModel):
....
price = DecimalField(max_digits=15)
execution_price = DecimalField(max_digits=15, null=True)
....
However, when our tests make an order with price 100,000 (crypto is crazy), we get this error:
"numeric field overflow
DETAIL: A field with precision 10, scale 5 must round to an absolute value less than 10^5"
But max_digits 15 should set the precision to 15, correct? When I read the code I linked below, it doesn't seem like passing in this parameter is doing anything:
https://github.com/coleifer/peewee/blob/00f32293e99bc7ad90f4706bd6b46d88f200b431/peewee.py#L4491
According to this, postgres should be able to store far more than 6 digits before the decimal place:
http://www.postgresqltutorial.com/postgresql-numeric/
So is this an actual issue, or am I misreading something? I hope this is actually worth you reviewing and not a stupid mistake on my part - I see how active you are online answering questions, and I both appreciate and admire that. | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/2015/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/2015/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/2014 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/2014/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/2014/comments | https://api.github.com/repos/coleifer/peewee/issues/2014/events | https://github.com/coleifer/peewee/issues/2014 | 494,279,056 | MDU6SXNzdWU0OTQyNzkwNTY= | 2,014 | Union broken in MySQL due to parentheses problem | {
"login": "jakedt",
"id": 2183986,
"node_id": "MDQ6VXNlcjIxODM5ODY=",
"avatar_url": "https://avatars.githubusercontent.com/u/2183986?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/jakedt",
"html_url": "https://github.com/jakedt",
"followers_url": "https://api.github.com/users/jakedt/followers",
"following_url": "https://api.github.com/users/jakedt/following{/other_user}",
"gists_url": "https://api.github.com/users/jakedt/gists{/gist_id}",
"starred_url": "https://api.github.com/users/jakedt/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/jakedt/subscriptions",
"organizations_url": "https://api.github.com/users/jakedt/orgs",
"repos_url": "https://api.github.com/users/jakedt/repos",
"events_url": "https://api.github.com/users/jakedt/events{/privacy}",
"received_events_url": "https://api.github.com/users/jakedt/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"Yeah, this query is failing on MySQL but works OK for Sqlite or Postgres.\r\n\r\nFor sqlite, we have a rule to never put parentheses around the left- or right-hand side.\r\n\r\nFor postgres, we always do, since postgres handles it correctly.\r\n\r\nFor mysql, we have a rule to not put parentheses if the left- or right-hand side is itself a compound query. It appears this is overly-simplistic. I honestly don't understand how mysql decides when to handle parentheses vs choke/throw an error. I think I've hacked in a fix for now by checking if the compound query is inside an expression or function-call, and in that case to avoid using parens. If there's a better rule I can apply, I'd be eager to implement it.",
"It appears that this particular sql parsing bug has existed in MySQL for over 12 years now:\r\n\r\nhttps://bugs.mysql.com/bug.php?id=25734\r\n\r\nIt appears to be fixed in 8.0, but I'm guessing you're either on 5.x or using MariaDB.\r\n\r\nMy suggestion is that although this is somewhat fixed, to try and re-work your query.",
"MariaDB thought they fixed it for 10.4: https://jira.mariadb.org/browse/MDEV-11953\r\n\r\nBut they missed some scenarios, including using compound select queries inside an IN expression (e.g.). I've opened a ticket, so we'll see what happens: https://jira.mariadb.org/browse/MDEV-20606"
] | 2019-09-16T21:10:35 | 2019-09-17T02:40:51 | 2019-09-17T00:43:26 | NONE | null | I believe that https://github.com/coleifer/peewee/commit/36bd887ac07647c60dfebe610b34efabec675706 broke a weird query that we have. I believe that the outer level or parens are not being detected.
Work in 3.6.4
Broken in 3.10.0
Repro case:
```python
import logging
from peewee import *
from playhouse.db_url import connect
db = connect("mysql://user:password@localhost:3307/testdb")
class Person(Model):
name = CharField()
class Meta:
database = db # This model uses the "people.db" database.
if __name__ == '__main__':
logging.basicConfig(level=logging.DEBUG)
db.create_tables([Person])
for person in (Person
.select()
.where(Person.id << (Person
.select(Person.name)
.where(Person.name == "bill")
.union_all(Person
.select(Person.name)
.where(Person.name == "frank")
)
)
)
):
print(person.name)
``` | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/2014/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/2014/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/2013 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/2013/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/2013/comments | https://api.github.com/repos/coleifer/peewee/issues/2013/events | https://github.com/coleifer/peewee/issues/2013 | 493,811,566 | MDU6SXNzdWU0OTM4MTE1NjY= | 2,013 | chalice with peewee | {
"login": "jlpl1999",
"id": 47018632,
"node_id": "MDQ6VXNlcjQ3MDE4NjMy",
"avatar_url": "https://avatars.githubusercontent.com/u/47018632?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/jlpl1999",
"html_url": "https://github.com/jlpl1999",
"followers_url": "https://api.github.com/users/jlpl1999/followers",
"following_url": "https://api.github.com/users/jlpl1999/following{/other_user}",
"gists_url": "https://api.github.com/users/jlpl1999/gists{/gist_id}",
"starred_url": "https://api.github.com/users/jlpl1999/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/jlpl1999/subscriptions",
"organizations_url": "https://api.github.com/users/jlpl1999/orgs",
"repos_url": "https://api.github.com/users/jlpl1999/repos",
"events_url": "https://api.github.com/users/jlpl1999/events{/privacy}",
"received_events_url": "https://api.github.com/users/jlpl1999/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"So I took a quick look. You can't really rely on state or local memory being preserved between any two requests w/a lambda function, so I'm not sure if connection pooling makes sense in that environment (though you could try it and measure).\r\n\r\nI'd just wrap the `route()` function to add a decorator that opens and closes the db on each request.\r\n\r\n```python\r\n\r\napp = Chalice(...)\r\ndb = MySQLDatabase(...)\r\n# Or,\r\n# db = PooledMySQLDatabase(...)\r\n\r\ndef my_route(*args, **kwargs):\r\n def inner(fn):\r\n def deco(*fa, **fk):\r\n db.connect()\r\n try:\r\n return fn(*fa, **fk)\r\n finally:\r\n db.close()\r\n return app.route(*args, **kwargs)(deco)\r\n return inner\r\n\r\n@my_route('/foo/', ...)\r\ndef some_view(...):\r\n # db should be opened before this function is called\r\n # and will be closed afterwards\r\n```\r\n\r\nSomething like that -- I didn't test it, but hopefully you get the idea."
] | 2019-09-16T01:18:55 | 2019-09-16T14:21:49 | 2019-09-16T14:21:48 | NONE | null | Do you have any suggestion for chalice framework to open close connect with MySql
only at https request occurred?
thanks | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/2013/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/2013/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/2012 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/2012/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/2012/comments | https://api.github.com/repos/coleifer/peewee/issues/2012/events | https://github.com/coleifer/peewee/issues/2012 | 492,495,843 | MDU6SXNzdWU0OTI0OTU4NDM= | 2,012 | How do I install the C-extensions? | {
"login": "amjith",
"id": 49260,
"node_id": "MDQ6VXNlcjQ5MjYw",
"avatar_url": "https://avatars.githubusercontent.com/u/49260?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/amjith",
"html_url": "https://github.com/amjith",
"followers_url": "https://api.github.com/users/amjith/followers",
"following_url": "https://api.github.com/users/amjith/following{/other_user}",
"gists_url": "https://api.github.com/users/amjith/gists{/gist_id}",
"starred_url": "https://api.github.com/users/amjith/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/amjith/subscriptions",
"organizations_url": "https://api.github.com/users/amjith/orgs",
"repos_url": "https://api.github.com/users/amjith/repos",
"events_url": "https://api.github.com/users/amjith/events{/privacy}",
"received_events_url": "https://api.github.com/users/amjith/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"I don't have sqlite3.h. I'll try to get that before trying again. ",
"Yup. That was it. :man_facepalming: ",
"The `setup.py` should print an error if you run `setup.py build_ext`...looks like maybe it got swallowed by `pip`? Not sure. At any rate, glad you got it sorted."
] | 2019-09-11T22:25:12 | 2019-09-12T02:48:44 | 2019-09-11T22:33:34 | NONE | null | The installation instruction mentioned that if Ihave cython installed then installing peewee will compile the C-extensions. But I'm not able to achieve taht result.
First I installed Cython and then I pip installed peewee and tried to use the `CSqliteExtDatabase` but it is not installed.
I have copied the output from the steps below:
```
(tempenv-50a4169627007) ↪ pip freeze
Cython==0.29.13
(tempenv-50a4169627007) ↪ pip --no-cache-dir install -U peewee
Looking in indexes: https://pypi.python.org/simple
Collecting peewee
Downloading https://files.pythonhosted.org/packages/a5/80/c84b0fa212a003db91c87822fd8559fed78e214c3c8f1a97a095ee711a95/peewee-3.10.0.tar.gz (2.3MB)
|████████████████████████████████| 2.3MB 482kB/s
Building wheels for collected packages: peewee
Building wheel for peewee (setup.py) ... done
Created wheel for peewee: filename=peewee-3.10.0-cp37-none-any.whl size=119321 sha256=4871885a538c6ab3ab7d923aeec56b3018062fa9d9da8acd81264831103d5932
Stored in directory: /tmp/pip-ephem-wheel-cache-0i30f038/wheels/5c/bb/b7/365edb46082a8da5c202eb4dc86ae335e4b322e6b1d430dbc8
Successfully built peewee
Installing collected packages: peewee
Successfully installed peewee-3.10.0
(tempenv-50a4169627007) ↪ python
Python 3.7.4 (default, Jul 9 2019, 15:11:16)
[GCC 7.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import playhouse.sqlite_ext
>>> playhouse.sqlite_ext.CYTHON_SQLITE_EXTENSIONS
False
>>>
``` | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/2012/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/2012/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/2011 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/2011/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/2011/comments | https://api.github.com/repos/coleifer/peewee/issues/2011/events | https://github.com/coleifer/peewee/issues/2011 | 492,319,726 | MDU6SXNzdWU0OTIzMTk3MjY= | 2,011 | Question: how to export SQL which can be used in postgreSQL | {
"login": "trim21",
"id": 13553903,
"node_id": "MDQ6VXNlcjEzNTUzOTAz",
"avatar_url": "https://avatars.githubusercontent.com/u/13553903?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/trim21",
"html_url": "https://github.com/trim21",
"followers_url": "https://api.github.com/users/trim21/followers",
"following_url": "https://api.github.com/users/trim21/following{/other_user}",
"gists_url": "https://api.github.com/users/trim21/gists{/gist_id}",
"starred_url": "https://api.github.com/users/trim21/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/trim21/subscriptions",
"organizations_url": "https://api.github.com/users/trim21/orgs",
"repos_url": "https://api.github.com/users/trim21/repos",
"events_url": "https://api.github.com/users/trim21/events{/privacy}",
"received_events_url": "https://api.github.com/users/trim21/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"seems that driver handle (escape) parameters itself instead of execute it as parameters in postgresql. Why doing that......",
"Peewee follows the DB-API convention / interface for executing queries. The SQL query uses placeholders for values, which are then interpolated by the driver however that needs to happen. Postgres (psycopg2) implements escaping as part of the library. Sqlite, however, prepares/compiles the statement *with* the placeholders, then binds the values separately using the `sqlite3_bind_XXX` interfaces. So it's up to the driver to do the appropriate thing for the database.\r\n\r\nThis is done for:\r\n\r\n1. security. If you are binding your parameters, then you do not need to worry about sql injection attacks.\r\n2. performance. Sqlite, for example, can reuse a compiled statement with a different set of parameters, avoiding the need to compile a statement over-and-over when only the parameters have changed.",
"In fact I want to use `asyncpg` to execute my peewee query asynchronous in my asyncio web server, which send query and parameters directly to postgresql server instead of escape it by python. So it only accepts query with `$1`,`$2` as placeholder. And simply custom `Context.param` won't work in this situation.\r\n\r\nDid that mean that there is no workaround now to get Postgresql compatible SQL string by `query.sql()`, only psycopg2 compatible? \r\n\r\nWhich means I have to handle SQL string after peewee generated it, I'm also considering security issues"
] | 2019-09-11T15:45:00 | 2019-09-11T16:57:43 | 2019-09-11T16:34:29 | NONE | null | In using peewee to generate some SQL, but postgreSQL database use `%s` as a place holder which is not supported by postgresql server, any chance I get postgresql compatible SQL string (which use `%#` as placeholder?
Is it possible now?
If it's now supported now, any plan for it?
Thank you very much. | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/2011/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/2011/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/2010 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/2010/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/2010/comments | https://api.github.com/repos/coleifer/peewee/issues/2010/events | https://github.com/coleifer/peewee/issues/2010 | 492,063,711 | MDU6SXNzdWU0OTIwNjM3MTE= | 2,010 | OperationalError on iregexp | {
"login": "kotofey-da-powah",
"id": 33459842,
"node_id": "MDQ6VXNlcjMzNDU5ODQy",
"avatar_url": "https://avatars.githubusercontent.com/u/33459842?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/kotofey-da-powah",
"html_url": "https://github.com/kotofey-da-powah",
"followers_url": "https://api.github.com/users/kotofey-da-powah/followers",
"following_url": "https://api.github.com/users/kotofey-da-powah/following{/other_user}",
"gists_url": "https://api.github.com/users/kotofey-da-powah/gists{/gist_id}",
"starred_url": "https://api.github.com/users/kotofey-da-powah/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/kotofey-da-powah/subscriptions",
"organizations_url": "https://api.github.com/users/kotofey-da-powah/orgs",
"repos_url": "https://api.github.com/users/kotofey-da-powah/repos",
"events_url": "https://api.github.com/users/kotofey-da-powah/events{/privacy}",
"received_events_url": "https://api.github.com/users/kotofey-da-powah/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"Your database (sqlite) doesn't support IREGEXP. Just use a normal regexp with case-insensitive matches/captures."
] | 2019-09-11T07:25:25 | 2019-09-11T14:53:49 | 2019-09-11T14:53:49 | NONE | null | Have a query that works fine:
```
groups = Group.select().where((Group.codename.regexp(q)) |
(Group.study_program.regexp(q)))
```
But the 'iregexp' one is giving an sql operational error:
```
groups = Group.select().where((Group.codename.iregexp(q)) |
(Group.study_program.iregexp(q)))
```
Traceback:
```
Traceback (most recent call last):
File "/Users/kotofey/Documents/SPBUBot/vbio/handlers/longpoll.py", line 46, in run
self.bot.process_message(update['object'])
File "/Users/kotofey/Documents/SPBUBot/vbio/bot.py", line 100, in process_message
handler['function'](msg)
File "bot.py", line 43, in handle_message
group_list(user, m, keyboard)
File "bot.py", line 82, in group_list
if len(group_list) == 0:
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/peewee.py", line 1897, in __len__
self._ensure_execution()
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/peewee.py", line 1879, in _ensure_execution
self.execute()
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/peewee.py", line 1796, in inner
return method(self, database, *args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/peewee.py", line 1867, in execute
return self._execute(database)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/peewee.py", line 2038, in _execute
cursor = database.execute(self)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/peewee.py", line 2994, in execute
return self.execute_sql(sql, params, commit=commit)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/peewee.py", line 2988, in execute_sql
self.commit()
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/peewee.py", line 2759, in __exit__
reraise(new_type, new_type(*exc_args), traceback)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/peewee.py", line 183, in reraise
raise value.with_traceback(tb)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/peewee.py", line 2981, in execute_sql
cursor.execute(sql, params or ())
peewee.OperationalError: near "IREGEXP": syntax error
``` | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/2010/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/2010/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/2009 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/2009/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/2009/comments | https://api.github.com/repos/coleifer/peewee/issues/2009/events | https://github.com/coleifer/peewee/issues/2009 | 489,639,227 | MDU6SXNzdWU0ODk2MzkyMjc= | 2,009 | TimestampField uses an undocumented power of 10 | {
"login": "Sekenre",
"id": 17621700,
"node_id": "MDQ6VXNlcjE3NjIxNzAw",
"avatar_url": "https://avatars.githubusercontent.com/u/17621700?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/Sekenre",
"html_url": "https://github.com/Sekenre",
"followers_url": "https://api.github.com/users/Sekenre/followers",
"following_url": "https://api.github.com/users/Sekenre/following{/other_user}",
"gists_url": "https://api.github.com/users/Sekenre/gists{/gist_id}",
"starred_url": "https://api.github.com/users/Sekenre/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/Sekenre/subscriptions",
"organizations_url": "https://api.github.com/users/Sekenre/orgs",
"repos_url": "https://api.github.com/users/Sekenre/repos",
"events_url": "https://api.github.com/users/Sekenre/events{/privacy}",
"received_events_url": "https://api.github.com/users/Sekenre/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"Originally this was expressed as 1, 10, 100, ... 1000000. I added the option to provide it as the exponent instead, but this broke the default of 1 (turning it into 10).\r\n\r\nFixed so that 0 and 1 both resolve to seconds resolution. To get 10th of a second, one needs to supply the resolution=10, but I don't think this is likely to be an issue. People tend to either use seconds, milliseconds or microseconds."
] | 2019-09-05T09:33:14 | 2019-09-05T16:00:36 | 2019-09-05T15:59:16 | NONE | null | If I create a TimestampField(resolution=1) it will unexpectedly multiply the timestamps by 10.
This is different from the default resolution of 1 second if the resolution is set to None.
Resolution as a power (`10 ** x`) where x is in `range(7)` is undocumented and maybe a bit confusing. To resolve this in my own code I had to set `resolution=0` which will make it harder for someone to read my intent. | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/2009/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/2009/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/2008 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/2008/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/2008/comments | https://api.github.com/repos/coleifer/peewee/issues/2008/events | https://github.com/coleifer/peewee/issues/2008 | 489,437,436 | MDU6SXNzdWU0ODk0Mzc0MzY= | 2,008 | DecimalField does not work correctly | {
"login": "ccodde",
"id": 54917342,
"node_id": "MDQ6VXNlcjU0OTE3MzQy",
"avatar_url": "https://avatars.githubusercontent.com/u/54917342?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/ccodde",
"html_url": "https://github.com/ccodde",
"followers_url": "https://api.github.com/users/ccodde/followers",
"following_url": "https://api.github.com/users/ccodde/following{/other_user}",
"gists_url": "https://api.github.com/users/ccodde/gists{/gist_id}",
"starred_url": "https://api.github.com/users/ccodde/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/ccodde/subscriptions",
"organizations_url": "https://api.github.com/users/ccodde/orgs",
"repos_url": "https://api.github.com/users/ccodde/repos",
"events_url": "https://api.github.com/users/ccodde/events{/privacy}",
"received_events_url": "https://api.github.com/users/ccodde/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"Sqlite only supports a couple different data-types: https://sqlite.org/datatype3.html\r\n\r\nSqlite interprets DECIMAL fields as REAL, which is a double-precision / float64. So that is why you are losing precision. Sqlite is optimizing the storage by treating the value as a numeric quantity, but it can only implement the value as an int64 or a float64.\r\n\r\nIf you don't plan on doing any math on it ever, you could use a text column for the storage:\r\n\r\n```python\r\nclass SqliteDecimalField(DecimalField):\r\n field_type = 'TEXT'\r\n```\r\n\r\nThe above will store the value precisely, but it is stored as a string so as soon as you try to do math on it you'll run into the same types of issues as before.\r\n\r\nBasic database literacy is a good thing. I'd suggest reading the sqlite docs next time."
] | 2019-09-04T22:40:19 | 2019-09-04T23:07:50 | 2019-09-04T23:07:50 | NONE | null | When choosing a large type accuracy, the accuracy is not saved and the data is stored incorrectly.
```python
from peewee import *
from decimal import Decimal
class Test(Model):
value = DecimalField(max_digits=26, decimal_places=18)
db = SqliteDatabase(':memory:')
db.bind([Test])
Test.create_table()
Test.create(value=Decimal('12345678.123456789123456789'))
row = Test.get()
print(row.value)
# 12345678.12345679
```
Save the number 12345678.123456789123456789
When extracting data, we get 12345678.12345679 | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/2008/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/2008/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/2007 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/2007/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/2007/comments | https://api.github.com/repos/coleifer/peewee/issues/2007/events | https://github.com/coleifer/peewee/issues/2007 | 488,931,377 | MDU6SXNzdWU0ODg5MzEzNzc= | 2,007 | MySQL connection lost even autoconnect is enabled. | {
"login": "Nossiac",
"id": 6194362,
"node_id": "MDQ6VXNlcjYxOTQzNjI=",
"avatar_url": "https://avatars.githubusercontent.com/u/6194362?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/Nossiac",
"html_url": "https://github.com/Nossiac",
"followers_url": "https://api.github.com/users/Nossiac/followers",
"following_url": "https://api.github.com/users/Nossiac/following{/other_user}",
"gists_url": "https://api.github.com/users/Nossiac/gists{/gist_id}",
"starred_url": "https://api.github.com/users/Nossiac/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/Nossiac/subscriptions",
"organizations_url": "https://api.github.com/users/Nossiac/orgs",
"repos_url": "https://api.github.com/users/Nossiac/repos",
"events_url": "https://api.github.com/users/Nossiac/events{/privacy}",
"received_events_url": "https://api.github.com/users/Nossiac/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"Thanks, I haven't experimented too much with mysql-connector. There's a little helper class in `playhouse.mysql_ext`, but that's about it as most Peewee users stick with pymysql.\r\n\r\n> I changed mysql connection timeout to 10s, so it's quite easy to reproduce.\r\n\r\nYeesh, that seems extreme. What if you have a long-running calculation during a transaction, e.g. a batch process or something?\r\n\r\n> I made a dirty patch here to test self._state.conn.is_connected(). it's working, but I'm sure that's not the right cure.\r\n\r\nThis is definitely not the right place to fix it.\r\n\r\nThe `autoconnect`, `is_closed()`, etc., all refer to the *internal* connection state managed by peewee. e.g., autoconnect is enabled so that attempting to issue a query will establish a connection if one does not exist. Peewee leans on the driver to manage the actual underlying connection (the pool is slightly different, because that actually checks the \"liveness\" of connections).\r\n\r\nSo if you want automatic reconnect, I'd suggest using something like the `ReconnectMixin` from `playhouse.shortcuts`. It is designed to work with `pymysql` primarily, but could be extended for mysql-connector.\r\n\r\nThe reconnecting mixin will catch an error raised when obtaining a cursor and executing a query. It then can, depending on the error class and error message, reconnect and retry the query automatically. People use it for long-lived MySQL connections that may be closed by the server.\r\n\r\nUsage:\r\n\r\n```python\r\n\r\nclass ReconnectMySQLDatabase(ReconnectMixin, MySQLDatabase):\r\n pass\r\n\r\ndb = ReconnectMySQLDatabase(...)\r\n```",
"I was able to replicate and resolve the issue by extending the ReconnectMixin list of errors to include the error raised by mysql-connector when an idle connection is killed by the server. You should now be able to use the `ReconnectMixin` from `master` and it will handle automatic re-connection."
] | 2019-09-04T04:19:46 | 2019-09-04T15:00:12 | 2019-09-04T15:00:12 | NONE | null | Using peewee with mysql-connector.
By default, a IDLE MySQL connection will timeout after 8 hours. When timeout happens, peewee runs into an exception:
```
File "/usr/local/lib/python3.6/site-packages/mysql/connector/connection.py", line 809, in cursor
raise errors.OperationalError("MySQL Connection not available.")
peewee.OperationalError: (-1, 'MySQL Connection not available.', None)
```
I changed mysql connection timeout to 10s, so it's quite easy to reproduce.
BTW, the option `autoconnect=True` didn't work for me. In the source code I found this:
```
def cursor(self, commit=None):
if self.is_closed():
if self.autoconnect:
self.connect()
else:
raise InterfaceError('Error, database connection not opened.')
return self._state.conn.cursor()
```
When timeout happens, I get:
self.is_closed() == False
self._state.conn.is_connected() == False
It seems the low-level broken connection is not detected by peewee `self.is_closed()`.
I made a dirty patch here to test `self._state.conn.is_connected()`. it's working, but I'm sure that's not the right cure.
Hope you can take a look.
| {
"url": "https://api.github.com/repos/coleifer/peewee/issues/2007/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/2007/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/2006 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/2006/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/2006/comments | https://api.github.com/repos/coleifer/peewee/issues/2006/events | https://github.com/coleifer/peewee/issues/2006 | 488,926,033 | MDU6SXNzdWU0ODg5MjYwMzM= | 2,006 | Chalice Python framework with Peewee | {
"login": "jlpl1999",
"id": 47018632,
"node_id": "MDQ6VXNlcjQ3MDE4NjMy",
"avatar_url": "https://avatars.githubusercontent.com/u/47018632?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/jlpl1999",
"html_url": "https://github.com/jlpl1999",
"followers_url": "https://api.github.com/users/jlpl1999/followers",
"following_url": "https://api.github.com/users/jlpl1999/following{/other_user}",
"gists_url": "https://api.github.com/users/jlpl1999/gists{/gist_id}",
"starred_url": "https://api.github.com/users/jlpl1999/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/jlpl1999/subscriptions",
"organizations_url": "https://api.github.com/users/jlpl1999/orgs",
"repos_url": "https://api.github.com/users/jlpl1999/repos",
"events_url": "https://api.github.com/users/jlpl1999/events{/privacy}",
"received_events_url": "https://api.github.com/users/jlpl1999/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"This is for tracking **issues**, not \"how-do-i\" questions. Please take it to stack overflow.\r\n\r\nhttp://docs.peewee-orm.com/en/latest/peewee/contributing.html#questions"
] | 2019-09-04T03:56:05 | 2019-09-04T12:42:02 | 2019-09-04T12:42:02 | NONE | null | How do i do the before/after connection with mysql/aws RDS along with chalice serverless framework using PeeWee as ORM? thanks | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/2006/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/2006/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/2005 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/2005/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/2005/comments | https://api.github.com/repos/coleifer/peewee/issues/2005/events | https://github.com/coleifer/peewee/issues/2005 | 488,495,790 | MDU6SXNzdWU0ODg0OTU3OTA= | 2,005 | can't support 5.5.*-mariadb | {
"login": "City-Zero",
"id": 19517295,
"node_id": "MDQ6VXNlcjE5NTE3Mjk1",
"avatar_url": "https://avatars.githubusercontent.com/u/19517295?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/City-Zero",
"html_url": "https://github.com/City-Zero",
"followers_url": "https://api.github.com/users/City-Zero/followers",
"following_url": "https://api.github.com/users/City-Zero/following{/other_user}",
"gists_url": "https://api.github.com/users/City-Zero/gists{/gist_id}",
"starred_url": "https://api.github.com/users/City-Zero/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/City-Zero/subscriptions",
"organizations_url": "https://api.github.com/users/City-Zero/orgs",
"repos_url": "https://api.github.com/users/City-Zero/repos",
"events_url": "https://api.github.com/users/City-Zero/events{/privacy}",
"received_events_url": "https://api.github.com/users/City-Zero/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"That's an ancient version of mariadb, first of all. Second of all, it doesn't matter because that version is so old it doesn't support any of the features that the version-check is designed to flip."
] | 2019-09-03T09:33:45 | 2019-09-03T18:07:25 | 2019-09-03T18:07:25 | NONE | null | https://github.com/coleifer/peewee/blob/cc02d32d05acfdfa2b4d01d99f646b56b6a3c754/peewee.py#L3813 | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/2005/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/2005/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/2004 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/2004/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/2004/comments | https://api.github.com/repos/coleifer/peewee/issues/2004/events | https://github.com/coleifer/peewee/issues/2004 | 488,356,554 | MDU6SXNzdWU0ODgzNTY1NTQ= | 2,004 | DecimalField does not work correctly | {
"login": "twixmix",
"id": 54825779,
"node_id": "MDQ6VXNlcjU0ODI1Nzc5",
"avatar_url": "https://avatars.githubusercontent.com/u/54825779?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/twixmix",
"html_url": "https://github.com/twixmix",
"followers_url": "https://api.github.com/users/twixmix/followers",
"following_url": "https://api.github.com/users/twixmix/following{/other_user}",
"gists_url": "https://api.github.com/users/twixmix/gists{/gist_id}",
"starred_url": "https://api.github.com/users/twixmix/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/twixmix/subscriptions",
"organizations_url": "https://api.github.com/users/twixmix/orgs",
"repos_url": "https://api.github.com/users/twixmix/repos",
"events_url": "https://api.github.com/users/twixmix/events{/privacy}",
"received_events_url": "https://api.github.com/users/twixmix/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [] | 2019-09-03T01:53:37 | 2019-09-04T22:40:54 | 2019-09-04T22:40:54 | NONE | null | When choosing a large type accuracy, the accuracy is not saved and the data is stored incorrectly.
```python
from peewee import *
from decimal import Decimal
class Test(Model):
value = DecimalField(max_digits=26, decimal_places=18)
db = SqliteDatabase(':memory:')
db.bind([Test])
Test.create_table()
Test.create(value=Decimal('12345678.123456789123456789'))
row = Test.get()
print(row.value)
```
Save the number 12345678.123456789123456789
When extracting data, we get 12345678.12345679 | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/2004/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/2004/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/2003 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/2003/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/2003/comments | https://api.github.com/repos/coleifer/peewee/issues/2003/events | https://github.com/coleifer/peewee/issues/2003 | 488,210,935 | MDU6SXNzdWU0ODgyMTA5MzU= | 2,003 | Exception if sqlite database contains an incorrect type | {
"login": "huntfx",
"id": 10235666,
"node_id": "MDQ6VXNlcjEwMjM1NjY2",
"avatar_url": "https://avatars.githubusercontent.com/u/10235666?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/huntfx",
"html_url": "https://github.com/huntfx",
"followers_url": "https://api.github.com/users/huntfx/followers",
"following_url": "https://api.github.com/users/huntfx/following{/other_user}",
"gists_url": "https://api.github.com/users/huntfx/gists{/gist_id}",
"starred_url": "https://api.github.com/users/huntfx/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/huntfx/subscriptions",
"organizations_url": "https://api.github.com/users/huntfx/orgs",
"repos_url": "https://api.github.com/users/huntfx/repos",
"events_url": "https://api.github.com/users/huntfx/events{/privacy}",
"received_events_url": "https://api.github.com/users/huntfx/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [] | 2019-09-02T14:14:03 | 2019-09-03T00:24:12 | 2019-09-03T00:24:12 | NONE | null | This is an issue I got in your `sqlite-web` script, but it appears to be specific to `peewee` so posting here.
Due to a bug in my code, I had some text stored in an integer column. Querying with both `sqlalchemy` and [sqliteonline](https://sqliteonline.com) worked and showed the strings that were in my integer column, and from a [quick search](https://dba.stackexchange.com/questions/106364/text-string-stored-in-sqlite-integer-column) it appears this is technically valid behaviour for sqlite.
While having strings in an integer column is definitely not expected or wanted behaviour, it seems to be fully supported by other scripts. I'm not sure if there's any metadata on individual records, but even just a simple try/except looks like it'd be fine for this case.
Here's a screenshot from `sqliteonline` showing it supporting the dodgy column:

The full traceback is here:
```
Traceback (most recent call last):
File "C:\Python27\lib\site-packages\flask\app.py", line 2292, in wsgi_app
response = self.full_dispatch_request()
File "C:\Python27\lib\site-packages\flask\app.py", line 1815, in full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\Python27\lib\site-packages\flask\app.py", line 1718, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "C:\Python27\lib\site-packages\flask\app.py", line 1813, in full_dispatch_request
rv = self.dispatch_request()
File "C:\Python27\lib\site-packages\flask\app.py", line 1799, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "C:\Users\peterh\AppData\Roaming\Python\Python27\site-packages\sqlite_web\sqlite_web.py", line 213, in inner
return fn(table, *args, **kwargs)
File "C:\Users\peterh\AppData\Roaming\Python\Python27\site-packages\sqlite_web\sqlite_web.py", line 463, in table_content
total_rows=total_rows)
File "C:\Python27\lib\site-packages\flask\templating.py", line 135, in render_template
context, ctx.app)
File "C:\Python27\lib\site-packages\flask\templating.py", line 117, in _render
rv = template.render(context)
File "C:\Users\peterh\AppData\Roaming\Python\Python27\site-packages\jinja2\environment.py", line 1008, in render
return self.environment.handle_exception(exc_info, True)
File "C:\Users\peterh\AppData\Roaming\Python\Python27\site-packages\jinja2\environment.py", line 780, in handle_exception
reraise(exc_type, exc_value, tb)
File "C:\Users\peterh\AppData\Roaming\Python\Python27\site-packages\sqlite_web\templates\table_content.html", line 1, in top-level template code
{% extends "base_table.html" %}
File "C:\Users\peterh\AppData\Roaming\Python\Python27\site-packages\sqlite_web\templates\base_table.html", line 1, in top-level template code
{% extends "base_tables.html" %}
File "C:\Users\peterh\AppData\Roaming\Python\Python27\site-packages\sqlite_web\templates\base_tables.html", line 1, in top-level template code
{% extends "base.html" %}
File "C:\Users\peterh\AppData\Roaming\Python\Python27\site-packages\sqlite_web\templates\base.html", line 62, in top-level template code
{% block content %}{% endblock %}
File "C:\Users\peterh\AppData\Roaming\Python\Python27\site-packages\sqlite_web\templates\base_table.html", line 29, in block "content"
{% block inner_content %}
File "C:\Users\peterh\AppData\Roaming\Python\Python27\site-packages\sqlite_web\templates\table_content.html", line 39, in block "inner_content"
{% for row in query %}
File "C:\Users\peterh\AppData\Roaming\Python\Python27\site-packages\peewee.py", line 4097, in next
self.cursor_wrapper.iterate()
File "C:\Users\peterh\AppData\Roaming\Python\Python27\site-packages\peewee.py", line 4016, in iterate
result = self.process_row(row)
File "C:\Users\peterh\AppData\Roaming\Python\Python27\site-packages\peewee.py", line 6974, in process_row
result[attr] = converters[i](row[i])
File "C:\Users\peterh\AppData\Roaming\Python\Python27\site-packages\peewee.py", line 4263, in python_value
return value if value is None else self.adapt(value)
ValueError: invalid literal for int() with base 10: 'Manual'
``` | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/2003/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/2003/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/2002 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/2002/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/2002/comments | https://api.github.com/repos/coleifer/peewee/issues/2002/events | https://github.com/coleifer/peewee/pull/2002 | 487,513,377 | MDExOlB1bGxSZXF1ZXN0MzEyNzYzOTg0 | 2,002 | Fix bug with multiple model prefetches | {
"login": "rwrigley",
"id": 38895052,
"node_id": "MDQ6VXNlcjM4ODk1MDUy",
"avatar_url": "https://avatars.githubusercontent.com/u/38895052?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/rwrigley",
"html_url": "https://github.com/rwrigley",
"followers_url": "https://api.github.com/users/rwrigley/followers",
"following_url": "https://api.github.com/users/rwrigley/following{/other_user}",
"gists_url": "https://api.github.com/users/rwrigley/gists{/gist_id}",
"starred_url": "https://api.github.com/users/rwrigley/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/rwrigley/subscriptions",
"organizations_url": "https://api.github.com/users/rwrigley/orgs",
"repos_url": "https://api.github.com/users/rwrigley/repos",
"events_url": "https://api.github.com/users/rwrigley/events{/privacy}",
"received_events_url": "https://api.github.com/users/rwrigley/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"Thanks"
] | 2019-08-30T14:27:53 | 2019-08-31T13:51:23 | 2019-08-31T13:51:15 | CONTRIBUTOR | null | I found when calling prefetch with a model multiple times but on different rel models would result in only one of the rel models getting the instances populated and all others with empty lists. This changes seems to fix the issue. | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/2002/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/2002/timeline | null | null | false | {
"url": "https://api.github.com/repos/coleifer/peewee/pulls/2002",
"html_url": "https://github.com/coleifer/peewee/pull/2002",
"diff_url": "https://github.com/coleifer/peewee/pull/2002.diff",
"patch_url": "https://github.com/coleifer/peewee/pull/2002.patch",
"merged_at": "2019-08-31T13:51:15"
} |
https://api.github.com/repos/coleifer/peewee/issues/2001 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/2001/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/2001/comments | https://api.github.com/repos/coleifer/peewee/issues/2001/events | https://github.com/coleifer/peewee/issues/2001 | 487,383,201 | MDU6SXNzdWU0ODczODMyMDE= | 2,001 | The Document's issue - "Model.first()" exists, but the method had disappeared yet | {
"login": "linusic",
"id": 30204682,
"node_id": "MDQ6VXNlcjMwMjA0Njgy",
"avatar_url": "https://avatars.githubusercontent.com/u/30204682?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/linusic",
"html_url": "https://github.com/linusic",
"followers_url": "https://api.github.com/users/linusic/followers",
"following_url": "https://api.github.com/users/linusic/following{/other_user}",
"gists_url": "https://api.github.com/users/linusic/gists{/gist_id}",
"starred_url": "https://api.github.com/users/linusic/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/linusic/subscriptions",
"organizations_url": "https://api.github.com/users/linusic/orgs",
"repos_url": "https://api.github.com/users/linusic/repos",
"events_url": "https://api.github.com/users/linusic/events{/privacy}",
"received_events_url": "https://api.github.com/users/linusic/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"The Method is still there:\r\n\r\n def first(self, database, n=1):\r\n\r\nhttps://github.com/coleifer/peewee/blob/b51b230a45e71464d90607ccfdd40ccff4d2d3f8/peewee.py#L2049",
"thx for u response\r\nI see, I use it incorrect ,sry!\r\n\r\nI think it use likely the \"get()\" method. \r\nso i use it by mistake -> \r\n # Owner.first() # error use \r\n\r\nbut it should use correctly ->\r\n Owner.select().where(Owner.name=='Alice').first() # right use",
"Beat me to it @oz123 thanks for helping out a newcomer."
] | 2019-08-30T09:26:30 | 2019-08-31T13:28:45 | 2019-08-30T14:04:02 | NONE | null | thanks for "peewee".
I saw a small issue when I read the document .
Document version: latest
and look follow pic.

| {
"url": "https://api.github.com/repos/coleifer/peewee/issues/2001/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/2001/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/2000 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/2000/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/2000/comments | https://api.github.com/repos/coleifer/peewee/issues/2000/events | https://github.com/coleifer/peewee/issues/2000 | 486,999,046 | MDU6SXNzdWU0ODY5OTkwNDY= | 2,000 | Column casting doesn't work in 3.10.0 | {
"login": "cubez",
"id": 337158,
"node_id": "MDQ6VXNlcjMzNzE1OA==",
"avatar_url": "https://avatars.githubusercontent.com/u/337158?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/cubez",
"html_url": "https://github.com/cubez",
"followers_url": "https://api.github.com/users/cubez/followers",
"following_url": "https://api.github.com/users/cubez/following{/other_user}",
"gists_url": "https://api.github.com/users/cubez/gists{/gist_id}",
"starred_url": "https://api.github.com/users/cubez/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/cubez/subscriptions",
"organizations_url": "https://api.github.com/users/cubez/orgs",
"repos_url": "https://api.github.com/users/cubez/repos",
"events_url": "https://api.github.com/users/cubez/events{/privacy}",
"received_events_url": "https://api.github.com/users/cubez/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"I can see both sides, but I do think that I will make the logic for adapting values more permissive. What changed is that an expression now looks a little bit harder to see if the right-hand-side can be converted using the conversion implied by the left-hand field. For a cast(), however, this should be more permissive.\r\n\r\nShould be working again: 92713817185aa7decf29234fe704ba2182c10196",
"Actually, I changed my mind about how to fix this. Instead, I will look at the `_coerce` internal flag and use that to determine whether to apply the conversion.\r\n\r\n42e2b429c226590bac20770a8a10a4b4a9b0c897",
"If it works, it works. 👍 Thank you for the fast fixing."
] | 2019-08-29T14:37:56 | 2019-08-30T08:19:24 | 2019-08-29T15:10:15 | NONE | null | Up until 3.9.6 I could do this:
```python
TableName.select().where(TableName.some_int_field.cast("CHAR").contains("abc"))
```
The result would just be empty. But now in 3.10.0 I get this error:
```sh
ValueError: invalid literal for int() with base 10: '%abc%'
```
Looking through the changelog I can't really find anything that would cause this. So I don't know if this is a bug or a feature. :) | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/2000/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/2000/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1999 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1999/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1999/comments | https://api.github.com/repos/coleifer/peewee/issues/1999/events | https://github.com/coleifer/peewee/pull/1999 | 486,990,285 | MDExOlB1bGxSZXF1ZXN0MzEyMzQ0NjI4 | 1,999 | fix typo | {
"login": "rwrigley",
"id": 38895052,
"node_id": "MDQ6VXNlcjM4ODk1MDUy",
"avatar_url": "https://avatars.githubusercontent.com/u/38895052?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/rwrigley",
"html_url": "https://github.com/rwrigley",
"followers_url": "https://api.github.com/users/rwrigley/followers",
"following_url": "https://api.github.com/users/rwrigley/following{/other_user}",
"gists_url": "https://api.github.com/users/rwrigley/gists{/gist_id}",
"starred_url": "https://api.github.com/users/rwrigley/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/rwrigley/subscriptions",
"organizations_url": "https://api.github.com/users/rwrigley/orgs",
"repos_url": "https://api.github.com/users/rwrigley/repos",
"events_url": "https://api.github.com/users/rwrigley/events{/privacy}",
"received_events_url": "https://api.github.com/users/rwrigley/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"Thank you, nice catch."
] | 2019-08-29T14:23:19 | 2019-08-29T14:33:13 | 2019-08-29T14:33:07 | CONTRIBUTOR | null | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1999/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/1999/timeline | null | null | false | {
"url": "https://api.github.com/repos/coleifer/peewee/pulls/1999",
"html_url": "https://github.com/coleifer/peewee/pull/1999",
"diff_url": "https://github.com/coleifer/peewee/pull/1999.diff",
"patch_url": "https://github.com/coleifer/peewee/pull/1999.patch",
"merged_at": "2019-08-29T14:33:07"
} |
|
https://api.github.com/repos/coleifer/peewee/issues/1998 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1998/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1998/comments | https://api.github.com/repos/coleifer/peewee/issues/1998/events | https://github.com/coleifer/peewee/issues/1998 | 485,295,682 | MDU6SXNzdWU0ODUyOTU2ODI= | 1,998 | conda-forge version of 3.10.0 | {
"login": "sterlingbaldwin",
"id": 6477639,
"node_id": "MDQ6VXNlcjY0Nzc2Mzk=",
"avatar_url": "https://avatars.githubusercontent.com/u/6477639?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/sterlingbaldwin",
"html_url": "https://github.com/sterlingbaldwin",
"followers_url": "https://api.github.com/users/sterlingbaldwin/followers",
"following_url": "https://api.github.com/users/sterlingbaldwin/following{/other_user}",
"gists_url": "https://api.github.com/users/sterlingbaldwin/gists{/gist_id}",
"starred_url": "https://api.github.com/users/sterlingbaldwin/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/sterlingbaldwin/subscriptions",
"organizations_url": "https://api.github.com/users/sterlingbaldwin/orgs",
"repos_url": "https://api.github.com/users/sterlingbaldwin/repos",
"events_url": "https://api.github.com/users/sterlingbaldwin/events{/privacy}",
"received_events_url": "https://api.github.com/users/sterlingbaldwin/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"get out of here with this crap, i don't have anything to do with whatever that is.",
"Ah, I just assumed you were the maintainer for the conda-forge feedstock, but it looks like its someone else. Peewee has +100k installs through conda-forge https://github.com/conda-forge/peewee-feedstock",
"Holy smokes! Never heard of it before."
] | 2019-08-26T15:25:29 | 2019-08-26T23:49:24 | 2019-08-26T16:28:53 | NONE | null | The latest version published to conda-forge is 3.9.2. It would be nice to have 3.10.0. | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1998/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/1998/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1997 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1997/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1997/comments | https://api.github.com/repos/coleifer/peewee/issues/1997/events | https://github.com/coleifer/peewee/issues/1997 | 484,972,835 | MDU6SXNzdWU0ODQ5NzI4MzU= | 1,997 | Question - Is there a way not to create a base model table in the database? | {
"login": "dsmurrell",
"id": 4035854,
"node_id": "MDQ6VXNlcjQwMzU4NTQ=",
"avatar_url": "https://avatars.githubusercontent.com/u/4035854?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/dsmurrell",
"html_url": "https://github.com/dsmurrell",
"followers_url": "https://api.github.com/users/dsmurrell/followers",
"following_url": "https://api.github.com/users/dsmurrell/following{/other_user}",
"gists_url": "https://api.github.com/users/dsmurrell/gists{/gist_id}",
"starred_url": "https://api.github.com/users/dsmurrell/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/dsmurrell/subscriptions",
"organizations_url": "https://api.github.com/users/dsmurrell/orgs",
"repos_url": "https://api.github.com/users/dsmurrell/repos",
"events_url": "https://api.github.com/users/dsmurrell/events{/privacy}",
"received_events_url": "https://api.github.com/users/dsmurrell/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"The base model *is not* created... you have to explicitly tell peewee which tables to create. It doesn't matter the inheritance chain -- each model class is just a single table.",
"Thanks! \r\n\r\nI've been using peeweedbevolve for too long which creates all by default. Just found the answer here for my use case.\r\n\r\nhttps://github.com/keredson/peewee-db-evolve/issues/24#issuecomment-360875831"
] | 2019-08-25T20:32:35 | 2019-08-25T20:55:47 | 2019-08-25T20:45:21 | NONE | null | I did scan the docs briefly, but nothing obvious popped out at me. I want to have the following configuration but not have the base table be created in the database as it's never used by me. Is there a way to do this?
```
class BaseModel(Model):
class Meta:
database = db
class User(BaseModel):
username = CharField(unique=True)
``` | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1997/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/1997/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1996 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1996/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1996/comments | https://api.github.com/repos/coleifer/peewee/issues/1996/events | https://github.com/coleifer/peewee/issues/1996 | 484,708,444 | MDU6SXNzdWU0ODQ3MDg0NDQ= | 1,996 | Support for Triggers and LISTEN/Notify | {
"login": "iguanaus",
"id": 5752769,
"node_id": "MDQ6VXNlcjU3NTI3Njk=",
"avatar_url": "https://avatars.githubusercontent.com/u/5752769?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/iguanaus",
"html_url": "https://github.com/iguanaus",
"followers_url": "https://api.github.com/users/iguanaus/followers",
"following_url": "https://api.github.com/users/iguanaus/following{/other_user}",
"gists_url": "https://api.github.com/users/iguanaus/gists{/gist_id}",
"starred_url": "https://api.github.com/users/iguanaus/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/iguanaus/subscriptions",
"organizations_url": "https://api.github.com/users/iguanaus/orgs",
"repos_url": "https://api.github.com/users/iguanaus/repos",
"events_url": "https://api.github.com/users/iguanaus/events{/privacy}",
"received_events_url": "https://api.github.com/users/iguanaus/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"There are huge differences between sqlite/mysql/postgres for writing triggers. If you need a trigger, just create it after your call to `db.create_tables(...)`:\r\n\r\n```python\r\ndb.create_tables([MyModel, ...])\r\ndb.execute_sql('create trigger ...')\r\n```\r\n\r\nFor LISTEN/NOTIFY, again, I'm not sure how Peewee would improve on this much as it's pretty straightforward. Just use `db.execute_sql('listen channel_name')` to subscribe, and then for notify:\r\n\r\n```python\r\npayload = {'now': time.time(), 'data': 'something'}\r\ndb.execute_sql('notify channel_name, %s', (json.dumps(payload),))\r\n```\r\n\r\nThe psycopg2 docs contain an example of polling for updates, presumably you'd do this in a separate thread or use a coroutine library."
] | 2019-08-23T20:55:22 | 2019-08-24T20:42:52 | 2019-08-24T20:42:52 | NONE | null | Great work on the library, it has been very flexible and quick to work with.
We are needing to notify a service whenever a table is updated. Our backend database is Postgres. Listen/Notify seems to optimally fit out needs. Ideally we need a way to trigger or notify on creation/updates, and then subscribe with polling to get responses.
## Pub implementation
On the pub side, there are two ways to implement this:
- A trigger on the table (similar to that described [here](https://stackoverflow.com/questions/5412474/using-pg-notify-in-postgresql-trigger-function))
- Bundling each insert/update in a transaction, and putting a notify at the end of it.
From a simplicity perspective, I would rather put a trigger in the table for the pub, then have a polling feature setup for subscribe. Does PeeWee or any integrated library via playhouse support triggers and adding them? I found a hack [implementation](https://stackoverflow.com/questions/34142550/sqlite-triggers-datetime-defaults-in-sql-ddl-using-peewee-in-python), is this what you would recommend if we wanted to add a trigger to the schema? This seems like a sensible addition at some point considering the power of pub/sub in postgres.
The other down-and-dirty implementation of this is to override the insert/update methods in the model and just turn them into transactions with a NOTIFY call at the end (we already do this for some things, such as insert_or_update where we query if the record exist and if not create, or if so update. Note that we do not use autoincrementing primary keys as we regularly create more than 2 billion records; we use uuid, so we lose a bit of your methods).
## Sub implementation
A sample implementation of this can be seen quickly on the psycopg website [here](http://initd.org/psycopg/docs/advanced.html#asynchronous-notifications). Is such a thing possible with PeeWee? How would you recommend building this?
Thank you a million, happy to do a MR to support the above if useful.
| {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1996/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/1996/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1995 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1995/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1995/comments | https://api.github.com/repos/coleifer/peewee/issues/1995/events | https://github.com/coleifer/peewee/issues/1995 | 483,770,343 | MDU6SXNzdWU0ODM3NzAzNDM= | 1,995 | Mysql gone away with peewee as second database in Django | {
"login": "srugano",
"id": 4678996,
"node_id": "MDQ6VXNlcjQ2Nzg5OTY=",
"avatar_url": "https://avatars.githubusercontent.com/u/4678996?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/srugano",
"html_url": "https://github.com/srugano",
"followers_url": "https://api.github.com/users/srugano/followers",
"following_url": "https://api.github.com/users/srugano/following{/other_user}",
"gists_url": "https://api.github.com/users/srugano/gists{/gist_id}",
"starred_url": "https://api.github.com/users/srugano/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/srugano/subscriptions",
"organizations_url": "https://api.github.com/users/srugano/orgs",
"repos_url": "https://api.github.com/users/srugano/repos",
"events_url": "https://api.github.com/users/srugano/events{/privacy}",
"received_events_url": "https://api.github.com/users/srugano/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"> The suggested method of solving this in Django is trough the usage of a middleware but this assume that in that case peewee related db is the main one, and has resulted in errors like this one:\r\n\r\nThat has nothing to do with \"solving\" your connection timing out and being closed. That middleware is simply to ensure you are cleanly opening and releasing connections when Django views are accessed... as, presumably, you are accessing the database during the views.\r\n\r\nThe error you are receiving, \"object() takes no parameters\", is related to the API for middlewares changing in Django 2.x. https://docs.djangoproject.com/en/2.2/topics/http/middleware/\r\n\r\nYou'll need to implement this:\r\n\r\n```python\r\nclass SimpleMiddleware:\r\n def __init__(self, get_response):\r\n self.get_response = get_response\r\n # One-time configuration and initialization.\r\n\r\n def __call__(self, request):\r\n database.connect()\r\n\r\n response = self.get_response(request)\r\n\r\n if not database.is_closed(): database.close()\r\n return response\r\n```\r\n\r\nThis is a fairly special usage of Peewee and you should be knowledgeable about both Django and Peewee... By your issue and the description, it seems to me that this is not the case for you. Probably you should stick with Django."
] | 2019-08-22T04:57:02 | 2019-08-22T16:30:37 | 2019-08-22T16:30:36 | NONE | null | I'm using `peewee` to access a remote *MySql* database to retrieve data that I need to display in a *Django* app. It means that `peewee` isn't really used to access the main db but just to like, define custom models:
Example in `databases.py` :
from django.conf import settings
from playhouse.pool import PooledMySQLDatabase
database = PooledMySQLDatabase(
settings.DB_PEEWEE,
**{
"use_unicode": True,
"charset": "utf8",
"max_connections": 32,
"stale_timeout": 300, # 5 minutes.
"password": settings.DB_PEEWEE_PSWRD,
"user": settings.DB_PEEWEE_USER,
"host": settings.DB_PEEWEE_HOST,
"port": settings.DB_PEEWEE_PORT,
}
)
in `models.py`:
from .databases import database
class BaseModel(peewee.Model):
class Meta:
database = database
class CountryGroups(BaseModel):
africa = peewee.CharField(null=True)
group_code = peewee.AutoField()
group_name = peewee.CharField()
latin_eur = peewee.CharField(null=True)
type = peewee.CharField()
class Meta:
table_name = "country_groups"
...
# other main django models
So the model can be easily called from the `views.py` file as :
CountryGroups_list = (
CountryGroups.select()
.where(CountryGroups.group_name << ["ERROR", "INFO"])
.order_by(CountryGroups.group_name.desc())
.limit(1000)
)
I can run the query fine. But I get an error after 24 hours where the connection is broken:
`(2006, "MySQL server has gone away (error(32, 'Broken pipe'))")`
The suggested method of solving this in `Django` is trough the usage of a [middleware][1] but this assume that in that case `peewee` related db is the main one, and has resulted in errors like this one:
File "/home/user/Dev/project/project/wsgi.py", line 14, in <module>
from configurations.wsgi import get_wsgi_application
File "/home/user/.virtualenvs/project/lib/python3.5/site-packages/configurations/wsgi.py", line 14, in <module>
application = get_wsgi_application()
File "/home/user/.virtualenvs/project/lib/python3.5/site-packages/django/core/wsgi.py", line 13, in get_wsgi_application
return WSGIHandler()
File "/home/user/.virtualenvs/project/lib/python3.5/site-packages/django/core/handlers/wsgi.py", line 135, in __init__
self.load_middleware()
File "/home/user/.virtualenvs/project/lib/python3.5/site-packages/django/core/handlers/base.py", line 37, in load_middleware
mw_instance = middleware(handler)
TypeError: object() takes no parameters
So my question is, how would I implement the auto **connect()** and **close()** to my generic *database* model so that I don't get the error?
[1]: http://docs.peewee-orm.com/en/latest/peewee/database.html#django | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1995/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/1995/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1994 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1994/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1994/comments | https://api.github.com/repos/coleifer/peewee/issues/1994/events | https://github.com/coleifer/peewee/issues/1994 | 483,010,693 | MDU6SXNzdWU0ODMwMTA2OTM= | 1,994 | db_value and model fields | {
"login": "bronte2k7",
"id": 29693866,
"node_id": "MDQ6VXNlcjI5NjkzODY2",
"avatar_url": "https://avatars.githubusercontent.com/u/29693866?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/bronte2k7",
"html_url": "https://github.com/bronte2k7",
"followers_url": "https://api.github.com/users/bronte2k7/followers",
"following_url": "https://api.github.com/users/bronte2k7/following{/other_user}",
"gists_url": "https://api.github.com/users/bronte2k7/gists{/gist_id}",
"starred_url": "https://api.github.com/users/bronte2k7/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/bronte2k7/subscriptions",
"organizations_url": "https://api.github.com/users/bronte2k7/orgs",
"repos_url": "https://api.github.com/users/bronte2k7/repos",
"events_url": "https://api.github.com/users/bronte2k7/events{/privacy}",
"received_events_url": "https://api.github.com/users/bronte2k7/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"No"
] | 2019-08-20T18:20:26 | 2019-08-20T18:43:59 | 2019-08-20T18:43:59 | NONE | null | Hi guys
```python
class CustomField(CharField):
def db_value(self, value):
# can I access the note field?
return value
class User(Model):
note = TextField(null=True)
extend = CustomField()
```
Is it possible to access the value in the note field, from db_value? | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1994/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/1994/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1993 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1993/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1993/comments | https://api.github.com/repos/coleifer/peewee/issues/1993/events | https://github.com/coleifer/peewee/issues/1993 | 482,034,939 | MDU6SXNzdWU0ODIwMzQ5Mzk= | 1,993 | Improve equality check | {
"login": "clintonb",
"id": 910510,
"node_id": "MDQ6VXNlcjkxMDUxMA==",
"avatar_url": "https://avatars.githubusercontent.com/u/910510?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/clintonb",
"html_url": "https://github.com/clintonb",
"followers_url": "https://api.github.com/users/clintonb/followers",
"following_url": "https://api.github.com/users/clintonb/following{/other_user}",
"gists_url": "https://api.github.com/users/clintonb/gists{/gist_id}",
"starred_url": "https://api.github.com/users/clintonb/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/clintonb/subscriptions",
"organizations_url": "https://api.github.com/users/clintonb/orgs",
"repos_url": "https://api.github.com/users/clintonb/repos",
"events_url": "https://api.github.com/users/clintonb/events{/privacy}",
"received_events_url": "https://api.github.com/users/clintonb/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"Here is a proposed implementation:\r\n\r\n```python\r\ndef __eq__(self, other: Any) -> bool:\r\n if other.__class__ != self.__class__:\r\n return False\r\n\r\n for field in self._meta.sorted_fields:\r\n if getattr(self, field.name) != getattr(other, field.name):\r\n return False\r\n\r\n return True\r\n```",
"I can't imagine a situation in practice where such a comparison would be valuable. It suggests to me that there's a problem elsewhere in the implementation of your code. Models are not a representation of the state of the DB at all times. It's just simple active record. As such, comparing IDs seems reasonable but it's best to never need to compare model instances at all because of this."
] | 2019-08-18T20:40:00 | 2019-08-19T00:52:14 | 2019-08-19T00:52:14 | NONE | null | The current implementation of `__eq__` on `Model` just checks if the primary keys are equal.
https://github.com/coleifer/peewee/blob/f6d693366eccb8e27b0b331246358f9c7d4e54b7/peewee.py#L6364-L6368
It would be preferable to if this method compared the value of all fields.
Test case:
```python
from models import Test
t1 = Test(id=1, foo='bar')
t2 = Test(id=1, foo='apple')
assert t1 != t2
```
Context: When writing tests, I prefer to compare two instances rather than iterate over all of the fields. | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1993/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/1993/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1992 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1992/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1992/comments | https://api.github.com/repos/coleifer/peewee/issues/1992/events | https://github.com/coleifer/peewee/issues/1992 | 481,909,115 | MDU6SXNzdWU0ODE5MDkxMTU= | 1,992 | Peewee does not automatically reconnect to MySQL | {
"login": "Xandaros",
"id": 265886,
"node_id": "MDQ6VXNlcjI2NTg4Ng==",
"avatar_url": "https://avatars.githubusercontent.com/u/265886?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/Xandaros",
"html_url": "https://github.com/Xandaros",
"followers_url": "https://api.github.com/users/Xandaros/followers",
"following_url": "https://api.github.com/users/Xandaros/following{/other_user}",
"gists_url": "https://api.github.com/users/Xandaros/gists{/gist_id}",
"starred_url": "https://api.github.com/users/Xandaros/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/Xandaros/subscriptions",
"organizations_url": "https://api.github.com/users/Xandaros/orgs",
"repos_url": "https://api.github.com/users/Xandaros/repos",
"events_url": "https://api.github.com/users/Xandaros/events{/privacy}",
"received_events_url": "https://api.github.com/users/Xandaros/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"Part of this is how the PyMySQL driver is implemented.\r\n\r\nHowever, Peewee doesn't automatically reconnect to databases by default. Check out `playhouse.shortcuts.ReconnectMixin` if you want automatic database reconnects.\r\n\r\n```python\r\n\r\nclass ReconnectMySQLDatabase(ReconnectMixin, MySQLDatabase):\r\n pass\r\n\r\n# Your db should now automatically attempt to reconnect for certain types of errors.\r\ndb = ReconnectMySQLDatabase(...)\r\n```",
"You may need to extend the list of `reconnect_errors` as an attribute on `ReconnectMixin`.",
"How is that not default? Isn't peewee meant to be easy to use?\r\n\r\nThat's why I initially chose it, at least. People said it was easy but doesn't necessarily allow for more complex queries.\r\n\r\nThat aside, I can't find anything about a `ReconnectMixin` in the docs. Opening the playhouse docs and searching for `reconnect` with ctrl-f, it comes up empty. Searching for `reconnect` using the search bar in the top-left, it also comes up empty...",
"I'm sorry you were so triggered by actually needing to think about software engineering. Blindly reconnecting is never going to be the default, as far as I'm concerned.\r\n\r\nYeah it was removed in 3.x and re-added recently (3.8 I think). It's there if you want it, but my opinion is its the DB drivers job to manage the connection (the socket/file/etc). If pymysql doesn't handle it, try opening the bug over there.",
"Another consideration is what if the database connection drops out mid-transaction? If Peewee were to automatically re-connect, possibly the first half of the transaction would be lost."
] | 2019-08-17T17:36:13 | 2019-08-19T18:13:12 | 2019-08-18T13:27:14 | NONE | null | peewee does not properly handle a dropped connection to the MySQL server. In my case, I am using peewee 3.10.0 and mariadb 10.3.12.
A simple program like this:
```python
import peewee
db = peewee.MySQLDatabase(database="test",
host="127.0.0.1",
user="test",
password="test")
class Test(peewee.Model):
test = peewee.TextField()
class Meta:
database = db
db.connect()
db.create_tables([Test])
input("")
print(list(Test.select()))
```
can already fail. If you start this program and, while it is waiting for input, restart the MySQL server, the select will fail.
I would expect peewee to handle this gracefully and quietly reconnect.
In this state, `db.is_closed()` returns `False` and a `db.connect()` will result in an error, saying it is already connected. The only way to recover from this is to explicitly close the connection with `db.close()`.
While the example I give here is rather contrived - you don't restart your database server all that often - I encountered this problem when my program was unable to access the database after running for about a day.
The error you get:
```
Traceback (most recent call last):
File "/usr/lib/python3.7/site-packages/peewee.py", line 2683, in execute_sql
cursor.execute(sql, params or ())
File "/usr/lib/python3.7/site-packages/pymysql/cursors.py", line 170, in execute
result = self._query(query)
File "/usr/lib/python3.7/site-packages/pymysql/cursors.py", line 328, in _query
conn.query(q)
File "/usr/lib/python3.7/site-packages/pymysql/connections.py", line 516, in query
self._affected_rows = self._read_query_result(unbuffered=unbuffered)
File "/usr/lib/python3.7/site-packages/pymysql/connections.py", line 727, in _read_query_result
result.read()
File "/usr/lib/python3.7/site-packages/pymysql/connections.py", line 1066, in read
first_packet = self.connection._read_packet()
File "/usr/lib/python3.7/site-packages/pymysql/connections.py", line 683, in _read_packet
packet.check_error()
File "/usr/lib/python3.7/site-packages/pymysql/protocol.py", line 220, in check_error
err.raise_mysql_exception(self._data)
File "/usr/lib/python3.7/site-packages/pymysql/err.py", line 109, in raise_mysql_exception
raise errorclass(errno, errval)
pymysql.err.InternalError: (1927, 'Connection was killed')
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "test.py", line 21, in <module>
print(list(Test.select()))
File "/usr/lib/python3.7/site-packages/peewee.py", line 5952, in __iter__
self.execute()
File "/usr/lib/python3.7/site-packages/peewee.py", line 1604, in inner
return method(self, database, *args, **kwargs)
File "/usr/lib/python3.7/site-packages/peewee.py", line 1675, in execute
return self._execute(database)
File "/usr/lib/python3.7/site-packages/peewee.py", line 1826, in _execute
cursor = database.execute(self)
File "/usr/lib/python3.7/site-packages/peewee.py", line 2696, in execute
return self.execute_sql(sql, params, commit=commit)
File "/usr/lib/python3.7/site-packages/peewee.py", line 2690, in execute_sql
self.commit()
File "/usr/lib/python3.7/site-packages/peewee.py", line 2481, in __exit__
reraise(new_type, new_type(*exc_args), traceback)
File "/usr/lib/python3.7/site-packages/peewee.py", line 178, in reraise
raise value.with_traceback(tb)
File "/usr/lib/python3.7/site-packages/peewee.py", line 2683, in execute_sql
cursor.execute(sql, params or ())
File "/usr/lib/python3.7/site-packages/pymysql/cursors.py", line 170, in execute
result = self._query(query)
File "/usr/lib/python3.7/site-packages/pymysql/cursors.py", line 328, in _query
conn.query(q)
File "/usr/lib/python3.7/site-packages/pymysql/connections.py", line 516, in query
self._affected_rows = self._read_query_result(unbuffered=unbuffered)
File "/usr/lib/python3.7/site-packages/pymysql/connections.py", line 727, in _read_query_result
result.read()
File "/usr/lib/python3.7/site-packages/pymysql/connections.py", line 1066, in read
first_packet = self.connection._read_packet()
File "/usr/lib/python3.7/site-packages/pymysql/connections.py", line 683, in _read_packet
packet.check_error()
File "/usr/lib/python3.7/site-packages/pymysql/protocol.py", line 220, in check_error
err.raise_mysql_exception(self._data)
File "/usr/lib/python3.7/site-packages/pymysql/err.py", line 109, in raise_mysql_exception
raise errorclass(errno, errval)
peewee.InternalError: (1927, 'Connection was killed')
```
Subsequent attempts to use the database will result in a slightly different error:
```
Traceback (most recent call last):
File "/usr/lib/python3.7/site-packages/peewee.py", line 2683, in execute_sql
cursor.execute(sql, params or ())
File "/usr/lib/python3.7/site-packages/pymysql/cursors.py", line 170, in execute
result = self._query(query)
File "/usr/lib/python3.7/site-packages/pymysql/cursors.py", line 328, in _query
conn.query(q)
File "/usr/lib/python3.7/site-packages/pymysql/connections.py", line 515, in query
self._execute_command(COMMAND.COM_QUERY, sql)
File "/usr/lib/python3.7/site-packages/pymysql/connections.py", line 745, in _execute_command
raise err.InterfaceError("(0, '')")
pymysql.err.InterfaceError: (0, '')
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "test.py", line 29, in <module>
print(list(Test.select()))
File "/usr/lib/python3.7/site-packages/peewee.py", line 5952, in __iter__
self.execute()
File "/usr/lib/python3.7/site-packages/peewee.py", line 1604, in inner
return method(self, database, *args, **kwargs)
File "/usr/lib/python3.7/site-packages/peewee.py", line 1675, in execute
return self._execute(database)
File "/usr/lib/python3.7/site-packages/peewee.py", line 1826, in _execute
cursor = database.execute(self)
File "/usr/lib/python3.7/site-packages/peewee.py", line 2696, in execute
return self.execute_sql(sql, params, commit=commit)
File "/usr/lib/python3.7/site-packages/peewee.py", line 2690, in execute_sql
self.commit()
File "/usr/lib/python3.7/site-packages/peewee.py", line 2481, in __exit__
reraise(new_type, new_type(*exc_args), traceback)
File "/usr/lib/python3.7/site-packages/peewee.py", line 178, in reraise
raise value.with_traceback(tb)
File "/usr/lib/python3.7/site-packages/peewee.py", line 2683, in execute_sql
cursor.execute(sql, params or ())
File "/usr/lib/python3.7/site-packages/pymysql/cursors.py", line 170, in execute
result = self._query(query)
File "/usr/lib/python3.7/site-packages/pymysql/cursors.py", line 328, in _query
conn.query(q)
File "/usr/lib/python3.7/site-packages/pymysql/connections.py", line 515, in query
self._execute_command(COMMAND.COM_QUERY, sql)
File "/usr/lib/python3.7/site-packages/pymysql/connections.py", line 745, in _execute_command
raise err.InterfaceError("(0, '')")
peewee.InterfaceError: (0, '')
```
I sometimes see a broken pipe error, too. | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1992/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/1992/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1991 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1991/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1991/comments | https://api.github.com/repos/coleifer/peewee/issues/1991/events | https://github.com/coleifer/peewee/issues/1991 | 481,715,589 | MDU6SXNzdWU0ODE3MTU1ODk= | 1,991 | Query with double outer join returns empty object instead of `None` | {
"login": "ibushong",
"id": 9298422,
"node_id": "MDQ6VXNlcjkyOTg0MjI=",
"avatar_url": "https://avatars.githubusercontent.com/u/9298422?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/ibushong",
"html_url": "https://github.com/ibushong",
"followers_url": "https://api.github.com/users/ibushong/followers",
"following_url": "https://api.github.com/users/ibushong/following{/other_user}",
"gists_url": "https://api.github.com/users/ibushong/gists{/gist_id}",
"starred_url": "https://api.github.com/users/ibushong/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/ibushong/subscriptions",
"organizations_url": "https://api.github.com/users/ibushong/orgs",
"repos_url": "https://api.github.com/users/ibushong/repos",
"events_url": "https://api.github.com/users/ibushong/events{/privacy}",
"received_events_url": "https://api.github.com/users/ibushong/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"If you don't select anything from City, Peewee will mark the intervening model (Venue) as NULL. There was a similar issue reporting the opposite condition -- namely, not to use empty models. The current logic looks at the models as nodes in a graph. In your example, Venue is in the middle, connecting Event <- Venue <- City. Since you requested stuff on Event and City, Peewee sees that Venue is both a source (i.e., we joining *from* Venue) and a destination (we are joining *to* Venue). Because of this, Peewee will drop an empty model instance in place so that we can go from Event -> City even in the event no data is returned for Venue. Although that isn't the case here, that is the reason for that logic.\r\n\r\nThe way to avoid this would require looking through the graph each time a result row is constructed and pruning empty parts. I'm not too inclined to make that change, but it's probably the right one.\r\n\r\nIn the meantime, just add the appropriate conditionals to work around it.\r\n\r\n* if event.venue.is is None ?\r\n* fix `__str__` so that it's smarter about resolving foreign keys",
"Going to mark this as a nice-to-have in the TODOs list.",
"Thanks for the explanation. I suspected it might be something like that. Pruning it definitely sounds like the right solution.\r\n\r\nAlso, while I was implementing a workaround, I realized a more dangerous/relevant symptom of this issue. If in the `for events in q:` loop I wanted to condition something on if the event has a venue or not, I would do `if event.venue:` but this is True even for events without a venue (since they have an empty Venue object). As you recommended in your comment, `if event.venue.id:` works, but I could see this being a pesky bug to track down. Actually I think I _just_ realized that this is the cause of a weird bug I saw a while ago in my project...\r\n"
] | 2019-08-16T17:45:37 | 2019-08-16T20:25:54 | 2019-08-16T19:25:27 | NONE | null | Models:
```python
class City(BaseModel):
name = CharField(null=False)
class Venue(BaseModel):
name = CharField(null=False)
city = ForeignKeyField(City, null=False)
def __str__(self):
return "%s (%s)" % (self.name, self.city.name)
class Event(BaseModel):
name = CharField(null=False)
venue = ForeignKeyField(Venue, null=True)
```
script:
```python
event = Event.create(name="Party", venue=None)
q = (Event.select(Event, Venue, City)
.join(Venue, join_type=JOIN.LEFT_OUTER)
.join(City, join_type=JOIN.LEFT_OUTER)
)
for event in q:
print event.id, event.name, event.venue
```
```
Traceback (most recent call last):
File "/Users/ibushong/discotech/discotech-api/peewee_bug.py", line 50, in <module>
print ep.id, ep.name, ep.venue
File "/Users/ibushong/discotech/discotech-api/peewee_bug.py", line 29, in __str__
return "%s (%s)" % (self.name, self.city.name)
File "/Users/ibushong/.pyenv/versions/discotech/lib/python2.7/site-packages/peewee.py", line 4241, in __get__
return self.get_rel_instance(instance)
File "/Users/ibushong/.pyenv/versions/discotech/lib/python2.7/site-packages/peewee.py", line 4236, in get_rel_instance
raise self.rel_model.DoesNotExist
__main__.CityDoesNotExist
```
I would expect `event.venue` to just return `None` but it seems like it's actually returning an "empty" venue object. So then when `__str__()` tries to access `self.city` (which must not be null), it his the `DoesNotExist` error.
This feels like a bug, but maybe it's just improper usage? | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1991/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/1991/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1990 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1990/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1990/comments | https://api.github.com/repos/coleifer/peewee/issues/1990/events | https://github.com/coleifer/peewee/issues/1990 | 481,518,774 | MDU6SXNzdWU0ODE1MTg3NzQ= | 1,990 | Set last_insert_id(`id`) on Insert ... On Duplicate Key Update in MySQL | {
"login": "malaney",
"id": 517419,
"node_id": "MDQ6VXNlcjUxNzQxOQ==",
"avatar_url": "https://avatars.githubusercontent.com/u/517419?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/malaney",
"html_url": "https://github.com/malaney",
"followers_url": "https://api.github.com/users/malaney/followers",
"following_url": "https://api.github.com/users/malaney/following{/other_user}",
"gists_url": "https://api.github.com/users/malaney/gists{/gist_id}",
"starred_url": "https://api.github.com/users/malaney/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/malaney/subscriptions",
"organizations_url": "https://api.github.com/users/malaney/orgs",
"repos_url": "https://api.github.com/users/malaney/repos",
"events_url": "https://api.github.com/users/malaney/events{/privacy}",
"received_events_url": "https://api.github.com/users/malaney/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"I just answered my own question!!\r\n\r\n> .on_conflict(\r\n preserve=[Model.first_name, Model.last_name],\r\n update={Model.id: fn.last_insert_id(Model.id)}\r\n )"
] | 2019-08-16T09:14:31 | 2019-08-16T09:43:59 | 2019-08-16T09:43:59 | NONE | null | I'm using peewee to generate an "INSERT ... ON DUPLICATE KEY UPDATE" query in MySQL using the .insert().on_conflict() methods for a table with an auto_increment ID. Whether the query performs an INSERT or an UPDATE I'd like the query to return the ID of the most recently created row or the ID of the most recently updated row. In MySQL this can be achieved by building a query that looks like the following:
`INSERT ... ON DUPLICATE KEY UPDATE `id`=last_insert_id(`id`)`
With this query, the very next call to last_insert_id will always return the right value whether the operation performs an insert or update. Is it possible to get peewee to render such a query using the Model.insert().on_conflict() API?? | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1990/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/1990/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1989 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1989/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1989/comments | https://api.github.com/repos/coleifer/peewee/issues/1989/events | https://github.com/coleifer/peewee/issues/1989 | 480,290,939 | MDU6SXNzdWU0ODAyOTA5Mzk= | 1,989 | Spellfix1 SQLite Extension? | {
"login": "FaizShah",
"id": 1187484,
"node_id": "MDQ6VXNlcjExODc0ODQ=",
"avatar_url": "https://avatars.githubusercontent.com/u/1187484?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/FaizShah",
"html_url": "https://github.com/FaizShah",
"followers_url": "https://api.github.com/users/FaizShah/followers",
"following_url": "https://api.github.com/users/FaizShah/following{/other_user}",
"gists_url": "https://api.github.com/users/FaizShah/gists{/gist_id}",
"starred_url": "https://api.github.com/users/FaizShah/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/FaizShah/subscriptions",
"organizations_url": "https://api.github.com/users/FaizShah/orgs",
"repos_url": "https://api.github.com/users/FaizShah/repos",
"events_url": "https://api.github.com/users/FaizShah/events{/privacy}",
"received_events_url": "https://api.github.com/users/FaizShah/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"Here's some starter code\r\n\r\n```python\r\nfrom peewee import *\r\nfrom playhouse.sqlite_ext import *\r\n\r\ndb = CSqliteExtDatabase('/tmp/spellfix.db')\r\ndb.load_extension('/path/to/spellfix1')\r\n\r\nclass WordList(VirtualModel):\r\n # See http://www.sqlite.org/spellfix1.html\r\n word = VirtualField(TextField)\r\n rank = VirtualField(IntegerField)\r\n distance = VirtualField(IntegerField)\r\n langid = VirtualField(IntegerField)\r\n score = VirtualField(FloatField)\r\n matchlen = VirtualField(IntegerField)\r\n phonehash = VirtualField(TextField)\r\n top = VirtualField(IntegerField)\r\n scope = VirtualField(FloatField)\r\n soundslike = VirtualField(TextField)\r\n\r\n class Meta:\r\n database = db\r\n extension_module = 'spellfix1'\r\n primary_key = False\r\n\r\nWordList.create_table()\r\n\r\nwith db.atomic():\r\n with open('/path/to/dictionary') as fh:\r\n for word in fh:\r\n WordList.insert({'word': word.strip()}).execute()\r\n\r\nwords = (\r\n 'speling',\r\n 'heling',\r\n 'lhelping',\r\n)\r\nfor word in words:\r\n query = (WordList\r\n .select(WordList.word, WordList.score, WordList.distance,\r\n WordList.phonehash, WordList.matchlen)\r\n .where(NodeList((WordList.word, SQL('MATCH'), word)) &\r\n (WordList.top == 5))\r\n .dicts())\r\n print('WORD: %s' % word)\r\n for result in query:\r\n print(result)\r\n```",
"Thank you Charles, much appreciated. \r\n\r\nYour blog has also been a great resource on closure.c, json1 and FTS5. Thanks for all you do!",
"Since it was a bit cumbersome to get the spellfix extension along with the python packages I depend on, I made a pip-installable version of it: https://github.com/karlb/sqlite-spellfix. Maybe that is helpful for you, too.",
"Excellent contribution @karlb thank you! Maybe we could make all the extensions pip installable like \"pip install sqlite-extensions[fts5,closures]\" using [extras_require](https://stackoverflow.com/a/60307740). I will take a look this weekend :)"
] | 2019-08-13T18:03:15 | 2020-07-15T21:43:38 | 2019-08-13T19:47:20 | NONE | null | Hi all,
I'm using the FTS extension for SQLite and I would like to test out Spellfix1 for FTS spelling correction in peewee.
What would be the easiest/best way to add the Spellfix1 extension for SQLite in peewee?
Here is some example code using it without peewee for reference:
```
# Build the extension.
!wget https://sqlite.org/2016/sqlite-src-3110100.zip
!unzip sqlite-src-3110100.zip
!gcc -shared -fPIC -Wall -Isqlite-src-3110100 sqlite-src-3110100/ext/misc/spellfix.c -o spellfix.so
# Load the extension
import sqlite3
db = sqlite3.connect(':memory:')
db.enable_load_extension(True)
db.load_extension('./spellfix')
# Create an FTS table and load some data in here.
cur.execute('''CREATE VIRTUAL TABLE value_fts USING fts5(value)''')
cur.execute('''INSERT INTO value_fts (rowid, value) SELECT id, value FROM data''')
# Create a table with just the vocab from the FTS5 table.
cur.execute('''CREATE VIRTUAL TABLE IF NOT EXISTS value_fts_vocab USING fts5vocab('value_fts', 'row') ''')
# Set up spellfix1 extension with the editcost algo.
cur.execute('''CREATE TABLE IF NOT EXISTS editcost(
iLang INT, -- The language ID
cFrom TEXT, -- Convert text from this
cTo TEXT, -- Convert text into this
iCost INT -- The cost of doing the conversion
)''')
cur.execute('''CREATE VIRTUAL TABLE IF NOT EXISTS value_fts_vocab_spl USING spellfix1(edit_cost_table=editcost)''')
# Load the vocab in the spellfix table.
cur.execute('''INSERT INTO value_fts_vocab_spl (word) SELECT term FROM value_fts_vocab''')
# Use the spellfix extension to correct the spelling from the FTS vocab.
cur.execute('''SELECT *, distance, matchlen FROM value_fts_vocab_spl WHERE word MATCH lower('Genr') ''')
cur.fetchall()
``` | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1989/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/1989/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1988 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1988/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1988/comments | https://api.github.com/repos/coleifer/peewee/issues/1988/events | https://github.com/coleifer/peewee/issues/1988 | 479,105,079 | MDU6SXNzdWU0NzkxMDUwNzk= | 1,988 | pwiz creates all fields as FloatField regardless of precision | {
"login": "albireox",
"id": 568775,
"node_id": "MDQ6VXNlcjU2ODc3NQ==",
"avatar_url": "https://avatars.githubusercontent.com/u/568775?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/albireox",
"html_url": "https://github.com/albireox",
"followers_url": "https://api.github.com/users/albireox/followers",
"following_url": "https://api.github.com/users/albireox/following{/other_user}",
"gists_url": "https://api.github.com/users/albireox/gists{/gist_id}",
"starred_url": "https://api.github.com/users/albireox/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/albireox/subscriptions",
"organizations_url": "https://api.github.com/users/albireox/orgs",
"repos_url": "https://api.github.com/users/albireox/repos",
"events_url": "https://api.github.com/users/albireox/events{/privacy}",
"received_events_url": "https://api.github.com/users/albireox/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"Pushed a fix -- oid 701 appears to be double-precision, so it's up-to-date now. If your schema already exists, however, it doesn't matter because Python uses a double internally anyways. Lastly, if it's an issue, you are free to modify the fields yourself.\r\n\r\n> Alternatively, is there a way to access the Postgresql underlying type for a field without having to connect to the DB?\r\n\r\nI don't know what this means.",
"Thanks, that works. My use for this case is that I have a tool that uses the introspection utils to generate PDF with the DB tables and columns, and it was assigning FLOAT to all the columns regardless of precision.\r\n\r\n> > Alternatively, is there a way to access the Postgresql underlying type for a field without having to connect to the DB?\r\n> \r\n> I don't know what this means.\r\n\r\nI meant if it's possible to get the PSQL type for a field (e.g., 'BIGINT', 'DOUBLE', 'REAL', 'VARCHAR', etc.)",
"> I meant if it's possible to get the PSQL type for a field\r\n\r\nCheck the code in reflection, it has all the info you need. You can map the oid to the typname in the pg_type table."
] | 2019-08-09T18:05:56 | 2019-08-09T21:08:03 | 2019-08-09T19:18:17 | NONE | null | It seems when `pwiz` creates a schema, it assigns `FloatField` to all the floating point types, regardless of their precision. Could it be possible to have it create the appropriate type of field?
Alternatively, is there a way to access the Postgresql underlying type for a field without having to connect to the DB? | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1988/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/1988/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1987 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1987/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1987/comments | https://api.github.com/repos/coleifer/peewee/issues/1987/events | https://github.com/coleifer/peewee/issues/1987 | 479,091,068 | MDU6SXNzdWU0NzkwOTEwNjg= | 1,987 | peewee internal error on updating class with generated columns | {
"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 | [
"> Are there ways to declare 'qid' in peewee model as generated and never update it?\r\n\r\nYou're best off using `INSERT` or `UPDATE` directly in that case, so you can be more specific about which columns are being written to.\r\n\r\nPeewee typically handles server-side defaults just fine, as typically they are provided by the `DEFAULT` SQL clause, so NULLs are handled correctly. Apparently this particular example is a bit different.\r\n\r\nAnother option is to specify a list of fields to update when calling `save()`, e.g. `.save(only=[Project.utime])`.",
"Hi Charles, thanks for the suggestion. An additional note on this - this issue exists on Mariadb 10.2.4+ and MySQL 5.7+ (when teams changed default for strict_mode). Rationale behind this can be found here - https://blog.sqlyog.com/beware-virtual-columns-may-render-backups-unusable/ at 4th comment.\r\n\r\nI showed an example - of course, in the example I can use INSERT/UPDATE directly, but you've invented Peewee to make life easier :-) and in real life I update lot of fields of an instance depending on lot of conditions and even not always know what exactly was updated, and, e.g. I just save the instance if \"dirty_fields\" is.\r\n\r\nOf course, it's the way to use smth like .save(except=[Project.qid]) (is it possible BTW?) but in fact it's the way to errors (if it was forgotten, for example) and, IMHO, it much more easier and safer is to define attribute 'computed' (well, 'readonly') and never include it in modify operations over DB (regardless of DB type). From the link above - \"This is a new feature, and with every new feature that affects DDL statements, the tools must evolve to deal with that. It has happened for triggers, stored routines, events, partitioning , and it must happen for virtual columns.\"\r\n\r\nThank you.",
"It seems problematic and difficult to try and determine how to handle something like \"read-only\" fields. Calls to save() delegate to `.insert()` or `.update()`, so we would need to exclude read-only fields there. But should one prevent explicitly attempting to store data via calls directly to `.insert()` / `.update()` / `.insert_many()`? Validation would possibly need to be added in several places. Additionally, it's not clear how setting \"read-only\" would affect DDL ... do we prevent creating tables with read-only fields? Do we extend the field constructor to require specification of the expression/generator?\r\n\r\nAs long as you're not modifying a field's value, presumably it wouldn't be included in the list of dirty fields, so that should allow you to avoid this issue when using `.save()`.\r\n\r\nI'd suggest that you look at wrapping things in helper methods that do exactly what you want, and then just calling those. Trying to handle this correctly seems a bit fraught.",
"Just look at this list of gotcha's a mile long. Fuck no:\r\n\r\nhttps://mariadb.com/kb/en/library/documentation/sql-statements-structure/sql-statements/data-definition/create/generated-columns/",
":-D Well, thank you!",
"Hello, Charles, I fixed the problem by disabling strict_mode in DB, so it's not a problem for me anymore. But just one more comment to the statement \"Peewee typically handles server-side defaults just fine\". With new defaults it doesn't, actually.\r\n\r\nThere are two types of DB updates:\r\n- .update(), .insert() and others with explicit fields specification, where writer exactly know what he is doing and fully responsible for this. Issues with these operation can be easily tracked and fixed.\r\n- kinds of .save() with implicit fields specification, where Peewee takes responsibility of what exactly will be saved to DB.\r\n\r\nI think, it will be reasonable compromise to take care only about \"implicit\" calls like .save() where writer can't influence selection of fields to be saved. In this case field attribute like 'readonly' will allow to specify fields which is prohibited to update in DB.\r\n\r\nThank you.",
"> I think, it will be reasonable compromise to take care only about \"implicit\" calls like .save() where writer can't influence selection of fields to be saved. In this case field attribute like 'readonly' will allow to specify fields which is prohibited to update in DB.\r\n\r\nI agree that this is probably the place to put such logic.\r\n\r\nMight be time to add it, because I recall someone asking for a readonly-type feature a while ago.",
"For the issue of DDL, I think this will need to be handled by the user.",
"I pushed a branch... I'm not in love with the way it's shaping out, but it provides a starting place.\r\n\r\nWill close this issue for now and put this on the back-burner to think about ways to integrate this stuff.",
"Thanks, Charles! You're doing a great job. Thank you again."
] | 2019-08-09T17:26:45 | 2019-08-12T10:30:01 | 2019-08-11T21:31:31 | NONE | null | Dear colleagues,
I have an issue with the updating class with generated column with MariaDB 10.4 and peewee 3.10.0
This is SQL definition:
```
CREATE TABLE IF NOT EXISTS `mw`.`project` (
`uuid` VARCHAR(36) NULL,
`qid` VARCHAR(36) GENERATED ALWAYS AS (uuid),
`utime` DATETIME NULL,
[ ... ]
```
this is how pwiz generates model:
```
class Project(BaseModel):
qid = CharField(null=True)
utime = DateTimeField(null=True)
uuid = CharField(null=True, unique=True)
[ ... ]
```
this is code which generate error (please, note that I don't modify 'qid') :
```
pj = Project.get(Project.id == 25)
pj.utime = datetime.now()
pj.save()
```
error is:
```
Traceback (most recent call last):
File "/project/venv/lib/python3.7/site-packages/peewee.py", line 2981, in execute_sql
cursor.execute(sql, params or ())
File "/project/venv/lib/python3.7/site-packages/pymysql/cursors.py", line 170, in execute
result = self._query(query)
File "/project/venv/lib/python3.7/site-packages/pymysql/cursors.py", line 328, in _query
conn.query(q)
File "/project/venv/lib/python3.7/site-packages/pymysql/connections.py", line 517, in query
self._affected_rows = self._read_query_result(unbuffered=unbuffered)
File "/project/venv/lib/python3.7/site-packages/pymysql/connections.py", line 732, in _read_query_result
result.read()
File "/project/venv/lib/python3.7/site-packages/pymysql/connections.py", line 1075, in read
first_packet = self.connection._read_packet()
File "/project/venv/lib/python3.7/site-packages/pymysql/connections.py", line 684, in _read_packet
packet.check_error()
File "/project/venv/lib/python3.7/site-packages/pymysql/protocol.py", line 220, in check_error
err.raise_mysql_exception(self._data)
File "/project/venv/lib/python3.7/site-packages/pymysql/err.py", line 109, in raise_mysql_exception
raise errorclass(errno, errval)
pymysql.err.InternalError: (1906, "The value specified for generated column 'qid' in table 'project' has been ignored")
```
Are there ways to declare 'qid' in peewee model as generated and never update it?
Thank you. | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1987/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/1987/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1986 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1986/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1986/comments | https://api.github.com/repos/coleifer/peewee/issues/1986/events | https://github.com/coleifer/peewee/issues/1986 | 478,577,901 | MDU6SXNzdWU0Nzg1Nzc5MDE= | 1,986 | Enumerating over query result | {
"login": "karambaq",
"id": 14233969,
"node_id": "MDQ6VXNlcjE0MjMzOTY5",
"avatar_url": "https://avatars.githubusercontent.com/u/14233969?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/karambaq",
"html_url": "https://github.com/karambaq",
"followers_url": "https://api.github.com/users/karambaq/followers",
"following_url": "https://api.github.com/users/karambaq/following{/other_user}",
"gists_url": "https://api.github.com/users/karambaq/gists{/gist_id}",
"starred_url": "https://api.github.com/users/karambaq/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/karambaq/subscriptions",
"organizations_url": "https://api.github.com/users/karambaq/orgs",
"repos_url": "https://api.github.com/users/karambaq/repos",
"events_url": "https://api.github.com/users/karambaq/events{/privacy}",
"received_events_url": "https://api.github.com/users/karambaq/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"http://docs.peewee-orm.com/en/latest/peewee/contributing.html\r\n\r\nPost this on stackoverflow or ask in IRC. This forum is for issues."
] | 2019-08-08T16:38:16 | 2019-08-08T21:06:11 | 2019-08-08T21:06:11 | NONE | null | I want to get next element after the predicate is true
I've tried to use
```
for i in enumerate(gs):
if predicate(i[1]):
print(i)
```
Output:
```
(0, <Fighter: 202157127>)
(0, <Fighter: 202157569>)
(0, <Fighter: 202158125>)
(0, <Fighter: 202159063>)
(0, <Fighter: 202160131>)
(0, <Fighter: 202160498>)
(0, <Fighter: 202160800>)
```
I need to catch that `i + 1` element, how can I do that? | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1986/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/1986/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1985 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1985/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1985/comments | https://api.github.com/repos/coleifer/peewee/issues/1985/events | https://github.com/coleifer/peewee/issues/1985 | 477,501,415 | MDU6SXNzdWU0Nzc1MDE0MTU= | 1,985 | BUG: FlaskDB incorrect implementation | {
"login": "Andrei-Pozolotin",
"id": 1622151,
"node_id": "MDQ6VXNlcjE2MjIxNTE=",
"avatar_url": "https://avatars.githubusercontent.com/u/1622151?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/Andrei-Pozolotin",
"html_url": "https://github.com/Andrei-Pozolotin",
"followers_url": "https://api.github.com/users/Andrei-Pozolotin/followers",
"following_url": "https://api.github.com/users/Andrei-Pozolotin/following{/other_user}",
"gists_url": "https://api.github.com/users/Andrei-Pozolotin/gists{/gist_id}",
"starred_url": "https://api.github.com/users/Andrei-Pozolotin/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/Andrei-Pozolotin/subscriptions",
"organizations_url": "https://api.github.com/users/Andrei-Pozolotin/orgs",
"repos_url": "https://api.github.com/users/Andrei-Pozolotin/repos",
"events_url": "https://api.github.com/users/Andrei-Pozolotin/events{/privacy}",
"received_events_url": "https://api.github.com/users/Andrei-Pozolotin/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"here is a minimum working version:\r\n```\r\nimport peewee\r\nfrom flask import current_app\r\nfrom playhouse.sqlite_ext import SqliteExtDatabase\r\n\r\nclass PeeweeDatabase:\r\n\r\n def init_app(self, app) -> None:\r\n app.before_request(self.perform_open)\r\n app.teardown_request(self.perform_close)\r\n\r\n def perform_open(self, *args, **kwargs) -> None:\r\n self.database.connect()\r\n\r\n def perform_close(self, *args, **kwargs) -> None:\r\n self.database.close()\r\n\r\n @property\r\n def flask_context(self) -> Any:\r\n return current_app\r\n\r\n def produce_database(self) -> peewee.Database:\r\n self.logger.debug(f\"produce_database\")\r\n datafile = current_app.config['DATABASE']\r\n return SqliteExtDatabase(datafile)\r\n\r\n @property\r\n def database(self) -> peewee.Database:\r\n context = self.flask_context\r\n if not hasattr(context, 'peewee_database'):\r\n context.peewee_database = self.produce_database()\r\n return context.peewee_database\r\n```\r\n",
"I disagree with your assessment.\r\n\r\nYou create a `FlaskDB()` instance by either\r\n\r\n1. passing it a flask app instance\r\n2. calling `init_app()` later with an app instance\r\n\r\nThis binds the pre/post-request hooks for the given app.\r\n\r\nThere is a 1-to-1 between `FlaskDB` instances and `Flask` instances, in other words.",
"I'm going to reopen this just to think about it a little more, but I'm not quite convinced that doing all kinds of magic with the app context is necessarily the right choice for this implementation.",
"even more simplified example:\r\n\r\n```\r\nimport peewee\r\nfrom flask import Flask, current_app\r\nfrom playhouse.sqlite_ext import SqliteExtDatabase\r\n\r\nclass PeeweeDatawrap:\r\n\r\n def init_app(self, app:Flask) -> None:\r\n app.extensions['peewee_database'] = self.produce_database(app)\r\n app.before_request(self.perform_open)\r\n app.teardown_request(self.perform_close)\r\n\r\n def perform_open(self, *args, **kwargs) -> None:\r\n self.database.connect()\r\n\r\n def perform_close(self, *args, **kwargs) -> None:\r\n self.database.close()\r\n\r\n def produce_database(self, app:Flask) -> peewee.Database:\r\n datafile = app.config['DATABASE']\r\n return SqliteExtDatabase(datafile)\r\n\r\n @property\r\n def database(self) -> peewee.Database:\r\n return current_app.extensions['peewee_database']\r\n```\r\n",
"with support for multiple database instances in the same flask app:\r\n```\r\nclass PeeweeDatawrap:\r\n\r\n def __init__(self, data_name:str='default'):\r\n self.data_name = f\"peewee_{data_name}\"\r\n\r\n def init_app(self, app:Flask,) -> None:\r\n assert not self.data_name in app.extensions, f\"duplicate entry: {self.data_name}\"\r\n app.extensions[self.data_name] = self.produce_database(app)\r\n\r\n # ... snip ... #\r\n\r\n @property\r\n def database(self) -> peewee.Database:\r\n return current_app.extensions[self.data_name]\r\n```",
"Thanks for the links and the implementation suggestions. I'm going to refactor the `FlaskDB` to more closely follow the flask extension guidelines (support for multiple apps, support for multiple databases-per-app), as you've suggested.",
"1. thank you.\r\n\r\n2. regarding the name: `FlaskDB`: \r\nbeing a for-flask extension, perhaps it should be flask-centric, \r\ni.e. make more sense from flask point of view, say: `PeeweeFlaskPlugin`\r\n",
"There's an issue I realized once I started implementing some changes. Accessing the `database` relies on `current_app`. Which implies that accessing the `Model` property (which provides a base model class) will also require an app context.\r\n\r\nThis means that people will need to change their model code around and wrap everything in an app context. This would be quite disruptive for existing codebases.\r\n\r\nGoing to pass on changing the implementation for now, and if I do choose to make changes, will probably do so in a separate class that allows people to continue using `FlaskDB` without an app context.",
"ok, I see.\r\n",
"Just to get a bit more perspective I checked out the [flask-sqlachemy extension](https://flask-sqlalchemy.palletsprojects.com/en/2.x/) and the [code](https://github.com/pallets/flask-sqlalchemy/blob/master/flask_sqlalchemy/__init__.py) looks to have the same behavior as the peewee `FlaskDB` extension.",
"1. well, we do not want to follow low standards, do we? :-)\r\n\r\n2. on another note, this pattern is also a major pain:\r\n```\r\nclass Model:\r\n class Meta:\r\n database: ...\r\n```\r\n\r\n3. perhaps switching peewee default database injection\r\nto flask-like `current_app` analogue would be less evil\r\n"
] | 2019-08-06T17:21:05 | 2019-08-13T19:04:00 | 2019-08-07T22:37:11 | NONE | null | 1. current implementation of `FlaskDB`
https://github.com/coleifer/peewee/blob/master/playhouse/flask_utils.py#L87
is incorrect: it stores `database` in `self` instead of the flask context
2. that prevents `FlaskDB` to be used with flask factory pattern for tests with multiple flask app instances using different per-app-instance database configurations created inside single python process
3. see:
https://flask.palletsprojects.com/en/1.1.x/patterns/appfactories/#factories-extensions
https://flask.palletsprojects.com/en/1.1.x/extensiondev/#the-extension-code
| {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1985/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/1985/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1984 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1984/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1984/comments | https://api.github.com/repos/coleifer/peewee/issues/1984/events | https://github.com/coleifer/peewee/issues/1984 | 475,903,242 | MDU6SXNzdWU0NzU5MDMyNDI= | 1,984 | Can't understand how pull data from joins | {
"login": "karambaq",
"id": 14233969,
"node_id": "MDQ6VXNlcjE0MjMzOTY5",
"avatar_url": "https://avatars.githubusercontent.com/u/14233969?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/karambaq",
"html_url": "https://github.com/karambaq",
"followers_url": "https://api.github.com/users/karambaq/followers",
"following_url": "https://api.github.com/users/karambaq/following{/other_user}",
"gists_url": "https://api.github.com/users/karambaq/gists{/gist_id}",
"starred_url": "https://api.github.com/users/karambaq/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/karambaq/subscriptions",
"organizations_url": "https://api.github.com/users/karambaq/orgs",
"repos_url": "https://api.github.com/users/karambaq/repos",
"events_url": "https://api.github.com/users/karambaq/events{/privacy}",
"received_events_url": "https://api.github.com/users/karambaq/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"You need to select it as well, then it will be available.\r\n\r\n```\r\nquery = (Fighter\r\n .select(Fighter, Timestamp)\r\n .join(Timestamp, on=(Fighter.id == Timestamp.id)))\r\nf = query.first()\r\n\r\nprint(f.left, f.right, f.timestamp.timestamp, f.timestamp.daytime)\r\n```",
"http://docs.peewee-orm.com/en/latest/peewee/relationships.html#selecting-from-multiple-sources",
"@coleifer Yes, but there are duplicate field names (id), how can I manage this? Can I select all fields except id field?\r\n\r\nEDIT: When I join two tables using SQL on id column it lefts only one id column, how can I do that using peewee?",
"Peewee handles this correctly.\r\n\r\nIn my example,\r\n\r\n```\r\nf.id # the id of the fighter\r\nf.timestamp.id # the id of the timestamp\r\n```\r\n\r\nAlso presumably since you're joining on the id then you can infer one from the other.\r\n\r\nI'd not recommend joining an auto-generated id, by the way, as it would be too easy for them to become out-of sync. Better to use an explicit foreign-key.",
"@coleifer Oh, let me show that:\r\n\r\n```\r\n games = (Fighter.select(Fighter, Timestamp).\r\n join(Timestamp, on=(Fighter.id == Timestamp.id))\r\n )\r\n print(games[0].timestamp.timestamp) # This prints fine\r\n for g in games.namedtuples(): # There is an error\r\n print(g)\r\n```\r\n\r\nTraceback:\r\n```\r\n File \"/usr/local/lib/python3.7/site-packages/peewee.py\", line 4127, in next\r\n self.cursor_wrapper.iterate()\r\n File \"/usr/local/lib/python3.7/site-packages/peewee.py\", line 4043, in iterate\r\n self.initialize() # Lazy initialization.\r\n File \"/usr/local/lib/python3.7/site-packages/peewee.py\", line 7065, in initialize\r\n self.tuple_class = collections.namedtuple('Row', attributes)\r\n File \"/usr/local/Cellar/python/3.7.3/Frameworks/Python.framework/Versions/3.7/lib/python3.7/collections/__init__.py\", line 373, in namedtuple\r\n raise ValueError(f'Encountered duplicate field name: {name!r}')\r\nValueError: Encountered duplicate field name: 'id'\r\n```\r\n\r\nIs it ok? If yes can you please explain it to me?\r\n\r\nUPD: I'm not so good in database architecture, id fields are inserting manually, they not auto-generated, there is one-to-one relationship, should I make id column in the second table as foreign key?\r\n\r\nUPD2: When I'm using `games.dicts()` instead of `games.namedtuples()` it works just as expected.",
"The behavior is what it is, as Peewee does not handle nesting or relationship-traversal when using the dicts/namedtuples/tuples methods. You can explicitly alias Timestamp.id in the .select() call if you wish, but you need to then explicitly specify all the columns on Timestamp which you intend to select."
] | 2019-08-01T21:45:51 | 2019-08-02T16:16:07 | 2019-08-02T11:21:15 | NONE | null | So I have two tables:
# fighters
```
id SERIAL PRIMARY KEY,
left_fighter text,
right_fighter text
```
# timestamp
```
id SERIAL PRIMARY KEY,
timestamp text,
daytime time
```
# Code
```
class BaseModel(Model):
class Meta:
database = db
class Fighter(BaseModel):
id = PrimaryKeyField(null=False)
left_fighter = CharField()
right_fighter = CharField()
class Meta:
table_name = 'fighters'
class Timestamp(BaseModel):
id = PrimaryKeyField(null=False)
timestamp = TimestampField()
daytime = TimeField()
table_name = 'timestamp'
fighter = (Fighter.select().join(
Timestamp, on=(Fighter.id == Timestamp.id)).first())
print(fighter.__dict__)
```
# Output:
```
{'__data__': {'id': 201322952, 'left_fighter': 'Кенши', 'right_fighter': 'Лю Кенг'}, '_dirty': set(), '__rel__': {}}
```
# Question
So I see there is data from first table, but I can't understand how to pull second table data. | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1984/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/1984/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1983 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1983/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1983/comments | https://api.github.com/repos/coleifer/peewee/issues/1983/events | https://github.com/coleifer/peewee/issues/1983 | 475,758,561 | MDU6SXNzdWU0NzU3NTg1NjE= | 1,983 | Column with name 'insert' replaces Model class method 'insert' | {
"login": "wspek",
"id": 23557813,
"node_id": "MDQ6VXNlcjIzNTU3ODEz",
"avatar_url": "https://avatars.githubusercontent.com/u/23557813?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/wspek",
"html_url": "https://github.com/wspek",
"followers_url": "https://api.github.com/users/wspek/followers",
"following_url": "https://api.github.com/users/wspek/following{/other_user}",
"gists_url": "https://api.github.com/users/wspek/gists{/gist_id}",
"starred_url": "https://api.github.com/users/wspek/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/wspek/subscriptions",
"organizations_url": "https://api.github.com/users/wspek/orgs",
"repos_url": "https://api.github.com/users/wspek/repos",
"events_url": "https://api.github.com/users/wspek/events{/privacy}",
"received_events_url": "https://api.github.com/users/wspek/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"This is why we have stuff like \"column_name\":\r\n\r\n```python\r\nclass MyModel(Model):\r\n insert_ = TextField(column_name='insert')\r\n```",
"@coleifer \r\n\r\nI have made sure all my columns are explicitly named now by using your suggestion. I hope this GIF demonstrates well that even though the **insert** column has an explicit `column_name` set, the `self.insert` class method is still assuming the value of the field.\r\n\r\n\r\n",
"Sorry, I think I get your point. I have to pay attention to the underscore you wrote down."
] | 2019-08-01T15:47:38 | 2019-08-01T16:44:39 | 2019-08-01T15:52:17 | NONE | null | Version: 3.9.6
I have discovered that when I create a Model which has a column literally named **insert**, the peewee code will throw an exception when trying to insert data through the `Model.insert` class method in [line 6311](https://github.com/coleifer/peewee/blob/ef27f0209a7942e28ba976264ceaf85891277bb1/peewee.py#L6311):
`pk = self.insert(**field_dict).execute()`
To reproduce simply create a model which has a column named **insert**. In my case, after adding a Model with the column named **insert**, things look like this:

Note the type `None` of the **insert** class method, which is due to the fact that now a column exists in the model with value `None`. After the actual field data is added, in my case, the **insert** field has value `False`. Because the code then tries to call `execute()` on this boolean value, ultimately my code fails with an exception:
`ERROR 'bool' object is not callable`
My Model also has columns **delete** and **create**, which may cause problems by overwriting class methods with the same names. That is because I am storing a table which contains database permissions for an unrelated software solution.
Thanks.
| {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1983/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/1983/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1982 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1982/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1982/comments | https://api.github.com/repos/coleifer/peewee/issues/1982/events | https://github.com/coleifer/peewee/issues/1982 | 475,290,612 | MDU6SXNzdWU0NzUyOTA2MTI= | 1,982 | Bulk update of json field not producing executable SQL in Postgres | {
"login": "saileshr",
"id": 757986,
"node_id": "MDQ6VXNlcjc1Nzk4Ng==",
"avatar_url": "https://avatars.githubusercontent.com/u/757986?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/saileshr",
"html_url": "https://github.com/saileshr",
"followers_url": "https://api.github.com/users/saileshr/followers",
"following_url": "https://api.github.com/users/saileshr/following{/other_user}",
"gists_url": "https://api.github.com/users/saileshr/gists{/gist_id}",
"starred_url": "https://api.github.com/users/saileshr/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/saileshr/subscriptions",
"organizations_url": "https://api.github.com/users/saileshr/orgs",
"repos_url": "https://api.github.com/users/saileshr/repos",
"events_url": "https://api.github.com/users/saileshr/events{/privacy}",
"received_events_url": "https://api.github.com/users/saileshr/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"I'm not in love with the way I've patched, this, but I have replicated the issue and believe it is fixed:\r\n\r\nef27f0209a7942e28ba976264ceaf85891277bb1\r\n\r\nI'd like to get a better handle on exactly when and where to apply such casts, but until I dive in deeper I suppose this will work.",
"thanks for the quick response and the fix.",
"Doesnt appear to be fixed.. but the error now is different:\r\n```\r\npeewee.ProgrammingError: syntax error at or near \"END\"\r\nLINE 1: ... SET \"db_tx_count\" = CASE \"metrics\".\"merchant_id\" END, \"db_a...\r\n```",
"Perhaps you're passing an empty list? Not sure, however there is a test that is passing if you bother seeing the commit.",
"@coleifer same thing happens with UUIDField.\r\nI inherited the UUIDField and applied the same fix, and seems to work well"
] | 2019-07-31T18:21:48 | 2021-04-29T14:07:46 | 2019-08-01T15:01:18 | NONE | null | ```
class Merchant(BaseModel):
name = TextField(primary_key=True)
class Metrics(BaseModel):
merchant = ForeignKeyField(backref='metrics', field='name', model=Merchant, primary_key=True)
db_tx_count = JSONField(null=True, default={})
```
I update a bunch of metrics records and store them in metrics_updated.
I then call:
```
Metrics.bulk_update(metrics_updated, fields=['db_tx_count'])
```
That produces the following SQL:
```
'UPDATE "metrics" SET "db_tx_count" = CASE "metrics"."merchant_id" WHEN %s THEN %s WHEN %s THEN %s END WHERE ("metrics"."merchant_id" IN (%s, %s))', ['Hobby Lobby', <psycopg2._json.Json object at 0x7f06c30d5cc0>, 'Caserta Pizzeria Bakr', <psycopg2._json.Json object at 0x7f06c30d5ef0>, 'Hobby Lobby', 'Caserta Pizzeria Bakr'])
```
which triggers the following postgres error:
```
peewee.ProgrammingError: column "db_tx_count" is of type json but expression is of type text
LINE 1: UPDATE "yodlee"."metrics" SET "db_tx_count" = CASE "metrics"...
^
HINT: You will need to rewrite or cast the expression.
```
Postgres 11.2. Python 3.6.7 Peewee 3.9.6
Please let me know if you need any other info
| {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1982/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/1982/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1981 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1981/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1981/comments | https://api.github.com/repos/coleifer/peewee/issues/1981/events | https://github.com/coleifer/peewee/issues/1981 | 474,548,204 | MDU6SXNzdWU0NzQ1NDgyMDQ= | 1,981 | MySQL does not support the specification of where clauses... | {
"login": "stormeyes",
"id": 5072174,
"node_id": "MDQ6VXNlcjUwNzIxNzQ=",
"avatar_url": "https://avatars.githubusercontent.com/u/5072174?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/stormeyes",
"html_url": "https://github.com/stormeyes",
"followers_url": "https://api.github.com/users/stormeyes/followers",
"following_url": "https://api.github.com/users/stormeyes/following{/other_user}",
"gists_url": "https://api.github.com/users/stormeyes/gists{/gist_id}",
"starred_url": "https://api.github.com/users/stormeyes/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/stormeyes/subscriptions",
"organizations_url": "https://api.github.com/users/stormeyes/orgs",
"repos_url": "https://api.github.com/users/stormeyes/repos",
"events_url": "https://api.github.com/users/stormeyes/events{/privacy}",
"received_events_url": "https://api.github.com/users/stormeyes/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [] | 2019-07-30T12:11:36 | 2019-07-30T12:48:55 | 2019-07-30T12:48:55 | NONE | null | Hi, I read the issue https://github.com/coleifer/peewee/issues/1307 and know I can use upsert-like method `on_conflict`, however when I try I got error: `MySQL does not support the specification of where clauses or conflict targets for conflict resolution.` , anyone knows why?
```
res = (Emp
.insert(first='foo', empno='125')
.on_conflict(
conflict_target=(Emp.empno,),
preserve=(Emp.first, Emp.last),
update={Emp.empno: '125.1'})
.execute())
``` | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1981/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/1981/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1980 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1980/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1980/comments | https://api.github.com/repos/coleifer/peewee/issues/1980/events | https://github.com/coleifer/peewee/issues/1980 | 474,134,172 | MDU6SXNzdWU0NzQxMzQxNzI= | 1,980 | Trouble Splitting Up Code | {
"login": "dkryptr",
"id": 13036301,
"node_id": "MDQ6VXNlcjEzMDM2MzAx",
"avatar_url": "https://avatars.githubusercontent.com/u/13036301?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/dkryptr",
"html_url": "https://github.com/dkryptr",
"followers_url": "https://api.github.com/users/dkryptr/followers",
"following_url": "https://api.github.com/users/dkryptr/following{/other_user}",
"gists_url": "https://api.github.com/users/dkryptr/gists{/gist_id}",
"starred_url": "https://api.github.com/users/dkryptr/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/dkryptr/subscriptions",
"organizations_url": "https://api.github.com/users/dkryptr/orgs",
"repos_url": "https://api.github.com/users/dkryptr/repos",
"events_url": "https://api.github.com/users/dkryptr/events{/privacy}",
"received_events_url": "https://api.github.com/users/dkryptr/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"> But the problem with this is that db is undefined.\r\n\r\nBecause you're not returning anything...\r\n\r\nThis is not peewee-specific but a general question about Python module organization. When you have dependencies like this, the typical solution is to introduce a third module that composes the two (db and main)."
] | 2019-07-29T16:05:56 | 2019-07-29T17:01:37 | 2019-07-29T17:01:37 | NONE | null | The issue I'm running into is pretty specific to my use case and I'm not sure how many it would affect. I'm creating AWS Lambda functions that insert/query from the database. I have my code separated into multiple files so that different lambda functions can re-use code. Here's a very simplified example.
db.py
```python
import os
from peewee import PeeweeException, Model, MySQLDatabase
hostname = os.environ["DB_HOST"]
username = os.environ["DB_USER"]
password = os.environ["DB_PASSWORD"]
database = os.environ["DB_DATABASE"]
try:
db = MySQLDatabase(
database=database,
user=username,
password=password,
host=hostname,
charset="utf8",
use_unicode=True,
)
except PeeweeException as e:
raise
class BaseModel(Model):
class Meta:
database = db
```
main.py
```python
import json
import os
import service
from db import db
def handler(event, context):
try:
db.connect()
response = service.run(db, event)
db.close()
except Exception as e:
return {
"statusCode": 500,
"body": json.dumps(
{
"code": "InternalFailure",
"message": "Internal server error",
}
),
}
return response
```
I'm excluding a few files(`model.py`, `service.py`) but `service.run(db, event)` imports model and inserts/queries the database using the models it imports.
The problem occurs when I try to write unit tests for main.py. Since main.py imports db, it immediately tries to read environment variables. So when my unit tests import main to test it, immediately my unit tests fail because those environment variables don't exist. I could easily mock out `os` but I don't think main.py should be calling db.py immediately anyways. So I've tried wrapping some code in db.py in a get_connection() function:
```python
def get_connection():
hostname = os.environ["DB_HOST"]
username = os.environ["DB_USER"]
password = os.environ["DB_PASSWORD"]
database = os.environ["DB_DATABASE"]
try:
db = MySQLDatabase(
database=database,
user=username,
password=password,
host=hostname,
charset="utf8",
use_unicode=True,
)
except PeeweeException as e:
raise
class BaseModel(Model):
class Meta:
database = db
```
But the problem with this is that db is undefined. Anyways, the long story short: I've tried a lot of things and I'm unable to figure it out and was wondering if you had any tips for me? | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1980/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/1980/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1979 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1979/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1979/comments | https://api.github.com/repos/coleifer/peewee/issues/1979/events | https://github.com/coleifer/peewee/issues/1979 | 474,070,965 | MDU6SXNzdWU0NzQwNzA5NjU= | 1,979 | Bulk insert with uuid foreign key | {
"login": "deissh",
"id": 21129524,
"node_id": "MDQ6VXNlcjIxMTI5NTI0",
"avatar_url": "https://avatars.githubusercontent.com/u/21129524?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/deissh",
"html_url": "https://github.com/deissh",
"followers_url": "https://api.github.com/users/deissh/followers",
"following_url": "https://api.github.com/users/deissh/following{/other_user}",
"gists_url": "https://api.github.com/users/deissh/gists{/gist_id}",
"starred_url": "https://api.github.com/users/deissh/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/deissh/subscriptions",
"organizations_url": "https://api.github.com/users/deissh/orgs",
"repos_url": "https://api.github.com/users/deissh/repos",
"events_url": "https://api.github.com/users/deissh/events{/privacy}",
"received_events_url": "https://api.github.com/users/deissh/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"Sqlite is indicating that you have a foreign-key constraint error. That is, one of the objects you are creating, is using an invalid foreign-key.\r\n\r\nPeewee attempts to convert the UUID instances in your models into their hex equivalent for storage, but it looks like one of your parameters is coming through with the dashes in place. Without seeing the \"training\" field it's hard for me to tell what's going on.",
"Added a test-case and replicated what I guess to be the bug, which is also fixed in the above commit.",
"thx\r\nits work"
] | 2019-07-29T14:04:21 | 2019-07-30T10:48:51 | 2019-07-29T16:54:05 | NONE | null | I'm using SQLite with PeeWee 3.9.6
```python3
TrainingMuscleGroups.insert_many(
[
*muscle_groups
],
fields=[
TrainingMuscleGroups.training,
TrainingMuscleGroups.muscle_group
]
).execute()
```
Models
```python3
class MuscleGroups(Model):
id = UUIDField(default=new_uuid, primary_key=True)
name = TextField(null=False, unique=True)
class TrainingMuscleGroups(Model):
id = UUIDField(default=new_uuid, primary_key=True)
muscle_group = ForeignKeyField(MuscleGroups)
```
will be an error like this
```
tests/test_a9_trainings.py:218: in fill_trainings
training = TrainingService.create(**data)
app/services/TrainingService.py:50: in create
TrainingMuscleGroups.muscle_group_id
venv/lib/python3.6/site-packages/peewee.py:1785: in inner
return method(self, database, *args, **kwargs)
venv/lib/python3.6/site-packages/peewee.py:1856: in execute
return self._execute(database)
venv/lib/python3.6/site-packages/peewee.py:2572: in _execute
return super(Insert, self)._execute(database)
venv/lib/python3.6/site-packages/peewee.py:2320: in _execute
cursor = database.execute(self)
venv/lib/python3.6/site-packages/peewee.py:2962: in execute
return self.execute_sql(sql, params, commit=commit)
venv/lib/python3.6/site-packages/peewee.py:2953: in execute_sql
raise
venv/lib/python3.6/site-packages/peewee.py:2732: in __exit__
reraise(new_type, new_type(*exc_args), traceback)
venv/lib/python3.6/site-packages/peewee.py:183: in reraise
raise value.with_traceback(tb)
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
self = <peewee.SqliteDatabase object at 0x7f7392bc8cc0>
sql = 'INSERT INTO "training_muscle_groups" ("training_id", "muscle_group_id", "id") VALUES (?, ?, ?)'
params = ['f5f44e2f-23e0-4f9f-a677-c157795b5726', 'a46e0c0658394439a6b8e3e63f3e19ac', '065675c39e304ca5b1c0a26fbdba5984']
commit = False
def execute_sql(self, sql, params=None, commit=SENTINEL):
logger.debug((sql, params))
if commit is SENTINEL:
if self.in_transaction():
commit = False
elif self.commit_select:
commit = True
else:
commit = not sql[:6].lower().startswith('select')
with __exception_wrapper__:
cursor = self.cursor(commit)
try:
> cursor.execute(sql, params or ())
E peewee.IntegrityError: FOREIGN KEY constraint failed
venv/lib/python3.6/site-packages/peewee.py:2949: IntegrityError
```
***some useless information (maybe)***
if I'm using bulk_create like this
```python3
TrainingMuscleGroups.bulk_create([
TrainingMuscleGroups(
training=training,
muscle_group_id=str(muscle_group.id) # and muscle_group=muscle_group is are eq
)
for muscle_group in muscle_groups
])
```
peewee will transform `id` field to UUIDField and finally in [`execute_sql`](https://github.com/coleifer/peewee/blob/3.9.6/peewee.py#L2936) params be like this

| {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1979/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/1979/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1978 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1978/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1978/comments | https://api.github.com/repos/coleifer/peewee/issues/1978/events | https://github.com/coleifer/peewee/issues/1978 | 473,493,095 | MDU6SXNzdWU0NzM0OTMwOTU= | 1,978 | Malformed column name returned from select() on modified field. | {
"login": "davidbernat",
"id": 5396131,
"node_id": "MDQ6VXNlcjUzOTYxMzE=",
"avatar_url": "https://avatars.githubusercontent.com/u/5396131?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/davidbernat",
"html_url": "https://github.com/davidbernat",
"followers_url": "https://api.github.com/users/davidbernat/followers",
"following_url": "https://api.github.com/users/davidbernat/following{/other_user}",
"gists_url": "https://api.github.com/users/davidbernat/gists{/gist_id}",
"starred_url": "https://api.github.com/users/davidbernat/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/davidbernat/subscriptions",
"organizations_url": "https://api.github.com/users/davidbernat/orgs",
"repos_url": "https://api.github.com/users/davidbernat/repos",
"events_url": "https://api.github.com/users/davidbernat/events{/privacy}",
"received_events_url": "https://api.github.com/users/davidbernat/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"`pw.fn.ST_AsText(PadsLocations.latlng).alias('latlng')` does return the appropriate result, as a monkey-patch.",
"Peewee relies on the driver to implement the db-api 2.0 spec. Part of this spec is that a cursor, after executing a query, contains a `description` property which tells us about the names of the columns being selected. This is determined by the database and then communicated to the driver. Presumably if you execute such a query in the mysql shell, the result column of such a function will not be \"latlng\" but something else.\r\n\r\nSo the correct thing to do, if you want to alias a function call to a given, is to explicitly specify the alias as you have done. Not a bug.\r\n\r\nConsider the case where you're grabbing a COUNT() or something. You'd have `fn.COUNT(MyModel.id)` or whatever. You wouldn't want that to default to being the value of \"MyModel.id\" ... so you explicitly alias it: `fn.COUNT(MyModel.id).alias('count')`.\r\n\r\n> as a monkey-patch\r\n\r\nlook up the definition of monkey-patch, you're using it incorrectly"
] | 2019-07-26T18:58:22 | 2019-07-26T19:32:39 | 2019-07-26T19:32:39 | NONE | null | ```
class PointField(pw.Field):
"""Geometry field type Point, conforming to MySQL 8.0+, format is WKT: 'POINT(18 23)'"""
# Field type in MySQL is Point with a capital P.
field_type = 'Point'
def python_value(self, value):
return value
def db_value(self, ewkt):
"""Converts EWKT format to MySQL database requirements, e.g., SRID=3857;POINT(10,10)"""
# Does the ewkt start with "SRID=XXXX;...".
# If so, remove the value from the geometry and parse/extract the srid
s = ewkt.split(";")
if s[0].startswith("SRID="):
geo = ";".join(s[1:])
srid = s[0].split("=")[1]
return pw.fn.ST_GeomFromText(geo, srid)
else:
return pw.fn.ST_GeomFromText(ewkt)
```
```
class PadsLocations(AetherDataModel):
name = pw.CharField(max_length=255, index=True)
latlng = PointField()
operator = pw.BooleanField()
operator_name = pw.CharField(max_length=255, index=True)
```
```
s = PadsLocations.select(PadsLocations.name, pw.fn.ST_AsText(PadsLocations.latlng))
for r in adf.read(s):
print(r.name, r.latlng)
```
`r.latlng` returns None. This is because the correct value returns with a key of "\`latlng)`".
| {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1978/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/1978/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1977 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1977/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1977/comments | https://api.github.com/repos/coleifer/peewee/issues/1977/events | https://github.com/coleifer/peewee/issues/1977 | 472,497,675 | MDU6SXNzdWU0NzI0OTc2NzU= | 1,977 | SchemaMigrator.add_column problem | {
"login": "richey-v",
"id": 6144958,
"node_id": "MDQ6VXNlcjYxNDQ5NTg=",
"avatar_url": "https://avatars.githubusercontent.com/u/6144958?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/richey-v",
"html_url": "https://github.com/richey-v",
"followers_url": "https://api.github.com/users/richey-v/followers",
"following_url": "https://api.github.com/users/richey-v/following{/other_user}",
"gists_url": "https://api.github.com/users/richey-v/gists{/gist_id}",
"starred_url": "https://api.github.com/users/richey-v/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/richey-v/subscriptions",
"organizations_url": "https://api.github.com/users/richey-v/orgs",
"repos_url": "https://api.github.com/users/richey-v/repos",
"events_url": "https://api.github.com/users/richey-v/events{/privacy}",
"received_events_url": "https://api.github.com/users/richey-v/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"What difference does it make what order the column is in the underlying storage? Absolutely none, truthfully."
] | 2019-07-24T20:17:14 | 2019-07-24T20:52:42 | 2019-07-24T20:52:42 | NONE | null | (using peewee 3.9.6 with sqlite3)
I am assuming the problem that I am reporting may be difficult to fix, so this Issue might be best resolved by adding a note to the relevant [documentation](http://docs.peewee-orm.com/en/latest/peewee/playhouse.html#SchemaMigrator.add_column).
I needed a new Field in a Model and I naively added the new Field _in between_ two other Fields. I wanted to provide a migration for the new Field on this Model, so I used `add_column`. The new Field was *inserted* in between the other two Fields, but the column for the data was added at the *end* of each row for the Model.
Ideally, `add_column` gets fixed to put the new data column in the correct position, but if that is too difficult or takes a long time to be fixed, _please_ add a note recommending that new Fields be added after the last old Field. | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1977/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/1977/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1976 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1976/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1976/comments | https://api.github.com/repos/coleifer/peewee/issues/1976/events | https://github.com/coleifer/peewee/pull/1976 | 472,239,821 | MDExOlB1bGxSZXF1ZXN0MzAwNjg4ODE1 | 1,976 | Avoid situations where connections have same ts. | {
"login": "itsmeczaharia",
"id": 18571895,
"node_id": "MDQ6VXNlcjE4NTcxODk1",
"avatar_url": "https://avatars.githubusercontent.com/u/18571895?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/itsmeczaharia",
"html_url": "https://github.com/itsmeczaharia",
"followers_url": "https://api.github.com/users/itsmeczaharia/followers",
"following_url": "https://api.github.com/users/itsmeczaharia/following{/other_user}",
"gists_url": "https://api.github.com/users/itsmeczaharia/gists{/gist_id}",
"starred_url": "https://api.github.com/users/itsmeczaharia/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/itsmeczaharia/subscriptions",
"organizations_url": "https://api.github.com/users/itsmeczaharia/orgs",
"repos_url": "https://api.github.com/users/itsmeczaharia/repos",
"events_url": "https://api.github.com/users/itsmeczaharia/events{/privacy}",
"received_events_url": "https://api.github.com/users/itsmeczaharia/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"What's odd is that `time.time()` has microsecond precision on my machine. Granted, calling `time.time()` appears to take only ~80ns, but still there's a lot of stuff going on that would seem to make identical timestamps an impossibility. I'm fine with merging, but I can't wrap my head around how this could happen in the first place.",
"Fixed and merged an equivalent (but not broken) patch."
] | 2019-07-24T11:52:23 | 2019-07-24T14:37:51 | 2019-07-24T14:37:50 | NONE | null | Hello,
I was able to reproduce the bug from this issue: https://github.com/coleifer/peewee/issues/1883
Adding a small random number to ts, avoids that race condition. | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1976/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/1976/timeline | null | null | false | {
"url": "https://api.github.com/repos/coleifer/peewee/pulls/1976",
"html_url": "https://github.com/coleifer/peewee/pull/1976",
"diff_url": "https://github.com/coleifer/peewee/pull/1976.diff",
"patch_url": "https://github.com/coleifer/peewee/pull/1976.patch",
"merged_at": null
} |
https://api.github.com/repos/coleifer/peewee/issues/1975 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1975/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1975/comments | https://api.github.com/repos/coleifer/peewee/issues/1975/events | https://github.com/coleifer/peewee/issues/1975 | 472,038,588 | MDU6SXNzdWU0NzIwMzg1ODg= | 1,975 | Cannot work with VIEWs in SQLite | {
"login": "erakli",
"id": 11831470,
"node_id": "MDQ6VXNlcjExODMxNDcw",
"avatar_url": "https://avatars.githubusercontent.com/u/11831470?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/erakli",
"html_url": "https://github.com/erakli",
"followers_url": "https://api.github.com/users/erakli/followers",
"following_url": "https://api.github.com/users/erakli/following{/other_user}",
"gists_url": "https://api.github.com/users/erakli/gists{/gist_id}",
"starred_url": "https://api.github.com/users/erakli/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/erakli/subscriptions",
"organizations_url": "https://api.github.com/users/erakli/orgs",
"repos_url": "https://api.github.com/users/erakli/repos",
"events_url": "https://api.github.com/users/erakli/events{/privacy}",
"received_events_url": "https://api.github.com/users/erakli/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"My guess is you're using an ancient version of sqlite. Try this and check the output:\r\n\r\n```python\r\n>>> import sqlite3\r\n>>> sqlite3.sqlite_version # My version is quite new.\r\n'3.29.0'\r\n```\r\n\r\nYou need to upgrade your sqlite for peewee to properly infer the column names.\r\n\r\nFor example, the following works fine on my machine:\r\n\r\n```python\r\ndb = SqliteDatabase(':memory:')\r\n\r\nclass Register(Model):\r\n key = TextField()\r\n value = IntegerField()\r\n class Meta:\r\n database = db\r\n\r\ndb.create_tables([Register])\r\n\r\nRegister.insert_many([('k%02d' % i, i) for i in range(100)]).execute()\r\n\r\ndb.execute_sql('create view \"small_reg\" as '\r\n 'select id, key, value from register '\r\n 'where value < 13')\r\n\r\nclass SmallReg(Register):\r\n class Meta:\r\n table_name = 'small_reg'\r\n\r\nquery = SmallReg.select()\r\nfor obj in query:\r\n print (obj.id, obj.key, obj.value)\r\n```",
"Yes, I have SQLite 3.11.0.\r\n\r\nWhat minimal version is supported by peewee?\r\n\r\n> On 24 Jul 2019, at 05:02, Charles Leifer <[email protected]> wrote:\r\n> \r\n> Closed #1975.\r\n> \r\n> —\r\n> You are receiving this because you authored the thread.\r\n> Reply to this email directly, view it on GitHub, or mute the thread.\r\n",
"That's actually not as old as I would have thought. I'm compiling an older sqlite and am going to check it out some more.",
"So here's what's happening... Peewee makes use of database drivers implementing the db-api 2.0 spec (psycopg2, stdlib sqlite3, pymysql, etc). After executing a query using a cursor, the cursor exposes a `description` property that tells you the names of the selected columns.\r\n\r\nIn my above example, the `cursor.description` (as reported by the sqlite3 driver) is:\r\n\r\n```python\r\n>>> cursor.description \r\n(('t1', None, None, None, None, None, None), ('t1', None, None, None, None, None, None), ('t1', None, None, None, None, None, None))\r\n```\r\n\r\nThe column names reported by the driver use the `sqlite3_column_name()` API. Seems like this behavior changed... I'll do some more digging.",
"I'm not sure why sqlite is behaving differently when using a view versus a regular table -- because it works as one would expect when querying a table. I suppose for now you can use a workaround of just explicitly aliasing the fields you select, or possibly try upgrading to a more recent sqlite?",
"Thanks for your advises and fast response, I appreciate this. \r\n\r\nI'll probably use aliases as a workaround because it would be more bulletproof. For now it works, thank you!\r\n\r\n```python\r\n>>> store_items_view.select(store_items_view.color_id.alias('color_id')).get()\r\n<store_items_view: (None, 11, None, None, None, None, None)>\r\n>>> print(store_items_view.select(store_items_view.color_id.alias('color_id')))\r\nSELECT \"t1\".\"color_id\" AS \"color_id\" FROM \"store_items_view\" AS \"t1\"\r\n```\r\nIs there any short-cut to define aliases in a compact way?\r\n\r\nFYI, SQLA always defines aliases for every column. Probably, peewee need to do the same?",
"I've patched this -- we use a more aggressive approach to slotting selected columns into the appropriate field slot. Tested it with sqlite 3.9 and verified it is working as expected.",
"> SQLA always defines aliases for every column\r\n\r\nShould be no need to do this, honestly, except maybe for old versions of sqlite. I think I'll pass on that for now.",
"So, I could expect fixed behavior in next release?\n\n> On 24 Jul 2019, at 17:35, Charles Leifer <[email protected]> wrote:\n> \n> I've patched this -- we use a more aggressive approach to slotting selected columns into the appropriate field slot. Tested it with sqlite 3.9 and verified it is working as expected.\n> \n> —\n> You are receiving this because you authored the thread.\n> Reply to this email directly, view it on GitHub, or mute the thread.\n",
"yea",
"Great! Thank you. \n\n> On 24 Jul 2019, at 17:57, Charles Leifer <[email protected]> wrote:\n> \n> yea\n> \n> —\n> You are receiving this because you authored the thread.\n> Reply to this email directly, view it on GitHub, or mute the thread.\n"
] | 2019-07-24T01:40:06 | 2019-07-24T15:21:20 | 2019-07-24T12:24:19 | NONE | null | I tried to use peewee to select from view. I reflected view
```python
>>> models = generate_models(db, include_views=True)
>>> globals().update(models)
>>> print_model(store_items_view)
store_items_view
item_no TEXT
color_id INT
new_or_used TEXT
completeness TEXT
quantity DEFAULT
unit_price INT
last_date DEFAULT
```
Then I tried to get anything from it
```python
>>> store_items_view.get()
<store_items_view: (None, None, None, None, None, None, None)>
```
If we inspect fields of returned instance, we found that all of them are empty. More interesting that `t1` field added:
```python
>>> store_items_view.get().t1
'10039c01'
```
SQL generated for `store_items_view.select()`:
```sql
SELECT
"t1"."item_no",
"t1"."color_id",
"t1"."new_or_used",
"t1"."completeness",
"t1"."quantity",
"t1"."unit_price",
"t1"."last_date"
FROM "store_items_view" AS "t1"
```
Maybe the problem is in quoted `"t1"` prefix?
peewee 3.9.6 | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1975/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/1975/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1974 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1974/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1974/comments | https://api.github.com/repos/coleifer/peewee/issues/1974/events | https://github.com/coleifer/peewee/issues/1974 | 471,889,847 | MDU6SXNzdWU0NzE4ODk4NDc= | 1,974 | Unecessary index on table creation | {
"login": "lucianobarcaro",
"id": 833149,
"node_id": "MDQ6VXNlcjgzMzE0OQ==",
"avatar_url": "https://avatars.githubusercontent.com/u/833149?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/lucianobarcaro",
"html_url": "https://github.com/lucianobarcaro",
"followers_url": "https://api.github.com/users/lucianobarcaro/followers",
"following_url": "https://api.github.com/users/lucianobarcaro/following{/other_user}",
"gists_url": "https://api.github.com/users/lucianobarcaro/gists{/gist_id}",
"starred_url": "https://api.github.com/users/lucianobarcaro/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/lucianobarcaro/subscriptions",
"organizations_url": "https://api.github.com/users/lucianobarcaro/orgs",
"repos_url": "https://api.github.com/users/lucianobarcaro/repos",
"events_url": "https://api.github.com/users/lucianobarcaro/events{/privacy}",
"received_events_url": "https://api.github.com/users/lucianobarcaro/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"You're welcome to override the default foreign-key index creation, by specifying `index=False` explicitly in the `ForeignKeyField` declaration/initialization.\r\n\r\nYou might double-check your information, however, to make sure that you actually *do* have an index on `user_id` in the referring table (`UserAccess`)."
] | 2019-07-23T19:31:51 | 2019-07-23T20:37:42 | 2019-07-23T20:37:42 | NONE | null | I'm new to peewee (2 weeks now) and I noted an unecessary index on table creation.
Simple case:
```
class Usuario(BaseModel):
nome = CharField()
class UsuarioAcesso(BaseModel):
usuario = ForeignKeyField(Usuario)
dataAcesso = DateTimeField()
fromIP = CharField()
class Meta:
primary_key = CompositeKey('usuario', 'dataAcesso')
```
On table UsuarioAcesso, peewee create 2 indexes:
Primary key as expected (usuario_id, dataAcesso)
and
usuario_acesso_usuario_id (usuario_id)
This second index is already covered with primary key (on MySQL/MariaDB, foreign keys works as expected with just primary key here).
Am I missing something?
Best regards :) | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1974/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/1974/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1973 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1973/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1973/comments | https://api.github.com/repos/coleifer/peewee/issues/1973/events | https://github.com/coleifer/peewee/issues/1973 | 471,652,489 | MDU6SXNzdWU0NzE2NTI0ODk= | 1,973 | shortcuts.model_to_dict convert 0 to None in ForeignKeyField unless recurse == False | {
"login": "duvifn",
"id": 17128619,
"node_id": "MDQ6VXNlcjE3MTI4NjE5",
"avatar_url": "https://avatars.githubusercontent.com/u/17128619?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/duvifn",
"html_url": "https://github.com/duvifn",
"followers_url": "https://api.github.com/users/duvifn/followers",
"following_url": "https://api.github.com/users/duvifn/following{/other_user}",
"gists_url": "https://api.github.com/users/duvifn/gists{/gist_id}",
"starred_url": "https://api.github.com/users/duvifn/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/duvifn/subscriptions",
"organizations_url": "https://api.github.com/users/duvifn/orgs",
"repos_url": "https://api.github.com/users/duvifn/repos",
"events_url": "https://api.github.com/users/duvifn/events{/privacy}",
"received_events_url": "https://api.github.com/users/duvifn/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"Thanks!"
] | 2019-07-23T11:52:29 | 2019-07-23T12:42:41 | 2019-07-23T12:31:46 | NONE | null | ```python
import peewee
from playhouse.shortcuts import model_to_dict
database = peewee.PostgresqlDatabase(
'temp_db',
....
)
database.connect()
class Group (peewee.Model):
id = peewee.BigIntegerField(null= False, index = True, unique = True, primary_key = True)
class Meta():
database = database
class User (peewee.Model):
id = peewee.BigIntegerField(null= False, index = True, unique = True, primary_key = True)
group_id = peewee.ForeignKeyField(Group, null = False)
class Meta():
database = database
database.create_tables([Group, User])
Group.create(id = 0)
User.create(id = 0, group_id = 0)
print (model_to_dict(User.get_by_id(0))['group_id'] == 0) # False
print (model_to_dict(User.get_by_id(0), False)['group_id'] == 0) #True
```
| {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1973/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/1973/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1972 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1972/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1972/comments | https://api.github.com/repos/coleifer/peewee/issues/1972/events | https://github.com/coleifer/peewee/issues/1972 | 470,936,876 | MDU6SXNzdWU0NzA5MzY4NzY= | 1,972 | Postgres transaction isolation level | {
"login": "duvifn",
"id": 17128619,
"node_id": "MDQ6VXNlcjE3MTI4NjE5",
"avatar_url": "https://avatars.githubusercontent.com/u/17128619?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/duvifn",
"html_url": "https://github.com/duvifn",
"followers_url": "https://api.github.com/users/duvifn/followers",
"following_url": "https://api.github.com/users/duvifn/following{/other_user}",
"gists_url": "https://api.github.com/users/duvifn/gists{/gist_id}",
"starred_url": "https://api.github.com/users/duvifn/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/duvifn/subscriptions",
"organizations_url": "https://api.github.com/users/duvifn/orgs",
"repos_url": "https://api.github.com/users/duvifn/repos",
"events_url": "https://api.github.com/users/duvifn/events{/privacy}",
"received_events_url": "https://api.github.com/users/duvifn/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"The underlying psycopg2 connection class is exposed as `db.connection()`, e.g.\r\n\r\n```python\r\ndb = PostgresqlDatabase('my_app')\r\nconn = db.connection() # returns current conn, opening one if necessary\r\n```\r\n\r\nThen use the psycopg2 apis to set the isolation level:\r\n\r\n```python\r\nfrom psycopg2 import extensions\r\nconn.set_isolation_level(extensions.ISOLATION_LEVEL_REPEATABLE_READ)\r\n```\r\n\r\nYou can put all this in a hook provided by peewee and executed automatically when a new connection is created.\r\n\r\n```python\r\n\r\nclass RCPostgresqlDatabase(PostgresqlDatabase):\r\n def _initialize_connection(self, conn):\r\n conn.set_isolation_level(...)\r\n```\r\n\r\nThis hook is called whenever a new connection is opened, so its probably what you're looking for.",
"Added support for passing this into the PostgresqlDatabase `__init__()` method in master, will be available in the next release.",
"@coleifer Thanks for the quick response and the code addition!\r\n\r\nDo you have any plan to add isolation level as a parameter to `db.atomic()` or `db.transaction()` in the future? Sometimes per-transaction config is needed rather than per-session....\r\n",
"Not really, it seems from the psycopg2 docs that when you set the isolation level it is for the duration of the session, so there doesn't seem to be an API that is just for the lifetime of a transaction. Because of this, I'm inclined to leave it as an exercise to the reader to implement a context-manager or whatever you need.",
"```python\r\n@contextmanager\r\ndef isolation(level):\r\n conn = db.connection()\r\n orig = conn.isolation_level\r\n conn.set_isolation_level(level)\r\n try:\r\n with db.atomic() as txn:\r\n yield txn\r\n finally:\r\n conn.set_isolation_level(orig)\r\n```\r\n\r\nSomething like this?",
"OK. Thanks again.\r\n\r\nIn case someone else will encounter this thread - another possible option (which i didn't try) is to use raw [`SET TRANSACTION`](https://www.postgresql.org/docs/9.5/sql-set-transaction.html) statement which should be ran before any other query in the transaction."
] | 2019-07-22T07:28:43 | 2019-07-22T11:13:25 | 2019-07-22T09:21:37 | NONE | null | Hi,
Probably I'm missing something but I couldn't find a way to specify transaction isolation level for Postgres (default to [`Read committed`](https://www.postgresql.org/docs/9.5/transaction-iso.html) which is not sufficient for my use case - in which `Repeatable read` is needed).
Any way to workaround it (without changing postgres config or manually open transaction)?
Thanks a lot! | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1972/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/1972/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1971 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1971/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1971/comments | https://api.github.com/repos/coleifer/peewee/issues/1971/events | https://github.com/coleifer/peewee/issues/1971 | 468,036,299 | MDU6SXNzdWU0NjgwMzYyOTk= | 1,971 | what's the alternative usage of ReadSlaveModel | {
"login": "kaka19ace",
"id": 1320568,
"node_id": "MDQ6VXNlcjEzMjA1Njg=",
"avatar_url": "https://avatars.githubusercontent.com/u/1320568?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/kaka19ace",
"html_url": "https://github.com/kaka19ace",
"followers_url": "https://api.github.com/users/kaka19ace/followers",
"following_url": "https://api.github.com/users/kaka19ace/following{/other_user}",
"gists_url": "https://api.github.com/users/kaka19ace/gists{/gist_id}",
"starred_url": "https://api.github.com/users/kaka19ace/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/kaka19ace/subscriptions",
"organizations_url": "https://api.github.com/users/kaka19ace/orgs",
"repos_url": "https://api.github.com/users/kaka19ace/repos",
"events_url": "https://api.github.com/users/kaka19ace/events{/privacy}",
"received_events_url": "https://api.github.com/users/kaka19ace/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"Instead of this, Peewee 3.x instead provides some really nice APIs for switching the database around at run-time.\r\n\r\n* http://docs.peewee-orm.com/en/latest/peewee/api.html#Database.bind_ctx\r\n* http://docs.peewee-orm.com/en/latest/peewee/api.html#Model.bind_ctx"
] | 2019-07-15T09:50:10 | 2019-07-15T17:26:26 | 2019-07-15T17:26:26 | NONE | null | hi, peewee playhouse 3.x version has no longer support read_slave,
and what's the alternative usage? | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1971/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/1971/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1970 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1970/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1970/comments | https://api.github.com/repos/coleifer/peewee/issues/1970/events | https://github.com/coleifer/peewee/issues/1970 | 467,617,747 | MDU6SXNzdWU0Njc2MTc3NDc= | 1,970 | Init db instance later | {
"login": "danieldaeschle",
"id": 30751516,
"node_id": "MDQ6VXNlcjMwNzUxNTE2",
"avatar_url": "https://avatars.githubusercontent.com/u/30751516?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/danieldaeschle",
"html_url": "https://github.com/danieldaeschle",
"followers_url": "https://api.github.com/users/danieldaeschle/followers",
"following_url": "https://api.github.com/users/danieldaeschle/following{/other_user}",
"gists_url": "https://api.github.com/users/danieldaeschle/gists{/gist_id}",
"starred_url": "https://api.github.com/users/danieldaeschle/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/danieldaeschle/subscriptions",
"organizations_url": "https://api.github.com/users/danieldaeschle/orgs",
"repos_url": "https://api.github.com/users/danieldaeschle/repos",
"events_url": "https://api.github.com/users/danieldaeschle/events{/privacy}",
"received_events_url": "https://api.github.com/users/danieldaeschle/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"Read the docs.\r\n\r\nhttp://docs.peewee-orm.com/en/latest/peewee/database.html#run-time-database-configuration"
] | 2019-07-12T22:05:07 | 2019-07-13T02:30:20 | 2019-07-13T02:30:19 | NONE | null | Is there any chance to initalize the database instance later?
When i want to create a MysqlDatabase i must give the "database" parameter.
But at the point of creating the instance i don't know it.
But i have to create the instance to create the models.
A better way for me would be to define the models without depend on the db instance.
Is there a way to add the models later to the db instance? | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1970/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/1970/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1969 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1969/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1969/comments | https://api.github.com/repos/coleifer/peewee/issues/1969/events | https://github.com/coleifer/peewee/issues/1969 | 466,002,450 | MDU6SXNzdWU0NjYwMDI0NTA= | 1,969 | Hybrid methods not using table aliases | {
"login": "mikemill",
"id": 1652125,
"node_id": "MDQ6VXNlcjE2NTIxMjU=",
"avatar_url": "https://avatars.githubusercontent.com/u/1652125?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/mikemill",
"html_url": "https://github.com/mikemill",
"followers_url": "https://api.github.com/users/mikemill/followers",
"following_url": "https://api.github.com/users/mikemill/following{/other_user}",
"gists_url": "https://api.github.com/users/mikemill/gists{/gist_id}",
"starred_url": "https://api.github.com/users/mikemill/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/mikemill/subscriptions",
"organizations_url": "https://api.github.com/users/mikemill/orgs",
"repos_url": "https://api.github.com/users/mikemill/repos",
"events_url": "https://api.github.com/users/mikemill/events{/privacy}",
"received_events_url": "https://api.github.com/users/mikemill/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"Well, the problem is either the descriptor protocol, or the implementation of `ModelAlias`.\r\n\r\nI find it simpler to look at this example, which I'm going to walk through just to get it all out in front of me to look at:\r\n\r\n```python\r\nclass Interval(Model):\r\n start = IntegerField()\r\n end = IntegerField()\r\n\r\n @hybrid_property\r\n def length(self):\r\n return self.end - self.start\r\n```\r\n\r\nThe `length` attribute implements the descriptor protocol, so it has `__get__()` which is called when the attribute is accessed as either a class attribute or instance attribute. `hybrid_property` is the simple case where we can pass either the model class or a model instance into the `length()` function as `self`.\r\n\r\nSo we either end up with:\r\n\r\n```python\r\nInterval.length -> length(self=Interval) -> Interval.end - Interval.start\r\n\r\nobj = Interval()\r\nobj.length -> length(self=obj) -> obj.end - obj.start\r\n```\r\n\r\nModel aliases are not subclasses of the model being aliased (though perhaps they ought to be) -- rather they are implemented as a simple proxy object. So when you look up the length attribute on a model alias, you get:\r\n\r\n```python\r\nIA = Interval.alias()\r\nIA.length -> ModelAlias(model=Interval) -> self.model.length -> length(self=Interval)\r\n```\r\n\r\nI'm not sure how to fix this one off the top of my head.",
"So it's possible to look at the model's `__dict__` while resolving the attribute on the alias, and then (if it's a hybrid property) explicitly passing `self` instead of `self.model` into the appropriate method on the `hybrid_property` instance....but...yuck.",
"Oh, I think I recall one of the reasons why we aren't doing model aliases as dynamically-created subclasses -- because of side-effects that occur when you declare foreign-keys in a derived class. So you subclass a model that has a foreign-key, it adds some stuff to the related model's metadata.\r\n\r\n```python\r\nclass User(Model):\r\n username = TextField()\r\n\r\nclass Tweet(Model):\r\n user = ForeignKeyField(User, backref='tweets')\r\n content = TextField()\r\n\r\nclass SubTweet(Tweet):\r\n pass\r\n\r\n# Now User._meta.backrefs contains a reference to \"SubTweet.user\", e.g.\r\n```",
"That said, getting rid of ModelAlias would remove some rather yucky conditionals and things... Probably be a really big win if I can pin down these side-effects and handle them nicely. Just thinking out loud.",
"I'm gonna leave this with the patch from 9e4f1fa at the moment."
] | 2019-07-09T21:55:49 | 2019-07-23T17:14:07 | 2019-07-23T17:14:07 | NONE | null | Peewee 3.8.2
I'm using a hybrid_method to simplify my querying. I found, however, that it ignores table aliases. In my use case the table has a foreign key to itself and I need to check the dates on the joined table and not on the parent table.
Here is an example script:
```python
from datetime import date
from peewee import DateField, ForeignKeyField, IntegerField, Model
from playhouse.hybrid import hybrid_method
from .database import db
class DateTest(Model):
value = IntegerField()
start = DateField(default=date.today)
finish = DateField(null=True)
parent = ForeignKeyField('self', null=True, on_delete='SET NULL')
@hybrid_method
def current_on(self, date):
return self.start <= date and (self.finish is None or self.finish >= date)
@current_on.expression
def current_on(cls, date):
return (cls.start <= date) & (cls.finish.is_null(True) | (cls.finish >= date))
class Meta:
database = db
if __name__ == '__main__':
db.create_tables([DateTest], safe=True)
parent = DateTest.create(value=123)
child = DateTest.create(value=456, parent=parent)
query = (
DateTest.select()
.where(DateTest.current_on(date.today()))
)
print(query.sql())
Child = DateTest.alias()
query2 = (
DateTest.select()
.join(Child)
.where(Child.current_on(date.today()))
)
print(query2.sql())
```
The output is:
```
('SELECT `t1`.`id`, `t1`.`value`, `t1`.`start`, `t1`.`finish`, `t1`.`parent_id` FROM `datetest` AS `t1` WHERE ((`t1`.`start` >= %s) AND (((`t1`.`finish` IS %s) OR `t1`.`finish`) <= %s))', [datetime.date(2019, 7, 9), None, datetime.date(2019, 7, 9)])
('SELECT `t1`.`id`, `t1`.`value`, `t1`.`start`, `t1`.`finish`, `t1`.`parent_id` FROM `datetest` AS `t1` INNER JOIN `datetest` AS `t2` ON (`t1`.`parent_id` = `t2`.`id`) WHERE ((`t1`.`start` >= %s) AND (((`t1`.`finish` IS %s) OR `t1`.`finish`) <= %s))', [datetime.date(2019, 7, 9), None, datetime.date(2019, 7, 9)])
```
As you can see in the second query, it is using `t1` instead of `t2` for the `current_on` expression.
Looking at the parameters to `current_on` I don't see how I could detect that an alias was used to change the results. | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1969/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/1969/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1968 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1968/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1968/comments | https://api.github.com/repos/coleifer/peewee/issues/1968/events | https://github.com/coleifer/peewee/issues/1968 | 464,456,433 | MDU6SXNzdWU0NjQ0NTY0MzM= | 1,968 | Get the original SQL statement | {
"login": "ztj1993",
"id": 13493380,
"node_id": "MDQ6VXNlcjEzNDkzMzgw",
"avatar_url": "https://avatars.githubusercontent.com/u/13493380?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/ztj1993",
"html_url": "https://github.com/ztj1993",
"followers_url": "https://api.github.com/users/ztj1993/followers",
"following_url": "https://api.github.com/users/ztj1993/following{/other_user}",
"gists_url": "https://api.github.com/users/ztj1993/gists{/gist_id}",
"starred_url": "https://api.github.com/users/ztj1993/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/ztj1993/subscriptions",
"organizations_url": "https://api.github.com/users/ztj1993/orgs",
"repos_url": "https://api.github.com/users/ztj1993/repos",
"events_url": "https://api.github.com/users/ztj1993/events{/privacy}",
"received_events_url": "https://api.github.com/users/ztj1993/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"Peewee issues parameterized queries. All the db drivers peewee works with out-of-the-box support this, so the `.sql()` method returns the query and the params, which is exactly what is sent to the db.\r\n\r\nIf you want to try, you can use `peewee.query_to_string(q)` which will interpolate the parameters, but this is obviously vulnerable to sql injection and is only provided for debugging."
] | 2019-07-05T04:29:37 | 2019-07-05T12:20:05 | 2019-07-05T12:20:04 | NONE | null | I execute the code:
```
sql = AdModel.select(AdModel.id).where(AdModel.status == 9,).sql()
print(sql)
```
The output is:
```
('SELECT `t1`.`id` FROM `ht_silo`.`ht_ad` AS `t1` WHERE (`t1`.`status` = %s)', [9])
```
How to output:
```
SELECT `t1`.`id` FROM `ht_silo`.`ht_ad` AS `t1` WHERE (`t1`.`status` = '9')
```
Thank you! | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1968/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/1968/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1967 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1967/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1967/comments | https://api.github.com/repos/coleifer/peewee/issues/1967/events | https://github.com/coleifer/peewee/issues/1967 | 464,185,916 | MDU6SXNzdWU0NjQxODU5MTY= | 1,967 | Matching peewee with vuex-orm | {
"login": "dsmurrell",
"id": 4035854,
"node_id": "MDQ6VXNlcjQwMzU4NTQ=",
"avatar_url": "https://avatars.githubusercontent.com/u/4035854?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/dsmurrell",
"html_url": "https://github.com/dsmurrell",
"followers_url": "https://api.github.com/users/dsmurrell/followers",
"following_url": "https://api.github.com/users/dsmurrell/following{/other_user}",
"gists_url": "https://api.github.com/users/dsmurrell/gists{/gist_id}",
"starred_url": "https://api.github.com/users/dsmurrell/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/dsmurrell/subscriptions",
"organizations_url": "https://api.github.com/users/dsmurrell/orgs",
"repos_url": "https://api.github.com/users/dsmurrell/repos",
"events_url": "https://api.github.com/users/dsmurrell/events{/privacy}",
"received_events_url": "https://api.github.com/users/dsmurrell/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"`model_to_dict` is a convenience helper, but people definitely tend to treat it as the be-all/end-all of putting their model data in a dict.\r\n\r\nYou can try excluding the `study` field and specifying `extra_attrs=['study_id']` which will use the built-in foreign-key object ID accessor. That may work.",
"Thanks, I'll give that a go!"
] | 2019-07-04T10:16:32 | 2019-07-04T18:05:04 | 2019-07-04T16:50:58 | NONE | null | I realise that it's not your problem to match peewee with random frontend tools... however, I'm wondering whether there is a simple solution that already exists but which I don't know about that can adequately match what peewee returns with what this specific frontend tool wants.
For models Studies and Surveys, where a survey belongs to a study, if I used the code:
`jsonify({'surveys': list(query.dicts())}`
to return a list of surveys, or
`survey = query[0]`
`jsonify({'survey': model_to_dict(survey, recurse=False)})`
to return a single survey...
The key which represents the study in the dictionary is 'study', but in both instances (in the second because `recurse=False` is used) the value is the study's id. For example:
`{
"description": "The is the Skin Pre-survey",
"id": "r7mzY2A8uMZv4R67Ca9tFF",
"study": "UQMKsya34CyKWMA7Y4ZWpX",
"title": "Skin Pre Survey"
}`
Is there any way to configure peewee to return a key of 'study_id' instead of 'study' here? As this would mean that the naming on the client side orm can be 'study_id' for the id, and 'study' for the related study. i.e. I can say survey.study_id and survey.study in the client side code which is far more readable.
Currently, to get around this we've mapped the id onto study and the object onto study_obj and this causes confusion.
I realise that we could get around this with bit of transforming at any point in the chain, but this would require extra lines of code for each foreign key in our schema and be an additional maintenance issue.
If this functionality doesn't exist already, we're happy to add it if you think it useful. Where about would be the best place to add this? | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1967/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/1967/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1966 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1966/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1966/comments | https://api.github.com/repos/coleifer/peewee/issues/1966/events | https://github.com/coleifer/peewee/issues/1966 | 464,110,754 | MDU6SXNzdWU0NjQxMTA3NTQ= | 1,966 | Can peewee create relations but without foreign key constraint? | {
"login": "ethanlinys",
"id": 18170680,
"node_id": "MDQ6VXNlcjE4MTcwNjgw",
"avatar_url": "https://avatars.githubusercontent.com/u/18170680?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/ethanlinys",
"html_url": "https://github.com/ethanlinys",
"followers_url": "https://api.github.com/users/ethanlinys/followers",
"following_url": "https://api.github.com/users/ethanlinys/following{/other_user}",
"gists_url": "https://api.github.com/users/ethanlinys/gists{/gist_id}",
"starred_url": "https://api.github.com/users/ethanlinys/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/ethanlinys/subscriptions",
"organizations_url": "https://api.github.com/users/ethanlinys/orgs",
"repos_url": "https://api.github.com/users/ethanlinys/repos",
"events_url": "https://api.github.com/users/ethanlinys/events{/privacy}",
"received_events_url": "https://api.github.com/users/ethanlinys/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"I don't really understand, nor am I familiar w/SQLAlchemy, so the code example makes no sense to me.\r\n\r\nIn short, if you want a foreign-key, use the foreign key field.\r\n\r\nIf not, use an `IntegerField` and add a property to your model class.\r\n\r\n```python\r\nclass Tweet(Model):\r\n user_id = IntegerField()\r\n\r\n @property\r\n def user(self):\r\n return User.get(User.id == self.user_id)\r\n```\r\n\r\nBut I have no idea why you would want to do this.",
"Yes, you can.\r\n\r\n`myfield = peewee.ForeignKeyField(OtherModel, lazy_load=True, _deferred=True)`\r\n\r\nI can confirm `_deferred` does not generate shit like\r\n\r\n```\r\n FOREIGN KEY (`myfield_id`) REFERENCES `othermodel` (`id`)\r\n```"
] | 2019-07-04T07:33:37 | 2021-12-24T07:02:13 | 2019-07-04T16:38:03 | NONE | null | In sqlalchemy I can do like below. [https://stackoverflow.com/questions/37806625/sqlalchemy-create-relations-but-without-foreign-key-constraint-in-db](url)
```
In [2]: class A(Base):
...: a_id = Column(Integer, primary_key=True)
...: __tablename__ = 'a'
...:
In [3]: class C(Base):
...: c_id = Column(Integer, primary_key=True)
...: a_id = Column(Integer)
...: __tablename__ = 'c'
...: a = relationship('A', foreign_keys=[a_id],
...: primaryjoin='A.a_id == C.a_id')
```
How can I do this by peewee? | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1966/reactions",
"total_count": 3,
"+1": 2,
"-1": 0,
"laugh": 0,
"hooray": 0,
"confused": 0,
"heart": 0,
"rocket": 0,
"eyes": 1
} | https://api.github.com/repos/coleifer/peewee/issues/1966/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1965 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1965/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1965/comments | https://api.github.com/repos/coleifer/peewee/issues/1965/events | https://github.com/coleifer/peewee/issues/1965 | 463,844,555 | MDU6SXNzdWU0NjM4NDQ1NTU= | 1,965 | Postgres field extension - inet data type | {
"login": "danielguardicore",
"id": 15857396,
"node_id": "MDQ6VXNlcjE1ODU3Mzk2",
"avatar_url": "https://avatars.githubusercontent.com/u/15857396?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/danielguardicore",
"html_url": "https://github.com/danielguardicore",
"followers_url": "https://api.github.com/users/danielguardicore/followers",
"following_url": "https://api.github.com/users/danielguardicore/following{/other_user}",
"gists_url": "https://api.github.com/users/danielguardicore/gists{/gist_id}",
"starred_url": "https://api.github.com/users/danielguardicore/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/danielguardicore/subscriptions",
"organizations_url": "https://api.github.com/users/danielguardicore/orgs",
"repos_url": "https://api.github.com/users/danielguardicore/repos",
"events_url": "https://api.github.com/users/danielguardicore/events{/privacy}",
"received_events_url": "https://api.github.com/users/danielguardicore/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"```python\r\nclass SomeField(Field):\r\n field_type = 'inet'\r\n```\r\n\r\nIf you require conversion from python data-types to db-friendly data-types, you would implement `python_value()` and `db_value()` as needed.\r\n\r\nhttp://docs.peewee-orm.com/en/latest/peewee/models.html#custom-fields"
] | 2019-07-03T16:23:50 | 2019-07-03T18:53:46 | 2019-07-03T18:53:46 | NONE | null | First off, Peewee is great :)
Postgres supports network data types.
https://www.postgresql.org/docs/9.1/datatype-net-types.html
What would be the best way to implement support for these fields instead of peewees IPAddr field?
A simple Field extension with the right type would suffice?
If so, I will prototype it and open a PR | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1965/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/1965/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1964 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1964/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1964/comments | https://api.github.com/repos/coleifer/peewee/issues/1964/events | https://github.com/coleifer/peewee/pull/1964 | 463,526,203 | MDExOlB1bGxSZXF1ZXN0MjkzOTg4MTIz | 1,964 | infer foreign key from the name of the model | {
"login": "nad2000",
"id": 177266,
"node_id": "MDQ6VXNlcjE3NzI2Ng==",
"avatar_url": "https://avatars.githubusercontent.com/u/177266?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/nad2000",
"html_url": "https://github.com/nad2000",
"followers_url": "https://api.github.com/users/nad2000/followers",
"following_url": "https://api.github.com/users/nad2000/following{/other_user}",
"gists_url": "https://api.github.com/users/nad2000/gists{/gist_id}",
"starred_url": "https://api.github.com/users/nad2000/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/nad2000/subscriptions",
"organizations_url": "https://api.github.com/users/nad2000/orgs",
"repos_url": "https://api.github.com/users/nad2000/repos",
"events_url": "https://api.github.com/users/nad2000/events{/privacy}",
"received_events_url": "https://api.github.com/users/nad2000/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"Going to pass on this and require the condition when multiple FKs are present."
] | 2019-07-03T03:30:02 | 2019-07-03T15:56:04 | 2019-07-03T15:56:04 | NONE | null | fix for #1963 | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1964/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/1964/timeline | null | null | false | {
"url": "https://api.github.com/repos/coleifer/peewee/pulls/1964",
"html_url": "https://github.com/coleifer/peewee/pull/1964",
"diff_url": "https://github.com/coleifer/peewee/pull/1964.diff",
"patch_url": "https://github.com/coleifer/peewee/pull/1964.patch",
"merged_at": null
} |
https://api.github.com/repos/coleifer/peewee/issues/1963 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1963/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1963/comments | https://api.github.com/repos/coleifer/peewee/issues/1963/events | https://github.com/coleifer/peewee/issues/1963 | 463,518,724 | MDU6SXNzdWU0NjM1MTg3MjQ= | 1,963 | Missing on= inference for joins (ValueError: More than one foreign key between.... Please specify which you are joining on.) | {
"login": "nad2000",
"id": 177266,
"node_id": "MDQ6VXNlcjE3NzI2Ng==",
"avatar_url": "https://avatars.githubusercontent.com/u/177266?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/nad2000",
"html_url": "https://github.com/nad2000",
"followers_url": "https://api.github.com/users/nad2000/followers",
"following_url": "https://api.github.com/users/nad2000/following{/other_user}",
"gists_url": "https://api.github.com/users/nad2000/gists{/gist_id}",
"starred_url": "https://api.github.com/users/nad2000/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/nad2000/subscriptions",
"organizations_url": "https://api.github.com/users/nad2000/orgs",
"repos_url": "https://api.github.com/users/nad2000/repos",
"events_url": "https://api.github.com/users/nad2000/events{/privacy}",
"received_events_url": "https://api.github.com/users/nad2000/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"My sense is to keep this explicit when multiple FKs are present, regardless of what the previous (2.x?) behavior may have been.",
"that's a bummer. I have heaps of queries that used to work with 2.x but now are broken (all tables have these created_by and modified_by)",
"Well let me reconsider.",
"Merged equivalent patch thanks."
] | 2019-07-03T02:54:27 | 2019-07-04T16:47:28 | 2019-07-04T16:47:13 | NONE | null | The inference of **on=...** has changed in the case with multiple foreign keys to the same table, for example,
```python
class User(Model):
...
class Record(Model):
user = ForeignKeyField(User)
created_by = ForeignKeyField(User)
updated_by = ForeignKeyField(User)
```
an attempt to join `Record` to `User` without given **on=...** (`python Record.select().join(User)`) fails with:
```
ValueError: More than one foreign key between <Model: Record> and <Model: User>. Please specify which you are joining on.
```
I reckon it used to pick up, by default, the foreign key with the name that matches the calls name, namely, **user** in this example.
| {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1963/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/1963/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1962 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1962/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1962/comments | https://api.github.com/repos/coleifer/peewee/issues/1962/events | https://github.com/coleifer/peewee/issues/1962 | 463,445,226 | MDU6SXNzdWU0NjM0NDUyMjY= | 1,962 | Can't access to joined model data | {
"login": "kyotops",
"id": 38300198,
"node_id": "MDQ6VXNlcjM4MzAwMTk4",
"avatar_url": "https://avatars.githubusercontent.com/u/38300198?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/kyotops",
"html_url": "https://github.com/kyotops",
"followers_url": "https://api.github.com/users/kyotops/followers",
"following_url": "https://api.github.com/users/kyotops/following{/other_user}",
"gists_url": "https://api.github.com/users/kyotops/gists{/gist_id}",
"starred_url": "https://api.github.com/users/kyotops/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/kyotops/subscriptions",
"organizations_url": "https://api.github.com/users/kyotops/orgs",
"repos_url": "https://api.github.com/users/kyotops/repos",
"events_url": "https://api.github.com/users/kyotops/events{/privacy}",
"received_events_url": "https://api.github.com/users/kyotops/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"In a many-to-many things are complicated. Depending on how you join, you're going to get duplicated data on one side or the other. Remember that the output of any query is always going to be a flat table-like data-structure. There is no nesting. So no rolling up of multiple Books for a single User. You'll get one User and one Book per User `times` Book.\r\n\r\nYou can still access this, you'd probably do something like\r\n\r\n```python\r\nfor user in query:\r\n related_book = user.book_relationship.book # Something like this, depends on your field names.\r\n```\r\n\r\nYour best bet is to do something like this:\r\n\r\n```python\r\nuser = User.get(User.username == 'charlie')\r\nliked_books = Book.select().join(BookRelationship, on=BookRelationship.from_user).where(BookRelationship.to_user=user)\r\n```"
] | 2019-07-02T21:31:58 | 2019-07-03T15:59:20 | 2019-07-03T15:59:20 | NONE | null | I'm trying to implement Many to Many select (http://docs.peewee-orm.com/en/latest/peewee/relationships.html#implementing-many-to-many), but I can't access to Book model data:
```
query = User.select(
User,
Book,
BookRelationship,
).join(
BookRelationship,
on=BookRelationship.from_user,
).join(
Book,
).where(
BookRelationship.to_user == self,
).order_by(
BookRelationship.created_at.desc()
)
for item in query:
# Can access only user data (item.username, item.fullname, item.age)
```
In this example, I'm trying to retrieve user data along with books he liked.
I didn't want to open this issue, because of this kind of trifle, but I couldn't find another way out. | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1962/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/1962/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1961 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1961/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1961/comments | https://api.github.com/repos/coleifer/peewee/issues/1961/events | https://github.com/coleifer/peewee/issues/1961 | 463,004,118 | MDU6SXNzdWU0NjMwMDQxMTg= | 1,961 | .exists() fails for a query with SQL literals/expresions | {
"login": "nad2000",
"id": 177266,
"node_id": "MDQ6VXNlcjE3NzI2Ng==",
"avatar_url": "https://avatars.githubusercontent.com/u/177266?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/nad2000",
"html_url": "https://github.com/nad2000",
"followers_url": "https://api.github.com/users/nad2000/followers",
"following_url": "https://api.github.com/users/nad2000/following{/other_user}",
"gists_url": "https://api.github.com/users/nad2000/gists{/gist_id}",
"starred_url": "https://api.github.com/users/nad2000/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/nad2000/subscriptions",
"organizations_url": "https://api.github.com/users/nad2000/orgs",
"repos_url": "https://api.github.com/users/nad2000/repos",
"events_url": "https://api.github.com/users/nad2000/events{/privacy}",
"received_events_url": "https://api.github.com/users/nad2000/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [] | 2019-07-02T03:38:52 | 2019-07-02T13:44:59 | 2019-07-02T13:44:59 | NONE | null | With **2.x** something like this was working.
```python
# This is a simplified query (check in one round-trip):
(User.select(SQL('1')) | Organisation.select(SQL('1'))).exists()
```
With **3.x (3.9.6)** the query gets build but **.exists()** fails with:
```
*** AttributeError: 'ModelCompoundSelectQuery' object has no attribute 'columns'
```
```sql
-- (User.select(SQL('1')) | Organisation.select(SQL('1'))).sql():
SELECT 1 FROM "user" AS "t1" UNION SELECT 1 FROM "organisation" AS "t2"
```
It might be that it has nothing to do specifically with SQL expressions
```python
(User.select(User.id) | Organisation.select(Organisation.id)).exists()
```
also fails with
```
*** AttributeError: 'ModelCompoundSelectQuery' object has no attribute 'columns'
``` | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1961/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/1961/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1960 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1960/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1960/comments | https://api.github.com/repos/coleifer/peewee/issues/1960/events | https://github.com/coleifer/peewee/pull/1960 | 458,904,907 | MDExOlB1bGxSZXF1ZXN0MjkwMzk1MTU2 | 1,960 | Implement LCONCAT | {
"login": "GrmpPnda",
"id": 12795082,
"node_id": "MDQ6VXNlcjEyNzk1MDgy",
"avatar_url": "https://avatars.githubusercontent.com/u/12795082?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/GrmpPnda",
"html_url": "https://github.com/GrmpPnda",
"followers_url": "https://api.github.com/users/GrmpPnda/followers",
"following_url": "https://api.github.com/users/GrmpPnda/following{/other_user}",
"gists_url": "https://api.github.com/users/GrmpPnda/gists{/gist_id}",
"starred_url": "https://api.github.com/users/GrmpPnda/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/GrmpPnda/subscriptions",
"organizations_url": "https://api.github.com/users/GrmpPnda/orgs",
"repos_url": "https://api.github.com/users/GrmpPnda/repos",
"events_url": "https://api.github.com/users/GrmpPnda/events{/privacy}",
"received_events_url": "https://api.github.com/users/GrmpPnda/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [] | 2019-06-20T22:02:04 | 2019-06-21T17:44:04 | 2019-06-21T17:44:04 | NONE | null | Implement a left-concat for string expressions. | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1960/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/1960/timeline | null | null | false | {
"url": "https://api.github.com/repos/coleifer/peewee/pulls/1960",
"html_url": "https://github.com/coleifer/peewee/pull/1960",
"diff_url": "https://github.com/coleifer/peewee/pull/1960.diff",
"patch_url": "https://github.com/coleifer/peewee/pull/1960.patch",
"merged_at": null
} |
https://api.github.com/repos/coleifer/peewee/issues/1959 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1959/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1959/comments | https://api.github.com/repos/coleifer/peewee/issues/1959/events | https://github.com/coleifer/peewee/issues/1959 | 458,630,398 | MDU6SXNzdWU0NTg2MzAzOTg= | 1,959 | AttributeError: 'bool' object has no attribute 'name' while getting self._pk value. | {
"login": "lalit-lintel",
"id": 26576603,
"node_id": "MDQ6VXNlcjI2NTc2NjAz",
"avatar_url": "https://avatars.githubusercontent.com/u/26576603?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/lalit-lintel",
"html_url": "https://github.com/lalit-lintel",
"followers_url": "https://api.github.com/users/lalit-lintel/followers",
"following_url": "https://api.github.com/users/lalit-lintel/following{/other_user}",
"gists_url": "https://api.github.com/users/lalit-lintel/gists{/gist_id}",
"starred_url": "https://api.github.com/users/lalit-lintel/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/lalit-lintel/subscriptions",
"organizations_url": "https://api.github.com/users/lalit-lintel/orgs",
"repos_url": "https://api.github.com/users/lalit-lintel/repos",
"events_url": "https://api.github.com/users/lalit-lintel/events{/privacy}",
"received_events_url": "https://api.github.com/users/lalit-lintel/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"I also have a similar issue when doing a `bulk_update`. Though I do have `pmid = pw.IntegerField(unique=True)` in my model.\r\n\r\n```python\r\n with self.dbase.atomic():\r\n for idx in range(0, num_papers_update, n_batch):\r\n db.PaperDB.bulk_update(self.update_l[idx:idx+n_batch],fields=[db.PaperDB.pmid,\r\n db.PaperDB.title,\r\n db.PaperDB.abstract,\r\n db.PaperDB.journal,\r\n db.PaperDB.authors,\r\n db.PaperDB.pubdate,\r\n db.PaperDB.mesh_terms,\r\n db.PaperDB.publication_types,\r\n db.PaperDB.chemical_list,\r\n db.PaperDB.keywords,\r\n db.PaperDB.doi,\r\n db.PaperDB.delete,\r\n db.PaperDB.affiliations,\r\n db.PaperDB.pmc,\r\n db.PaperDB.other_id,\r\n db.PaperDB.medline_ta,\r\n db.PaperDB.nlm_unique_id,\r\n db.PaperDB.issn_linking,\r\n db.PaperDB.country,\r\n db.PaperDB.pubyear,\r\n db.PaperDB.pubmonth,\r\n db.PaperDB.pubday])\r\n```\r\n```bash\r\n~/anaconda3/lib/python3.8/site-packages/peewee.py in bulk_update(cls, model_list, fields, batch_size)\r\n 6350 \r\n 6351 for batch in batches:\r\n-> 6352 id_list = [model._pk for model in batch]\r\n 6353 update = {}\r\n 6354 for field, attr in zip(fields, attrs):\r\n\r\n~/anaconda3/lib/python3.8/site-packages/peewee.py in <listcomp>(.0)\r\n 6350 \r\n 6351 for batch in batches:\r\n-> 6352 id_list = [model._pk for model in batch]\r\n 6353 update = {}\r\n 6354 for field, attr in zip(fields, attrs):\r\n\r\nAttributeError: 'dict' object has no attribute '_pk'\r\n\r\n```\r\n\r\nAdditionally is there a way to not need to define all the fields repeatedly here and just update all fields with the incoming fields? Or could bulk_update just update the relevant ones in the list item that are being fed in?",
"http://docs.peewee-orm.com/en/latest/peewee/api.html#Model.bulk_update - you have to pass list of model instances to `bulk_update()`."
] | 2019-06-20T12:32:41 | 2021-09-03T12:12:16 | 2019-06-20T12:58:28 | NONE | null | I am using a model without a primary. and also used peewee signals
To have a model without a primary key, I declare it like below.
```python
class MyModel(base.BaseModel):
field1 = pw.IntegerField(index=True)
field2 = pw.IntegerField()
class Meta:
primary_key = False
```
But on create I am getting below error.
```python
Traceback (most recent call last):
File "/home/lalit/app/venv/lib/python3.6/site-packages/peewee.py", line 5454, in create
inst.save(force_insert=True)
File "/home/lalit/app/src/myfile.py", line 23, in save
super().save(*args, **kwargs)
File "/home/lalit/app/venv/lib/python3.6/site-packages/playhouse/signals.py", line 68, in save
pk_value = self._pk
File "/home/lalit/app/venv/lib/python3.6/site-packages/peewee.py", line 5519, in get_id
return getattr(self, self._meta.primary_key.name)
AttributeError: 'bool' object has no attribute 'name'
```
Error raised by the "save" method in Model class in signals file.
Can please look into this?
Thanks. | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1959/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/1959/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1958 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1958/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1958/comments | https://api.github.com/repos/coleifer/peewee/issues/1958/events | https://github.com/coleifer/peewee/pull/1958 | 457,970,173 | MDExOlB1bGxSZXF1ZXN0Mjg5NjcwMTc5 | 1,958 | Add support for MySQL STRAIGHT_JOIN | {
"login": "d0d0",
"id": 553292,
"node_id": "MDQ6VXNlcjU1MzI5Mg==",
"avatar_url": "https://avatars.githubusercontent.com/u/553292?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/d0d0",
"html_url": "https://github.com/d0d0",
"followers_url": "https://api.github.com/users/d0d0/followers",
"following_url": "https://api.github.com/users/d0d0/following{/other_user}",
"gists_url": "https://api.github.com/users/d0d0/gists{/gist_id}",
"starred_url": "https://api.github.com/users/d0d0/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/d0d0/subscriptions",
"organizations_url": "https://api.github.com/users/d0d0/orgs",
"repos_url": "https://api.github.com/users/d0d0/repos",
"events_url": "https://api.github.com/users/d0d0/events{/privacy}",
"received_events_url": "https://api.github.com/users/d0d0/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"Going to pass.",
"Is the feature available in the peewee now ?",
"I see latest peewee version was added in Apr 23, 2020, so this one not yet released ???",
"I did not merge this change.",
"Any alternative way to include straight_join in peewee ?",
"or is there a way to replace **select** with **select straight_join** once the query is built ? any solution related to this one is much appreciated thanks",
"It seems like a very obscure mysql thing to try and hint the query-planner to use a certain ordering. I don't really plan on supporting or maintaining that functionality. I'd suggest tweaking your query or re-generating statistics.",
"okay\r\nthanks"
] | 2019-06-19T11:57:08 | 2020-09-11T04:06:41 | 2019-06-19T14:43:50 | NONE | null | Add support for mysql STRAIGHT_JOIN. Resolves https://github.com/coleifer/peewee/issues/842 | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1958/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/1958/timeline | null | null | false | {
"url": "https://api.github.com/repos/coleifer/peewee/pulls/1958",
"html_url": "https://github.com/coleifer/peewee/pull/1958",
"diff_url": "https://github.com/coleifer/peewee/pull/1958.diff",
"patch_url": "https://github.com/coleifer/peewee/pull/1958.patch",
"merged_at": null
} |
https://api.github.com/repos/coleifer/peewee/issues/1957 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1957/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1957/comments | https://api.github.com/repos/coleifer/peewee/issues/1957/events | https://github.com/coleifer/peewee/issues/1957 | 457,865,703 | MDU6SXNzdWU0NTc4NjU3MDM= | 1,957 | How to add fields to existing tables | {
"login": "qa1057",
"id": 35075555,
"node_id": "MDQ6VXNlcjM1MDc1NTU1",
"avatar_url": "https://avatars.githubusercontent.com/u/35075555?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/qa1057",
"html_url": "https://github.com/qa1057",
"followers_url": "https://api.github.com/users/qa1057/followers",
"following_url": "https://api.github.com/users/qa1057/following{/other_user}",
"gists_url": "https://api.github.com/users/qa1057/gists{/gist_id}",
"starred_url": "https://api.github.com/users/qa1057/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/qa1057/subscriptions",
"organizations_url": "https://api.github.com/users/qa1057/orgs",
"repos_url": "https://api.github.com/users/qa1057/repos",
"events_url": "https://api.github.com/users/qa1057/events{/privacy}",
"received_events_url": "https://api.github.com/users/qa1057/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"* https://www.postgresql.org/docs/current/sql-altertable.html\r\n* https://www.sqlite.org/lang_altertable.html\r\n* https://dev.mysql.com/doc/refman/8.0/en/alter-table.html\r\n\r\nPeewee can help you. If you had looked at the docs, you'd probably have found it:\r\n\r\nhttp://docs.peewee-orm.com/en/latest/peewee/playhouse.html#migrate",
"This kind of question belongs on stack overflow. NOT on the issue tracker. Please use your brain."
] | 2019-06-19T08:05:52 | 2019-06-19T14:39:51 | 2019-06-19T14:39:33 | NONE | null | For example, now I have created a model and executed to create a table. Then I want to add fields to this table. What should I do? | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1957/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/1957/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1956 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1956/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1956/comments | https://api.github.com/repos/coleifer/peewee/issues/1956/events | https://github.com/coleifer/peewee/issues/1956 | 457,795,947 | MDU6SXNzdWU0NTc3OTU5NDc= | 1,956 | `ignore_unknown` unexpectedly doesn't ignore `id` field. | {
"login": "blakewest",
"id": 2524396,
"node_id": "MDQ6VXNlcjI1MjQzOTY=",
"avatar_url": "https://avatars.githubusercontent.com/u/2524396?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/blakewest",
"html_url": "https://github.com/blakewest",
"followers_url": "https://api.github.com/users/blakewest/followers",
"following_url": "https://api.github.com/users/blakewest/following{/other_user}",
"gists_url": "https://api.github.com/users/blakewest/gists{/gist_id}",
"starred_url": "https://api.github.com/users/blakewest/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/blakewest/subscriptions",
"organizations_url": "https://api.github.com/users/blakewest/orgs",
"repos_url": "https://api.github.com/users/blakewest/repos",
"events_url": "https://api.github.com/users/blakewest/events{/privacy}",
"received_events_url": "https://api.github.com/users/blakewest/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"This makes sense -- so the issue is that your `BaseModel` class has an `id` primary key field (since no primary key is declared). When you subclass it, just because of how Python works, you get an `id` attribute on your subclass (`Website`).\r\n\r\nTo work around this, just declare your base model with the primary key explicitly disabled:\r\n\r\n```python\r\nclass BaseModel(Model):\r\n class Meta:\r\n database = ...\r\n primary_key = False\r\n```",
"@coleifer thanks for the quick response and for pointing out the issue. I would still view this as a bug though, for a few reasons:\r\n1.) It's simply not expected that if I explicitly declare a primary key, and don't have `id` anywhere on the model, that somehow `id` is in fact actually on the model.\r\n\r\n2.) To drive this point home, PeeWee explicitly tells me `id` is not a field. See this screenshot: \r\n\r\n\r\n3.) Having to put `primary_key = False` on my BaseModel kind of defeats the point of my BaseModel. I may only want to have this non-traditional primary key on one model, not all of them. And I can't even directly add `Meta: primary_key = False` onto my `Website` class, and still have it inherit from BaseModel.\r\n\r\nMy expectation would be that if I don't put `id` on the model, it's not on the model. And especially if I ask PeeWee directly what fields are on my model, and it gives me a list... then those would in fact be the only fields on the model. Is there a higher level reason why the current behavior is intended?",
"> It's simply not expected that if I explicitly declare a primary key, and don't have id anywhere on the model, that somehow id is in fact actually on the model.\r\n\r\nI understand and agree with you. There's a convention that if no primary key is defined, an `id` auto-incrementing pk will be added automatically. This gets inherited. It is what it is. This problem is really just confined to this particular case (implicit \"id\" being inherited, then a different primary key being declared).\r\n\r\nThe other problem is that you are explicitly specifying \"ignore_unknown\", which patches all attributes directly onto the model instance. If you specify `ignore_unknown=False` then Peewee will check that the key corresponds to a field declared directly on the model.\r\n\r\nI'd suggest you do not use `ignore_unknown=True`.\r\n\r\nThe proper way to fix this, I think, would be to modify the `FieldAccessor` so that setting the value of the field attribute (via the descriptor) would validate that the field belongs to the instance you're setting the value on. I don't want to introduce that complexity, though, as this seems like a pretty rare situation to add the overhead of doing a check every single time you set an instance attribute.",
"@coleifer ah, yeah, the `ignore_unknown` part. I actually was gonna bring this up earlier. This is also very unexpected behavior to me. I saw in the source [here](https://github.com/coleifer/peewee/blob/master/playhouse/shortcuts.py#L139) that you call `setattr(instance, key, val)` whenever an unknown attribute is found. What is the reasoning for that behavior? My expectation would have been to actually ignore it. As in, do nothing (ie. just the `continue` part in this case). \r\nIf `ignore_unknown` actually ignored the unknown attributes, then the bug also would not have happened. \r\nAs for why I don't just use `ignore_unknown=False`, it's because I'm cobbling together this model from various data sources. There are loads of columns on it that are irrelevant for my needs, so `ignore_unknown` seemed like exactly what I need. I basically wanted my explicitly declared fields to act as a whitelist. And sure I could whitelist it all on my own, but I thought that's why ignore unknown would do for me. \r\n\r\nSo all in all, I think my fix for this would be to change the behavior of ignore_unknown to actually ignore_unknown attributes. Or introduce a new option that does (maybe `only_set_known_fields`?). I get this would be a backwards-incompatible change, but I would argue the current behavior is incorrect. And if you're relying on `ignore_unknown` to set the unknown ones on the model, then it seems like you're doing something wrong.\r\n\r\nI'd be happy to raise a PR if you agreed with either of those paths.",
"Here's the thing -- `dict_to_model` is just a simple shortcut. Models already accept `**kwargs` in their constructor. `dict_to_model` is helpful especially for taking a nested dictionary and turning it into a graph of models and their dependencies.\r\n\r\nI think you're really wasting way too much time. In the time you've spent writing these comments you could have very easily written a filter expression that does exactly what you need:\r\n\r\n```python\r\nfield_names = MyModel._meta.sorted_field_names\r\nf = lambda i: i[0] in field_names\r\ndef clean_data(data):\r\n return dict(filter(f, data.items()))\r\n\r\n# NB: use a transaction or a bulk insert instead!\r\nfor d in list_of_dicts:\r\n MyModel.create(**clean_data(d))\r\n```"
] | 2019-06-19T04:06:30 | 2019-06-23T16:36:24 | 2019-06-19T14:36:06 | NONE | null | Hi, I just started working with PeeWee, and came across some issues while working with the `ignore_unknown` option. Specifically, when trying to use `dict_to_model` with the `ignore_unknown` option, it doesn't seem to actually ignore all unknown traits. It ignores everything except for `id`. Here's a short example below that demonstrates the problem...
```python
from database.base_model import BaseModel
from peewee import *
from playhouse.shortcuts import dict_to_model, update_model_from_dict
Website.drop_table()
class BaseModel(Model):
class Meta:
db_file = './database/demo/test.db.sqlite'
database = SqliteDatabase(db_file)
class Website(BaseModel):
url = CharField(primary_key=True)
name = CharField()
Website.create_table()
attrs = {"url": "https://some_website.com/some_resource/123245", "name": "Cool Website", "id": 456, "some_random_attr": True}
website = dict_to_model(Website, attrs, ignore_unknown=True)
website.save(force_insert=True) # => Throws OperationalError: table website has no column named id
```
I would have expected the save call to work. I know the table has no column `id`. I explicitly didn't give it such a column. I used `url` as the primary key instead. To give some context... I'm using PeeWee with a little scraper I'm building. It so happens that I'm combining my scraped data with some other data that includes a field called `id`. For my purposes I want to ignore this field (and all others that I didn't explicitly lay out in the model), hence me setting the `ignore_unknown` option.
I saw a similar error when updating an existing model through a similar means. For example... the following code fails in the same way:
```python
existing = Website.get_or_none(Website.url == 'https://some_website.com/some_resource/123245')
updated_attrs = {"url": "https://some_website.com/some_resource/123245", "name": "Very Cool Website", "id": 456, "some_other_random_attr": True}
updated = update_model_from_dict(existing, updated_attrs, ignore_unknown=True)
updated.save() # Fail! OperationError
```
In my actual project, I was seeing a more cryptic error, and actually was getting `ValueError: invalid literal for int() with base 10: 'http://www.some_website.com/index.php?a=odds&ma_id=823911369`. I couldn't get that error to neatly re-produce. But it stemmed from the same issue. In my code I had to put a `if 'id' in attrs: attrs.pop('id')`, which solved it. But this seems gross, and not what is expected with `ignore_unknown`.
Thoughts? | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1956/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/1956/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1955 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1955/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1955/comments | https://api.github.com/repos/coleifer/peewee/issues/1955/events | https://github.com/coleifer/peewee/issues/1955 | 457,615,055 | MDU6SXNzdWU0NTc2MTUwNTU= | 1,955 | Implement full-text search in mysql? | {
"login": "dzpt",
"id": 5781080,
"node_id": "MDQ6VXNlcjU3ODEwODA=",
"avatar_url": "https://avatars.githubusercontent.com/u/5781080?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/dzpt",
"html_url": "https://github.com/dzpt",
"followers_url": "https://api.github.com/users/dzpt/followers",
"following_url": "https://api.github.com/users/dzpt/following{/other_user}",
"gists_url": "https://api.github.com/users/dzpt/gists{/gist_id}",
"starred_url": "https://api.github.com/users/dzpt/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/dzpt/subscriptions",
"organizations_url": "https://api.github.com/users/dzpt/orgs",
"repos_url": "https://api.github.com/users/dzpt/repos",
"events_url": "https://api.github.com/users/dzpt/events{/privacy}",
"received_events_url": "https://api.github.com/users/dzpt/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"Here is the doc: http://docs.peewee-orm.com/en/latest/peewee/query_operators.html#adding-user-defined-operators\r\n\r\nJust write a wrapper.\r\n\r\n```python\r\ndef Match(columns, expr, modifier=None):\r\n match = fn.MATCH(*columns) # MATCH(col0, col1, ...)\r\n args = expr if modifier is None else NodeList((expr, SQL(modifier))) \r\n return NodeList((match, fn.AGAINST(args)))\r\n\r\n.where(Match((Post.title, Post.text), 'search query'))\r\n\r\n.where(Match((Post.title, Post.text), 'foo AND bar', 'IN BOOLEAN MODE'))\r\n```",
"To make it even easier, I added an implementation in f76ce0b."
] | 2019-06-18T17:49:52 | 2019-06-18T20:08:08 | 2019-06-18T20:08:07 | NONE | null | It wasn't mentioned on the doc. Only issue #532
You link to user-defined function but i have no idea how to use it to implement full-text search.
There's no doc on `Expression`
I've tried with this, but how am i supposed to set MATCH around `lhs`?
```
def fulltext(lhs, rhs):
return Expression(lhs, 'AGAINST', rhs, True)
```
I have to use raw query like this instead
`q = q.select().where(SQL("MATCH (title) AGAINST(%s)", ("test",)))`
have no idea why i have to use `("test",)`, if i input `"test"`:
`q = q.select().where(SQL("MATCH (title) AGAINST(%s)", "test"))`
i'll get `TypeError: not all arguments converted during string formatting` | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1955/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/1955/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1954 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1954/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1954/comments | https://api.github.com/repos/coleifer/peewee/issues/1954/events | https://github.com/coleifer/peewee/issues/1954 | 456,647,075 | MDU6SXNzdWU0NTY2NDcwNzU= | 1,954 | After importing database, IntegrityError raised for every new record | {
"login": "joshuaia",
"id": 51882760,
"node_id": "MDQ6VXNlcjUxODgyNzYw",
"avatar_url": "https://avatars.githubusercontent.com/u/51882760?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/joshuaia",
"html_url": "https://github.com/joshuaia",
"followers_url": "https://api.github.com/users/joshuaia/followers",
"following_url": "https://api.github.com/users/joshuaia/following{/other_user}",
"gists_url": "https://api.github.com/users/joshuaia/gists{/gist_id}",
"starred_url": "https://api.github.com/users/joshuaia/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/joshuaia/subscriptions",
"organizations_url": "https://api.github.com/users/joshuaia/orgs",
"repos_url": "https://api.github.com/users/joshuaia/repos",
"events_url": "https://api.github.com/users/joshuaia/events{/privacy}",
"received_events_url": "https://api.github.com/users/joshuaia/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"You need to update the sequence that controls the next value of the primary key.\r\n\r\n```sql\r\nSELECT setval('users_id_seq', (SELECT MAX(id) FROM users)+1);\r\n```\r\n\r\nFor whatever reason, the way you're doing your inserts isn't setting this properly."
] | 2019-06-16T14:27:30 | 2019-06-18T19:49:06 | 2019-06-18T19:49:05 | NONE | null | I'm importing database like this:
`psql -h localhost -d db_name -U user -f db.sql`
Example of sql query:
```
INSERT INTO public.users(id, email, password) VALUES (1, '[email protected]', 'PASSWORD_HASH');
INSERT INTO public.users(id, email, password) VALUES (2, '[email protected]', 'PASSWORD_HASH');
INSERT INTO public.users(id, email, password) VALUES (3, '[email protected]', 'PASSWORD_HASH');
```
User model:
```
class User(db.Model):
email = CharField(unique=True)
password = CharField()
```
After that, I'm trying to create new record, eg. register new user:
```
new_user = User.create(
email=email,
password=generate_password_hash(password),
)
# After creating, redirect user to home page
```
But at this moment `IntegrityError` is raised:
`duplicate key value violates unique constraint "users_pkey" DETAIL: Key (id)=(1) already exists.`
But, without importing the DB, the error does not appear. And new data is successfully saving. | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1954/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/1954/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1953 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1953/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1953/comments | https://api.github.com/repos/coleifer/peewee/issues/1953/events | https://github.com/coleifer/peewee/issues/1953 | 456,592,320 | MDU6SXNzdWU0NTY1OTIzMjA= | 1,953 | peewee.ProgrammingError: syntax error at or near "RETURNING" | {
"login": "ernest-andela",
"id": 46436012,
"node_id": "MDQ6VXNlcjQ2NDM2MDEy",
"avatar_url": "https://avatars.githubusercontent.com/u/46436012?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/ernest-andela",
"html_url": "https://github.com/ernest-andela",
"followers_url": "https://api.github.com/users/ernest-andela/followers",
"following_url": "https://api.github.com/users/ernest-andela/following{/other_user}",
"gists_url": "https://api.github.com/users/ernest-andela/gists{/gist_id}",
"starred_url": "https://api.github.com/users/ernest-andela/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/ernest-andela/subscriptions",
"organizations_url": "https://api.github.com/users/ernest-andela/orgs",
"repos_url": "https://api.github.com/users/ernest-andela/repos",
"events_url": "https://api.github.com/users/ernest-andela/events{/privacy}",
"received_events_url": "https://api.github.com/users/ernest-andela/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"Fixed: I set primary_key = False",
"It appears to me that Redshift should support the Postgresql `RETURNING` clause, as it is not listed among the \"unsupported postgresql features\":\r\n\r\nhttps://docs.aws.amazon.com/redshift/latest/dg/c_unsupported-postgresql-features.html"
] | 2019-06-16T01:50:51 | 2019-06-18T19:50:51 | 2019-06-18T19:50:51 | NONE | null | I am getting the error below and l don't know what is causing this error
I am saving this into a model using Redshift Postgres Database:
```
etl_dic = { "email": "email" }
File "/Users/ernestappiah/Desktop/FlaskApplications/AirflowETL/terravion/service/subscriptions/operations/subscription.py", line 220, in dump_android_to_db
SubscriptionETLModel.insert(etl_dic).execute()
File "/Users/ernestappiah/Desktop/FlaskApplications/Environments/env_terravion/terravion_env/lib/python3.6/site-packages/peewee.py", line 1785, in inner
return method(self, database, *args, **kwargs)
File "/Users/ernestappiah/Desktop/FlaskApplications/Environments/env_terravion/terravion_env/lib/python3.6/site-packages/peewee.py", line 1856, in execute
return self._execute(database)
File "/Users/ernestappiah/Desktop/FlaskApplications/Environments/env_terravion/terravion_env/lib/python3.6/site-packages/peewee.py", line 2572, in _execute
return super(Insert, self)._execute(database)
File "/Users/ernestappiah/Desktop/FlaskApplications/Environments/env_terravion/terravion_env/lib/python3.6/site-packages/peewee.py", line 2318, in _execute
cursor = self.execute_returning(database)
File "/Users/ernestappiah/Desktop/FlaskApplications/Environments/env_terravion/terravion_env/lib/python3.6/site-packages/peewee.py", line 2325, in execute_returning
cursor = database.execute(self)
File "/Users/ernestappiah/Desktop/FlaskApplications/Environments/env_terravion/terravion_env/lib/python3.6/site-packages/peewee.py", line 2962, in execute
return self.execute_sql(sql, params, commit=commit)
File "/Users/ernestappiah/Desktop/FlaskApplications/Environments/env_terravion/terravion_env/lib/python3.6/site-packages/peewee.py", line 2956, in execute_sql
self.commit()
File "/Users/ernestappiah/Desktop/FlaskApplications/Environments/env_terravion/terravion_env/lib/python3.6/site-packages/peewee.py", line 2732, in __exit__
reraise(new_type, new_type(*exc_args), traceback)
File "/Users/ernestappiah/Desktop/FlaskApplications/Environments/env_terravion/terravion_env/lib/python3.6/site-packages/peewee.py", line 183, in reraise
raise value.with_traceback(tb)
File "/Users/ernestappiah/Desktop/FlaskApplications/Environments/env_terravion/terravion_env/lib/python3.6/site-packages/peewee.py", line 2949, in execute_sql
cursor.execute(sql, params or ())
peewee.ProgrammingError: syntax error at or near "RETURNING"
LINE 1: ...ic"."subscription_etl" ("email") VALUES ('email') RETURNING ...
^
``` | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1953/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/1953/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1952 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1952/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1952/comments | https://api.github.com/repos/coleifer/peewee/issues/1952/events | https://github.com/coleifer/peewee/issues/1952 | 455,501,379 | MDU6SXNzdWU0NTU1MDEzNzk= | 1,952 | NOT NULL constraint failed | {
"login": "BOBONA",
"id": 25057945,
"node_id": "MDQ6VXNlcjI1MDU3OTQ1",
"avatar_url": "https://avatars.githubusercontent.com/u/25057945?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/BOBONA",
"html_url": "https://github.com/BOBONA",
"followers_url": "https://api.github.com/users/BOBONA/followers",
"following_url": "https://api.github.com/users/BOBONA/following{/other_user}",
"gists_url": "https://api.github.com/users/BOBONA/gists{/gist_id}",
"starred_url": "https://api.github.com/users/BOBONA/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/BOBONA/subscriptions",
"organizations_url": "https://api.github.com/users/BOBONA/orgs",
"repos_url": "https://api.github.com/users/BOBONA/repos",
"events_url": "https://api.github.com/users/BOBONA/events{/privacy}",
"received_events_url": "https://api.github.com/users/BOBONA/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"What in the fuck is this. Please don't post walls-of-meaningless-code."
] | 2019-06-13T02:07:58 | 2020-09-28T12:14:55 | 2019-06-13T03:23:03 | NONE | null | models/prcl.py:
```
from peewee import *
DATABASE = SqliteDatabase('databases/prcl.db')
class Prcl(Model):
CityBlock = FloatField()
Parcel = IntegerField()
OwnerCode = IntegerField()
ParcelId = BigIntegerField()
PrimAddrRecNum = IntegerField()
AddrType = TextField(default="")
LowAddrNum = IntegerField()
LowAddrSuf = TextField(default="")
HighAddrNum = IntegerField()
HighAddrSuf = TextField(default="")
NLC = IntegerField()
Parity = TextField(default="")
StPreDir = TextField(default="")
StName = TextField(default="")
StType = TextField(default="")
StSufDir = TextField(default="")
StdUnitNum = TextField(default="")
OwnerName = TextField(default="")
OwnerName2 = TextField(default="")
OwnerAddr = TextField(default="")
OwnerCity = TextField(default="")
OwnerState = TextField(default="")
OwnerCountry = TextField(default="")
OwnerZIP = TextField(default="")
OwnerRank = TextField(default="")
LegalDesc1 = TextField(default="")
LegalDesc2 = TextField(default="")
LegalDesc3 = TextField(default="")
LegalDesc4 = TextField(default="")
LegalDesc5 = TextField(default="")
AsrClassCode = IntegerField()
AsrLandUse1 = IntegerField()
AsrLanduse2 = IntegerField()
RedevPhase = IntegerField()
RedevYearEnd = IntegerField()
RedevPhase2 = IntegerField()
RedevYearEnd2 = IntegerField()
VacantLot = BooleanField()
SpecBusDist = IntegerField()
SpecBusDist2 = IntegerField()
TIFDist = IntegerField()
LendingAgcy = IntegerField()
Condominium = BooleanField()
NbrOfUnits = IntegerField()
NbrOfApts = IntegerField()
Frontage = FloatField()
LandArea = IntegerField()
RecDailyDate = DateField()
RecDailyNum = IntegerField()
RecBookNum = TextField(default="")
RecPageNum = IntegerField()
AsdLand = DoubleField()
AsdImprove = DoubleField()
AsdTotal = DoubleField()
BillLand = DoubleField()
BillImprove = DoubleField()
BillTotal = DoubleField()
AprLand = DoubleField()
CostAprImprove = DoubleField()
AsmtAppealYear = IntegerField()
AsmtAppealNum = IntegerField()
AsmtAppealType = TextField(default="")
PriorAsdDate = DateField()
PriorAsdLand = DoubleField()
PriorAsdImprove = DoubleField()
PriorAsdTotal = DoubleField()
PriorTaxAmt = DoubleField()
CDALandUse1 = IntegerField()
CDALandUse2 = IntegerField()
LRMSUnitNum = TextField(default="")
Zoning = TextField(default="")
NbrOfBldgsRes = IntegerField()
NbrOfBldgsCom = IntegerField()
FirstYearBuilt = IntegerField()
LastYearBuilt = IntegerField()
ResSalePrice = DoubleField()
ResSaleDate = DateField()
VacBldgYear = IntegerField()
GeoCityBlockPart = DoubleField()
Ward10 = IntegerField()
Precinct10 = IntegerField()
InspArea10 = IntegerField()
Ward00 = IntegerField()
Precinct02 = IntegerField()
Precinct04 = IntegerField()
Nbrhd = IntegerField()
CDADist = IntegerField()
CDASubDist = IntegerField()
PoliceDist = IntegerField()
CensTract10 = IntegerField()
CensBlock10 = IntegerField()
CensBlock00 = DoubleField()
Ward90 = IntegerField()
Precinct90 = IntegerField()
CensBlock90 = DoubleField()
HouseConsDist = IntegerField()
AsrNbrhd = IntegerField()
EntZone = IntegerField()
ImpactArea = IntegerField()
CTDArea = IntegerField()
LeafArea = IntegerField()
ZIP = DoubleField()
OnFloodBlock = IntegerField()
SpecParcelType = TextField(default="")
SubParcelType = TextField(default="")
NbrOfSubAccts = IntegerField()
NbrOfCondos = IntegerField()
LRMSParcel = BooleanField()
AcctPrimary = BooleanField()
GisPrimary = BooleanField()
GisCityBLock = FloatField()
GisParcel = IntegerField()
GisOwnerCode = IntegerField()
Handle = TextField(default="")
Parcel9 = DoubleField()
OwnerOcc = TextField(default="")
FirstDate = DateField()
LastDate = DateField()
OwnerUpdate = DateField()
class Meta:
database = DATABASE
db_table = 'Prcl'
def initialize():
DATABASE.connect()
DATABASE.create_tables([Prcl], safe=True)
DATABASE.close()
```
main.py:
```
import os
from datetime import datetime
import xml.etree.ElementTree as ET
import peewee
from models import prclsale
from models import prcl
field_types = {
peewee.TextField: (lambda string: string),
peewee.IntegerField: (lambda string: int(string)),
peewee.FloatField: (lambda string: float(string)),
peewee.DoubleField: (lambda string: float(string)),
# this is how Access formats their dates
peewee.DateField: (lambda string: datetime.strptime(string, '%Y-%m-%dT%H:%M:%S')),
peewee.BooleanField: (lambda string: bool(int(string))),
peewee.BigIntegerField: (lambda string: float(string))
}
# TODO add a way for the method to resume where it stopped from an error
def populate_database(database, file, model_class, update=False):
model_class.initialize()
# This method requires the xml file to be formatted a certain way so that it can use reflection
if os.path.isfile(database) and not update:
# abort if the database already exists
pass
root = ET.parse(file).getroot()
for table_index, table in enumerate(list(root)):
# get the table class
table_class = getattr(model_class, table.tag)
entries = list(table)
for index, entry in enumerate(entries):
# just printing the progress
if index % 500 == 0:
print(str(round(1000 * (index / len(entries))) / 10) + "%")
fields = list(entry)
table_class.create(
# create the model with a dictionary of the row's fields and values
# use the model class and field type lambdas to transform the xml text to the proper type
**{field.tag: field_types.get(getattr(table_class, field.tag).__class__)(field.text)
for field in fields}
)
populate_database('databases/prcl.db', 'static/prcl_TEST.xml', prcl)
```
static/prcl_TEST.xml:
```
<dataroot>
<Prcl>
<Prcl>
<CityBlock>1</CityBlock>
<Parcel>5</Parcel>
<OwnerCode>0</OwnerCode>
<ParcelId>00010000050</ParcelId>
<PrimAddrRecNum>1</PrimAddrRecNum>
<AddrType>3</AddrType>
<LowAddrNum>626</LowAddrNum>
<LowAddrSuf></LowAddrSuf>
<HighAddrNum>626</HighAddrNum>
<HighAddrSuf></HighAddrSuf>
<NLC>785</NLC>
<Parity>E</Parity>
<StPreDir>S</StPreDir>
<StName>1ST</StName>
<StType>ST</StType>
<StSufDir></StSufDir>
<StdUnitNum></StdUnitNum>
<OwnerName>CITY OF ST LOUIS</OwnerName>
<OwnerAddr>1200 MARKET ST</OwnerAddr>
<OwnerCity>ST LOUIS MO</OwnerCity>
<OwnerZIP>63103</OwnerZIP>
<LegalDesc1>CB 1 FIRST ST</LegalDesc1>
<LegalDesc2>0.140 ACS</LegalDesc2>
<LegalDesc3>BROWNS SURVEY ADDN LOT PTS 9 THRU 12</LegalDesc3>
<LegalDesc4>BD N-POPCAR S- PLUM</LegalDesc4>
<AsrClassCode>4</AsrClassCode>
<AsrLandUse1>3000</AsrLandUse1>
<AsrLanduse2>0</AsrLanduse2>
<RedevPhase>0</RedevPhase>
<RedevYearEnd>0</RedevYearEnd>
<RedevPhase2>0</RedevPhase2>
<RedevYearEnd2>0</RedevYearEnd2>
<VacantLot>1</VacantLot>
<SpecBusDist>0</SpecBusDist>
<SpecBusDist2>0</SpecBusDist2>
<TIFDist>0</TIFDist>
<LendingAgcy>0</LendingAgcy>
<Condominium>0</Condominium>
<NbrOfUnits>0</NbrOfUnits>
<NbrOfApts>0</NbrOfApts>
<Frontage>0</Frontage>
<LandArea>6098</LandArea>
<RecDailyNum>0</RecDailyNum>
<RecBookNum> CVN</RecBookNum>
<RecPageNum>0</RecPageNum>
<AsdLand>6800</AsdLand>
<AsdImprove>-2300</AsdImprove>
<AsdTotal>4400</AsdTotal>
<BillLand>6800</BillLand>
<BillImprove>-2300</BillImprove>
<BillTotal>4400</BillTotal>
<AprLand>21300</AprLand>
<CostAprImprove>0</CostAprImprove>
<AsmtAppealYear>0</AsmtAppealYear>
<AsmtAppealNum>0</AsmtAppealNum>
<PriorAsdDate>2015-10-04T00:00:00</PriorAsdDate>
<PriorAsdLand>6800</PriorAsdLand>
<PriorAsdImprove>-2300</PriorAsdImprove>
<PriorAsdTotal>4400</PriorAsdTotal>
<PriorTaxAmt>0</PriorTaxAmt>
<CDALandUse1>6700</CDALandUse1>
<CDALandUse2>0</CDALandUse2>
<LRMSUnitNum></LRMSUnitNum>
<NbrOfBldgsRes>0</NbrOfBldgsRes>
<NbrOfBldgsCom>0</NbrOfBldgsCom>
<FirstYearBuilt>0</FirstYearBuilt>
<LastYearBuilt>0</LastYearBuilt>
<ResSalePrice>0</ResSalePrice>
<VacBldgYear>0</VacBldgYear>
<GeoCityBlockPart>1.0085</GeoCityBlockPart>
<Ward10>7</Ward10>
<Precinct10>6</Precinct10>
<InspArea10>3</InspArea10>
<Ward00>7</Ward00>
<Precinct02>12</Precinct02>
<Precinct04>6</Precinct04>
<Nbrhd>35</Nbrhd>
<CDADist>9</CDADist>
<CDASubDist>2</CDASubDist>
<PoliceDist>4</PoliceDist>
<CensTract10>1274</CensTract10>
<CensBlock10>1054</CensBlock10>
<CensBlock00>1222.1001</CensBlock00>
<Ward90>7</Ward90>
<Precinct90>6</Precinct90>
<CensBlock90>1222.104</CensBlock90>
<HouseConsDist>55</HouseConsDist>
<AsrNbrhd>266</AsrNbrhd>
<EntZone>1</EntZone>
<ImpactArea>0</ImpactArea>
<CTDArea>0</CTDArea>
<LeafArea>0</LeafArea>
<ZIP>63102</ZIP>
<OnFloodBlock>1</OnFloodBlock>
<NbrOfSubAccts>1</NbrOfSubAccts>
<NbrOfCondos>0</NbrOfCondos>
<LRMSParcel>1</LRMSParcel>
<AcctPrimary>1</AcctPrimary>
<GisPrimary>1</GisPrimary>
<GisCityBLock>1</GisCityBLock>
<GisParcel>5</GisParcel>
<GisOwnerCode>0</GisOwnerCode>
<Handle>10001000005</Handle>
<Parcel9>100005</Parcel9>
<FirstDate>2009-01-25T00:00:00</FirstDate>
<LastDate>2019-05-17T00:00:00</LastDate>
<OwnerUpdate>1983-05-10T00:00:00</OwnerUpdate>
</Prcl>
</Prcl>
</dataroot>
```
main.py just loads in the database from the xml file.
When I run main.py, I get 'peewee.IntegrityError: NOT NULL constraint failed: Prcl.LowAddrSuf.'
I have a default value for LowAddrSuf so I'm not sure how else to fix it.
Please ask if my problem isn't clear enough. | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1952/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/1952/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1951 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1951/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1951/comments | https://api.github.com/repos/coleifer/peewee/issues/1951/events | https://github.com/coleifer/peewee/issues/1951 | 455,343,810 | MDU6SXNzdWU0NTUzNDM4MTA= | 1,951 | Strange Operational Error | {
"login": "BOBONA",
"id": 25057945,
"node_id": "MDQ6VXNlcjI1MDU3OTQ1",
"avatar_url": "https://avatars.githubusercontent.com/u/25057945?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/BOBONA",
"html_url": "https://github.com/BOBONA",
"followers_url": "https://api.github.com/users/BOBONA/followers",
"following_url": "https://api.github.com/users/BOBONA/following{/other_user}",
"gists_url": "https://api.github.com/users/BOBONA/gists{/gist_id}",
"starred_url": "https://api.github.com/users/BOBONA/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/BOBONA/subscriptions",
"organizations_url": "https://api.github.com/users/BOBONA/orgs",
"repos_url": "https://api.github.com/users/BOBONA/repos",
"events_url": "https://api.github.com/users/BOBONA/events{/privacy}",
"received_events_url": "https://api.github.com/users/BOBONA/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"Nevermind, I just realized that uppercase table names are generally an issue.",
"You have complete control over the model class name and/or the table name (same w/fields and columns).\r\n\r\nhttp://docs.peewee-orm.com/en/latest/peewee/models.html#table-names"
] | 2019-06-12T17:46:57 | 2019-06-12T18:15:16 | 2019-06-12T17:51:43 | NONE | null | ```
model_class = MyModel
model_class.create(
**stuff
)
```
Try this code^
This doesn't work and I get an error that says that 'mymodel' is not a table.
Is this a glitch or is it intended? I can't figure out how to fix it by myself.
Is the solution to only use lowercase names? :) | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1951/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/1951/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1950 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1950/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1950/comments | https://api.github.com/repos/coleifer/peewee/issues/1950/events | https://github.com/coleifer/peewee/issues/1950 | 455,015,398 | MDU6SXNzdWU0NTUwMTUzOTg= | 1,950 | Could I get more exactly error of IntegrityError? | {
"login": "fy0",
"id": 1579850,
"node_id": "MDQ6VXNlcjE1Nzk4NTA=",
"avatar_url": "https://avatars.githubusercontent.com/u/1579850?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/fy0",
"html_url": "https://github.com/fy0",
"followers_url": "https://api.github.com/users/fy0/followers",
"following_url": "https://api.github.com/users/fy0/following{/other_user}",
"gists_url": "https://api.github.com/users/fy0/gists{/gist_id}",
"starred_url": "https://api.github.com/users/fy0/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/fy0/subscriptions",
"organizations_url": "https://api.github.com/users/fy0/orgs",
"repos_url": "https://api.github.com/users/fy0/repos",
"events_url": "https://api.github.com/users/fy0/events{/privacy}",
"received_events_url": "https://api.github.com/users/fy0/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [] | 2019-06-12T05:15:24 | 2019-06-12T18:22:36 | 2019-06-12T18:22:36 | NONE | null | Hello, I wrote some code to pick out `duplicate key` and `NOT NULL` exception from IntegrityError, by text match.
```python
class PeeweeContext:
def __init__(self, db):
self.db = db
def __enter__(self):
pass
def __exit__(self, exc_type, exc_val, exc_tb):
db = self.db
if isinstance(exc_val, peewee.IntegrityError):
db.rollback()
if exc_val.args[0].startswith('duplicate key'):
raise AlreadyExists()
elif exc_val.args[0].startswith('NOT NULL constraint failed'):
raise NotNullConstraintFailed()
elif isinstance(exc_val, peewee.DatabaseError):
db.rollback()
logger.error("database error", exc_val)
raise ResourceException("database error")
```
But the code not work on a server with PG 11.3, because exception info was printed by chinese.
```
peewee.IntegrityError: 错误: 重复键违反唯一约束"domain_user_id_name"
DETAIL: 键值"(user_id, name)=(\x5ab0d481cbc00000, 'test')" 已经存在
```
```
postgres@server:~$ locale
LANG=zh_CN.UTF-8
LANGUAGE=zh_CN:zh
LC_CTYPE="zh_CN.UTF-8"
...
```
So could I get more exactly error to avoid text match?
Thanks
| {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1950/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/1950/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1949 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1949/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1949/comments | https://api.github.com/repos/coleifer/peewee/issues/1949/events | https://github.com/coleifer/peewee/issues/1949 | 454,200,667 | MDU6SXNzdWU0NTQyMDA2Njc= | 1,949 | delete signal hooks with delete_instance in recurse mode | {
"login": "Kruptein",
"id": 1814713,
"node_id": "MDQ6VXNlcjE4MTQ3MTM=",
"avatar_url": "https://avatars.githubusercontent.com/u/1814713?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/Kruptein",
"html_url": "https://github.com/Kruptein",
"followers_url": "https://api.github.com/users/Kruptein/followers",
"following_url": "https://api.github.com/users/Kruptein/following{/other_user}",
"gists_url": "https://api.github.com/users/Kruptein/gists{/gist_id}",
"starred_url": "https://api.github.com/users/Kruptein/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/Kruptein/subscriptions",
"organizations_url": "https://api.github.com/users/Kruptein/orgs",
"repos_url": "https://api.github.com/users/Kruptein/repos",
"events_url": "https://api.github.com/users/Kruptein/events{/privacy}",
"received_events_url": "https://api.github.com/users/Kruptein/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"That's correct, using the `recurse` functionality issues efficient bulk deletes for any dependent objects. As such, the `delete_instance()` methods of the deps are not called.\r\n\r\nIt is done this way for efficiency in terms of the database.\r\n\r\n(Better yet is to just specify the `on_delete='CASCADE'` option when declaring foreign-keys, and let the database handle everything).\r\n\r\nBut as to your problem, you'll need to do it manually if you want to do some special processing for each deleted dependent object.",
"Yes I have the proper on cascade things, as ultimately the database is correctly wiped. It's just that I need to do some extra work outside of the database that I hoped to simplify with signals. But I understand the performance reasons, thanks for your work. "
] | 2019-06-10T14:31:27 | 2019-06-10T15:54:05 | 2019-06-10T15:48:28 | NONE | null | Hi,
I have a couple of signal hooks that act on pre_delete. As mentioned in the docs these signals only work with delete_instance. I'm however under the impression that this does not work in combination with the recurse=True field of delete_instance. (i.e. the signals do not trigger for dependencies).
take for example these signals:
```python
@pre_delete(sender=Room)
def on_room_delete(model_class, instance):
logger.warning("DELETE ROOM")
@pre_delete(sender=Location)
def on_location_delete(model_class, instance):
logger.warning("DELETE LOCATION")
```
Where a `Room` consists of multiple `Location`s. When calling `some_room.delete_instance(True)` both the room and related locations are removed from the database as expected, however only the DELETE ROOM signal is triggered.
Any suggestions what I can do to work around this ? | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1949/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/1949/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1948 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1948/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1948/comments | https://api.github.com/repos/coleifer/peewee/issues/1948/events | https://github.com/coleifer/peewee/issues/1948 | 454,170,812 | MDU6SXNzdWU0NTQxNzA4MTI= | 1,948 | Join with multiple subqueries does not work | {
"login": "willianantunes",
"id": 4432783,
"node_id": "MDQ6VXNlcjQ0MzI3ODM=",
"avatar_url": "https://avatars.githubusercontent.com/u/4432783?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/willianantunes",
"html_url": "https://github.com/willianantunes",
"followers_url": "https://api.github.com/users/willianantunes/followers",
"following_url": "https://api.github.com/users/willianantunes/following{/other_user}",
"gists_url": "https://api.github.com/users/willianantunes/gists{/gist_id}",
"starred_url": "https://api.github.com/users/willianantunes/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/willianantunes/subscriptions",
"organizations_url": "https://api.github.com/users/willianantunes/orgs",
"repos_url": "https://api.github.com/users/willianantunes/repos",
"events_url": "https://api.github.com/users/willianantunes/events{/privacy}",
"received_events_url": "https://api.github.com/users/willianantunes/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"As a fantastic workaround, I could make it work by doing the following steps:\r\n\r\n- Copy the Peewee generated RAW SQL\r\n- Paste it inside `raw` function (look the details [here](http://docs.peewee-orm.com/en/latest/peewee/api.html#Model.raw))\r\n\r\nResult:\r\n\r\n\r\n",
"What in the fuck is this, do you actually expect me to read this massive wall of \"code\"?\r\n\r\nIf you can provide a *minimal* example then I'm happy to reopen and discuss.",
"Also, Peewee resolves joins w/multiple selections into a graph of models.\r\n\r\nIf your usage is simplistic and you just need the attrs all available on a single instance, then I suggest you append the following to all your queries: \r\n\r\n```python\r\nquery = SomeModel.valids().objects()\r\nquery2 = Another.invalids().objects()\r\n```\r\n\r\nThis will patch all attributes, including any joined attributes, onto a single model.\r\n\r\nYou can also experiment with `.tuples()` or `.dicts()`.",
"Sorry, @coleifer! I know what you mean. I'll update the question to be as simple as possible . About your suggestion, I had already done it and got the same error.",
"No problem, yes a minimal example would be fantastic, esp if it uses well-understood conventions like user-has-many-tweets, etc. Also you forgot to include the traceback (if there was one). That would be helpful.\r\n\r\nI'll reopen when I've received additional info.",
"@coleifer I simplified the code with minimum input in order to reproduce de error just executing the module giving you have Peewee installed. Some additional info that might be helpful:\r\n\r\n- I’m processing large CSV files. Each file has its own model\r\n- Some models may have references to other models, but without database integrity (FK)\r\n- `SalesDetails` has two references from `Customer`\r\n- I use `alias` as I am using the same table for two different JOINs",
"Just a note, you have:\r\n\r\n```python\r\n(~(Employee.code >> None))\r\n```\r\n\r\nDon't do that! Use this instead:\r\n\r\n```python\r\nEmployee.code.is_null(False)\r\n```",
"```python\r\n\r\nseller_query = Employee.select().where(Employee.code.is_null(False))\r\nManager = Employee.alias()\r\nmanager_query = Manager.select().where(Manager.code.is_null(False))\r\n\r\nquery = (SalesDetails\r\n .select(SalesDetails, Employee, Manager)\r\n .join(seller_query, on=(SalesDetails.seller_code == seller_query.c.code), attr='seller')\r\n .join(manager_query, on=(SalesDetails.manager_code == manager_query.c.code), attr='manager'))\r\nfor sales_details in query:\r\n print(sales_details.id, sales_details.seller.code, sales_details.manager.code)\r\n```",
"I updated the code with [your suggestion](https://github.com/coleifer/peewee/issues/1948#issuecomment-500505104) and I got the same unexpected behavior.\r\n\r\nYour sample code showed [here](https://github.com/coleifer/peewee/issues/1948#issuecomment-500506931) does not work as well.\r\n\r\nAs a TSHOOT example, if I do the following, it does not work:\r\n```python\r\nlist(SalesDetails.raw(SalesDetails.valids().sql()[0], *SalesDetails.valids().sql()[1]))\r\n```\r\nBut if I do like that, it work properly:\r\n```python\r\nlist(SalesDetails.raw(\"\"\"\r\nSELECT t1.id, t1.seller_code, t1.manager_code\r\nFROM salesdetails AS t1\r\n INNER JOIN (SELECT t2.code FROM employee AS t2 WHERE (t2.code IS NOT NULL)) AS seller ON (t1.seller_code = seller.code)\r\n LEFT OUTER JOIN (SELECT t2.code FROM employee AS t2 WHERE (t2.code IS NOT NULL)) AS manager\r\n ON (t1.manager_code = manager.code)\r\n\"\"\"))\r\n```\r\n@coleifer it seems there is a bug during the bind logic between the RAW SQL and its parameters.\r\n\r\nJust to make it clear: the RAW SQL I set on the \"work properly\" example I got from Peewee.",
"@coleifer I found a \"better\" way to make it work:\r\n```python\r\nlist(SalesDetails.raw(SalesDetails.valids().sql()[0].replace(\"\\\"\", \"\"), *SalesDetails.valids().sql()[1]))\r\n```\r\nApparently the `\"` is the guy which causes the bug.\r\n",
"What all of this tells me is that Peewee is generating the correct SQL. I have *no* idea why or where you are getting confused. For example:\r\n\r\n> I got the same unexpected behavior.\r\n\r\n**What** unexpected behavior? You still have not specified, but remain stubbornly attached to your own idea of \"piping\" peewee's *correct* sql into a direct interface to the cursor.\r\n\r\n> Your sample code showed here does not work as well.\r\n\r\nIn what way does it \"not work\"?\r\n\r\nAs far as I can tell https://github.com/coleifer/peewee/issues/1948#issuecomment-500506931 should be the right general approach.\r\n\r\nPlease read:\r\n\r\n* http://docs.peewee-orm.com/en/latest/peewee/relationships.html\r\n* Specifically, [Selecting from multiple sources](http://docs.peewee-orm.com/en/latest/peewee/relationships.html#selecting-from-multiple-sources)",
"@willianantunes Just a note, in your minimal example, if I modify the query to include `.dicts()` and then print out the record, I get `{'id': 1, 'seller_code': 'A123456', 'manager_code': 'NON-EXIST'}`\r\n\r\nAnd if you look at where you declare the record, it is, in fact, `NON-EXIST`.\r\n\r\nAre you expecting `sd.manager_code` to be `None` because it should be the null side of the outer join from the query? That is not intended to be the case given what you've written.\r\n\r\nIf I wrote something like\r\n\r\n```python\r\n return (\r\n SalesDetails.select(SalesDetails.seller_code, SalesDetails.manager_code, seller.c.code.alias('scode'), manager.c.code.alias('mcode'))\r\n .join(\r\n seller,\r\n join_type=JOIN.INNER,\r\n on=(SalesDetails.seller_code == seller.c.code),\r\n )\r\n .join(\r\n manager,\r\n join_type=JOIN.LEFT_OUTER,\r\n on=(SalesDetails.manager_code == manager.c.code),\r\n )\r\n ).dicts()\r\n```\r\n\r\nThen I would generate\r\n\r\n```sql\r\nSELECT \"t1\".\"seller_code\", \"t1\".\"manager_code\", \"seller\".\"code\" AS \"scode\", \"manager\".\"code\" AS \"mcode\"\r\nFROM \"salesdetails\" AS \"t1\" INNER JOIN (SELECT \"t2\".\"code\" FROM \"employee\" AS \"t2\" WHERE (\"t2\".\"code\" IS NOT ?)) AS \"seller\" ON (\"t1\".\"seller_code\" = \"seller\".\"code\") LEFT OUTER JOIN (SELECT \"t2\".\"code\" FROM \"employee\" AS \"t2\" WHERE (\"t2\".\"code\" IS NOT ?)) AS \"manager\" ON (\"t1\".\"manager_code\" = \"manager\".\"code\")\r\n```\r\n\r\nand receive the following object (which corresponds to the attributes on a peewee object if I wasn't using a dict): `{'seller_code': 'A123456', 'manager_code': 'NON-EXIST', 'scode': 'A123456', 'mcode': None}`.\r\n\r\n`scode` and `mcode` correspond to the records on the joined table. They aren't included by default."
] | 2019-06-10T13:27:43 | 2019-06-11T23:09:37 | 2019-06-10T15:43:41 | NONE | null | I have the following sample module configuration to setup Peewee:
```python
from peewee import JOIN
from peewee import Model
from peewee import SqliteDatabase
from peewee import TextField
db = SqliteDatabase(f"tmp-sample.db")
class BaseModel(Model):
class Meta:
database = db
class Employee(BaseModel):
code = TextField(null=True, index=True)
@staticmethod
def valids(*fields):
return Employee.select(*fields).where(Employee.code.is_null(False))
class SalesDetails(BaseModel):
seller_code = TextField(null=True, index=True)
manager_code = TextField(null=True, index=True)
@staticmethod
def valids(*fields):
seller = Employee.valids(Employee.code).alias("seller")
manager = Employee.valids(Employee.code).alias("manager")
return (
SalesDetails.select(*fields)
.join(seller, join_type=JOIN.INNER, on=(SalesDetails.seller_code == seller.c.code))
.join(manager, join_type=JOIN.LEFT_OUTER, on=(SalesDetails.manager_code == manager.c.code))
)
db.connect()
# CREATE AND POPULATE DB
if not db.table_exists(SalesDetails):
db.create_tables([Employee, SalesDetails])
Employee(code="A123456").save()
SalesDetails(seller_code="A123456", manager_code="NON-EXIST").save()
try:
# ASSERTION THAT FAILS
for sd in SalesDetails.valids():
assert sd.seller_code == "A123456"
assert sd.manager_code is None
finally:
db.close()
```
When I execute the code above, the assertions statements does not pass. Sample output result:

The generated RAW SQL work properly, but the constructed object does not have the fields it should be. | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1948/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/1948/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1947 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1947/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1947/comments | https://api.github.com/repos/coleifer/peewee/issues/1947/events | https://github.com/coleifer/peewee/pull/1947 | 454,166,526 | MDExOlB1bGxSZXF1ZXN0Mjg2NjczNjI3 | 1,947 | Support raising custom DoesNotExist exceptions in models | {
"login": "onyb",
"id": 3684187,
"node_id": "MDQ6VXNlcjM2ODQxODc=",
"avatar_url": "https://avatars.githubusercontent.com/u/3684187?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/onyb",
"html_url": "https://github.com/onyb",
"followers_url": "https://api.github.com/users/onyb/followers",
"following_url": "https://api.github.com/users/onyb/following{/other_user}",
"gists_url": "https://api.github.com/users/onyb/gists{/gist_id}",
"starred_url": "https://api.github.com/users/onyb/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/onyb/subscriptions",
"organizations_url": "https://api.github.com/users/onyb/orgs",
"repos_url": "https://api.github.com/users/onyb/repos",
"events_url": "https://api.github.com/users/onyb/events{/privacy}",
"received_events_url": "https://api.github.com/users/onyb/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"@coleifer Could you please explain the reason why you closed this PR? Is raising custom `DoesNotExist` exceptions already possible with PeeWee, or perhaps there is something you'd like me to improve?"
] | 2019-06-10T13:18:18 | 2019-06-20T12:43:06 | 2019-06-10T15:41:33 | NONE | null | ### Why do we need this?
- The current way of raising a custom `DoesNotExist` exception is to override model methods like `.get_by_id()`, catch `DoesNotExist` and re-raise with a custom exception class. This is too much boilerplate for something that should be doable with something like:
```py
class BaseModel(Model):
DoesNotExist = MyCustomException
```
- Django ORM supports it, and so do most other ORMs. | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1947/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/1947/timeline | null | null | false | {
"url": "https://api.github.com/repos/coleifer/peewee/pulls/1947",
"html_url": "https://github.com/coleifer/peewee/pull/1947",
"diff_url": "https://github.com/coleifer/peewee/pull/1947.diff",
"patch_url": "https://github.com/coleifer/peewee/pull/1947.patch",
"merged_at": null
} |
https://api.github.com/repos/coleifer/peewee/issues/1946 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1946/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1946/comments | https://api.github.com/repos/coleifer/peewee/issues/1946/events | https://github.com/coleifer/peewee/issues/1946 | 453,941,121 | MDU6SXNzdWU0NTM5NDExMjE= | 1,946 | Mysql 1093 error | {
"login": "dzpt",
"id": 5781080,
"node_id": "MDQ6VXNlcjU3ODEwODA=",
"avatar_url": "https://avatars.githubusercontent.com/u/5781080?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/dzpt",
"html_url": "https://github.com/dzpt",
"followers_url": "https://api.github.com/users/dzpt/followers",
"following_url": "https://api.github.com/users/dzpt/following{/other_user}",
"gists_url": "https://api.github.com/users/dzpt/gists{/gist_id}",
"starred_url": "https://api.github.com/users/dzpt/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/dzpt/subscriptions",
"organizations_url": "https://api.github.com/users/dzpt/orgs",
"repos_url": "https://api.github.com/users/dzpt/repos",
"events_url": "https://api.github.com/users/dzpt/events{/privacy}",
"received_events_url": "https://api.github.com/users/dzpt/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"Found it there #1609 ",
"`on_delete='CASCADE'`.",
"Doesn't work on mysql 5.7.\r\ni have to upgrade to mariadb 10.3.15 to have `UPDATE Statements With the Same Source and Target`\r\nhttps://mariadb.com/kb/en/library/update/#update-statements-with-the-same-source-and-target",
"MySQL has supported ON DELETE CASCADE for ages. Here it is documented in the 5.5 manual:\r\n\r\n> CASCADE: Delete or update the row from the parent table, and automatically delete or update the matching rows in the child table. Both ON DELETE CASCADE and ON UPDATE CASCADE are supported.\r\n\r\nMariaDB has similarly supported this for ages.\r\n\r\nThere is also of course the option to ON DELETE SET NULL."
] | 2019-06-09T21:23:20 | 2019-06-10T17:27:07 | 2019-06-09T21:26:55 | NONE | null | I got this error after trying to delete a record which has dependency like this with mysql 5.7:
```
class Topic(BaseModel):
class Meta:
table_name = 'forum_topic'
id = AutoField()
class Post(BaseModel):
class Meta:
table_name = 'forum_post'
id = AutoField()
reply_to: Post = ForeignKeyField(
'self', null=True, default=None, backref='child_posts')
topic = ForeignKeyField(Topic, null=True, default=None, backref='posts')
```
> peewee.InternalError: (1093, "You can't specify target table 'forum_post' for update in FROM clause")
generated query:
``('DELETE FROM `forum_post` WHERE (`forum_post`.`reply_to_id` IN (SELECT `forum_post`.`id` FROM `forum_post` AS `forum_post` WHERE (`forum_post`.`topic_id` = %s)))', [2])`
1093 error: In MySQL you can't delete from the same table you are selecting from.
https://dev.mysql.com/doc/refman/8.0/en/subquery-restrictions.html | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1946/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/1946/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1945 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1945/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1945/comments | https://api.github.com/repos/coleifer/peewee/issues/1945/events | https://github.com/coleifer/peewee/issues/1945 | 453,702,688 | MDU6SXNzdWU0NTM3MDI2ODg= | 1,945 | Add support (or docs) for how to create jsonb indexes for Postgres | {
"login": "jboothatgranular",
"id": 19270303,
"node_id": "MDQ6VXNlcjE5MjcwMzAz",
"avatar_url": "https://avatars.githubusercontent.com/u/19270303?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/jboothatgranular",
"html_url": "https://github.com/jboothatgranular",
"followers_url": "https://api.github.com/users/jboothatgranular/followers",
"following_url": "https://api.github.com/users/jboothatgranular/following{/other_user}",
"gists_url": "https://api.github.com/users/jboothatgranular/gists{/gist_id}",
"starred_url": "https://api.github.com/users/jboothatgranular/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/jboothatgranular/subscriptions",
"organizations_url": "https://api.github.com/users/jboothatgranular/orgs",
"repos_url": "https://api.github.com/users/jboothatgranular/repos",
"events_url": "https://api.github.com/users/jboothatgranular/events{/privacy}",
"received_events_url": "https://api.github.com/users/jboothatgranular/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"Don't be a hero:\r\n\r\n```python\r\ndb.execute_sql(\"create index idx_data_foo ON layer USING gin (data->'foo');\")\r\n```"
] | 2019-06-07T21:34:58 | 2019-06-07T21:53:37 | 2019-06-07T21:53:37 | NONE | null | I'm trying to create a gin index on a postgres jsonb column.
```
=> \d layer
Table "public.layer"
Column | Type | Collation | Nullable | Default
-------------------------+------------------------+-----------+----------+---------
data | jsonb | | not null |
...
```
I can do in psql via `CREATE INDEX idx_data_foo ON layer USING gin ((data->'foo'));`
I can't seem to get it to go with the migrations support in playhouse. I have passing the whole `(data->'foo')` as a string, but it complains that isn't a column name. I've tried passing the column/JsonLookup `Layer.data["foo"]` but that isn't a string.
Is there a simple way this is expected to work that I'm missing? Needs documented? Needs implemented? Pointers if its needs implemented? Should I be doing the query a different way? (I'm trying to accelerate a `WHERE data->'foo'::text ?| '{a,b,c}'::text[]` type query) | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1945/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/1945/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1944 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1944/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1944/comments | https://api.github.com/repos/coleifer/peewee/issues/1944/events | https://github.com/coleifer/peewee/issues/1944 | 453,063,911 | MDU6SXNzdWU0NTMwNjM5MTE= | 1,944 | delete_instance with recursive=True only works with one level | {
"login": "dzpt",
"id": 5781080,
"node_id": "MDQ6VXNlcjU3ODEwODA=",
"avatar_url": "https://avatars.githubusercontent.com/u/5781080?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/dzpt",
"html_url": "https://github.com/dzpt",
"followers_url": "https://api.github.com/users/dzpt/followers",
"following_url": "https://api.github.com/users/dzpt/following{/other_user}",
"gists_url": "https://api.github.com/users/dzpt/gists{/gist_id}",
"starred_url": "https://api.github.com/users/dzpt/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/dzpt/subscriptions",
"organizations_url": "https://api.github.com/users/dzpt/orgs",
"repos_url": "https://api.github.com/users/dzpt/repos",
"events_url": "https://api.github.com/users/dzpt/events{/privacy}",
"received_events_url": "https://api.github.com/users/dzpt/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"Oh, yeah - I don't think it correctly handles foreign-keys to self. The best way is to lean on your database to handle this with an `on_delete=...` in your `ForeignKeyField()` declaration.",
"@coleifer Oh, so what's the purpose of recursive flag, it only works for 1 level?\r\n\r\nhttps://github.com/coleifer/flask-peewee/issues/31\r\nI've read this post and thought peewee can do delete recursively.\r\n\r\nSelf-reference is needed to be use on multiple level items like categories, posts.\r\nI use mysql, so any other way to do delete recursively? Or i have to override `delete` method to implement it myself?",
"If you have a row with a deep dependency graph of foreign-keys, it will correctly handle dependent rows without leaving orphaned data. That is the purpose.\r\n\r\nThe reason it does not support hierarchical data (i.e. self-referential foreign-keys) is to avoid cycles in the dependency graph.\r\n\r\n> I use mysql\r\n\r\nDoesn't innodb support ON DELETE constraints?",
"> avoid cycles in the dependency graph.\r\n\r\nCan we check the type of foreign key before deleting, it would avoid circular delete?\r\nI prefer to do delete on code rather than depend on db.\r\n\r\n\r\n\r\n",
"I remembered that the other - in fact, main - reason for not supporting this is that we don't know how *deep* into the graph to go without resolving foreign-keys at every step.\r\n\r\nSo with a non-self-referential graph of foreign-keys, we just make sure to issue a query for each node in the graph (each foreign-key). With self-referential, we would have to issue *n* deletes where *n* is the maximum depth of any row's relations. But we don't know how far to go without resolving at each step. So peewee doesn't do this, but you could very easily write it yourself.\r\n\r\nOr just use the database. The database knows how to delete a self-referential collection of rows. That is why the `ON DELETE` constraint exists. Use it!\r\n\r\n> I prefer to do delete on code rather than depend on db.\r\n\r\nWhy? To my thinking that's 100% backwards."
] | 2019-06-06T14:29:44 | 2019-06-09T14:27:49 | 2019-06-09T14:27:49 | NONE | null | I have a table with foreign key to itself
```
class Post(BaseModel):
reply_to: Post = ForeignKeyField(
'self', null=True, default=None, backref='child_posts', on_delete='CASCADE')
```
Then in db if i have
```
id reply_to_id
1 nulll
2 1
3 2
4 3
5 4
```
If i `delete_instance(True, True)` record `id=2`, it deletes ID `2,3` only and leave ID `4,5`.
It means it doesn't delete recursively (only works for 1 level).
Did i miss something or i have to deploy delete recursively by myself? | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1944/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/1944/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1943 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1943/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1943/comments | https://api.github.com/repos/coleifer/peewee/issues/1943/events | https://github.com/coleifer/peewee/issues/1943 | 452,483,430 | MDU6SXNzdWU0NTI0ODM0MzA= | 1,943 | Pandas DataFrame as peewee backend | {
"login": "isthisthat",
"id": 1259045,
"node_id": "MDQ6VXNlcjEyNTkwNDU=",
"avatar_url": "https://avatars.githubusercontent.com/u/1259045?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/isthisthat",
"html_url": "https://github.com/isthisthat",
"followers_url": "https://api.github.com/users/isthisthat/followers",
"following_url": "https://api.github.com/users/isthisthat/following{/other_user}",
"gists_url": "https://api.github.com/users/isthisthat/gists{/gist_id}",
"starred_url": "https://api.github.com/users/isthisthat/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/isthisthat/subscriptions",
"organizations_url": "https://api.github.com/users/isthisthat/orgs",
"repos_url": "https://api.github.com/users/isthisthat/repos",
"events_url": "https://api.github.com/users/isthisthat/events{/privacy}",
"received_events_url": "https://api.github.com/users/isthisthat/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"> sqlite writes and reads are painfully slow (10x slower) on my system through the python interface\r\n\r\nWhat driver are you using?\r\n\r\nHow are you executing these queries?\r\n\r\nCompared to what? C? The sqlite3 shell?\r\n\r\n> Is a pandas DataFrame something you might consider supporting as a back-end natively?\r\n\r\nSorry, definitely not.",
"> What driver are you using?\r\n\r\nI've tried `SqliteDatabase`, `SqliteExtDatabase` and `APSWDatabase` with all the `PRAGMA` tips and tricks I could find.\r\n\r\n> How are you executing these queries?\r\n\r\nUsing e.g. list(Model.select(...).where(...).dicts())\r\n\r\n> Compared to what?\r\n\r\nThe sqlite3 shell"
] | 2019-06-05T12:50:59 | 2019-06-05T14:57:31 | 2019-06-05T14:45:42 | NONE | null | Hi @coleifer, for some reason sqlite writes and reads are painfully slow (10x slower) on my system through the python interface. System commands to sqlite are fast as expected. I've been experimenting replacing the sqlite back-end with a pandas DataFrame. I had some success using peewee Model select `.sql()` and then `pandasql.sqldf(sql)` to query a DataFrame. However that still loads data to an sqlite db behind the scenes so was taking up twice the memory. Is a pandas DataFrame something you might consider supporting as a back-end natively? I guess the missing link is a translation from sql to pandas query syntax as outlined [here](https://pandas.pydata.org/pandas-docs/stable/getting_started/comparison/comparison_with_sql.html). Thanks! | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1943/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/1943/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1942 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1942/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1942/comments | https://api.github.com/repos/coleifer/peewee/issues/1942/events | https://github.com/coleifer/peewee/pull/1942 | 451,939,740 | MDExOlB1bGxSZXF1ZXN0Mjg0OTI3NjQz | 1,942 | replace instance delete method with model delete method | {
"login": "fenngwd",
"id": 8489549,
"node_id": "MDQ6VXNlcjg0ODk1NDk=",
"avatar_url": "https://avatars.githubusercontent.com/u/8489549?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/fenngwd",
"html_url": "https://github.com/fenngwd",
"followers_url": "https://api.github.com/users/fenngwd/followers",
"following_url": "https://api.github.com/users/fenngwd/following{/other_user}",
"gists_url": "https://api.github.com/users/fenngwd/gists{/gist_id}",
"starred_url": "https://api.github.com/users/fenngwd/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/fenngwd/subscriptions",
"organizations_url": "https://api.github.com/users/fenngwd/orgs",
"repos_url": "https://api.github.com/users/fenngwd/repos",
"events_url": "https://api.github.com/users/fenngwd/events{/privacy}",
"received_events_url": "https://api.github.com/users/fenngwd/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"Thanks! This makes sense to me.",
"Another option would be for me to move those methods (delete, insert, select, update) to the metaclass instead. That would expose them as class-methods on model classes, but prevent you from accidentally calling them on a model instance. Might be worth doing in the near future."
] | 2019-06-04T11:21:16 | 2019-06-04T11:50:21 | 2019-06-04T11:43:57 | CONTRIBUTOR | null | The pitfalls of delete method in instance are numerous. It may cause unintended consequences, such as truncating table.
I want to disable delete method call and raise warning in instance. After reading the code, I found that delete_instance use delete to do the actual dirty work in instance. Because of this, disabling delete method is difficult without changing delete_instance method. I have to copy delete_instance 's code and fix it to workaround this.
If code is changed as below, we can still call delete method in Model Object without any change, and call delete_instance method in Model's instance correctly, and at the same time, we can override delete method in instance to disable usage in instance for avoiding unexpected consequences. | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1942/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/1942/timeline | null | null | false | {
"url": "https://api.github.com/repos/coleifer/peewee/pulls/1942",
"html_url": "https://github.com/coleifer/peewee/pull/1942",
"diff_url": "https://github.com/coleifer/peewee/pull/1942.diff",
"patch_url": "https://github.com/coleifer/peewee/pull/1942.patch",
"merged_at": "2019-06-04T11:43:57"
} |
https://api.github.com/repos/coleifer/peewee/issues/1941 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1941/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1941/comments | https://api.github.com/repos/coleifer/peewee/issues/1941/events | https://github.com/coleifer/peewee/issues/1941 | 451,509,179 | MDU6SXNzdWU0NTE1MDkxNzk= | 1,941 | alias function partly broken in peewee 3.9.4 and 3.9.5 | {
"login": "anne17",
"id": 1526661,
"node_id": "MDQ6VXNlcjE1MjY2NjE=",
"avatar_url": "https://avatars.githubusercontent.com/u/1526661?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/anne17",
"html_url": "https://github.com/anne17",
"followers_url": "https://api.github.com/users/anne17/followers",
"following_url": "https://api.github.com/users/anne17/following{/other_user}",
"gists_url": "https://api.github.com/users/anne17/gists{/gist_id}",
"starred_url": "https://api.github.com/users/anne17/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/anne17/subscriptions",
"organizations_url": "https://api.github.com/users/anne17/orgs",
"repos_url": "https://api.github.com/users/anne17/repos",
"events_url": "https://api.github.com/users/anne17/events{/privacy}",
"received_events_url": "https://api.github.com/users/anne17/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"Thanks, I've been able to replicate this and am working on a fix.",
"Fixed, pushing a new release 3.9.6",
"See also #1914",
"Sorry to be bugging you again, but will you be pushing the new release to pypi?",
"I thought I had, 3.9.6? https://github.com/coleifer/peewee/releases/tag/3.9.6",
"Oh, guess not, done.",
"Great, thank you!"
] | 2019-06-03T14:16:33 | 2019-06-07T08:19:33 | 2019-06-03T14:56:47 | NONE | null | I just upgraded from peewee 3.9.3 to 3.9.5 and suddenly I am getting the following error:
``` File "/home/anne/projects/recapi/recapi/views/recipe_data.py", line 39, in get_recipe_data
User, pw.JOIN.LEFT_OUTER, on=(User.id == recipemodel.Recipe.created_by).alias("a")
File "/home/anne/projects/recapi/venv/lib/python3.7/site-packages/peewee.py", line 698, in inner
method(clone, *args, **kwargs)
File "/home/anne/projects/recapi/venv/lib/python3.7/site-packages/peewee.py", line 6603, in join
on, attr, constructor = self._normalize_join(src, dest, on, attr)
File "/home/anne/projects/recapi/venv/lib/python3.7/site-packages/peewee.py", line 6534, in _normalize_join
attr == fk_field.object_id_name and not is_backref:
AttributeError: 'AutoField' object has no attribute 'object_id_name'
```
The same error occurs in peewee 3.9.4 but everything is running fine in 3.9.3. The code piece that breaks looks like this:
```Changed = User.alias()
recipes = recipemodel.Recipe.select(
recipemodel.Recipe, User, Changed, pw.fn.group_concat(tagmodel.Tag.tagname).alias("taglist")
).where(
recipemodel.Recipe.published == published
).join(
User, pw.JOIN.LEFT_OUTER, on=(User.id == recipemodel.Recipe.created_by).alias("a")
).switch(
recipemodel.Recipe
).join(
Changed, pw.JOIN.LEFT_OUTER, on=(Changed.id == recipemodel.Recipe.changed_by).alias("b")
).switch(
recipemodel.Recipe
).join(
tagmodel.RecipeTags, pw.JOIN.LEFT_OUTER, on=(tagmodel.RecipeTags.recipeID == recipemodel.Recipe.id)
).join(
tagmodel.Tag, pw.JOIN.LEFT_OUTER, on=(tagmodel.Tag.id == tagmodel.RecipeTags.tagID)
).group_by(recipemodel.Recipe.id)
```
It's the `.alias("a")` and `.alias("b")` bits that seem to be causing the trouble.
Please let me know if there is any relevant information lacking from this bug report. | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1941/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/1941/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1940 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1940/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1940/comments | https://api.github.com/repos/coleifer/peewee/issues/1940/events | https://github.com/coleifer/peewee/pull/1940 | 451,335,608 | MDExOlB1bGxSZXF1ZXN0Mjg0NDQ2Mzg3 | 1,940 | replace instance delete method with model delete method | {
"login": "fenngwd",
"id": 8489549,
"node_id": "MDQ6VXNlcjg0ODk1NDk=",
"avatar_url": "https://avatars.githubusercontent.com/u/8489549?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/fenngwd",
"html_url": "https://github.com/fenngwd",
"followers_url": "https://api.github.com/users/fenngwd/followers",
"following_url": "https://api.github.com/users/fenngwd/following{/other_user}",
"gists_url": "https://api.github.com/users/fenngwd/gists{/gist_id}",
"starred_url": "https://api.github.com/users/fenngwd/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/fenngwd/subscriptions",
"organizations_url": "https://api.github.com/users/fenngwd/orgs",
"repos_url": "https://api.github.com/users/fenngwd/repos",
"events_url": "https://api.github.com/users/fenngwd/events{/privacy}",
"received_events_url": "https://api.github.com/users/fenngwd/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [] | 2019-06-03T07:39:05 | 2019-06-03T16:09:32 | 2019-06-03T16:09:32 | CONTRIBUTOR | null | The pitfalls of `delete` method in instance are numerous. It may cause unintended consequences, such as truncating table.
I want to disable `delete` method call and raise warning in instance. After reading the code, I found that `delete_instance` use `delete` to do the actual dirty work in instance. Because of this, disabling `delete` method is difficult without changing `delete_instance` method. I have to copy `delete_instance` 's code and fix it to workaround this.
If code is changed as below, we can still call `delete` method in Model Object without any change, and call `delete_instance` method in Model's instance correctly, and at the same time, we can override `delete` method in instance to disable usage in instance for avoiding unexpected consequences. | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1940/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/1940/timeline | null | null | false | {
"url": "https://api.github.com/repos/coleifer/peewee/pulls/1940",
"html_url": "https://github.com/coleifer/peewee/pull/1940",
"diff_url": "https://github.com/coleifer/peewee/pull/1940.diff",
"patch_url": "https://github.com/coleifer/peewee/pull/1940.patch",
"merged_at": null
} |
https://api.github.com/repos/coleifer/peewee/issues/1939 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1939/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1939/comments | https://api.github.com/repos/coleifer/peewee/issues/1939/events | https://github.com/coleifer/peewee/issues/1939 | 449,696,029 | MDU6SXNzdWU0NDk2OTYwMjk= | 1,939 | Peewee 3.9.5 throws TypeError on Windows running Python 3.7 | {
"login": "sn0opy",
"id": 49074,
"node_id": "MDQ6VXNlcjQ5MDc0",
"avatar_url": "https://avatars.githubusercontent.com/u/49074?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/sn0opy",
"html_url": "https://github.com/sn0opy",
"followers_url": "https://api.github.com/users/sn0opy/followers",
"following_url": "https://api.github.com/users/sn0opy/following{/other_user}",
"gists_url": "https://api.github.com/users/sn0opy/gists{/gist_id}",
"starred_url": "https://api.github.com/users/sn0opy/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/sn0opy/subscriptions",
"organizations_url": "https://api.github.com/users/sn0opy/orgs",
"repos_url": "https://api.github.com/users/sn0opy/repos",
"events_url": "https://api.github.com/users/sn0opy/events{/privacy}",
"received_events_url": "https://api.github.com/users/sn0opy/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"What-the-what? Can you share how you're setting up and tearing down your connections? This seems like it should only happen if two conns are created at the *exact same timestamp*.",
"The code is open source. I'm linking the diff to the python2 to 3 migration. Unfortunately, I', not really that much into peewee and flask, but I hope the following diff helps anyway\r\n\r\nhttps://github.com/cecpk/OSM-Rocketmap/commit/79539952592f7fb78c061373dabb664f533354d0#diff-541e2b217ba4a7d7859dae2cb443b6b7",
"Not sure, can you provide a script to replicate?\r\n\r\nClosing as I don't anticipate this being likely, but will gladly reopen if you can do so."
] | 2019-05-29T09:26:30 | 2019-05-30T20:11:17 | 2019-05-30T20:11:16 | NONE | null | I'm getting the following stack trace running on Windows with Python 3.7. The exact same code runs fine on Linux with Python 3.5 up to 3.7.
Is there anything, that has to be tweaked in my own code to run on Windows properly or is there an actual issue in Peewee's code? The Flask version being used on Linux and Windows is 1.0.3.
```
Traceback (most recent call last):
File "C:\Python37\lib\site-packages\flask\app.py", line 2311, in wsgi_app
response = self.full_dispatch_request()
File "C:\Python37\lib\site-packages\flask\app.py", line 1834, in full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\Python37\lib\site-packages\flask\app.py", line 1737, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "C:\Python37\lib\site-packages\flask\_compat.py", line 36, in reraise
raise value
File "C:\Python37\lib\site-packages\flask\app.py", line 1830, in full_dispatch_request
rv = self.preprocess_request()
File "C:\Python37\lib\site-packages\flask\app.py", line 2106, in preprocess_request
rv = func()
File "C:\Python37\lib\site-packages\playhouse\flask_utils.py", line 181, in connect_db
self.database.connect()
File "C:\Python37\lib\site-packages\playhouse\pool.py", line 108, in connect
return super(PooledDatabase, self).connect(reuse_if_open)
File "C:\Python37\lib\site-packages\peewee.py", line 2882, in connect
self._state.set_connection(self._connect())
File "C:\Python37\lib\site-packages\playhouse\pool.py", line 125, in _connect
ts, conn = heapq.heappop(self._connections)
TypeError: '<' not supported between instances of 'Connection' and 'Connection'
``` | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1939/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/1939/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1938 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1938/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1938/comments | https://api.github.com/repos/coleifer/peewee/issues/1938/events | https://github.com/coleifer/peewee/issues/1938 | 448,426,697 | MDU6SXNzdWU0NDg0MjY2OTc= | 1,938 | Handle missing record for ForeignKeyField | {
"login": "dzpt",
"id": 5781080,
"node_id": "MDQ6VXNlcjU3ODEwODA=",
"avatar_url": "https://avatars.githubusercontent.com/u/5781080?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/dzpt",
"html_url": "https://github.com/dzpt",
"followers_url": "https://api.github.com/users/dzpt/followers",
"following_url": "https://api.github.com/users/dzpt/following{/other_user}",
"gists_url": "https://api.github.com/users/dzpt/gists{/gist_id}",
"starred_url": "https://api.github.com/users/dzpt/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/dzpt/subscriptions",
"organizations_url": "https://api.github.com/users/dzpt/orgs",
"repos_url": "https://api.github.com/users/dzpt/repos",
"events_url": "https://api.github.com/users/dzpt/events{/privacy}",
"received_events_url": "https://api.github.com/users/dzpt/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"> After the record has been deleted but still has reference from other table, i'll get *DoesNotExist: instance matching query does not exist error if i access to record.edited_by_user\r\n\r\nWhat do you mean, you have orphaned `User` instances? e.g., the `edited_by_user` column contains a user id for which no corresponding user row exists?\r\n\r\nIf this is the case, then google \"referential integrity\". Your database should be enforcing these kinds of constraints, updating orphaned foreign-keys to NULL is supported by many databases. Peewee implements this as well via the `delete_instance(recursive=True, delete_nullable=False)`."
] | 2019-05-25T06:24:35 | 2019-05-26T03:02:38 | 2019-05-26T03:02:38 | NONE | null | `edited_by_user = ForeignKeyField(User, null=True)`
After the record has been deleted but still has reference from other table, i'll get `*DoesNotExist: instance matching query does not exist error if i access to record.edited_by_user`
How do i get rid of it like the record is null then return None like `get_or_none`?
This case can be annoying to None object model in template.
It's impossible to use `try/except` in template? Then i have to write another method to check if the field is getable or not
```
def get_edited_by_user()
try/except ....
```
Then assign it to the template.
That's so annoying. It should be another argument to determine return None for empty/missing ForeignKeyField | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1938/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/1938/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1937 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1937/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1937/comments | https://api.github.com/repos/coleifer/peewee/issues/1937/events | https://github.com/coleifer/peewee/issues/1937 | 448,353,953 | MDU6SXNzdWU0NDgzNTM5NTM= | 1,937 | Syntax for using json_each in subquery | {
"login": "brandond",
"id": 370103,
"node_id": "MDQ6VXNlcjM3MDEwMw==",
"avatar_url": "https://avatars.githubusercontent.com/u/370103?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/brandond",
"html_url": "https://github.com/brandond",
"followers_url": "https://api.github.com/users/brandond/followers",
"following_url": "https://api.github.com/users/brandond/following{/other_user}",
"gists_url": "https://api.github.com/users/brandond/gists{/gist_id}",
"starred_url": "https://api.github.com/users/brandond/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/brandond/subscriptions",
"organizations_url": "https://api.github.com/users/brandond/orgs",
"repos_url": "https://api.github.com/users/brandond/repos",
"events_url": "https://api.github.com/users/brandond/events{/privacy}",
"received_events_url": "https://api.github.com/users/brandond/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"Hmm, I think I found something that works, although I'm not sure if it's the best way to do it:\r\n\r\n```python\r\ntve = peewee.fn.json_each('[1,2,3]').alias('tve')\r\ninactive_users = peewee.Select(from_list=[tve], columns=[tve.c.value]).cte('inactive_users')\r\ndq = (Tweet\r\n .delete()\r\n .where(Tweet.user_id << inactive_users)\r\n .with_cte(inactive_users))\r\ndq.execute()\r\n\r\n```",
"I guess the proper way to do this would be to have `json_each` registered as a TableFunction, but right now we only get to use it through `JSONField.children()`, unless I'm missing something.",
"Whoa, whoa... Slow down!\r\n\r\n```python\r\n\r\nid_list = [1, 2, 3]\r\nid_json = json.dumps(id_list)\r\n\r\nsubq = Select(from_list=fn.json_each(id_json), columns=[Entity('value')])\r\nquery = Tweet.delete().where(Tweet.id.in_(subq))\r\n```\r\n\r\nThis works fine for me.",
"I think the crux of the problem is that your \"column\" is being treated as a sql parameter rather than a column name. Hence I use `columns=[Entity('value')]` to indicate this is a name.",
"Thanks - that'll work! I couldn't figure out how to get it to recognize 'value' as a column name without binding it to something.",
"@coleifer - For the record, when I try this as shown in your example on a Select query I get the following error:\r\n`TypeError: object of type 'Function' has no len()`\r\n\r\nI think it should be:\r\n```python\r\nsubq = Select(from_list=[fn.json_each(id_json)], columns=[Entity('value')])\r\n```\r\n",
"Oh right, yep."
] | 2019-05-24T21:08:17 | 2019-05-28T20:26:28 | 2019-05-28T17:03:53 | NONE | null | I'm trying to do something like this:
```sql
DELETE FROM tweet WHERE tweet.user_id IN (SELECT value FROM json_each('[1,2,3]'))
```
I have tried something like this, but it ends up selecting the literal string 'value' instead of the value column:
```python
inactive_users = peewee.Select(from_list=[peewee.fn.json_each('[1,2,3]')], columns=['value'])
dq = (Tweet
.delete()
.where(Tweet.user.in_(inactive_users)))
dq.execute()
```
In reality the JSON list is actually sourced from another query that's using the `json_group_array` aggregation to output a lengthy list of IDs that I am doing some post-processing on. If I simply pass the Python list in directly, it binds a host parameter for each list entry, which ends up overrunning the sqlite SQLITE_MAX_VARIABLE_NUMBER limit if the list is large; I'm trying to work around this by serializing the list back to a JSON string and then using the table-valued `json_each` function in a subquery to split it back out. | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1937/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/1937/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1936 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1936/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1936/comments | https://api.github.com/repos/coleifer/peewee/issues/1936/events | https://github.com/coleifer/peewee/issues/1936 | 447,466,285 | MDU6SXNzdWU0NDc0NjYyODU= | 1,936 | python 3.6.8 DateTimeField formats 无效 | {
"login": "itmeryn",
"id": 18156931,
"node_id": "MDQ6VXNlcjE4MTU2OTMx",
"avatar_url": "https://avatars.githubusercontent.com/u/18156931?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/itmeryn",
"html_url": "https://github.com/itmeryn",
"followers_url": "https://api.github.com/users/itmeryn/followers",
"following_url": "https://api.github.com/users/itmeryn/following{/other_user}",
"gists_url": "https://api.github.com/users/itmeryn/gists{/gist_id}",
"starred_url": "https://api.github.com/users/itmeryn/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/itmeryn/subscriptions",
"organizations_url": "https://api.github.com/users/itmeryn/orgs",
"repos_url": "https://api.github.com/users/itmeryn/repos",
"events_url": "https://api.github.com/users/itmeryn/events{/privacy}",
"received_events_url": "https://api.github.com/users/itmeryn/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"Is there a question? Under certain conditions and depending on your database driver, the date/time may be returned from the database cursor as a string. Similarly if you're loading csv or json into your date/time-field, it may be a string.",
"按照截图的逻辑 就会直接返回value 字段中配置的format 并没有生效",
"English. Still not a clue what this issue is about.",
"According to the logic of the screenshot, the format directly returned in the value field does not take effect."
] | 2019-05-23T06:09:26 | 2019-05-26T14:04:41 | 2019-05-23T10:29:57 | NONE | null |



| {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1936/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/1936/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1935 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1935/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1935/comments | https://api.github.com/repos/coleifer/peewee/issues/1935/events | https://github.com/coleifer/peewee/issues/1935 | 447,323,241 | MDU6SXNzdWU0NDczMjMyNDE= | 1,935 | Auto change IntegerField to ForeignKeyField? | {
"login": "dzpt",
"id": 5781080,
"node_id": "MDQ6VXNlcjU3ODEwODA=",
"avatar_url": "https://avatars.githubusercontent.com/u/5781080?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/dzpt",
"html_url": "https://github.com/dzpt",
"followers_url": "https://api.github.com/users/dzpt/followers",
"following_url": "https://api.github.com/users/dzpt/following{/other_user}",
"gists_url": "https://api.github.com/users/dzpt/gists{/gist_id}",
"starred_url": "https://api.github.com/users/dzpt/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/dzpt/subscriptions",
"organizations_url": "https://api.github.com/users/dzpt/orgs",
"repos_url": "https://api.github.com/users/dzpt/repos",
"events_url": "https://api.github.com/users/dzpt/events{/privacy}",
"received_events_url": "https://api.github.com/users/dzpt/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"When you write:\r\n\r\n```python\r\ngroup = ForeignKeyField(AdminGroup)\r\n```\r\n\r\nPeewee will add a column `group_id` which stores the related `AdminGroup.id` value. So you're stepping on your own toes.\r\n\r\nAdditionally, every `ForeignKeyField` by default will add a \"<field_name>_id\" descriptor to the model, which provides access to the underlying `AdminGroup.id` value (e.g., the integer, not an `AdminGroup` instance).\r\n\r\nJust use `group = ForeignKeyField(AdminGroup)`. Peewee automatically creates an equivalent integer field for you at `group_id`.",
"Thank you, but i need to declare `group_id` for using on other part of my code.\r\nAny chance to get the real type before bind that to `ObjectIdAccessor` or disable this feature?",
"So `group` and `group_id` are totally different values, then?\r\n\r\nIn that case you can either:\r\n\r\n- set the `column_name` parameter of the `group` foreign key field\r\n- set the `object_id_name` parameter of the `group` foreign key field to something other than `group_id` so it doesn't conflict"
] | 2019-05-22T20:16:04 | 2019-05-22T20:58:17 | 2019-05-22T20:43:40 | NONE | null | I have a model like this
```
class AdminUser(BaseModel):
class Meta:
table_name = '_admin_user'
id = AutoField()
group_id = IntegerField()
group: AdminGroup = ForeignKeyField(AdminGroup)
```
After checking type of `group_id` field by using `type(getattr(model, 'group_id')`, it becomes `ForeignKeyField `, not `IntegerField` any more.
But after moving group_id under group field, it won't happen any more, `group_id` type will be `IntergerField`
```
group: AdminGroup = ForeignKeyField(AdminGroup)
group_id = IntegerField()
```
Why is that and how do i preserve / get the correct field type of `*_id`? | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1935/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/1935/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1934 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1934/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1934/comments | https://api.github.com/repos/coleifer/peewee/issues/1934/events | https://github.com/coleifer/peewee/issues/1934 | 446,007,532 | MDU6SXNzdWU0NDYwMDc1MzI= | 1,934 | Rawquery with table name doesn't work?! | {
"login": "dzpt",
"id": 5781080,
"node_id": "MDQ6VXNlcjU3ODEwODA=",
"avatar_url": "https://avatars.githubusercontent.com/u/5781080?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/dzpt",
"html_url": "https://github.com/dzpt",
"followers_url": "https://api.github.com/users/dzpt/followers",
"following_url": "https://api.github.com/users/dzpt/following{/other_user}",
"gists_url": "https://api.github.com/users/dzpt/gists{/gist_id}",
"starred_url": "https://api.github.com/users/dzpt/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/dzpt/subscriptions",
"organizations_url": "https://api.github.com/users/dzpt/orgs",
"repos_url": "https://api.github.com/users/dzpt/repos",
"events_url": "https://api.github.com/users/dzpt/events{/privacy}",
"received_events_url": "https://api.github.com/users/dzpt/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"You can't put the table-name in as a parameterized query with your MySQL driver. Simple as that. For instance, with SQLite, this comes up in other places, too -- like if you're creating an INDEX on an expression, you can't use parameter placeholders for the expression values."
] | 2019-05-20T09:16:48 | 2019-05-20T11:42:03 | 2019-05-20T11:42:03 | NONE | null | Mysql 5.7
Peewee 3.9.5
-
I use this code
`db.execute_sql("select count(*) from %s", ('_admin_group',))`
and got this
`peewee.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''_admin_group'' at line 1")`
but this one works
`db.execute_sql("select * from _admin_group where id=%s", (1,))`
Is there any problem while working with table name? | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1934/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/1934/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1933 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1933/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1933/comments | https://api.github.com/repos/coleifer/peewee/issues/1933/events | https://github.com/coleifer/peewee/issues/1933 | 444,358,757 | MDU6SXNzdWU0NDQzNTg3NTc= | 1,933 | How to generate sql to carry database name? | {
"login": "ztj1993",
"id": 13493380,
"node_id": "MDQ6VXNlcjEzNDkzMzgw",
"avatar_url": "https://avatars.githubusercontent.com/u/13493380?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/ztj1993",
"html_url": "https://github.com/ztj1993",
"followers_url": "https://api.github.com/users/ztj1993/followers",
"following_url": "https://api.github.com/users/ztj1993/following{/other_user}",
"gists_url": "https://api.github.com/users/ztj1993/gists{/gist_id}",
"starred_url": "https://api.github.com/users/ztj1993/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/ztj1993/subscriptions",
"organizations_url": "https://api.github.com/users/ztj1993/orgs",
"repos_url": "https://api.github.com/users/ztj1993/repos",
"events_url": "https://api.github.com/users/ztj1993/events{/privacy}",
"received_events_url": "https://api.github.com/users/ztj1993/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"Yes, you can use the `schema` parameter:\r\n\r\n```python\r\nclass AttrModel(Model):\r\n id = AutoField() # NOTE: use AutoField, not PrimaryKeyField, which is deprecated.\r\n\r\n class Meta:\r\n table_name = 'attrs'\r\n schema = 'silo'\r\n\r\n# AttrModel will now be queried like \"select * from silo.attrs as t1\".\r\n```",
"@coleifer Thank you!"
] | 2019-05-15T10:26:05 | 2019-05-16T01:23:22 | 2019-05-15T11:52:26 | NONE | null | model:
```
class AttrModel(Model):
id = PrimaryKeyField(help_text='id')
class Meta:
table_name = 'attrs'
database = MySQLDatabase(database='silo')
```
generate sql:
```
sql = AttrModel.select().sql()
print(sql)
```
result:
```
('SELECT `t1`.`id` FROM `attrs` AS `t1`', [])
```
I want result:
```
('SELECT `t1`.`id` FROM `attrs` AS `silo`.`t1`', [])
```
Can it be realized?
| {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1933/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/1933/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1932 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1932/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1932/comments | https://api.github.com/repos/coleifer/peewee/issues/1932/events | https://github.com/coleifer/peewee/issues/1932 | 444,306,592 | MDU6SXNzdWU0NDQzMDY1OTI= | 1,932 | Get initial value of dirty fields. | {
"login": "lalit-lintel",
"id": 26576603,
"node_id": "MDQ6VXNlcjI2NTc2NjAz",
"avatar_url": "https://avatars.githubusercontent.com/u/26576603?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/lalit-lintel",
"html_url": "https://github.com/lalit-lintel",
"followers_url": "https://api.github.com/users/lalit-lintel/followers",
"following_url": "https://api.github.com/users/lalit-lintel/following{/other_user}",
"gists_url": "https://api.github.com/users/lalit-lintel/gists{/gist_id}",
"starred_url": "https://api.github.com/users/lalit-lintel/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/lalit-lintel/subscriptions",
"organizations_url": "https://api.github.com/users/lalit-lintel/orgs",
"repos_url": "https://api.github.com/users/lalit-lintel/repos",
"events_url": "https://api.github.com/users/lalit-lintel/events{/privacy}",
"received_events_url": "https://api.github.com/users/lalit-lintel/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"> It is great if peewee also manages the old/initial value of fields when it gets changed.\r\n>\r\n> There anything is available which can help to get the inital value of fields?\r\n\r\nYou need to manage this yourself, unfortunately.\r\n\r\nPeewee has very simplistic tracking for when fields are assigned, but this was only designed to simplify the use-case of when you have a lot of columns but only need to save a subset of them.\r\n\r\nIf you need to find original values, you can always query the DB for the current state of the row data.\r\n\r\nAnother option would be to mess around with overriding `Model.__init__` to add extra logic for saving the initial data the model is instantiated with.",
"```python\r\nclass MyModel(Model):\r\n field1 = TextField()\r\n ... etc ...\r\n\r\n def __init__(self, **kwargs):\r\n super(MyModel, self).__init__(**kwargs)\r\n self._initial_data = self.__data__.copy()\r\n```",
"> ```python\r\n> class MyModel(Model):\r\n> field1 = TextField()\r\n> ... etc ...\r\n> \r\n> def __init__(self, **kwargs):\r\n> super(MyModel, self).__init__(**kwargs)\r\n> self._initial_data = self.__data__.copy()\r\n> ```\r\n\r\nThanks for this hint, I got the expected result with this."
] | 2019-05-15T08:35:37 | 2019-05-17T05:07:44 | 2019-05-15T11:56:14 | NONE | null | Peewee has a feature that manages dirty fields.
It managing the list of fields name, which is changed, but not the old/initial value of those fields.
It is great if peewee also manages the old/initial value of fields when it gets changed.
There anything is available which can help to get the inital value of fields? | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1932/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/1932/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1931 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1931/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1931/comments | https://api.github.com/repos/coleifer/peewee/issues/1931/events | https://github.com/coleifer/peewee/issues/1931 | 443,944,983 | MDU6SXNzdWU0NDM5NDQ5ODM= | 1,931 | bulk_create throws NotNullViolation when DEFAULT constraint is present | {
"login": "ymrzkrrs",
"id": 43073619,
"node_id": "MDQ6VXNlcjQzMDczNjE5",
"avatar_url": "https://avatars.githubusercontent.com/u/43073619?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/ymrzkrrs",
"html_url": "https://github.com/ymrzkrrs",
"followers_url": "https://api.github.com/users/ymrzkrrs/followers",
"following_url": "https://api.github.com/users/ymrzkrrs/following{/other_user}",
"gists_url": "https://api.github.com/users/ymrzkrrs/gists{/gist_id}",
"starred_url": "https://api.github.com/users/ymrzkrrs/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/ymrzkrrs/subscriptions",
"organizations_url": "https://api.github.com/users/ymrzkrrs/orgs",
"repos_url": "https://api.github.com/users/ymrzkrrs/repos",
"events_url": "https://api.github.com/users/ymrzkrrs/events{/privacy}",
"received_events_url": "https://api.github.com/users/ymrzkrrs/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"I switched to using `default=datetime.today` with bulk_create for this use case, as it fills the field value before inserting.",
"Peewee is not exactly aware of defaults implemented on the server. It can work with them, but it's not the same as using the `default=` python-side implementation.\r\n\r\nTo get bulk create w/a server-side default, use the `insert_many()` API instead:\r\n\r\n```python\r\nstart_dates = [\r\n datetime.date(...),\r\n datetime.date(...),\r\n ...\r\n]\r\n\r\nSummary.insert_many([(date,) for date in start_dates], fields=[Summary.start_date]).execute()\r\n```"
] | 2019-05-14T14:22:39 | 2019-05-14T15:02:46 | 2019-05-14T15:02:46 | NONE | null | I have the following model:
```
class Summary(Model):
start_date = DateField(formats=['%Y-%m-%d'])
end_date = DateField(formats=['%Y-%m-%d'], constraints=[SQL('DEFAULT CURRENT_DATE')])
class Meta:
database = db
db_table = 'test_table'
```
If I insert using:
```
summary = Summary(start_date=date(2019,4,29))
summary.save()
```
it works. The debugging logs show:
```
2019-05-14 16:13:52 DEBUG peewee:peewee:2928 - ('INSERT INTO "test_table" ("start_date") VALUES (%s) RETURNING "test_table"."id"', [datetime.date(2019, 4, 29)])
```
However if I try inserting using bulk_create:
```
Summary.bulk_create([summary], batch_size=100)
```
It throws:
```
psycopg2.errors.NotNullViolation: null value in column "end_date" violates not-null constraint
```
The debugging logs show that the bulk_create query is different, which is causing the error.
```
2019-05-14 16:20:25 DEBUG peewee:peewee:2928 - ('INSERT INTO "test_table" ("start_date", "end_date") VALUES (%s, %s) RETURNING "test_table"."id"', [datetime.date(2019, 4, 29), None])
```
I'm using PostgreSQL. | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1931/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/1931/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1930 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1930/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1930/comments | https://api.github.com/repos/coleifer/peewee/issues/1930/events | https://github.com/coleifer/peewee/pull/1930 | 443,497,188 | MDExOlB1bGxSZXF1ZXN0Mjc4MzUyMDMy | 1,930 | Fix empty bulk_create error | {
"login": "vicrac",
"id": 26183214,
"node_id": "MDQ6VXNlcjI2MTgzMjE0",
"avatar_url": "https://avatars.githubusercontent.com/u/26183214?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/vicrac",
"html_url": "https://github.com/vicrac",
"followers_url": "https://api.github.com/users/vicrac/followers",
"following_url": "https://api.github.com/users/vicrac/following{/other_user}",
"gists_url": "https://api.github.com/users/vicrac/gists{/gist_id}",
"starred_url": "https://api.github.com/users/vicrac/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/vicrac/subscriptions",
"organizations_url": "https://api.github.com/users/vicrac/orgs",
"repos_url": "https://api.github.com/users/vicrac/repos",
"events_url": "https://api.github.com/users/vicrac/events{/privacy}",
"received_events_url": "https://api.github.com/users/vicrac/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [] | 2019-05-13T16:40:40 | 2019-05-13T17:00:27 | 2019-05-13T17:00:27 | NONE | null | I noticed that attempt to insert an empty bulk to database (sqlite in my case) is causing following error:
```
Traceback (most recent call last):
File "/home/vicrac/peewee/peewee.py", line 2946, in execute_sql
cursor.execute(sql, params or ())
sqlite3.OperationalError: incomplete input
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/vicrac/peewee/tests/base.py", line 240, in inner
method(self)
File "/home/vicrac/peewee/tests/models.py", line 176, in test_empty_bulk_create
User.bulk_create([])
File "/home/vicrac/peewee/peewee.py", line 6016, in bulk_create
res = cls.insert_many(accum, fields=fields).execute()
File "/home/vicrac/peewee/peewee.py", line 1785, in inner
return method(self, database, *args, **kwargs)
File "/home/vicrac/peewee/peewee.py", line 1856, in execute
return self._execute(database)
File "/home/vicrac/peewee/peewee.py", line 2571, in _execute
return super(Insert, self)._execute(database)
File "/home/vicrac/peewee/peewee.py", line 2320, in _execute
cursor = database.execute(self)
File "/home/vicrac/peewee/peewee.py", line 2959, in execute
return self.execute_sql(sql, params, commit=commit)
File "/home/vicrac/peewee/peewee.py", line 2953, in execute_sql
self.commit()
File "/home/vicrac/peewee/peewee.py", line 2729, in __exit__
reraise(new_type, new_type(*exc_args), traceback)
File "/home/vicrac/peewee/peewee.py", line 183, in reraise
raise value.with_traceback(tb)
File "/home/vicrac/peewee/peewee.py", line 2946, in execute_sql
cursor.execute(sql, params or ())
peewee.OperationalError: incomplete input
```
It took me some time to figure it out, so I fixed it the simplest possible way - return from method if list is empty. I added also a simple test for it (which currently passess). | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1930/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/1930/timeline | null | null | false | {
"url": "https://api.github.com/repos/coleifer/peewee/pulls/1930",
"html_url": "https://github.com/coleifer/peewee/pull/1930",
"diff_url": "https://github.com/coleifer/peewee/pull/1930.diff",
"patch_url": "https://github.com/coleifer/peewee/pull/1930.patch",
"merged_at": null
} |
https://api.github.com/repos/coleifer/peewee/issues/1929 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1929/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1929/comments | https://api.github.com/repos/coleifer/peewee/issues/1929/events | https://github.com/coleifer/peewee/issues/1929 | 442,928,783 | MDU6SXNzdWU0NDI5Mjg3ODM= | 1,929 | jsonb_to_recordset usage | {
"login": "alejandrohenriquez",
"id": 1672932,
"node_id": "MDQ6VXNlcjE2NzI5MzI=",
"avatar_url": "https://avatars.githubusercontent.com/u/1672932?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/alejandrohenriquez",
"html_url": "https://github.com/alejandrohenriquez",
"followers_url": "https://api.github.com/users/alejandrohenriquez/followers",
"following_url": "https://api.github.com/users/alejandrohenriquez/following{/other_user}",
"gists_url": "https://api.github.com/users/alejandrohenriquez/gists{/gist_id}",
"starred_url": "https://api.github.com/users/alejandrohenriquez/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/alejandrohenriquez/subscriptions",
"organizations_url": "https://api.github.com/users/alejandrohenriquez/orgs",
"repos_url": "https://api.github.com/users/alejandrohenriquez/repos",
"events_url": "https://api.github.com/users/alejandrohenriquez/events{/privacy}",
"received_events_url": "https://api.github.com/users/alejandrohenriquez/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [] | 2019-05-10T23:42:44 | 2019-05-10T23:45:01 | 2019-05-10T23:45:01 | NONE | null | I need use the postgresql function jsonb_to_recordset (https://www.postgresql.org/docs/current/functions-json.html) in an Insert/Select context.
How could I implement this?
Best Regards | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1929/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/1929/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1928 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1928/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1928/comments | https://api.github.com/repos/coleifer/peewee/issues/1928/events | https://github.com/coleifer/peewee/issues/1928 | 442,864,307 | MDU6SXNzdWU0NDI4NjQzMDc= | 1,928 | SQLite: Check constraint to check if value is in list causes infinite loop | {
"login": "HashFail",
"id": 4693508,
"node_id": "MDQ6VXNlcjQ2OTM1MDg=",
"avatar_url": "https://avatars.githubusercontent.com/u/4693508?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/HashFail",
"html_url": "https://github.com/HashFail",
"followers_url": "https://api.github.com/users/HashFail/followers",
"following_url": "https://api.github.com/users/HashFail/following{/other_user}",
"gists_url": "https://api.github.com/users/HashFail/gists{/gist_id}",
"starred_url": "https://api.github.com/users/HashFail/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/HashFail/subscriptions",
"organizations_url": "https://api.github.com/users/HashFail/orgs",
"repos_url": "https://api.github.com/users/HashFail/repos",
"events_url": "https://api.github.com/users/HashFail/events{/privacy}",
"received_events_url": "https://api.github.com/users/HashFail/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"Try\r\n\r\n`constraints=[Check(\"test in ('http', 'smb')\")]`",
"Oh, derp. Thanks!"
] | 2019-05-10T19:30:58 | 2019-05-10T20:16:45 | 2019-05-10T20:16:45 | NONE | null | Maybe this isn't supported, but it seems like a parse error to me.
Minimal example:
```python
from peewee import SqliteDatabase, CharField, Check
from playhouse.signals import Model
class Test(Model):
database = SqliteDatabase('test.db')
database.connect()
test = CharField(constraints=Check("test in ('http','smb')"))
def main():
database = SqliteDatabase('test.db')
database.connect()
Test._meta.database = database
database.create_tables([Test])
if __name__ == '__main__':
main()
```
Running this code causes an infinite loop in `create_tables`. The following works just fine in SQLite:
```sql
create table test(test varchar CHECK(test in ('http','smb')));
insert into test values ('abc');
>> Error: CHECK constraint failed: test
```
EDIT: Version numbers are Python 3.6.8, peewee 3.9.5 | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1928/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/1928/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1927 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1927/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1927/comments | https://api.github.com/repos/coleifer/peewee/issues/1927/events | https://github.com/coleifer/peewee/pull/1927 | 441,438,881 | MDExOlB1bGxSZXF1ZXN0Mjc2NzY1OTU5 | 1,927 | Makes minor spelling or grammar changes | {
"login": "fpcorso",
"id": 9730040,
"node_id": "MDQ6VXNlcjk3MzAwNDA=",
"avatar_url": "https://avatars.githubusercontent.com/u/9730040?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/fpcorso",
"html_url": "https://github.com/fpcorso",
"followers_url": "https://api.github.com/users/fpcorso/followers",
"following_url": "https://api.github.com/users/fpcorso/following{/other_user}",
"gists_url": "https://api.github.com/users/fpcorso/gists{/gist_id}",
"starred_url": "https://api.github.com/users/fpcorso/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/fpcorso/subscriptions",
"organizations_url": "https://api.github.com/users/fpcorso/orgs",
"repos_url": "https://api.github.com/users/fpcorso/repos",
"events_url": "https://api.github.com/users/fpcorso/events{/privacy}",
"received_events_url": "https://api.github.com/users/fpcorso/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [] | 2019-05-07T20:46:39 | 2019-05-07T21:01:01 | 2019-05-07T21:01:01 | NONE | null | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1927/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/1927/timeline | null | null | false | {
"url": "https://api.github.com/repos/coleifer/peewee/pulls/1927",
"html_url": "https://github.com/coleifer/peewee/pull/1927",
"diff_url": "https://github.com/coleifer/peewee/pull/1927.diff",
"patch_url": "https://github.com/coleifer/peewee/pull/1927.patch",
"merged_at": null
} |
|
https://api.github.com/repos/coleifer/peewee/issues/1926 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1926/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1926/comments | https://api.github.com/repos/coleifer/peewee/issues/1926/events | https://github.com/coleifer/peewee/issues/1926 | 441,169,215 | MDU6SXNzdWU0NDExNjkyMTU= | 1,926 | user-defined function from int to string gives ValueError when printed | {
"login": "isthisthat",
"id": 1259045,
"node_id": "MDQ6VXNlcjEyNTkwNDU=",
"avatar_url": "https://avatars.githubusercontent.com/u/1259045?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/isthisthat",
"html_url": "https://github.com/isthisthat",
"followers_url": "https://api.github.com/users/isthisthat/followers",
"following_url": "https://api.github.com/users/isthisthat/following{/other_user}",
"gists_url": "https://api.github.com/users/isthisthat/gists{/gist_id}",
"starred_url": "https://api.github.com/users/isthisthat/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/isthisthat/subscriptions",
"organizations_url": "https://api.github.com/users/isthisthat/orgs",
"repos_url": "https://api.github.com/users/isthisthat/repos",
"events_url": "https://api.github.com/users/isthisthat/events{/privacy}",
"received_events_url": "https://api.github.com/users/isthisthat/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"Peewee looks at the field type when converting values coming back from the DB. What version of Peewee are you using, by chance? In more recent versions, the conversion logic was made a little bit more forgiving, allowing fallback to the original value.\r\n\r\nThis works, for ex:\r\n\r\n```python\r\ndb = SqliteDatabase(':memory:')\r\n\r\nclass Num(Model):\r\n val = IntegerField()\r\n class Meta:\r\n database = db\r\n\r\[email protected]()\r\ndef to_s(n):\r\n return {\r\n 0: 'zero',\r\n 1: 'one',\r\n 2: 'two'}.get(n, 'too many')\r\n\r\nNum.create_table()\r\nNum.insert_many([(i,) for i in range(4)]).execute()\r\n\r\nquery = (Num\r\n .select(fn.to_s(Num.val).alias('val'))\r\n .order_by(Num.val))\r\nfor row in query:\r\n print(row.val)\r\n# zero\r\n# one\r\n# two\r\n# too many\r\n```\r\n\r\nFor older versions, you can try:\r\n\r\n```python\r\nfn.to_dna(Base.abase, coerce=False)\r\n```",
"> Then I tried casting as blob but I get zeros. query2() gives [{'abase\") AS NONE)': 0},...\r\n\r\nYou might note that the key of the dict is all messed up. Sqlite does not give very helpful column names when you are selecting a function or something and do not provide an alias. You probably want to do:\r\n\r\n```python\r\nfn.to_dna(Base.abase).alias('dna')\r\n```\r\n\r\nSo you can access it using a nice name.",
"> I basically want to save space by storing an int instead of a char but then be able to print it back easily. Any advice? Thank you.\r\n\r\nAn integer takes up 8 bytes (sqlite uses 64-bit integers). A char takes up a single byte. So you might rethink that as well...because your decision is 8x more wasteful.",
"Oh dear! thanks a lot for the advice."
] | 2019-05-07T10:58:40 | 2019-05-07T16:15:46 | 2019-05-07T15:40:05 | NONE | null | Setup:
from enum import Enum
from peewee import *
from playhouse.sqlite_ext import SqliteExtDatabase
DNA = Enum('DNA', {"N":-1, "A":1, "T":2, "C":3, "G":4})
db = Proxy()
def toDNA(n):
return DNA(n).name.upper()
class Base(Model):
abase = IntegerField(default=-1) # DNA
class Meta:
database = db
def setupDB():
dbs = SqliteExtDatabase("foo")
db.initialize(dbs)
db.connect(reuse_if_open=True)
db.create_tables([Base], safe=True)
db.register_function(toDNA, "to_dna", 1)
# add dummy data
Base.create(abase="-1")
Base.create(abase="4")
def query():
return list(Base.select(fn.to_dna(Base.abase)).dicts())
def query2():
return list(Base.select(fn.to_dna(Base.abase).cast('NONE')).dicts())
If I run `query()` I get `invalid literal for int() with base 10: 'N'`
Then I tried casting as blob but I get zeros. `query2()` gives `[{'abase") AS NONE)': 0},`...
I basically want to save space by storing an int instead of a char but then be able to print it back easily. Any advice? Thank you.
| {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1926/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/1926/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1925 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1925/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1925/comments | https://api.github.com/repos/coleifer/peewee/issues/1925/events | https://github.com/coleifer/peewee/issues/1925 | 440,896,729 | MDU6SXNzdWU0NDA4OTY3Mjk= | 1,925 | Unable to join to model on backreference select() | {
"login": "brandond",
"id": 370103,
"node_id": "MDQ6VXNlcjM3MDEwMw==",
"avatar_url": "https://avatars.githubusercontent.com/u/370103?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/brandond",
"html_url": "https://github.com/brandond",
"followers_url": "https://api.github.com/users/brandond/followers",
"following_url": "https://api.github.com/users/brandond/following{/other_user}",
"gists_url": "https://api.github.com/users/brandond/gists{/gist_id}",
"starred_url": "https://api.github.com/users/brandond/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/brandond/subscriptions",
"organizations_url": "https://api.github.com/users/brandond/orgs",
"repos_url": "https://api.github.com/users/brandond/repos",
"events_url": "https://api.github.com/users/brandond/events{/privacy}",
"received_events_url": "https://api.github.com/users/brandond/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"~~What is `Plugin` in this context? Is it a model class? Model alias?~~\r\n\r\nOh, actually nevermind! When re-selecting from an existing query, it seems like there's a bug when you pass a model class directly in.\r\n\r\nFor now, just explicitly specify the fields or list them, e.g.:\r\n\r\n```python\r\n return (self.plugin_incidents\r\n .select(PluginIncident.guid, PluginIncident.number, *Plugin._meta.sorted_fields)\r\n .join(Plugin)\r\n```",
"I think I got it fixed, just FYI in 5f51598.",
"That fixed it, thanks! I was going to take a shot at working around it with a prefetch but this is much easier.",
"FWIW, one of the recent changes seems to have also fixed an issue I was having with using a subquery in a join:\r\n\r\n```python\r\nteam_name = (Team.select(Team.name)\r\n .where((Team.name == Host.tags['TechOwnerName']) |\r\n (Team.remedy_group == Host.tags['RemedyGroup']))\r\n .limit(1))\r\n\r\nfor vuln in (self.vulnerabilities\r\n .select(fn.COALESCE(Team.guid, Vulnerability.guid).alias('guid'),\r\n Plugin.id,\r\n Vulnerability.plugin,\r\n fn.COUNT(Vulnerability.plugin).alias('count'))\r\n .join(Query)\r\n .switch(Vulnerability)\r\n .join(Plugin)\r\n .switch(Vulnerability)\r\n .join(Host)\r\n .join(Team, JOIN.LEFT_OUTER, on=(Team.name == team_name))):\r\n # do something\r\n\r\n```\r\nPreviously it would try to append an table alias (`from \"team\" as \"t5\"`) to the subquery inside the join statement, which obviously wasn't valid SQL."
] | 2019-05-06T21:13:10 | 2019-05-06T23:58:52 | 2019-05-06T21:31:19 | NONE | null | I have the following canned query that I expose as a property on a subclass of one of my models. `plugin_incidendents` is a backreference from the PluginIncident model to this model.
```python
class RemediationGroupBase(peewee.Model)
# model definition here
class RemediationGroup(RemediationGroupBase)
@property
def assigned_plugins(self):
return (self.plugin_incidents
.select(PluginIncident.guid, PluginIncident.number, Plugin)
.join(Plugin)
.switch(Vulnerability)
.order_by(PluginIncident.guid, Plugin.id)
.where(PluginIncident.guid != GUID_IGNORE)
.where(PluginIncident.number.is_null(False))
.where(PluginIncident.plugin_id.is_null(False)))
```
I can `count()` this just fine:
```
('SELECT COUNT(1) FROM (SELECT 1 FROM "pluginincident" AS "t1" INNER JOIN "plugin" AS "t2" ON ("t1"."plugin_id" = "t2"."id") WHERE (((("t1"."remediation_group_id" = ?) AND ("t1"."guid" != ?)) AND ("t1"."number" IS NOT ?)) AND ("t1"."plugin_id" IS NOT ?)) LIMIT ? OFFSET ?) AS "_wrapped"', [766, u'AG_BLACK_HOLE_CREATE_NO_TICKET', None, None, 50, 0])
```
But when I try to paginate and iterate over it I get the following:
```
for i, ticket in enumerate(tickets):
File "/home/ec2-user/ansible-env/lib/python2.7/site-packages/peewee.py", line 4125, in next
self.cursor_wrapper.iterate()
File "/home/ec2-user/ansible-env/lib/python2.7/site-packages/peewee.py", line 4041, in iterate
self.initialize() # Lazy initialization.
File "/home/ec2-user/ansible-env/lib/python2.7/site-packages/peewee.py", line 7062, in initialize
self._initialize_columns()
File "/home/ec2-user/ansible-env/lib/python2.7/site-packages/peewee.py", line 6962, in _initialize_columns
node = raw_node.unwrap()
TypeError: unbound method unwrap() must be called with Plugin instance as first argument (got nothing instead)
```
This is because the query is selecting the `plugin` table name as a literal string, instead of selecting all columns from that model:
```sql
SELECT "t1"."guid", "t1"."number", "plugin" AS "t2"
FROM "pluginincident" AS "t1"
INNER JOIN "plugin" AS "t2"
ON ("t1"."plugin_id" = "t2"."id")
WHERE (((("t1"."remediation_group_id" = ?) AND ("t1"."guid" != ?)) AND ("t1"."number" IS NOT ?)) AND ("t1"."plugin_id" IS NOT ?))
ORDER BY "t1"."guid", "t2"."id"
LIMIT ?
OFFSET ?;
```
with the following bindings:
```
[766, u'GUIDVAL', None, None, 50, 0]
```
Am I getting the syntax wrong here or something? | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1925/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/1925/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1924 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1924/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1924/comments | https://api.github.com/repos/coleifer/peewee/issues/1924/events | https://github.com/coleifer/peewee/issues/1924 | 440,609,016 | MDU6SXNzdWU0NDA2MDkwMTY= | 1,924 | IndexError: tuple index out of range when using db.execute_sql | {
"login": "ymrzkrrs",
"id": 43073619,
"node_id": "MDQ6VXNlcjQzMDczNjE5",
"avatar_url": "https://avatars.githubusercontent.com/u/43073619?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/ymrzkrrs",
"html_url": "https://github.com/ymrzkrrs",
"followers_url": "https://api.github.com/users/ymrzkrrs/followers",
"following_url": "https://api.github.com/users/ymrzkrrs/following{/other_user}",
"gists_url": "https://api.github.com/users/ymrzkrrs/gists{/gist_id}",
"starred_url": "https://api.github.com/users/ymrzkrrs/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/ymrzkrrs/subscriptions",
"organizations_url": "https://api.github.com/users/ymrzkrrs/orgs",
"repos_url": "https://api.github.com/users/ymrzkrrs/repos",
"events_url": "https://api.github.com/users/ymrzkrrs/events{/privacy}",
"received_events_url": "https://api.github.com/users/ymrzkrrs/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"I think your example is not correct or you're not providing all the information. Something doesn't make sense.\r\n\r\nFor example, this works fine:\r\n\r\n```python\r\nfrom peewee import *\r\ndb = PostgresqlDatabase('some_db')\r\nprint(db.execute_sql('SELECT current_timestamp').fetchone())\r\n```\r\n\r\nThe `execute_sql()` function is a fundamental method in peewee and is used extensively.",
"I just re-run the example from another machine to make sure I did't miss anything. The query you provided `SELECT current_timestamp` works but the one I provided doesn't. Please kindly review again.\r\n\r\nHere is a complete example :\r\n\r\n```\r\nfrom peewee import *\r\nfrom playhouse.postgres_ext import *\r\nfrom environs import Env\r\nenv= Env()\r\nenv.read_env()\r\n\r\ntesting_flatten_function = \"\"\"\r\ncreate or replace function testing_flatten_function\r\n (view_name text, table_name text, regular_columns text, json_column text)\r\n returns text language plpgsql as $$\r\ndeclare\r\n cols text;\r\nbegin\r\n execute format ($ex$\r\n select string_agg(format('%2$s->>%%1$L \"%2$s.%%1$s\"', key), ', ')\r\n from (\r\n select distinct key\r\n from %1$s, jsonb_each(%2$s)\r\n order by 1\r\n ) s;\r\n $ex$, table_name, json_column)\r\n into cols;\r\n execute format($ex$\r\n drop view if exists %1$s;\r\n create view %1$s as \r\n select %3$s, %4$s from %2$s\r\n $ex$, view_name, table_name, regular_columns, cols);\r\n return cols;\r\nend $$;\r\n\"\"\"\r\n\r\n# This works without issue\r\nimport psycopg2\r\nconn = psycopg2.connect(\"host={} dbname={} user={} password={}\".format(env.str('PG_HOST'), env.str('PG_DB'), env.str('PG_USER'), env.str('PG_PWD')))\r\ncursor = conn.cursor()\r\ncursor.execute(testing_flatten_function)\r\n\r\ndb = PostgresqlExtDatabase(env.str('PG_DB'),\r\n user=env.str('PG_USER'),\r\n password=env.str('PG_PWD'),\r\n host=env.str('PG_HOST'))\r\n\r\n# This works\r\nprint(db.execute_sql('SELECT current_timestamp').fetchone())\r\n\r\n# This doesn't work\r\ndb.execute_sql(testing_flatten_function)\r\n```\r\n\r\nOutput:\r\n```\r\n(datetime.datetime(2019, 5, 6, 14, 35, 55, 510756, tzinfo=psycopg2.tz.FixedOffsetTimezone(offset=0, name=None)),)\r\n~/mainenv/lib/python3.6/site-packages/peewee.py in execute_sql(self, sql, params, commit)\r\n 2938 cursor = self.cursor(commit)\r\n 2939 try:\r\n-> 2940 cursor.execute(sql, params or ())\r\n 2941 except Exception:\r\n 2942 if self.autorollback and not self.in_transaction():\r\n\r\nIndexError: tuple index out of range\r\n```",
"Perhaps it's a psycopg2 thing, where -- because your SQL query uses the same \"%\"-style placeholders as Python's string interpolation -- somewhere in the query handling, psycopg2 is trying to interpolate the empty params list.\r\n\r\nI'd suggest this is probably something to take up with the psycopg2 folks. Alternatively,\r\n\r\n```python\r\ncursor = db.cursor()\r\ncursor.execute(your_sql_here)\r\n```",
"That's why I checked using psycopg2, which worked fine :\r\n```\r\nimport psycopg2\r\nconn = psycopg2.connect(\"host={} dbname={} user={} password={}\".format(env.str('PG_HOST'), env.str('PG_DB'), env.str('PG_USER'), env.str('PG_PWD')))\r\ncursor = conn.cursor()\r\ncursor.execute(testing_flatten_function)\r\n```\r\nThe alternative you provided also works, but in my opinion the problem here is in `db.execute_sql` because in psycopg2 [docs](http://initd.org/psycopg/docs/cursor.html#cursor.execute), `None` is the default value for `vars` in `cursor.execute(query, vars)`. \r\n\r\nIs there any reason it is `params or ()` instead of simply `params` here https://github.com/coleifer/peewee/blob/master/peewee.py#L2946 ?",
"> That's why I checked using psycopg2, which worked fine :\r\n\r\nYes and no. psycopg2 is doing some kind of interpolation behind-the-scenes, which to my thinking is a no-no. If you had done `cursor.execute(q, ())` you would again encounter the same error.",
"@ymrzkrrs Did you ever solve this issue?",
"@coleifer @ymrzkrrs Nevermind, simply included an extra % to escape the %:\r\n\r\n```\r\nand ((id %% 2)) = 0)\r\n```"
] | 2019-05-06T09:15:18 | 2019-08-14T17:09:09 | 2019-05-06T14:11:13 | NONE | null | I have function to create on PostgreSQL:
```
jsonb_flatten_function = """
create or replace function create_jsonb_flat_view
(view_name text, table_name text, regular_columns text, json_column text)
returns text language plpgsql as $$
declare
cols text;
begin
execute format ($ex$
select string_agg(format('%2$s->>%%1$L "%2$s.%%1$s"', key), ', ')
from (
select distinct key
from %1$s, jsonb_each(%2$s)
order by 1
) s;
$ex$, table_name, json_column)
into cols;
execute format($ex$
drop view if exists %1$s;
create view %1$s as
select %3$s, %4$s from %2$s
$ex$, view_name, table_name, regular_columns, cols);
return cols;
end $$;
"""
```
If try to execute the previous sql with
```
db.execute_sql(jsonb_flatten_function)
```
it raises
```
Traceback (most recent call last):
File "/home/user/init_pg.py", line 91, in <module>
db.execute_sql(jsonb_flatten_function)
File "/home/user/mainenv/lib/python3.6/site-packages/peewee.py", line 2940, in execute_sql
cursor.execute(sql, params or ())
IndexError: tuple index out of range
```
However if I use a `psycopg2` curosr manually or use:
```
cursor = db.cursor()
cursor.execute(jsonb_flatten_function)
```
It works without any issue.
Removing `or ()` from `cursor.execute(sql, params or ())` seems to fix it, I'm not sure why it exists in the first place though. | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1924/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/1924/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1923 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1923/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1923/comments | https://api.github.com/repos/coleifer/peewee/issues/1923/events | https://github.com/coleifer/peewee/issues/1923 | 440,579,626 | MDU6SXNzdWU0NDA1Nzk2MjY= | 1,923 | SQL Syntax Error in Model.save() when row is empty | {
"login": "0az",
"id": 30874884,
"node_id": "MDQ6VXNlcjMwODc0ODg0",
"avatar_url": "https://avatars.githubusercontent.com/u/30874884?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/0az",
"html_url": "https://github.com/0az",
"followers_url": "https://api.github.com/users/0az/followers",
"following_url": "https://api.github.com/users/0az/following{/other_user}",
"gists_url": "https://api.github.com/users/0az/gists{/gist_id}",
"starred_url": "https://api.github.com/users/0az/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/0az/subscriptions",
"organizations_url": "https://api.github.com/users/0az/orgs",
"repos_url": "https://api.github.com/users/0az/repos",
"events_url": "https://api.github.com/users/0az/events{/privacy}",
"received_events_url": "https://api.github.com/users/0az/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"This seems contrived and I'm wondering how it even would come about in practice. Your model definition does not match the UPDATE statement you've shared, either.\r\n\r\nWhen you instantiate a model, it has an empty data dict. If you call `.create()` without any kwargs, this is effectively the same as instantiating w/no data. So when you go to save this model in a subsequent call, having not set any values, there's nothing going on there. I've chosen to raise a `ValueError` in this case, but I do believe that in practice it would take some rather contrived workflow to actually encounter this.",
"It came about because I misread docs, and called `.save` immediately after `.create`. The lack of a useful error (now fixed) is why I brought it up, as it took an hour and a fresh set of eyes to figure out why."
] | 2019-05-06T07:47:21 | 2019-05-06T16:41:05 | 2019-05-06T14:00:45 | CONTRIBUTOR | null | When `save()` is called on a row with nothing to save, there is a SQL syntax error caused by a lack of fields to update: `('UPDATE "foo" SET WHERE ("foo"."foo" = ?)', [0])`.
<details><summary>MCVE</summary>
from peewee import IntegerField, Model, SqliteDatabase
db = SqliteDatabase(':memory:')
class Foo(BaseModel):
foo = IntegerField(null=True)
class Meta:
database = db
db.create_tables([Foo])
foo = Foo.create()
# peewee.OperationalError: near "WHERE": syntax error
# ('UPDATE "foo" SET WHERE ("foo"."foo" = ?)', [0])
foo.save()
</details> | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1923/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/1923/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1922 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1922/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1922/comments | https://api.github.com/repos/coleifer/peewee/issues/1922/events | https://github.com/coleifer/peewee/pull/1922 | 440,570,259 | MDExOlB1bGxSZXF1ZXN0Mjc2MDg1Nzk3 | 1,922 | Replace deprecated PrimaryKeyField with AutoField in docs | {
"login": "0az",
"id": 30874884,
"node_id": "MDQ6VXNlcjMwODc0ODg0",
"avatar_url": "https://avatars.githubusercontent.com/u/30874884?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/0az",
"html_url": "https://github.com/0az",
"followers_url": "https://api.github.com/users/0az/followers",
"following_url": "https://api.github.com/users/0az/following{/other_user}",
"gists_url": "https://api.github.com/users/0az/gists{/gist_id}",
"starred_url": "https://api.github.com/users/0az/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/0az/subscriptions",
"organizations_url": "https://api.github.com/users/0az/orgs",
"repos_url": "https://api.github.com/users/0az/repos",
"events_url": "https://api.github.com/users/0az/events{/privacy}",
"received_events_url": "https://api.github.com/users/0az/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"Danke."
] | 2019-05-06T07:20:59 | 2019-05-06T13:53:09 | 2019-05-06T13:53:06 | CONTRIBUTOR | null | <details>
<summary>Grep after change</summary>
> rg -i 'PrimaryKeyField'
CHANGELOG.md
885:Re-add a shim for `PrimaryKeyField` (renamed to `AutoField`) and log a
tests/fields.py
450:class TestCompositePrimaryKeyField(ModelTestCase):
peewee.py
124: 'PrimaryKeyField', # XXX: Deprecated, change to AutoField.
4346:class PrimaryKeyField(AutoField):
4348: __deprecated__('"PrimaryKeyField" has been renamed to "AutoField". '
4351: super(PrimaryKeyField, self).__init__(*args, **kwargs)
docs/peewee/changes.rst
56:* :py:class:`PrimaryKeyField` has been renamed to :py:class:`AutoField`
</details> | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1922/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/1922/timeline | null | null | false | {
"url": "https://api.github.com/repos/coleifer/peewee/pulls/1922",
"html_url": "https://github.com/coleifer/peewee/pull/1922",
"diff_url": "https://github.com/coleifer/peewee/pull/1922.diff",
"patch_url": "https://github.com/coleifer/peewee/pull/1922.patch",
"merged_at": "2019-05-06T13:53:06"
} |
https://api.github.com/repos/coleifer/peewee/issues/1921 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1921/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1921/comments | https://api.github.com/repos/coleifer/peewee/issues/1921/events | https://github.com/coleifer/peewee/issues/1921 | 440,199,552 | MDU6SXNzdWU0NDAxOTk1NTI= | 1,921 | SQLError: row value misused after upgrade | {
"login": "brandond",
"id": 370103,
"node_id": "MDQ6VXNlcjM3MDEwMw==",
"avatar_url": "https://avatars.githubusercontent.com/u/370103?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/brandond",
"html_url": "https://github.com/brandond",
"followers_url": "https://api.github.com/users/brandond/followers",
"following_url": "https://api.github.com/users/brandond/following{/other_user}",
"gists_url": "https://api.github.com/users/brandond/gists{/gist_id}",
"starred_url": "https://api.github.com/users/brandond/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/brandond/subscriptions",
"organizations_url": "https://api.github.com/users/brandond/orgs",
"repos_url": "https://api.github.com/users/brandond/repos",
"events_url": "https://api.github.com/users/brandond/events{/privacy}",
"received_events_url": "https://api.github.com/users/brandond/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"Try rather than using distinct as a function, to append a call to .distinct() at the end of the query.",
"If I go back to 3.6.4 and rerun the exact same sequence, it looks like 3.9.5 is putting parentheses around the column list that weren't there before:\r\n\r\n```\r\n3.9.5: ('SELECT COUNT(1) FROM (SELECT DISTINCT (\"t1\".\"ip_address\", \"t1\".\"port\", \"t1\".\"protocol\", \"t1\".\"plugin_id\", \"t1\".\"first_seen\") FROM \"vulnerability\" AS \"t1\" WHERE (((\"t1\".\"remediation_group_id\" = ?) AND (\"t1\".\"plugin_id\" = ?)) AND (\"t1\".\"guid\" = ?))) AS \"_wrapped\"', [764, 22024, u'AGGAA5V0FSFJTAOW8FUSBXO8AGPWPK'])\r\n3.6.4: ('SELECT COUNT(1) FROM (SELECT DISTINCT \"t1\".\"ip_address\", \"t1\".\"port\", \"t1\".\"protocol\", \"t1\".\"plugin_id\", \"t1\".\"first_seen\" FROM \"vulnerability\" AS \"t1\" WHERE (((\"t1\".\"remediation_group_id\" = ?) AND (\"t1\".\"plugin_id\" = ?)) AND (\"t1\".\"guid\" = ?))) AS \"_wrapped\"', [764, 22024, u'AGGAA5V0FSFJTAOW8FUSBXO8AGPWPK'])\r\n```\r\n\r\nI'm using this with sqlite - apsw 3.24.0.post1",
"There's some logic outside this block that's preparing a query for self.vulnerabilties, but I am calling distinct() at the end of the query rather than as a function.\r\n\r\n```\r\nvulns = (self.vulnerabilities\r\n .where(Vulnerability.plugin_id == plugin_id)\r\n .where(Vulnerability.guid == template_guid)\r\n .switch(Vulnerability))\r\nhosts = (vulns.select(Vulnerability.ip_address, Vulnerability.dns_name)\r\n .distinct())\r\nvuln_count = vulns.count()\r\n```\r\n",
"Can you share what `self.vulnerabilities` is?\r\n\r\nI'm wondering if you're re-selecting or somehow selecting a tuple instead of a list of columns?\r\n\r\nIn your example code you have `hosts = ...` but that doesn't appear to be in any way relevant to the error, right? I'm just not understanding why you included it.",
"For example, I'm trying to replicate this and cannot:\r\n\r\n```python\r\nclass RD(TestModel):\r\n key = TextField()\r\n value = IntegerField()\r\n\r\nnums = [0, 1, 2, 3, 2, 1, 0]\r\nRD.insert_many([('k%s' % i, i) for i in nums]).execute()\r\nassert RD.select(RD.key).distinct().count() == 4 # Works\r\n```",
"This came up during regression testing and may possibly be relevant, 2692e781da2ebaa33ae72098b18122d3b2d46a30 -- but that being said, I cannot replicate the invalid SQL you are reporting.\r\n\r\nPlease provide more information or at least an example of how I can replicate this issue.",
"Sorry, I was trying to trim out some extra bits of non-peewee code and omitted the wrong bit. The full block is:\r\n\r\n```\r\nvulns = (self.vulnerabilities\r\n .where(Vulnerability.plugin_id == plugin_id)\r\n .where(Vulnerability.guid == template_guid)\r\n .switch(Vulnerability))\r\nhosts = (vulns.select(Vulnerability.ip_address, Vulnerability.dns_name)\r\n .distinct())\r\nvuln_count = vulns.count()\r\nhost_count = hosts.count() # <-- this causes the exception\r\nfirst_vuln = vulns.get()\r\nplugin_obj = Plugin.get(id=plugin_id)\r\n```\r\n\r\nThis is actually in a class method with a bunch of business logic in it that subclasses one of my Model classes, so self.vulnerabilities is a query against another table via foreign key backreference.\r\n\r\nI'll try with that commit, and if that does not fix it I'll see if I can easily bisect and/or replicate.",
"2692e78 fixes this issue. Thanks!\r\n\r\nFWIW, a bisect showed ff321c514c06858565635279367ecc891852047d as the breaking commit.",
"Thanks so much for bisecting, very helpful. I'll look into that some more, but glad the immediate issue is now resolved."
] | 2019-05-03T20:00:44 | 2019-05-05T12:35:51 | 2019-05-05T07:45:47 | NONE | null | I recently updated to 3.9.5 and I'm now experiencing the following errors with a query that was previously working:
```
[DEBUG] 2019-05-03T19:05:14.901Z 1eeeb36c-0a1e-44ec-91b8-ddd09d60ed4e ('SELECT COUNT(1) FROM (SELECT DISTINCT ("t1"."ip_address", "t1"."port", "t1"."protocol", "t1"."plugin_id", "t1"."first_seen") FROM "vulnerability" AS "t1" WHERE ((("t1"."remediation_group_id" = ?) AND ("t1"."plugin_id" = ?)) AND ("t1"."guid" = ?))) AS "_wrapped"', [764, 103569, u'AGGAA5V0FSFJTAOW8FUSBXO8AGPWPK'])
[ERROR] 2019-05-03T19:05:14.902Z 1eeeb36c-0a1e-44ec-91b8-ddd09d60ed4e Unable to update plugin ticket INC000008958030
Traceback (most recent call last):
File "/home/ec2-user/ansible-env/lib/python2.7/site-packages/ticketlib/remediation.py", line 466, in update_plugin_ticket
host_count = hosts.count()
File "/home/ec2-user/ansible-env/lib/python2.7/site-packages/peewee.py", line 1785, in inner
return method(self, database, *args, **kwargs)
File "/home/ec2-user/ansible-env/lib/python2.7/site-packages/peewee.py", line 2061, in count
return Select([clone], [fn.COUNT(SQL('1'))]).scalar(database)
File "/home/ec2-user/ansible-env/lib/python2.7/site-packages/peewee.py", line 1785, in inner
return method(self, database, *args, **kwargs)
File "/home/ec2-user/ansible-env/lib/python2.7/site-packages/peewee.py", line 2046, in scalar
row = self.tuples().peek(database)
File "/home/ec2-user/ansible-env/lib/python2.7/site-packages/peewee.py", line 1785, in inner
return method(self, database, *args, **kwargs)
File "/home/ec2-user/ansible-env/lib/python2.7/site-packages/peewee.py", line 2033, in peek
rows = self.execute(database)[:n]
File "/home/ec2-user/ansible-env/lib/python2.7/site-packages/peewee.py", line 1785, in inner
return method(self, database, *args, **kwargs)
File "/home/ec2-user/ansible-env/lib/python2.7/site-packages/peewee.py", line 1856, in execute
return self._execute(database)
File "/home/ec2-user/ansible-env/lib/python2.7/site-packages/peewee.py", line 2027, in _execute
cursor = database.execute(self)
File "/home/ec2-user/ansible-env/lib/python2.7/site-packages/peewee.py", line 2953, in execute
return self.execute_sql(sql, params, commit=commit)
File "/home/ec2-user/ansible-env/lib/python2.7/site-packages/playhouse/apsw_ext.py", line 112, in execute_sql
cursor.execute(sql, params or ())
File "src/cursor.c", line 1019, in APSWCursor_execute.sqlite3_prepare
File "src/statementcache.c", line 386, in sqlite3_prepare
SQLError: SQLError: row value misused
``` | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1921/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/1921/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1920 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1920/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1920/comments | https://api.github.com/repos/coleifer/peewee/issues/1920/events | https://github.com/coleifer/peewee/issues/1920 | 440,076,331 | MDU6SXNzdWU0NDAwNzYzMzE= | 1,920 | Foreign Key creation during create_table does not use reference field length | {
"login": "geonyoro",
"id": 10379310,
"node_id": "MDQ6VXNlcjEwMzc5MzEw",
"avatar_url": "https://avatars.githubusercontent.com/u/10379310?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/geonyoro",
"html_url": "https://github.com/geonyoro",
"followers_url": "https://api.github.com/users/geonyoro/followers",
"following_url": "https://api.github.com/users/geonyoro/following{/other_user}",
"gists_url": "https://api.github.com/users/geonyoro/gists{/gist_id}",
"starred_url": "https://api.github.com/users/geonyoro/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/geonyoro/subscriptions",
"organizations_url": "https://api.github.com/users/geonyoro/orgs",
"repos_url": "https://api.github.com/users/geonyoro/repos",
"events_url": "https://api.github.com/users/geonyoro/events{/privacy}",
"received_events_url": "https://api.github.com/users/geonyoro/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"What exactly is the error you are encountering? The linked ticket does not strike me as being relevant.\r\n\r\nHow is this varchar foreign-key field being declared? How is the field it is pointing to declared?",
"```python\r\nclass ReleaseASINMap(BaseModel):\r\n release_id = peewee.CharField(max_length=51, unique=True, null=True)\r\n\r\nclass ReverseStringMap(BaseModel):\r\n release_map = peewee.ForeignKeyField(ReleaseASINMap, field=\"release_id\", \r\n backref='reverse_map',\r\n on_delete=\"CASCADE\")\r\n\r\npeewee.InternalError: (1005, u\"Can't create table 'repricer.reverse_string_map' (errno: 150)\"\r\n```\r\nMaybe I'm on to nothing here. It did work on my local, not in production, and by googling I see the #150 error is related to foreign keys.",
"Note: please format your code in the future. For fuck's sake it is not hard.",
"The errno: 150 is coming from MySQL - not Peewee...",
"So if I look at the generated SQL for the CREATE TABLE query looks OK to me:\r\n\r\n```sql\r\nCREATE TABLE IF NOT EXISTS `reverse_string_map` (\r\n `id` INTEGER AUTO_INCREMENT NOT NULL PRIMARY KEY, \r\n `release_map_id` VARCHAR(51) NOT NULL, \r\n FOREIGN KEY (`release_map_id`) \r\n REFERENCES `release_asin_map` (`release_id`) \r\n ON DELETE CASCADE)\r\n```\r\n\r\nYou may want to check your MySQL manual, verify the storage engine you are using (you need InnoDB), etc, etc. This SO answer may help:\r\n\r\nhttps://stackoverflow.com/questions/1457305/mysql-creating-tables-with-foreign-keys-giving-errno-150",
"The following code works fine for me and does not produce any error, so I'll suggest you've got some problem on your side and that this isn't a bug in Peewee:\r\n\r\n```python\r\nfrom peewee import *\r\n\r\ndb = MySQLDatabase('peewee_test')\r\n\r\nclass BaseModel(Model):\r\n class Meta:\r\n legacy_table_names = False\r\n database = db\r\n\r\nclass ReleaseASINMap(BaseModel):\r\n release_id = CharField(max_length=51, unique=True, null=True)\r\n\r\nclass ReverseStringMap(BaseModel):\r\n release_map = ForeignKeyField(ReleaseASINMap, field=\"release_id\",\r\n backref='reverse_map',\r\n on_delete=\"CASCADE\")\r\n\r\ndb.create_tables([ReleaseASINMap, ReverseStringMap])\r\ndb.drop_tables([ReleaseASINMap, ReverseStringMap])\r\n```",
"Noted the issue. It was with the collations difference. Database itself is on latin1 collation, some tables are on utf8. Thanks for that."
] | 2019-05-03T14:38:06 | 2019-05-06T08:12:58 | 2019-05-04T13:21:06 | NONE | null | I have a table using InnoDB engine in MySQL. The field I want to reference is a varchar of 51.
Using the create_table or create_tables([Table]) syntax to create it, the created foreign key field is varchar of 255, leading an error #150. | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1920/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/1920/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1919 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1919/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1919/comments | https://api.github.com/repos/coleifer/peewee/issues/1919/events | https://github.com/coleifer/peewee/issues/1919 | 439,776,015 | MDU6SXNzdWU0Mzk3NzYwMTU= | 1,919 | Bug in mapping to class? | {
"login": "ruby99",
"id": 18327723,
"node_id": "MDQ6VXNlcjE4MzI3NzIz",
"avatar_url": "https://avatars.githubusercontent.com/u/18327723?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/ruby99",
"html_url": "https://github.com/ruby99",
"followers_url": "https://api.github.com/users/ruby99/followers",
"following_url": "https://api.github.com/users/ruby99/following{/other_user}",
"gists_url": "https://api.github.com/users/ruby99/gists{/gist_id}",
"starred_url": "https://api.github.com/users/ruby99/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/ruby99/subscriptions",
"organizations_url": "https://api.github.com/users/ruby99/orgs",
"repos_url": "https://api.github.com/users/ruby99/repos",
"events_url": "https://api.github.com/users/ruby99/events{/privacy}",
"received_events_url": "https://api.github.com/users/ruby99/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"Can you use readable names here? Wtf is r, ou, backr.",
"Oh, also: is this a regression? If so, What is the last version in which this worked?",
"regarding 2nd comment, IDK. I'm evaluating if peewee can replace django's orm for one of my projects.",
"regarding 1st comment:\r\n\r\n```\r\nclass OU(peewee.Model):\r\n name = peewee.CharField(max_length=32)\r\n\r\n```\r\n```\r\nclass R(peewee.Model):\r\n ou = peewee.ForeignKeyField(OU, null=False, backref='r_set')\r\n back = peewee.ForeignKeyField('self', null=True)\r\n front = peewee.ForeignKeyField('self', null=True)\r\n idx = peewee.IntegerField()\r\n lbl = peewee.CharField(null=True,max_length=8)\r\n \r\n def __str__(self):\r\n \t\"\"\"\r\n \tWARNING!\r\n \tThis is costly, at least with peewee. With others ORMs probably too\r\n \t\"\"\"\r\n \treturn self.ou.name + \" \" + self.lbl\r\n\r\n class Meta:\r\n \t# Make ou.id + idx UNIQUE together\r\n \tindexes = (\r\n \t\t(('ou', 'idx'), True),\r\n \t)\r\n```\r\n\r\nI want to get all distinct r.back.ous for given r.ou.name. dicts() and tuples() works as expected, eg:\r\n```\r\n>>> print(list(R.select(BackOU).join(OU).switch(R).join(Back, on=R.back).join(BackOU).where(OU.name==\"G-CK-p1\").group_by(BackOU).dicts()))\r\n[{'id': 2, 'name': 'G-ELE-p1'}]\r\n```\r\n",
"First off, you've written your query in the most ass-backward way conceivable. Try writing your query so you are selecting first from OU, since that's what you're after anyways:\r\n\r\n```python\r\n\r\n# Should be equivalent and is much more clear.\r\n# Because you're interested in data from the OU table, start there.\r\nquery = (OU\r\n .select(OU)\r\n .join_from(OU, R)\r\n .join_from(R, Back, on=(Back.back == R.id))\r\n .join_from(Back, BackOU)\r\n .where(BackOU.name == 'G-CK-p1')\r\n .group_by(OU))\r\n\r\n# Works as expected.\r\nfor ou_obj in query:\r\n print(ou_obj.name)\r\n```\r\n\r\n--------------------------\r\n\r\nMore in-depth explanation...\r\n\r\n> dicts() and tuples() works as expected, eg:\r\n\r\nIf this is the case, then the problem is likely that you are running into Peewee's logic that, when dealing with model graphs (which is what any foreign-key relationship forms), will reconstruct that graph when iterating the cursor.\r\n\r\nThe `dicts()` and `tuples()` (and `namedtuples()` and `objects()`) do not do this graph processing.\r\n\r\nThe fact is, you're starting \"from\" the `R` model, but you're interested in the fields on the `BackOU` model. When peewee builds the graph, it sees that a) the starting model is R and b) the selected data is coming from BackOU, so you probably want to do something like this:\r\n\r\n```python\r\n\r\n# Iterating over the query, because you start from \"R\", yields R() instances.\r\nfor r_instance in query:\r\n # The backou data you're interested in is *probably* accessible like this, but the\r\n # query is honestly so fucked, I'm not sure.\r\n print(r_instance.back.ou.name)\r\n```\r\n\r\n**Lastly**: if you want to avoid all the model graph logic, just use the \".objects()\" method of the query. This will patch all attributes from the cursor directly onto the model instance:\r\n\r\n```python\r\n\r\nfor r_instance in query.objects():\r\n print(r_instance.name) # Should be backou.name here.\r\n```\r\n\r\n-------------------------\r\n\r\nQuestions go on stackoverflow or IRC, by the way.",
"**First:** I knew diving deep into models will distract from my point. Peewee produces valid SQL (the one included is from debug log, and not something I've conceived myself...), and orm is not able to map it back to model, which *is* passed to .select(). It feels at least inconsistent, and that's why I've decided to open the ticket.\r\n\r\n> First off, you've written your query in the most ass-backward way conceivable. \r\n\r\nThanks, :-P\r\n\r\nOUs group Rs. I'm looking for all groups related to the one I know. So the way I wrote this query feels more natural to me.\r\n\r\nAlso, there are 100s of thousands of individual Rs, and one group can point to 10s of other groups. I feel (maybe that's even what they taught me 20+ years ago) it's proper to limit rows as soon as possible before going on with another joins. But SQL is not my area of expertise, so this may be irrelevant nowadays.\r\n\r\n> More in-depth explanation...\r\n\r\n[...]\r\n\r\n> The fact is, you're starting \"from\" the `R` model, but you're interested in the fields on the `BackOU` model. When peewee builds the graph, it sees that a) the starting model is R and b) the selected data is coming from BackOU, so you probably want to do something like this:\r\n> \r\n> ```python\r\n> # Iterating over the query, because you start from \"R\", yields R() instances.\r\n> for r_instance in query:\r\n> # The backou data you're interested in is *probably* accessible like this, but the\r\n> # query is honestly so fucked, I'm not sure.\r\n> print(r_instance.back.ou.name)\r\n> ```\r\n\r\n```python\r\nq = (R\r\n .select(R,OU,Back,BackOU)\r\n .join(OU)\r\n .switch(R)\r\n .join(Back,on=R.back)\r\n .join(BackOU)\r\n .where(OU.name==\"G-CK-p1\")\r\n .group_by(BackOU)\r\n)\r\n```\r\nwill do this without N+1 problem.\r\n\r\n`.select()` will work, but with additional query.\r\n\r\n`.select(BackOU)` will fail.\r\n \r\n> **Lastly**: if you want to avoid all the model graph logic, just use the \".objects()\" method of the query. This will patch all attributes from the cursor directly onto the model instance:\r\n> \r\n> ```python\r\n> for r_instance in query.objects():\r\n> print(r_instance.name) # Should be backou.name here.\r\n> ```\r\n\r\nWhich way is the peewee way?\r\n\r\nAnd now back to the docs.\r\nRegards,\r\nb.",
"In your example you've got an OU name. And it seemed you were interested in getting the OU id/name via a couple hops. So:\r\n\r\n* I've shared an equivalent query that you can use.\r\n* Or you can tack \".objects()\" onto the query you shared and access the name directly."
] | 2019-05-02T20:33:19 | 2019-05-03T12:06:02 | 2019-05-03T03:30:48 | NONE | null | Hello,
```
>>> peewee.__version__
'3.9.5'
```
```
Back = R.alias()
BackOU = OU.alias()
R.select(BackOU).join(OU).switch(R).join(Back, on=R.back).join(BackOU).where(OU.name=="G-CK-p1").group_by(BackOU)
```
while SQL seems about right:
```sql
SELECT "t1"."id", "t1"."name"
FROM "r" AS "t2"
INNER JOIN "ou" AS "t3"
ON ("t2"."ou_id" = "t3"."id")
INNER JOIN "r" AS "t4"
ON ("t2"."back_id" = "t4"."id")
INNER JOIN "ou" AS "t1"
ON ("t4"."ou_id" = "t1"."id")
WHERE ("t3"."name" = ?)
GROUP BY "t1"', ['G-CK-p1'])
```
traceback:
```
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/fback/python/peewee.py", line 5809, in <lambda>
cls.__name__, self.__str__()))
File "/home/fback/Apps/rel/models.py", line 30, in __str__
return self.ou.name + " " + self.lbl
File "/home/fback/python/peewee.py", line 4142, in __get__
return self.get_rel_instance(instance)
File "/home/fback/python/peewee.py", line 4137, in get_rel_instance
raise self.rel_model.DoesNotExist
models.OUDoesNotExist
```
indicates that ORM maps to R, instead of OU.
Regards,
b. | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1919/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/1919/timeline | null | completed | null | null |
Subsets and Splits