On Aug 17, 2013, at 8:07 AM, Felix Schwarz <
felix....@oss.schwarz.eu> wrote:
>
> Am 16.08.2013 20:14, schrieb Michael Bayer:
>>> I guess this is because table.columns does not contain the new column.
>>
>> op.add_column() has nothing to do with the "Table" object you've created, there's no connection between these two elements.
>>
>> Normally when I'm doing an add_column() and I also want to do an update(), I just create a lightweight table() upfront with the columns I need:
>
> To me there are couple of different points which confuse me:
> 1. I kind of expected that my column wouldn't be connected to my table (even
> though it would be nice). However I didn't find out how to manually add the
> column to my Table after add_column().
if you have a Table you can use append_column() on it, it's just this Column can't be associated with any other table. The alembic op.add_column() associates it with a table internally. I can try having it detach but I'd need to add a lot of tests to ensure it is fully detached, as there's a lot of state stuff that goes on when that happens.
> 2. I'd like to avoid duplicating the table definition as I use
> add_column/update quite often (e.g. to add a column with "NOT NULL" and a
> non-server-side default)
there's no duplication of table definition here. We're talking about a Column, but if you need that Column to take place in an UPDATE statement separate from the op.add_column(), no "NOT NULL", type information, or anything else is needed. Just name your column by name, as I illustrated:
t = table("tablename", column("columnname"))
no MetaData needed, no table options, no types, no constraints, no foreign keys, no other columns besides that which you want in your UPDATE statement. It is an extremely minimal form of table metadata.
> 3. Could alembic/SQLAlchemy please throw an exception if 'values' references
> a column name which is unknown for the given table? Silently dropping the
> value can lead to some longer debugging/makes a nasty surprise.
it does. in 0.7 it's a warning and in 0.8 becomes an exception, see
http://docs.sqlalchemy.org/en/rel_0_8/changelog/migration_08.html#unconsumed-column-names-warning-becomes-an-exception
demo:
from sqlalchemy import *
from sqlalchemy.sql import table, column
from sqlalchemy import __version__
if __version__ < '0.8.0':
import warnings
warnings.filterwarnings("error")
m = MetaData()
t1 = Table('t', m, Column('a', Integer), Column('b', Integer))
t2 = table('t', column('a'), column('b'))
try:
print(t1.update().values(c='asdf'))
except:
pass
else:
assert False
try:
print(t2.update().values(c='asdf'))
except:
pass
else:
assert False