case_convention in db & python code

12 views
Skip to first unread message

Petr Kobalíček

unread,
Jan 5, 2011, 2:41:27 PM1/5/11
to sqlal...@googlegroups.com
Hi,

I'm using underscored_separator_convention in a database, but
camelCase in python code.

I created small wrapper across a table column so I don't need to
define columns using a key property:

from sqlalchemy import Column as SqlColumn

def underscored(s):
result = u""
for i in xrange(0, len(s)):
c = s[i]
if (c.isupper()):
if i > 0: result += u"_"
result += c.lower()
elif c.isdigit():
if len(result) and result[-1].isdigit():
result += c
else:
result += u"_" + c
else:
result += c

return result

def Column(*args, **kw):
k = args[0]
m = list(args)
m[0] = underscored(k)
return SqlColumn(key=k, *m, **kw)

Usage:
Column("productId", BigInteger, Sequence("ux_address_id_seq"),
primary_key=True),
This will create a table column "product_id", but I access it as
productId in python and sqlalchemy expression code.

My question: Is this code good or there is a better way directly built
into the sqlalchemy?

Thanks!
Petr

Michael Bayer

unread,
Jan 5, 2011, 3:52:43 PM1/5/11
to sqlal...@googlegroups.com
You can apply the "macro" at the Column, Table, or mapper() level, but yeah pretty much you need to define the name munging code you want, and you need to embed it somewhere between your configuration and the schema/ORM the way you are doing here.

Here's an alternate name mangler in case its useful:

def uncamelize(text):
def downcase(matchobj):
return "_" + matchobj.group(0).lower()
if text:
text = text[0].lower() + re.sub(r'([A-Z])', downcase, text[1:])
return text

> --
> You received this message because you are subscribed to the Google Groups "sqlalchemy" group.
> To post to this group, send email to sqlal...@googlegroups.com.
> To unsubscribe from this group, send email to sqlalchemy+...@googlegroups.com.
> For more options, visit this group at http://groups.google.com/group/sqlalchemy?hl=en.
>

Petr Kobalíček

unread,
Jan 6, 2011, 4:46:26 PM1/6/11
to sqlal...@googlegroups.com
Hi Michael,

I didn't find an example of this "macro" feature so I'm going to stay
with my solution at this time:)

Thank you anyway!
Petr

Reply all
Reply to author
Forward
0 new messages