kennethreitz / records

SQL for Humans™
https://pypi.python.org/pypi/records/
ISC License
7.15k stars 570 forks source link

rows.first() gives ValueError: RecordCollection contains too many rows #122

Closed leafonsword closed 6 years ago

leafonsword commented 6 years ago

records: 0.5.2 Python: 3.6 MySQL driver: mysqlclient (1.3.12)

>>> rows = db.query('select * from tmpRDSBak_20180102170341SMS_Unsub_Month_BG;') 
>>> rows.first()
Traceback (most recent call last):
  File "<input>", line 1, in <module>
    rows.first()
  File "/usr/local/miniconda2/envs/py3_env/lib/python3.6/site-packages/records.py", line 222, in first
    raise ValueError('RecordCollection contains too many rows.')
ValueError: RecordCollection contains too many rows.

But this table just contains 13 rows

>>> rows = db.query('select count(*) from tmpRDSBak_20180102170341SMS_Unsub_Month_BG;')
>>> rows.first()
<Record {"count(*)": 13}>  
kennell commented 6 years ago

I just stumbled across the same error. Looking at the relevant code part, it seems that raising this exception is the intended behaviour of first() whenever there are >1 rows. See: https://github.com/kennethreitz/records/blob/master/records.py#L205

@kennethreitz I feel like this is a bad naming choice. Given the wording, i would expect first() to give me the first element, regardless of how many rows have been returned by ther query. Perhaps introduce something like one() that returns exactly one row or raises a exception if >1 rows are retreived.

Otherwise, great library. Keep it up.

Tethik commented 6 years ago

Coming from a .NET background this weirded me out a bit too. I'm used to first() returning the first item of a sequence of any length, while single() ensures that there is also only one item.

Sqlalchemy has first() return the first row (although it also does a limit 1) and uses one() to return and enforce.

I think I'd go for the sqlalchemy naming convention (first/one), since thats more closely python related :snake:

vlcinsky commented 6 years ago

Resolved by PR #127

kennell commented 6 years ago

Thanks guys!