Merge pull request #186 from paulfitz/create_column_by_example
add Table.create_column_by_example method
This commit is contained in:
commit
348fdf3f94
@ -312,6 +312,17 @@ class Table(object):
|
||||
finally:
|
||||
self.database._release()
|
||||
|
||||
def create_column_by_example(self, name, value):
|
||||
"""
|
||||
Explicitly create a new column ``name`` with a type that is appropriate to store
|
||||
the given example ``value``. The type is guessed in the same way as for the
|
||||
insert method with ``ensure=True``. If a column of the same name already exists,
|
||||
no action is taken, even if it is not of the type we would have created.
|
||||
|
||||
table.create_column_by_example('length', 4.2)
|
||||
"""
|
||||
self._ensure_columns({name: value}, {})
|
||||
|
||||
def drop_column(self, name):
|
||||
"""
|
||||
Drop the column ``name``.
|
||||
|
||||
@ -7,6 +7,7 @@ try:
|
||||
except ImportError: # pragma: no cover
|
||||
from ordereddict import OrderedDict # Python < 2.7 drop-in
|
||||
|
||||
from sqlalchemy import FLOAT, INTEGER, TEXT
|
||||
from sqlalchemy.exc import IntegrityError, SQLAlchemyError, ArgumentError
|
||||
|
||||
from dataset import connect
|
||||
@ -379,13 +380,24 @@ class TableTestCase(unittest.TestCase):
|
||||
assert m['temperature'] == -10, 'new temp. should be -10 but is %d' % m['temperature']
|
||||
|
||||
def test_create_column(self):
|
||||
from sqlalchemy import FLOAT
|
||||
tbl = self.tbl
|
||||
tbl.create_column('foo', FLOAT)
|
||||
assert 'foo' in tbl.table.c, tbl.table.c
|
||||
assert isinstance(tbl.table.c['foo'].type, FLOAT), tbl.table.c['foo'].type
|
||||
assert 'foo' in tbl.columns, tbl.columns
|
||||
|
||||
def test_ensure_column(self):
|
||||
tbl = self.tbl
|
||||
tbl.create_column_by_example('foo', 0.1)
|
||||
assert 'foo' in tbl.table.c, tbl.table.c
|
||||
assert isinstance(tbl.table.c['foo'].type, FLOAT), tbl.table.c['bar'].type
|
||||
tbl.create_column_by_example('bar', 1)
|
||||
assert 'bar' in tbl.table.c, tbl.table.c
|
||||
assert isinstance(tbl.table.c['bar'].type, INTEGER), tbl.table.c['bar'].type
|
||||
tbl.create_column_by_example('pippo', 'test')
|
||||
assert 'pippo' in tbl.table.c, tbl.table.c
|
||||
assert isinstance(tbl.table.c['pippo'].type, TEXT), tbl.table.c['pippo'].type
|
||||
|
||||
def test_key_order(self):
|
||||
res = self.db.query('SELECT temperature, place FROM weather LIMIT 1')
|
||||
keys = list(res.next().keys())
|
||||
|
||||
Loading…
Reference in New Issue
Block a user