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/1618 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1618/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1618/comments | https://api.github.com/repos/coleifer/peewee/issues/1618/events | https://github.com/coleifer/peewee/pull/1618 | 328,825,235 | MDExOlB1bGxSZXF1ZXN0MTkyMjQ1NDU5 | 1,618 | Correct spelling mistakes. | {
"login": "EdwardBetts",
"id": 3818,
"node_id": "MDQ6VXNlcjM4MTg=",
"avatar_url": "https://avatars.githubusercontent.com/u/3818?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/EdwardBetts",
"html_url": "https://github.com/EdwardBetts",
"followers_url": "https://api.github.com/users/EdwardBetts/followers",
"following_url": "https://api.github.com/users/EdwardBetts/following{/other_user}",
"gists_url": "https://api.github.com/users/EdwardBetts/gists{/gist_id}",
"starred_url": "https://api.github.com/users/EdwardBetts/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/EdwardBetts/subscriptions",
"organizations_url": "https://api.github.com/users/EdwardBetts/orgs",
"repos_url": "https://api.github.com/users/EdwardBetts/repos",
"events_url": "https://api.github.com/users/EdwardBetts/events{/privacy}",
"received_events_url": "https://api.github.com/users/EdwardBetts/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"Thank you!"
] | 2018-06-03T12:38:58 | 2018-06-03T20:22:09 | 2018-06-03T20:01:37 | CONTRIBUTOR | null | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1618/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/1618/timeline | null | null | false | {
"url": "https://api.github.com/repos/coleifer/peewee/pulls/1618",
"html_url": "https://github.com/coleifer/peewee/pull/1618",
"diff_url": "https://github.com/coleifer/peewee/pull/1618.diff",
"patch_url": "https://github.com/coleifer/peewee/pull/1618.patch",
"merged_at": "2018-06-03T20:01:37"
} |
|
https://api.github.com/repos/coleifer/peewee/issues/1617 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1617/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1617/comments | https://api.github.com/repos/coleifer/peewee/issues/1617/events | https://github.com/coleifer/peewee/issues/1617 | 328,762,654 | MDU6SXNzdWUzMjg3NjI2NTQ= | 1,617 | importing peewee hangs debugging on windows | {
"login": "GitHubAre",
"id": 17234860,
"node_id": "MDQ6VXNlcjE3MjM0ODYw",
"avatar_url": "https://avatars.githubusercontent.com/u/17234860?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/GitHubAre",
"html_url": "https://github.com/GitHubAre",
"followers_url": "https://api.github.com/users/GitHubAre/followers",
"following_url": "https://api.github.com/users/GitHubAre/following{/other_user}",
"gists_url": "https://api.github.com/users/GitHubAre/gists{/gist_id}",
"starred_url": "https://api.github.com/users/GitHubAre/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/GitHubAre/subscriptions",
"organizations_url": "https://api.github.com/users/GitHubAre/orgs",
"repos_url": "https://api.github.com/users/GitHubAre/repos",
"events_url": "https://api.github.com/users/GitHubAre/events{/privacy}",
"received_events_url": "https://api.github.com/users/GitHubAre/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"Try to use Pycharm. ",
"pycharm works fine, thank you!"
] | 2018-06-02T17:40:13 | 2018-06-02T22:15:26 | 2018-06-02T22:15:26 | NONE | null | Hello,
I am using Visual Studio Code and Windows 10 for development
I have installed peewee using pip.
When having _from peewee import *_ I cant debug and everything hangs on the import line.
If I remove breakpoints from Visual Studio Code it does not hang.
Can you please suggest what could be problem? What is happening behind the scenes that could block the debugger?
| {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1617/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/1617/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1616 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1616/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1616/comments | https://api.github.com/repos/coleifer/peewee/issues/1616/events | https://github.com/coleifer/peewee/issues/1616 | 327,206,079 | MDU6SXNzdWUzMjcyMDYwNzk= | 1,616 | use value as LIKE left hand operand | {
"login": "gbour",
"id": 644293,
"node_id": "MDQ6VXNlcjY0NDI5Mw==",
"avatar_url": "https://avatars.githubusercontent.com/u/644293?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/gbour",
"html_url": "https://github.com/gbour",
"followers_url": "https://api.github.com/users/gbour/followers",
"following_url": "https://api.github.com/users/gbour/following{/other_user}",
"gists_url": "https://api.github.com/users/gbour/gists{/gist_id}",
"starred_url": "https://api.github.com/users/gbour/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/gbour/subscriptions",
"organizations_url": "https://api.github.com/users/gbour/orgs",
"repos_url": "https://api.github.com/users/gbour/repos",
"events_url": "https://api.github.com/users/gbour/events{/privacy}",
"received_events_url": "https://api.github.com/users/gbour/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"Sure, you can use `Value(123456)`:\r\n\r\n```python\r\n\r\n# If prefix is a string literal:\r\nquery = SomeTable.select().where(Value('123456').startswith('someprefix'))\r\n\r\n# If prefix is a column on the table:\r\nquery = SomeTable.select().where(Value('123456').startswith(SomeTable.prefix))\r\n```",
"Oh really good, I did not found it in the documentation\r\nThanks very much @coleifer, you made my day :+1: \r\n\r\nthis is only in 3.4.0 version, right ?",
"The `Value` type was added in 3.0. Prior to 3.x you may be able to use `Param` instead."
] | 2018-05-29T07:49:38 | 2018-05-29T15:45:29 | 2018-05-29T13:47:15 | NONE | null | Hello,
In sqlite, we can do a query like that (prefix being a field of mytable table):
`SELECT * FROM mytable WHERE 123456 LIKE prefix||'%'`
same in mysql:
`SELECT * FROM mytable WHERE 123456 LIKE concat(prefix,'%')`
It will match prefixes like '12' or '1234'. I use it for prefix matching.
Unfortunately with peewee, *%* left hand must be the table field.
Is there a proper way to do that ?
Thanks for your help.
| {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1616/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/1616/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1615 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1615/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1615/comments | https://api.github.com/repos/coleifer/peewee/issues/1615/events | https://github.com/coleifer/peewee/issues/1615 | 327,062,488 | MDU6SXNzdWUzMjcwNjI0ODg= | 1,615 | Inserting billions of rows | {
"login": "stefdoerr",
"id": 7935362,
"node_id": "MDQ6VXNlcjc5MzUzNjI=",
"avatar_url": "https://avatars.githubusercontent.com/u/7935362?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/stefdoerr",
"html_url": "https://github.com/stefdoerr",
"followers_url": "https://api.github.com/users/stefdoerr/followers",
"following_url": "https://api.github.com/users/stefdoerr/following{/other_user}",
"gists_url": "https://api.github.com/users/stefdoerr/gists{/gist_id}",
"starred_url": "https://api.github.com/users/stefdoerr/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/stefdoerr/subscriptions",
"organizations_url": "https://api.github.com/users/stefdoerr/orgs",
"repos_url": "https://api.github.com/users/stefdoerr/repos",
"events_url": "https://api.github.com/users/stefdoerr/events{/privacy}",
"received_events_url": "https://api.github.com/users/stefdoerr/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"I tried moving the `with db.atomic():` inside the `for group in tqdm(groups):` loop which is how I had written it in `sqlite` and the progress bar said that it would take 6 hours to complete versus 2 minutes in `sqlite`\r\n\r\n```python\r\n with h5py.File(dataset, 'r') as infile:\r\n groups = list(infile)\r\n for group in tqdm(groups): # Around 50k iterations\r\n data = []\r\n for i, myval in enumerate(np.array(infile[group]['myval'])):\r\n data.append((group, 'c{0:06d}'.format(i), myval, False, False))\r\n with db.atomic():\r\n Data.insert_many(data, fields=fields).execute()\r\n```",
"This is how the code looks like in `sqlite`\r\n\r\n```python\r\nc.execute('CREATE TABLE workunits (wuID INTEGER PRIMARY KEY, name TEXT DEFAULT NULL)')\r\nconn.commit()\r\nc.execute('''CREATE TABLE data (x1 TEXT NOT NULL, \r\n x2 TEXT NOT NULL, \r\n x3 INTEGER, \r\n x4 REAL DEFAULT NULL, \r\n x5 REAL DEFAULT NULL, \r\n x6 INTEGER DEFAULT NULL, \r\n x7 INTEGER DEFAULT NULL,\r\n FOREIGN KEY(x3) REFERENCES workunits(wuID),\r\n PRIMARY KEY(x1, x2)\r\n )''')\r\nconn.commit()\r\nconn.close()\r\n\r\nwith h5py.File(dataset, 'r') as infile:\r\n groups = list(infile)\r\n for group in tqdm(groups):\r\n rdata = [(group, 'c{0:06d}'.format(i), 0, val, 0, 0) for i, val in enumerate(np.array(infile[group]['val']))]\r\n c.executemany(\"INSERT INTO data VALUES (?, ?, NULL, ?, ?, ?, ?)\", rdata)\r\n```",
"I have a feeling that the answer is: \"use NoSQL\" :grin: ",
"My personal answer will never be to use NoSQL! Peewee can handle this, but it does impose some overhead. Here are the docs on ideas for speeding-up bulk inserts:\r\n\r\nhttp://docs.peewee-orm.com/en/latest/peewee/querying.html#bulk-inserts\r\n\r\n[Your comment](https://github.com/coleifer/peewee/issues/1615#issuecomment-392557450), in which you use a transaction and insert_many() looks good but you may be hitting practical limits with SQLite's ability to parameterize the data. Peewee also may be getting in the way by ensuring/validating data-types before building up the query. You can always profile the code to see what's going on.\r\n\r\nUsing `executemany()` with a sqlite3 cursor is just fine, too. Peewee database objects have a `cursor()` method with exposes a DB-API cursor. So this should work:\r\n\r\n```python\r\ndb = pw.SqliteDatabase(...)\r\ndb.create_tables([WorkUnit, Data])\r\ncursor = db.cursor()\r\n\r\nwith h5py.File(dataset, 'r') as infile:\r\n groups = list(infile)\r\n for group in tqdm(groups):\r\n rdata = [(group, 'c{0:06d}'.format(i), 0, val, 0, 0) for i, val in enumerate(np.array(infile[group]['val']))]\r\n cursor.executemany(\"INSERT INTO data VALUES (?, ?, NULL, ?, ?, ?, ?)\", rdata)\r\n```\r\n\r\nLastly, you can try batching the inserts:\r\n\r\n```python\r\n with h5py.File(dataset, 'r') as infile:\r\n groups = list(infile)\r\n for group in tqdm(groups): # Around 50k iterations\r\n data = []\r\n for i, myval in enumerate(np.array(infile[group]['myval'])):\r\n data.append((group, 'c{0:06d}'.format(i), myval, False, False))\r\n\r\n with db.atomic():\r\n for i in range(0, len(data), 100): # INSERT 100 rows at-a-time\r\n Data.insert_many(data[i:i+100], fields=fields).execute()\r\n```",
"Great! Thanks for the input :) I will give it a try tomorrow.",
"So I tried the peewee cursor\r\n```python\r\ncursor = db.cursor()\r\ncursor.executemany(\"INSERT INTO data VALUES (?, ?, NULL, ?, ?, ?, ?)\", rdata)\r\n```\r\nversus the sqlite cursor\r\n```python\r\nconn = sqlite3.connect(dbpath)\r\nc = conn.cursor()\r\nc.executemany(\"INSERT INTO data VALUES (?, ?, NULL, ?, ?, ?, ?)\", rdata)\r\n```\r\nand the first one is still orders of magnitude slower. I don't know what the cause is since I can't profile very easily on the machine I'm currently on but in any case it seems I'll just mix'n'match between peewee and sqlite3 for the moment.\r\n",
"That's very strange, since the first one is literally the same as the second. It *may* have something to do with the way Peewee sets up the connection autocommit... you can try wrapping it in a transaction and seeing if that has any effect:\r\n\r\n```python\r\nwith db.atomic():\r\n cursor.executemany(...)\r\n```"
] | 2018-05-28T15:32:19 | 2018-05-29T13:48:32 | 2018-05-28T22:51:35 | NONE | null | Hi, I wanted to try out peewee for the first time but I hit a snag at inserting ~20 billion rows. With the python sqlite3 library it works super fast (~1.5 minutes).
With peewee I don't see any progress. Neither does the file grow nor does it finish within a reasonable time-frame and there is no indication of progress.
I don't know if I'm doing something really bad. The only difference is that I could not create a double-column primary key in Data so I made a double-column index instead.
Any help would be appreciated :)
```python
import os
import numpy as np
import h5py
from tqdm import tqdm
import peewee as pw
db = pw.SqliteDatabase(dbpath)
class WorkUnit(pw.Model):
name = pw.CharField()
class Meta:
database = db
class Data(pw.Model):
x1 = pw.CharField()
x2 = pw.CharField()
x3 = pw.ForeignKeyField(WorkUnit, null=True)
x4 = pw.FloatField(null=True)
x5 = pw.FloatField(null=True)
x6 = pw.BooleanField(null=True)
x7 = pw.BooleanField(null=True)
class Meta:
indexes = (
(('x1', 'x2'), True), # True for unique
)
database = db
db.connect()
def createTables():
db.create_tables([WorkUnit, Data])
def initializeDB(dataset):
data = []
fields = [Data.x1, Data.x2, Data.x5, Data.x6, Data.x7]
with h5py.File(dataset, 'r') as infile:
groups = list(infile)
for group in tqdm(groups):
for i, myval in enumerate(np.array(infile[group]['myval'])):
data.append((group, 'c{0:06d}'.format(i), myval, False, False))
with db.atomic():
Data.insert_many(data, fields=fields).execute()
``` | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1615/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/1615/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1614 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1614/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1614/comments | https://api.github.com/repos/coleifer/peewee/issues/1614/events | https://github.com/coleifer/peewee/issues/1614 | 326,434,137 | MDU6SXNzdWUzMjY0MzQxMzc= | 1,614 | Problem serializing query result to JSON | {
"login": "mgraupner",
"id": 586644,
"node_id": "MDQ6VXNlcjU4NjY0NA==",
"avatar_url": "https://avatars.githubusercontent.com/u/586644?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/mgraupner",
"html_url": "https://github.com/mgraupner",
"followers_url": "https://api.github.com/users/mgraupner/followers",
"following_url": "https://api.github.com/users/mgraupner/following{/other_user}",
"gists_url": "https://api.github.com/users/mgraupner/gists{/gist_id}",
"starred_url": "https://api.github.com/users/mgraupner/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/mgraupner/subscriptions",
"organizations_url": "https://api.github.com/users/mgraupner/orgs",
"repos_url": "https://api.github.com/users/mgraupner/repos",
"events_url": "https://api.github.com/users/mgraupner/events{/privacy}",
"received_events_url": "https://api.github.com/users/mgraupner/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"Yes, this is the intended behavior. That group by looks sketchy as hell since you're selecting columns that aren't included in the group by...granted, that probably works fine for SQLite and MySQL. Anyways!\r\n\r\n`model_to_dict` probably isn't going to work correctly for what you're trying to do without some gymnastics. It's probably much easier to just do something like:\r\n\r\n```python\r\naccum = []\r\nfor user_obj in result:\r\n user_dict = model_to_dict(user_obj, recurse=False)\r\n user_dict['latest_event'] = model_to_dict(user_obj.event, recurse=False)\r\n```",
"Thanks, the group_by clause had the wrong content (fixed now).\r\n\r\nDoes your solution still apply or is there some automated way now? Or is there a better way for the query so that there is an automated way?",
"The solution I gave is probably the easiest way to achieve what you want. Events is a backref from the perspective of the user object, so peewee treats it as a list. Since you only need the one event per user, just use the approach I suggested.",
"The given example works as expected. Thank you very much for your help. I think I just expected too much automatism after reading the manual. :)\r\n\r\nSome minor stuff: I think you forgot to add the user_dict to the accum list in your example."
] | 2018-05-25T08:48:25 | 2018-05-25T16:50:33 | 2018-05-25T16:50:33 | NONE | null | Following model:
```
class User(BaseModel):
...
class Event(BaseModel):
...
user = ForeignKeyField(User, related_name='events')
```
I want to have the newest event for each user:
```
result = (User
.select(User, Event)
.join(Event)
.group_by(Event.user_id)
.having(fn.MAX(Event.create_date))
.order_by(Event.create_date.desc())
)
```
and then serialize the result to JSON:
```
serialized = [model_to_dict(r, recurse=True, backrefs=True) for r in result]
```
unfortunately now ALL events are included in the serialized data (guess that's what backrefs does), not just the newest like in my query. Is this the intended behaviour? How can I only get the user/event I was selecting for in the query?
Thanks for your help. | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1614/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/1614/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1613 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1613/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1613/comments | https://api.github.com/repos/coleifer/peewee/issues/1613/events | https://github.com/coleifer/peewee/issues/1613 | 326,396,432 | MDU6SXNzdWUzMjYzOTY0MzI= | 1,613 | SchemaMigrator.add_column ignores the index_type, always results a btree index. | {
"login": "wonderbeyond",
"id": 228361,
"node_id": "MDQ6VXNlcjIyODM2MQ==",
"avatar_url": "https://avatars.githubusercontent.com/u/228361?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/wonderbeyond",
"html_url": "https://github.com/wonderbeyond",
"followers_url": "https://api.github.com/users/wonderbeyond/followers",
"following_url": "https://api.github.com/users/wonderbeyond/following{/other_user}",
"gists_url": "https://api.github.com/users/wonderbeyond/gists{/gist_id}",
"starred_url": "https://api.github.com/users/wonderbeyond/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/wonderbeyond/subscriptions",
"organizations_url": "https://api.github.com/users/wonderbeyond/orgs",
"repos_url": "https://api.github.com/users/wonderbeyond/repos",
"events_url": "https://api.github.com/users/wonderbeyond/events{/privacy}",
"received_events_url": "https://api.github.com/users/wonderbeyond/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"Thanks, I've fixed this in 8a95426 and added a test and updated docs. I appreciate you taking the time to report this issue."
] | 2018-05-25T06:26:17 | 2018-05-25T13:52:40 | 2018-05-25T13:52:40 | NONE | null | with `db.create_tables`, I can get an `GIN` index for a field like below:
```python
BinaryJSONField(default=dict, index=True, null=True)
```
However, if I add a new column with `migrator.add_column`, I always get a btree index.
You may need inspecting code here: https://github.com/coleifer/peewee/blob/master/playhouse/migrate.py#L290 | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1613/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/1613/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1612 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1612/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1612/comments | https://api.github.com/repos/coleifer/peewee/issues/1612/events | https://github.com/coleifer/peewee/issues/1612 | 326,366,663 | MDU6SXNzdWUzMjYzNjY2NjM= | 1,612 | table_exists() function not working. | {
"login": "djh2020",
"id": 6467508,
"node_id": "MDQ6VXNlcjY0Njc1MDg=",
"avatar_url": "https://avatars.githubusercontent.com/u/6467508?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/djh2020",
"html_url": "https://github.com/djh2020",
"followers_url": "https://api.github.com/users/djh2020/followers",
"following_url": "https://api.github.com/users/djh2020/following{/other_user}",
"gists_url": "https://api.github.com/users/djh2020/gists{/gist_id}",
"starred_url": "https://api.github.com/users/djh2020/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/djh2020/subscriptions",
"organizations_url": "https://api.github.com/users/djh2020/orgs",
"repos_url": "https://api.github.com/users/djh2020/repos",
"events_url": "https://api.github.com/users/djh2020/events{/privacy}",
"received_events_url": "https://api.github.com/users/djh2020/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"So in examining / digging through your tests I see your documentation isn't accurate. Looks like it needs to be updated.\r\n\r\nhttps://github.com/coleifer/peewee/blob/49c162d5939bb52627c1e6a1687e722b8bf83ec9/tests/database.py#L398\r\n\r\n\r\ndocumented\r\n<img width=\"702\" alt=\"screen shot 2018-05-24 at 8 22 18 pm\" src=\"https://user-images.githubusercontent.com/6467508/40524715-02f652c0-5f91-11e8-9f98-fa47bc38ebec.png\">\r\n\r\n\r\nactually...\r\n<img width=\"341\" alt=\"screen shot 2018-05-24 at 8 24 11 pm\" src=\"https://user-images.githubusercontent.com/6467508/40524726-16597fe0-5f91-11e8-85a6-a36e768d2cc3.png\">\r\n",
"Thank you, I've fixed this so that the implementation matches the docs (i.e., you pass the table name)."
] | 2018-05-25T03:15:45 | 2018-05-25T13:38:00 | 2018-05-25T13:38:00 | NONE | null | I am unable to get this function to work. I have tried (table='job'),('job'),(job),(['job'])

| {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1612/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/1612/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1611 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1611/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1611/comments | https://api.github.com/repos/coleifer/peewee/issues/1611/events | https://github.com/coleifer/peewee/issues/1611 | 325,655,257 | MDU6SXNzdWUzMjU2NTUyNTc= | 1,611 | get_or_create failing | {
"login": "ra-esmith",
"id": 24212262,
"node_id": "MDQ6VXNlcjI0MjEyMjYy",
"avatar_url": "https://avatars.githubusercontent.com/u/24212262?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/ra-esmith",
"html_url": "https://github.com/ra-esmith",
"followers_url": "https://api.github.com/users/ra-esmith/followers",
"following_url": "https://api.github.com/users/ra-esmith/following{/other_user}",
"gists_url": "https://api.github.com/users/ra-esmith/gists{/gist_id}",
"starred_url": "https://api.github.com/users/ra-esmith/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/ra-esmith/subscriptions",
"organizations_url": "https://api.github.com/users/ra-esmith/orgs",
"repos_url": "https://api.github.com/users/ra-esmith/repos",
"events_url": "https://api.github.com/users/ra-esmith/events{/privacy}",
"received_events_url": "https://api.github.com/users/ra-esmith/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"Ok so the GET if I just do that fails!! But why? I can run this query by hand in psql ...\r\nThere are other fields in the table, here they are, but this record does exist, wht this value for code.\r\n\r\n\r\ndoing a select explicitly\r\n('SELECT \"t1\".\"code\", \"t1\".\"allstars\", \"t1\".\"average_resale_factor\", \"t1\".\"away_losses\", \"t1\".\"away_pitcher_rating\", \"t1\".\"away_points\", \"t1\".\"away_wins\", \"t1\".\"canceled\", \"t1\".\"count_resales\", \"t1\".\"count_scans\", \"t1\".\"count_tickets\", \"t1\".\"days_since_last_game\", \"t1\".\"days_until_next_game\", \"t1\".\"division\", \"t1\".\"family\", \"t1\".\"games_left\", \"t1\".\"home_losses\", \"t1\".\"home_pitcher_rating\", \"t1\".\"home_points\", \"t1\".\"home_win_percent\", \"t1\".\"home_win_record\", \"t1\".\"home_wins\", \"t1\".\"kd_playing\", \"t1\".\"national_holiday\", \"t1\".\"national_tv\", \"t1\".\"nearest_storm\", \"t1\".\"opponent_id\", \"t1\".\"precipitation\", \"t1\".\"precipitation_intensity\", \"t1\".\"prediction_override\", \"t1\".\"promotional\", \"t1\".\"religious_holiday\", \"t1\".\"rw_playing\", \"t1\".\"star_multiplier\", \"t1\".\"team_id\", \"t1\".\"team_score\", \"t1\".\"temperature\", \"t1\".\"time\", \"t1\".\"meta_sold_seats_number\", \"t1\".\"meta_available_seats_number\", \"t1\".\"meta_total_num_seats_stadium\", \"t1\".\"meta_available_seats_total_cost\" FROM \"game\" AS \"t1\" WHERE (\"t1\".\"code\" = %s) LIMIT %s OFFSET %s', [u'LR091816', 1, 0])\r\nwere not able to get it\r\nTraceback (most recent call last):\r\n File \"/home/anon/Desktop/ra/precast-master/precast_ingest_util.py\", line 139, in create_or_increment\r\n foo = model.get(model.code == 'LR091816')\r\n File \"/home/anon/miniconda2/lib/python2.7/site-packages/peewee.py\", line 5311, in get\r\n return sq.get()\r\n File \"/home/anon/miniconda2/lib/python2.7/site-packages/peewee.py\", line 5705, in get\r\n return clone.execute()[0]\r\n File \"/home/anon/miniconda2/lib/python2.7/site-packages/peewee.py\", line 1522, in inner\r\n return method(self, database, *args, **kwargs)\r\n File \"/home/anon/miniconda2/lib/python2.7/site-packages/peewee.py\", line 1593, in execute\r\n return self._execute(database)\r\n File \"/home/anon/miniconda2/lib/python2.7/site-packages/peewee.py\", line 1747, in _execute\r\n cursor = database.execute(self)\r\n File \"/home/anon/miniconda2/lib/python2.7/site-packages/peewee.py\", line 2590, in execute\r\n return self.execute_sql(sql, params, commit=commit)\r\n File \"/home/anon/miniconda2/lib/python2.7/site-packages/peewee.py\", line 2584, in execute_sql\r\n self.commit()\r\n File \"/home/anon/miniconda2/lib/python2.7/site-packages/peewee.py\", line 2377, in __exit__\r\n reraise(new_type, new_type(*exc_args), traceback)\r\n File \"/home/anon/miniconda2/lib/python2.7/site-packages/peewee.py\", line 2577, in execute_sql\r\n cursor.execute(sql, params or ())\r\nInternalError: current transaction is aborted, commands ignored until end of transaction block\r\n\r\n",
"in psql on this db \r\nthe following returns a record\r\n\r\n SELECT \"t1\".\"code\", \"t1\".\"allstars\", \"t1\".\"average_resale_factor\", \"t1\".\"away_losses\", \"t1\".\"away_pitcher_rating\", \"t1\".\"away_points\", \"t1\".\"away_wins\", \"t1\".\"canceled\", \"t1\".\"count_resales\", \"t1\".\"count_scans\", \"t1\".\"count_tickets\", \"t1\".\"days_since_last_game\", \"t1\".\"days_until_next_game\", \"t1\".\"division\", \"t1\".\"family\", \"t1\".\"games_left\", \"t1\".\"home_losses\", \"t1\".\"home_pitcher_rating\", \"t1\".\"home_points\", \"t1\".\"home_win_percent\", \"t1\".\"home_win_record\", \"t1\".\"home_wins\", \"t1\".\"kd_playing\", \"t1\".\"national_holiday\", \"t1\".\"national_tv\", \"t1\".\"nearest_storm\", \"t1\".\"opponent_id\", \"t1\".\"precipitation\", \"t1\".\"precipitation_intensity\", \"t1\".\"prediction_override\", \"t1\".\"promotional\", \"t1\".\"religious_holiday\", \"t1\".\"rw_playing\", \"t1\".\"star_multiplier\", \"t1\".\"team_id\", \"t1\".\"team_score\", \"t1\".\"temperature\", \"t1\".\"time\", \"t1\".\"meta_sold_seats_number\", \"t1\".\"meta_available_seats_number\", \"t1\".\"meta_total_num_seats_stadium\", \"t1\".\"meta_available_seats_total_cost\" FROM \"game\" AS \"t1\" WHERE (\"t1\".\"code\" = 'LR091816') LIMIT 1 OFFSET 0;\r\n",
"Ok so a pee wee sleet for this code works fine, but the get fails?\r\n\r\n try:\r\n print(\"doing a select explicitly fails\")\r\n Game.select()\r\n print(\"get one code explicit select\") # this works\r\n foo = Game.select().where(Game.code == 'LR091816')\r\n print(foo)\r\n \r\n print(\"get one code explicit get\") # ths fails !!\r\n foo = Game.get(Game.code == 'LR091816')\r\n print(foo)\r\n \r\n print(\"doing a get with passed in model explicitly fails\")\r\n foo = model.get(model.code == 'LR091816')\r\n print(\"\\nlets try getting it with model.get and passing in dic\")\r\n z = model.get(**kwargs)\r\n print(z)\r\n except:\r\n print(\"were not able to get it\")\r\n traceback.print_exc() \r\n exit()\r\n\r\n\r\nConsider\r\nget one code explicit select\r\n<peewee.ModelSelect object at 0x7f3544100890>\r\nget one code explicit get\r\n('SELECT \"t1\".\"code\", \"t1\".\"allstars\", \"t1\".\"average_resale_factor\", \"t1\".\"away_losses\", \"t1\".\"away_pitcher_rating\", \"t1\".\"away_points\", \"t1\".\"away_wins\", \"t1\".\"canceled\", \"t1\".\"count_resales\", \"t1\".\"count_scans\", \"t1\".\"count_tickets\", \"t1\".\"days_since_last_game\", \"t1\".\"days_until_next_game\", \"t1\".\"division\", \"t1\".\"family\", \"t1\".\"games_left\", \"t1\".\"home_losses\", \"t1\".\"home_pitcher_rating\", \"t1\".\"home_points\", \"t1\".\"home_win_percent\", \"t1\".\"home_win_record\", \"t1\".\"home_wins\", \"t1\".\"kd_playing\", \"t1\".\"national_holiday\", \"t1\".\"national_tv\", \"t1\".\"nearest_storm\", \"t1\".\"opponent_id\", \"t1\".\"precipitation\", \"t1\".\"precipitation_intensity\", \"t1\".\"prediction_override\", \"t1\".\"promotional\", \"t1\".\"religious_holiday\", \"t1\".\"rw_playing\", \"t1\".\"star_multiplier\", \"t1\".\"team_id\", \"t1\".\"team_score\", \"t1\".\"temperature\", \"t1\".\"time\", \"t1\".\"meta_sold_seats_number\", \"t1\".\"meta_available_seats_number\", \"t1\".\"meta_total_num_seats_stadium\", \"t1\".\"meta_available_seats_total_cost\" FROM \"game\" AS \"t1\" WHERE (\"t1\".\"code\" = %s) LIMIT %s OFFSET %s', [u'LR091816', 1, 0])\r\nwere not able to get it\r\n",
"perhaps get is not an API I should use, was only doing it for testing\r\nwill go back to select and see if I can implement get_or_create with explicity calls",
"i pass in my model (table name) as a variable to a def\r\nalong with kwargs\r\n\r\nI tried\r\nmodel.select().where(**kwargs)\r\n\r\nbut that does not expand kwargs into\r\ncode == 'foo'\r\n\r\nhow do I convert my kwargs into a where expr?\r\n",
"if I do a simple .create then the records are created\r\n\r\nso it seem that the .get is failing to detect if record is present ?",
"AHH \r\n\r\nso when I call get_or_create I am NOT passing in an exression A = B\r\ninstead I have a dictionary A:B, ...\r\nthat I pass in\r\n\r\nDoes the aPI no longer support this? Perhaps it never did?\r\n\r\nHow do I convert from a dictoinary to the expression get_or_create requires?",
"I have been passing in a dictionary\r\nusing **dict to get_or_create\r\n\r\nand that hsould have worked ...?\r\n",
"oh but the create wants a = while the get wants a ==\r\n\r\nI wonder how that works out internally to peewee",
"so the basic first problem is the get_or_create call\r\n\r\nwhy it is finding some \"other\" id other than the id of my the record I want to look at it is just a puzzle (the error). peewee fails on this dupcliate key violation, when it trys to create a new record using an existing id for a record that should never have been looked at/modified in the table!!",
"leaving me with the desire to try doing this all by hand to see if it would work ... but not knowing how to write the select (or update) passing in a dicdtionary of values as I don't know how to write the were expression in python from a dictionary/hash.",
"Can you clarify exactly what problem you'd like help solving? I'm having a hard time following your comments.",
"For what it's worth, `get_or_create` accepts keyword arguments and works on that basis. The `InternalError` you're seeing indicates that something like the following has occurred:\r\n\r\n1. An insert/delete/update triggered an integrity error.\r\n2. You did not explicitly rollback / commit\r\n3. A select was issued subsequent to the integrity error and is failing now.\r\n\r\nThe simplest implementation for get-or-create looks like this:\r\n\r\n```python\r\n\r\n# First try to create it. Rely on an integrity error being raised to determine\r\n# that the object exists.\r\ntry:\r\n with MyModel._meta.database.atomic():\r\n obj = MyModel.create(...)\r\nexcept IntegrityError:\r\n obj = MyModel.get(...)\r\n```\r\n\r\nIf you wish to try and do the select first:\r\n\r\n```python\r\ntry:\r\n obj = MyModel.get(...)\r\nexcept MyModel.DoesNotExist:\r\n try:\r\n with MyModel._meta.database.atomic():\r\n obj = MyModel.create(...)\r\n except IntegrityError:\r\n obj = MyModel.get(...)\r\n```",
"Hello,\n\nSure.\n\nGiven a hash/dictionary in python like\nx = {\"a\":1, \"b\":2}\n\nHow can i write a select query in python, given only x as input, where I want to just\nget records that have a == 1 and b == 2\nso the query\nmodel.select().where(x)\nwhich translates into\nmodel.select().where(model.a == 1, model.b == 2)\n\nIf I can do that I can debug what is going on I think.\n\nThanks!\nevan\n\nSent with [ProtonMail](https://protonmail.com) Secure Email.\n\n‐‐‐‐‐‐‐ Original Message ‐‐‐‐‐‐‐\nOn May 23, 2018 9:59 AM, Charles Leifer <[email protected]> wrote:\n\n> Can you clarify exactly what problem you'd like help solving? I'm having a hard time following your comments.\n>\n> —\n> You are receiving this because you authored the thread.\n> Reply to this email directly, [view it on GitHub](https://github.com/coleifer/peewee/issues/1611#issuecomment-391357055), or [mute the thread](https://github.com/notifications/unsubscribe-auth/AXFzJr7UYTwcNnd2VKW9qcpDDyTYy3Tvks5t1WskgaJpZM4UKOxE).",
"If I can do a select then I would also like to do an update and a create using the same paradigm. Basically write get_or_create by hand. And then see where it crashes in my code .\n\nThanks!\nEvan\n\nSent with [ProtonMail](https://protonmail.com) Secure Email.\n\n‐‐‐‐‐‐‐ Original Message ‐‐‐‐‐‐‐\nOn May 23, 2018 12:07 PM, evan <[email protected]> wrote:\n\n> Hello,\n>\n> Sure.\n>\n> Given a hash/dictionary in python like\n> x = {\"a\":1, \"b\":2}\n>\n> How can i write a select query in python, given only x as input, where I want to just\n> get records that have a == 1 and b == 2\n> so the query\n> model.select().where(x)\n> which translates into\n> model.select().where(model.a == 1, model.b == 2)\n>\n> If I can do that I can debug what is going on I think.\n>\n> Thanks!\n> evan\n>\n> Sent with [ProtonMail](https://protonmail.com) Secure Email.\n>\n> ‐‐‐‐‐‐‐ Original Message ‐‐‐‐‐‐‐\n> On May 23, 2018 9:59 AM, Charles Leifer <[email protected]> wrote:\n>\n>> Can you clarify exactly what problem you'd like help solving? I'm having a hard time following your comments.\n>>\n>> —\n>> You are receiving this because you authored the thread.\n>> Reply to this email directly, [view it on GitHub](https://github.com/coleifer/peewee/issues/1611#issuecomment-391357055), or [mute the thread](https://github.com/notifications/unsubscribe-auth/AXFzJr7UYTwcNnd2VKW9qcpDDyTYy3Tvks5t1WskgaJpZM4UKOxE).",
"If you want to use keyword-arguments for your where clause (which is gross but OK) you can use [filter()](http://docs.peewee-orm.com/en/latest/peewee/api.html#Model.filter). For example:\r\n\r\n```python\r\nclass User(Model):\r\n username = TextField()\r\n\r\nuser_obj = User.filter(username='charlie').get()\r\n\r\n# Or, multiple objects:\r\nusers = User.filter(username__in=['charlie', 'huey', 'mickey'])\r\nfor user in users:\r\n print(user.username)\r\n```\r\n\r\nIt's better to use expressions, though. You can very easily convert a dictionary into the appropriate expressions by using `Model._meta.fields`, which is a mapping of field-name -> field object.\r\n\r\nI think your code is \"crashing\" because of an un-rolled-back integrity error that occurs. You mention you're using Postgres -- how are you instantiating your database?",
"I am using Postgres. And have several apps hitting it. I just do a create database x\n\nThere are lots of constraints between my tables. Indeed if a table a was behind not available that would be a problem\n\nBut when I just alone try to get or create these records it fails to work. The records do not get created. However the raw create call will work creating the records.\n\nA select will fail to return the record of done before create.\n\nA get will fail but complain about some other record Id\n\nEvan",
"You know that get_or_create and related apis are all covered by thorough tests. If there were something fundamentally broken these tests would fail. My point is that the code works. As to why you're having issues, I don't know but I suspect the problem is not peewee.",
"Hello,\n\nOh I am sure that pee wee is not the problem.\n\nI am thinking that perhaps\nI crash somewhere and then postgres is not responding.\n\nDo I need to wrap calls in an atomic or commit/rollback in the event that a call fails?\n\nThe problem is more that I upgraded and have not figured out something that changed. Or I am getting data in a bad order (my current thought).\n\nSo perhaps I do\na get_create or some other sql call - which fails. But do not rollback?\n\nAnd then later do a\nget_or_create which fails be cause postgres is in a bad state?\n\nTrying to come up with some theory ...\n\nEvan\n\nSent with [ProtonMail](https://protonmail.com) Secure Email.\n\n‐‐‐‐‐‐‐ Original Message ‐‐‐‐‐‐‐\nOn May 23, 2018 2:01 PM, Charles Leifer <[email protected]> wrote:\n\n> You know that get_or_create and related apis are all covered by thorough tests. If there were something fundamentally broken these tests would fail. My point is that the code works. As to why you're having issues, I don't know but I suspect the problem is not peewee.\n>\n> —\n> You are receiving this because you authored the thread.\n> Reply to this email directly, [view it on GitHub](https://github.com/coleifer/peewee/issues/1611#issuecomment-391442617), or [mute the thread](https://github.com/notifications/unsubscribe-auth/AXFzJo4Wgd3LurhlXNS7ny1Ekiyr9Pjqks5t1aQAgaJpZM4UKOxE).",
"Hello,\n\nI have about a dozen very large applications running peewee, and there is no problem. They are all very similar.\n\nIt is just this new app (two of them actually) that is having some issue. So the \"data\" coming in and then my code is the issue. The integrity issue is certainly a great one for me to look at. Just not sure how to find a example of where that happens.\n\nMy code loads lots of csv files, which are all interdependent but noisy - so constraints sometimes do not get satisfied.\n\nIf one of the inserts (or updates) \"fails\" with peewee. do I need to do anything to get postgres (or peewee) to continue to work for the next unrelated insert/update?\n\nEvan\n\nSent with [ProtonMail](https://protonmail.com) Secure Email.\n\n‐‐‐‐‐‐‐ Original Message ‐‐‐‐‐‐‐\nOn May 23, 2018 2:22 PM, evan <[email protected]> wrote:\n\n> Hello,\n>\n> Oh I am sure that pee wee is not the problem.\n>\n> I am thinking that perhaps\n> I crash somewhere and then postgres is not responding.\n>\n> Do I need to wrap calls in an atomic or commit/rollback in the event that a call fails?\n>\n> The problem is more that I upgraded and have not figured out something that changed. Or I am getting data in a bad order (my current thought).\n>\n> So perhaps I do\n> a get_create or some other sql call - which fails. But do not rollback?\n>\n> And then later do a\n> get_or_create which fails be cause postgres is in a bad state?\n>\n> Trying to come up with some theory ...\n>\n> Evan\n>\n> Sent with [ProtonMail](https://protonmail.com) Secure Email.\n>\n> ‐‐‐‐‐‐‐ Original Message ‐‐‐‐‐‐‐\n> On May 23, 2018 2:01 PM, Charles Leifer <[email protected]> wrote:\n>\n>> You know that get_or_create and related apis are all covered by thorough tests. If there were something fundamentally broken these tests would fail. My point is that the code works. As to why you're having issues, I don't know but I suspect the problem is not peewee.\n>>\n>> —\n>> You are receiving this because you authored the thread.\n>> Reply to this email directly, [view it on GitHub](https://github.com/coleifer/peewee/issues/1611#issuecomment-391442617), or [mute the thread](https://github.com/notifications/unsubscribe-auth/AXFzJo4Wgd3LurhlXNS7ny1Ekiyr9Pjqks5t1aQAgaJpZM4UKOxE).",
"> If one of the inserts (or updates) \"fails\" with peewee. do I need to do anything to get postgres (or peewee) to continue to work for the next unrelated insert/update?\r\n\r\nYes, you'd need to rollback. e.g. `db.rollback()`",
"I'm going to close this... this issue is out-of-control. If you can create a reproducible *short* script that I can use to reproduce the failure, I'm happy to look into this again.",
"Ok"
] | 2018-05-23T11:02:16 | 2018-05-25T15:08:25 | 2018-05-25T14:01:17 | NONE | null | Hello,
So millions of times get_or_create works fine, but sometimes I am crashing on
what is a legal select statement ! Using newest peewee ...
As a test would like to try the get and create manually, but am unsure how to write that now.
Here are some of what I have found. The table t1 has a primary key named "code".
There is no "id" defined on the table.
AND if I run this query select below in psql it works fine ... but for some reason peewee crashes
with it ...
Naturally I have a dictionary with the value {'code': 'LR091816'}
How would I do a select manually in peewee passing in this dictionary, figure it would be a good test.
I tried model.select().where(d) but that did not seem to work.
Here is the log ...
('SELECT "t1"."code" FROM "game" AS "t1" WHERE ("t1"."code" = %s) LIMIT %s OFFSET %s', [u'LR091816', 1, 0])
* get create failed!
Traceback (most recent call last):
File "/home/anon/Desktop/test/precast_ingest_util.py", line 146, in create_or_increment
model.get_or_create(**kwargs) # the select fails
File "/home/anon/miniconda2/lib/python2.7/site-packages/peewee.py", line 5344, in get_or_create
return query.get(), False
File "/home/anon/miniconda2/lib/python2.7/site-packages/peewee.py", line 5705, in get
return clone.execute()[0]
File "/home/anon/miniconda2/lib/python2.7/site-packages/peewee.py", line 1522, in inner
return method(self, database, *args, **kwargs)
File "/home/anon/miniconda2/lib/python2.7/site-packages/peewee.py", line 1593, in execute
return self._execute(database)
File "/home/anon/miniconda2/lib/python2.7/site-packages/peewee.py", line 1747, in _execute
cursor = database.execute(self)
File "/home/anon/miniconda2/lib/python2.7/site-packages/peewee.py", line 2590, in execute
return self.execute_sql(sql, params, commit=commit)
File "/home/anon/miniconda2/lib/python2.7/site-packages/peewee.py", line 2584, in execute_sql
self.commit()
File "/home/anon/miniconda2/lib/python2.7/site-packages/peewee.py", line 2377, in __exit__
reraise(new_type, new_type(*exc_args), traceback)
File "/home/anon/miniconda2/lib/python2.7/site-packages/peewee.py", line 2577, in execute_sql
cursor.execute(sql, params or ())
InternalError: current transaction is aborted, commands ignored until end of transaction block
current transaction is aborted, commands ignored until end of transaction block
{'code': 'LR091816'}
| {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1611/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/1611/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1610 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1610/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1610/comments | https://api.github.com/repos/coleifer/peewee/issues/1610/events | https://github.com/coleifer/peewee/issues/1610 | 325,066,901 | MDU6SXNzdWUzMjUwNjY5MDE= | 1,610 | get_or_create violates unique constraint when saving | {
"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 | [
"Can you create a minimal test-case I can use to reproduce the issue? I'm unclear from your comment what your model looks like or where the actual error is occurring.",
"I don't seem to be able to reproduce this on a simple case so it may have something to do with my DB (Postgresql). For what I can see, the problem is related to the fact that, although the primary key in Plate has a sequence set, when I do the \r\n\r\n```python\r\ndbo, created = Plate.get_or_create(plate_id=1234)\r\n```\r\n\r\nThe resulting object doesnt have a pk\r\n\r\n```python\r\ndbo\r\n<Plate: pk=None, plate_id=1234>\r\n```\r\n\r\nOther tables in the same DB, with primary key sequences set in the same manner return an object with a `pk != None` when initialised with `get_or_create`. I'll keep digging.\r\n\r\n",
"Ok, I think I fixed it. In my Models some of the primary keys were set to `BigIntegerField` instead of to `PrimaryKeyField` because the underlying primary key field was set as a big integer in Postgresql. Changing it to `PrimaryKeyField` seems to have solved the issue and I don't see any ill effect.\r\n\r\nWorth noting that the models were generated using pywiz, although the peewee 2 version of it. Also, this used to work fine in peewee 2 so not sure if this is a bug or not.",
"Sounds like you got it.\r\n\r\nFor what it's worth, in peewee 3.x, you can use `AutoField` or `BigAutoField` depending on the underlying data-type (serial vs bigserial). `PrimaryKeyField` is provided for backwards-compatibility, but is just an alias for `AutoField`."
] | 2018-05-21T21:33:45 | 2018-05-22T00:57:52 | 2018-05-22T00:57:52 | NONE | null | If I do
```python
dbo, created = Plate.get_or_create(plate_id=1234)
if created is True:
dbo.chunk = 'a'
dbo.save()
```
O get an error
```python
IntegrityError: duplicate key value violates unique constraint "plate_id_uniq"
DETAIL: Key (plate_id)=(1234) already exists
```
This seems to happen because the `.save()` method tries to create the record again, instead of updating it. This code used to work with peewee 2.
| {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1610/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/1610/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1609 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1609/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1609/comments | https://api.github.com/repos/coleifer/peewee/issues/1609/events | https://github.com/coleifer/peewee/issues/1609 | 325,038,699 | MDU6SXNzdWUzMjUwMzg2OTk= | 1,609 | MySQL Error 1093 on recursive instance deletion | {
"login": "timlehr",
"id": 5310859,
"node_id": "MDQ6VXNlcjUzMTA4NTk=",
"avatar_url": "https://avatars.githubusercontent.com/u/5310859?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/timlehr",
"html_url": "https://github.com/timlehr",
"followers_url": "https://api.github.com/users/timlehr/followers",
"following_url": "https://api.github.com/users/timlehr/following{/other_user}",
"gists_url": "https://api.github.com/users/timlehr/gists{/gist_id}",
"starred_url": "https://api.github.com/users/timlehr/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/timlehr/subscriptions",
"organizations_url": "https://api.github.com/users/timlehr/orgs",
"repos_url": "https://api.github.com/users/timlehr/repos",
"events_url": "https://api.github.com/users/timlehr/events{/privacy}",
"received_events_url": "https://api.github.com/users/timlehr/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"From the MySQL [update docs](https://dev.mysql.com/doc/refman/8.0/en/update.html):\r\n\r\n> You cannot update a table and select from the same table in a subquery.\r\n\r\nSee also [delete docs](https://dev.mysql.com/doc/refman/8.0/en/delete.html#idm139870165521360).\r\n\r\nThis appears to be a MySQL limitation. You can try to work around it in your code, but for now Peewee does not implement a workaround for this specific issue.",
"Hi Charles,\r\n\r\nYeah, I was worried that would be the case.\r\nAny suggestions on how I could tackle this? Any function in the model I could re-implement to make it work? \r\n\r\nThe [fixes suggested on stackoverflow](https://stackoverflow.com/a/44971214/9288624) seem easy enough, but Idon't have enough insight into peewee yet to know where to start.\r\n\r\nThank you for the quick reply by the way!\r\nYour support for this project is outstanding.",
"I didn't realize it was possible to even do the above...one would think that the MySQL query engine would be able to rewrite the problematic query as a selection from a derived table. Alas.\r\n\r\nFor starters, peewee `Model` does expose a `dependencies` method, which yields 2-tuples of the form `(query, foreign-key)` and provides access to all dependent objects. You could look into the code there for some ideas on how to resolve dependencies. Another option which may or may-not work is to use a common table expression (requires newer mariadb / mysql 8 if I recall correctly).\r\n\r\nWithout really getting into the nitty-gritty I can't be more specific right now.",
"Alright, thank you. Would be fantastic if an official solution would find it's way into Peewee in the future. Meanwhile I will have a closer look into the `dependencies` method. CTEs are no option for me unfortunately (because of the new requirements). If I find a suitable, generic workaround I'll post it here. \r\n",
"An alternative might be to simply specify your foreign-keys as \"ON DELETE CASCADE\" and then just delete the parent row (or \"ON DELETE SET NULL\" as the case may be). The ForeignKeyField() accepts \"on_delete\" and \"on_update\" parameters, e.g.\r\n\r\n```python\r\nfk_field = ForeignKeyField(SomeModel, on_delete='CASCADE')\r\n```"
] | 2018-05-21T19:54:09 | 2018-05-21T21:44:54 | 2018-05-21T21:44:54 | NONE | null | Hi Charles,
I'm using the recursive delete instance functionality of peewee quite a bit and so far it always worked out quite well. However, I recently added a self-referencing FK to one of my models `File`:
`_source_file = ForeignKeyField(column_name="sourcefile", model='self', null=True, field='dbid')`
I'm accessing / using that field via a `hybrid_property`, as I do with most of my fields. Now when I'm deleting a model that is an dependency to File, MySQL stops with the following error:
> InternalError: (1093, u"Table 'File' is specified twice, both as a target for 'UPDATE' and as a separate source for data")
I found a couple of suggestions on the web on how to fix the query, but since it's created automatically by peewee for me (awesome!), there is not much I can do. I hope I attached enough information for you to take a look at this.
Thank you!
Cheers,
Tim
### Log
> ('DELETE FROM `FileDependency` WHERE (`File_dbid` IN (SELECT `t1`.`dbid` FROM `File` AS `t1` WHERE (`t1`.`Version_dbid` IN (SELECT `t2`.`dbid` FROM `Version` AS `t2` WHERE (`t2`.`Variant_dbid` IN (SELECT `t3`.`dbid` FROM `Variant` AS `t3` WHERE (`t3`.`Task_dbid` IN (SELECT `t4`.`dbid` FROM `Task` AS `t4` WHERE (`t4`.`Asset_dbid` IN (SELECT `t5`.`dbid` FROM `Asset` AS `t5` WHERE (`t5`.`Category_dbid` IN (SELECT `t6`.`dbid` FROM `Category` AS `t6` WHERE (`t6`.`dbid` = %s)))))))))))))', [40])
> ('DELETE FROM `FileDependency` WHERE (`dependency_dbid` IN (SELECT `t1`.`dbid` FROM `File` AS `t1` WHERE (`t1`.`Version_dbid` IN (SELECT `t2`.`dbid` FROM `Version` AS `t2` WHERE (`t2`.`Variant_dbid` IN (SELECT `t3`.`dbid` FROM `Variant` AS `t3` WHERE (`t3`.`Task_dbid` IN (SELECT `t4`.`dbid` FROM `Task` AS `t4` WHERE (`t4`.`Asset_dbid` IN (SELECT `t5`.`dbid` FROM `Asset` AS `t5` WHERE (`t5`.`Category_dbid` IN (SELECT `t6`.`dbid` FROM `Category` AS `t6` WHERE (`t6`.`dbid` = %s)))))))))))))', [40])
> ('UPDATE `File` SET `sourcefile` = %s WHERE (`sourcefile` IN (SELECT `File`.`dbid` FROM `File` AS `File` WHERE (`File`.`Version_dbid` IN (SELECT `t1`.`dbid` FROM `Version` AS `t1` WHERE (`t1`.`Variant_dbid` IN (SELECT `t2`.`dbid` FROM `Variant` AS `t2` WHERE (`t2`.`Task_dbid` IN (SELECT `t3`.`dbid` FROM `Task` AS `t3` WHERE (`t3`.`Asset_dbid` IN (SELECT `t4`.`dbid` FROM `Asset` AS `t4` WHERE (`t4`.`Category_dbid` IN (SELECT `t5`.`dbid` FROM `Category` AS `t5` WHERE (`t5`.`dbid` = %s)))))))))))))', [None, 40])
### Traceback
> File "/home/tim/dev-root/scarif-dev/scarif-db/src/scarif/db/models/dbbasemodel.py", line 70, in delete_instance
super(DBBaseModel, self).delete_instance(recursive, delete_nullable)
File "/home/tim/Scarif/projects/NewPro-SCivCsp/_python_env/lib/python2.7/site-packages/peewee.py", line 5407, in delete_instance
model.update(**{fk.name: None}).where(query).execute()
File "/home/tim/Scarif/projects/NewPro-SCivCsp/_python_env/lib/python2.7/site-packages/peewee.py", line 1522, in inner
return method(self, database, *args, **kwargs)
File "/home/tim/Scarif/projects/NewPro-SCivCsp/_python_env/lib/python2.7/site-packages/peewee.py", line 1593, in execute
return self._execute(database)
File "/home/tim/Scarif/projects/NewPro-SCivCsp/_python_env/lib/python2.7/site-packages/peewee.py", line 2014, in _execute
cursor = database.execute(self)
File "/home/tim/Scarif/projects/NewPro-SCivCsp/_python_env/lib/python2.7/site-packages/peewee.py", line 2589, in execute
return self.execute_sql(sql, params, commit=commit)
File "/home/tim/Scarif/projects/NewPro-SCivCsp/_python_env/lib/python2.7/site-packages/peewee.py", line 2583, in execute_sql
self.commit()
File "/home/tim/Scarif/projects/NewPro-SCivCsp/_python_env/lib/python2.7/site-packages/peewee.py", line 2376, in __exit__
reraise(new_type, new_type(*exc_args), traceback)
File "/home/tim/Scarif/projects/NewPro-SCivCsp/_python_env/lib/python2.7/site-packages/peewee.py", line 2576, in execute_sql
cursor.execute(sql, params or ())
File "/home/tim/Scarif/projects/NewPro-SCivCsp/_python_env/lib/python2.7/site-packages/pymysql/cursors.py", line 165, in execute
result = self._query(query)
File "/home/tim/Scarif/projects/NewPro-SCivCsp/_python_env/lib/python2.7/site-packages/pymysql/cursors.py", line 321, in _query
conn.query(q)
File "/home/tim/Scarif/projects/NewPro-SCivCsp/_python_env/lib/python2.7/site-packages/pymysql/connections.py", line 860, in query
self._affected_rows = self._read_query_result(unbuffered=unbuffered)
File "/home/tim/Scarif/projects/NewPro-SCivCsp/_python_env/lib/python2.7/site-packages/pymysql/connections.py", line 1061, in _read_query_result
result.read()
File "/home/tim/Scarif/projects/NewPro-SCivCsp/_python_env/lib/python2.7/site-packages/pymysql/connections.py", line 1349, in read
first_packet = self.connection._read_packet()
File "/home/tim/Scarif/projects/NewPro-SCivCsp/_python_env/lib/python2.7/site-packages/pymysql/connections.py", line 1018, in _read_packet
packet.check_error()
File "/home/tim/Scarif/projects/NewPro-SCivCsp/_python_env/lib/python2.7/site-packages/pymysql/connections.py", line 384, in check_error
err.raise_mysql_exception(self._data)
File "/home/tim/Scarif/projects/NewPro-SCivCsp/_python_env/lib/python2.7/site-packages/pymysql/err.py", line 107, in raise_mysql_exception
raise errorclass(errno, errval)
InternalError: (1093, u"Table 'File' is specified twice, both as a target for 'UPDATE' and as a separate source for data") | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1609/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/1609/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1608 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1608/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1608/comments | https://api.github.com/repos/coleifer/peewee/issues/1608/events | https://github.com/coleifer/peewee/issues/1608 | 324,648,958 | MDU6SXNzdWUzMjQ2NDg5NTg= | 1,608 | Can't add parameters for DecimalField used in ArrayField (peewee 2.10.2) | {
"login": "ssrebelious",
"id": 2326764,
"node_id": "MDQ6VXNlcjIzMjY3NjQ=",
"avatar_url": "https://avatars.githubusercontent.com/u/2326764?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/ssrebelious",
"html_url": "https://github.com/ssrebelious",
"followers_url": "https://api.github.com/users/ssrebelious/followers",
"following_url": "https://api.github.com/users/ssrebelious/following{/other_user}",
"gists_url": "https://api.github.com/users/ssrebelious/gists{/gist_id}",
"starred_url": "https://api.github.com/users/ssrebelious/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/ssrebelious/subscriptions",
"organizations_url": "https://api.github.com/users/ssrebelious/orgs",
"repos_url": "https://api.github.com/users/ssrebelious/repos",
"events_url": "https://api.github.com/users/ssrebelious/events{/privacy}",
"received_events_url": "https://api.github.com/users/ssrebelious/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"That's a nice workaround but I'll see what I can do to offer better support.",
"This fix will be in the 3.4.0 release. If you plan to continue using 2.10 then the subclassing solution is totally fine."
] | 2018-05-19T18:09:24 | 2018-05-20T03:52:49 | 2018-05-20T03:48:20 | NONE | null | I have a model where I need to define custom parameters for DecimalField that is used inside ArrayField:
```python
class Pricing(Model):
base_cost = ArrayField(
DecimalField,
max_digits=16,
decimal_places=2,
help_text='Base cost',
null=False
)
class Meta:
database = postgres_db
```
This results in error telling me that `max_digits` and `decimal_places` are not supported parameters for `ArrayField`. I took a quick peek into `ArrayField` class and I guess that the `__init__` method might be an issue: *args and **kwargs are passed as parameters to `self.__field = field_class(*args, **kwargs)` and `super(ArrayField, self).__init__(*args, **kwargs)`.
As a workaround I could subclass `DecimalFiled` with required parameters and pass it to `ArrayField`. Is there another way? | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1608/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/1608/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1607 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1607/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1607/comments | https://api.github.com/repos/coleifer/peewee/issues/1607/events | https://github.com/coleifer/peewee/issues/1607 | 324,349,299 | MDU6SXNzdWUzMjQzNDkyOTk= | 1,607 | [Feature Request] iregex support | {
"login": "wonderbeyond",
"id": 228361,
"node_id": "MDQ6VXNlcjIyODM2MQ==",
"avatar_url": "https://avatars.githubusercontent.com/u/228361?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/wonderbeyond",
"html_url": "https://github.com/wonderbeyond",
"followers_url": "https://api.github.com/users/wonderbeyond/followers",
"following_url": "https://api.github.com/users/wonderbeyond/following{/other_user}",
"gists_url": "https://api.github.com/users/wonderbeyond/gists{/gist_id}",
"starred_url": "https://api.github.com/users/wonderbeyond/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/wonderbeyond/subscriptions",
"organizations_url": "https://api.github.com/users/wonderbeyond/orgs",
"repos_url": "https://api.github.com/users/wonderbeyond/repos",
"events_url": "https://api.github.com/users/wonderbeyond/events{/privacy}",
"received_events_url": "https://api.github.com/users/wonderbeyond/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"Peewee supports a regexp operator. Depending on the database you're using, you can utilize the db-specific features to handle case-sensitivity.",
"Added support for MySQL and Postgresql. SQLite is going to be trickier and I may not implement it.\r\n\r\nSee: f631f222fe6b0c5cb68de99dede98d03454d3e3f"
] | 2018-05-18T10:07:54 | 2018-05-18T16:53:43 | 2018-05-18T14:02:11 | NONE | null | See https://docs.djangoproject.com/zh-hans/2.0/ref/models/querysets/#iregex | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1607/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/1607/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1606 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1606/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1606/comments | https://api.github.com/repos/coleifer/peewee/issues/1606/events | https://github.com/coleifer/peewee/issues/1606 | 324,109,514 | MDU6SXNzdWUzMjQxMDk1MTQ= | 1,606 | Help: AttributeError: when select with more than one join | {
"login": "eguzmanf",
"id": 13544743,
"node_id": "MDQ6VXNlcjEzNTQ0NzQz",
"avatar_url": "https://avatars.githubusercontent.com/u/13544743?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/eguzmanf",
"html_url": "https://github.com/eguzmanf",
"followers_url": "https://api.github.com/users/eguzmanf/followers",
"following_url": "https://api.github.com/users/eguzmanf/following{/other_user}",
"gists_url": "https://api.github.com/users/eguzmanf/gists{/gist_id}",
"starred_url": "https://api.github.com/users/eguzmanf/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/eguzmanf/subscriptions",
"organizations_url": "https://api.github.com/users/eguzmanf/orgs",
"repos_url": "https://api.github.com/users/eguzmanf/repos",
"events_url": "https://api.github.com/users/eguzmanf/events{/privacy}",
"received_events_url": "https://api.github.com/users/eguzmanf/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"Since you don't appear to have actual foreign-keys, you'll need to tell peewee how to reconstruct the model graph by providing aliases in your join predicates:\r\n\r\n```python\r\n .join(age, pw.JOIN.LEFT_OUTER, on=(cit.AGE_ID == age.AGE_ID).alias('agecitas'))\r\n .join(per, pw.JOIN.LEFT_OUTER, on=(age.PER_ID == per.PER_ID).alias('sktpersona'))\r\n```\r\n\r\nAlso one look at the tests should have revealed that this logic is tested thoroughly in peewee. Meaning you have a bug in your code rather than a bug in peewee.\r\n\r\nFor that you need to use StackOverflow or you can try `#peewee` on freenode IRC. This is not a troubleshooting support site.",
"Ok Thanks, I will ask on StackOverflow",
"For what it's worth, I *did* answer your question."
] | 2018-05-17T17:06:16 | 2018-05-18T14:16:12 | 2018-05-17T19:12:28 | NONE | null | **Hi Friends,
I needs help please, I'm getting the following error when try a select with join:**
(work) C:\Users\eguzman\Documents\python-work\asterisk-insert-reminder>python script.py
Traceback (most recent call last):
File "script.py", line 41, in <module>
row.ageagendas.CODIGO, row.ageagendas.PER_ID, row.stkpersonas.DOCUMENTO))
AttributeError: 'AgeCitas' object has no attribute 'stkpersonas'
The code: **script.py**
**-----------------------------------------------------------------------------------------------------**
```python
import peewee as pw
from classes.model import MySqlDbModel, AgeCitas, AgeAgendas, StkPersonas
class SelectCitasToRemind(MySqlDbModel):
@staticmethod
def selectCitasToRemind():
cit = AgeCitas.alias()
age = AgeAgendas.alias()
per = StkPersonas.alias()
query = (cit.select(
cit.CIT_ID, cit.AGE_ID, cit.FECHAHORA,
age.AGE_ID, age.CODIGO, age.CEN_ID, age.PER_ID,
per.PER_ID, per.DOCUMENTO, per.NOMBRE)
.join(age, pw.JOIN.LEFT_OUTER, on=(cit.AGE_ID == age.AGE_ID))
.join(per, pw.JOIN.LEFT_OUTER, on=(age.PER_ID == per.PER_ID))
.where((cit.CIT_ID.is_null(False))
& (cit.PAC_ID.is_null(False))
)
.limit(10)
)
return query
query = SelectCitasToRemind.selectCitasToRemind()
for row in query:
print("{} | {} | {} | {} | {} | {}".format(
row.CIT_ID, row.AGE_ID, row.FECHAHORA,
row.ageagendas.CODIGO, row.ageagendas.PER_ID, row.stkpersonas.DOCUMENTO))
```
The code: **classes/model.py**
**-----------------------------------------------------------------------------------------------------**
```python
import peewee as pw
# Conection to mydbname database
dbn = 'mydbname'
user = 'myusername'
pwd = '******'
host = 'localhost'
prt = 3306
db = pw.MySQLDatabase(dbn, user=user,
password=pwd, host=host, port=prt)
class MySqlDbModel(pw.Model):
class Meta:
database = db
class AgeCitas(MySqlDbModel):
CIT_ID = pw.BigIntegerField()
AGE_ID = pw.BigIntegerField()
FECHAHORA = pw.DateTimeField()
ACT_ID = pw.BigIntegerField()
PAC_ID = pw.BigIntegerField()
ASIGNADA = pw.CharField()
IND_ID = pw.BigIntegerField()
ACUDIO = pw.DoubleField()
ORDEN = pw.DoubleField()
class Meta:
table_name = 'AGE_CITAS'
class AgeAgendas(MySqlDbModel):
AGE_ID = pw.DecimalField()
CODIGO = pw.CharField()
CEN_ID = pw.DecimalField()
PER_ID = pw.DecimalField()
NPR_ID = pw.DecimalField()
DESCRIPCION = pw.CharField()
COLOR = pw.CharField()
class Meta:
table_name = 'AGE_AGENDAS'
class StkPersonas(MySqlDbModel):
PER_ID = pw.BigIntegerField()
DOCUMENTO = pw.CharField()
NOMBRE = pw.CharField()
APELLIDO1 = pw.CharField()
APELLIDO2 = pw.CharField()
FECHA_ALTA = pw.DateTimeField()
FECHA_BAJA = pw.DateTimeField()
EMAIL = pw.CharField()
TELEFONO1 = pw.CharField()
TELEFONO2 = pw.CharField()
TELEFONO3 = pw.CharField()
TELEFONO4 = pw.CharField()
SEXO = pw.CharField()
NACIMIENTO = pw.DateTimeField()
ES_PACIENTE = pw.CharField()
ES_PROFESIONAL = pw.CharField()
class Meta:
table_name = 'STK_PERSONAS'
``` | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1606/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/1606/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1605 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1605/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1605/comments | https://api.github.com/repos/coleifer/peewee/issues/1605/events | https://github.com/coleifer/peewee/issues/1605 | 322,984,836 | MDU6SXNzdWUzMjI5ODQ4MzY= | 1,605 | Get untouched database field values | {
"login": "timlehr",
"id": 5310859,
"node_id": "MDQ6VXNlcjUzMTA4NTk=",
"avatar_url": "https://avatars.githubusercontent.com/u/5310859?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/timlehr",
"html_url": "https://github.com/timlehr",
"followers_url": "https://api.github.com/users/timlehr/followers",
"following_url": "https://api.github.com/users/timlehr/following{/other_user}",
"gists_url": "https://api.github.com/users/timlehr/gists{/gist_id}",
"starred_url": "https://api.github.com/users/timlehr/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/timlehr/subscriptions",
"organizations_url": "https://api.github.com/users/timlehr/orgs",
"repos_url": "https://api.github.com/users/timlehr/repos",
"events_url": "https://api.github.com/users/timlehr/events{/privacy}",
"received_events_url": "https://api.github.com/users/timlehr/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"That is the purpose of `dirty_fields`. For your use-case I'd suggest putting an interface on-top of your model instance and routing accesses through that. In that way you can track changes."
] | 2018-05-14T21:17:06 | 2018-05-14T21:29:08 | 2018-05-14T21:29:08 | NONE | null | Hi Charles,
in Peewee 2 I was using the `prepared()` function to store the initial field values selected from the DB in a dictionary, so I could compare it with `__data__` at any time to determine if changes have been made. I know that the dirty field is supposed to offer this functionality, but using the dirty flags, I can not determine if the user has undone his changes. Since `prepared()` is gone in version 3, I'm struggling to find a function for my subclasses to do the same thing again. Any suggestions on this matter?
Best,
Tim | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1605/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/1605/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1604 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1604/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1604/comments | https://api.github.com/repos/coleifer/peewee/issues/1604/events | https://github.com/coleifer/peewee/issues/1604 | 322,869,341 | MDU6SXNzdWUzMjI4NjkzNDE= | 1,604 | "KeyError: None" when using JOIN and aggregate_rows in 2.10.2 | {
"login": "eely22",
"id": 4094985,
"node_id": "MDQ6VXNlcjQwOTQ5ODU=",
"avatar_url": "https://avatars.githubusercontent.com/u/4094985?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/eely22",
"html_url": "https://github.com/eely22",
"followers_url": "https://api.github.com/users/eely22/followers",
"following_url": "https://api.github.com/users/eely22/following{/other_user}",
"gists_url": "https://api.github.com/users/eely22/gists{/gist_id}",
"starred_url": "https://api.github.com/users/eely22/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/eely22/subscriptions",
"organizations_url": "https://api.github.com/users/eely22/orgs",
"repos_url": "https://api.github.com/users/eely22/repos",
"events_url": "https://api.github.com/users/eely22/events{/privacy}",
"received_events_url": "https://api.github.com/users/eely22/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"Peewee 3.x removed `aggregate_rows` because it was, in retrospect, a poorly-designed hack. The concept, roughly, was to produce a cartesian product of all the requested data and then de-duplicate it on the Python side. It's slow (because Python), expensive (because amount of bits being xferred) and buggy (because I never trusted it enough to start using it in production).\r\n\r\nFor the trivial use-case it works fine (users and tweets). I should not have included it as a public API, though, and that mistake has been corrected in 3.x.\r\n\r\nI'm not planning to implement any fixes for APIs that were deprecated in 3.x, unfortunately I just don't have either the time or the interest. I'm sorry that this bug is occurring, though, and would be happy to help you come up with an alternate way to implement what you're trying to do.",
"We are currently refactoring to use prefetch instead. However, I am struggling a bit to understand how it can replace certain parts of joining, such as ordering. So, for example, if I started with a query like this:\r\n```\r\nrecords = A\\\r\n .select(A, B, C)\\\r\n .join(B, JOIN_LEFT_OUTER)\\\r\n .join(C, JOIN_LEFT_OUTER)\\\r\n .order_by(C.val)\\\r\n .aggregate_rows()\r\n```\r\n\r\nI would end up with a list of A objects ordered by some value in C, which is what I want. \r\n\r\nHow would I do the same with prefetch? If I did this:\r\n\r\n```\r\nrecords = prefetch(A.select(), B, C.select().order_by(C.val))\r\n```\r\n\r\nI don't end up what I want, the list of A objects is ordered by A's primary key. \r\n\r\nI suppose I could order the list in python after I have fetched everything, but the database can do this for me and is more efficient. \r\n\r\nThis can also apply to filtering results, so something like this:\r\n\r\n```\r\nrecords = A\\\r\n .select(A, B, C)\\\r\n .join(B, JOIN_LEFT_OUTER)\\\r\n .join(C, JOIN_LEFT_OUTER)\\\r\n .where(C.val < 100)\\\r\n .aggregate_rows()\r\n```\r\n\r\nIt is the same type of issue. I want a list of A objects filtered by some value from C. Again, I suppose I can filter in python. Or I could select the C objects I want and map it backwards, so like this:\r\n\r\n```\r\nprefetch(C.select().where(C.val < 100), B, A) \r\n```\r\n\r\nBut now I have a list of C objects and have to reverse my logic, which is unintuitive.\r\n\r\nIs there any way to replicate the join behavior with prefetch? It uses subqueries, so I don't see how to do this. Or is there some other way I am not seeing? I am looking in the docs but can't seem to find any examples, so if you can point me to some, that would be appreciated.",
"So the thing is, you can actually just write:\r\n\r\n```python\r\nquery = (A\r\n .select(A, B, C)\r\n .join(B, JOIN.LEFT_OUTER)\r\n .join(C, JOIN.LEFT_OUTER)\r\n .order_by(C.val))\r\nfor a in query:\r\n if a.b is None:\r\n # just an a\r\n elif a.b.c is None:\r\n # A and b, but no c\r\n else:\r\n # a b and c\r\n```\r\n\r\nThe only thing is you'll get duplicate a's and b's potentially. All `aggregate_rows()` did was try to \"roll up\" the duplicates, but depending on you use-case you can handle it yourself.",
"As far as using `prefetch()`, you can also:\r\n\r\n```python\r\na_s = (A\r\n .select()\r\n .join(B, JOIN.LEFT_OUTER)\r\n .join(C, JOIN.LEFT_OUTER)\r\n .order_by(C.val))\r\nall_together = prefetch(a_s, B, C)\r\n```",
"I see where you are going with this. The second answer sets off alarm bells in terms of efficiency as it is now doing multiple joins AND multiple subqueries. We have some more complex scenarios so we will need to profile this.\r\n\r\nAs for the first answer, again, we have some more complex queries then listed here, which could create a lot deeper nested logic. Something we will have to look at.\r\n\r\nI get that the aggregate_rows isn't so efficient, but our workload is generally based on serverless computing. So we have infinite compute resources (so to speak), but the bottleneck is always the database. We try to offload as much as we can from the database, which is why aggregate_rows worked well for us. \r\n\r\nEither way, we have some options to stop using aggregate_rows. Perhaps we would also look into fixing the function to suit our purposes, we shall see.",
"Combining something like the first approach, which contains duplicate rows, with [itertools.groupby](https://docs.python.org/2/library/itertools.html#itertools.groupby) should allow you to emulate what aggregate_rows() was doing.",
"Just to clarify, you expect the second approach to also have duplicate A records, correct? So with either approach we will need to dedupe.",
"`prefetch` won't return duplicates, but it is structured differently.",
"prefetch won't, but the first query is a join, which will. I just tried it with my above example and saw it returned two objects even though there is only one A in the database.\r\n\r\nUnless I am missing something?",
"If you're comfortable with SQL, I'd suggest running the query with the joins in a sql shell and observing the way the columns are represented (and duplicated).",
"I am comfortable SQL, and I did run the query. I understand how the columns are all represented. I guess my comment was that peewee is still returning me duplicate A objects, and I thought that you had indicated that maybe it would not. So I was trying to fish for a solution where I did not have to explicitly deduplicate in this scenario. I would honestly expect peewee to return me duplicate A objects, but thought your response indicated it would not. But maybe I just misunderstood your answer?",
"> peewee is still returning me duplicate A objects\r\n\r\nExactly. All `aggregate_rows()` did was to roll up the duplicates and accumulate joined rows as related instances. That's why I suggested using something like `itertools.groupby`.",
"For anyone who stumbles upon this, here is how we ultimately solved the issue:\r\n\r\n```\r\na_s = (A\r\n .select()\r\n .join(B, JOIN.LEFT_OUTER)\r\n .join(C, JOIN.LEFT_OUTER)\r\n .order_by(C.val))\r\n .group_by(A.id)\r\nall_together = prefetch(a_s, B, C)\r\n```\r\n\r\nAllows us to order A by joined tables, but we dedupe by grouping on A's primary key. Then we prefetch the other values through subqueries. So no duplicate A objects, and all other fields are prefetched. \r\n\r\nPerformance can still be a concern as you are now joining multiple tables, grouping, and then running subqueries on top of that, so your mileage may vary depending on your situation. "
] | 2018-05-14T15:33:22 | 2018-05-16T16:20:55 | 2018-05-16T16:20:55 | NONE | null | There is a case where using joins and aggregate_rows is causing uncaught exceptions. The example seems to be related to joining tables through a junction table, where there are two tables A and C and another B that joins the two together. B has two rows, both pointing to the same A. The two B records have one with a C object and the other with a null C. Similar to this:
```
B - C
/
A
\
B - NULL
```
When attempting to join and aggregate the rows, we see the following stack trace:
```
Error
Traceback (most recent call last):
File "/Users/ericely/workspace/test/test_peewee.py", line 48, in test_peewee
print len(records)
File "/Users/ericely/workspace/env/lib/python2.7/site-packages/peewee.py", line 3298, in __len__
return len(self.execute())
File "/Users/ericely/workspace/env/lib/python2.7/site-packages/peewee.py", line 2334, in __len__
return self.count
File "/Users/ericely/workspace/env/lib/python2.7/site-packages/peewee.py", line 2330, in count
self.fill_cache()
File "/Users/ericely/workspace/env/lib/python2.7/site-packages/peewee.py", line 2377, in fill_cache
next(self)
File "/Users/ericely/workspace/env/lib/python2.7/site-packages/peewee.py", line 2363, in next
obj = self.iterate()
File "/Users/ericely/workspace/env/lib/python2.7/site-packages/peewee.py", line 2761, in iterate
instance._data[metadata.foreign_key.name]]
KeyError: None
```
The code to generate this is:
```
import unittest
from peewee import *
db = SqliteDatabase(':memory:')
# create a base model class that our application's models will extend
class BaseModel(Model):
class Meta:
database = db
class A(BaseModel):
val = FloatField(default=3.14)
class C(BaseModel):
val = IntegerField(default=42)
class B(BaseModel):
a = ForeignKeyField(A, null=True, default=None)
c = ForeignKeyField(C, null=True, default=None)
class Osha_Violation_Model_Tests(unittest.TestCase):
def test_peewee(self):
A.create_table()
B.create_table()
C.create_table()
# save the first record chain
A().save(force_insert=True)
a = A.get(A.id == 1)
C().save(force_insert=True)
c = C.get(C.id == 1)
B(a=a, c=c).save(force_insert=True)
# save the second record chain, starting with the same A, without a C link
a = A.get(A.id == 1)
B(a=a).save(force_insert=True)
records = A\
.select(A, B, C)\
.join(B, JOIN_LEFT_OUTER)\
.join(C, JOIN_LEFT_OUTER)\
.aggregate_rows()
print len(records)
```
This is peewee 2.10.2. Even though 2.10.2 isn't the latest release, we are still using it since 3.X has some breaking backward changes. I know aggregate_rows was removed in 3.X and prefetch is now recommended, but we still have a relatively large codebase on 2.10.2. | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1604/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/1604/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1603 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1603/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1603/comments | https://api.github.com/repos/coleifer/peewee/issues/1603/events | https://github.com/coleifer/peewee/issues/1603 | 322,192,087 | MDU6SXNzdWUzMjIxOTIwODc= | 1,603 | why not model.DoesNotExist inherite form Exception? | {
"login": "xvdy",
"id": 12590255,
"node_id": "MDQ6VXNlcjEyNTkwMjU1",
"avatar_url": "https://avatars.githubusercontent.com/u/12590255?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/xvdy",
"html_url": "https://github.com/xvdy",
"followers_url": "https://api.github.com/users/xvdy/followers",
"following_url": "https://api.github.com/users/xvdy/following{/other_user}",
"gists_url": "https://api.github.com/users/xvdy/gists{/gist_id}",
"starred_url": "https://api.github.com/users/xvdy/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/xvdy/subscriptions",
"organizations_url": "https://api.github.com/users/xvdy/orgs",
"repos_url": "https://api.github.com/users/xvdy/repos",
"events_url": "https://api.github.com/users/xvdy/events{/privacy}",
"received_events_url": "https://api.github.com/users/xvdy/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"`DoesNotExist` is not an instance but a class:\r\n\r\n```python\r\nisinstance(Model.DoesNotExist, Exception) -- False\r\nissubclass(Model.DoesNotExist, Exception) -- True\r\n```\r\n\r\nYou catch it like this:\r\n\r\n```python\r\ntry:\r\n obj = SomeModel.get(SomeModel.field == 'value')\r\nexcept SomeModel.DoesNotExist:\r\n print('obj with field=value does not exist')\r\n```"
] | 2018-05-11T07:12:06 | 2018-05-11T15:34:10 | 2018-05-11T15:34:10 | NONE | null | ```
@asyncio.coroutine
def get(self, source_, *args, **kwargs):
"""Get the model instance.
:param source_: model or base query for lookup
Example::
async def my_async_func():
obj1 = await objects.get(MyModel, id=1)
obj2 = await objects.get(MyModel, MyModel.id == 1)
obj3 = await objects.get(MyModel.select().where(MyModel.id == 1))
All will return `MyModel` instance with `id = 1`
"""
yield from self.connect()
if isinstance(source_, peewee.Query):
query = source_
model = query.model_class
else:
query = source_.select()
model = source_
conditions = list(args) + [(getattr(model, k) == v)
for k, v in kwargs.items()]
if conditions:
query = query.where(*conditions)
try:
result = yield from self.execute(query)
return list(result)[0]
except IndexError:
print(type(model.DoesNotExist))
print(type(Exception))
print(isinstance(model.DoesNotExist, Exception))
raise model.DoesNotExist
```
print(isinstance(model.DoesNotExist, Exception)) # False | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1603/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/1603/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1602 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1602/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1602/comments | https://api.github.com/repos/coleifer/peewee/issues/1602/events | https://github.com/coleifer/peewee/issues/1602 | 321,744,944 | MDU6SXNzdWUzMjE3NDQ5NDQ= | 1,602 | Alias fields gets lost when doing union | {
"login": "kwellman",
"id": 279549,
"node_id": "MDQ6VXNlcjI3OTU0OQ==",
"avatar_url": "https://avatars.githubusercontent.com/u/279549?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/kwellman",
"html_url": "https://github.com/kwellman",
"followers_url": "https://api.github.com/users/kwellman/followers",
"following_url": "https://api.github.com/users/kwellman/following{/other_user}",
"gists_url": "https://api.github.com/users/kwellman/gists{/gist_id}",
"starred_url": "https://api.github.com/users/kwellman/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/kwellman/subscriptions",
"organizations_url": "https://api.github.com/users/kwellman/orgs",
"repos_url": "https://api.github.com/users/kwellman/repos",
"events_url": "https://api.github.com/users/kwellman/events{/privacy}",
"received_events_url": "https://api.github.com/users/kwellman/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"I added a test-case that I think is equivalent to your example. It is passing for me: 909b371123a73ea00b7db18bbdb870083286d603\r\n\r\nHere's the test-case code:\r\n\r\n```python\r\n def test_union_with_join(self):\r\n u1, u2 = [User.create(username='u%s' % i) for i in (1, 2)]\r\n for u, ts in ((u1, ('t1', 't2')), (u2, ('t1',))):\r\n for t in ts:\r\n Tweet.create(user=u, content='%s-%s' % (u.username, t))\r\n\r\n q1 = (User\r\n .select(User, Tweet)\r\n .join(Tweet, on=(Tweet.user == User.id).alias('tweet')))\r\n q2 = (User\r\n .select(User, Tweet)\r\n .join(Tweet, on=(Tweet.user == User.id).alias('tweet')))\r\n\r\n with self.assertQueryCount(1):\r\n self.assertEqual(\r\n sorted([(user.username, user.tweet.content) for user in q1]),\r\n [('u1', 'u1-t1'), ('u1', 'u1-t2'), ('u2', 'u2-t1')])\r\n\r\n uq = q1.union_all(q2)\r\n with self.assertQueryCount(1):\r\n result = [(user.username, user.tweet.content) for user in uq]\r\n self.assertEqual(sorted(result), [\r\n ('u1', 'u1-t1'),\r\n ('u1', 'u1-t1'),\r\n ('u1', 'u1-t2'),\r\n ('u1', 'u1-t2'),\r\n ('u2', 'u2-t1'),\r\n ('u2', 'u2-t1'),\r\n ])\r\n```\r\n\r\nAm I missing something?",
"Travis-CI build including the above patch: https://travis-ci.org/coleifer/peewee/builds/377071024 (passed)",
"Sorry. I feel really stupid for not checking which peewee version I was using. \r\n\r\nI just upgraded to the latest from peewee version 3.2.3 and it works. \r\n\r\nYep...I'm an idiot.",
"No need to apologize, this was fixed only recently."
] | 2018-05-09T22:15:28 | 2018-05-10T13:55:56 | 2018-05-10T00:11:13 | NONE | null | I wrote a little test to show my problem:
```python
from peewee import Model, SqliteDatabase, CharField, ForeignKeyField
database = SqliteDatabase(':memory:')
class BaseModel(Model):
class Meta:
database = database
class Tournament(BaseModel):
name = CharField()
class Result(BaseModel):
tournament = ForeignKeyField(Tournament)
database.create_tables([Tournament, Result])
t = Tournament.create(name='Tournament1')
Result.create(tournament=t)
q1 = Tournament.select(Tournament, Result).join(Result, on=(Result.tournament==Tournament.id).alias('result'))
q2 = Tournament.select(Tournament, Result).join(Result, on=(Result.tournament==Tournament.id).alias('result'))
# this works fine
for tournament in q1:
print tournament.result
# this works fine
for tournament in q2:
print tournament.result
# raises "AttributeError: 'Tournament' object has no attribute 'result'"
for tournament in (q1+q2):
print tournament.result
```
I want to run a union of two queries that each have a join that results in a new field that holds the joined row. Unfortunately the queries are not returning the new field when I do a union but it works fine running the queries separately. Is this a bug?
Thanks | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1602/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/1602/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1601 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1601/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1601/comments | https://api.github.com/repos/coleifer/peewee/issues/1601/events | https://github.com/coleifer/peewee/issues/1601 | 321,073,619 | MDU6SXNzdWUzMjEwNzM2MTk= | 1,601 | flask_utils fails to import if libsqlite3 or sqlite-devel is not installed | {
"login": "bmamouri",
"id": 6419173,
"node_id": "MDQ6VXNlcjY0MTkxNzM=",
"avatar_url": "https://avatars.githubusercontent.com/u/6419173?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/bmamouri",
"html_url": "https://github.com/bmamouri",
"followers_url": "https://api.github.com/users/bmamouri/followers",
"following_url": "https://api.github.com/users/bmamouri/following{/other_user}",
"gists_url": "https://api.github.com/users/bmamouri/gists{/gist_id}",
"starred_url": "https://api.github.com/users/bmamouri/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/bmamouri/subscriptions",
"organizations_url": "https://api.github.com/users/bmamouri/orgs",
"repos_url": "https://api.github.com/users/bmamouri/repos",
"events_url": "https://api.github.com/users/bmamouri/events{/privacy}",
"received_events_url": "https://api.github.com/users/bmamouri/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"Oops, just realized the problem is already fixed in the [latest version](https://github.com/coleifer/peewee/blob/master/playhouse/sqlite_ext.py#L47).\r\n\r\nPlease close the issue. Thanks"
] | 2018-05-08T07:31:01 | 2018-05-08T07:35:36 | 2018-05-08T07:35:35 | NONE | null | Similar issue in the past: https://github.com/coleifer/peewee/issues/1218
I use PostgreSQL and my server does not have SQLite installed. When I want to import FlaskDB from flask_utils, I encounter the following issue:
```
File "/home/ubuntu/presentation/api/server.py", line 4, in <module>
from playhouse.flask_utils import FlaskDB
File "/home/ubuntu/.local/share/virtualenvs/api-eYDWRPCf/lib/python3.6/site-packages/playhouse/flask_utils.py", line 12, in <module>
from playhouse.db_url import connect as db_url_connect
File "/home/ubuntu/.local/share/virtualenvs/api-eYDWRPCf/lib/python3.6/site-packages/playhouse/db_url.py", line 9, in <module>
from playhouse.sqlite_ext import SqliteExtDatabase
File "/home/ubuntu/.local/share/virtualenvs/api-eYDWRPCf/lib/python3.6/site-packages/playhouse/sqlite_ext.py", line 74, in <module>
FTS_VER = sqlite3.sqlite_version_info[:3] >= (3, 7, 4) and 'FTS4' or 'FTS3'
```
The output of importing sqlite3:
```
ubuntu@REDACTED:~/wattcost/presentation/api$ python -m sqlite3
Traceback (most recent call last):
File "/home/ubuntu/.pyenv/versions/3.6.5/lib/python3.6/runpy.py", line 183, in _run_module_as_main
mod_name, mod_spec, code = _get_module_details(mod_name, _Error)
File "/home/ubuntu/.pyenv/versions/3.6.5/lib/python3.6/runpy.py", line 142, in _get_module_details
return _get_module_details(pkg_main_name, error)
File "/home/ubuntu/.pyenv/versions/3.6.5/lib/python3.6/runpy.py", line 109, in _get_module_details
__import__(pkg_name)
File "/home/ubuntu/.pyenv/versions/3.6.5/lib/python3.6/sqlite3/__init__.py", line 23, in <module>
from sqlite3.dbapi2 import *
File "/home/ubuntu/.pyenv/versions/3.6.5/lib/python3.6/sqlite3/dbapi2.py", line 27, in <module>
from _sqlite3 import *
ModuleNotFoundError: No module named '_sqlite3'
```
It seems the root cause of the issue is [here](https://github.com/coleifer/peewee/blob/master/peewee.py#L30):
```
try:
from pysqlite3 import dbapi2 as pysq3
except ImportError:
try:
from pysqlite2 import dbapi2 as pysq3
except ImportError:
pysq3 = None # <= What is causing the problem
try:
import sqlite3
except ImportError:
sqlite3 = pysq3
else:
if pysq3 and pysq3.sqlite_version_info >= sqlite3.sqlite_version_info:
sqlite3 = pysq3
```
One way to solve this problem would be to convert FTS_VER into a lambda function so it can be evaluated lazily. | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1601/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/1601/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1600 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1600/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1600/comments | https://api.github.com/repos/coleifer/peewee/issues/1600/events | https://github.com/coleifer/peewee/issues/1600 | 321,038,032 | MDU6SXNzdWUzMjEwMzgwMzI= | 1,600 | Request: forgetting to wrap comparisons in parentheses, or using the wrong operators should cause an error | {
"login": "robhawkins",
"id": 308934,
"node_id": "MDQ6VXNlcjMwODkzNA==",
"avatar_url": "https://avatars.githubusercontent.com/u/308934?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/robhawkins",
"html_url": "https://github.com/robhawkins",
"followers_url": "https://api.github.com/users/robhawkins/followers",
"following_url": "https://api.github.com/users/robhawkins/following{/other_user}",
"gists_url": "https://api.github.com/users/robhawkins/gists{/gist_id}",
"starred_url": "https://api.github.com/users/robhawkins/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/robhawkins/subscriptions",
"organizations_url": "https://api.github.com/users/robhawkins/orgs",
"repos_url": "https://api.github.com/users/robhawkins/repos",
"events_url": "https://api.github.com/users/robhawkins/events{/privacy}",
"received_events_url": "https://api.github.com/users/robhawkins/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"Sorry, there's not really any way to identify these kinds of mistakes. The documentation makes it abundantly clear that you're to use `&` and `|`, typically if you do make the mistake of using `and` and `or` you won't repeat it."
] | 2018-05-08T04:23:44 | 2018-05-08T13:35:31 | 2018-05-08T13:35:30 | NONE | null | Is it possible to throw an exception when someone writes a condition the wrong way in peewee?
I'm just getting to know this very useful tool. I used it for the first time a week ago, and then again today, and had forgotten to use `&` instead of `and` and also forgot to wrap the conditions in parentheses. This caused some unexpected results during testing and did not throw an error indicating the root cause of the issue.
Is it possible to identify such issues for the user? This cost me an extra 45 mins of development time and I wonder if that could be avoided in the future in the off chance I forget again. Thanks! This is a great tool. | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1600/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/1600/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1599 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1599/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1599/comments | https://api.github.com/repos/coleifer/peewee/issues/1599/events | https://github.com/coleifer/peewee/issues/1599 | 320,640,596 | MDU6SXNzdWUzMjA2NDA1OTY= | 1,599 | different select behavior between 3.3.4 and 3.2.2 | {
"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 | [
"I try many peewee versions, 3.2.4 is first version that return the values of table1 and 3.2.3 is the latest version that return the value of table2",
"The change that was introduced was to avoid overwriting values. You're selecting all columns on `Table1` (including it's status field), so it's expected that the status field would contain the value on Table1.\r\n\r\nTo capture the status field on table 2 there are a number of things you can do:\r\n\r\n* specify an alias for the Table2.status value (e.g. Table2.status.alias('status2'))\r\n* if a foreign-key exists between the joined tables, look-up the attribute on the joined instance\r\n* otherwise specify a join attribute by specifying an alias on the join predicate"
] | 2018-05-06T23:57:28 | 2018-05-07T01:15:05 | 2018-05-07T00:09:19 | NONE | null | I try some code like this
```python
# coding=utf-8
import peewee
from peewee import IntegerField, FixedCharField, TextField
db = peewee.SqliteDatabase('example.db')
class DB(peewee.Model):
class Meta:
database = db
class Table1(DB):
name = TextField(unique=True, null=False)
status = TextField()
class Table2(DB):
user_name = TextField(unique=True)
status = TextField()
if __name__ == '__main__':
Table1.create_table(fail_silently=True)
Table2.create_table(fail_silently=True)
Table1.create(name='name', status='status_table_1')
Table2.create(user_name='name', status='status_table_2')
data = Table1.select(Table1, Table2.status) \
.join(Table2, peewee.JOIN['LEFT_OUTER'], on=(Table1.name == Table2.user_name)) \
.where(Table1.name == 'name').objects()
print(data[0].status)
```
in peewee 3.2.2 it's `status_table_2`
but in peewee 3.3.4 it's `status_table_1`
I wonder is this a break change without change major version, or it's just a bug.
| {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1599/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/1599/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1598 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1598/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1598/comments | https://api.github.com/repos/coleifer/peewee/issues/1598/events | https://github.com/coleifer/peewee/issues/1598 | 320,602,850 | MDU6SXNzdWUzMjA2MDI4NTA= | 1,598 | auto primary key field | {
"login": "ra-esmith",
"id": 24212262,
"node_id": "MDQ6VXNlcjI0MjEyMjYy",
"avatar_url": "https://avatars.githubusercontent.com/u/24212262?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/ra-esmith",
"html_url": "https://github.com/ra-esmith",
"followers_url": "https://api.github.com/users/ra-esmith/followers",
"following_url": "https://api.github.com/users/ra-esmith/following{/other_user}",
"gists_url": "https://api.github.com/users/ra-esmith/gists{/gist_id}",
"starred_url": "https://api.github.com/users/ra-esmith/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/ra-esmith/subscriptions",
"organizations_url": "https://api.github.com/users/ra-esmith/orgs",
"repos_url": "https://api.github.com/users/ra-esmith/repos",
"events_url": "https://api.github.com/users/ra-esmith/events{/privacy}",
"received_events_url": "https://api.github.com/users/ra-esmith/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"looks like the model.insert call is not making the primary key. i have not intentionally passed in a primary key, also possible the record coming in has null on the primary key already and you are not overwriting that? I am going to try .create instead of .insert",
"Peewee has a convention of using `id` for an auto-incrementing primary key field. Perhaps you're subclassing models which override the primary key?\r\n\r\nCan you provide example code I can use to reliably replicate this issue? Without that I'm a little at a loss how to replicate this or even verify there is a bug.",
"Please comment with additional details or steps I can follow to replicate, and I will be happy to reopen and investigate.",
"Hello,\n\nThanks for the help.\n\nI have resolved this on my end.\n\nIssue comes up if one has a postgres 9.6 version. I moved to 10 postgres and it went away.\nHowever, I also was more brutal in my code as related to ID generation and storage, and perhaps that also fixed the problem.\n\nEitherway I am in peewee 3x and looks to be working now.\n\nThanks!!!!\nEvan\n\nSent with [ProtonMail](https://protonmail.com) Secure Email.\n\n‐‐‐‐‐‐‐ Original Message ‐‐‐‐‐‐‐\nOn May 8, 2018 9:45 AM, Charles Leifer <[email protected]> wrote:\n\n> Please comment with additional details or steps I can follow to replicate, and I will be happy to reopen and investigate.\n>\n> —\n> You are receiving this because you authored the thread.\n> Reply to this email directly, [view it on GitHub](https://github.com/coleifer/peewee/issues/1598#issuecomment-387407156), or [mute the thread](https://github.com/notifications/unsubscribe-auth/AXFzJlcgsNjM032U-b8jr-Y-ANUeknJIks5twaFjgaJpZM4T0FOF)."
] | 2018-05-06T15:37:16 | 2018-05-08T13:46:56 | 2018-05-08T13:45:01 | NONE | null | Using peewee 3.3.1 (just upgraded to 3.3.4).
Python
On ubuntu 16
"sometimes" I find a rather odd new error.
I have various classes which have foriegn keys etc, some have no primary key defined. Peewee defiens an auto increments the key on creation, or it has in the "past versions". However, I now find that "sometimes" the auto increment of the primary key does not occur and it comes out as null in the insert and blows an error in sql. Saying null value in colum n";id"; violates not-null constraint (postgres).
Then "failing row contains (null, ...)
statement is
insert into table ("foo_id", ..
and foo is the foreign table.
NOW, if i put int an autofield and explcitly deal with that then the problem goes away.
But would rather not rewrite my code, and would like to know what is up.
Ideas?
Evan | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1598/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/1598/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1597 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1597/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1597/comments | https://api.github.com/repos/coleifer/peewee/issues/1597/events | https://github.com/coleifer/peewee/issues/1597 | 320,486,879 | MDU6SXNzdWUzMjA0ODY4Nzk= | 1,597 | Peewee returns Decimal(), unsupported type. | {
"login": "mtairu",
"id": 4996264,
"node_id": "MDQ6VXNlcjQ5OTYyNjQ=",
"avatar_url": "https://avatars.githubusercontent.com/u/4996264?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/mtairu",
"html_url": "https://github.com/mtairu",
"followers_url": "https://api.github.com/users/mtairu/followers",
"following_url": "https://api.github.com/users/mtairu/following{/other_user}",
"gists_url": "https://api.github.com/users/mtairu/gists{/gist_id}",
"starred_url": "https://api.github.com/users/mtairu/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/mtairu/subscriptions",
"organizations_url": "https://api.github.com/users/mtairu/orgs",
"repos_url": "https://api.github.com/users/mtairu/repos",
"events_url": "https://api.github.com/users/mtairu/events{/privacy}",
"received_events_url": "https://api.github.com/users/mtairu/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"solved."
] | 2018-05-05T07:18:33 | 2018-05-05T11:51:23 | 2018-05-05T11:51:23 | NONE | null | Querying data from RDS, and peewee get the record succesfully however, when I loop through to get the value, it returns Decimal(), or corresponding type. I used peewee in my last project, and it did not return data like this.
```
records = market.select().limit(1)
return [r.volume for r in records]
results:
[Decimal(89033)]
``` | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1597/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/1597/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1596 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1596/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1596/comments | https://api.github.com/repos/coleifer/peewee/issues/1596/events | https://github.com/coleifer/peewee/issues/1596 | 319,818,101 | MDU6SXNzdWUzMTk4MTgxMDE= | 1,596 | Syntax error while using db.execute_sql to get sqlite3 table schema | {
"login": "gzxultra",
"id": 10581586,
"node_id": "MDQ6VXNlcjEwNTgxNTg2",
"avatar_url": "https://avatars.githubusercontent.com/u/10581586?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/gzxultra",
"html_url": "https://github.com/gzxultra",
"followers_url": "https://api.github.com/users/gzxultra/followers",
"following_url": "https://api.github.com/users/gzxultra/following{/other_user}",
"gists_url": "https://api.github.com/users/gzxultra/gists{/gist_id}",
"starred_url": "https://api.github.com/users/gzxultra/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/gzxultra/subscriptions",
"organizations_url": "https://api.github.com/users/gzxultra/orgs",
"repos_url": "https://api.github.com/users/gzxultra/repos",
"events_url": "https://api.github.com/users/gzxultra/events{/privacy}",
"received_events_url": "https://api.github.com/users/gzxultra/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"Those \".\"-commands are only implemented in the sqlite shell. They're not part of the sql interface.",
"Check out the code in SqliteDatabase like get_tables, get_columns, etc if\nyou want to introspect the database. There's also the reflection module in\nplayhouse.reflection. Check the docs.\n\nOn Thu, May 3, 2018, 2:48 AM 夏天的风铃_ <[email protected]> wrote:\n\n> I got a syntax error when using db.execute_sql to get sqlite3 table schema,\n>\n> Reproduce:\n>\n> In [135]: db = SqliteDatabase('test.db')\n> ...:\n> ...:\n> ...: class ExampleTable(Model):\n> ...: class Meta:\n> ...: table_name = 'test_table'\n> ...: database = db\n> ...:\n> ...: created_time = DateTimeField(default=datetime.datetime.now)\n> ...: update_time = DateTimeField(default=datetime.datetime.now)\n> ...:\n>\n> In [136]: ExampleTable\n> Out[136]: __main__.ExampleTable\n>\n> In [137]: ExampleTable.create_table()\n>\n> In [138]: db.execute_sql('.schema')\n> ---------------------------------------------------------------------------\n> OperationalError Traceback (most recent call last)\n> ~/.local/share/virtualenvs/pycsvsql-TYJ8UyNv/lib/python3.6/site-packages/peewee.py in execute_sql(self, sql, params, commit)\n> 2566 try:\n> -> 2567 cursor.execute(sql, params or ())\n> 2568 except Exception:\n>\n> OperationalError: near \".\": syntax error\n>\n> During handling of the above exception, another exception occurred:\n>\n> OperationalError Traceback (most recent call last)\n> <ipython-input-138-e0357ff2f49e> in <module>()\n> ----> 1 db.execute_sql('.schema')\n>\n> ~/.local/share/virtualenvs/pycsvsql-TYJ8UyNv/lib/python3.6/site-packages/peewee.py in execute_sql(self, sql, params, commit)\n> 2572 else:\n> 2573 if commit and not self.in_transaction():\n> -> 2574 self.commit()\n> 2575 return cursor\n> 2576\n>\n> ~/.local/share/virtualenvs/pycsvsql-TYJ8UyNv/lib/python3.6/site-packages/peewee.py in __exit__(self, exc_type, exc_value, traceback)\n> 2365 new_type = self.exceptions[exc_type.__name__]\n> 2366 exc_args = exc_value.args\n> -> 2367 reraise(new_type, new_type(*exc_args), traceback)\n> 2368\n> 2369 EXCEPTIONS = {\n>\n> ~/.local/share/virtualenvs/pycsvsql-TYJ8UyNv/lib/python3.6/site-packages/peewee.py in reraise(tp, value, tb)\n> 173 def reraise(tp, value, tb=None):\n> 174 if value.__traceback__ is not tb:\n> --> 175 raise value.with_traceback(tb)\n> 176 raise value\n> 177\n>\n> ~/.local/share/virtualenvs/pycsvsql-TYJ8UyNv/lib/python3.6/site-packages/peewee.py in execute_sql(self, sql, params, commit)\n> 2565 cursor = self.cursor(commit)\n> 2566 try:\n> -> 2567 cursor.execute(sql, params or ())\n> 2568 except Exception:\n> 2569 if self.autorollback and not self.in_transaction():\n>\n> OperationalError: near \".\": syntax error\n>\n> I was expecting something like,\n>\n> sqlite> .schema\n> CREATE TABLE IF NOT EXISTS \"test_table\" (\"id\" INTEGER NOT NULL PRIMARY KEY, \"created_time\" DATETIME NOT NULL, \"update_time\" DATETIME NOT NULL);\n>\n> Can you tell me how to fix it?\n>\n> —\n> You are receiving this because you are subscribed to this thread.\n> Reply to this email directly, view it on GitHub\n> <https://github.com/coleifer/peewee/issues/1596>, or mute the thread\n> <https://github.com/notifications/unsubscribe-auth/AAHUprxEhAxcns6tLtO0MPv2tREa9WdWks5turZmgaJpZM4TwodY>\n> .\n>\n"
] | 2018-05-03T07:48:53 | 2018-05-03T10:58:07 | 2018-05-03T10:56:10 | NONE | null | Problem:
I got a syntax error when using db.execute_sql to get sqlite3 table schema,
Reproduce:
```python
In [135]: db = SqliteDatabase('test.db')
...:
...:
...: class ExampleTable(Model):
...: class Meta:
...: table_name = 'test_table'
...: database = db
...:
...: created_time = DateTimeField(default=datetime.datetime.now)
...: update_time = DateTimeField(default=datetime.datetime.now)
...:
In [136]: ExampleTable
Out[136]: __main__.ExampleTable
In [137]: ExampleTable.create_table()
In [138]: db.execute_sql('.schema')
---------------------------------------------------------------------------
OperationalError Traceback (most recent call last)
~/.local/share/virtualenvs/pycsvsql-TYJ8UyNv/lib/python3.6/site-packages/peewee.py in execute_sql(self, sql, params, commit)
2566 try:
-> 2567 cursor.execute(sql, params or ())
2568 except Exception:
OperationalError: near ".": syntax error
During handling of the above exception, another exception occurred:
OperationalError Traceback (most recent call last)
<ipython-input-138-e0357ff2f49e> in <module>()
----> 1 db.execute_sql('.schema')
~/.local/share/virtualenvs/pycsvsql-TYJ8UyNv/lib/python3.6/site-packages/peewee.py in execute_sql(self, sql, params, commit)
2572 else:
2573 if commit and not self.in_transaction():
-> 2574 self.commit()
2575 return cursor
2576
~/.local/share/virtualenvs/pycsvsql-TYJ8UyNv/lib/python3.6/site-packages/peewee.py in __exit__(self, exc_type, exc_value, traceback)
2365 new_type = self.exceptions[exc_type.__name__]
2366 exc_args = exc_value.args
-> 2367 reraise(new_type, new_type(*exc_args), traceback)
2368
2369 EXCEPTIONS = {
~/.local/share/virtualenvs/pycsvsql-TYJ8UyNv/lib/python3.6/site-packages/peewee.py in reraise(tp, value, tb)
173 def reraise(tp, value, tb=None):
174 if value.__traceback__ is not tb:
--> 175 raise value.with_traceback(tb)
176 raise value
177
~/.local/share/virtualenvs/pycsvsql-TYJ8UyNv/lib/python3.6/site-packages/peewee.py in execute_sql(self, sql, params, commit)
2565 cursor = self.cursor(commit)
2566 try:
-> 2567 cursor.execute(sql, params or ())
2568 except Exception:
2569 if self.autorollback and not self.in_transaction():
OperationalError: near ".": syntax error
```
I was expecting something like this,
```sql
sqlite> .schema --indent
CREATE TABLE IF NOT EXISTS "test_table"(
"id" INTEGER NOT NULL PRIMARY KEY,
"created_time" DATETIME NOT NULL,
"update_time" DATETIME NOT NULL
);
```
Could you tell me how to fix it? | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1596/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/1596/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1595 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1595/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1595/comments | https://api.github.com/repos/coleifer/peewee/issues/1595/events | https://github.com/coleifer/peewee/pull/1595 | 319,747,172 | MDExOlB1bGxSZXF1ZXN0MTg1NTg3OTc0 | 1,595 | Add .execute() in examples with insert_many | {
"login": "rennerocha",
"id": 382887,
"node_id": "MDQ6VXNlcjM4Mjg4Nw==",
"avatar_url": "https://avatars.githubusercontent.com/u/382887?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/rennerocha",
"html_url": "https://github.com/rennerocha",
"followers_url": "https://api.github.com/users/rennerocha/followers",
"following_url": "https://api.github.com/users/rennerocha/following{/other_user}",
"gists_url": "https://api.github.com/users/rennerocha/gists{/gist_id}",
"starred_url": "https://api.github.com/users/rennerocha/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/rennerocha/subscriptions",
"organizations_url": "https://api.github.com/users/rennerocha/orgs",
"repos_url": "https://api.github.com/users/rennerocha/repos",
"events_url": "https://api.github.com/users/rennerocha/events{/privacy}",
"received_events_url": "https://api.github.com/users/rennerocha/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"Thank you, this is helpful."
] | 2018-05-02T23:39:12 | 2018-05-03T00:18:54 | 2018-05-03T00:18:48 | CONTRIBUTOR | null | If the code is executed without .execute(), the data will never be inserted. | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1595/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/1595/timeline | null | null | false | {
"url": "https://api.github.com/repos/coleifer/peewee/pulls/1595",
"html_url": "https://github.com/coleifer/peewee/pull/1595",
"diff_url": "https://github.com/coleifer/peewee/pull/1595.diff",
"patch_url": "https://github.com/coleifer/peewee/pull/1595.patch",
"merged_at": "2018-05-03T00:18:48"
} |
https://api.github.com/repos/coleifer/peewee/issues/1594 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1594/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1594/comments | https://api.github.com/repos/coleifer/peewee/issues/1594/events | https://github.com/coleifer/peewee/issues/1594 | 319,480,899 | MDU6SXNzdWUzMTk0ODA4OTk= | 1,594 | constraints of ForeignKeyField cause syntax error | {
"login": "elonzh",
"id": 8749411,
"node_id": "MDQ6VXNlcjg3NDk0MTE=",
"avatar_url": "https://avatars.githubusercontent.com/u/8749411?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/elonzh",
"html_url": "https://github.com/elonzh",
"followers_url": "https://api.github.com/users/elonzh/followers",
"following_url": "https://api.github.com/users/elonzh/following{/other_user}",
"gists_url": "https://api.github.com/users/elonzh/gists{/gist_id}",
"starred_url": "https://api.github.com/users/elonzh/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/elonzh/subscriptions",
"organizations_url": "https://api.github.com/users/elonzh/orgs",
"repos_url": "https://api.github.com/users/elonzh/repos",
"events_url": "https://api.github.com/users/elonzh/events{/privacy}",
"received_events_url": "https://api.github.com/users/elonzh/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"peewee version: 3.2.2\r\ndatabase: mysql 5.6",
"i changed the sql to\r\n```sql\r\nCREATE TABLE IF NOT EXISTS `trial_books` (`id` INTEGER AUTO_INCREMENT NOT NULL PRIMARY KEY, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL, `book_id` INTEGER UNSIGNED NOT NULL, FOREIGN KEY (`\r\n book_id`) REFERENCES `books` (`id`))\r\n``\r\n\r\nit works.\r\n\r\nthat is, ``book_id` INTEGER NOT NULL UNSIGNED` is a wrong sql for mysql\r\n\r\n\r\n",
"[13.1.17 CREATE TABLE Syntax](https://dev.mysql.com/doc/refman/5.6/en/create-table.html)\r\n\r\n```\r\ncolumn_definition:\r\n data_type [NOT NULL | NULL] [DEFAULT default_value]\r\n [AUTO_INCREMENT] [UNIQUE [KEY]] [[PRIMARY] KEY]\r\n [COMMENT 'string']\r\n [COLUMN_FORMAT {FIXED|DYNAMIC|DEFAULT}]\r\n [STORAGE {DISK|MEMORY|DEFAULT}]\r\n [reference_definition]\r\n\r\ndata_type:\r\n BIT[(length)]\r\n | TINYINT[(length)] [UNSIGNED] [ZEROFILL]\r\n | SMALLINT[(length)] [UNSIGNED] [ZEROFILL]\r\n | MEDIUMINT[(length)] [UNSIGNED] [ZEROFILL]\r\n | INT[(length)] [UNSIGNED] [ZEROFILL]\r\n | INTEGER[(length)] [UNSIGNED] [ZEROFILL]\r\n | BIGINT[(length)] [UNSIGNED] [ZEROFILL]\r\n | REAL[(length,decimals)] [UNSIGNED] [ZEROFILL]\r\n | DOUBLE[(length,decimals)] [UNSIGNED] [ZEROFILL]\r\n | FLOAT[(length,decimals)] [UNSIGNED] [ZEROFILL]\r\n | DECIMAL[(length[,decimals])] [UNSIGNED] [ZEROFILL]\r\n | NUMERIC[(length[,decimals])] [UNSIGNED] [ZEROFILL]\r\n | DATE\r\n | TIME[(fsp)]\r\n | TIMESTAMP[(fsp)]\r\n | DATETIME[(fsp)]\r\n | YEAR\r\n | CHAR[(length)]\r\n [CHARACTER SET charset_name] [COLLATE collation_name]\r\n | VARCHAR(length)\r\n [CHARACTER SET charset_name] [COLLATE collation_name]\r\n | BINARY[(length)]\r\n | VARBINARY(length)\r\n | TINYBLOB\r\n | BLOB[(length)]\r\n | MEDIUMBLOB\r\n | LONGBLOB\r\n | TINYTEXT\r\n [CHARACTER SET charset_name] [COLLATE collation_name]\r\n | TEXT[(length)]\r\n [CHARACTER SET charset_name] [COLLATE collation_name]\r\n | MEDIUMTEXT\r\n [CHARACTER SET charset_name] [COLLATE collation_name]\r\n | LONGTEXT\r\n [CHARACTER SET charset_name] [COLLATE collation_name]\r\n | ENUM(value1,value2,value3,...)\r\n [CHARACTER SET charset_name] [COLLATE collation_name]\r\n | SET(value1,value2,value3,...)\r\n [CHARACTER SET charset_name] [COLLATE collation_name]\r\n | spatial_type\r\n```",
"You're probably best off creating your own field type.\r\n\r\n```python\r\nclass UnsignedIntegerField(IntegerField):\r\n field_type = 'INTEGER UNSIGNED'\r\n```"
] | 2018-05-02T09:36:01 | 2018-05-02T14:47:04 | 2018-05-02T14:47:04 | NONE | null | I have some models based on the database which was created by sql.
here is ddl for the model `Book`:
```sql
create table fennec.user_books
(
id int unsigned auto_increment
primary key,
book_id int unsigned not null,
user_type smallint(5) unsigned not null,
user_id int not null,
stage smallint(5) unsigned not null,
created_at timestamp(6) default CURRENT_TIMESTAMP(6) not null,
updated_at timestamp(6) default CURRENT_TIMESTAMP(6) not null,
constraint user_books_learning_unique
unique (book_id, user_type, user_id),
constraint user_books_book_id_foreign
foreign key (book_id) references fennec.books (id)
on delete cascade
)
engine=InnoDB
;
create index user_books_book_id_index
on fennec.user_books (book_id)
;
```
and the model `Book`:
```python
class Book(pwx.Model, SerializeMixin, SequenceMixin, ResourceMixin):
__seq_scope_field_name__ = 'series'
__appends__ = ['cover_urls', 'video_urls']
class Meta:
per_page = 3
table_name = 'books'
id = pw.AutoField()
series = pw.ForeignKeyField(Series, column_name='series_id', backref='books', index=True)
sequence = pw.DoubleField()
title = pw.CharField(max_length=45)
chinese_title = pw.CharField(max_length=45, null=True)
status = pw.SmallIntegerField(
choices=enum2choices(ResourceStatus),
default=ResourceStatus.UNPUBLISHED.value
)
description = pw.CharField(max_length=512, null=True)
cover_name = pw.CharField(max_length=255)
video_name = pw.CharField(max_length=255)
lyric = pw.TextField()
@validates(InclusionValidator(*enum_values(ResourceStatus)))
def validate_status(self, value):
return value
@property
def cover_urls(self):
return media.get_media_urls(current_app.config['MEDIA_PRI_IMG_BUCKET'], self.cover_name, private=True)
@property
def video_urls(self):
return media.get_media_urls(current_app.config['MEDIA_PRI_VID_BUCKET'], self.video_name, private=True)
@staticmethod
def of_series(series):
return Book.select().where(Book.series == series)
```
now we need a new model `TrialBook`:
```python
class TrialBook(pwx.Model, SerializeMixin):
class Meta:
table_name = 'trial_books'
id = pw.AutoField(constraints=[pw.SQL("UNSIGNED")])
book = pw.ForeignKeyField(Book, column_name='book_id', index=True)
```
we added `UNSIGNED` for `TrialBook.id` because the ddl of `Book.id` is `UNSIGNED`.
but when we got a syntax error like that:
```
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 'UNSIGNED, FOREIGN KEY (`book_id`) REFERENCES `books` (`id`))' at line 1")
```
ddl for `TrialBook`:
```
('CREATE TABLE IF NOT EXISTS `trial_books` (`id` INTEGER AUTO_INCREMENT NOT NULL PRIMARY KEY, `created_at` DATETIME NOT NULL, `updated_at` DATETIME NOT NULL, `book_id` INTEGER NOT NULL unsigned, FOREIGN KEY (`book_id`) REFERENCES `books` (`id`))',
[])
```
| {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1594/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/1594/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1593 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1593/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1593/comments | https://api.github.com/repos/coleifer/peewee/issues/1593/events | https://github.com/coleifer/peewee/issues/1593 | 318,983,987 | MDU6SXNzdWUzMTg5ODM5ODc= | 1,593 | Model level constraint | {
"login": "bySabi",
"id": 6242574,
"node_id": "MDQ6VXNlcjYyNDI1NzQ=",
"avatar_url": "https://avatars.githubusercontent.com/u/6242574?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/bySabi",
"html_url": "https://github.com/bySabi",
"followers_url": "https://api.github.com/users/bySabi/followers",
"following_url": "https://api.github.com/users/bySabi/following{/other_user}",
"gists_url": "https://api.github.com/users/bySabi/gists{/gist_id}",
"starred_url": "https://api.github.com/users/bySabi/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/bySabi/subscriptions",
"organizations_url": "https://api.github.com/users/bySabi/orgs",
"repos_url": "https://api.github.com/users/bySabi/repos",
"events_url": "https://api.github.com/users/bySabi/events{/privacy}",
"received_events_url": "https://api.github.com/users/bySabi/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"Fields have `null=False` by default, or in other words, by default fields do not allow null values.",
"@coleifer thanks for take the time to answer Peewee beginners questions. You are doing a very good job here 👏\r\n\r\none more ... \r\n\r\nI create a SQLite db and a model with a DateField, say:\r\n```\r\nclass MyModel(BaseModel):\r\n n1 = IntegerField(unique=True)\r\n date1 = DateField(unique=True)\r\n```\r\nThen the model is populate from a json file:\r\n```\r\n with open('json.jl') as f:\r\n for line in f.readlines()\r\n data = MyModel(**json.loads(line))\r\n data.save()\r\n```\r\nThe above code is running fine, UNIQUE constraints raise exceptions has expected. \r\nBut I put, intentionally, wrong values on `date1` field like '2017-1-59' or 'any string' and the values get store without `Exception`. I thought that `DateField` enforce some constraint or validation. \r\n\r\nWhat I miss here??\r\n ",
"You should be passing them in as Python `datetime.date` objects rather than as strings.",
"`DateField` only set the field type on table creation, but don´t do validation beyond null check or unique constraints? \r\n",
"It's more complicated than that, unfortunately.\r\n\r\nSQLite doesn't have a true date/time data-type. Databases like MySQL or Postgres would raise an error if you tried to insert garbage data, but with SQLite you need to either represent the date-time as a string (in which case you should use YYYY-mm-dd HH:MM:SS to ensure lexicographic sorting) or an integer timestamp.\r\n\r\nIf you want to enforce validation, you can subclass DateTimeField (or DateField or whatever) and modify the `db_value()` method to ensure strings are valid dates (or datetimes or whatever).",
"@coleifer now is clear to me. Thanks a lot for the details in the explanation.\r\n\r\nI take your advice and convert date str to `datetime.date` before save it.\r\n\r\n"
] | 2018-04-30T18:14:22 | 2018-05-01T15:04:20 | 2018-04-30T19:31:58 | NONE | null | A incomer here ...
I know the field constraints but I need `null=False` for all fields.
Can I set `null=False` by default for a Model, Is this possible?
| {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1593/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/1593/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1592 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1592/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1592/comments | https://api.github.com/repos/coleifer/peewee/issues/1592/events | https://github.com/coleifer/peewee/issues/1592 | 318,695,659 | MDU6SXNzdWUzMTg2OTU2NTk= | 1,592 | Missing things from Changes in 3.0 doc | {
"login": "tomako",
"id": 1412056,
"node_id": "MDQ6VXNlcjE0MTIwNTY=",
"avatar_url": "https://avatars.githubusercontent.com/u/1412056?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/tomako",
"html_url": "https://github.com/tomako",
"followers_url": "https://api.github.com/users/tomako/followers",
"following_url": "https://api.github.com/users/tomako/following{/other_user}",
"gists_url": "https://api.github.com/users/tomako/gists{/gist_id}",
"starred_url": "https://api.github.com/users/tomako/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/tomako/subscriptions",
"organizations_url": "https://api.github.com/users/tomako/orgs",
"repos_url": "https://api.github.com/users/tomako/repos",
"events_url": "https://api.github.com/users/tomako/events{/privacy}",
"received_events_url": "https://api.github.com/users/tomako/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"Thanks for reporting, should be fixed.",
"I added the following methods to select queries:\r\n\r\n* `union_all()`\r\n* `union()`\r\n* `intersect()`\r\n* `except_()`"
] | 2018-04-29T07:08:20 | 2018-04-29T19:08:35 | 2018-04-29T19:08:10 | NONE | null | I've just moved a project to the latest version and found few shortcomings that I think are missing from the list of changes. I've checked also the release notes but neither found there. Anyway they might be useful for others.
- Database class init parameter `fields` (for adding custom fields) has been renamed to `field_types`
- SQL class init parameter `params` now is expected to be iterable
- SelectQuery's `union_all` method is gone but there is an operator (`+`) instead of it. As I remember I used the method call because there was no operator. And in fact I see the `union_all` method in the CTE class. TBH it was simpler to use the operator than understand what CTE is ;)
Ps. Special thanks for the `BigAutoField`. I was about to add it. | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1592/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/1592/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1591 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1591/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1591/comments | https://api.github.com/repos/coleifer/peewee/issues/1591/events | https://github.com/coleifer/peewee/issues/1591 | 318,591,837 | MDU6SXNzdWUzMTg1OTE4Mzc= | 1,591 | Feature: get_unique_row | {
"login": "yanghg-basefx",
"id": 29534214,
"node_id": "MDQ6VXNlcjI5NTM0MjE0",
"avatar_url": "https://avatars.githubusercontent.com/u/29534214?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/yanghg-basefx",
"html_url": "https://github.com/yanghg-basefx",
"followers_url": "https://api.github.com/users/yanghg-basefx/followers",
"following_url": "https://api.github.com/users/yanghg-basefx/following{/other_user}",
"gists_url": "https://api.github.com/users/yanghg-basefx/gists{/gist_id}",
"starred_url": "https://api.github.com/users/yanghg-basefx/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/yanghg-basefx/subscriptions",
"organizations_url": "https://api.github.com/users/yanghg-basefx/orgs",
"repos_url": "https://api.github.com/users/yanghg-basefx/repos",
"events_url": "https://api.github.com/users/yanghg-basefx/events{/privacy}",
"received_events_url": "https://api.github.com/users/yanghg-basefx/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"Given how easy it is to add this to your own base model class, I'm going to pass on adding similar functionality to peewee. As you noted, the proper way to guarantee uniqueness is to have a unique constraint.\r\n\r\n```python\r\n@classmethod\r\ndef get_unique_row(cls, *expr):\r\n query = cls.select().where(*expr).limit(2)\r\n results = list(query)\r\n if len(results) == 1:\r\n return results[0]\r\n elif len(results) == 0:\r\n raise cls.DoesNotExist\r\n else:\r\n raise NonUniqueException\r\n```",
"That's what I need! Thanks!"
] | 2018-04-28T02:21:55 | 2018-05-02T00:35:23 | 2018-04-29T19:11:56 | NONE | null | Consider: If one database can't have an unique index, but some queries must get a unique record, what should we do?
So I implement this method in SelectQuery (peewee 2.8.1):
```python
def get_unique_row(self):
clone = self.paginate(1, 2)
qrw = clone.execute()
try:
row = next(qrw)
except StopIteration:
raise self.model_class.DoesNotExist('...')
else:
try:
next(qrw)
except StopIteration:
return row
else:
raise self.model_class.ExistsTooMany('...')
```
It's really useful for us, and avoided a lot of unexpected exceptions. So if you can add a method like it to peewee 3.X, that's best! We can easier to upgrade our own peewee branch.
Thanks! | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1591/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/1591/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1590 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1590/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1590/comments | https://api.github.com/repos/coleifer/peewee/issues/1590/events | https://github.com/coleifer/peewee/pull/1590 | 318,315,732 | MDExOlB1bGxSZXF1ZXN0MTg0NTUxOTA5 | 1,590 | Fix issue with sort_models and DeferredForeignKey | {
"login": "sanjredfield",
"id": 5788651,
"node_id": "MDQ6VXNlcjU3ODg2NTE=",
"avatar_url": "https://avatars.githubusercontent.com/u/5788651?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/sanjredfield",
"html_url": "https://github.com/sanjredfield",
"followers_url": "https://api.github.com/users/sanjredfield/followers",
"following_url": "https://api.github.com/users/sanjredfield/following{/other_user}",
"gists_url": "https://api.github.com/users/sanjredfield/gists{/gist_id}",
"starred_url": "https://api.github.com/users/sanjredfield/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/sanjredfield/subscriptions",
"organizations_url": "https://api.github.com/users/sanjredfield/orgs",
"repos_url": "https://api.github.com/users/sanjredfield/repos",
"events_url": "https://api.github.com/users/sanjredfield/events{/privacy}",
"received_events_url": "https://api.github.com/users/sanjredfield/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"Thank you, I've submitted an equivalent cleaned-up patch with a test-case: d92036e7602f29c5ce4dae4ff2ffd09c28fab218",
"Thanks very much, I'll be sure to include a test case if I submit another PR in the future."
] | 2018-04-27T08:08:01 | 2018-04-29T19:12:20 | 2018-04-29T19:12:20 | NONE | null | I found an issue when using DeferredForeignKey and create_tables. The easiest way to duplicate the issue is to make a small modification to [this](http://docs.peewee-orm.com/en/latest/peewee/models.html#circular-foreign-key-dependencies) example from the peewee docs.
Here is the original example, which works fine.
```python
class User(Model):
username = CharField()
favorite_tweet = DeferredForeignKey('Tweet', null=True)
class Tweet(Model):
message = TextField()
user = ForeignKeyField(User, backref='tweets')
db.create_tables([User, Tweet])
```
However, one small change, and the example no longer works. The change is simply to rename `User` to `AUser`.
```python
class AUser(Model):
username = CharField()
favorite_tweet = DeferredForeignKey('Tweet', null=True)
class Tweet(Model):
message = TextField()
user = ForeignKeyField(AUser, backref='tweets')
db.create_tables([AUser, Tweet])
```
The original example from the docs works because `Tweet` is alphabetically before `User`, and `sort_models.dfs` gets called in the order: `Tweet` -> `User`. However, if we rename `User` to `AUser`, the call order of `dfs` is now `AUser` -> `Tweet`, therefore causing `Tweet` to be created first. This throws an error:
```
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "goals/model/__init__.py", line 54, in create_tables
db.create_tables([AUser, Tweet])
File "/usr/lib/python2.7/site-packages/peewee.py", line 2724, in create_tables
model.create_table(**options)
File "/usr/lib/python2.7/site-packages/peewee.py", line 5456, in create_table
cls._schema.create_all(safe, **options)
File "/usr/lib/python2.7/site-packages/peewee.py", line 4722, in create_all
self.create_table(safe, **table_options)
File "/usr/lib/python2.7/site-packages/peewee.py", line 4618, in create_table
self.database.execute(self._create_table(safe=safe, **options))
File "/usr/lib/python2.7/site-packages/playhouse/postgres_ext.py", line 446, in execute
cursor = self.execute_sql(sql, params, commit=commit)
File "/usr/lib/python2.7/site-packages/peewee.py", line 2583, in execute_sql
self.commit()
File "/usr/lib/python2.7/site-packages/peewee.py", line 2376, in __exit__
reraise(new_type, new_type(*exc_args), traceback)
File "/usr/lib/python2.7/site-packages/peewee.py", line 2576, in execute_sql
cursor.execute(sql, params or ())
peewee.ProgrammingError: relation "auser" does not exist
```
The attached pull request fixes the issue by making a small modification to `dfs` in `sort_models`. I've added a check to ensure that deferred foreign keys are not traversed by the dfs. | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1590/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/1590/timeline | null | null | false | {
"url": "https://api.github.com/repos/coleifer/peewee/pulls/1590",
"html_url": "https://github.com/coleifer/peewee/pull/1590",
"diff_url": "https://github.com/coleifer/peewee/pull/1590.diff",
"patch_url": "https://github.com/coleifer/peewee/pull/1590.patch",
"merged_at": null
} |
https://api.github.com/repos/coleifer/peewee/issues/1589 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1589/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1589/comments | https://api.github.com/repos/coleifer/peewee/issues/1589/events | https://github.com/coleifer/peewee/issues/1589 | 318,263,724 | MDU6SXNzdWUzMTgyNjM3MjQ= | 1,589 | Database.cursor parameter documentation and consistency. | {
"login": "diekhans",
"id": 110053,
"node_id": "MDQ6VXNlcjExMDA1Mw==",
"avatar_url": "https://avatars.githubusercontent.com/u/110053?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/diekhans",
"html_url": "https://github.com/diekhans",
"followers_url": "https://api.github.com/users/diekhans/followers",
"following_url": "https://api.github.com/users/diekhans/following{/other_user}",
"gists_url": "https://api.github.com/users/diekhans/gists{/gist_id}",
"starred_url": "https://api.github.com/users/diekhans/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/diekhans/subscriptions",
"organizations_url": "https://api.github.com/users/diekhans/orgs",
"repos_url": "https://api.github.com/users/diekhans/repos",
"events_url": "https://api.github.com/users/diekhans/events{/privacy}",
"received_events_url": "https://api.github.com/users/diekhans/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"Thanks, I've updated the method signature for `PostgresqlExtDatabase` and mentioned in the docs that the parameter is internal-use-only. fbb4ded7000d5163344c67236fee7a1fae38991c"
] | 2018-04-27T03:12:50 | 2018-04-27T13:38:33 | 2018-04-27T13:38:33 | NONE | null | peewee-3.3.1
http://docs.peewee-orm.com/en/latest/peewee/api.html#Database.cursor
Indicates that Database.currsor(commit=None ) has cursor as an optional an parameter. However, It does not define what this parameter does.
playhouse.postgres_ext.PostgresqlExtDatabase.cursor(commit) has the commit parameter as required. which conflictes with the definition in the base class.
thanks for the increidble package.
| {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1589/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/1589/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1588 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1588/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1588/comments | https://api.github.com/repos/coleifer/peewee/issues/1588/events | https://github.com/coleifer/peewee/pull/1588 | 317,986,759 | MDExOlB1bGxSZXF1ZXN0MTg0MzA4Mzgy | 1,588 | 'Metadata' object has no attribute 'model_ref' | {
"login": "klen",
"id": 90699,
"node_id": "MDQ6VXNlcjkwNjk5",
"avatar_url": "https://avatars.githubusercontent.com/u/90699?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/klen",
"html_url": "https://github.com/klen",
"followers_url": "https://api.github.com/users/klen/followers",
"following_url": "https://api.github.com/users/klen/following{/other_user}",
"gists_url": "https://api.github.com/users/klen/gists{/gist_id}",
"starred_url": "https://api.github.com/users/klen/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/klen/subscriptions",
"organizations_url": "https://api.github.com/users/klen/orgs",
"repos_url": "https://api.github.com/users/klen/repos",
"events_url": "https://api.github.com/users/klen/events{/privacy}",
"received_events_url": "https://api.github.com/users/klen/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"Thank you!"
] | 2018-04-26T11:25:59 | 2018-04-26T12:04:25 | 2018-04-26T12:04:17 | CONTRIBUTOR | null | Fixed mistype in Metadata class. It breaks migrations for now. | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1588/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/1588/timeline | null | null | false | {
"url": "https://api.github.com/repos/coleifer/peewee/pulls/1588",
"html_url": "https://github.com/coleifer/peewee/pull/1588",
"diff_url": "https://github.com/coleifer/peewee/pull/1588.diff",
"patch_url": "https://github.com/coleifer/peewee/pull/1588.patch",
"merged_at": "2018-04-26T12:04:17"
} |
https://api.github.com/repos/coleifer/peewee/issues/1587 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1587/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1587/comments | https://api.github.com/repos/coleifer/peewee/issues/1587/events | https://github.com/coleifer/peewee/issues/1587 | 317,742,146 | MDU6SXNzdWUzMTc3NDIxNDY= | 1,587 | Preserving column names without needing Pythonic attribute names convention | {
"login": "ketozhang",
"id": 13506487,
"node_id": "MDQ6VXNlcjEzNTA2NDg3",
"avatar_url": "https://avatars.githubusercontent.com/u/13506487?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/ketozhang",
"html_url": "https://github.com/ketozhang",
"followers_url": "https://api.github.com/users/ketozhang/followers",
"following_url": "https://api.github.com/users/ketozhang/following{/other_user}",
"gists_url": "https://api.github.com/users/ketozhang/gists{/gist_id}",
"starred_url": "https://api.github.com/users/ketozhang/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/ketozhang/subscriptions",
"organizations_url": "https://api.github.com/users/ketozhang/orgs",
"repos_url": "https://api.github.com/users/ketozhang/repos",
"events_url": "https://api.github.com/users/ketozhang/events{/privacy}",
"received_events_url": "https://api.github.com/users/ketozhang/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"Columns are exposed as attributes on model classes. As such, they must be valid Python identifiers. Peewee makes allowances for the weird types of column-names you might see by allowing you to specify the `column_name` parameter when defining your field, as you have done in your example model definition.\r\n\r\nAs long as you're working with the data in Python *as Python objects* it makes sense to me that you'd need to use Pythonic identifiers. As you said, you're importing this from a CSV file ... it's unclear to me why, if you're defining the schema, you wouldn't take that opportunity to make it conventional?\r\n\r\nTake a look here for a thorough explanation and rationale: https://launchbylunch.com/posts/2014/Feb/16/sql-naming-conventions/\r\n\r\nPeewee supports the above naming conventions, which are considered to be the \"80%\" use-case, while making it possible to still work with unconventional schemas (\"the 20% case\"). I think that's how it shall remain.",
"As an additional note, using the getitem APIs is particularly user-hostile because:\r\n\r\n* No tab-completion when debugging\r\n* No validation when code is being interpreted (hence, no AttributeError)\r\n* Additional typing (4 characters for brackets+quotes vs 1 for dot).\r\n* Non-obvious -- fields are model-class attributes, you should access them as you would any class attribute.",
"> As long as you're working with the data in Python as Python objects it makes sense to me that you'd need to use Pythonic identifiers. As you said, you're importing this from a CSV file ... it's unclear to me why, if you're defining the schema, you wouldn't take that opportunity to make it conventional?\r\n\r\nUnfortunately the naming is not up to me. How would you propose naming a column like `2MASS` (Two Micron All-Sky Survey) to a Python identifier that preserves its historical name possibly `TMASS` but by the link you provided it follow pythonic variable names very closely so maybe `tmass`.\r\n\r\nYou propose for every schema I wish to create via importing some csv, I change the column names on the csv (given I'm importing via list of dicts) so it matches python convention. Then, I have to create a Model with this new columns names while also specifying the old \"unconventional\" columns names to the Field argument `column_name`. The 2nd step is reasonable but the 1st step shouldn't be needed as my Model knows if I refer to \"2MASS\" it should recognize it's the same w/e I named the Python conventional attribute by looking at the Field attribute `column_name`. \r\n\r\nSorry if it's a bit confusing it was difficult to word this out.",
"Theoretically once you've got your data into your db you don't need to think about what it was originally named in the csv...so we're talking about a one-time data-loading operation...\r\n\r\nI'd suggest making a translation table... untested code but should convey the idea hopefully:\r\n\r\n```python\r\nclass MyModel(Model):\r\n tmass = FloatField(column_name='2mass')\r\n # etc...\r\n\r\nttable = {f.column_name: f.name for f in MyModel._meta.sorted_fields}\r\ndef translate(in_data):\r\n return {ttable[k]: v for k, v in in_data.items()}\r\n\r\nfor row_dict in csv_file:\r\n MyModel.insert(translate(row)).execute()\r\n```"
] | 2018-04-25T18:25:21 | 2018-04-25T19:24:29 | 2018-04-25T18:53:13 | NONE | null | I understand that peewee requires storing every column as a the attribute of the Model instance. @coleifer once told me that `column_name` only preserves SQL column_name however it is impossible to access the column in the Model instance:
> In this way, the actual underlying column-name is still preserved and used, it's just that the accessor for it conforms to a Pythonic naming convention.
I would like to suggest Pandas' convention which is to use `__getitem__` which solves the issue of naming convention such as a variable name starting with a number
```python
>>> df = pd.DataFrame([[1,2,3],['a','b','c']], columns=['1a', '1b', '1c'])
>>> df
1a 1b 1c
0 1 2 3
1 a b c
>>> df.1a
File "<stdin>", line 1
df.1a
^
SyntaxError: invalid syntax
>>> df['1a']
0 1
1 a
Name: 1a, dtype: object
>>>df.__dict__
{'_data': BlockManager
Items: Index(['1a', '1b', '1c'], dtype='object')
Axis 1: RangeIndex(start=0, stop=2, step=1)
ObjectBlock: slice(0, 3, 1), 3 x 2, dtype: object,
'_iloc': <pandas.core.indexing._iLocIndexer at 0x1e9928e15c0>,
'_item_cache': {},
'is_copy': None}
```
There are many cases where my column name would conflict with Python naming convention. Take for instance a [catalog I am current working with](http://aquarius.elte.hu/glade/Download.html) has the column named `2MASS` and another named `SDSS-DR12` (both fail Python name convention). The task is to import the 'space' delimited text file to SQL via:
```python
class Catalog(BaseModel):
two_MASS = TextField(column_name='2MASS')
SDSS_DR12 = TextField(column_name='SDSS-DR12')
# ... some more fields
df = pd.read_csv('catalog.txt')
# ... do some data cleaning
data = df.dicts('records')
Catalog.insert_many(data).execute()
```
The last line would fail unless in `df`, I were to change the names via `df.rename({'2MASS': 'two_MASS', 'SDSS-DR12':'SDSS_DR12'})`. I would love to not do this because I expect all column names to be consistent. It is much more expandable to access the column by `Model.__getitem__('column name') ` rather than `getattr(Model, 'column_name')`. For instance:
```python
Catalog.select(Catalog['2MASS']) # equivalent to Catalog.select(Catalog.twoMASS)
```
@coleifer please let me know if peewee is able to support this in another way.
| {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1587/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/1587/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1586 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1586/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1586/comments | https://api.github.com/repos/coleifer/peewee/issues/1586/events | https://github.com/coleifer/peewee/issues/1586 | 317,143,033 | MDU6SXNzdWUzMTcxNDMwMzM= | 1,586 | [attention] DATABASE_URL issue | {
"login": "ak4nv",
"id": 73960,
"node_id": "MDQ6VXNlcjczOTYw",
"avatar_url": "https://avatars.githubusercontent.com/u/73960?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/ak4nv",
"html_url": "https://github.com/ak4nv",
"followers_url": "https://api.github.com/users/ak4nv/followers",
"following_url": "https://api.github.com/users/ak4nv/following{/other_user}",
"gists_url": "https://api.github.com/users/ak4nv/gists{/gist_id}",
"starred_url": "https://api.github.com/users/ak4nv/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/ak4nv/subscriptions",
"organizations_url": "https://api.github.com/users/ak4nv/orgs",
"repos_url": "https://api.github.com/users/ak4nv/repos",
"events_url": "https://api.github.com/users/ak4nv/events{/privacy}",
"received_events_url": "https://api.github.com/users/ak4nv/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"Ew interesting I wonder if that's been reported to python, since it's in the urllib.parse module.",
"https://bugs.python.org/issue18140"
] | 2018-04-24T09:27:49 | 2018-04-24T15:21:32 | 2018-04-24T15:21:32 | NONE | null | If you like using DATABASE_URL, just keep in mind that your password should not contain a "?" character.
```shell
>>> from urllib.parse import urlparse
>>> urlparse('postgres://login:p?assword@localhost:5432/db')
ParseResult(scheme='postgres', netloc='login:p', path='', params='', query='assword@localhost:5432/db', fragment='')
```
Happy conding! :smile: | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1586/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/1586/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1585 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1585/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1585/comments | https://api.github.com/repos/coleifer/peewee/issues/1585/events | https://github.com/coleifer/peewee/issues/1585 | 316,289,691 | MDU6SXNzdWUzMTYyODk2OTE= | 1,585 | Each object be an singleton though the entire application | {
"login": "GabrielSalla",
"id": 15304514,
"node_id": "MDQ6VXNlcjE1MzA0NTE0",
"avatar_url": "https://avatars.githubusercontent.com/u/15304514?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/GabrielSalla",
"html_url": "https://github.com/GabrielSalla",
"followers_url": "https://api.github.com/users/GabrielSalla/followers",
"following_url": "https://api.github.com/users/GabrielSalla/following{/other_user}",
"gists_url": "https://api.github.com/users/GabrielSalla/gists{/gist_id}",
"starred_url": "https://api.github.com/users/GabrielSalla/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/GabrielSalla/subscriptions",
"organizations_url": "https://api.github.com/users/GabrielSalla/orgs",
"repos_url": "https://api.github.com/users/GabrielSalla/repos",
"events_url": "https://api.github.com/users/GabrielSalla/events{/privacy}",
"received_events_url": "https://api.github.com/users/GabrielSalla/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"So, SQLAlchemy uses an identity-map to do this kind of thing. Which brings a lot of other logic into the equation, such as the concept of session/object lifetimes, aggregating changes during commit, etc.\r\n\r\nPeewee, on the other hand, is an active-record ORM. Objects are containers for row data rather than canonical representations of the rows themselves. I find this mental model easier to work with. I know which queries are going to be executed and when they'll run.\r\n\r\nIt's a matter of preference, but peewee is fundamentally different from SQLAlchemy in this regard."
] | 2018-04-20T14:27:24 | 2018-04-20T15:28:36 | 2018-04-20T15:28:36 | NONE | null | SQLAlchemy has a neat feature where everytime an object of a model is instantiated, if this instance already existed, it would return the same object it already had (exactly). As an example, if you select objects from the database twice, both answers would be the same, including the `id()` of the objects.
It's a really interesting approach as we can select objects from anywhere in the code, change it's values and it will change anywhere this object exists too (as they are the same).
This would avoid problems where you already have the instance somewhere, select for the object in another function, change it's values but the first object will remain intact.
Is it an option for Peewee? I don't even know how hard it would be to implement it.
Here's an example code of what I mean.
```python
from peewee import *
class BaseModel(Model):
class Meta:
database = db
class User(BaseModel):
username = CharField(unique=True)
db = SqliteDatabase('my_database.db')
db.connect()
db.create_tables([User])
charlie = User.create(username='charlie')
c1 = User.get(User.username == 'charlie')
c2 = User.get(User.username == 'charlie')
# Assert all of them are the same
assert id(charlie) == id(c1) == id(c2)
``` | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1585/reactions",
"total_count": 9,
"+1": 4,
"-1": 0,
"laugh": 0,
"hooray": 2,
"confused": 0,
"heart": 3,
"rocket": 0,
"eyes": 0
} | https://api.github.com/repos/coleifer/peewee/issues/1585/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1584 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1584/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1584/comments | https://api.github.com/repos/coleifer/peewee/issues/1584/events | https://github.com/coleifer/peewee/issues/1584 | 316,052,026 | MDU6SXNzdWUzMTYwNTIwMjY= | 1,584 | Window function for MySQL | {
"login": "victators",
"id": 5924717,
"node_id": "MDQ6VXNlcjU5MjQ3MTc=",
"avatar_url": "https://avatars.githubusercontent.com/u/5924717?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/victators",
"html_url": "https://github.com/victators",
"followers_url": "https://api.github.com/users/victators/followers",
"following_url": "https://api.github.com/users/victators/following{/other_user}",
"gists_url": "https://api.github.com/users/victators/gists{/gist_id}",
"starred_url": "https://api.github.com/users/victators/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/victators/subscriptions",
"organizations_url": "https://api.github.com/users/victators/orgs",
"repos_url": "https://api.github.com/users/victators/repos",
"events_url": "https://api.github.com/users/victators/events{/privacy}",
"received_events_url": "https://api.github.com/users/victators/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"> Are the window function queries supported for MySQL databases?\r\n\r\nI'm not sure, although they are supported with integration tests for Postgresql.",
"You might try this for now:\r\n\r\n```python\r\nw = Window(partition_by=[PROJECT.date])\r\nquery = (aap\r\n .select(aap.date, aap.animal, aap.value, fn.AVG(aap.value).over(w).alias('avg'))\r\n .where((aap.date == '2018-02-08') & (aap.animal == 'DOG'))\r\n .window(w)) # Try adding this.\r\n```",
"I tried that too from your example in the docs but I just realized my MariaDB is running on MySQL 5.6 and window functions don't seem to come out until MySQL 8.0 so it was doomed from the start. Thank you for your help though",
"Yeah, recent MySQL and MariaDB have support but I haven't tested it personally."
] | 2018-04-19T21:44:30 | 2018-04-19T22:05:01 | 2018-04-19T21:58:32 | NONE | null | Are the window function queries supported for MySQL databases? I tried running the following and I get a ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '(PARTITION BY `t1`.`date`) AS `avg` FROM `PROJECT` AS `aap` WHERE (' at line 1")
Thank you!
```python
try:
db.connect()
aap = PROJECT.alias('aap')
query = (aap.select(aap.date,
aap.animal,
aap.value,
fn.AVG(aap.value).over(partition_by = [PROJECT.date]).alias('avg'))
.where((aap.date == '2018-02-08') & (aap.animal == 'DOG')))
finally:
db.close()
print([c.avg for c in query])
``` | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1584/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/1584/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1583 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1583/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1583/comments | https://api.github.com/repos/coleifer/peewee/issues/1583/events | https://github.com/coleifer/peewee/issues/1583 | 315,967,045 | MDU6SXNzdWUzMTU5NjcwNDU= | 1,583 | Data Class query result | {
"login": "hugo-pires",
"id": 7768784,
"node_id": "MDQ6VXNlcjc3Njg3ODQ=",
"avatar_url": "https://avatars.githubusercontent.com/u/7768784?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/hugo-pires",
"html_url": "https://github.com/hugo-pires",
"followers_url": "https://api.github.com/users/hugo-pires/followers",
"following_url": "https://api.github.com/users/hugo-pires/following{/other_user}",
"gists_url": "https://api.github.com/users/hugo-pires/gists{/gist_id}",
"starred_url": "https://api.github.com/users/hugo-pires/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/hugo-pires/subscriptions",
"organizations_url": "https://api.github.com/users/hugo-pires/orgs",
"repos_url": "https://api.github.com/users/hugo-pires/repos",
"events_url": "https://api.github.com/users/hugo-pires/events{/privacy}",
"received_events_url": "https://api.github.com/users/hugo-pires/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"You mean the 3.7 data-classes? Sure...just provide your own constructor function and call .objects(), e.g.:\r\n\r\n```python\r\ndef make_data_class(data_dict):\r\n # do whatever.\r\n return DataClass(**data_dict)\r\n\r\nfor data_class_obj in some_query.objects(make_data_class):\r\n ...\r\n```",
"Thank you. I am sorry but I am a newbie. After adapting your code I am getting the following error:\r\n\r\n```AttributeError: 'SelectQuery' object has no attribute 'objects'```",
"What version of peewee are you using?",
"peewee 2.10.1\r\n",
"Peewee 3.2.5 is the most recent version.",
"Thank you."
] | 2018-04-19T17:17:46 | 2018-04-19T20:19:48 | 2018-04-19T17:23:58 | NONE | null | Hello
Is it possible the get the query results as a Data Class instance?
Thank you | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1583/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/1583/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1582 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1582/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1582/comments | https://api.github.com/repos/coleifer/peewee/issues/1582/events | https://github.com/coleifer/peewee/issues/1582 | 315,899,311 | MDU6SXNzdWUzMTU4OTkzMTE= | 1,582 | timestamp auto update | {
"login": "1xinghuan",
"id": 33982538,
"node_id": "MDQ6VXNlcjMzOTgyNTM4",
"avatar_url": "https://avatars.githubusercontent.com/u/33982538?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/1xinghuan",
"html_url": "https://github.com/1xinghuan",
"followers_url": "https://api.github.com/users/1xinghuan/followers",
"following_url": "https://api.github.com/users/1xinghuan/following{/other_user}",
"gists_url": "https://api.github.com/users/1xinghuan/gists{/gist_id}",
"starred_url": "https://api.github.com/users/1xinghuan/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/1xinghuan/subscriptions",
"organizations_url": "https://api.github.com/users/1xinghuan/orgs",
"repos_url": "https://api.github.com/users/1xinghuan/repos",
"events_url": "https://api.github.com/users/1xinghuan/events{/privacy}",
"received_events_url": "https://api.github.com/users/1xinghuan/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"Sure, with the caveat that the new value will not be available to your code unless you explicitly re-fetch the new value.\r\n\r\n```python\r\nclass TimestampTest(Model):\r\n name = CharField(max_length=20)\r\n create_time = DateTimeField(constraints=[SQL('DEFAULT CURRENT_TIMESTAMP')])\r\n last_modify_time = DateTimeField(constraints=[SQL('DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP')])\r\n```",
"Thanks, but I find it can only be useful when using Model.update(). If I use Model.save(), it doesn't auto update.\r\n\r\n```\r\n query = TimestampTest.update(name=\"37a_000\").where(TimestampTest.id == 1)\r\n query.execute()\r\n```\r\nThis will update the last_modify_time.\r\n\r\n```\r\n test = TimestampTest.get(id=1)\r\n test.name = \"37a_0a\"\r\n test.save()\r\n```\r\nThis doesn't update.",
"Good point. You'll need to specify that peewee should only save the name field:\r\n\r\n```python\r\ntest.save(only=(TimestampTest.name,))\r\n```\r\n\r\nThat ought to do the trick."
] | 2018-04-19T14:19:56 | 2018-04-19T15:29:04 | 2018-04-19T14:47:31 | NONE | null | Can peewee support auto update time when modify data? Like in MySql, it can use "ON UPDATE CURRENT_TIMESTAMP":
```
CREATE TABLE `timestampTest` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(20) DEFAULT NULL,
`create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`last_modify_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP)
``` | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1582/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/1582/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1581 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1581/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1581/comments | https://api.github.com/repos/coleifer/peewee/issues/1581/events | https://github.com/coleifer/peewee/issues/1581 | 315,885,531 | MDU6SXNzdWUzMTU4ODU1MzE= | 1,581 | Date storage and converstion | {
"login": "biskit",
"id": 1078732,
"node_id": "MDQ6VXNlcjEwNzg3MzI=",
"avatar_url": "https://avatars.githubusercontent.com/u/1078732?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/biskit",
"html_url": "https://github.com/biskit",
"followers_url": "https://api.github.com/users/biskit/followers",
"following_url": "https://api.github.com/users/biskit/following{/other_user}",
"gists_url": "https://api.github.com/users/biskit/gists{/gist_id}",
"starred_url": "https://api.github.com/users/biskit/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/biskit/subscriptions",
"organizations_url": "https://api.github.com/users/biskit/orgs",
"repos_url": "https://api.github.com/users/biskit/repos",
"events_url": "https://api.github.com/users/biskit/events{/privacy}",
"received_events_url": "https://api.github.com/users/biskit/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"That format is no good because it doesn't sort lexicographically. Sqlite doesn't have a dedicate date/time data-type. You'll want to convert those to YYYY-mm-ddTHH:MM:SS so they sort correctly.\r\n\r\nPeewee *can* read values like that if you specify the strptime format, however comparisons like the one in your example will not work correctly:\r\n\r\n```python\r\nlousy_datetime = DateTimeField(formats=['%m/%d/%Y %I:%M %p'])\r\n```\r\n\r\nIt should be possible to also craft a one-time migration using sqlite's date/time functions: https://www.sqlite.org/lang_datefunc.html"
] | 2018-04-19T13:47:11 | 2018-04-19T14:44:07 | 2018-04-19T14:44:07 | NONE | null | I have a date coming in like this '04/20/2018 7:52 PM'. It's stored in a DateTimeField column as is. So any comparison against datetime.now() fails (typically > some datetime). | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1581/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/1581/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1580 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1580/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1580/comments | https://api.github.com/repos/coleifer/peewee/issues/1580/events | https://github.com/coleifer/peewee/issues/1580 | 315,793,587 | MDU6SXNzdWUzMTU3OTM1ODc= | 1,580 | Problem importing ManyToManyField from playhouse.fields in pipenv | {
"login": "philippnkling",
"id": 13765363,
"node_id": "MDQ6VXNlcjEzNzY1MzYz",
"avatar_url": "https://avatars.githubusercontent.com/u/13765363?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/philippnkling",
"html_url": "https://github.com/philippnkling",
"followers_url": "https://api.github.com/users/philippnkling/followers",
"following_url": "https://api.github.com/users/philippnkling/following{/other_user}",
"gists_url": "https://api.github.com/users/philippnkling/gists{/gist_id}",
"starred_url": "https://api.github.com/users/philippnkling/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/philippnkling/subscriptions",
"organizations_url": "https://api.github.com/users/philippnkling/orgs",
"repos_url": "https://api.github.com/users/philippnkling/repos",
"events_url": "https://api.github.com/users/philippnkling/events{/privacy}",
"received_events_url": "https://api.github.com/users/philippnkling/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"Sounds like `pipenv` has an old version of peewee on your computer.\r\n\r\nIn peewee 3.x `ManyToManyField` has moved into `peewee`, so:\r\n\r\n```python\r\n# 3.x\r\nfrom peewee import ManyToManyField\r\n```\r\n\r\nI'm not familiar with `pipenv` but it sounds like it's using an older version of peewee on your computer and the newer 3.x on your server.",
"Thank you. This seemed to be the case for me."
] | 2018-04-19T09:17:55 | 2018-04-23T07:30:10 | 2018-04-19T14:45:26 | NONE | null | Hey,
recently I am having the problem of being unable to import the ManyToManyField from playhouse.fields on an Ubuntu server where I am using pipenv to manage packages and run python. Namely the command
`from playhouse.fields import ManyToManyField`
will lead to the error:
`ImportError: cannot import name ManyToManyField`
When I am using the same import command on my computer, it works, so this problem might be related to the virtualenvironment of pipenv. However, maybe this is a problem of different versions and you could help me.
Additionally, the import command `from playhouse.shortcuts import ManyToManyField` works. Could I use this instead of the playhouse.fields entry? Are they the same? Can you tell me, why it might not find the ManyToManyField in the playhouse.fields? I would be grateful for any reference.
Thank you. | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1580/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/1580/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1579 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1579/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1579/comments | https://api.github.com/repos/coleifer/peewee/issues/1579/events | https://github.com/coleifer/peewee/issues/1579 | 315,581,344 | MDU6SXNzdWUzMTU1ODEzNDQ= | 1,579 | Issue with union queries for models with similar columns | {
"login": "bison",
"id": 240676,
"node_id": "MDQ6VXNlcjI0MDY3Ng==",
"avatar_url": "https://avatars.githubusercontent.com/u/240676?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/bison",
"html_url": "https://github.com/bison",
"followers_url": "https://api.github.com/users/bison/followers",
"following_url": "https://api.github.com/users/bison/following{/other_user}",
"gists_url": "https://api.github.com/users/bison/gists{/gist_id}",
"starred_url": "https://api.github.com/users/bison/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/bison/subscriptions",
"organizations_url": "https://api.github.com/users/bison/orgs",
"repos_url": "https://api.github.com/users/bison/repos",
"events_url": "https://api.github.com/users/bison/events{/privacy}",
"received_events_url": "https://api.github.com/users/bison/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"I wouldn't say you're doing anything wrong. What's happening is the result-rows from the cursor look like:\r\n\r\n```sql\r\nselect t1.id, t1.user_id, t1.content, t2.id, t2.username \r\nfrom tweet as t1 \r\ninner join users as t2 on (t1.user_id=t2.id) \r\nwhere t2.id = 1 \r\nunion \r\nselect t3.id, t3.user_id, t3.content, t4.id, t4.username \r\nfrom tweet as t3 \r\ninner join users as t4 on (t3.user_id=t4.id);\r\n```\r\n\r\nProduces:\r\n\r\n```\r\nid|user_id|content|id|username\r\n 1| 1| u1-1| 1| u1\r\n 2| 1| u1-2| 1| u1\r\n 3| 2| u2-1| 2| u2\r\n```\r\n\r\nWhen peewee iterates over the result rows, it sees columns named (id, user_id, content, id, username). The 2nd id corresponds to the user's id rather than the tweet id. You can fix this in a number of ways without needing to update peewee:\r\n\r\n1. Don't select the user's id.\r\n2. Alias the user's id to a different attribute.\r\n\r\nWith the patch I've just pushed (80a2048837100c102d5387366cb1a5531739cb91) it should no longer be a problem, because:\r\n\r\n1. Instead of putting all attributes onto the selected model when a UNION is present, attempt to resolve the model graph. So the user's \"id\" and \"username\" would be put on Tweet.user (e.g. tweet.user.id, tweet.user.username).\r\n2. When returning a flat result, do not overwrite attrs. So \"id\" in your example would be the tweet id since that's the first \"id\" column we see. The 2nd user \"id\" would not be stored.",
"Got it. Looks like 3.2.4 works for me. Thanks!"
] | 2018-04-18T17:54:29 | 2018-04-19T14:45:35 | 2018-04-19T14:45:35 | NONE | null | When I union two queries that are selecting multiple models, the IDs seem to be confused (actually any column with the same name):
```python
query = Tweet.select(Tweet, User).join(User).where(User.id == 1)
query2 = Tweet.select(Tweet, User).join(User)
union = query | query2
for t in union:
print(t.id)
```
Outputs `1` twice, where I would expect `1` followed by `2`. I've only tested on sqlite with latest 3.x release of peewee. Am I doing something wrong? This worked in the last 2.x release I tested. | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1579/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/1579/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1578 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1578/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1578/comments | https://api.github.com/repos/coleifer/peewee/issues/1578/events | https://github.com/coleifer/peewee/issues/1578 | 315,473,483 | MDU6SXNzdWUzMTU0NzM0ODM= | 1,578 | Move playhouse module as a submodule on peewee? | {
"login": "vadimkantorov",
"id": 1041752,
"node_id": "MDQ6VXNlcjEwNDE3NTI=",
"avatar_url": "https://avatars.githubusercontent.com/u/1041752?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/vadimkantorov",
"html_url": "https://github.com/vadimkantorov",
"followers_url": "https://api.github.com/users/vadimkantorov/followers",
"following_url": "https://api.github.com/users/vadimkantorov/following{/other_user}",
"gists_url": "https://api.github.com/users/vadimkantorov/gists{/gist_id}",
"starred_url": "https://api.github.com/users/vadimkantorov/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/vadimkantorov/subscriptions",
"organizations_url": "https://api.github.com/users/vadimkantorov/orgs",
"repos_url": "https://api.github.com/users/vadimkantorov/repos",
"events_url": "https://api.github.com/users/vadimkantorov/events{/privacy}",
"received_events_url": "https://api.github.com/users/vadimkantorov/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"This is simply how peewee is organized. Peewee is a standalone python module and all extras/extensions are included in a separate namespace.",
"I see your point. My suggestion was to move naming in the direction of making `playhouse` module name more related to peewee. A middle ground may be `peweeplayhouse`?",
"It's been this way since ... 2010? I'm not too interested in changing it."
] | 2018-04-18T13:12:33 | 2018-04-18T14:39:36 | 2018-04-18T13:46:47 | NONE | null | Finding in source code something like `import playhouse.shortcuts` is not very specific or self-explaining IMO.
A big leap would be moving at least some functions like `model_to_dict` / `dict_to_model` to stock peewee, but even making them `peewee.playhouse.model_to_dict` would be more discoverable.
Thanks for a great package!
| {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1578/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/1578/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1577 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1577/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1577/comments | https://api.github.com/repos/coleifer/peewee/issues/1577/events | https://github.com/coleifer/peewee/issues/1577 | 315,302,680 | MDU6SXNzdWUzMTUzMDI2ODA= | 1,577 | Column name conflict | {
"login": "biskit",
"id": 1078732,
"node_id": "MDQ6VXNlcjEwNzg3MzI=",
"avatar_url": "https://avatars.githubusercontent.com/u/1078732?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/biskit",
"html_url": "https://github.com/biskit",
"followers_url": "https://api.github.com/users/biskit/followers",
"following_url": "https://api.github.com/users/biskit/following{/other_user}",
"gists_url": "https://api.github.com/users/biskit/gists{/gist_id}",
"starred_url": "https://api.github.com/users/biskit/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/biskit/subscriptions",
"organizations_url": "https://api.github.com/users/biskit/orgs",
"repos_url": "https://api.github.com/users/biskit/repos",
"events_url": "https://api.github.com/users/biskit/events{/privacy}",
"received_events_url": "https://api.github.com/users/biskit/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"Right, so you named a column the same as a classmethod.\r\n\r\nThe workaround here is to:\r\n\r\n```python\r\nclass Foo(Model):\r\n update = TimestampField() # uh-oh.\r\n\r\n# do this instead:\r\nclass Foo(Model):\r\n update_ = TimestampField(column_name='update') # added \"_\" to avoid name conflict.\r\n```\r\n\r\nI suppose I can add this to the docs as well.",
"A document update would be extremely helpful. Not sure how one can find it there, but atleast one may get lucky.",
"For sure, there's starting to be a bit of sprawl in the docs. If you had suggestions for re-organizing I'd be open to any ideas.\r\n\r\nAdded a note in the bottom of the \"Fields\" sub-section (after creating custom field).",
"I was getting that feeling too. One has to balance verbosity with tersity and finding that spot is hard. I'm bad at documentation, but there's nothing like more documentation (just more maintenance :-). \r\nWish I had some out-of-the-box ideas..."
] | 2018-04-18T02:04:50 | 2018-04-18T02:22:52 | 2018-04-18T02:14:54 | NONE | null | This one left me scratching my head till trial and error found it.
1. Create a table with a column name 'update' - OK
2. Create a record - OK
2. Query a record - OK
3. Update a record - Not OK. Messages are extremely confusing from 'TypeError: 'str' object is not callable' to 'TypeError: 'unicode' object is not callable' to what not.
If this is documented somewhere, please disregard this. | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1577/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/1577/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1576 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1576/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1576/comments | https://api.github.com/repos/coleifer/peewee/issues/1576/events | https://github.com/coleifer/peewee/issues/1576 | 315,109,828 | MDU6SXNzdWUzMTUxMDk4Mjg= | 1,576 | Joins are shared after clone | {
"login": "bison",
"id": 240676,
"node_id": "MDQ6VXNlcjI0MDY3Ng==",
"avatar_url": "https://avatars.githubusercontent.com/u/240676?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/bison",
"html_url": "https://github.com/bison",
"followers_url": "https://api.github.com/users/bison/followers",
"following_url": "https://api.github.com/users/bison/following{/other_user}",
"gists_url": "https://api.github.com/users/bison/gists{/gist_id}",
"starred_url": "https://api.github.com/users/bison/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/bison/subscriptions",
"organizations_url": "https://api.github.com/users/bison/orgs",
"repos_url": "https://api.github.com/users/bison/repos",
"events_url": "https://api.github.com/users/bison/events{/privacy}",
"received_events_url": "https://api.github.com/users/bison/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"Some quick testing revealed a bug in the cloning of the from-list and the join dictionaries. Pushed a fix.",
"For what it's worthy, queries should be immutable -- so no need to call clone():\r\n\r\n```python\r\nquery = Tweet.select()\r\nnew_query = query.join(User)\r\n# query -> select * from tweet\r\n# new_query -> select * from tweet join user\r\n```"
] | 2018-04-17T15:21:16 | 2018-04-17T19:15:31 | 2018-04-17T16:34:58 | NONE | null | On latest 3.x release (haven't tested others), the list of joins appears to be shared between queries after calling clone:
```python
query = Tweet.select()
new_query = query.clone()
new_query.join(User)
print(query.sql())
print(new_query.sql())
```
Outputs:
```
('SELECT "t1"."id", "t1"."user_id", "t1"."text" FROM "tweet" AS "t1" INNER JOIN "user" AS "t2" ON ("t1"."user_id" = "t2"."id")', [])
('SELECT "t1"."id", "t1"."user_id", "t1"."text" FROM "tweet" AS "t1" INNER JOIN "user" AS "t2" ON ("t1"."user_id" = "t2"."id")', [])
``` | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1576/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/1576/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1575 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1575/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1575/comments | https://api.github.com/repos/coleifer/peewee/issues/1575/events | https://github.com/coleifer/peewee/issues/1575 | 315,061,743 | MDU6SXNzdWUzMTUwNjE3NDM= | 1,575 | Can ManyToManyField support "self" | {
"login": "1xinghuan",
"id": 33982538,
"node_id": "MDQ6VXNlcjMzOTgyNTM4",
"avatar_url": "https://avatars.githubusercontent.com/u/33982538?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/1xinghuan",
"html_url": "https://github.com/1xinghuan",
"followers_url": "https://api.github.com/users/1xinghuan/followers",
"following_url": "https://api.github.com/users/1xinghuan/following{/other_user}",
"gists_url": "https://api.github.com/users/1xinghuan/gists{/gist_id}",
"starred_url": "https://api.github.com/users/1xinghuan/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/1xinghuan/subscriptions",
"organizations_url": "https://api.github.com/users/1xinghuan/orgs",
"repos_url": "https://api.github.com/users/1xinghuan/repos",
"events_url": "https://api.github.com/users/1xinghuan/events{/privacy}",
"received_events_url": "https://api.github.com/users/1xinghuan/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"You're _much_ better off just doing this:\r\n\r\n```python\r\n\r\nclass User(ModelBase):\r\n name = CharField()\r\n class Meta:\r\n table_name = 'users'\r\n\r\nclass Relationship(ModelBase):\r\n from_user = ForeignKeyField(User, backref='following')\r\n to_user = ForeignKeyField(User, backref='followers')\r\n```"
] | 2018-04-17T13:32:47 | 2018-04-17T13:44:26 | 2018-04-17T13:44:13 | NONE | null | Is that possible to use ManyToManyField in such way:
```
class User(ModelBase):
name = CharField(column_name='NAME', null=False)
followers = ManyToManyField("self", backref="following")
class Meta:
db_table = 'users'
```
Then it can create a table like "user_user_through" | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1575/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/1575/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1574 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1574/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1574/comments | https://api.github.com/repos/coleifer/peewee/issues/1574/events | https://github.com/coleifer/peewee/issues/1574 | 314,604,714 | MDU6SXNzdWUzMTQ2MDQ3MTQ= | 1,574 | ArrayField equals queries | {
"login": "tuukkamustonen",
"id": 94327,
"node_id": "MDQ6VXNlcjk0MzI3",
"avatar_url": "https://avatars.githubusercontent.com/u/94327?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/tuukkamustonen",
"html_url": "https://github.com/tuukkamustonen",
"followers_url": "https://api.github.com/users/tuukkamustonen/followers",
"following_url": "https://api.github.com/users/tuukkamustonen/following{/other_user}",
"gists_url": "https://api.github.com/users/tuukkamustonen/gists{/gist_id}",
"starred_url": "https://api.github.com/users/tuukkamustonen/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/tuukkamustonen/subscriptions",
"organizations_url": "https://api.github.com/users/tuukkamustonen/orgs",
"repos_url": "https://api.github.com/users/tuukkamustonen/repos",
"events_url": "https://api.github.com/users/tuukkamustonen/events{/privacy}",
"received_events_url": "https://api.github.com/users/tuukkamustonen/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"You might try using `Param` or `Passthrough` around your list, e.g.\r\n\r\n```python\r\n.where(MyModel.field == Passthrough(['element', 'another']))\r\n```",
"In peewee 3.x, for what it's worth, it's not necessary to use a wrapper around the value, you can express the equality as you'd expect:\r\n\r\n```python\r\nquery = SomeModel.get(SomeModel.array_field == ['foo', 'bar', 'baz'])\r\n```",
"> ```python\r\n> .where(MyModel.field == Passthrough(['element', 'another']))\r\n> ```\r\n\r\nThis indeed does the trick, interesting. I was using `Clause` as a workaround, but `Passthrough`/`Param` (both work) makes it a bit cleaner and safer.\r\n\r\nWill definitively upgrade to 3 soon. Thanks.",
"Actually, maybe I could ask in which (other) cases do we need `Param`/`Passthrough`? Docs don't mention them.\r\n\r\nOr are these completely removed in 3.x? **Edit:** seems so as they're not found in ``peewee.py`` anymore.",
"Removed in 3.x. For 2.x you'll want to use it in places where you're passing a non-scalar type (like a list or something) to a database driver that understands those types...i.e., psycopg2 understands lists and dicts."
] | 2018-04-16T11:11:47 | 2018-04-16T20:42:16 | 2018-04-16T18:36:58 | NONE | null | How do you query [ArrayField](http://docs.peewee-orm.com/en/latest/peewee/playhouse.html#ArrayField) for equal list comparison like:
```sql
... WHERE field = ARRAY['element', 'another'];
```
`.where(MyModel.field == ['element', 'another'])` produces:
```sql
WHERE (\"field\" = (ARRAY['e', 'l', 'e', 'm', 'e', 'n', 't']::TEXT[], ARRAY['a', 'n', 'o', 't', 'h', 'e', 'r']::TEXT[]))
```
(Still using the oldish peewee `2.10.2`, sorry!) | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1574/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/1574/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1573 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1573/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1573/comments | https://api.github.com/repos/coleifer/peewee/issues/1573/events | https://github.com/coleifer/peewee/issues/1573 | 314,547,718 | MDU6SXNzdWUzMTQ1NDc3MTg= | 1,573 | UnboundLocalError: local variable 'constructor' referenced before assignment | {
"login": "raphael0202",
"id": 9609923,
"node_id": "MDQ6VXNlcjk2MDk5MjM=",
"avatar_url": "https://avatars.githubusercontent.com/u/9609923?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/raphael0202",
"html_url": "https://github.com/raphael0202",
"followers_url": "https://api.github.com/users/raphael0202/followers",
"following_url": "https://api.github.com/users/raphael0202/following{/other_user}",
"gists_url": "https://api.github.com/users/raphael0202/gists{/gist_id}",
"starred_url": "https://api.github.com/users/raphael0202/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/raphael0202/subscriptions",
"organizations_url": "https://api.github.com/users/raphael0202/orgs",
"repos_url": "https://api.github.com/users/raphael0202/repos",
"events_url": "https://api.github.com/users/raphael0202/events{/privacy}",
"received_events_url": "https://api.github.com/users/raphael0202/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"When calling `switch()` you need to pass the model you are switching the context to. The error message is not very helpful, but you should change your code in this manner:\r\n\r\n```python\r\n.join(User).switch(PlatformBridge).join(Bot)\r\n```",
"I've also amended the implementation of `switch()` so that when called with no parameters it will default to switching to the query's model.",
"Ok, thank you for the quick response!"
] | 2018-04-16T08:27:56 | 2018-04-16T15:26:49 | 2018-04-16T13:32:16 | NONE | null | This error occurs on Peewee 3.1.1, after an upgrade from Peewee 2.9.3.
Here is quick script that reproduces the error:
```import peewee
class Bot(BaseModel):
name = peewee.CharField(max_length=30, index=True)
class User(BaseModel):
original_id = peewee.CharField(max_length=50, null=True)
class PlatformBridge(BaseModel):
bot = peewee.ForeignKeyField(Bot, backref='platform_bridges')
user = peewee.ForeignKeyField(User, backref='platform_bridges')
PlatformBridge.select(PlatformBridge, User, Bot).join(User).switch().join(Bot)
```
with `BaseModel` being a base class where the db connection is configured.
The stacktrace:
```
Traceback (most recent call last):
File "test.py", line 14, in <module>
PlatformBridge.select(PlatformBridge, User, Bot).join(User).switch().join(Bot)
File "/opt/likeabot/virtualenv/lib/python3.5/site-packages/peewee.py", line 569, in inner
method(clone, *args, **kwargs)
File "/opt/likeabot/virtualenv/lib/python3.5/site-packages/peewee.py", line 5634, in join
on, attr, constructor = self._normalize_join(src, dest, on, attr)
File "/opt/likeabot/virtualenv/lib/python3.5/site-packages/peewee.py", line 5628, in _normalize_join
return (on, attr, constructor)
UnboundLocalError: local variable 'constructor' referenced before assignment
```
on Python 3.5.2. | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1573/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/1573/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1572 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1572/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1572/comments | https://api.github.com/repos/coleifer/peewee/issues/1572/events | https://github.com/coleifer/peewee/issues/1572 | 314,426,290 | MDU6SXNzdWUzMTQ0MjYyOTA= | 1,572 | Duplicate AS clause in SQL when aliasing a function call | {
"login": "Terrance",
"id": 4025899,
"node_id": "MDQ6VXNlcjQwMjU4OTk=",
"avatar_url": "https://avatars.githubusercontent.com/u/4025899?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/Terrance",
"html_url": "https://github.com/Terrance",
"followers_url": "https://api.github.com/users/Terrance/followers",
"following_url": "https://api.github.com/users/Terrance/following{/other_user}",
"gists_url": "https://api.github.com/users/Terrance/gists{/gist_id}",
"starred_url": "https://api.github.com/users/Terrance/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/Terrance/subscriptions",
"organizations_url": "https://api.github.com/users/Terrance/orgs",
"repos_url": "https://api.github.com/users/Terrance/repos",
"events_url": "https://api.github.com/users/Terrance/events{/privacy}",
"received_events_url": "https://api.github.com/users/Terrance/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"Thanks for reporting, I'll take a look.",
"Fixed, thanks.",
"Works great, thanks for the quick response! 🙂"
] | 2018-04-15T15:41:50 | 2018-04-16T07:20:04 | 2018-04-16T02:42:14 | NONE | null | I have two tables -- `User`, and `Data` which references users. When querying, I add a property on the user result for whether any data rows reference that user (in reality there's other metadata attached here too):
```python
class User(Model):
...
@classmethod
def select_context(cls):
return (cls.select(cls, fn.Exists(Data.select()
.where(Data.user == User.id))
.alias("exists")))
```
Running that query using APSW on Peewee 3.x gives me `apsw.SQLError: SQLError: near "AS": syntax error`, but this seemed to work fine on 2.x.
SQL example in Peewee 2.10.2:
```python
>>> User.select(User.id, fn.Exists(Data.select()).alias("exists")).sql()
('SELECT "t1"."id", Exists(SELECT "t2"."id" FROM "data" AS t2) AS exists FROM "user" AS t1', [])
```
And in 3.x (tested with 3.0.0 and 3.2.2), note two `AS` clauses for `exists`:
```python
>>> User.select(User.id, fn.Exists(Data.select()).alias("exists")).sql()
('SELECT "t1"."id", Exists(SELECT "t2"."id" FROM "data" AS "t2") AS "t3" AS "exists" FROM "user" AS "t1"', [])
```
I had a look through the 3.0 changes but couldn't see anything obvious that applies here? | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1572/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/1572/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1571 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1571/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1571/comments | https://api.github.com/repos/coleifer/peewee/issues/1571/events | https://github.com/coleifer/peewee/issues/1571 | 314,098,488 | MDU6SXNzdWUzMTQwOTg0ODg= | 1,571 | Compare dates | {
"login": "loukash",
"id": 2196038,
"node_id": "MDQ6VXNlcjIxOTYwMzg=",
"avatar_url": "https://avatars.githubusercontent.com/u/2196038?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/loukash",
"html_url": "https://github.com/loukash",
"followers_url": "https://api.github.com/users/loukash/followers",
"following_url": "https://api.github.com/users/loukash/following{/other_user}",
"gists_url": "https://api.github.com/users/loukash/gists{/gist_id}",
"starred_url": "https://api.github.com/users/loukash/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/loukash/subscriptions",
"organizations_url": "https://api.github.com/users/loukash/orgs",
"repos_url": "https://api.github.com/users/loukash/repos",
"events_url": "https://api.github.com/users/loukash/events{/privacy}",
"received_events_url": "https://api.github.com/users/loukash/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"Fix problem_1\r\n```\r\n\t@hybrid_method\r\n\tdef is_valid(self):\r\n\t\treturn (self.not_after > datetime.now()) & (self.not_before < datetime.now())\r\n```\r\n`Cert.select().where(Cert.is_valid() == True)`",
"Here is perhaps a cleaner way of implementing `is_valid()`:\r\n\r\n```python\r\n\r\n @hybrid_property\r\n def is_valid(cls):\r\n n = datetime.datetime.now()\r\n return self.not_before <= n <= self.not_after\r\n\r\n @is_valid.expression\r\n def is_valid(self):\r\n now = SQL('current_timestamp')\r\n return (self.not_before <= now) & (self.not_after >= now)\r\n```\r\n\r\nAs far as \"valid_for\", you can pass a `datetime.timedelta` to Peewee and it should do the right thing:\r\n\r\n```python\r\n\r\n @hybrid_property\r\n def valid_for(self):\r\n return (self.not_after - datetime.datetime.now()).days\r\n\r\n @valid_for.expression\r\n def valid_for(self):\r\n return fn.AGE(self.end)\r\n\r\nquery = Cert.select().where(Cert.valid_for > datetime.timedelta(days=99))\r\n```\r\n\r\nDoes that address your problem? Also note you do not need to write \"== True\" in your expressions.",
"@coleifer Thank you :)"
] | 2018-04-13T13:01:49 | 2018-04-13T14:15:24 | 2018-04-13T14:15:24 | NONE | null | My model:
```
class Cert(db.Model):
not_before = DateTimeField();
not_after = DateTimeField();
@hybrid_property
def is_valid(self):
return True if (self.not_after > datetime.now()) and (self.not_before <= datetime.now()) else False
@hybrid_property
def valid_for(self):
return (self.not_after - datetime.now()).days
@valid_for.expression
def valid_for(cls):
return fn.AGE(cls.not_after)
@is_valid.expression
def is_valid(cls):
return True if (cls.not_after - fn.SELECT(SQL('localtimestamp')) > 0) and (fn.SELECT(SQL('localtimestamp') - cls.not_before) <= 0) else False
```
I use expression based on "virtual" fields.
1st problem:
```
query = Cert.select().where(Cert.is_valid == True)
('SELECT "t1"."id", "t1"."not_before", "t1"."not_after" FROM "cert" AS "t1" WHERE %s', [True])
```
2nd problem:
```
query = Cert.select().where(Cert.valid_for > 99)
('SELECT "t1"."id", "t1"."not_before", "t1"."not_after" FROM "cert" AS "t1" WHERE (AGE("t1"."not_after") > %s)', [99])
No operator matches the given name and argument type(s). You might need to add explicit type casts.
```
99 is int. How I can set it as postgresql interval? (interval '99 day')
Where is my mistakes? | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1571/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/1571/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1570 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1570/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1570/comments | https://api.github.com/repos/coleifer/peewee/issues/1570/events | https://github.com/coleifer/peewee/issues/1570 | 313,955,660 | MDU6SXNzdWUzMTM5NTU2NjA= | 1,570 | "return_id_list" should be mentioned in 3.0 backwards-incompatible changes. | {
"login": "aniketpanjwani",
"id": 16311215,
"node_id": "MDQ6VXNlcjE2MzExMjE1",
"avatar_url": "https://avatars.githubusercontent.com/u/16311215?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/aniketpanjwani",
"html_url": "https://github.com/aniketpanjwani",
"followers_url": "https://api.github.com/users/aniketpanjwani/followers",
"following_url": "https://api.github.com/users/aniketpanjwani/following{/other_user}",
"gists_url": "https://api.github.com/users/aniketpanjwani/gists{/gist_id}",
"starred_url": "https://api.github.com/users/aniketpanjwani/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/aniketpanjwani/subscriptions",
"organizations_url": "https://api.github.com/users/aniketpanjwani/orgs",
"repos_url": "https://api.github.com/users/aniketpanjwani/repos",
"events_url": "https://api.github.com/users/aniketpanjwani/events{/privacy}",
"received_events_url": "https://api.github.com/users/aniketpanjwani/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"Ahh, you're right, sorry I missed that. I can add it."
] | 2018-04-13T03:15:07 | 2018-04-13T03:59:59 | 2018-04-13T03:59:59 | NONE | null | In 2.x, there was a "return_id_list" method for Postgresql by which you could get back the new ids created through "insert_many". It appears that this has been replaced with a more general "returning" method.
However, neither change is documented in the "Changes in 3.0" page. Happy to make a PR myself, but I just wanted to confirm first that you agreed with my assessment.
Cheers! | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1570/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/1570/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1569 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1569/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1569/comments | https://api.github.com/repos/coleifer/peewee/issues/1569/events | https://github.com/coleifer/peewee/issues/1569 | 313,951,554 | MDU6SXNzdWUzMTM5NTE1NTQ= | 1,569 | ImproperlyConfigured: MySQL driver not installed! | {
"login": "MatthewKosloski",
"id": 1219553,
"node_id": "MDQ6VXNlcjEyMTk1NTM=",
"avatar_url": "https://avatars.githubusercontent.com/u/1219553?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/MatthewKosloski",
"html_url": "https://github.com/MatthewKosloski",
"followers_url": "https://api.github.com/users/MatthewKosloski/followers",
"following_url": "https://api.github.com/users/MatthewKosloski/following{/other_user}",
"gists_url": "https://api.github.com/users/MatthewKosloski/gists{/gist_id}",
"starred_url": "https://api.github.com/users/MatthewKosloski/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/MatthewKosloski/subscriptions",
"organizations_url": "https://api.github.com/users/MatthewKosloski/orgs",
"repos_url": "https://api.github.com/users/MatthewKosloski/repos",
"events_url": "https://api.github.com/users/MatthewKosloski/events{/privacy}",
"received_events_url": "https://api.github.com/users/MatthewKosloski/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"Peewee will work with `pymysql` or `mysql-python`. It sounds like you have an issue with your module-import path. This is not an issue with Peewee -- I'd suggest trying StackOverflow.",
"`mysqlclient` is recommend",
"So for mysql:\r\n\r\n* [pymysql](https://github.com/PyMySQL/PyMySQL) is a pure-python mysql client, works with python 2 and 3. Peewee will use attempt to use pymysql first.\r\n* [mysqlclient](https://github.com/PyMySQL/mysqlclient-python) uses a c extension and supports python 3. It exposes a `MySQLdb` module. Peewee will attempt to use this module if pymysql is not installed.\r\n* `mysql-python` is also called [MySQLdb1](https://github.com/farcepest/MySQLdb1) and is legacy and should not be used. Since this shares the same module name as mysqlclient, same applies.\r\n* [mysql-connector python](https://github.com/mysql/mysql-connector-python) pure-python (I think??) supports python 3. To use this driver you can use `playhouse.mysql_ext.MySQLConnectorDatabase`.",
"@weaming mysqlclient did not seem to work in my case.\r\n@coleifer -- `pymysql` worked without issue on first attempt.\r\nThanks!",
"> @weaming mysqlclient did not seem to work in my case.\r\n> @coleifer -- `pymysql` worked without issue on first attempt.\r\n> Thanks!\r\n\r\n`mysqlclient` further depends on some other dependencies, as stated in the [official doc](https://github.com/PyMySQL/mysqlclient-python), . It depends on which OS you are using, slight difference between macOS and Ubuntu, for instance."
] | 2018-04-13T02:47:04 | 2020-11-09T03:28:17 | 2018-04-13T03:16:35 | NONE | null | Hey, guys. I'm trying to connect to my remote MySQL database using Peewee, but I am getting the following error (in a virtual environment):
```
Traceback (most recent call last):
File "peewee_test.py", line 2, in <module>
from student import Student
File "/Users/Matthew/Desktop/python-mvc/student.py", line 10, in <module>
db.connect()
File "/Users/Matthew/Desktop/python-mvc/lib/python3.6/site-packages/peewee.py", line 2467, in connect
self._state.set_connection(self._connect())
File "/Users/Matthew/Desktop/python-mvc/lib/python3.6/site-packages/peewee.py", line 3164, in _connect
raise ImproperlyConfigured('MySQL driver not installed!')
peewee.ImproperlyConfigured: MySQL driver not installed!
```
student.py
```
from peewee import *
db = MySQLDatabase(
host='host_here',
user='mysql_username_here',
password='mysql_password_here',
database='mysql_db_here'
)
db.connect()
class Student(Model):
firstName = CharField()
lastName = CharField()
class Meta:
database = db
```
peewee_test.py
```
from peewee import *
from student import Student
john_doe = Student.create(
firstName='John',
lastName='Doe',
is_relative=False
)
```
I installed MySQL via Homebrew. This is the version I have:
```
mysql Ver 14.14 Distrib 5.7.12, for osx10.10 (x86_64) using EditLine wrapper
```
I also installed `PyMySQL` as others have suggested [here](https://github.com/coleifer/peewee/issues/390#issuecomment-48612520). Others also suggested installing `mysql-python`, but I get an error when when attempting to install it:
```
Collecting mysql-python
Using cached MySQL-python-1.2.5.zip
Complete output from command python setup.py egg_info:
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "/private/var/folders/m7/wyjxzv8s5sdbh2jr35tq55y00000gn/T/pip-build-xh7783h6/mysql-python/setup.py", line 13, in <module>
from setup_posix import get_config
File "/private/var/folders/m7/wyjxzv8s5sdbh2jr35tq55y00000gn/T/pip-build-xh7783h6/mysql-python/setup_posix.py", line 2, in <module>
from ConfigParser import SafeConfigParser
ModuleNotFoundError: No module named 'ConfigParser'
----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in /private/var/folders/m7/wyjxzv8s5sdbh2jr35tq55y00000gn/T/pip-build-xh7783h6/mysql-python/
```
I have two installations of Python on My Mac (running OSX 10.10): Python 2.7 and 3.6. I'm using `pip3` to install the above packages.
Thank you for your time! | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1569/reactions",
"total_count": 4,
"+1": 4,
"-1": 0,
"laugh": 0,
"hooray": 0,
"confused": 0,
"heart": 0,
"rocket": 0,
"eyes": 0
} | https://api.github.com/repos/coleifer/peewee/issues/1569/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1568 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1568/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1568/comments | https://api.github.com/repos/coleifer/peewee/issues/1568/events | https://github.com/coleifer/peewee/issues/1568 | 313,757,916 | MDU6SXNzdWUzMTM3NTc5MTY= | 1,568 | migration: Default value is set to non-unique value with add_column even if field needs uniqueness | {
"login": "ccosby",
"id": 194775,
"node_id": "MDQ6VXNlcjE5NDc3NQ==",
"avatar_url": "https://avatars.githubusercontent.com/u/194775?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/ccosby",
"html_url": "https://github.com/ccosby",
"followers_url": "https://api.github.com/users/ccosby/followers",
"following_url": "https://api.github.com/users/ccosby/following{/other_user}",
"gists_url": "https://api.github.com/users/ccosby/gists{/gist_id}",
"starred_url": "https://api.github.com/users/ccosby/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/ccosby/subscriptions",
"organizations_url": "https://api.github.com/users/ccosby/orgs",
"repos_url": "https://api.github.com/users/ccosby/repos",
"events_url": "https://api.github.com/users/ccosby/events{/privacy}",
"received_events_url": "https://api.github.com/users/ccosby/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"Interesting... so what you're running into is -- you'd like to add a new, non-nullable, unique field with a dynamic default. The migrator's `apply_default()` helper is implemented such that, if the field's default is callable, it is only called once:\r\n\r\n```python\r\n def apply_default(self, table, column_name, field):\r\n default = field.default\r\n if callable(default):\r\n default = default()\r\n\r\n return (self.make_context()\r\n .literal('UPDATE ')\r\n .sql(Entity(table))\r\n .literal(' SET ')\r\n .sql(Expression(\r\n Entity(column_name),\r\n OP.EQ,\r\n field.db_value(default),\r\n flat=True)))\r\n```\r\n\r\nI'm leery of changing this to run a separate UPDATE for every row that may already exist in the table.\r\n\r\nI'd propose instead that you do something like this:\r\n\r\n1. use migrator to add the field (non-unique and nullable)\r\n2. in a transaction/loop update the existing rows\r\n3. use migrator to make field not-null and add a unique index on it.\r\n\r\nWDYT?",
"Your suggestion is in fact what I did. LMK if you ever want to address it in peewee official.\r\n\r\n```python\r\nmigrator = MySQLMigrator(db)\r\n\r\nclass StrUUIDField(peewee.CharField):\r\n def db_value(self, value):\r\n if isinstance(value, uuid.UUID):\r\n return value.hex\r\n try:\r\n return uuid.UUID(value).hex\r\n except (TypeError, ValueError):\r\n return value\r\n\r\n def python_value(self, value):\r\n if isinstance(value, uuid.UUID):\r\n return value.hex\r\n return None if value is None else uuid.UUID(value).hex\r\n \r\ndef add_unique_column(model, field_name='uuid', field_default=uuid.uuid4):\r\n \"\"\"Add uuid field to a given model type.\r\n This is here because calling add_column calls apply_default, resulting in every row\r\n getting the same initial value. Not good when you want a unique value.\r\n \"\"\"\r\n\r\n # First add the column with null as the default value. No indexes.\r\n field_definition = StrUUIDField(null=True, index=False, unique=False)\r\n migrate(\r\n migrator.add_column(model._meta.table_name, field_name, field_definition),\r\n )\r\n\r\n # Update every row with a unique uuid\r\n for inst in model.select(model.id):\r\n setattr(inst, field_name, field_default() if callable(field_default) else field_default)\r\n inst.save()\r\n\r\n # Now set the column to NOT NULL and create the unique index\r\n migrate(\r\n migrator.add_not_null(model._meta.table_name, field_name),\r\n migrator.add_index(model._meta.table_name, (field_name,), unique=True)\r\n )\r\n```",
"I think I'll pass but will keep this in mind should it come up again. Thanks for sharing your implementation.",
"For what it's worth, I too ran into this and was confused by the behavior.\r\n\r\nIf the migrator's `apply_default()` determines that the default is callable (i.e., dynamic), isn't caching the value breaking the expectation of the user?\r\n\r\nI understand the reason for passing on this implementation, but it would be helpful to throw a warning or error explaining this limitation (or even pointing them to this issue!)\r\n"
] | 2018-04-12T14:42:14 | 2020-05-05T07:06:05 | 2018-04-12T16:10:49 | NONE | null | https://github.com/coleifer/peewee/blob/449450d738a8c8f2893e5309d03d03bc249e9d7e/playhouse/migrate.py#L273
This is the migrate() equivalent of https://github.com/coleifer/peewee/issues/429
When using playhouse.migrate.SchemaMigrator.add_column() with field.default set to a callable and field.unique=True, more work has to be done to create a unique value for every row. This will be slow for big tables, but is necessary for UUIDs and things of that ilk.
If you think there's enough need for this, I'll spend some time on it. If not, just close this issue with a note stating so.
| {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1568/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/1568/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1567 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1567/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1567/comments | https://api.github.com/repos/coleifer/peewee/issues/1567/events | https://github.com/coleifer/peewee/issues/1567 | 313,562,518 | MDU6SXNzdWUzMTM1NjI1MTg= | 1,567 | PooledDatabase's reuse_if_open setting is not working | {
"login": "axiaoxin",
"id": 2876405,
"node_id": "MDQ6VXNlcjI4NzY0MDU=",
"avatar_url": "https://avatars.githubusercontent.com/u/2876405?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/axiaoxin",
"html_url": "https://github.com/axiaoxin",
"followers_url": "https://api.github.com/users/axiaoxin/followers",
"following_url": "https://api.github.com/users/axiaoxin/following{/other_user}",
"gists_url": "https://api.github.com/users/axiaoxin/gists{/gist_id}",
"starred_url": "https://api.github.com/users/axiaoxin/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/axiaoxin/subscriptions",
"organizations_url": "https://api.github.com/users/axiaoxin/orgs",
"repos_url": "https://api.github.com/users/axiaoxin/repos",
"events_url": "https://api.github.com/users/axiaoxin/events{/privacy}",
"received_events_url": "https://api.github.com/users/axiaoxin/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"And the usage of \r\n \r\n with db:\r\n do_some_query()\r\n\r\nstill raise the MySQL gone away error",
"f0a6f11aea19089af34befed2dab886706e1593a",
"\r\nWhy the super class of PooledDatabase is object? there is no connect function. dose the super class is Database? ",
"`PooledDatabase` is used in multi-class inheritance later on in the module."
] | 2018-04-12T03:17:48 | 2018-04-12T12:48:28 | 2018-04-12T04:21:15 | NONE | null | https://github.com/coleifer/peewee/blob/master/playhouse/pool.py#L122
the reuse_if_open params is no used | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1567/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/1567/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1566 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1566/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1566/comments | https://api.github.com/repos/coleifer/peewee/issues/1566/events | https://github.com/coleifer/peewee/issues/1566 | 313,516,108 | MDU6SXNzdWUzMTM1MTYxMDg= | 1,566 | Migration leaves out foreign key constraint | {
"login": "csytan",
"id": 16357,
"node_id": "MDQ6VXNlcjE2MzU3",
"avatar_url": "https://avatars.githubusercontent.com/u/16357?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/csytan",
"html_url": "https://github.com/csytan",
"followers_url": "https://api.github.com/users/csytan/followers",
"following_url": "https://api.github.com/users/csytan/following{/other_user}",
"gists_url": "https://api.github.com/users/csytan/gists{/gist_id}",
"starred_url": "https://api.github.com/users/csytan/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/csytan/subscriptions",
"organizations_url": "https://api.github.com/users/csytan/orgs",
"repos_url": "https://api.github.com/users/csytan/repos",
"events_url": "https://api.github.com/users/csytan/events{/privacy}",
"received_events_url": "https://api.github.com/users/csytan/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"As far as I know sqlite doesn't support adding constraints. Can you try executing the equivalent alter table query and see what happens?",
"Sure thing. It looks like `ALTER TABLE` works with the `ON DELETE` clause:\r\n\r\n```\r\n~/dev$ sqlite3 testdb\r\nSQLite version 3.19.3 2017-06-27 16:48:08\r\nEnter \".help\" for usage hints.\r\nsqlite> PRAGMA foreign_keys = ON;\r\nsqlite>\r\nsqlite> CREATE TABLE IF NOT EXISTS \"table\" (\r\n ...> id INTEGER PRIMARY KEY AUTOINCREMENT\r\n ...> );\r\nsqlite>\r\nsqlite> ALTER TABLE \"table\" ADD COLUMN \"fk\" INTEGER REFERENCES \"table\"(id) ON DELETE SET NULL;\r\nsqlite>\r\nsqlite> .schema table\r\nCREATE TABLE IF NOT EXISTS \"table\" (\r\n id INTEGER PRIMARY KEY AUTOINCREMENT\r\n, \"fk\" INTEGER REFERENCES \"table\"(id) ON DELETE SET NULL);\r\nsqlite>\r\n```\r\n\r\n",
"I believe this should be fixed in 449450d738a8c8f2893e5309d03d03bc249e9d7e",
"Added test-case which shows the \"ON DELETE\" bits are being carried-over into the migration. Thanks for reporting.",
"Thanks @coleifer. I've tested on master and it's working correctly now 👍"
] | 2018-04-11T22:58:16 | 2018-04-12T16:33:45 | 2018-04-12T14:41:24 | NONE | null | When adding a foreign key column using `playhouse.migrate`, the foreign key constraint is missing from the updated table schema. Here's some test code:
## 1. Create a test table with a working foreign key
```
# Using peewee==3.2.2
import peewee
from playhouse import migrate
database = peewee.SqliteDatabase('testdb')
database.connect()
class Table(peewee.Model):
old_foreign_key = peewee.ForeignKeyField('self', null=True, on_delete='SET NULL')
class Meta:
database = database
database.create_tables([
Table
], safe=True)
database.close()
```
## 2. Add a foreign key to the test table
```
my_db = migrate.SqliteDatabase('testdb')
migrator = migrate.SqliteMigrator(my_db)
with my_db.transaction():
field = migrate.ForeignKeyField(
Table, field=Table.id, null=True, on_delete='SET NULL')
migrate.migrate(
migrator.add_column('table', 'new_foreign_key', field)
)
migrator.database.close()
```
## Results
Foreign key constraint is missing for the `new_foreign_key`. Expecting a `FOREIGN KEY ("new_foreign_key_id") REFERENCES "table" ("id") ON DELETE SET NULL)` clause.
<img width="682" alt="screen shot 2018-04-11 at 3 52 43 pm" src="https://user-images.githubusercontent.com/16357/38647310-740cc2ae-3da0-11e8-8c03-30fee5c0f1be.png">
| {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1566/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/1566/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1565 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1565/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1565/comments | https://api.github.com/repos/coleifer/peewee/issues/1565/events | https://github.com/coleifer/peewee/issues/1565 | 312,575,702 | MDU6SXNzdWUzMTI1NzU3MDI= | 1,565 | Model.create() option to skip saving immediately | {
"login": "vadimkantorov",
"id": 1041752,
"node_id": "MDQ6VXNlcjEwNDE3NTI=",
"avatar_url": "https://avatars.githubusercontent.com/u/1041752?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/vadimkantorov",
"html_url": "https://github.com/vadimkantorov",
"followers_url": "https://api.github.com/users/vadimkantorov/followers",
"following_url": "https://api.github.com/users/vadimkantorov/following{/other_user}",
"gists_url": "https://api.github.com/users/vadimkantorov/gists{/gist_id}",
"starred_url": "https://api.github.com/users/vadimkantorov/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/vadimkantorov/subscriptions",
"organizations_url": "https://api.github.com/users/vadimkantorov/orgs",
"repos_url": "https://api.github.com/users/vadimkantorov/repos",
"events_url": "https://api.github.com/users/vadimkantorov/events{/privacy}",
"received_events_url": "https://api.github.com/users/vadimkantorov/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"Well... you can wrap your operations in a transaction, using `atomic()`. `atomic()` is a context-manager or decorator, but if you want to use it in the above middleware-type API, you should be able to:\r\n\r\n```python\r\n\r\nclass TransactionPerRequest(object):\r\n def process_request(self, req, resp):\r\n req._txn = self.db.atomic()\r\n req._txn.__enter__()\r\n\r\n def process_response(self, req, resp, resource):\r\n if not self.db.is_closed():\r\n req._txn.__exit__(None, None, None)\r\n self.db.close()\r\n\r\n def __init__(self, db):\r\n self.db = db\r\n```",
"Will this also prevent (non-null, etc) constraints from being validated on creation time? A way to enable a delay to actual saving time would be great.",
"> Will this also prevent (non-null, etc) constraints from being validated on creation time?\r\n\r\nIt should, as the INSERTs are executed -- they are simply executed in a transaction which is not committed until the `atomic` block exits (which is in the process_response example).\r\n\r\nIf you're trying to postpone actually inserting the records (and dealing with any integrity-errors, etc) -- I'd suggest using a Queue and pushing the models into it, then at the end of the request consume the queue and save all the models."
] | 2018-04-09T15:23:20 | 2018-04-11T19:58:26 | 2018-04-11T19:58:25 | NONE | null | From what I can see in the source code, there is no option to postpone saving:
https://github.com/coleifer/peewee/blob/master/peewee.py#L5160
How do I postpone saving? I wish to do some object modification and having a single db request would be more economical.
Should I wrap the `create` call in `db.atomic()`? Like in https://github.com/coleifer/peewee/blob/master/peewee.py#L5214
Currently I wrap it with the following falcon-middleware:
```python
class TransactionPerRequest(object):
def process_request(self, req, resp):
self.db.connect()
self.db.begin()
def process_response(self, req, resp, resource):
if not self.db.is_closed():
self.db.commit()
self.db.close()
def __init__(self, db):
self.db = db
```
but the model is not updated, unless `save()` is called explicitly again after `create()`.
Thanks! | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1565/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/1565/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1564 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1564/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1564/comments | https://api.github.com/repos/coleifer/peewee/issues/1564/events | https://github.com/coleifer/peewee/issues/1564 | 312,122,863 | MDU6SXNzdWUzMTIxMjI4NjM= | 1,564 | Convenient way to select random records from union | {
"login": "vegeta1k95",
"id": 32207817,
"node_id": "MDQ6VXNlcjMyMjA3ODE3",
"avatar_url": "https://avatars.githubusercontent.com/u/32207817?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/vegeta1k95",
"html_url": "https://github.com/vegeta1k95",
"followers_url": "https://api.github.com/users/vegeta1k95/followers",
"following_url": "https://api.github.com/users/vegeta1k95/following{/other_user}",
"gists_url": "https://api.github.com/users/vegeta1k95/gists{/gist_id}",
"starred_url": "https://api.github.com/users/vegeta1k95/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/vegeta1k95/subscriptions",
"organizations_url": "https://api.github.com/users/vegeta1k95/orgs",
"repos_url": "https://api.github.com/users/vegeta1k95/repos",
"events_url": "https://api.github.com/users/vegeta1k95/events{/privacy}",
"received_events_url": "https://api.github.com/users/vegeta1k95/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"```python\r\ns1 = SomeModel.select().where(...)\r\ns2 = SomeModel.select().where(...)\r\nquery = (s1 & s2).order_by(fn.RANDOM())\r\n```",
"@coleifer \r\nWhenever I'm trying to iterate through this new query or make a list I get error:\r\n```\r\npeewee.OperationalError: 1st ORDER BY term does not match any column in the result set\r\n```\r\nDoes `ModelCompoundSelectQuery` support iterations?",
"What database are you using?\r\n\r\nAnd yes, it supports iteration. The error is in the SQL query.",
"I use mostly `SqliteQueueDatabase` from `playhouse.sqliteq`.\r\nBut I also tried this with standard `SqliteDatabase` and got the same error.\r\nPeewee version: `3.2.2`, Python `3.6.3`",
"This works:\r\n\r\n```python\r\nclass Register(BaseModel):\r\n value = IntegerField()\r\n\r\nclass Data(BaseModel):\r\n key = TextField()\r\n\r\ndb.create_tables([Register, Data])\r\n\r\nfor i in range(10):\r\n Register.create(value=i)\r\n\r\nfor k in range(10):\r\n Data.create(key='k%s' % k)\r\n\r\ndata = Data.select(fn.RANDOM(), Data)\r\nreg = Register.select(fn.RANDOM(), Register)\r\nunion = (data | reg).order_by(SQL('1'))\r\nfor row in union.tuples():\r\n print(row)\r\n```\r\n\r\nBasically it selects a random value and uses it as the first column in each query. Then in the union query, we order all results by the first column (a random value)."
] | 2018-04-06T21:21:26 | 2018-04-07T17:20:55 | 2018-04-07T17:20:23 | NONE | null | Suppose there are two `SELECT` queries that can't be joined into one by joining `WHERE` clauses for some reason.
Is there any way to get their random ordered union?
Example:
Both this
```
s1 = SomeModel.select().where( some_condition1 )
s2 = SomeModel.select().where( some_condition2 )
s3 = (s1 & s2).order_by(fn.Random())
```
and this
```
s1 = SomeModel.select().where( some_condition1 ).ordered_by(fn.Random())
s2 = SomeModel.select().where( some_condition2 ).ordered_by(fn.Random())
s3 = (s1 & s2)
```
raise error:
```
peewee.OperationalError: 1st ORDER BY term does not match any column in the result set
```
**My current workaround:**
```
import random
s1 = SomeModel.select().where( some_condition1 )
s2 = SomeModel.select().where( some_condition2 )
s3 = (s1 & s2)
s3_list = list(s3)
random.shuffle(s3_list)
``` | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1564/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/1564/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1563 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1563/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1563/comments | https://api.github.com/repos/coleifer/peewee/issues/1563/events | https://github.com/coleifer/peewee/issues/1563 | 312,089,707 | MDU6SXNzdWUzMTIwODk3MDc= | 1,563 | Foreign keys must specify a `rel_field` | {
"login": "csytan",
"id": 16357,
"node_id": "MDQ6VXNlcjE2MzU3",
"avatar_url": "https://avatars.githubusercontent.com/u/16357?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/csytan",
"html_url": "https://github.com/csytan",
"followers_url": "https://api.github.com/users/csytan/followers",
"following_url": "https://api.github.com/users/csytan/following{/other_user}",
"gists_url": "https://api.github.com/users/csytan/gists{/gist_id}",
"starred_url": "https://api.github.com/users/csytan/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/csytan/subscriptions",
"organizations_url": "https://api.github.com/users/csytan/orgs",
"repos_url": "https://api.github.com/users/csytan/repos",
"events_url": "https://api.github.com/users/csytan/events{/privacy}",
"received_events_url": "https://api.github.com/users/csytan/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"The error message is out-of-date. The parameter name is \"field\" (no \"rel_\"). It refers to the field on the model your FK points to - typically the primary key.",
"```\r\n# e.g., to reference the \"id\" field of ServiceCategory:\r\nForeignKeyField(db.ServiceCategory, db.ServiceCategory.id, null=True, on_delete='SET NULL')\r\n```"
] | 2018-04-06T19:25:10 | 2018-04-06T19:48:48 | 2018-04-06T19:47:07 | NONE | null | Hi Charles,
Thank you for your excellent library 🙌
I'm trying to do some migrations by adding a ForeignKeyField, but I'm getting this error:
https://github.com/coleifer/peewee/blob/master/playhouse/migrate.py#L264
I couldn't find any documentation on what the `rel_field` is supposed to be.
## Code
```
with my_db.transaction():
migrate.migrate(
migrator.add_column('service', 'parent', peewee.ForeignKeyField(
db.ServiceCategory, null=True, on_delete='SET NULL'))
)
```
```
ValueError: Foreign keys must specify a `rel_field`.
```
## After adding a `rel_field`
```
with my_db.transaction():
migrate.migrate(
migrator.add_column('service', 'parent', peewee.ForeignKeyField(
db.ServiceCategory, rel_field='servicecategory', null=True, on_delete='SET NULL'))
)
```
```
Traceback (most recent call last):
File "run.py", line 179, in <module>
db.migrations.run()
File "/Users/csytan/Documents/dev/cozycal/db/migrations/__init__.py", line 18, in run
importlib.import_module('db.migrations.{}'.format(version))
File "/usr/local/Cellar/python/3.6.5/Frameworks/Python.framework/Versions/3.6/lib/python3.6/importlib/__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 994, in _gcd_import
File "<frozen importlib._bootstrap>", line 971, in _find_and_load
File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 665, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 678, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "/Users/csytan/Documents/dev/cozycal/db/migrations/51.py", line 11, in <module>
db.ServiceCategory, rel_field='servicecategory', null=True, on_delete='SET NULL'))
File "/Users/csytan/Library/Python/3.6/lib/python/site-packages/peewee.py", line 4127, in __init__
super(ForeignKeyField, self).__init__(*args, **kwargs)
TypeError: __init__() got an unexpected keyword argument 'rel_field'
```
| {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1563/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/1563/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1562 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1562/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1562/comments | https://api.github.com/repos/coleifer/peewee/issues/1562/events | https://github.com/coleifer/peewee/pull/1562 | 312,052,823 | MDExOlB1bGxSZXF1ZXN0MTgwMDA2MDg3 | 1,562 | Update api.rst for Sqlitedatabase inheritance | {
"login": "Declan1984",
"id": 8843918,
"node_id": "MDQ6VXNlcjg4NDM5MTg=",
"avatar_url": "https://avatars.githubusercontent.com/u/8843918?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/Declan1984",
"html_url": "https://github.com/Declan1984",
"followers_url": "https://api.github.com/users/Declan1984/followers",
"following_url": "https://api.github.com/users/Declan1984/following{/other_user}",
"gists_url": "https://api.github.com/users/Declan1984/gists{/gist_id}",
"starred_url": "https://api.github.com/users/Declan1984/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/Declan1984/subscriptions",
"organizations_url": "https://api.github.com/users/Declan1984/orgs",
"repos_url": "https://api.github.com/users/Declan1984/repos",
"events_url": "https://api.github.com/users/Declan1984/events{/privacy}",
"received_events_url": "https://api.github.com/users/Declan1984/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"Thanks I'll pass on this for now. It'd be nice if the python domain of ReST supported this type of annotation but I couldn't find it."
] | 2018-04-06T17:17:58 | 2018-04-06T18:15:26 | 2018-04-06T18:15:26 | NONE | null | Adding an explicit indication that Sqlitedatabase inherits from Database; if proposed change is accepted, I can go into the other classes and add similar explicit reference. | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1562/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/1562/timeline | null | null | false | {
"url": "https://api.github.com/repos/coleifer/peewee/pulls/1562",
"html_url": "https://github.com/coleifer/peewee/pull/1562",
"diff_url": "https://github.com/coleifer/peewee/pull/1562.diff",
"patch_url": "https://github.com/coleifer/peewee/pull/1562.patch",
"merged_at": null
} |
https://api.github.com/repos/coleifer/peewee/issues/1561 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1561/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1561/comments | https://api.github.com/repos/coleifer/peewee/issues/1561/events | https://github.com/coleifer/peewee/pull/1561 | 311,987,399 | MDExOlB1bGxSZXF1ZXN0MTc5OTU3Mjcx | 1,561 | Made an AttributeError message more informative. | {
"login": "vsajip",
"id": 130553,
"node_id": "MDQ6VXNlcjEzMDU1Mw==",
"avatar_url": "https://avatars.githubusercontent.com/u/130553?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/vsajip",
"html_url": "https://github.com/vsajip",
"followers_url": "https://api.github.com/users/vsajip/followers",
"following_url": "https://api.github.com/users/vsajip/following{/other_user}",
"gists_url": "https://api.github.com/users/vsajip/gists{/gist_id}",
"starred_url": "https://api.github.com/users/vsajip/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/vsajip/subscriptions",
"organizations_url": "https://api.github.com/users/vsajip/orgs",
"repos_url": "https://api.github.com/users/vsajip/repos",
"events_url": "https://api.github.com/users/vsajip/events{/privacy}",
"received_events_url": "https://api.github.com/users/vsajip/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"Going to pass, thanks."
] | 2018-04-06T14:00:44 | 2018-04-06T14:14:20 | 2018-04-06T14:14:20 | NONE | null | If a stray keyword argument is passed to a `Model` initialisation, the resulting `AttributeError` message isn't particularly informative - it mentions neither the failing attribute nor the instance type affected. This change makes the error message more informative. | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1561/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/1561/timeline | null | null | false | {
"url": "https://api.github.com/repos/coleifer/peewee/pulls/1561",
"html_url": "https://github.com/coleifer/peewee/pull/1561",
"diff_url": "https://github.com/coleifer/peewee/pull/1561.diff",
"patch_url": "https://github.com/coleifer/peewee/pull/1561.patch",
"merged_at": null
} |
https://api.github.com/repos/coleifer/peewee/issues/1560 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1560/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1560/comments | https://api.github.com/repos/coleifer/peewee/issues/1560/events | https://github.com/coleifer/peewee/issues/1560 | 311,392,572 | MDU6SXNzdWUzMTEzOTI1NzI= | 1,560 | FTS with snippet/extract | {
"login": "rcarmo",
"id": 392683,
"node_id": "MDQ6VXNlcjM5MjY4Mw==",
"avatar_url": "https://avatars.githubusercontent.com/u/392683?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/rcarmo",
"html_url": "https://github.com/rcarmo",
"followers_url": "https://api.github.com/users/rcarmo/followers",
"following_url": "https://api.github.com/users/rcarmo/following{/other_user}",
"gists_url": "https://api.github.com/users/rcarmo/gists{/gist_id}",
"starred_url": "https://api.github.com/users/rcarmo/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/rcarmo/subscriptions",
"organizations_url": "https://api.github.com/users/rcarmo/orgs",
"repos_url": "https://api.github.com/users/rcarmo/repos",
"events_url": "https://api.github.com/users/rcarmo/events{/privacy}",
"received_events_url": "https://api.github.com/users/rcarmo/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"Try:\r\n\r\n```python\r\nfn.snippet(FTSPage._meta.entity).alias('extract')\r\n```",
"FTS5 is a completely different library, really. I'd suggest doing a very close reading of the fts5 sqlite documentation if you haven't already. Personally, I've gone back to FTS4 because FTS5 was just a bit problematic (especially dealing with special chars in search queries).",
"Thanks, `._meta.entity`did the trick (in the sense that now I have a logical error someplace else and an empty query result, but at least it runs). I was using 2.8.x, so I missed any doc updates in the meantime.\r\n\r\nAs to FTS5, I'll probably wait, then. I did check out the docs briefly, but since I need accented character support I'll to a test fork...\r\n\r\nThanks for the quick reply!",
"Well, feel free to share the model definitions and the query, be happy to try and troubleshoot.",
"Thanks, will check a few things first, since I need to validate what’s going in to the FTS table - will reply here if it’s not a content error...",
"This is the only page I can find discussing peewee and ```fts5``` ```snippet()``` on the web. Hope the following helps someone in the future, possibly me.\r\n\r\nI was able to get the snippet out of an ```FTS5Model``` class using the following:\r\n```fn.snippet(Record._meta.entity, 1, '<b>', '</b>', '...', 10).alias('snippet')```\r\n\r\nI am, however, doing as @coleifer and dropping ```FTS5Model``` for ```FTSModel``` with ```fts4.``` My reason is that I could not find a way to store unique records using ```FTS5Model``` but I know how to do it with ```FTSModel``` + ```Model```. It seems ```fts5```is not mature enough yet."
] | 2018-04-04T21:10:44 | 2018-08-01T01:34:51 | 2018-04-04T21:21:00 | CONTRIBUTOR | null | Hi there,
I'm porting an older bit of code to 3.x, and am having trouble with the following:
```python
query = (FTSPage.select(Page,
FTSPage,
fn.snippet(FTSPage.as_entity()).alias('extract'),
FTSPage.bm25().alias('score'))
.join(Page)
.where(FTSPage.match(qstring))
.order_by(SQL('score').desc())
.order_by(Page.mtime.desc())
.limit(limit))
```
This allows me to render an extract of the match document, but breaks in 3.x. I read through the `Entity` documentation, and tried using `Entity(FTSPage)`instead of `as_entity`, but clearly that is not the way to go here... Any pointers?
(Also, any hints regarding moving to FTS5 would be appreciated - the docs seem straightforward, but I suspect there will be some caveats) | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1560/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/1560/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1559 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1559/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1559/comments | https://api.github.com/repos/coleifer/peewee/issues/1559/events | https://github.com/coleifer/peewee/issues/1559 | 311,136,116 | MDU6SXNzdWUzMTExMzYxMTY= | 1,559 | Support type hints in model fields | {
"login": "tuukkamustonen",
"id": 94327,
"node_id": "MDQ6VXNlcjk0MzI3",
"avatar_url": "https://avatars.githubusercontent.com/u/94327?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/tuukkamustonen",
"html_url": "https://github.com/tuukkamustonen",
"followers_url": "https://api.github.com/users/tuukkamustonen/followers",
"following_url": "https://api.github.com/users/tuukkamustonen/following{/other_user}",
"gists_url": "https://api.github.com/users/tuukkamustonen/gists{/gist_id}",
"starred_url": "https://api.github.com/users/tuukkamustonen/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/tuukkamustonen/subscriptions",
"organizations_url": "https://api.github.com/users/tuukkamustonen/orgs",
"repos_url": "https://api.github.com/users/tuukkamustonen/repos",
"events_url": "https://api.github.com/users/tuukkamustonen/events{/privacy}",
"received_events_url": "https://api.github.com/users/tuukkamustonen/received_events",
"type": "User",
"site_admin": false
} | [] | closed | true | null | [] | null | [
"I think type hints are misguided and unpythonic, and it's my stance that they will never be supported by peewee. Python is a high-level dynamic language, peewee plays to these strengths. You couldn't implement peewee in go, it'd look completely different.\r\n\r\nI enjoy statically typed languages. When I want static typing I use c or go. When I want dynamic or metaprogramming I use python.\r\n\r\nThese are my opinions and I understand that others have their own views. My goals for peewee are to make it composable and consistent, and I feel I can do that best by using python's dynamism.",
"I understand your clause fully, just note that type hints could be supported where dynamic python magic is not needed. Plus in this case the library itself wouldn't imbue type hints - it would just support users declaring them. That would require changes (ie. something like what I suggested above) and I understand that you're reluctant to add that. Anyway, if you (or anyone here) comes up with a simpler idea, chime in.\r\n\r\nMaybe I'll ask about this on mypy tracker as well. I'll ping back here if there's any further insight.",
"@tuukkamustonen oh I've just got your proposition. I'ts cludgy. I come to something like User.c.name (stealed from sqlalchemy). My temporary solution is to turn off typing in queries or cast User.name to any (sadly python have no typescript-style casts like (obj as any) for that purpose, but we have `cast()` function, heh)",
"@tuukkamustonen, @enomado can you share a snippet of code of how you \"by pass\" mypy errors.\r\nI'm stuck on this\r\n```\r\nmodel/__init__.py:5: error: Cannot find module named 'peewee'\r\nmodel/__init__.py:17: error: Name 'SqliteDatabase' is not defined\r\nmodel/__init__.py:20: error: Name 'Model' is not defined\r\nmodel/__init__.py:26: error: Name 'IntegerField' is not defined\r\nmodel/__init__.py:27: error: Name 'IntegerField' is not defined\r\n```\r\n",
"Well I could silence `mypy` creating a very simple local `peewee.pyi` , for my needs:\r\nstubs/peewee.pyi\r\n```\r\nimport typing\r\n\r\nclass Field:\r\n def __init__(self, **kwargs) -> None: ...\r\n\r\nclass CharField(Field): ...\r\n\r\nclass IntegerField(Field): ...\r\n\r\nclass DateField(Field): ...\r\n\r\nclass Model:\r\n def __init__(self, **kwargs) -> None: ...\r\n\r\nclass SqliteDatabase:\r\n def __init__(self, *args, **kwargs) -> None: ...\r\n```\r\n\r\nand tested with: \r\n```\r\n$ MYPYPATH=stubs/ mypy combs.py\r\n``` \r\n\r\nAt the end it seems with can add a simple peewee `mypy` silencer to https://github.com/python/typeshed\r\n\r\n",
"Static type check is great tool and like unit test and code coverage you don't have to check it all.\r\n\r\nSome kind of developers, like me, need all the help from tools that we can have.\r\n\r\nTo me type annotations is more useful than normal doc comments. It forces me to have them updated and follow type hints PEP 484 specs.\r\n\r\nPython dynamism is great for create flexible libs, frameworks and tools like `peewee`. But in everyday jobs too much flexibility could be a problem, Type-Driven Development help me to be centered on the task.\r\n",
"@bySabi I think your problem is different than what we discussed here? You had:\r\n\r\n> ```\r\n> model/__init__.py:5: error: Cannot find module named 'peewee'\r\n> ```\r\n\r\nThat probably just tells that your (virtual)environment/PYTHONPATH is somehow messed up, because it's not finding `peewee` at all, thus giving errors also for stuff imported from it? You shouldn't be getting those errors in the first place.\r\n\r\nI don't think this issue can be handled through type stubs (`.pyi`s) as you still cannot provide different types for instance variable vs. class variable, something like `ClassInstanceVar` (see https://github.com/python/mypy/issues/1097 for discussion, there's also a hacky solution by @enomado).",
"@tuukkamustonen it's possible that I missed something on `mypy` settings but virtual env is working fine when the project is runned.\r\n\r\nI think the problem with objects: SqliteDatabase, Model, IntergerField ... it's because they were imported using `from peewee import *` and that's why I could not apply `ignore_missing_imports` mypy setting on `peewee`. Lesson learned! : - )\r\n\r\nIn the end I could solve it using above `peewee.pyi` stub file.\r\n\r\nAnd your are right, my typing hint problem don't have nothing to do with this issue. But anyway annotate models with types IMO is lot of duplicate work cause peewee type Fields (IntergerField, CharField, ...) will do the typecheck/validation at runtime.\r\n\r\n\r\n\r\n\r\n\r\n\r\n",
"I would also like to request this, because it helps with code completion.\r\n\r\nFor example, consider the code:\r\n\r\n my_user = User.select().first()\r\n\r\nThis returns a <Model: User>, but it would be great if it type hinted to a User object, because on the next line of code, I would get a list of functions available to user (for example, if the User class had a function ```user_function()```, I would see user_function() in the list of suggestions in the code completion hints. I know that I can specify this using # type: User, but I'd prefer it be automatic.\r\n\r\nAlso, is it possible to specify a return collection type? For example, in SQLAlchemy, I can do something like \r\n\r\n orders = relationship(\"Order\", back_populates=\"user\", collection_class=Orders) # type: Orders\r\n\r\nand the orders will be returned as an Orders object, which is a custom class object that inherits from InstrumentedList. This allows me to add special functions, such as .most_recent(), .to_df(), etc..."
] | 2018-04-04T08:40:52 | 2021-06-13T17:04:05 | 2018-04-04T11:22:46 | NONE | null | Being aware that you don't like type hints (#1298), I'll be bold and ask if you would allow users to annotate their models with type hints?
Problem:
```python
class User(peewee.Model):
name = CharField()
u = User()
u.name = 'Joe' # mypy will nag because inferred type is 'CharField'
```
Cannot:
```python
class User(peewee.Model):
name = CharField() # type: str
u = User()
u.name = 'Joe' # sure works now but
User.select().where(User.name.id == 1) # violation as User.name is marked as 'str'
```
Would it be possible to have separate fields for class and instance:
```python
class User(peewee.Model):
name_c = CharField(instance_field='name')
name = None # type: str - simply a placeholder for mypy type
name: str # in py3.6+
u = User()
u.name = 'Joe' # would now have 'str' type
User.select().where(User.name_c.id == 1) # would have 'CharField' type
```
The idea being that instance would override the `name` field with getter/setter (declared as `instance_field`).
Yeah it is hackish, but it would be better than having to `# type: <override>` everywhere.
I believe this couldn't go to typeshed stubs anyway due to being context-specific.
| {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1559/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/1559/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1558 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1558/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1558/comments | https://api.github.com/repos/coleifer/peewee/issues/1558/events | https://github.com/coleifer/peewee/issues/1558 | 310,694,782 | MDU6SXNzdWUzMTA2OTQ3ODI= | 1,558 | insert_many fails on sqlite 3.6.20 | {
"login": "binrush",
"id": 3984423,
"node_id": "MDQ6VXNlcjM5ODQ0MjM=",
"avatar_url": "https://avatars.githubusercontent.com/u/3984423?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/binrush",
"html_url": "https://github.com/binrush",
"followers_url": "https://api.github.com/users/binrush/followers",
"following_url": "https://api.github.com/users/binrush/following{/other_user}",
"gists_url": "https://api.github.com/users/binrush/gists{/gist_id}",
"starred_url": "https://api.github.com/users/binrush/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/binrush/subscriptions",
"organizations_url": "https://api.github.com/users/binrush/orgs",
"repos_url": "https://api.github.com/users/binrush/repos",
"events_url": "https://api.github.com/users/binrush/events{/privacy}",
"received_events_url": "https://api.github.com/users/binrush/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"Correct, SQLite began supporting multi-value INSERT statements in 3.7.11, which was released over 6 years ago: http://sqlite.org/releaselog/3_7_11.html\r\n\r\nFor simplicity, Peewee 3.0 no longer includes this workaround. You can, of course, write your code to process the INSERTs in a loop (which is all 2.x did)."
] | 2018-04-03T05:01:13 | 2018-04-03T12:09:41 | 2018-04-03T12:09:41 | NONE | null | Hi! Thank you for your great project.
On peewee version 3.2.2, I'm trying to use insert_many with sqite 3.6.20:
```python
import peewee as pw
import logging
logging.basicConfig(level=logging.DEBUG)
db = pw.SqliteDatabase(':memory:')
class TestTable(pw.Model):
id = pw.PrimaryKeyField()
data = pw.TextField()
class Meta:
database = db
db.create_tables([TestTable])
TestTable.insert_many([{'id': 1, 'data': 'one'}, {'id': 2, 'data': 'two'}]).execute()
```
But I get error, because sqlite 3.6.20 does not support multiple inserts syntax:
```
---------------------------------------------------------------------------
OperationalError Traceback (most recent call last)
~/pe-ve/lib/python3.5/site-packages/peewee.py in execute_sql(self, sql, params, commit)
2519 try:
-> 2520 cursor.execute(sql, params or ())
2521 except Exception:
OperationalError: near ",": syntax error
```
Dump of queries peewee executes:
```
DEBUG:peewee:('CREATE TABLE IF NOT EXISTS "testtable" ("id" INTEGER NOT NULL PRIMARY KEY, "data" TEXT NOT NULL)', [])
DEBUG:peewee:('INSERT INTO "testtable" ("id", "data") VALUES (?, ?), (?, ?)', [1, 'one', 2, 'two'])
```
In older peewee version (2.8.3), in such cases peewee dropped to multiple inserts instead (it had bug with on_conflict clause though). Was this compatibility dropped by some reason? | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1558/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/1558/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1557 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1557/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1557/comments | https://api.github.com/repos/coleifer/peewee/issues/1557/events | https://github.com/coleifer/peewee/issues/1557 | 310,387,707 | MDU6SXNzdWUzMTAzODc3MDc= | 1,557 | «Connection already open» when trying to get data from session_interface in flask | {
"login": "ak4nv",
"id": 73960,
"node_id": "MDQ6VXNlcjczOTYw",
"avatar_url": "https://avatars.githubusercontent.com/u/73960?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/ak4nv",
"html_url": "https://github.com/ak4nv",
"followers_url": "https://api.github.com/users/ak4nv/followers",
"following_url": "https://api.github.com/users/ak4nv/following{/other_user}",
"gists_url": "https://api.github.com/users/ak4nv/gists{/gist_id}",
"starred_url": "https://api.github.com/users/ak4nv/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/ak4nv/subscriptions",
"organizations_url": "https://api.github.com/users/ak4nv/orgs",
"repos_url": "https://api.github.com/users/ak4nv/repos",
"events_url": "https://api.github.com/users/ak4nv/events{/privacy}",
"received_events_url": "https://api.github.com/users/ak4nv/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"When you use the `FlaskDB` helper class, it automatically registers two callbacks with Flask:\r\n\r\n* before_request() -- open the database connection\r\n* teardown_request() -- close the database connection\r\n\r\nMy guess is that when the `before_request()` callback fires, it's raising an exception because the database connection was already opened previously...most likely by your session-store implementation.\r\n\r\nIf you intend to use a database-backed session-store, I'd suggest that you don't use `FlaskDB` and manage the connections yourself (by registering your own `before_request` and `teardown_request` handlers). Or alternatively you could move to a connection-pooled database and handle opening/closing the session-store connections in the session store?\r\n\r\nAt any rate, I'm not familiar with how flask's session stuff is implemented, there may be hooks or other ways to work around this.",
"@coleifer year, I understand this. I just wanna say it worked fine on oldier versions of peewee.\r\nBTW, does peewee connect automatically if you execute first query without calling `database.connect()` method?\r\nJust wanna override handlers like this:\r\n```python\r\ndef connect_db(self):\r\n if self.database.is_closed():\r\n self.database.connect()\r\n\r\ndef close_db(self, exc):\r\n if not self.database.is_closed():\r\n self.database.close()\r\n\r\n```",
"Yea peewee will automatically open a connection in that case."
] | 2018-04-02T03:53:01 | 2018-04-04T11:07:19 | 2018-04-02T14:02:54 | NONE | null | Hi!
I'm trying to get session data from table in my custom session interface in Flask and I'm getting the error `Connection already open`.
Here is a code sample
```python
import peewee as pw
from flask import Flask, jsonify
from flask.sessions import SessionInterface, SessionMixin
from werkzeug.datastructures import CallbackDict
from playhouse.flask_utils import FlaskDB
from playhouse.sqlite_ext import JSONField
from datetime import datetime
app = Flask(__name__)
db = FlaskDB(app, 'sqliteext:///test_db.sqlite')
class Session(CallbackDict, SessionMixin):
def __init__(self, store={}):
def on_update(self):
self.modified = True
self._store = store
self.modified = False
CallbackDict.__init__(self, store.get('data', {}), on_update)
@classmethod
def find(cls, sid):
try:
store = SessionStore.get(sid=sid)
except SessionStore.DoesNotExist:
store = {}
return cls(store)
def save(self):
if hasattr(self._store, 'data') and self.modified:
self._store.data = self
self._store.save()
class MySI(SessionInterface):
null_session_class = Session
def open_session(self, app, request):
sid = request.cookies.get('sid')
return Session.find(sid) if sid else None
def save_session(self, app, session, response):
if session.modified:
session.save()
class SessionStore(db.Model):
sid = pw.CharField(primary_key=True)
data = JSONField()
expired = pw.DateTimeField(default=datetime.now)
class Meta:
table_name = 'sessions'
app.session_interface = MySI()
@app.route('/')
def main():
return jsonify(ok=1)
if __name__ == '__main__':
if not SessionStore.table_exists():
SessionStore.create_table()
app.run(debug=True)
```
And try this
```bash
$ curl -b sid=123 localhost:5000
```
With all latest version of flask and peewee
I played around a little bit with versions and I found 2.8.5 peewee version hasn't this issue. It appeared in 2.8.7
Python version is 3.6.4 | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1557/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/1557/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1556 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1556/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1556/comments | https://api.github.com/repos/coleifer/peewee/issues/1556/events | https://github.com/coleifer/peewee/issues/1556 | 310,365,075 | MDU6SXNzdWUzMTAzNjUwNzU= | 1,556 | IPField Design | {
"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 | [
"Mine does not support Python 2 tho... :thinking: ",
"Because the `ipaddress` is a Python 3.x-only module, I'm going to pass on any related modifications to the peewee `IPField`. I think it's perfectly fine for this functionality to continue existing in a third-party library like yours (until such time as Peewee drops python 2 support, which I don't have plans for but will probably happen at some point).\r\n\r\nThanks for sharing this with me, I wasn't aware of the `ipaddress` module and it looks very nice."
] | 2018-04-02T00:13:23 | 2018-04-02T13:54:24 | 2018-04-02T13:54:24 | NONE | null | Hello, about the Design of new Peewee `IPField`, I am the creator of a package `peewee-extra-fields`,
we have a similar Field for IP, I think we can tinker and collaborate for better on that field:
We have `IPAddressField` and `IPNetworkField` its features are:
- They use Native Pythons `ipaddress.IPv4Address` and `ipaddress.IPv4Network`
- They use IPv4 and IPv6 transparently.
- The can do checking whether or not two hosts are on the same subnet, iterating over all hosts in a particular subnet, checking whether or not a string represents a valid IP address or network definition, etc etc.
**Compare:**
Peewee:
```python
class IPField(BigIntegerField):
def db_value(self, val):
if val is not None:
return struct.unpack('!I', socket.inet_aton(val))[0]
def python_value(self, val):
if val is not None:
return socket.inet_ntoa(struct.pack('!I', val))
```
peewee-extra-fields:
```python
class IPAddressField(BigIntegerField):
def db_value(self, value: str) -> int:
if value and isinstance(value, (str, int)):
try:
ip_address(value)
except Exception as error:
raise ValueError(f"""{self.__class__.__name__} IP Value is
not a Valid IP v4 or v6 Address: {value} --> {error}.""")
else:
return int(ip_address(value)) # Valid IPv4Address/IPv6Address.
return value # is None.
def python_value(self, value: str) -> IPv4Address:
return ip_address(value) if value else value
```
My implementation is transparently Compatible with IPv6:
```python
>>> struct.unpack('!I', socket.inet_aton("fe80::12c3:7bff:fe92:9d4c"))[0]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
OSError: illegal IP address string passed to inet_aton
illegal IP address string passed to inet_aton
>>> int(ip_address("fe80::12c3:7bff:fe92:9d4c"))
338288524927261089655370957493906873676
>>> socket.inet_ntoa(struct.pack('!I', 338288524927261089655370957493906873676))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
struct.error: argument out of range
argument out of range
>>> str(ip_address("fe80::12c3:7bff:fe92:9d4c"))
'fe80::12c3:7bff:fe92:9d4c'
```
If you like it feel free to steal the code for Peewee itself, no problem.
If you dont like it feel free to Close this Issue, no problem.
:smile_cat: | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1556/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/1556/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1555 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1555/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1555/comments | https://api.github.com/repos/coleifer/peewee/issues/1555/events | https://github.com/coleifer/peewee/issues/1555 | 310,265,633 | MDU6SXNzdWUzMTAyNjU2MzM= | 1,555 | Default value with SQL and returns of Model.create | {
"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 | [
"> I know peewee not supported SQL default yet, but use constraints to instead of is ok\r\n\r\nThis is the correct way to implement server-side column defaults in Peewee.\r\n\r\nPostgres supports a `RETURNING` clause, so you can retrieve the server-created timestamp by specifying the timestamp column, as you have done. With SQLite and MySQL there is no option but to re-fetch the columns with a `SELECT` query.\r\n\r\nI've corrected the issue with passing the `Model` class in e6012b21daf9656076b46a7db5a6229d98e0f734 so if you pull the latest version you should be able to pass `Model` classes to returning.",
"@coleifer Wait, if we can't get results from SQLite and MySQL after inserted, how does a self-increasing primary key works? We don't even know the exact value.\r\n\r\nMy real case:\r\n```python\r\nclass User(BaseModel, BaseUser):\r\n id = BlobField(primary_key=True, constraints=[SQL(\"DEFAULT int2bytea(nextval('id_gen_seq'))\")])\r\n```\r\n",
"@coleifer\r\n\r\nHere's a new issue, looks like a bug about sequence:\r\ndb: PostgreSQL 9.6\r\n\r\n```python\r\ndb.execute_sql('''CREATE SEQUENCE IF NOT EXISTS user_count_seq NO MINVALUE NO MAXVALUE START 1 CACHE 1000 NO CYCLE;''')\r\n\r\nclass User2(Model):\r\n number = IntegerField(sequence='user_count_seq') \r\n\r\nUser2.create_table(safe=True)\r\n```\r\n\r\nCrashed:\r\n```\r\nTraceback (most recent call last):\r\n File \"D:\\ProgramData\\Anaconda3\\lib\\site-packages\\peewee.py\", line 2517, in execute_sql\r\n cursor.execute(sql, params or ())\r\npsycopg2.ProgrammingError: syntax error at or near \"NULL\"\r\nLINE 1: NULL\r\n```\r\n\r\nLet's look at SQL:\r\n```python\r\nprint(''.join(User2._schema._create_table()._sql))\r\n```\r\n\r\n```SQL\r\nCREATE TABLE IF NOT EXISTS \"user2\" (\"id\" SERIAL NOT NULL PRIMARY KEY, \"number\" INTEGER NOT NULL DEFAULT NEXTVAL('user_count_seq'))\r\n```\r\n\r\nEmmmm, SQL is right, so what's up?\r\n",
"Append:\r\n\r\n\r\n\r\n\r\n`params` is [None]",
"Temporary solution:\r\n\r\n```python\r\ndef get_user_count_seq():\r\n return db.execute_sql(\"select nextval('user_count_seq')\").fetchone()[0]\r\n\r\n\r\nclass User2(BaseModel):\r\n number = peewee.IntegerField(default=get_user_count_seq)\r\n\r\n\r\ndb.create_tables([User2])\r\n```\r\n",
"Sqlite has an API last_rowid() which returns the id of the last-inserted row. MySQL has a similar API. Postgres doesn't need one because it supports returning arbitrary values from the inserted row.",
"Let me take a look into the sql error.",
"Let me take a look into the sql error.",
"Fixed, pushed new release 3.2.2.",
"Good job!"
] | 2018-03-31T19:29:31 | 2018-04-01T17:27:27 | 2018-04-01T17:02:48 | NONE | null | I know peewee not supported SQL default yet, but use `constraints` to instead of is ok, for example:
```python
timestamp = DateTimeField(constraints=[SQL('DEFAULT CURRENT_TIMESTAMP')])
```
It works, but not perfect.
```python
from peewee import *
db = SqliteDatabase(":memory:")
class Test(Model):
timestamp = DateTimeField(constraints=[SQL('DEFAULT CURRENT_TIMESTAMP')])
class Meta:
db_table = 'test'
database = db
db.create_tables([Test], safe=True)
for i in range(5):
item = Test.create()
print("%r %r" % (item.id, item.timestamp))
get_ts = lambda x: x.timestamp
print(list(map(get_ts, Test.select().execute())))
```
Results:
```
1 None
2 None
3 None
4 None
5 None
[datetime.datetime(2018, 3, 31, 18, 55, 4), datetime.datetime(2018, 3, 31, 18, 55, 4), datetime.datetime(2018, 3, 31, 18, 55, 4), datetime.datetime(2018, 3, 31, 18, 55, 4), datetime.datetime(2018, 3, 31, 18, 55, 4)]
```
I thought the value of Test.timestamp is from default (None), not from db.
Is there a solution?
BTW: Actually I'm a postgres user, so i can use `Model.insert` to replace `Model.create`, and I found a bug here.
Document said: To select all columns from a particular table, you can simply pass in the Model class.
http://docs.peewee-orm.com/en/latest/peewee/querying.html?highlight=returning#returning-clause
But I got [] after pass Model class:
```python
ret = User.insert(**vals).returning(User).execute()
```
Get right results after pass all fields:
```python
User.insert(**vals).returning(*User._meta.fields.values()).execute()
```
My peewee version is 3.2.0
| {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1555/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/1555/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1554 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1554/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1554/comments | https://api.github.com/repos/coleifer/peewee/issues/1554/events | https://github.com/coleifer/peewee/issues/1554 | 309,551,094 | MDU6SXNzdWUzMDk1NTEwOTQ= | 1,554 | playhouse.postgres_ext.BinaryJSONField returns string | {
"login": "felipetrz",
"id": 568830,
"node_id": "MDQ6VXNlcjU2ODgzMA==",
"avatar_url": "https://avatars.githubusercontent.com/u/568830?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/felipetrz",
"html_url": "https://github.com/felipetrz",
"followers_url": "https://api.github.com/users/felipetrz/followers",
"following_url": "https://api.github.com/users/felipetrz/following{/other_user}",
"gists_url": "https://api.github.com/users/felipetrz/gists{/gist_id}",
"starred_url": "https://api.github.com/users/felipetrz/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/felipetrz/subscriptions",
"organizations_url": "https://api.github.com/users/felipetrz/orgs",
"repos_url": "https://api.github.com/users/felipetrz/repos",
"events_url": "https://api.github.com/users/felipetrz/events{/privacy}",
"received_events_url": "https://api.github.com/users/felipetrz/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"The JSONB code is tested, so if something were that badly broken it would certainly show up as a lot of test failures.\r\n\r\nAre you using `playhouse.postgres_ext.PostgresqlExtDatabase` instead of the generic `peewee.PostgresqlDatabase`?",
"Sorry, the bug was actually with peewee-moves, that wasn't creating the table with the correct field type."
] | 2018-03-28T22:13:00 | 2018-03-29T20:08:08 | 2018-03-29T15:26:30 | NONE | null | When I store data in a postgres JSONB field using the provided field type, it should be accessed as a dict/list object when I retrieve it. Instead it's being returned as a string. | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1554/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/1554/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1553 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1553/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1553/comments | https://api.github.com/repos/coleifer/peewee/issues/1553/events | https://github.com/coleifer/peewee/issues/1553 | 309,531,153 | MDU6SXNzdWUzMDk1MzExNTM= | 1,553 | Pwiz does not generate column defaults | {
"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 | [
"I'm curious what this patch would entail...feel free to submit but I can't make any guarantees about merging.",
"I am not sure whether any defaults extracted from the schema itself should be translated into Python defaults. Enforcement at the schema level is different than at the application level.\r\n\r\nLooking at postgres output:\r\n\r\n```# \\d eventlog\r\n Table \"public.eventlog\"\r\n Column | Type | Modifiers \r\n-----------+-----------------------------+-------------------------------------------------------\r\n id | integer | not null default nextval('eventlog_id_seq'::regclass)\r\n timestamp | timestamp without time zone | not null default CURRENT_TIMESTAMP\r\n data | text | not null\r\n```\r\n\r\nOutput of:\r\n\r\n```sql\r\nselect column_name, ordinal_position, column_default, is_nullable, data_type\r\nfrom information_schema.columns \r\nwhere table_name='eventlog';\r\n\r\n column_name | ordinal_position | column_default | is_nullable | data_type \r\n-------------+------------------+--------------------------------------+-------------+-----------------------------\r\n id | 1 | nextval('eventlog_id_seq'::regclass) | NO | integer\r\n timestamp | 2 | CURRENT_TIMESTAMP | NO | timestamp without time zone\r\n data | 3 | | NO | text\r\n(3 rows)\r\n```\r\n\r\nLooking at this output, we'd want to ignore the `nextval(...)` for the \"id\" column, since this is just the auto-generated sequence. As for the `CURRENT_TIMESTAMP`, this raises the question...would this be translated to `default=datetime.datetime.now`, or more correctly listed as a column constraint, e.g.:\r\n\r\n```python\r\ntimestamp = DateTImeField(constraints=[SQL('DEFAULT CURRENT_TIMESTAMP')])\r\n```",
"Well, I can see the problem as highlighted for postgres. \r\n\r\nFor the rest, I propose just doing the bare minimum to get it working for the simple data types, float, integers, datetime(as proposed above).\r\n\r\nMy thoughts are that for anyone who is using peewee for extended testing, the db schema generated by the using create_tables should be the same as an original schema taken and then having the models file created by pwiz. ie.\r\n\r\ndb1 -> pwiz -> models.py\r\nmodels.py > create_tables < db2\r\ndb2 == db1 \r\nas close as possible.\r\n\r\nIf both db1 and db2 are generated by the peewee file, then sure, they are likely equal, but if the above process is used, they might be different.\r\nI'm more partial to Sqlite and MySQL since those are what I use.",
"> For the rest, I propose just doing the bare minimum to get it working for the simple data types, float, integers, datetime(as proposed above).\r\n\r\nDoing something halfway can often lead to a worse result than not doing it at all.\r\n\r\nI'm also still not sure whether the default column values should be expressed as constraints (which is more \"correct\") or as application-level Python defaults. Implementing them as server constraints would preserve the symmetry between introspection -> models.py -> create_tables(), but might also lead to undesired application-level behavior since the server-side defaults may not be communicated back to the application layer.\r\n\r\nFor simple values like string/numeric constants I think it might be better to implement them as application-level Python defaults. For functions/expressions like `CURRENT_TIMESTAMP` (or `now()` in postgres), it would be tempting to try and convert these to a Python equivalent like `datetime.datetime.now`, wherever possible... But doing this at the application level would break the symmetry between the reflected db and the schema peewee would create with the introspected models.",
"I've got a sample patch that captures the server-side constraint and preserves it as a column constraint: 93ad80375f23181cac71836c81097b4ba8f09957",
"Another option occurred to me, which is to let the user decide by specifying command-line options...e.g. `--server-defaults` and `--python-defaults` or something.",
"Well, dang it bro, that was fast. I was hoping to use this as my \"chance\" to say I've worked on something open source by contributing to the code, but hey, I guess some other time.\r\n\r\nAnyway, server defaults I think \"should\" already be permanent. The python defaults at such a point don't mean much then.\r\n\r\nUse case: if we are running tests on an empty DB, for whatever reason, the testing schema should be close to reflected as possible. That's the challenge I face.",
"In what situation would server side defaults not be communicated back to the application layer after introspection -> models -> create table? ",
"Well, let's say you have a timestamp column that defaults to the current timestamp. If you create a model instance without specifying the timestamp, letting the db determine the value, the timestamp for the new row is not communicated back to the application. You'd need to re-fetch the value from the newly-inserted row to get the timestamp. This isn't necessarily true with Postgres, which supports the `RETURNING` clause, but something to be aware of.",
"As far as `pwiz`, it is more intended to save you time when starting to use peewee with an existing database. So the assumption is that you'll fill in the `default` settings, etc, and use the generated code as a starting point rather than the final thing.\r\n\r\nFor a test database, you shouldn't need to use pwiz since presumably your application already has all the models?",
"a66c54c now includes change to capture server-side defaults.",
"Cool!\r\n\r\nBy the way, this issue was generated by the recommended method in the testing section of [the documentation](http://docs.peewee-orm.com/en/latest/peewee/database.html), where it is recommended \r\n\r\n> As an aside, and speaking from experience, I recommend testing your application using the same database backend you use in production, so as to avoid any potential compatibility issues.\r\n\r\nAnd in the example:\r\n`\r\n test_db.connect()\r\n test_db.create_tables(MODELS)`",
"That's right... I don't see where `pwiz` would enter into the equation when testing using your application models, however?"
] | 2018-03-28T21:04:16 | 2018-04-03T12:12:04 | 2018-04-02T14:42:48 | NONE | null | There seems to be no inclusion of column default values.
Given that the information schema for the three systems includes it, is it okay if I submit my workaround for this as a pull request?
My pull initially focuses on MySQL, but with 'possibility' of including psql and sqlite. | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1553/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/1553/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1552 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1552/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1552/comments | https://api.github.com/repos/coleifer/peewee/issues/1552/events | https://github.com/coleifer/peewee/issues/1552 | 308,441,692 | MDU6SXNzdWUzMDg0NDE2OTI= | 1,552 | [BUG] Float gets autoconverted into integer in query in Peewee 3.1 | {
"login": "Egor3f",
"id": 5215884,
"node_id": "MDQ6VXNlcjUyMTU4ODQ=",
"avatar_url": "https://avatars.githubusercontent.com/u/5215884?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/Egor3f",
"html_url": "https://github.com/Egor3f",
"followers_url": "https://api.github.com/users/Egor3f/followers",
"following_url": "https://api.github.com/users/Egor3f/following{/other_user}",
"gists_url": "https://api.github.com/users/Egor3f/gists{/gist_id}",
"starred_url": "https://api.github.com/users/Egor3f/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/Egor3f/subscriptions",
"organizations_url": "https://api.github.com/users/Egor3f/orgs",
"repos_url": "https://api.github.com/users/Egor3f/repos",
"events_url": "https://api.github.com/users/Egor3f/events{/privacy}",
"received_events_url": "https://api.github.com/users/Egor3f/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"Just a thought -- if you have a price and are multiplying it by a float, that could cause issues... you might have better luck using a `DecimalField` which will not introduce precision errors.\r\n\r\nI'll look into the issue as reported, just thought I'd mention that as a suggestion.",
"I just wrote a small test-case and it is passing:\r\n\r\n```python\r\nclass Item(TestModel):\r\n price = IntegerField()\r\n multiplier = FloatField(default=1.)\r\n\r\n\r\nclass TestFieldValueHandling(ModelTestCase):\r\n requires = [Item]\r\n\r\n def test_int_float_multi(self):\r\n i = Item.create(price=10, multiplier=0.75)\r\n i_db = (Item\r\n .select(Item, (Item.price * Item.multiplier).alias('total'))\r\n .where(Item.id == i.id)\r\n .get())\r\n self.assertEqual(i_db.price, 10)\r\n```\r\n\r\nCan you help me understand what I've got wrong in my setup so I can replicate this?",
"Ahh, got it to fail, nevermind:\r\n\r\n```python\r\n i_db = (Item\r\n .select(Item, (Item.price * 0.75).alias('total'))\r\n .where(Item.id == i.id)\r\n .get())\r\n self.assertEqual(i_db.price, 10)\r\n self.assertEqual(i_db.multiplier, .75)\r\n self.assertEqual(i_db.total, 7.5) # FAILS -- 0\r\n```",
"Fixed in: 969c208f34f159b742e81be722e6a409400843ad\r\n\r\nYou should now be able to pass \"False\" as the 2nd parameter of `Value` (the 3.0 replacement for Passthrough):\r\n\r\n```python\r\nItem.select((Item.price * Value(multiplier, False)).alias('final_price'))\r\n```"
] | 2018-03-26T05:57:23 | 2018-03-26T15:15:13 | 2018-03-26T15:15:12 | NONE | null | I have exaclty the same issue, as there: https://github.com/coleifer/peewee/issues/1150
I need to multiply IntegerField by float value in select query (to apply commission or discount to price field).
But in actual SQL query float gets converted to integer, so 0.9 becomes 0.
In peewee v2 I could use `Item.select((Item.price * Passthrough(multiplier)).alias('final_price'))`
There is no Passthrough function in peewee v3.
My database is Mariadb through pymysql, if it matters.
It seeems strange that such simple action is impossible in peewee. And more strange, that in Peewee v2 I could do that, and in new version I can't.
P.S. I don't need any CASTing, just need to pass right value without converting. | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1552/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/1552/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1551 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1551/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1551/comments | https://api.github.com/repos/coleifer/peewee/issues/1551/events | https://github.com/coleifer/peewee/issues/1551 | 308,419,035 | MDU6SXNzdWUzMDg0MTkwMzU= | 1,551 | Why don't you support oracle database? | {
"login": "inpool",
"id": 3860872,
"node_id": "MDQ6VXNlcjM4NjA4NzI=",
"avatar_url": "https://avatars.githubusercontent.com/u/3860872?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/inpool",
"html_url": "https://github.com/inpool",
"followers_url": "https://api.github.com/users/inpool/followers",
"following_url": "https://api.github.com/users/inpool/following{/other_user}",
"gists_url": "https://api.github.com/users/inpool/gists{/gist_id}",
"starred_url": "https://api.github.com/users/inpool/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/inpool/subscriptions",
"organizations_url": "https://api.github.com/users/inpool/orgs",
"repos_url": "https://api.github.com/users/inpool/repos",
"events_url": "https://api.github.com/users/inpool/events{/privacy}",
"received_events_url": "https://api.github.com/users/inpool/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"It's pretty obvious that open source developers won't bother with Oracle and it's licences. \r\nWhat's the justification for writing and orm in your free time for a database you don't use?\r\n\r\nIf you are interested, it's easy to add a backed for Oracle, and if you have a license you can actually even test the code.\r\n\r\nMaybe you can convince your employer to pay for the effort as a path to migrate from Oracle to PostgreSQL.",
"Oracle has a DB-API 2.0-compatible Python driver, I believe it's called `cx_Oracle`? If you want to add support for Oracle you should be able to subclass `Database` and implement the appropriate methods to get it working with Oracle.\r\n\r\nAs @oz123 alluded to, Oracle is a proprietary database. I have no interest in supporting or maintaining support for it.",
"Thank you! I'll try it."
] | 2018-03-26T03:03:44 | 2018-03-26T17:03:52 | 2018-03-26T15:26:16 | NONE | null | I often need to write tools about existing apps, which are based on Oracle, and I love peewee, and when I'm ready to use her, I find that she doesn't support Oracle. Why does peewee not support Oracle? | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1551/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/1551/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1550 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1550/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1550/comments | https://api.github.com/repos/coleifer/peewee/issues/1550/events | https://github.com/coleifer/peewee/pull/1550 | 308,336,266 | MDExOlB1bGxSZXF1ZXN0MTc3MjgxMjU4 | 1,550 | Integration with Sanic | {
"login": "rxcai",
"id": 5463519,
"node_id": "MDQ6VXNlcjU0NjM1MTk=",
"avatar_url": "https://avatars.githubusercontent.com/u/5463519?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/rxcai",
"html_url": "https://github.com/rxcai",
"followers_url": "https://api.github.com/users/rxcai/followers",
"following_url": "https://api.github.com/users/rxcai/following{/other_user}",
"gists_url": "https://api.github.com/users/rxcai/gists{/gist_id}",
"starred_url": "https://api.github.com/users/rxcai/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/rxcai/subscriptions",
"organizations_url": "https://api.github.com/users/rxcai/orgs",
"repos_url": "https://api.github.com/users/rxcai/repos",
"events_url": "https://api.github.com/users/rxcai/events{/privacy}",
"received_events_url": "https://api.github.com/users/rxcai/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [] | 2018-03-25T09:49:22 | 2018-03-25T20:27:41 | 2018-03-25T20:27:40 | CONTRIBUTOR | null | Using peewee in a Sanic project and got `Error 2006: MySQL server has gone away`. After implementation of handler in request and response middleware, the error has gone and the application runs well. | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1550/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/1550/timeline | null | null | false | {
"url": "https://api.github.com/repos/coleifer/peewee/pulls/1550",
"html_url": "https://github.com/coleifer/peewee/pull/1550",
"diff_url": "https://github.com/coleifer/peewee/pull/1550.diff",
"patch_url": "https://github.com/coleifer/peewee/pull/1550.patch",
"merged_at": "2018-03-25T20:27:40"
} |
https://api.github.com/repos/coleifer/peewee/issues/1549 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1549/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1549/comments | https://api.github.com/repos/coleifer/peewee/issues/1549/events | https://github.com/coleifer/peewee/issues/1549 | 307,891,444 | MDU6SXNzdWUzMDc4OTE0NDQ= | 1,549 | pip install peewee fails with Anaconda on Win10 | {
"login": "happylrd",
"id": 15155131,
"node_id": "MDQ6VXNlcjE1MTU1MTMx",
"avatar_url": "https://avatars.githubusercontent.com/u/15155131?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/happylrd",
"html_url": "https://github.com/happylrd",
"followers_url": "https://api.github.com/users/happylrd/followers",
"following_url": "https://api.github.com/users/happylrd/following{/other_user}",
"gists_url": "https://api.github.com/users/happylrd/gists{/gist_id}",
"starred_url": "https://api.github.com/users/happylrd/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/happylrd/subscriptions",
"organizations_url": "https://api.github.com/users/happylrd/orgs",
"repos_url": "https://api.github.com/users/happylrd/repos",
"events_url": "https://api.github.com/users/happylrd/events{/privacy}",
"received_events_url": "https://api.github.com/users/happylrd/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"Hmm... I don't know, with setup.py, how to check if a header file/shared lib is going to be available ahead-of-time.",
"@coleifer `conda install -c conda-forge peewee` can solve this problem, the only regrettable thing is that the version of peewee is a little old, just 2.10.2.\r\n\r\n**Supplement 2018.4.10**\r\nThe version of [peewee](https://anaconda.org/conda-forge/peewee) is v3.1.5, it's enough to use for me. ",
"Ew, yeah... Peewee has much more extensive integration with SQLite in 3.x, although it's restricted to a module in `playhouse`. I'm not sure how to conditionally compile that, if Cython and a C compiler is installed but sqlite is not?",
"Cython and a C compiler has installed.\r\nconda list:\r\n`sqlite 3.22.0 h9d3ae62_0`\r\nSo I'm puzzled about installing peewee fail with pip.\r\nOr can you update the version of [peewee ](https://anaconda.org/conda-forge/peewee) in conda-forge?",
"I have no idea what conda is?",
"Anaconda is a python and R distribution. It aims to provide everything you need (python wise) for data science \"out of the box\".\r\nIt includes:\r\n- The core python language\r\n- 100+ python \"packages\" (libraries)\r\n- Spyder (IDE/editor - like pycharm) and Jupyter\r\n- **conda, Anaconda's own package manager**, used for updating Anaconda and packages\r\n\r\nSee [here](https://stackoverflow.com/questions/49471840/anaconda-error-cannot-open-include-file-sqlite3-h-no-such-file-or-directory), it may help to update the version of peewee.",
"@happylrd probably better to ask [here](https://github.com/conda-forge/peewee-feedstock) since it seems the conda package wasn't made by coleifer.\r\n\r\nIt looks like @pmlandwehr and @dharhas have marked themselves as the maintainers of that.",
"Let me rephrase: I totally don't care what conda is.\r\n\r\nI'd suggest you check it out with whoever the maintainers are.",
"For all you winblows lusers out there, I've added an option to the setup.py script to skip building SQLite-specific C extensions. Docs here:\r\n\r\nhttp://docs.peewee-orm.com/en/latest/peewee/installation.html#skip-compilation-of-sqlite-extensions",
"This environment var is supported in the latest version on PyPI -- 3.1.7, which I just pushed. Hope this helps!"
] | 2018-03-23T03:35:43 | 2018-04-10T04:00:19 | 2018-03-27T13:51:47 | NONE | null | `pip install peewee` fails with Anaconda on Windows 10.
- OS: Windows 10
- Python: Python 3.6.4 :: Anaconda, Inc.
- Cython: 0.27.3
### error
```
playhouse\_sqlite_ext.c(531): fatal error C1083: Cannot open include file: 'sqlite3.h': No such file or directory
error: command 'D:\\MyIDE\\VS2015\\VC\\BIN\\x86_amd64\\cl.exe' failed with exit status 2
```
**But when I used official Python without Anaconda, it installed successfully**.So what can I do for installing peewee successfully with Python in Anaconda?
| {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1549/reactions",
"total_count": 3,
"+1": 3,
"-1": 0,
"laugh": 0,
"hooray": 0,
"confused": 0,
"heart": 0,
"rocket": 0,
"eyes": 0
} | https://api.github.com/repos/coleifer/peewee/issues/1549/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1548 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1548/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1548/comments | https://api.github.com/repos/coleifer/peewee/issues/1548/events | https://github.com/coleifer/peewee/issues/1548 | 307,744,108 | MDU6SXNzdWUzMDc3NDQxMDg= | 1,548 | ArrayField should use the db_value and python_value methods of it's data-type | {
"login": "coleifer",
"id": 119974,
"node_id": "MDQ6VXNlcjExOTk3NA==",
"avatar_url": "https://avatars.githubusercontent.com/u/119974?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/coleifer",
"html_url": "https://github.com/coleifer",
"followers_url": "https://api.github.com/users/coleifer/followers",
"following_url": "https://api.github.com/users/coleifer/following{/other_user}",
"gists_url": "https://api.github.com/users/coleifer/gists{/gist_id}",
"starred_url": "https://api.github.com/users/coleifer/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/coleifer/subscriptions",
"organizations_url": "https://api.github.com/users/coleifer/orgs",
"repos_url": "https://api.github.com/users/coleifer/repos",
"events_url": "https://api.github.com/users/coleifer/events{/privacy}",
"received_events_url": "https://api.github.com/users/coleifer/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"eba0aefdc63b2d4106334cd5c11d1c9de659fb12"
] | 2018-03-22T17:32:33 | 2018-03-23T14:52:14 | 2018-03-23T14:52:14 | OWNER | null | Currently `ArrayField` does no processing in either `db_value` or `python_value`, meaning arrays of fields that implement custom conversion will not work as expected. | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1548/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/1548/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1547 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1547/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1547/comments | https://api.github.com/repos/coleifer/peewee/issues/1547/events | https://github.com/coleifer/peewee/issues/1547 | 307,621,498 | MDU6SXNzdWUzMDc2MjE0OTg= | 1,547 | Add documentation for ~ opertor | {
"login": "dyadav7",
"id": 8121360,
"node_id": "MDQ6VXNlcjgxMjEzNjA=",
"avatar_url": "https://avatars.githubusercontent.com/u/8121360?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/dyadav7",
"html_url": "https://github.com/dyadav7",
"followers_url": "https://api.github.com/users/dyadav7/followers",
"following_url": "https://api.github.com/users/dyadav7/following{/other_user}",
"gists_url": "https://api.github.com/users/dyadav7/gists{/gist_id}",
"starred_url": "https://api.github.com/users/dyadav7/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/dyadav7/subscriptions",
"organizations_url": "https://api.github.com/users/dyadav7/orgs",
"repos_url": "https://api.github.com/users/dyadav7/repos",
"events_url": "https://api.github.com/users/dyadav7/events{/privacy}",
"received_events_url": "https://api.github.com/users/dyadav7/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"There is an example.\r\n\r\n\r\n",
"Thanks"
] | 2018-03-22T12:25:10 | 2018-03-23T01:46:52 | 2018-03-22T13:44:55 | NONE | null | Documentation has example for contains - e.g. Facility.name.contains('tennis').
There should be example for reverse of this contain API / reverse of any than queries.
e.g. I want to search for a Facility for which the Facility.name does not contain "tennis".
See: https://stackoverflow.com/questions/25734566/operator-not-in-with-peewee
Thanks
Deepak | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1547/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/1547/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1546 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1546/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1546/comments | https://api.github.com/repos/coleifer/peewee/issues/1546/events | https://github.com/coleifer/peewee/issues/1546 | 307,141,491 | MDU6SXNzdWUzMDcxNDE0OTE= | 1,546 | peewee.InterfaceError: (0, '') | pymysql.err.InterfaceError: (0, '') | {
"login": "MozzieHan",
"id": 23057269,
"node_id": "MDQ6VXNlcjIzMDU3MjY5",
"avatar_url": "https://avatars.githubusercontent.com/u/23057269?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/MozzieHan",
"html_url": "https://github.com/MozzieHan",
"followers_url": "https://api.github.com/users/MozzieHan/followers",
"following_url": "https://api.github.com/users/MozzieHan/following{/other_user}",
"gists_url": "https://api.github.com/users/MozzieHan/gists{/gist_id}",
"starred_url": "https://api.github.com/users/MozzieHan/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/MozzieHan/subscriptions",
"organizations_url": "https://api.github.com/users/MozzieHan/orgs",
"repos_url": "https://api.github.com/users/MozzieHan/repos",
"events_url": "https://api.github.com/users/MozzieHan/events{/privacy}",
"received_events_url": "https://api.github.com/users/MozzieHan/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"This looks like a bug in peewee-async or something? Some server issue?\r\n\r\nPeewee is tested with mysql every release (and every commit for that matter) so I know mysql isn't horribly broken or anything.",
"The follow up is at https://github.com/05bit/peewee-async/issues/26",
"We encounter the same problem with peewee with use recent `flask` version 1.0.2 without relying on `flask-peewee`.\r\n\r\nWe do not open/close connection between each request, I was expecting to be able to reuse the connection across request.\r\n\r\nWe do not use the connection pool.",
"I think we found the issue. Looking up earlier log, we noticed mysqld server closed the only connection we had and we did not reconnect after. \r\n\r\nref: http://docs.peewee-orm.com/en/latest/peewee/database.html#error-2006-mysql-server-has-gone-away\r\nref: http://docs.peewee-orm.com/en/latest/peewee/database.html#flask\r\n\r\nTy!",
"Hi,\r\n I have the same issue but I'm not using any framework. \r\nI'm in a asyncio method.\r\n\r\n```\r\nTraceback (most recent call last):\r\n File \"/usr/local/lib/python3.8/site-packages/pymysql/connections.py\", line 756, in _write_bytes\r\n self._sock.sendall(data)\r\nConnectionResetError: [Errno 104] Connection reset by peer\r\n\r\nDuring handling of the above exception, another exception occurred:\r\n\r\nTraceback (most recent call last):\r\n File \"/usr/local/lib/python3.8/site-packages/peewee.py\", line 3144, in execute_sql\r\n cursor.execute(sql, params or ())\r\n File \"/usr/local/lib/python3.8/site-packages/pymysql/cursors.py\", line 148, in execute\r\n result = self._query(query)\r\n File \"/usr/local/lib/python3.8/site-packages/pymysql/cursors.py\", line 310, in _query\r\n conn.query(q)\r\n File \"/usr/local/lib/python3.8/site-packages/pymysql/connections.py\", line 547, in query\r\n self._execute_command(COMMAND.COM_QUERY, sql)\r\n File \"/usr/local/lib/python3.8/site-packages/pymysql/connections.py\", line 814, in _execute_command\r\n self._write_bytes(packet)\r\n File \"/usr/local/lib/python3.8/site-packages/pymysql/connections.py\", line 759, in _write_bytes\r\n raise err.OperationalError(\r\npymysql.err.OperationalError: (2006, \"MySQL server has gone away (ConnectionResetError(104, 'Connection reset by peer'))\")\r\n\r\nDuring handling of the above exception, another exception occurred:\r\n\r\nTraceback (most recent call last):\r\n File \"/usr/local/lib/python3.8/site-packages/discord/client.py\", line 343, in _run_event\r\n await coro(*args, **kwargs)\r\n File \"/app/my_discord_client.py\", line 96, in on_member_update\r\n GameSessionManager.handle_user_update(before, after)\r\n File \"/app/game_session_manager.py\", line 47, in handle_user_update\r\n target_user = cls.get_or_create_user(user_id=after.id, name=after.name)\r\n File \"/app/game_session_manager.py\", line 18, in get_or_create_user\r\n target_user = DiscordUser.get(id=user_id)\r\n File \"/usr/local/lib/python3.8/site-packages/peewee.py\", line 6438, in get\r\n return sq.get()\r\n File \"/usr/local/lib/python3.8/site-packages/peewee\r\n```\r\n",
"The connection was reset - presumably your connection was idle and mysql closed it after a given amount of time elapsed. Check the reconnectmixin if you want to try automatically reconnecting:\r\n\r\nhttps://github.com/coleifer/peewee/blob/master/playhouse/shortcuts.py#L174",
"Actually I wrapped at first the database loading with a Singleton pattern. But it not a good idea I presume :)\r\n\r\nIt was like this:\r\n```python\r\nfrom peewee import MySQLDatabase\r\n\r\nfrom settings_loader import SettingLoader\r\n\r\n\r\nclass Singleton(type):\r\n _instances = {}\r\n\r\n def __call__(cls, *args, **kwargs):\r\n if cls not in cls._instances:\r\n cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)\r\n return cls._instances[cls]\r\n\r\n\r\nclass DatabaseLoader(Singleton, object):\r\n\r\n @classmethod\r\n def get_database(cls, name=\"bot\"):\r\n settings = SettingLoader().settings\r\n return MySQLDatabase(database=name,\r\n host=settings.database_host,\r\n user=settings.database_user,\r\n passwd=settings.database_password)\r\n```\r\n\r\nI switched to this. We'll see if it's better\r\n```python\r\nclass DatabaseLoader(object):\r\n\r\n @classmethod\r\n def get_database(cls, name=\"bot\"):\r\n settings = SettingLoader().settings\r\n return PooledMySQLDatabase(\r\n database=name,\r\n max_connections=10,\r\n stale_timeout=300,\r\n host=settings.database_host,\r\n user=settings.database_user,\r\n passwd=settings.database_password)\r\n```\r\n",
"The database is already a singleton instance, so this is redundant. Also using the pool won't help you.",
"You think my problem is somewhere else? Removing the singleton wont help?",
">I'm in a asyncio method.\r\n\r\nI can't debug your code for you, but connection management is straightforward in a non-async or threaded environment. The db (which, yes, is a singleton) maintains a connection-per-thread automatically - this also works for gevent which monkeypatches threadlocal. In asyncio, you would probably want to manage a connection-per-async-context but you're on your own in terms of figuring that out. With the db, you need to call connect and close the connection when you're done with it - its all documented http://docs.peewee-orm.com/en/latest/peewee/database.html#connection-management",
"Thanks a lot for all those info. I'll try to figure out where it's wrong.\r\n",
"I have the same problem too with fastapi, however I have added the `ReconnectMixin`:\r\n\r\n```python3\r\nclass DB(ReconnectMixin, MySQLDatabase):\r\n pass\r\n\r\ndb = DB(host=Config.DB_HOST, port=Config.DB_PORT, user=Config.DB_USER, passwd=Config.DB_PWD, database=Config.DB_NAME)\r\n```\r\n\r\nAnd added the automatic retry into the middleware:\r\n```python3\r\nasync def catch_exceptions_middleware(request: Request, call_next):\r\n try:\r\n if db.is_closed():\r\n db.connect()\r\n return await call_next(request)\r\n except Exception:\r\n logger.error('error occurs, err=%s' % traceback.format_exc())\r\n return JSONResponse()\r\n```\r\n\r\nHowever, the InterfaceError still occurs, and I wondering why it doesn't work.",
"@paulzhn my reply above https://github.com/coleifer/peewee/issues/1546#issuecomment-832784804 describes some of the difficulty with async and connection management.\r\n\r\nAdditionally you may need to extend the list of errors the reconnect mixin catches.",
"> @paulzhn my reply above [#1546 (comment)](https://github.com/coleifer/peewee/issues/1546#issuecomment-832784804) describes some of the difficulty with async and connection management.\r\n> \r\n> Additionally you may need to extend the list of errors the reconnect mixin catches.\r\n\r\n```python3\r\n File \"/home/paul/.local/lib/python3.8/site-packages/peewee.py\", line 3144, in execute_sql\r\n cursor.execute(sql, params or ())\r\n File \"/home/paul/.local/lib/python3.8/site-packages/pymysql/cursors.py\", line 148, in execute\r\n result = self._query(query)\r\n File \"/home/paul/.local/lib/python3.8/site-packages/pymysql/cursors.py\", line 310, in _query\r\n conn.query(q)\r\n File \"/home/paul/.local/lib/python3.8/site-packages/pymysql/connections.py\", line 547, in query\r\n self._execute_command(COMMAND.COM_QUERY, sql)\r\n File \"/home/paul/.local/lib/python3.8/site-packages/pymysql/connections.py\", line 793, in _execute_command\r\n raise err.InterfaceError(0, \"\")\r\npymysql.err.InterfaceError: (0, '')\r\n\r\nDuring handling of the above exception, another exception occurred:\r\n\r\nTraceback (most recent call last):\r\n File \"/home/paul/code/communist_backend/utils/common.py\", line 65, in f\r\n data, code = func(*args, **kwargs)\r\n File \"/home/paul/code/communist_backend/api/available_school_branch.py\", line 20, in post\r\n for i in result:\r\n File \"/home/paul/.local/lib/python3.8/site-packages/peewee.py\", line 6874, in __iter__\r\n self.execute()\r\n File \"/home/paul/.local/lib/python3.8/site-packages/peewee.py\", line 1907, in inner\r\n return method(self, database, *args, **kwargs)\r\n File \"/home/paul/.local/lib/python3.8/site-packages/peewee.py\", line 1978, in execute\r\n return self._execute(database)\r\n File \"/home/paul/.local/lib/python3.8/site-packages/peewee.py\", line 2150, in _execute\r\n cursor = database.execute(self)\r\n File \"/home/paul/.local/lib/python3.8/site-packages/peewee.py\", line 3157, in execute\r\n return self.execute_sql(sql, params, commit=commit)\r\n File \"/home/paul/.local/lib/python3.8/site-packages/peewee.py\", line 3151, in execute_sql\r\n self.commit()\r\n File \"/home/paul/.local/lib/python3.8/site-packages/peewee.py\", line 2917, in __exit__\r\n reraise(new_type, new_type(exc_value, *exc_args), traceback)\r\n File \"/home/paul/.local/lib/python3.8/site-packages/peewee.py\", line 190, in reraise\r\n raise value.with_traceback(tb)\r\n File \"/home/paul/.local/lib/python3.8/site-packages/peewee.py\", line 3144, in execute_sql\r\n cursor.execute(sql, params or ())\r\n File \"/home/paul/.local/lib/python3.8/site-packages/pymysql/cursors.py\", line 148, in execute\r\n result = self._query(query)\r\n File \"/home/paul/.local/lib/python3.8/site-packages/pymysql/cursors.py\", line 310, in _query\r\n conn.query(q)\r\n File \"/home/paul/.local/lib/python3.8/site-packages/pymysql/connections.py\", line 547, in query\r\n self._execute_command(COMMAND.COM_QUERY, sql)\r\n File \"/home/paul/.local/lib/python3.8/site-packages/pymysql/connections.py\", line 793, in _execute_command\r\n raise err.InterfaceError(0, \"\")\r\npeewee.InterfaceError: (0, '')\r\n```\r\n\r\ncode:\r\n```python3\r\nclass ReconnectDB(MySQLDatabase, ReconnectMixin):\r\n pass\r\n\r\nclass Ext:\r\n db = ReconnectDB(\r\n Config.DB_NAME,\r\n host=Config.DB_HOST,\r\n port=Config.DB_PORT,\r\n user=Config.DB_USER,\r\n passwd=Config.DB_PWD\r\n )\r\n```\r\n\r\nMy another project with flask and peewee also occurs the problem, the traceback is as above. I think it might not be related to async?",
"Are you using multiprocessing?",
"On my side I still have the issue with the `PooledMySQLDatabase`.\r\nI'm using multiprocessing. Another lib receive asyncio events and then preform insertion in the database. So multiple insert can appear at the same time.\r\n\r\n\r\n",
"If you're using multiprocessing, you need to be sure you're not opening connections until after you fork a new process. See also caveats about asyncio above.",
"Actually no, It's not multiprocessing. I thought it was but asyncio is actually a coroutine and so using the same process. \r\nI've added the decorator `@db.connection_context()` to my method but still. I have now the same error as @paulbooth `peewee.InterfaceError: (0, '')`.\r\n\r\nI'll try to create my own wrapper to ping and reconnect like described [here](https://stackoverflow.com/questions/56319791/finding-source-of-pymysql-error-err-interfaceerror0).\r\n",
"I'd suggest carefully debugging this because it almost certainly indicates connection mis-management somewhere in the call-stack. This can be especially true with asyncio, e.g. https://github.com/coleifer/peewee/issues/1546#issuecomment-832784804",
"Can we reopen the issue? I came across the same problem in my personal project using sanic(asyncio) + peewee.\r\n\r\nRestarting the server solved the problem.",
"As I've said before, I'm quite confident this is always attributable to user error or mismanagement of the connection lifecycle.\r\n\r\n* https://github.com/coleifer/peewee/issues/1546#issuecomment-864622366\r\n* https://github.com/coleifer/peewee/issues/1546#issuecomment-832674172"
] | 2018-03-21T07:26:23 | 2021-11-22T13:40:03 | 2018-03-21T13:39:47 | NONE | null | I am encountering this exception (using peewee-async high-level api) then my asyncio based daemon is idle (about 15 minutes or so), after that time, this exception occurs, I have tried to close and reopen connection, and was surprised that Manager (high-level api) did not track its state (close/reopen is done using its methods).
```
Traceback (most recent call last):
File "/home/ubuntu/dati-server/match/manager.py", line 56, in clean_up_user
await exam_end_all_handler(current_match_id, user_id)
File "/home/ubuntu/dati-server/match/manager.py", line 407, in exam_end_all_handler
match_result = await MatchUserRecord.set_user_score_and_winner(match_id)
File "/home/ubuntu/dati-server/models/record.py", line 260, in set_user_score_and_winner
score1 = await user_record1.get_match_score()
File "/home/ubuntu/dati-server/models/record.py", line 108, in get_match_score
answer_records = await objects.execute(UserAnswerRecord.filter(match_id=self.match.id, user_id=self.user_id))
File "/home/ubuntu/dati-server/env/lib/python3.6/site-packages/peewee.py", line 1386, in __get__
return self.get_object_or_id(instance)
File "/home/ubuntu/dati-server/env/lib/python3.6/site-packages/peewee.py", line 1377, in get_object_or_id
obj = self.rel_model.get(self.field.to_field == rel_id)
File "/home/ubuntu/dati-server/env/lib/python3.6/site-packages/peewee.py", line 4988, in get
return sq.get()
File "/home/ubuntu/dati-server/env/lib/python3.6/site-packages/peewee.py", line 3220, in get
return next(clone.execute())
File "/home/ubuntu/dati-server/env/lib/python3.6/site-packages/peewee.py", line 3274, in execute
self._qr = ResultWrapper(model_class, self._execute(), query_meta)
File "/home/ubuntu/dati-server/env/lib/python3.6/site-packages/peewee.py", line 2939, in _execute
return self.database.execute_sql(sql, params, self.require_commit)
File "/home/ubuntu/dati-server/env/lib/python3.6/site-packages/peewee_async.py", line 1041, in execute_sql
return super().execute_sql(*args, **kwargs)
File "/home/ubuntu/dati-server/env/lib/python3.6/site-packages/peewee.py", line 3837, in execute_sql
self.commit()
File "/home/ubuntu/dati-server/env/lib/python3.6/site-packages/peewee.py", line 3656, in __exit__
reraise(new_type, new_type(*exc_args), traceback)
File "/home/ubuntu/dati-server/env/lib/python3.6/site-packages/peewee.py", line 135, in reraise
raise value.with_traceback(tb)
File "/home/ubuntu/dati-server/env/lib/python3.6/site-packages/peewee.py", line 3830, in execute_sql
cursor.execute(sql, params or ())
File "/home/ubuntu/dati-server/env/lib/python3.6/site-packages/pymysql/cursors.py", line 165, in execute
result = self._query(query)
File "/home/ubuntu/dati-server/env/lib/python3.6/site-packages/pymysql/cursors.py", line 321, in _query
conn.query(q)
File "/home/ubuntu/dati-server/env/lib/python3.6/site-packages/pymysql/connections.py", line 859, in query
self._execute_command(COMMAND.COM_QUERY, sql)
File "/home/ubuntu/dati-server/env/lib/python3.6/site-packages/pymysql/connections.py", line 1075, in _execute_command
raise err.InterfaceError("(0, '')")
peewee.InterfaceError: (0, '')
``` | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1546/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/1546/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1545 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1545/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1545/comments | https://api.github.com/repos/coleifer/peewee/issues/1545/events | https://github.com/coleifer/peewee/issues/1545 | 306,896,671 | MDU6SXNzdWUzMDY4OTY2NzE= | 1,545 | a + b != sum([a, b]) | {
"login": "phryk",
"id": 1021513,
"node_id": "MDQ6VXNlcjEwMjE1MTM=",
"avatar_url": "https://avatars.githubusercontent.com/u/1021513?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/phryk",
"html_url": "https://github.com/phryk",
"followers_url": "https://api.github.com/users/phryk/followers",
"following_url": "https://api.github.com/users/phryk/following{/other_user}",
"gists_url": "https://api.github.com/users/phryk/gists{/gist_id}",
"starred_url": "https://api.github.com/users/phryk/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/phryk/subscriptions",
"organizations_url": "https://api.github.com/users/phryk/orgs",
"repos_url": "https://api.github.com/users/phryk/repos",
"events_url": "https://api.github.com/users/phryk/events{/privacy}",
"received_events_url": "https://api.github.com/users/phryk/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"Peewee uses operator overloads to compose expressions and queries themselves. For queries, the operators are:\r\n\r\n* addition: UNION ALL\r\n* bitwise or: UNION\r\n* bitwise and: INTERSECT\r\n* subtraction: EXCEPT\r\n\r\nI'm not sure how the `sum` builtin is implemented but apparently it is doing something weird. You can use `reduce()` with `operator.add` instead of `sum`... Or actually maybe that's the problem, it's doing a left-fold with `0` as the initial value?",
"The only other alternative I can think that would be appropriate would be to throw an error if a user attempts to add a query and a scalar value. This would cause `sum` (or any fold/reduce with a zero initial value) to fail, presumably, so I'm not sure that solves your problem.\r\n\r\nIn short, I think you'll need to work around this using your own iterator."
] | 2018-03-20T14:44:30 | 2018-03-20T16:03:02 | 2018-03-20T16:03:02 | NONE | null | Expected behavior:
`a + b == sum([a, b])`
Actual behavior:
```
>>> a = User.select(User.id)
>>> b = News.select(News.id)
>>> a + b == sum([a, b])
False
>>> (a + b).sql()
('SELECT "t1"."id" FROM "user" AS "t1" UNION ALL SELECT "t2"."id" FROM "news" AS "t2"', [])
>>> sum([a, b]).sql()
('? UNION ALL SELECT "t1"."id" FROM "user" AS "t1" UNION ALL SELECT "t2"."id" FROM "news" AS "t2"', [0])
```
It would be A) logically consistent and B) nice for dynamic query construction if the behavior of `sum` on queries could be fixed. | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1545/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/1545/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1544 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1544/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1544/comments | https://api.github.com/repos/coleifer/peewee/issues/1544/events | https://github.com/coleifer/peewee/issues/1544 | 306,513,158 | MDU6SXNzdWUzMDY1MTMxNTg= | 1,544 | drop_table does not pass **options properly | {
"login": "ccosby",
"id": 194775,
"node_id": "MDQ6VXNlcjE5NDc3NQ==",
"avatar_url": "https://avatars.githubusercontent.com/u/194775?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/ccosby",
"html_url": "https://github.com/ccosby",
"followers_url": "https://api.github.com/users/ccosby/followers",
"following_url": "https://api.github.com/users/ccosby/following{/other_user}",
"gists_url": "https://api.github.com/users/ccosby/gists{/gist_id}",
"starred_url": "https://api.github.com/users/ccosby/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/ccosby/subscriptions",
"organizations_url": "https://api.github.com/users/ccosby/orgs",
"repos_url": "https://api.github.com/users/ccosby/repos",
"events_url": "https://api.github.com/users/ccosby/events{/privacy}",
"received_events_url": "https://api.github.com/users/ccosby/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"Thanks, fixed."
] | 2018-03-19T15:32:24 | 2018-03-19T15:37:10 | 2018-03-19T15:37:10 | NONE | null | https://github.com/coleifer/peewee/blob/74f3b30e6c0a6f8461b8bd33a21fd5fe9ad5c8c3/peewee.py#L4542
It appears as if **options should be passed to _drop_table() instead of execute() here.
unittest doesn't catch this one because it tests the private method instead of the public one. | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1544/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/1544/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1543 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1543/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1543/comments | https://api.github.com/repos/coleifer/peewee/issues/1543/events | https://github.com/coleifer/peewee/issues/1543 | 306,243,551 | MDU6SXNzdWUzMDYyNDM1NTE= | 1,543 | Add column if doesn't exist | {
"login": "Shashwat986",
"id": 5304561,
"node_id": "MDQ6VXNlcjUzMDQ1NjE=",
"avatar_url": "https://avatars.githubusercontent.com/u/5304561?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/Shashwat986",
"html_url": "https://github.com/Shashwat986",
"followers_url": "https://api.github.com/users/Shashwat986/followers",
"following_url": "https://api.github.com/users/Shashwat986/following{/other_user}",
"gists_url": "https://api.github.com/users/Shashwat986/gists{/gist_id}",
"starred_url": "https://api.github.com/users/Shashwat986/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/Shashwat986/subscriptions",
"organizations_url": "https://api.github.com/users/Shashwat986/orgs",
"repos_url": "https://api.github.com/users/Shashwat986/repos",
"events_url": "https://api.github.com/users/Shashwat986/events{/privacy}",
"received_events_url": "https://api.github.com/users/Shashwat986/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"Adding columns strikes me as being different-enough from just creating tables that I think the current division of APIs is appropriate.\r\n\r\nThe table is based on a model, which is declared in Python code -- from the perspective of a running app, it's structure is static. When adding (or otherwise altering) fields on a model, you do it offline, modifying the model definition. Since it's not a dynamic operation, it makes sense to code the schema migrations in a similar manner. Also, `create_tables` ensures that a table exists, but it does not otherwise alter a pre-existing table.\r\n\r\nChanging a pre-existing database table is a very dangerous operation and I think that such a method would cause a lot of confusion."
] | 2018-03-18T14:11:33 | 2018-03-18T22:34:49 | 2018-03-18T22:34:49 | NONE | null | I was wondering if it would be useful to have a method to add any new columns to a table, or to all tables in the database. It'll make db migrations much easier.
In my head, usage would look like:
```py
db.connect()
db.create_tables([User, Tweet])
db.add_columns([User, Tweet]) # or User.add_columns()
```
I feel this makes sense, especially after `create_tables` is safe by default now, so, in theory, it can be run every time. Similarly, `add_columns` can also run every time, making any and all migrations single-line.
I was looking at this as a use-case primarily for SQLite, because SQLite doesn't allow any other ALTER TABLE commands, so, this makes more sense than a migration; however, it may make sense for all database types.
Also, if this is something we're interested in, I'm more than happy with picking this up myself, and creating a PR. | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1543/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/1543/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1542 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1542/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1542/comments | https://api.github.com/repos/coleifer/peewee/issues/1542/events | https://github.com/coleifer/peewee/issues/1542 | 306,186,539 | MDU6SXNzdWUzMDYxODY1Mzk= | 1,542 | TimestampField type is different if accessed via query as opposed to directly | {
"login": "vsajip",
"id": 130553,
"node_id": "MDQ6VXNlcjEzMDU1Mw==",
"avatar_url": "https://avatars.githubusercontent.com/u/130553?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/vsajip",
"html_url": "https://github.com/vsajip",
"followers_url": "https://api.github.com/users/vsajip/followers",
"following_url": "https://api.github.com/users/vsajip/following{/other_user}",
"gists_url": "https://api.github.com/users/vsajip/gists{/gist_id}",
"starred_url": "https://api.github.com/users/vsajip/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/vsajip/subscriptions",
"organizations_url": "https://api.github.com/users/vsajip/orgs",
"repos_url": "https://api.github.com/users/vsajip/repos",
"events_url": "https://api.github.com/users/vsajip/events{/privacy}",
"received_events_url": "https://api.github.com/users/vsajip/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"`DateTimeField` uses a \"datetime\" column-type for the backend data-storage. In SQLite in particular, which does not have a date/time column type, it can be much more efficient to store the data as an integer timestamp. The `TimestampField` exists to allow you to work with Python `datetime` objects but store them in the database as integers.\r\n\r\nIf you are simply trying to store a floating-point timestamp, just use a `FloatField` or a `DoubleField`.",
"> and how is it best avoided?\r\n\r\nI have been working through this issue as I was inputting a timestamp from an API and just as you described, I would get a float field and a datetime in the different scenarios.\r\n\r\nFor anyone else coming across this issue, the solution for me was to convert the timestamp into a datetime object before creating the instance.\r\n\r\nIn the example by OP, you could use:\r\n`instance = MyModel.create(..., expiry=datetime.utcnow() + timedelta(seconds=86400), ...)`\r\nor similar, depending upon whether you need offset aware dates or not."
] | 2018-03-17T20:08:22 | 2020-07-02T09:23:43 | 2018-03-17T21:13:37 | NONE | null | If I have a model which has a timestamp field:
```
class MyModel(BaseModel):
...
expiry = TimestampField(utc=True, index=True, default=None)
...
```
If I then create an instance using e.g.
```
instance = MyModel.create(..., expiry=time.time() + 86400, ...)
```
then the type of `instance.expiry` is a `float`. However, if I access via a query, then it's a `datetime`:
```
instance = MyModel.select().first()
```
Is there a good reason for this inconsistency, and how is it best avoided?
| {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1542/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/1542/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1541 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1541/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1541/comments | https://api.github.com/repos/coleifer/peewee/issues/1541/events | https://github.com/coleifer/peewee/pull/1541 | 306,006,999 | MDExOlB1bGxSZXF1ZXN0MTc1NTkzMDY5 | 1,541 | Make connecting signals operation idempotent | {
"login": "bmwant",
"id": 3602533,
"node_id": "MDQ6VXNlcjM2MDI1MzM=",
"avatar_url": "https://avatars.githubusercontent.com/u/3602533?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/bmwant",
"html_url": "https://github.com/bmwant",
"followers_url": "https://api.github.com/users/bmwant/followers",
"following_url": "https://api.github.com/users/bmwant/following{/other_user}",
"gists_url": "https://api.github.com/users/bmwant/gists{/gist_id}",
"starred_url": "https://api.github.com/users/bmwant/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/bmwant/subscriptions",
"organizations_url": "https://api.github.com/users/bmwant/orgs",
"repos_url": "https://api.github.com/users/bmwant/repos",
"events_url": "https://api.github.com/users/bmwant/events{/privacy}",
"received_events_url": "https://api.github.com/users/bmwant/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"@coleifer could you review this one?",
"I don't think this is exactly a bug, and I don't love the solution proposed in this patch. I don't really think of registering a signal as an idempotent operation, and registering the same combination of receiver/name/sender seems like a user mistake.\r\n\r\nI've tried to address some of the quirks of connect/disconnect in two commits:\r\n\r\n* 8992c69ed8708d89e4f888d97b997a0232098141\r\n* 2d421a9db9ddc6223c35972291afe37bc2b20c68\r\n\r\nRegistering a handler twice for the same combination of receiver/name/sender will result in a `ValueError`. I'm not clear on how this would come up in practice, since when a module is imported once it continues to remain in the sys module cache. If you want to avoid side-effects you can do your registration in an init function that only runs once."
] | 2018-03-16T17:05:28 | 2018-03-16T18:55:09 | 2018-03-16T18:55:09 | NONE | null | ## Rationale
Attaching receivers should not crash a program.
## Use cases
1. Module has been reloaded
`m.py`
```
from peewee import *
from playhouse import signals
class A(signals.Model):
a = TextField(default='')
state = []
@signals.post_save(sender=A)
def post_save(sender, instance, created):
state.append((sender, instance, instance._pk, created))
```
and `test.py`
```
import m
try:
from importlib import reload
except ImportError:
pass
reload(m)
```
will raise `ValueError`.
2. We should allow assigning same receiver multiple times (it should be idempotent) to handle cases like this
`test2.py`
```
from peewee import *
from playhouse import signals
class A(signals.Model):
a = TextField(default='')
database = SqliteDatabase(':memory:')
A._meta.set_database(database)
A.create_table()
state = []
@signals.post_save(sender=A)
def post_save(sender, instance, created):
state.append((sender, instance, instance._pk, created))
def ensure_receivers_are_connected():
# I am not sure whether `flush` was invoked or not at some point
signals.post_save(sender=A)(post_save)
ensure_receivers_are_connected()
a = A(a='my text')
a.save()
assert len(state) == 1
```
But I guess we still need to prohibit binding in a such way function to different sender. In case you intentionally want to do such a thing you have `disconnect` method. | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1541/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/1541/timeline | null | null | false | {
"url": "https://api.github.com/repos/coleifer/peewee/pulls/1541",
"html_url": "https://github.com/coleifer/peewee/pull/1541",
"diff_url": "https://github.com/coleifer/peewee/pull/1541.diff",
"patch_url": "https://github.com/coleifer/peewee/pull/1541.patch",
"merged_at": null
} |
https://api.github.com/repos/coleifer/peewee/issues/1540 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1540/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1540/comments | https://api.github.com/repos/coleifer/peewee/issues/1540/events | https://github.com/coleifer/peewee/issues/1540 | 305,818,961 | MDU6SXNzdWUzMDU4MTg5NjE= | 1,540 | update_or_create is missing ? | {
"login": "elonzh",
"id": 8749411,
"node_id": "MDQ6VXNlcjg3NDk0MTE=",
"avatar_url": "https://avatars.githubusercontent.com/u/8749411?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/elonzh",
"html_url": "https://github.com/elonzh",
"followers_url": "https://api.github.com/users/elonzh/followers",
"following_url": "https://api.github.com/users/elonzh/following{/other_user}",
"gists_url": "https://api.github.com/users/elonzh/gists{/gist_id}",
"starred_url": "https://api.github.com/users/elonzh/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/elonzh/subscriptions",
"organizations_url": "https://api.github.com/users/elonzh/orgs",
"repos_url": "https://api.github.com/users/elonzh/repos",
"events_url": "https://api.github.com/users/elonzh/events{/privacy}",
"received_events_url": "https://api.github.com/users/elonzh/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"Because it's hard to correctly write a generic version of these methods that isn't vulnerable to race conditions. The proper way to implement this is very short, and as a result, I leave it up to users to implement their own method for create-or-get (similar workflow for insert-or-update):\r\n\r\n```python\r\n# create-or-get\r\ntry:\r\n with db.atomic():\r\n return SomeObj.create(...)\r\nexcept IntegrityError:\r\n return SomeObj.get(...)\r\n```"
] | 2018-03-16T06:46:54 | 2018-03-16T13:59:58 | 2018-03-16T13:59:58 | NONE | null | I'm curious that why the model method `update_or_create` is not provided.
https://github.com/coleifer/peewee/commit/073364ad89a8de48f4a25bbf6106bf42050d34fa | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1540/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/1540/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1539 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1539/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1539/comments | https://api.github.com/repos/coleifer/peewee/issues/1539/events | https://github.com/coleifer/peewee/issues/1539 | 305,226,342 | MDU6SXNzdWUzMDUyMjYzNDI= | 1,539 | db.batch_commit() mode | {
"login": "HarryR",
"id": 303926,
"node_id": "MDQ6VXNlcjMwMzkyNg==",
"avatar_url": "https://avatars.githubusercontent.com/u/303926?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/HarryR",
"html_url": "https://github.com/HarryR",
"followers_url": "https://api.github.com/users/HarryR/followers",
"following_url": "https://api.github.com/users/HarryR/following{/other_user}",
"gists_url": "https://api.github.com/users/HarryR/gists{/gist_id}",
"starred_url": "https://api.github.com/users/HarryR/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/HarryR/subscriptions",
"organizations_url": "https://api.github.com/users/HarryR/orgs",
"repos_url": "https://api.github.com/users/HarryR/repos",
"events_url": "https://api.github.com/users/HarryR/events{/privacy}",
"received_events_url": "https://api.github.com/users/HarryR/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"I originally thought that the `10` in the call to batch_commit() was the total number of batches, but on reading again I think you mean to imply a batch size of 10, or, a commit every 10 rows?\r\n\r\nSomething like that should be do-able, but it is probably cleaner to pass an iterator, e.g.:\r\n\r\n```python\r\n\r\nfor row in db.batch_commit(list_of_data, 100):\r\n Model.create(**row)\r\n```\r\n\r\nContinuing that thought, the `batch_commit` would be a generator that would:\r\n\r\n```python\r\n\r\n# Helper.\r\ndef chunked(iterable, n):\r\n marker = object()\r\n for group in (list(g) for g in izip_longest(*[iter(iterable)] * n,\r\n fillvalue=marker)):\r\n if group[-1] is marker:\r\n del group[group.index(marker):]\r\n yield group\r\n\r\n# method on Database\r\ndef batch_commit(self, it, n):\r\n for obj_group in chunked(it, n):\r\n with self.atomic():\r\n for obj in obj_group:\r\n yield obj\r\n```\r\n\r\nI didn't test this yet, so I'm not sure if it works. Just thinking out loud.",
"Added in 3d4e6e4."
] | 2018-03-14T16:09:38 | 2018-03-14T18:57:27 | 2018-03-14T18:57:27 | NONE | null | ```python
db = SqliteDatabase(':memory:')
with db.batch_commit(10):
for n in range(0, 1234):
Model.create(**...)
```
Every N'th model creation commits the transaction, the equivalent Python without `batch_commit` is:
```python
with db.manual_commit():
db.begin():
for n, row in enumerate(...):
Model.create(**row)
if n % 100 == 0:
db.commit()
db.begin()
db.commit()
```
Having a `batch_commit` would make it easier/simpler to make batch inserts faster.
Alternatively there is `Model.insert_many`, but to create multiple linked models at the same time the `batch_commit` method could be useful.
Using `db.atomic()` works unless you have a large number of items to insert, in that case periodic commits are used to ensure data is synchronised to disk, e.g.:
```python
with db.atomic():
for row in data:
row.update(defaults)
Model.create(**row)
```
it's probably easier to do it using a batch iterator instead of modifying peewee:
```python
for work in batch(rows, n=1234):
with db.atomic():
for row in work:
Model.create(**row)
```
Feel free to close, I answered own question... | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1539/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/1539/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1538 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1538/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1538/comments | https://api.github.com/repos/coleifer/peewee/issues/1538/events | https://github.com/coleifer/peewee/issues/1538 | 305,105,309 | MDU6SXNzdWUzMDUxMDUzMDk= | 1,538 | Introspector does not preserve capitalized columns name | {
"login": "ketozhang",
"id": 13506487,
"node_id": "MDQ6VXNlcjEzNTA2NDg3",
"avatar_url": "https://avatars.githubusercontent.com/u/13506487?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/ketozhang",
"html_url": "https://github.com/ketozhang",
"followers_url": "https://api.github.com/users/ketozhang/followers",
"following_url": "https://api.github.com/users/ketozhang/following{/other_user}",
"gists_url": "https://api.github.com/users/ketozhang/gists{/gist_id}",
"starred_url": "https://api.github.com/users/ketozhang/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/ketozhang/subscriptions",
"organizations_url": "https://api.github.com/users/ketozhang/orgs",
"repos_url": "https://api.github.com/users/ketozhang/repos",
"events_url": "https://api.github.com/users/ketozhang/events{/privacy}",
"received_events_url": "https://api.github.com/users/ketozhang/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"The introspector \"python-izes\" the column names by default. So if you have such a table, the actual field definition will look something like:\r\n\r\n```python\r\ndept = TextField(column_name='Dept')\r\n```\r\n\r\nIn this way, the actual underlying column-name is still preserved and used, it's just that the accessor for it conforms to a Pythonic naming convention.\r\n\r\nIf you want to use the column-names as-is, you can pass `literal_column_names=True` to the `introspect()` or `generate_models()` methods."
] | 2018-03-14T10:41:03 | 2018-03-16T14:00:10 | 2018-03-16T14:00:10 | NONE | null | Given a simple table like
```python
class Table(Model):
employee = CharField(unique=True)
Dept = TextField()
```
On the attempt in trying to introspect this table `models = Introspector.from_database(db).generate_models()`, the keys in `models['Table'].__dict__` are all lowercase:
```python
>>> models['Table'].__dict__
# psuedo output
mappingproxy({...,
'employee': <peewee.FieldDescriptor at 0x7f480108c748>,
'dept': <peewee.FieldDescriptor at 0x7f480108ceb8>, # want 'Dept' got 'dept'
...})
```
** Is there any way to preserve capitalized object names?**
---
The reason why I need this is because of such an insert statement:
```python
data = {
'employee' : 'John Smith'
'Dept' : 'Accounting'
}
Table.insert(**data) # or Table.create(**data) getting two different errors weirdly.
```
| {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1538/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/1538/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1537 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1537/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1537/comments | https://api.github.com/repos/coleifer/peewee/issues/1537/events | https://github.com/coleifer/peewee/issues/1537 | 305,097,899 | MDU6SXNzdWUzMDUwOTc4OTk= | 1,537 | how to get sql when save | {
"login": "visonforcoding",
"id": 4387302,
"node_id": "MDQ6VXNlcjQzODczMDI=",
"avatar_url": "https://avatars.githubusercontent.com/u/4387302?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/visonforcoding",
"html_url": "https://github.com/visonforcoding",
"followers_url": "https://api.github.com/users/visonforcoding/followers",
"following_url": "https://api.github.com/users/visonforcoding/following{/other_user}",
"gists_url": "https://api.github.com/users/visonforcoding/gists{/gist_id}",
"starred_url": "https://api.github.com/users/visonforcoding/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/visonforcoding/subscriptions",
"organizations_url": "https://api.github.com/users/visonforcoding/orgs",
"repos_url": "https://api.github.com/users/visonforcoding/repos",
"events_url": "https://api.github.com/users/visonforcoding/events{/privacy}",
"received_events_url": "https://api.github.com/users/visonforcoding/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"You can turn on query logging: http://docs.peewee-orm.com/en/latest/peewee/database.html#logging-queries\r\n\r\n```python\r\n# Print all queries to stderr.\r\nimport logging\r\nlogger = logging.getLogger('peewee')\r\nlogger.setLevel(logging.DEBUG)\r\nlogger.addHandler(logging.StreamHandler())\r\n```\r\n\r\nJust a guess, but if you're not able to save...are you explicitly specifying the primary key? In other words, is your primary key something other than an auto-incrementing integer? If so, check out:\r\n\r\nhttp://docs.peewee-orm.com/en/latest/peewee/models.html#id3"
] | 2018-03-14T10:19:17 | 2018-03-14T14:00:08 | 2018-03-14T14:00:08 | NONE | null | can i get the sql when i use save function . i don`t know why i can`t save. | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1537/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/1537/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1536 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1536/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1536/comments | https://api.github.com/repos/coleifer/peewee/issues/1536/events | https://github.com/coleifer/peewee/issues/1536 | 304,595,039 | MDU6SXNzdWUzMDQ1OTUwMzk= | 1,536 | DataSet thaw() exports dates in isoformat() which is not on the format list for DateTimeField | {
"login": "yevrah",
"id": 118672,
"node_id": "MDQ6VXNlcjExODY3Mg==",
"avatar_url": "https://avatars.githubusercontent.com/u/118672?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/yevrah",
"html_url": "https://github.com/yevrah",
"followers_url": "https://api.github.com/users/yevrah/followers",
"following_url": "https://api.github.com/users/yevrah/following{/other_user}",
"gists_url": "https://api.github.com/users/yevrah/gists{/gist_id}",
"starred_url": "https://api.github.com/users/yevrah/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/yevrah/subscriptions",
"organizations_url": "https://api.github.com/users/yevrah/orgs",
"repos_url": "https://api.github.com/users/yevrah/repos",
"events_url": "https://api.github.com/users/yevrah/events{/privacy}",
"received_events_url": "https://api.github.com/users/yevrah/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"This is a bit tricky because JSON should utilize ISO format, but Peewee really only has date-parsing logic to work-around the fact that SQLite doesn't have a native datetime data-type. By convention, Peewee has used the equivalent of Python's `__str__()` for datetime/date/time objects when persisting in SQLite.\r\n\r\nAdding more formats is certainly one route, but my preference is to just change the export format to match what peewee already can handle. Fewer changes. If you want ISO, you can always subclass and extend `DataSet`.",
"b65a8cb443a61ee0e861e4e79c7f66d4396a4488 -- `str()` instead of `isoformat`, includes test.",
"Thanks @coleifer makes much more sense. Didn't occur to me to fix it at the root, thought ISO made sense as it's also what I normally use. Cheers, much appreciated.",
"> ISO made sense\r\n\r\nWell that was the problem, it does make sense. But it seemed expedient to move to a serialization format that could inter-operate with Peewee as-is and leave implementing an ISO date format for a separate Exporter class."
] | 2018-03-13T01:18:25 | 2018-03-13T14:03:55 | 2018-03-13T03:18:09 | NONE | null | We are using a script to freeze copies of our staging and prod MySQL database. For development we are using SQLite, using the thawed data from MySQL. However, this issue can be replicated just from freezing and thawing between SQLite entities.
Test script below to show the issue.
```python
# test.py
from peewee import *
from datetime import datetime
from playhouse.dataset import DataSet
from os import remove
# Reset
try: remove('user.db')
except: pass
# Db
db = SqliteDatabase('user.db')
class User(Model):
name = CharField(default='John Doe')
last_login = DateTimeField()
class Meta:
database = db
class UserThawed(User):
pass
if __name__ == "__main__":
# Create entity
db.create_tables([User])
User(name='John Doe', last_login=datetime.now()).save()
# Blind Test
john = User().get()
print("\n\nOriginal Entity\n=====================")
print("Last Login: {}".format(john.last_login))
print("Type of: {}".format(type(john.last_login)))
# Freeze
ds = DataSet('sqlite:///user.db')
user = ds['user']
ds.freeze(user.all(), format='json', filename='user.json')
# Thaw
user_thawed = ds['userthawed']
user_thawed.thaw(format='json', filename='user.json')
# Blind Test for Thawed Item
john_thawed = UserThawed().get()
print("\n\nThawed Entity\n=====================")
print("Last Login: {}".format(john_thawed.last_login))
print("Type of: {}".format(type(john_thawed.last_login)))
```
Which outputs the following when run.
```bash
# Output from > python test.py
Original Entity
=====================
Last Login: 2018-03-13 12:06:29.403321
Type of: <class 'datetime.datetime'>
Thawed Entity
=====================
Last Login: 2018-03-13T12:06:29.403321
Type of: <class 'str'>
```
I noticed that freeze uses datetime.isoformat() to convert DateTimeField, and DateField - but this format is not in the format lists.
We have tested a quick fix by adding `DateTimeField.formats.append('%Y-%m-%dT%H:%M:%S')`, and `DateField.formats.append(''%Y-%m-%dT%H:%M:%S'')` to our models file - which resolved the MySQL to SqlLite issue.
From our testing between SQLite to SQLite, it would seem `'%Y-%m-%dT%H:%M:%S.%f'` would also need to be added to the list.
It would be great to have it added to the format lists at https://github.com/coleifer/peewee/blob/master/peewee.py#L3955 and https://github.com/coleifer/peewee/blob/master/peewee.py#L3974
Have not tested TimeField, and I haven't been able to dig around the code enough to understand if appending it to __sqlite_datetime_formats__, and __sqlite_date_trunc__ is necessary.
| {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1536/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/1536/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1535 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1535/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1535/comments | https://api.github.com/repos/coleifer/peewee/issues/1535/events | https://github.com/coleifer/peewee/pull/1535 | 304,187,131 | MDExOlB1bGxSZXF1ZXN0MTc0MjM4Mjk0 | 1,535 | Add big integer auto field support. | {
"login": "delobanov",
"id": 37274413,
"node_id": "MDQ6VXNlcjM3Mjc0NDEz",
"avatar_url": "https://avatars.githubusercontent.com/u/37274413?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/delobanov",
"html_url": "https://github.com/delobanov",
"followers_url": "https://api.github.com/users/delobanov/followers",
"following_url": "https://api.github.com/users/delobanov/following{/other_user}",
"gists_url": "https://api.github.com/users/delobanov/gists{/gist_id}",
"starred_url": "https://api.github.com/users/delobanov/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/delobanov/subscriptions",
"organizations_url": "https://api.github.com/users/delobanov/orgs",
"repos_url": "https://api.github.com/users/delobanov/repos",
"events_url": "https://api.github.com/users/delobanov/events{/privacy}",
"received_events_url": "https://api.github.com/users/delobanov/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"Replaced with cleaner implementation in 37e538f. Thanks."
] | 2018-03-11T19:42:00 | 2018-03-11T20:21:42 | 2018-03-11T20:21:42 | NONE | null | I added a new class that represents 8 bit autoincrement field. Tested this on postgresql. | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1535/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/1535/timeline | null | null | false | {
"url": "https://api.github.com/repos/coleifer/peewee/pulls/1535",
"html_url": "https://github.com/coleifer/peewee/pull/1535",
"diff_url": "https://github.com/coleifer/peewee/pull/1535.diff",
"patch_url": "https://github.com/coleifer/peewee/pull/1535.patch",
"merged_at": null
} |
https://api.github.com/repos/coleifer/peewee/issues/1534 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1534/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1534/comments | https://api.github.com/repos/coleifer/peewee/issues/1534/events | https://github.com/coleifer/peewee/issues/1534 | 304,104,389 | MDU6SXNzdWUzMDQxMDQzODk= | 1,534 | Incorrect SQL for integer-returning `Case()` within `fn.SUM()`, with PostgreSQL | {
"login": "a-p-",
"id": 4145331,
"node_id": "MDQ6VXNlcjQxNDUzMzE=",
"avatar_url": "https://avatars.githubusercontent.com/u/4145331?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/a-p-",
"html_url": "https://github.com/a-p-",
"followers_url": "https://api.github.com/users/a-p-/followers",
"following_url": "https://api.github.com/users/a-p-/following{/other_user}",
"gists_url": "https://api.github.com/users/a-p-/gists{/gist_id}",
"starred_url": "https://api.github.com/users/a-p-/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/a-p-/subscriptions",
"organizations_url": "https://api.github.com/users/a-p-/orgs",
"repos_url": "https://api.github.com/users/a-p-/repos",
"events_url": "https://api.github.com/users/a-p-/events{/privacy}",
"received_events_url": "https://api.github.com/users/a-p-/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"Thank you for the excellent report. I was able to replicate this and found a bug related to updating mutable scope-specific settings in-place instead of copying. Should be fixed. I'll push a new bugfix release shortly.",
"I'm getting the same error and wondering when this can be fixed? Thanks.",
"The example above is working correctly for me, and as the comment I made on Mar 10, 2018 indicates - this fix was merged quite a long time ago.\r\n\r\nIf you can provide an example illustrating the error you're receiving I will look into it.",
"Here is the [example](https://stackoverflow.com/questions/63627858/get-error-when-using-sum-and-case-in-sqlalchemy/63631184#63631184). Then I realized this looks like a bug related to `SQLAlchemy` or `asyncpg` instead. Please take a look and would like to know your expertise thought on this. Thanks.",
"I'm confused. You're reporting an issue on the peewee issue tracker, but saying the bug is with sqlalchemy and asyncpg."
] | 2018-03-10T20:54:55 | 2020-08-29T18:04:09 | 2018-03-10T22:18:54 | NONE | null | Peewee 3.1.2 appears to be generating incorrect SQL for a `Case()` call that evaluates to an integer within an `fn.SUM()` call, when using PostgreSQL (10.1).
Some simplified example code to reproduce the problem is at the bottom.
The query is like:
```python
query = Example.select(
Example.name,
fn.SUM(Case(None, [(('A' == Example.status), 1)], 0)).alias('status_a_count')
).group_by(Example.name)
```
Iterating over the results results in an exception like:
```
psycopg2.ProgrammingError: function sum(text) does not exist
LINE 1: SELECT "t1"."name", SUM(CASE WHEN ("t1"."status" = 'A') THEN...
^
HINT: No function matches the given name and argument types. You might need to add explicit type casts.
```
The Peewee logging emits this:
```
('SELECT "t1"."name", SUM(CASE WHEN ("t1"."status" = %s) THEN %s ELSE %s END) AS "status_a_count" FROM "example" AS "t1" GROUP BY "t1"."name"', ['A', '1', '0'])
```
And the PostgreSQL log includes:
```
ERROR: function sum(text) does not exist at character 21
HINT: No function matches the given name and argument types. You might need to add explicit type casts.
STATEMENT: SELECT "t1"."name", SUM(CASE WHEN ("t1"."status" = 'A') THEN '1' ELSE '0' END) AS "status_a_count" FROM "example" AS "t1" GROUP BY "t1"."name"
```
Looks like the `1` and `0` integer literals within the Python code end up as string literals `'1'` and `'0'`, instead of integer literals, in the generated SQL query.
Example code:
```python
#!/usr/bin/env python3.6
import logging
import random
from peewee import *
import playhouse.postgres_ext
database = playhouse.postgres_ext.PostgresqlExtDatabase(database='test')
# Sample table to query against.
class Example(Model):
class Meta:
database = database
id = AutoField()
name = TextField()
status = TextField()
database.connect()
with database.atomic() as transaction:
database.create_tables([Example])
# Populate the sample table with some sample data.
for i in range(0, 100):
example = Example(
name=random.choice(['Name-0', 'Name-1', 'Name-2', 'Name-3']),
status=random.choice(['A', 'B', 'C', 'D'])
)
example.save()
# Enable logging.
logger = logging.getLogger('peewee')
logger.setLevel(logging.DEBUG)
logger.addHandler(logging.StreamHandler())
# Problematic query...
query = Example.select(
Example.name,
fn.SUM(Case(None, [(('A' == Example.status), 1)], 0)).alias('status_a_count')
).group_by(Example.name)
for row in query:
print(row.status_a_count)
transaction.rollback()
database.close()
```
| {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1534/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/1534/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1533 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1533/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1533/comments | https://api.github.com/repos/coleifer/peewee/issues/1533/events | https://github.com/coleifer/peewee/issues/1533 | 304,070,815 | MDU6SXNzdWUzMDQwNzA4MTU= | 1,533 | ProgrammingError during get_or_create | {
"login": "jonathan-s",
"id": 2124818,
"node_id": "MDQ6VXNlcjIxMjQ4MTg=",
"avatar_url": "https://avatars.githubusercontent.com/u/2124818?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/jonathan-s",
"html_url": "https://github.com/jonathan-s",
"followers_url": "https://api.github.com/users/jonathan-s/followers",
"following_url": "https://api.github.com/users/jonathan-s/following{/other_user}",
"gists_url": "https://api.github.com/users/jonathan-s/gists{/gist_id}",
"starred_url": "https://api.github.com/users/jonathan-s/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/jonathan-s/subscriptions",
"organizations_url": "https://api.github.com/users/jonathan-s/orgs",
"repos_url": "https://api.github.com/users/jonathan-s/repos",
"events_url": "https://api.github.com/users/jonathan-s/events{/privacy}",
"received_events_url": "https://api.github.com/users/jonathan-s/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"I'm using peewee-async so it may have to do with that library. Checking.. "
] | 2018-03-10T13:30:28 | 2018-03-10T14:19:22 | 2018-03-10T14:19:22 | NONE | null | I'm running Postgres with peewee 2.10.2
When running the following code:
```
Author.get_or_create(
id=author['id'],
defaults=author
)
```
I get syntax error at or near "AS" `LINE 1: ...t1"."country" FROM "author" AS t1 WHERE ("author" AS t1 AND ...` It happens for the second AS. The full query is the following.
```
SELECT "t1"."id", "t1"."ctime", "t1"."mtime", "t1"."name", "t1"."gender", "t1"."country"
FROM "author" AS t1
WHERE ("author" AS t1 AND ("t1"."id" = %s)) [16667]
``` | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1533/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/1533/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1532 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1532/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1532/comments | https://api.github.com/repos/coleifer/peewee/issues/1532/events | https://github.com/coleifer/peewee/issues/1532 | 304,067,837 | MDU6SXNzdWUzMDQwNjc4Mzc= | 1,532 | Flat tuples | {
"login": "jonathan-s",
"id": 2124818,
"node_id": "MDQ6VXNlcjIxMjQ4MTg=",
"avatar_url": "https://avatars.githubusercontent.com/u/2124818?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/jonathan-s",
"html_url": "https://github.com/jonathan-s",
"followers_url": "https://api.github.com/users/jonathan-s/followers",
"following_url": "https://api.github.com/users/jonathan-s/following{/other_user}",
"gists_url": "https://api.github.com/users/jonathan-s/gists{/gist_id}",
"starred_url": "https://api.github.com/users/jonathan-s/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/jonathan-s/subscriptions",
"organizations_url": "https://api.github.com/users/jonathan-s/orgs",
"repos_url": "https://api.github.com/users/jonathan-s/repos",
"events_url": "https://api.github.com/users/jonathan-s/events{/privacy}",
"received_events_url": "https://api.github.com/users/jonathan-s/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"You can easily write a little transform:\r\n\r\n```python\r\n\r\nimport operator\r\nflat_transform = lambda query: map(operator.itemgetter(0), query)\r\n\r\nx = [(1,), (2,), (3,), (4,)]\r\nlist(flat_transform(x)) # [1, 2, 3, 4]\r\n```"
] | 2018-03-10T12:42:21 | 2018-03-10T15:21:04 | 2018-03-10T15:21:04 | NONE | null | It would be nice if there was an option to return tuples that were flat. Much like the django queryset `values_list(flat=True)`. | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1532/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/1532/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1531 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1531/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1531/comments | https://api.github.com/repos/coleifer/peewee/issues/1531/events | https://github.com/coleifer/peewee/pull/1531 | 303,933,250 | MDExOlB1bGxSZXF1ZXN0MTc0MDczMzUx | 1,531 | Support prefetching ManyToManyFields | {
"login": "iBelieve",
"id": 3230912,
"node_id": "MDQ6VXNlcjMyMzA5MTI=",
"avatar_url": "https://avatars.githubusercontent.com/u/3230912?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/iBelieve",
"html_url": "https://github.com/iBelieve",
"followers_url": "https://api.github.com/users/iBelieve/followers",
"following_url": "https://api.github.com/users/iBelieve/following{/other_user}",
"gists_url": "https://api.github.com/users/iBelieve/gists{/gist_id}",
"starred_url": "https://api.github.com/users/iBelieve/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/iBelieve/subscriptions",
"organizations_url": "https://api.github.com/users/iBelieve/orgs",
"repos_url": "https://api.github.com/users/iBelieve/repos",
"events_url": "https://api.github.com/users/iBelieve/events{/privacy}",
"received_events_url": "https://api.github.com/users/iBelieve/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"Interesting... Since the `prefetch` API requires the specification of the intervening models, it *does* seem a bit un-intuitive to access the related instances through the many-to-many field. Or maybe it is intuitive? I'm not sure...ManyToManyField is such a hack!",
"At least for my use case, it feels intuitive, as I'm trying to fetch a list of users and their teams. I'm using prefetch as an optimization to prevent an N+1 situation for fetching teams for each user, so it feels most intuitive to access prefetched teams through the ManyToManyField.\r\n\r\nBasically, I'd like to go from this:\r\n\r\n```\r\nfor user in User.select():\r\n print(user.teams)\r\n```\r\n\r\nto the optimized version:\r\n\r\n```\r\nfor user in prefetch(User.select(), TeamMember, Team):\r\n print(user.teams)\r\n```\r\n\r\nWithout this, I'd have to do something like:\r\n\r\n```\r\nfor user in prefetch(User.select(), TeamMember, Team):\r\n teams = [through.team for through in user.teammember_set]\r\n print(teams)\r\n```\r\n\r\nWhich feels un-intuitive and requires that I treat prefetched queries differently from regular queries. Of course, the alternative is do not use ManyToManyField and just have a property on user that fetches teams which also works with prefetched, but for my use case ManyToManyField is simple and meets my needs.",
"Agreed, thanks for the patch!"
] | 2018-03-09T18:17:35 | 2018-03-10T04:05:31 | 2018-03-10T04:05:30 | CONTRIBUTOR | null | Previously, prefetching a relationship exposed in a ManyToMany field would only expose the through model’s prefetched data. Now, the many to many field correctly exposes the prefetched data via the through field’s prefetched results, rather than requerying what has already been prefetched. | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1531/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/1531/timeline | null | null | false | {
"url": "https://api.github.com/repos/coleifer/peewee/pulls/1531",
"html_url": "https://github.com/coleifer/peewee/pull/1531",
"diff_url": "https://github.com/coleifer/peewee/pull/1531.diff",
"patch_url": "https://github.com/coleifer/peewee/pull/1531.patch",
"merged_at": "2018-03-10T04:05:30"
} |
https://api.github.com/repos/coleifer/peewee/issues/1530 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1530/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1530/comments | https://api.github.com/repos/coleifer/peewee/issues/1530/events | https://github.com/coleifer/peewee/issues/1530 | 303,890,280 | MDU6SXNzdWUzMDM4OTAyODA= | 1,530 | Why ForeignKeyAccessor.__set__() doesn't update instance._dirty? | {
"login": "TwoAnts",
"id": 5968383,
"node_id": "MDQ6VXNlcjU5NjgzODM=",
"avatar_url": "https://avatars.githubusercontent.com/u/5968383?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/TwoAnts",
"html_url": "https://github.com/TwoAnts",
"followers_url": "https://api.github.com/users/TwoAnts/followers",
"following_url": "https://api.github.com/users/TwoAnts/following{/other_user}",
"gists_url": "https://api.github.com/users/TwoAnts/gists{/gist_id}",
"starred_url": "https://api.github.com/users/TwoAnts/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/TwoAnts/subscriptions",
"organizations_url": "https://api.github.com/users/TwoAnts/orgs",
"repos_url": "https://api.github.com/users/TwoAnts/repos",
"events_url": "https://api.github.com/users/TwoAnts/events{/privacy}",
"received_events_url": "https://api.github.com/users/TwoAnts/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"Fixed, thanks for reporting."
] | 2018-03-09T16:02:52 | 2018-03-09T16:27:21 | 2018-03-09T16:26:34 | NONE | null | I use `=` to set a `ForeignKeyField` and call `save()` method, but it doesn't take effect.
When I read the source code in peewee.py, I found that `ForeignKeyAccessor.__set__()` seems not to update the `instance._dirty` . This leads to a failure to update `ForeignKeyField` by calling `save()` method.
Please fix it, if it is a bug.
| {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1530/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/1530/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1529 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1529/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1529/comments | https://api.github.com/repos/coleifer/peewee/issues/1529/events | https://github.com/coleifer/peewee/pull/1529 | 303,666,019 | MDExOlB1bGxSZXF1ZXN0MTczODc2OTY0 | 1,529 | Clarify that safe=True is the default behaviour. The existing doc sounded like it was False by default. | {
"login": "bryhoyt",
"id": 4769854,
"node_id": "MDQ6VXNlcjQ3Njk4NTQ=",
"avatar_url": "https://avatars.githubusercontent.com/u/4769854?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/bryhoyt",
"html_url": "https://github.com/bryhoyt",
"followers_url": "https://api.github.com/users/bryhoyt/followers",
"following_url": "https://api.github.com/users/bryhoyt/following{/other_user}",
"gists_url": "https://api.github.com/users/bryhoyt/gists{/gist_id}",
"starred_url": "https://api.github.com/users/bryhoyt/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/bryhoyt/subscriptions",
"organizations_url": "https://api.github.com/users/bryhoyt/orgs",
"repos_url": "https://api.github.com/users/bryhoyt/repos",
"events_url": "https://api.github.com/users/bryhoyt/events{/privacy}",
"received_events_url": "https://api.github.com/users/bryhoyt/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [] | 2018-03-08T23:08:42 | 2018-03-09T15:00:25 | 2018-03-09T15:00:25 | CONTRIBUTOR | null | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1529/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/1529/timeline | null | null | false | {
"url": "https://api.github.com/repos/coleifer/peewee/pulls/1529",
"html_url": "https://github.com/coleifer/peewee/pull/1529",
"diff_url": "https://github.com/coleifer/peewee/pull/1529.diff",
"patch_url": "https://github.com/coleifer/peewee/pull/1529.patch",
"merged_at": "2018-03-09T15:00:25"
} |
|
https://api.github.com/repos/coleifer/peewee/issues/1528 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1528/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1528/comments | https://api.github.com/repos/coleifer/peewee/issues/1528/events | https://github.com/coleifer/peewee/pull/1528 | 303,665,295 | MDExOlB1bGxSZXF1ZXN0MTczODc2Mzgw | 1,528 | Clarify comment that sounded like create_tables() in Peewee 3 will dr… | {
"login": "bryhoyt",
"id": 4769854,
"node_id": "MDQ6VXNlcjQ3Njk4NTQ=",
"avatar_url": "https://avatars.githubusercontent.com/u/4769854?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/bryhoyt",
"html_url": "https://github.com/bryhoyt",
"followers_url": "https://api.github.com/users/bryhoyt/followers",
"following_url": "https://api.github.com/users/bryhoyt/following{/other_user}",
"gists_url": "https://api.github.com/users/bryhoyt/gists{/gist_id}",
"starred_url": "https://api.github.com/users/bryhoyt/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/bryhoyt/subscriptions",
"organizations_url": "https://api.github.com/users/bryhoyt/orgs",
"repos_url": "https://api.github.com/users/bryhoyt/repos",
"events_url": "https://api.github.com/users/bryhoyt/events{/privacy}",
"received_events_url": "https://api.github.com/users/bryhoyt/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"Cheers!"
] | 2018-03-08T23:05:32 | 2018-03-09T15:00:08 | 2018-03-09T15:00:03 | CONTRIBUTOR | null | …op your table if it exists.
This scared me on first read. I had to read it a couple times to figure out that the second part of the parenthetical comment was talking about the drop_tables() method. And I had to read the source code to be fully sure.
I like the updated functionality, though. It's a great improvement, thanks! | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1528/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/1528/timeline | null | null | false | {
"url": "https://api.github.com/repos/coleifer/peewee/pulls/1528",
"html_url": "https://github.com/coleifer/peewee/pull/1528",
"diff_url": "https://github.com/coleifer/peewee/pull/1528.diff",
"patch_url": "https://github.com/coleifer/peewee/pull/1528.patch",
"merged_at": "2018-03-09T15:00:03"
} |
https://api.github.com/repos/coleifer/peewee/issues/1527 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1527/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1527/comments | https://api.github.com/repos/coleifer/peewee/issues/1527/events | https://github.com/coleifer/peewee/issues/1527 | 302,081,403 | MDU6SXNzdWUzMDIwODE0MDM= | 1,527 | Postgres Match returns only one result | {
"login": "metakermit",
"id": 1818628,
"node_id": "MDQ6VXNlcjE4MTg2Mjg=",
"avatar_url": "https://avatars.githubusercontent.com/u/1818628?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/metakermit",
"html_url": "https://github.com/metakermit",
"followers_url": "https://api.github.com/users/metakermit/followers",
"following_url": "https://api.github.com/users/metakermit/following{/other_user}",
"gists_url": "https://api.github.com/users/metakermit/gists{/gist_id}",
"starred_url": "https://api.github.com/users/metakermit/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/metakermit/subscriptions",
"organizations_url": "https://api.github.com/users/metakermit/orgs",
"repos_url": "https://api.github.com/users/metakermit/repos",
"events_url": "https://api.github.com/users/metakermit/events{/privacy}",
"received_events_url": "https://api.github.com/users/metakermit/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"Not sure what the issue might be, but the `Match` function is tested and returns multiple results where appropriate. Perhaps there's an issue with the query you're providing?",
"Example ipython notebook showing it working:\r\n\r\nhttps://gist.github.com/coleifer/cee34b9db777c76de95a0c717aadd030"
] | 2018-03-04T12:22:45 | 2018-03-04T16:29:52 | 2018-03-04T16:29:52 | NONE | null | Hi, I'm using the `Match` functionality to access Postgres' [full-text search](http://docs.peewee-orm.com/en/latest/peewee/playhouse.html#pg-fts) (`from playhouse.postgres_ext import Match`), but I only get 1 result.
For comparison, using the same search query (just a single word) the `contains` query returns more results. How can I access all the results from a `Match`?
```
ipdb> len([m for m in Act.select().where(Act.content.contains(query))])
66
ipdb> len([m for m in Act.select().where(Match(Act.content, query))])
1
``` | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1527/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/1527/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1526 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1526/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1526/comments | https://api.github.com/repos/coleifer/peewee/issues/1526/events | https://github.com/coleifer/peewee/issues/1526 | 301,951,733 | MDU6SXNzdWUzMDE5NTE3MzM= | 1,526 | Get all results from a Select Query without specifying columns | {
"login": "ketozhang",
"id": 13506487,
"node_id": "MDQ6VXNlcjEzNTA2NDg3",
"avatar_url": "https://avatars.githubusercontent.com/u/13506487?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/ketozhang",
"html_url": "https://github.com/ketozhang",
"followers_url": "https://api.github.com/users/ketozhang/followers",
"following_url": "https://api.github.com/users/ketozhang/following{/other_user}",
"gists_url": "https://api.github.com/users/ketozhang/gists{/gist_id}",
"starred_url": "https://api.github.com/users/ketozhang/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/ketozhang/subscriptions",
"organizations_url": "https://api.github.com/users/ketozhang/orgs",
"repos_url": "https://api.github.com/users/ketozhang/repos",
"events_url": "https://api.github.com/users/ketozhang/events{/privacy}",
"received_events_url": "https://api.github.com/users/ketozhang/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"I'm not sure about your definition for the `User` model you've used in your examples, but presumably it has fields on it besides the ID?\r\n\r\nLet's look at some examples:\r\n\r\n```python\r\nclass User(Model):\r\n username = TextField()\r\n```\r\n\r\nThe user model in these examples has a username field, as well as an implicit \"id\" field. As you will see, `User.select()` will select all the columns in the table by default. The query is iterable and the results it yields are, by default, instances of the model class. You can, if you like, get different objects from the cursor as the examples below show:\r\n\r\n```python\r\nIn [7]: query = User.select().where(User.id.between(0, 3))\r\n\r\nIn [8]: for user in query:\r\n ...: print(user.id, user.username)\r\n ...: \r\n1 huey\r\n2 charlie\r\n3 mickey\r\n\r\nIn [9]: for user_dict in query.dicts():\r\n ...: print(user_dict)\r\n ...: \r\n{'id': 1, 'username': 'huey'}\r\n{'id': 2, 'username': 'charlie'}\r\n{'id': 3, 'username': 'mickey'}\r\n\r\nIn [10]: for user_row in query.namedtuples():\r\n ...: print(user_row)\r\n ...: \r\nRow(id=1, username='huey')\r\nRow(id=2, username='charlie')\r\nRow(id=3, username='mickey')\r\n```\r\n\r\nThere's no magic \".all()\" you need... simply iterate over the `Select` query itself. If you explicitly want a cursor-wrapper (though there's no need, as the query itself is fine to use), you can use the return value of `Select.execute()`.\r\n\r\nDoes this answer your question?\r\n\r\nPS - I'm finding it hard to believe you've read the docs if you are confused on this... it's covered by the quick-start if you'd like a refresher.",
"If you want to work with python lists of objects, just wrap the query in `list(...)`, although there's no need to as the query itself is iterable.\r\n\r\n```python\r\nIn [11]: query = User.select().where(User.id < 4)\r\n\r\nIn [12]: list(query)\r\nOut[12]: \r\n[<__main__.User at 0x7f983115b240>,\r\n <__main__.User at 0x7f983115b828>,\r\n <__main__.User at 0x7f9831157ac8>]\r\n\r\nIn [13]: list(query.dicts())\r\nOut[13]: \r\n[{'id': 1, 'username': 'huey'},\r\n {'id': 2, 'username': 'charlie'},\r\n {'id': 3, 'username': 'mickey'}]\r\n\r\nIn [14]: [x for x in query]\r\nOut[14]: \r\n[<__main__.User at 0x7f983115b240>,\r\n <__main__.User at 0x7f983115b828>,\r\n <__main__.User at 0x7f9831157ac8>]\r\n\r\nIn [15]: [x for x in query.dicts()]\r\nOut[15]: \r\n[{'id': 1, 'username': 'huey'},\r\n {'id': 2, 'username': 'charlie'},\r\n {'id': 3, 'username': 'mickey'}]\r\n```",
"@coleifer Thank you\r\n\r\nI've now found the documentation hidden away in the near last row of **querying**\r\nhttp://docs.peewee-orm.com/en/latest/peewee/querying.html?highlight=dicts()#retrieving-row-tuples-dictionaries-namedtuples\r\n\r\n>PS - I'm finding it hard to believe you've read the docs if you are confused on this... it's covered by the quick-start if you'd like a refresher.\r\n\r\nNo, it is not in [quickstart](http://docs.peewee-orm.com/en/latest/peewee/quickstart.html#lists-of-records), majority of the documentation extract results by knowing which columns you specifically want. There is rarely any documentation on all columns for instance:\r\n\r\n```python\r\nquery = (Pet\r\n .select(Pet, Person)\r\n .join(Person)\r\n .where(Pet.animal_type == 'cat'))\r\n\r\nfor pet in query:\r\n print(pet.name, pet.owner.name) #this is great if I only want name and owner's name\r\n```\r\n\r\n My suggestion is to highlight the `query.dicts()` method. I simply could've just searched for 'dicts' however majority of your documentation that uses dictionary are for query building see [here](http://docs.peewee-orm.com/en/latest/search.html?q=dict&check_keywords=yes&area=default)\r\n\r\n>There's no magic \".all()\" you need... simply iterate over the Select query itself. If you explicitly want a cursor-wrapper (though there's no need, as the query itself is fine to use), you can use the return value of Select.execute().\r\n\r\nI believe I've used this before but the query returned nothing (while it shouldn't)\r\n```python\r\nquery = User.select()\r\nrow1 = query.execute().cursor.fetchone()\r\n```\r\n\r\nThank you very much, this does solve my problem!\r\n",
"> I believe I've used this before but the query returned nothing (while it shouldn't)\r\n\r\nYou're using private APIs... really you shouldn't need to access the DB-API 2.0 cursor at all since Peewee provides cursor-wrappers that are efficient.\r\n\r\n```python\r\nquery = User.select()\r\na_row = query.get()\r\n\r\n# Or,\r\na_row = query[0]\r\n\r\n# Or,\r\na_row = query.first()\r\n```\r\n\r\nRemember that with select queries there's no need to explicitly call `execute()` -- they will execute implicitly when iterated (or if you call `.get()` or `.first()` on them).",
"`row1 = query.execute().cursor.fetchone()` was constructed from your following statement:\r\n\r\n>If you explicitly want a cursor-wrapper (though there's no need, as the query itself is fine to use), you can use the return value of Select.execute().\r\n\r\nI must have interpreted it wrong.",
"Calling `execute()` on a select query returns a cursor-like object but it is not a db-api cursor. Again, not necessary as the query itself should be treated like a cursor."
] | 2018-03-03T01:03:25 | 2018-03-03T01:55:07 | 2018-03-03T01:32:48 | NONE | null | Hi, so far I've read majority of the documentation on peewee. While there are plenty of instructions on how to create a SelectQuery [[1]](http://docs.peewee-orm.com/en/latest/peewee/querying.html
)[[2]](http://docs.peewee-orm.com/en/latest/peewee/query_examples.html#basic-exercises). There is no example on extracting everything about the results (list of rows). One would expect a query statement from SQL return a table-like. I've come from using SQLalchemy expression language to peewee ORM. I have no background on Flask
Throughout reading the whole documentation and a whole page of google results I've never found the proper use of SelectQuery.
### Goal: Extract a range of entries from SQL
**Not very useful as it only returns PK**
```python
db = SqliteDatabase(...)
query = User.select().where(User.id.between(0,100))
cursor = db.execute(query)
print(cursor.fetchone()) # prints primary key
```
**If the previous one only return PK why does this return everything**
```python
query = User.select()
cursor = db.execute_sql()(*query)
print(cursor.fetchone()) # prints a row as a tuple!!
```
**Bad practice, but works perfectly 👍**
```python
query = User.select().where(User.id.between(0,100))
rows = [row._data for row in query]
```
**Now I'm just being hopeful**
```
import pandas as pd
query = User.select().where(User.id.between(0,100))
pd.read_sql(query.sql()) # this is obviously incorrect
```
Either I am very ignorant about how ORM work... actually [SQLAchemy supports this](http://docs.sqlalchemy.org/en/latest/orm/tutorial.html#returning-lists-and-scalars):
..or there is some missing about peewee that the developers decided it is not within the scope of peewee to take care of. So is there a method from query that is on the lines of
```python
query = User.select().where(User.id.between(0,100))
rows = query.all() # a list of results or rows, no need to be dictionary but preferable
```
*Similar concerns:*
* #134
* [Is there a way to query.all() in peewee?
](https://stackoverflow.com/questions/43755511/is-there-a-way-to-query-all-in-peewee)
* [Get full result back from PeeWee query (for conversion to JSON)](https://stackoverflow.com/questions/35225682/get-full-result-back-from-peewee-query-for-conversion-to-json?rq=1) | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1526/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/1526/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1525 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1525/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1525/comments | https://api.github.com/repos/coleifer/peewee/issues/1525/events | https://github.com/coleifer/peewee/issues/1525 | 301,635,789 | MDU6SXNzdWUzMDE2MzU3ODk= | 1,525 | execute_sql() got an unexpected keyword argument 'commit' | {
"login": "jcrevits",
"id": 11039634,
"node_id": "MDQ6VXNlcjExMDM5NjM0",
"avatar_url": "https://avatars.githubusercontent.com/u/11039634?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/jcrevits",
"html_url": "https://github.com/jcrevits",
"followers_url": "https://api.github.com/users/jcrevits/followers",
"following_url": "https://api.github.com/users/jcrevits/following{/other_user}",
"gists_url": "https://api.github.com/users/jcrevits/gists{/gist_id}",
"starred_url": "https://api.github.com/users/jcrevits/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/jcrevits/subscriptions",
"organizations_url": "https://api.github.com/users/jcrevits/orgs",
"repos_url": "https://api.github.com/users/jcrevits/repos",
"events_url": "https://api.github.com/users/jcrevits/events{/privacy}",
"received_events_url": "https://api.github.com/users/jcrevits/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"I'm not sure I follow. In your database class have you overridden the `execute_sql` method?\r\n\r\nIf you look at the signature of `execute_sql` you'll see:\r\n\r\n```python\r\n def execute_sql(self, sql, params=None, commit=SENTINEL):\r\n```\r\n\r\nI don't see `execute_sql()` being overridden by either `PostgresqlExtDatabase` or the `Pooled`-database classes, so I'm not sure what could be happening.",
"Mmmm, I didn't write the original code but it looks like your instincts were right - someone overwrote the `execute_sql` method for some reason. Sorry for making you check - will close this issue! 🙇 "
] | 2018-03-02T02:52:07 | 2018-03-05T02:27:58 | 2018-03-05T02:27:58 | NONE | null | Hi there, good job on the new version and I've been trying to upgrade one of our (older) systems that uses peewee. However I've been encountering the issue below. Does the traceback speak to you? This is with using postgres and `PooledPostgresqlExtDatabase`. Thank you and "hopefully" this is not on my side! (i.e. it's an actual bug)
```
Traceback (most recent call last):
File "/home/travis/build/[secure]/[repo]/tests/controllers/test_proofread.py", line 17, in setUp
self.parser = ParserModel.create(name='TestParser', code='tp', extension="xlsx")
File "/home/travis/virtualenv/python3.6.3/lib/python3.6/site-packages/peewee.py", line 5102, in create
inst.save(force_insert=True)
File "/home/travis/virtualenv/python3.6.3/lib/python3.6/site-packages/playhouse/signals.py", line 64, in save
ret = super(Model, self).save(*args, **kwargs)
File "/home/travis/virtualenv/python3.6.3/lib/python3.6/site-packages/peewee.py", line 5225, in save
pk_from_cursor = self.insert(**field_dict).execute()
File "/home/travis/virtualenv/python3.6.3/lib/python3.6/site-packages/peewee.py", line 1451, in inner
return method(self, database, *args, **kwargs)
File "/home/travis/virtualenv/python3.6.3/lib/python3.6/site-packages/peewee.py", line 1522, in execute
return self._execute(database)
File "/home/travis/virtualenv/python3.6.3/lib/python3.6/site-packages/peewee.py", line 2154, in _execute
return super(Insert, self)._execute(database)
File "/home/travis/virtualenv/python3.6.3/lib/python3.6/site-packages/peewee.py", line 1928, in _execute
cursor = self.execute_returning(database)
File "/home/travis/virtualenv/python3.6.3/lib/python3.6/site-packages/peewee.py", line 1935, in execute_returning
cursor = database.execute(self)
File "/home/travis/virtualenv/python3.6.3/lib/python3.6/site-packages/playhouse/postgres_ext.py", line 426, in execute
cursor = self.execute_sql(sql, params, commit=commit)
TypeError: execute_sql() got an unexpected keyword argument 'commit'Traceback (most recent call last):
File "/home/travis/build/[secure]/nashville-parser/tests/controllers/test_proofread.py", line 17, in setUp
self.parser = ParserModel.create(name='TestParser', code='tp', extension="xlsx")
File "/home/travis/virtualenv/python3.6.3/lib/python3.6/site-packages/peewee.py", line 5102, in create
inst.save(force_insert=True)
File "/home/travis/virtualenv/python3.6.3/lib/python3.6/site-packages/playhouse/signals.py", line 64, in save
ret = super(Model, self).save(*args, **kwargs)
File "/home/travis/virtualenv/python3.6.3/lib/python3.6/site-packages/peewee.py", line 5225, in save
pk_from_cursor = self.insert(**field_dict).execute()
File "/home/travis/virtualenv/python3.6.3/lib/python3.6/site-packages/peewee.py", line 1451, in inner
return method(self, database, *args, **kwargs)
File "/home/travis/virtualenv/python3.6.3/lib/python3.6/site-packages/peewee.py", line 1522, in execute
return self._execute(database)
File "/home/travis/virtualenv/python3.6.3/lib/python3.6/site-packages/peewee.py", line 2154, in _execute
return super(Insert, self)._execute(database)
File "/home/travis/virtualenv/python3.6.3/lib/python3.6/site-packages/peewee.py", line 1928, in _execute
cursor = self.execute_returning(database)
File "/home/travis/virtualenv/python3.6.3/lib/python3.6/site-packages/peewee.py", line 1935, in execute_returning
cursor = database.execute(self)
File "/home/travis/virtualenv/python3.6.3/lib/python3.6/site-packages/playhouse/postgres_ext.py", line 426, in execute
cursor = self.execute_sql(sql, params, commit=commit)
TypeError: execute_sql() got an unexpected keyword argument 'commit'
``` | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1525/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/1525/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1524 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1524/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1524/comments | https://api.github.com/repos/coleifer/peewee/issues/1524/events | https://github.com/coleifer/peewee/issues/1524 | 301,485,327 | MDU6SXNzdWUzMDE0ODUzMjc= | 1,524 | Documentation for `Case` Shortcut | {
"login": "r0mille",
"id": 2582481,
"node_id": "MDQ6VXNlcjI1ODI0ODE=",
"avatar_url": "https://avatars.githubusercontent.com/u/2582481?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/r0mille",
"html_url": "https://github.com/r0mille",
"followers_url": "https://api.github.com/users/r0mille/followers",
"following_url": "https://api.github.com/users/r0mille/following{/other_user}",
"gists_url": "https://api.github.com/users/r0mille/gists{/gist_id}",
"starred_url": "https://api.github.com/users/r0mille/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/r0mille/subscriptions",
"organizations_url": "https://api.github.com/users/r0mille/orgs",
"repos_url": "https://api.github.com/users/r0mille/repos",
"events_url": "https://api.github.com/users/r0mille/events{/privacy}",
"received_events_url": "https://api.github.com/users/r0mille/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"I forgot that file existed, and so it hasn't been updated yet for 3.x.\r\n\r\nYou can find the `Case` helper here, as it's now part of \"peewee.py\": http://docs.peewee-orm.com/en/latest/peewee/api.html#Case"
] | 2018-03-01T17:06:25 | 2018-03-01T17:11:09 | 2018-03-01T17:11:09 | NONE | null | https://github.com/coleifer/peewee/blob/master/playhouse/README.md
mentions a section for `Shortcuts/helpers` where CASE statements can be constructed.
However there is nothing in Peewee docs that would help a user figure out how to construct `CASE` statements.
http://docs.peewee-orm.com/en/latest/peewee/playhouse.html#shortcuts
Anything would be appreciated! Thanks in advance! | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1524/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/1524/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1523 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1523/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1523/comments | https://api.github.com/repos/coleifer/peewee/issues/1523/events | https://github.com/coleifer/peewee/issues/1523 | 301,282,369 | MDU6SXNzdWUzMDEyODIzNjk= | 1,523 | Aggregation result as list | {
"login": "ak4nv",
"id": 73960,
"node_id": "MDQ6VXNlcjczOTYw",
"avatar_url": "https://avatars.githubusercontent.com/u/73960?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/ak4nv",
"html_url": "https://github.com/ak4nv",
"followers_url": "https://api.github.com/users/ak4nv/followers",
"following_url": "https://api.github.com/users/ak4nv/following{/other_user}",
"gists_url": "https://api.github.com/users/ak4nv/gists{/gist_id}",
"starred_url": "https://api.github.com/users/ak4nv/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/ak4nv/subscriptions",
"organizations_url": "https://api.github.com/users/ak4nv/orgs",
"repos_url": "https://api.github.com/users/ak4nv/repos",
"events_url": "https://api.github.com/users/ak4nv/events{/privacy}",
"received_events_url": "https://api.github.com/users/ak4nv/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"I'm going to assume the `name` field has a string as Python equivalent. By default, the result of the query is coerced to the same type of the original field, a string in this case. You can prevent this by doing:\r\n\r\n``` python\r\n qs = (Model\r\n .select(Model.group, fn.array_agg(Model.name, coerce=False).alias('name'))\r\n .group_by(Model.group)\r\n .order_by(Model.group))\r\n```\r\nThis should return a list!",
"@Karel-van-de-Plassche Thanks a lot!\r\nI've found solution for 2 version of peewee:\r\n```python\r\nf = fn.array_agg(Model.name)\r\nf._coerce = False\r\nqs = (Model\r\n .select(Model.group, f)\r\n .group_by(Model.group)\r\n .order_by(Model.group))\r\n```",
"@ak04nv Great! Be aware that `_coerce` is part of the private API, and might change without notice. If this solution works for you, feel free to close the issue.",
"Did @Karel-van-de-Plassche's suggestion of passing `coerce=False` into the function work for you @ak04nv ?",
"@coleifer yes and thank you guys again!"
] | 2018-03-01T05:28:14 | 2018-03-02T04:49:08 | 2018-03-02T04:49:08 | NONE | null | Hi!
First of all my congratulations with new major release! I've been using peewee several years and I love it!
This code below returns aggregated field as string. Is there another way to get result as list?
```python
qs = (Model
.select(Model.group, fn.array_agg(Model.name).alias('name'))
.group_by(Model.group)
.order_by(Model.group))
```
Thanks a lot! | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1523/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/1523/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1522 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1522/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1522/comments | https://api.github.com/repos/coleifer/peewee/issues/1522/events | https://github.com/coleifer/peewee/issues/1522 | 300,848,272 | MDU6SXNzdWUzMDA4NDgyNzI= | 1,522 | Returns on inserts | {
"login": "justin-richert",
"id": 12699723,
"node_id": "MDQ6VXNlcjEyNjk5NzIz",
"avatar_url": "https://avatars.githubusercontent.com/u/12699723?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/justin-richert",
"html_url": "https://github.com/justin-richert",
"followers_url": "https://api.github.com/users/justin-richert/followers",
"following_url": "https://api.github.com/users/justin-richert/following{/other_user}",
"gists_url": "https://api.github.com/users/justin-richert/gists{/gist_id}",
"starred_url": "https://api.github.com/users/justin-richert/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/justin-richert/subscriptions",
"organizations_url": "https://api.github.com/users/justin-richert/orgs",
"repos_url": "https://api.github.com/users/justin-richert/repos",
"events_url": "https://api.github.com/users/justin-richert/events{/privacy}",
"received_events_url": "https://api.github.com/users/justin-richert/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"The code gets a bit difficult when it's trying to figure out what to return for insert queries when the db supports returning clauses. By default we want to select the table's primary key and return the last-inserted ID...but if the user specifies something else, we probably should return a cursor over the returned results.\r\n\r\nIn the current code, you should be able to do this:\r\n\r\n```python\r\n\r\nclass ServerDefault(Model):\r\n timestamp = DateTimeField(constraints=[SQL('default (now())')])\r\n\r\nquery = ServerDefault.insert().returning(ServerDefault.id, ServerDefault.timestamp)\r\nlast_id = query.execute()\r\nnew_rows = list(query)\r\nnew_id, new_timestamp = new_rows[0]\r\n```\r\n\r\nI made a small fix, which will cause `execute()` to return the cursor if the returning clause is non-default, so in master you would write:\r\n\r\n```python\r\nquery = ServerDefault.insert().returning(ServerDefault.id, ServerDefault.timestamp)\r\ncursor = query.execute()\r\nnew_id, new_timestamp = cursor[0]\r\n```\r\n\r\nThanks for bringing this to my attention -- it highlighed a fragile API. The API is still more fragile than I would like, but hopefully it's more obvious now... If you specify a returning clause, you'll get a cursor back -- whether inserting one row or multiple rows.",
"It didn't occur to me to check the query object after execution for some reason. Thanks for pointing that out.\r\n\r\nI really appreciate your help with this! And thanks for the awesome project.",
"No worries, glad to help. Once I push a new release (3.1.2) the query will directly return a cursor object so it won't be quite so confusing hopefully."
] | 2018-02-28T00:41:49 | 2018-02-28T14:55:45 | 2018-02-28T04:00:29 | NONE | null | I'm having a little trouble with peewee's insert query.
It would be ideal if `<ModelInstance>.create()` would allow for returning all columns. I know it returns primary keys automatically, but I have a model that has server side defaults besides the primary key that I need to render in a response after inserting a row.
However, given that implementation may not be likely (or at least not soon), I turned to `<ModelInstance>.insert().returning(<column_list>).execute()`. I don't pass anything to insert yet because I'm testing on a table with two columns, one being of type bigserial, one being of type timestamp with tz, both with values generated on the db server side.
I've tracked through a significant portion of the code executed from that line of code, and in doing so, I came across `last_insert_id`, a function that checks the `query_type` param. In the case of the code I executed for the insert, `query_type` is `Insert.SIMPLE`, which is equal to 0. Then, `last_insert_id` executes this line: `return cursor if query_type else cursor[0][0]`, which scraps the result set I had achieved by invoking the returning function and just returns the id of the inserted row. I can't tell if that is a bug and this line should read `return cursor if query_type is not None else cursor[0][0]`, or if that was intended. If it is intended to affect the `Insert.SIMPLE` query type, it seems as though it should also check if `.returning` was used. | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1522/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/1522/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1521 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1521/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1521/comments | https://api.github.com/repos/coleifer/peewee/issues/1521/events | https://github.com/coleifer/peewee/issues/1521 | 300,575,416 | MDU6SXNzdWUzMDA1NzU0MTY= | 1,521 | different exception type | {
"login": "MR-omid",
"id": 3023805,
"node_id": "MDQ6VXNlcjMwMjM4MDU=",
"avatar_url": "https://avatars.githubusercontent.com/u/3023805?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/MR-omid",
"html_url": "https://github.com/MR-omid",
"followers_url": "https://api.github.com/users/MR-omid/followers",
"following_url": "https://api.github.com/users/MR-omid/following{/other_user}",
"gists_url": "https://api.github.com/users/MR-omid/gists{/gist_id}",
"starred_url": "https://api.github.com/users/MR-omid/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/MR-omid/subscriptions",
"organizations_url": "https://api.github.com/users/MR-omid/orgs",
"repos_url": "https://api.github.com/users/MR-omid/repos",
"events_url": "https://api.github.com/users/MR-omid/events{/privacy}",
"received_events_url": "https://api.github.com/users/MR-omid/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"Peewee wraps database driver-specific exceptions with it's own exception types... This is done so that, regardless of what database driver you're using, you can catch the a single exception type.\r\n\r\nSo you would, theoretically, just write:\r\n\r\n```python\r\ntry:\r\n model.save()\r\nexcept peewee.IntegrityError:\r\n # do whatever.\r\n```",
"thanks for your reply, but i tested and its not work.\r\nworking code:\r\n```python\r\nclass Config(Database.model):\r\n attribute = TextField(unique=True)\r\n value = ComplexField()\r\n\r\n class Meta:\r\n db_table = 'core_config'\r\n\r\n @staticmethod\r\n def save_changes(configs=None):\r\n if not configs:\r\n configs = default_configs\r\n for config in configs:\r\n try:\r\n model = Config()\r\n model.attribute = config['attribute']\r\n model.value = config['value']\r\n model.save()\r\n except psycopg2.IntegrityError:\r\n model = Config.get(attribute=config['attribute'])\r\n model.value = config['value']\r\n model.save()\r\n```\r\n\r\nbut this one is not catch exception:\r\n```python\r\nclass Config(Database.model):\r\n attribute = TextField(unique=True)\r\n value = ComplexField()\r\n\r\n class Meta:\r\n db_table = 'core_config'\r\n\r\n @staticmethod\r\n def save_changes(configs=None):\r\n if not configs:\r\n configs = default_configs\r\n for config in configs:\r\n try:\r\n model = Config()\r\n model.attribute = config['attribute']\r\n model.value = config['value']\r\n model.save()\r\n except peewee.IntegrityError:\r\n model = Config.get(attribute=config['attribute'])\r\n model.value = config['value']\r\n model.save()\r\n```",
"I'll see if I can replicate it. Thanks for the update.",
"I can't replicate the issue:\r\n\r\n```python\r\nimport peewee\r\n\r\n\r\ndb = peewee.PostgresqlDatabase('peewee_test', user='postgres')\r\n\r\nclass Register(peewee.Model):\r\n value = peewee.IntegerField(unique=True)\r\n class Meta:\r\n database = db\r\n\r\ndb.create_tables([Register])\r\n\r\n# Clear out any rows.\r\nRegister.delete().execute()\r\n\r\nRegister.create(value=1)\r\n\r\nwith db.atomic():\r\n try:\r\n Register.create(value=1)\r\n except peewee.IntegrityError:\r\n print('Integrity error caught')\r\n\r\ndb.drop_tables([Register])\r\n```\r\n\r\nThe above code correctly prints \"Integrity error caught\".",
"my peewee version is: 2.10.2\r\ni can't upgrade, \r\nfor backward compatibility with custom migration.\r\nmay be problem in this version?",
"hey, i tested again and its worked :)\r\nbut if i set `autorollback` to false, problem will be appear.\r\n```\r\n\r\nTraceback (most recent call last):\r\n File \"/usr/local/lib/python3.5/dist-packages/peewee.py\", line 3830, in execute_sql\r\n cursor.execute(sql, params or ())\r\npsycopg2.IntegrityError: duplicate key value violates unique constraint \"core_config_attribute\"\r\nDETAIL: Key (attribute)=(test) already exists.\r\n\r\n\r\nDuring handling of the above exception, another exception occurred:\r\n\r\nTraceback (most recent call last):\r\n File \"/home/dpe/workspace/python/F.SystemAPI/models/Config.py\", line 31, in save_changes\r\n model.save()\r\n File \"/usr/local/lib/python3.5/dist-packages/playhouse/signals.py\", line 69, in save\r\n ret = super(Model, self).save(*args, **kwargs)\r\n File \"/usr/local/lib/python3.5/dist-packages/peewee.py\", line 5170, in save\r\n pk_from_cursor = self.insert(**field_dict).execute()\r\n File \"/usr/local/lib/python3.5/dist-packages/peewee.py\", line 3584, in execute\r\n cursor = self._execute()\r\n File \"/usr/local/lib/python3.5/dist-packages/peewee.py\", line 2939, in _execute\r\n return self.database.execute_sql(sql, params, self.require_commit)\r\n File \"/usr/local/lib/python3.5/dist-packages/peewee.py\", line 3837, in execute_sql\r\n self.commit()\r\n File \"/usr/local/lib/python3.5/dist-packages/peewee.py\", line 3656, in __exit__\r\n reraise(new_type, new_type(*exc_args), traceback)\r\n File \"/usr/local/lib/python3.5/dist-packages/peewee.py\", line 135, in reraise\r\n raise value.with_traceback(tb)\r\n File \"/usr/local/lib/python3.5/dist-packages/peewee.py\", line 3830, in execute_sql\r\n cursor.execute(sql, params or ())\r\npeewee.IntegrityError: duplicate key value violates unique constraint \"core_config_attribute\"\r\nDETAIL: Key (attribute)=(test) already exists.\r\n\r\n\r\nDuring handling of the above exception, another exception occurred:\r\n\r\nTraceback (most recent call last):\r\n File \"/usr/local/lib/python3.5/dist-packages/peewee.py\", line 3830, in execute_sql\r\n cursor.execute(sql, params or ())\r\npsycopg2.InternalError: current transaction is aborted, commands ignored until end of transaction block\r\n\r\n\r\nDuring handling of the above exception, another exception occurred:\r\n\r\nTraceback (most recent call last):\r\n File \"/home/dpe/workspace/python/F.SystemAPI/dev.py\", line 18, in <module>\r\n server.start()\r\n File \"/home/dpe/workspace/python/F.SystemAPI/core/Server.py\", line 36, in start\r\n Config.save_changes([{'attribute':'test','value':'omid'},{'attribute':'test2','value':'omid'},{'attribute':'test','value':'omid3'}])\r\n File \"/home/dpe/workspace/python/F.SystemAPI/models/Config.py\", line 35, in save_changes\r\n model = Config.get(attribute=config['attribute'])\r\n File \"/usr/local/lib/python3.5/dist-packages/peewee.py\", line 4988, in get\r\n return sq.get()\r\n File \"/usr/local/lib/python3.5/dist-packages/peewee.py\", line 3220, in get\r\n return next(clone.execute())\r\n File \"/usr/local/lib/python3.5/dist-packages/peewee.py\", line 3274, in execute\r\n self._qr = ResultWrapper(model_class, self._execute(), query_meta)\r\n File \"/usr/local/lib/python3.5/dist-packages/peewee.py\", line 2939, in _execute\r\n return self.database.execute_sql(sql, params, self.require_commit)\r\n File \"/usr/local/lib/python3.5/dist-packages/peewee.py\", line 3837, in execute_sql\r\n self.commit()\r\n File \"/usr/local/lib/python3.5/dist-packages/peewee.py\", line 3656, in __exit__\r\n reraise(new_type, new_type(*exc_args), traceback)\r\n File \"/usr/local/lib/python3.5/dist-packages/peewee.py\", line 135, in reraise\r\n raise value.with_traceback(tb)\r\n File \"/usr/local/lib/python3.5/dist-packages/peewee.py\", line 3830, in execute_sql\r\n cursor.execute(sql, params or ())\r\npeewee.InternalError: current transaction is aborted, commands ignored until end of transaction block\r\n```",
"If you are using Postgres, you need to take care that, if you get the connection into a bad state -- i.e., by an IntegrityError -- you need to rollback. Auto-rollback will issue the rollback automatically, but it's better, in my opinion, to manage the transaction yourself:\r\n\r\n```python\r\ntry:\r\n with db.atomic():\r\n some_obj.save()\r\nexcept peewee.IntegrityError:\r\n # do something else?\r\n```"
] | 2018-02-27T10:36:31 | 2018-03-07T02:02:42 | 2018-03-05T13:15:57 | NONE | null | hi
with postgres database connection, exception raised as `psycopg2.IntegrityError` but its not same as `peewee.IntegrityError` and not catchable.
it is normal to use `psycopg2.IntegrityError` in except ?
for example:
```
try:
model.save()
except psycopg2.IntegrityError:
raise
``` | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1521/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/1521/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1520 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1520/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1520/comments | https://api.github.com/repos/coleifer/peewee/issues/1520/events | https://github.com/coleifer/peewee/issues/1520 | 300,543,511 | MDU6SXNzdWUzMDA1NDM1MTE= | 1,520 | Subquery (SELECT) in join condition doesn't produce valid SQL | {
"login": "Karel-van-de-Plassche",
"id": 6404167,
"node_id": "MDQ6VXNlcjY0MDQxNjc=",
"avatar_url": "https://avatars.githubusercontent.com/u/6404167?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/Karel-van-de-Plassche",
"html_url": "https://github.com/Karel-van-de-Plassche",
"followers_url": "https://api.github.com/users/Karel-van-de-Plassche/followers",
"following_url": "https://api.github.com/users/Karel-van-de-Plassche/following{/other_user}",
"gists_url": "https://api.github.com/users/Karel-van-de-Plassche/gists{/gist_id}",
"starred_url": "https://api.github.com/users/Karel-van-de-Plassche/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/Karel-van-de-Plassche/subscriptions",
"organizations_url": "https://api.github.com/users/Karel-van-de-Plassche/orgs",
"repos_url": "https://api.github.com/users/Karel-van-de-Plassche/repos",
"events_url": "https://api.github.com/users/Karel-van-de-Plassche/events{/privacy}",
"received_events_url": "https://api.github.com/users/Karel-van-de-Plassche/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"The query example you provided makes no sense to me. Why are you joining `PureNetworkParams` on a sub-select when you are already selecting from the `Network` model? I'd think this is more correct:\r\n\r\n```python\r\nquery = (Network\r\n .select()\r\n .join(PureNetworkParams, on=(PureNetworkParams.network == Network.id)))\r\n```\r\n\r\nThe reason I'm confused is because in your example, the right-hand-side of your join expression is a subquery that is in no way correlated.",
"As far as joining on subqueries, there are a handful of tests and I've even added another. Hopefully this clarifies the issue for you:\r\n\r\n```python\r\n\r\n# Let's get the tweets written by \"huey\" or \"zaizee\".\r\n\r\n# First let's make a query on the \"users\" table:\r\nusers = (User\r\n .select(User.id, User.username)\r\n .where(User.username.in_(['huey', 'zaizee'])))\r\n\r\n# Now select from tweet and join the tweet's user_id on the user from the sub-select:\r\nquery = (Tweet\r\n .select(Tweet.content, users.c.username.alias('username'))\r\n .join(users, on=(Tweet.user == users.c.id)))\r\n```\r\n\r\nThe above query produces the following SQL:\r\n\r\n```sql\r\nSELECT \"t1\".\"content\", \"t2\".\"username\" AS \"username\"\r\nFROM \"tweet\" AS \"t1\"\r\nINNER JOIN (\r\n SELECT \"t3\".\"id\", \"t3\".\"username\"\r\n FROM \"users\" AS \"t3\"\r\n WHERE (\"t3\".\"username\" IN ('huey', 'zaizee'))\r\n) AS \"t2\" ON (\"t1\".\"user_id\" = \"t2\".\"id\")\r\n```",
"I am using the subquery to join a CTE, because I join on the value of an ArrayField. I'm aware that this is an SQL antipattern, and an edge case I'm not sure you'd want to support with Peewee. Let me try your suggestions, and if I fail report back with a better test case showing what I want to do.",
"A better example would certainly clarify the issue for me. Keep me posted.",
"Going to close this for now. If you want to share more examples, please leave a comment and I'll re-open the issue.",
"I noticed the SQL query I was trying to recreate in peewee also didn't give me the correct result. I've since then fixed the issue on my side. Let me use this opportunity to thank you for your amazing package and near-instant support!\r\n\r\nFor anyone foolish enough to do a recursive self-join on an array field, I've included my solution for future reference:\r\n\r\nschema:\r\n``` python\r\nfrom peewee import *\r\nfrom playhouse.postgres_ext import *\r\n\r\ndb = PostgresqlExtDatabase(database='qlknn_test', register_hstore=True)\r\nclass BaseModel(Model):\r\n class Meta:\r\n database = db\r\n\r\nclass Network(BaseModel):\r\n networks = ArrayField(IntegerField, null=True)\r\n\r\n def get_parameter(self):\r\n name_list = []\r\n if self.networks is not None:\r\n for net_id in self.networks:\r\n name = Network.get_by_id(net_id).get_parameter()\r\n name_list.append(name)\r\n else:\r\n pparam = PureParameters.select(PureParameters.name).join(Network).where(Network.id == self.id).get()\r\n name_list.append(pparam.name)\r\n return name_list\r\n\r\nclass PureParameters(BaseModel):\r\n network = ForeignKeyField(Network)\r\n name = TextField()\r\n```\r\nInitialize tables:\r\n``` python\r\npurenet1 = Network.create()\r\npparam1 = PureParameters.create(network=purenet1, name='alice')\r\npurenet2 = Network.create()\r\npparam2 = PureParameters.create(network=purenet2, name='bob')\r\npurenet3 = Network.create()\r\npparam3 = PureParameters.create(network=purenet3, name='eve')\r\n\r\ncombonet = Network.create(networks=[purenet1.id, purenet2.id])\r\nmultinet = Network.create(networks=[combonet.id, purenet3.id])\r\n```\r\nRecursive function solution:\r\n``` python\r\nIn [1]: purenet1.get_parameter()\r\nOut[1]: ['alice']\r\n\r\nIn [2]: combonet.get_parameter()\r\nOut[2]: [['alice'], ['bob']]\r\n\r\nIn [3]: multinet.get_parameter()\r\nOut[3]: [[['alice'], ['bob']], ['eve']]\r\n```\r\nFlat peewee SQL query solution:\r\n``` python\r\nx = Network.alias()\r\ny = Network.alias()\r\nsubx = x.select(x.id, x.networks)\r\nsuby = y.select(y.id)\r\n\r\nquery = (Network.select(Network.id, fn.array_agg(PureParameters.name, coerce=False))\r\n .join(subx, JOIN.LEFT_OUTER, on=subx.c.id == fn.ANY(Network.networks))\r\n .join(suby, JOIN.LEFT_OUTER, on=suby.c.id == fn.ANY(subx.c.networks))\r\n .join(PureParameters, on=((PureParameters.network_id == Network.id) |\r\n (PureParameters.network_id == subx.c.id) |\r\n (PureParameters.network_id == suby.c.id)))\r\n .group_by(Network.id)\r\n )\r\n```\r\nScaling is not great, so you should probably think about re-designing part of the database (this one is on production, so one extra join not in the example):\r\n``` SQL\r\nGroupAggregate (cost=282391.93..283171.43 rows=533 width=36)\r\n Group Key: network.id\r\n -> Sort (cost=282391.93..282649.54 rows=103045 width=8)\r\n Sort Key: network.id\r\n -> Hash Join (cost=21.19..273811.93 rows=103045 width=8)\r\n Hash Cond: (purenetworkparams.id = hyperparameters.pure_network_params_id)\r\n -> Nested Loop (cost=1.32..272403.53 rows=100984 width=8)\r\n -> Nested Loop Left Join (cost=0.55..18246.05 rows=52406 width=12)\r\n -> Nested Loop Left Join (cost=0.28..1703.66 rows=5285 width=39)\r\n -> Seq Scan on network (cost=0.00..19.33 rows=533 width=35)\r\n -> Index Scan using network_pkey on network t2 (cost=0.28..3.06 rows=10 width=35)\r\n Index Cond: (id = ANY (network.networks))\r\n -> Index Only Scan using network_pkey on network t3 (cost=0.28..3.03 rows=10 width=4)\r\n Index Cond: (id = ANY (t2.networks))\r\n -> Bitmap Heap Scan on purenetworkparams (cost=0.77..4.82 rows=3 width=8)\r\n Recheck Cond: ((network_id = network.id) OR (network_id = t2.id) OR (network_id = t3.id))\r\n -> BitmapOr (cost=0.77..0.77 rows=3 width=0)\r\n -> Bitmap Index Scan on purenetworkparams_network_id (cost=0.00..0.17 rows=1 width=0)\r\n Index Cond: (network_id = network.id)\r\n -> Bitmap Index Scan on purenetworkparams_network_id (cost=0.00..0.17 rows=1 width=0)\r\n Index Cond: (network_id = t2.id)\r\n -> Bitmap Index Scan on purenetworkparams_network_id (cost=0.00..0.17 rows=1 width=0)\r\n Index Cond: (network_id = t3.id)\r\n -> Hash (cost=15.50..15.50 rows=350 width=8)\r\n -> Seq Scan on hyperparameters (cost=0.00..15.50 rows=350 width=8)\r\n```"
] | 2018-02-27T09:02:33 | 2018-02-28T17:44:32 | 2018-02-27T16:28:27 | NONE | null | I'm using 96cbe09. In a complicated query I need to join on a subquery result. The smallest reproducible case that gives the same error/SQL problems is:
``` python
query = (Network
.select()
.join(PureNetworkParams,
on=(PureNetworkParams.network_id ==
Network.select(Network.id)))
)
query.sql()
('SELECT "t1"."id", "t1"."feature_names", "t1"."target_names", "t1"."recipe", "t1"."networks" FROM "develop"."network" AS "t1" INNER JOIN "develop"."purenetworkparams" AS "t2" ON ("t2"."network_id" = (SELECT "t1"."id" FROM "develop"."network" AS "t1") AS "t3")',
[])
query.get()
ProgrammingError: syntax error at or near "AS"
LINE 1: ...ELECT "t1"."id" FROM "develop"."network" AS "t1") AS "t3") L...
```
When I removed the `AS "T3"` and try in my PostgreSQL GUI, it works perfectly.
PS. There might be an SQL workaround, this is just the query I got working first in raw SQL.
PPS. Might be able to rephrase this with a subquery/alias, but can't get the complicated query to work (yet) | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1520/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/1520/timeline | null | completed | null | null |
https://api.github.com/repos/coleifer/peewee/issues/1519 | https://api.github.com/repos/coleifer/peewee | https://api.github.com/repos/coleifer/peewee/issues/1519/labels{/name} | https://api.github.com/repos/coleifer/peewee/issues/1519/comments | https://api.github.com/repos/coleifer/peewee/issues/1519/events | https://github.com/coleifer/peewee/issues/1519 | 300,533,502 | MDU6SXNzdWUzMDA1MzM1MDI= | 1,519 | Cursor count attribute returns 0, when shouldn't | {
"login": "vikt0rs",
"id": 5230490,
"node_id": "MDQ6VXNlcjUyMzA0OTA=",
"avatar_url": "https://avatars.githubusercontent.com/u/5230490?v=4",
"gravatar_id": "",
"url": "https://api.github.com/users/vikt0rs",
"html_url": "https://github.com/vikt0rs",
"followers_url": "https://api.github.com/users/vikt0rs/followers",
"following_url": "https://api.github.com/users/vikt0rs/following{/other_user}",
"gists_url": "https://api.github.com/users/vikt0rs/gists{/gist_id}",
"starred_url": "https://api.github.com/users/vikt0rs/starred{/owner}{/repo}",
"subscriptions_url": "https://api.github.com/users/vikt0rs/subscriptions",
"organizations_url": "https://api.github.com/users/vikt0rs/orgs",
"repos_url": "https://api.github.com/users/vikt0rs/repos",
"events_url": "https://api.github.com/users/vikt0rs/events{/privacy}",
"received_events_url": "https://api.github.com/users/vikt0rs/received_events",
"type": "User",
"site_admin": false
} | [] | closed | false | null | [] | null | [
"The `count` attribute of the cursor wrapper is something different than the `count()` method of a `Select` query:\r\n\r\n```python\r\n\r\ncreate_3_users()\r\nUser.select().count() == 3 # True\r\n\r\nqr = User.select().execute()\r\nqr.count == 0 # True\r\n\r\n[x for x in qr]\r\nqr.count == 3 # True\r\n```\r\n\r\nThe `CursorWrapper.count` attribute tracks how many rows have been read from the cursor. It's a private API and has a different meaning than `Select.count()`.\r\n\r\nMake sense?",
"Suggestion: Maybe it can be renamed to _count to signify the private status?",
"It's not documented, so I'm not even sure what would lead someone to using it?",
"Thanks for the explanation, but it is the part of public API, so I was pretty sure, that I can use it. Please, inform what's wrong in this idea? :)",
"> it is the part of public API\r\n\r\nCan you please share where this is documented?",
"@coleifer You are right, I was misinterpreting PEP8\r\n@vikt0rs As per PEP8 https://www.python.org/dev/peps/pep-0008/#public-and-internal-interfaces:\r\n> All undocumented interfaces should be assumed to be internal.\r\n",
"Agreed, this wasn't documented, sorry for my note"
] | 2018-02-27T08:27:23 | 2018-02-27T15:56:47 | 2018-02-27T15:09:20 | NONE | null | For some reasons, when I try to check if request returns some data with the "count" attribute, the check fails because it always returns 0. Please, suggest.
PS - this also worked in 2.X
```
>>> docs.select().execute()
<peewee.ModelObjectCursorWrapper object at 0x1089b80f0>
>>> docs.select().execute().count
0
>>> len(docs.select().execute())
308
``` | {
"url": "https://api.github.com/repos/coleifer/peewee/issues/1519/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/1519/timeline | null | completed | null | null |
Subsets and Splits