Search code examples
javajdbcderbyreserved-words

Determine if a word is a reserved word in Apache Derby


Is there a way to escape only the columns that are reserved words?

For example, I'd like to generate the following statement using java:

create table person(id int, name varchar(255), "year" int);

Notice that "year" has to be escaped because it's a reserved word? Is there a way to determine if a string is a reserved word?

The reason I don't just escape all the columns is because I'd rather have queries look like this:

select id, name, "year" from person

Rather than this:

select "id", "name", "year" from person

Solution

  • From a generic JDBC perspective, there is a way of determining the keywords, using the SQL:2003 keywords list (which you need to obtain yourself) + the result of DatabaseMetaData.getSQLKeywords():

    Retrieves a comma-separated list of all of this database's SQL keywords that are NOT also SQL:2003 keywords.

    However this depends on the list of keywords in the JDBC driver being complete and up to date, which is not always the case. I don't know if that is the case for Derby or not. If you are writing generic software it is better to always quote to avoid the hassle.

    There are plans to include functionality in JDBC 4.3 to quote object names (that is given a string it will either return the string as is (no quoting necessary), quoted if necessary or throws an SQLException if the object name is invalid or quoting is not possible). This isn't final IIRC, and would then need to wait for driver vendors to implements it..