convert database_column_names to mixedCaseNames and back again

by @jehiah on 2006-06-14 06:33
Filed under: All, Programming, Python

It's common to name your database columns like this_is_a_column with what I call "underscore case". It's also twice as common to name variables in your code with either CamelCaseFormat or mixedCaseFormat. I hate the tedious effort of going between the two, so here is a snippet of python that does the work for me.

It works by passing a column name to a transform function that processes it through a regular expression. That regular expression passes the matched groups through a helper function before putting it all back together again.

File:caseTransformations.py

[python]
import re
def toMixedCase(columnName):
    """ pass 'a_column_name' get back 'aColumnName' """
    return re.sub("(_[a-zA-Z])",toMixedCaseHelper,columnName)
def toMixedCaseHelper(match):
    """ pass a match of '_a' and you get back 'A' """
    return match.group(0)[1].upper()

def toUnderscoreCase(columnName):
    """ pass 'aColumnName' and get back 'a_column_name' """
    return re.sub("([a-z][A-Z])",toUnderscoreCaseHelper,columnName)
def toUnderscoreCaseHelper(match):
    """ pass a match of 'aZ' and get back 'a_z' """
    return match.group(0)[0] + '_'+match.group(0)[1].lower()

[/python]

Now let's see it at work:

>>> import caseTransformations
>>> caseTransformations.toMixedCase("your_column_name")
'yourColumnName'
>>> caseTransformations.toUnderscoreCase("yourMixedCaseName")
'your_mixed_case_name'

Beautiful.

It might not be perfect, and you could speed it up by pre-compiling the regular expressions, but I'm happy with it (and open to suggestions of a better implementation)

Subscribe via RSS ı Email
© 2017 - Jehiah Czebotar