How to approach converting camelCase to snake_case field names

Hi folks,

I am hooking Phoenix up to an existing database that (unfortunately) has camelCase field names. I was wondering has anyone had any experience with this? I know that you can make Ecto work with camelCase field names but, ideally, I’d like to convert/translate the field names to snake_case when they are read from the database. It this possible? Or is it a bad idea?


1 Like

Macro.underscore/1 will turn camelCase and PascalCase into snake_case. I don’t know if you’re supposed to use something else, but that’s the one I usually use if I need to.

iex> Macro.underscore "hejHopp"

It also works with modules, etc.

iex> Macro.underscore HejHopp

Hi gonz,

Thanks for responding! I was thinking of something more as an interface between the database and the application which did this for me automatically for all fields I specify. To be efficient I guess it would need to be part of the actual SQL query that is built. For instance, if I have a table:-

users table

…the query built by Ecto would be something like:

select id, firstName as first_name, lastName as last_name
from users

I’m just not sure where to start with integrating something like this with Ecto. Any ideas appreciated!


Even though I can’t tell you how to do this right now, Ecto might support aliases in the future:

That looks perfect - thanks! Looks like the pull request is coming along well :slight_smile:

I’m highly looking forward to aliases myself! I’m interacting with an ancient database that prepends the (often very large) table name to each column name, so instead of having a column name of, say, id, I have blahLongTableNameInCamelCase_id, which makes for VERY dreadfully long queries… >.>

Looking forward to this feature. Very useful when I’m writing elixir app for a legacy database created by Rails.

1 Like

Hi all, we have a PR open here: Appreciate if we can get comments and review there.