pudo / dataset

Easy-to-use data handling for SQL data stores with support for implicit table creation, bulk loading, and transactions.

Home Page:https://dataset.readthedocs.org/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

table.create_index after db.create_table raises DatasetException("Table has not been created yet.")

inactivist opened this issue · comments

(dataset version 1.4.1, Python3.8)

I'm new to dataset, so I have a usage question. What is the proper way to create additional index on a table, before inserting data? I haven't found any documentation that shows how to do this.

Per #293 (comment), I should be able to create indexes immediately after db.create_table() call.

If I call table.create_index() immediately after db.create_table(), DatasetException("Table has not been created yet.") is raised.

I'm looking for a working example, if possible.

Example code:

from datetime import datetime
import dataset

db = dataset.connect("sqlite:///:memory:")
table = db.create_table(table_name="test")
# Want to create an index on date column
table.create_index(["created_on"])  # any other parameters needed here?
table.insert(dict(name="John Doe", age=37, created_on=datetime.now()))
table.insert(dict(name="Jane Doe", age=34, gender="female", created_on=datetime.now()))

john = table.find_one(name="John Doe")
print(john)
$ python test_dataset_index_creation.py 
Traceback (most recent call last):
  File "test_dataset_index_creation.py", line 7, in <module>
    table.create_index(["created_on"])
  File "venv/lib/python3.8/site-packages/dataset/table.py", line 558, in create_index
    raise DatasetException("Table has not been created yet.")
dataset.util.DatasetException: Table has not been created yet.

Ah, I see my mistake, I failed to create the column via table.create_column("created_on", db.types.datetime) prior to calling create_index (obviously, can't create an index on a column that's not yet been defined.)