warn about unicode column having non-unicode default

Issue #2079 resolved
Former user created an issue

foo = Column(Unicode(32), default="bar")

prints a warning when left at the default, and the source of this warning can be a pain to track down, as it only appears when the user's code doesn't specify a non-unicode value (ie, the default gets used).

If the library could detect the conflict of column type and default, and warn about it with a sane message when the model is loaded, that would be lovely

Comments (6)

  1. Mike Bayer repo owner
    • changed milestone to 0.7.0
    • changed component to sql

    hey good idea. I was thinking why don't we just coerce, but yeah more consistent just treat it like the others.

  2. Former user Account Deleted
    from sqlalchemy.ext.declarative import declarative_base
    from sqlalchemy import Table, Column, Integer, Unicode, create_engine
    
    Base = declarative_base()
    
    class Post(Base):
        __tablename__ = 'post'
    
        id = Column(Integer, primary_key=True)
        name = Column(Unicode(32), default=u'unicode_default')
        author = Column(Unicode(32), default='non_unicode_default')
    
        def __init__(self, id, name, author):
            self.id = id
            self.name = name
            self.author = author
    
    engine = create_engine('sqlite://', echo=False)
    Base.metadata.create_all(engine)
    
    
    
    
     SAWarning: Unicode column received non-unicode default value.
      author = Column(Unicode(32), default='non_unicode_default')
    
  3. Former user Account Deleted

    With both patches applied in order, you get:

            if self.default is not None:
                if isinstance(self.default, (ColumnDefault, Sequence)):
                    args.append(self.default)
                else:
                    if getattr(self.type, '_warn_on_bytestring', False):
                        # Py3K
                        #if isinstance(self.default, bytes):
                        # Py2K
                        if isinstance(self.default, str):
                        # end Py2K
                            util.warn("Unicode column received non-unicode "
                                      "default value.")                    
                    args.append(ColumnDefault(self.default))
    

    Things I'm not sure about:

    1. Does anything need to be done nuder this clause -- I know nothing yet about 'Sequence'

      if isinstance(self.default, (ColumnDefault, Sequence)):

    2. Do these other checks I see elsewhere also need to happen in the above schema.py snippet:

          if self.convert_unicode or dialect.convert_unicode:
              if dialect.supports_unicode_binds and self.convert_unicode != 'force':
                  ....
      

    Thanks for letting me play along.

  4. Log in to comment