问题
This has been bothering me for a while, and I can't arrive at a solution that feels right...
Given an OO language in which the usual naming convention for object properties is camelCased, and an example object like this:
{
id: 667,
firstName: "Vladimir",
lastName: "Horowitz",
canPlayPiano: true
}
How should I model this structure in a PostgreSQL table?
There are three main options:
- unquoted camelCase column names
- quoted camelCase column names
- unquoted (lowercase) names with underscores
They each have their drawbacks:
Unquoted identifiers automatically fold to lowercase. This means that you can create a table with a
canPlayPiano
column, but the mixed case never reaches the database. When you inspect the table, the column will always show up ascanplaypiano
- in psql, pgadmin, explain results, error messages, everything.Quoted identifiers keep their case, but once you create them like that, you will always have to quote them. IOW, if you create a table with a
"canPlayPiano"
column, aSELECT canPlayPiano ...
will fail. This adds a lot of unnecessary noise to all SQL statements.Lowercase names with underscores are unambiguous, but they don't map well to the names that the application language is using. You will have to remember to use different names for storage (
can_play_piano
) and for code (canPlayPiano
). It also prevents certain types of code automation, where properties and DB columns need to be named the same.
So I'm caught between a rock and a hard place (and a large stone; there are three options). Whatever I do, some part is going to feel awkward. For the last 10 years or so, I've been using option 3, but I keep hoping there would be a better solution.
I'm grateful for any advice you might have.
PS: I do realize where the case folding and the need for quotes is coming from - the SQL standard, or rather PostgreSQL's adaptation of the standard. I know how it works; I'm more interested in advice about best practices than explanations about how PG handles identifiers.
回答1:
Given that PostgreSQL uses case-insensitive identifiers with underscores, should you change all your identifiers in your application to do the same? Clearly not. So why do you think the reverse is a reasonable choice?
The convention in PostgreSQL has come about through a mix of standards compliance and long-term experience of its users. Stick with it.
If translating between column-names and identifiers gets tedious, have the computer do it - they're good at things like that. I'm guessing almost all of the 9-million database abstraction libraries out there can do that. If you have a dynamic language it'll take you all of two lines of code to swap column-names to identifiers in CamelCase.
回答2:
If your columns in the PostgreSQL
are with underscores
, you can put aliases but with doule-quotes.
Example :
SELECT my_column as "myColumn" from table;
来源:https://stackoverflow.com/questions/11270753/underscores-or-camelcase-in-postgresql-identifiers-when-the-programming-languag