Last active
December 19, 2015 11:58
-
-
Save theY4Kman/5951460 to your computer and use it in GitHub Desktop.
Generates a MySQL (maybe generic SQL) expression which converts the stored index of an enum to its constant name. Useful if some jackasses put their constants in the PHP code—not in the database—and you want to see more descriptive values than numbers.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| def sql_enum_if(enum_dict, field): | |
| """ | |
| Example: | |
| >>> enum_dict = {'CONST_NAME': 1, 'CONST_TWO': 2} | |
| {'CONST_TWO': 2, 'CONST_NAME': 1} | |
| >>> sql_enum_if(enum_dict, 'myfield') | |
| 'IF(myfield = 2, "CONST_TWO", IF(myfield = 1, "CONST_NAME", "<unknown>")) AS myfield' | |
| """ | |
| def _sql_enum_if(items): | |
| if not items: | |
| return '"<unknown>"' | |
| return 'IF(%s = %d, "%s", %s)' % (field, items[0][1], items[0][0], _sql_enum_if(items[1:])) | |
| return '%s AS %s' % (_sql_enum_if(enum_dict.items()), field) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment