pudo / dataset

Easy-to-use data handling for SQL data stores with support for implicit table creation, bulk loading, and transactions.
https://dataset.readthedocs.org/
MIT License
4.76k stars 297 forks source link

cannot create table after load_table #281

Closed allanberry closed 5 years ago

allanberry commented 5 years ago

Hi there, good software; thanks.

I bumped into this; seems like a bug to me, but as I'm new to the system, I might have missed something.

This works fine:

db = dataset.connect('sqlite:///data/stuff.db')
table = db['people']
table.insert(dict(name='John Doe', age=46, country='China'))

But if I try and make a table after checking whether it exists, it fails:

db = dataset.connect('sqlite:///data/stuff.db')
if not db.load_table('people'):
    table = db['people']
    table.insert(dict(name='John Doe', age=46, country='China'))

I get this:

Traceback (most recent call last):
  File "visit.py", line 11, in <module>
    table.insert(dict(name='John Doe', age=46, country='China'))
  File "/Users/allanberry/.local/share/virtualenvs/webcat-DZ0rpZOL/lib/python3.7/site-packages/dataset/table.py", line 79, in insert
    row = self._sync_columns(row, ensure, types=types)
  File "/Users/allanberry/.local/share/virtualenvs/webcat-DZ0rpZOL/lib/python3.7/site-packages/dataset/table.py", line 281, in _sync_columns
    self._sync_table(sync_columns)
  File "/Users/allanberry/.local/share/virtualenvs/webcat-DZ0rpZOL/lib/python3.7/site-packages/dataset/table.py", line 228, in _sync_table
    raise DatasetException("Table does not exist: %s" % self.name)
dataset.util.DatasetException: Table does not exist: people

If the table doesn't exist, shouldn't it just create it, regardless of whether it's in the if not clause?

Thanks.

pudo commented 5 years ago

That's sort of the intended behaviour. I'd reframe the sample like this:

db = dataset.connect('sqlite:///data/stuff.db')
if 'people' not in db:
    table = db['people']
    table.insert(dict(name='John Doe', age=46, country='China'))