On May 27, 2013, at 5:12 PM, Chris Withers <[email protected]> wrote:

> Hi,
> 
> I'd like to come up with a string column type that prevents empty values, or 
> a function that returns a string column which prevents empty values.
> 
> I've tried two approaches, both of which failed:
> 
> class NotEmptyString(String, SchemaType):
> 
>    def _set_table(self, column, table):
>        table.append_constraint(CheckConstraint(column != ''))
> 
> The above works, but results in two check constraints for each NotEmptyString 
> on each table, why is that?

I'm not able to reproduce that, only does it once for me (I'd pdb to see if 
_set_table() is being called multiple times).

You can avoid the underscore method using events though a little more verbosely:

class NotEmptyString(String, SchemaType):
    def __init__(self, length, **kw):
        String.__init__(self, length)
        SchemaType.__init__(self, **kw)

from sqlalchemy import event

@event.listens_for(NotEmptyString, "after_parent_attach")
def _set_column(type_, column, **kw):

    @event.listens_for(column, "after_parent_attach")
    def _set_table(column, table, **kw):
        table.append_constraint(CheckConstraint(column != ''))






> 
> def not_empty_string(size, **kw):
>    col = Column(String(size), nullable=False, **kw)
>    cons = CheckConstraint(col!='')
>    cons._set_parent_with_dispatch(col)
>    return col
> 
> So, I tried this to get around the two-check-constraints problem, but here 
> the issue is that I don't have the column name when I need to make the 
> constraint, the above barfs when creating the table:
> 
> ProgrammingError: (ProgrammingError) syntax error at or near ":"
> LINE 3:  id VARCHAR(10) NOT NULL CHECK (table.col != :param_1),
> 
> What should I have been doing here and what am I doing wrong?
> 
> In the meantime, I'll just use table-level check constraints, but I'd like to 
> make this DRY and I don't want to risk forgetting the constraint for a 
> column...
> 
> cheers,
> 
> Chris
> 
> -- 
> Simplistix - Content Management, Batch Processing & Python Consulting
>           - http://www.simplistix.co.uk
> 
> -- 
> You received this message because you are subscribed to the Google Groups 
> "sqlalchemy" group.
> To unsubscribe from this group and stop receiving emails from it, send an 
> email to [email protected].
> To post to this group, send email to [email protected].
> Visit this group at http://groups.google.com/group/sqlalchemy?hl=en.
> For more options, visit https://groups.google.com/groups/opt_out.
> 
> 

-- 
You received this message because you are subscribed to the Google Groups 
"sqlalchemy" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To post to this group, send email to [email protected].
Visit this group at http://groups.google.com/group/sqlalchemy?hl=en.
For more options, visit https://groups.google.com/groups/opt_out.


Reply via email to