vapor-community / postgresql

Robust PostgreSQL interface for Swift
MIT License
131 stars 33 forks source link

Support SQL keyword as column names #38

Closed BrettRToomey closed 7 years ago

BrettRToomey commented 7 years ago

Moved from: https://github.com/vapor/fluent/issues/131

Feature, Enhancement, or Optimization

Name of Feature

Support SQL keyword as column names

Introduction

I was adding a model with a "var desc: String" field, then in the preparation step console shows error:

Failed to prepare [ModelName]
invalidSQL("ERROR: syntax error at or near "desc"\nLINE 1: ...RIMARY KEY NOT NULL, desc VARCH...\n ^\n")"

(more details in https://github.com/vapor/postgresql-provider/issues/9)

Changing "desc" to "desca" fixes the problem, and apparently it's caused by "desc" as a reserved keyword in SQL, which could be worked around by adding [] around the column names (http://stackoverflow.com/questions/285775/how-to-deal-with-sql-column-names-that-look-like-sql-keywords).

Motivation

Since Fluent should be DB agnostic, it shouldn't limit what name Model var/column could have, so we should make it support any var name.

Proposed solution

Not sure if MySQL, Postgres & MongoDB share similar solution to special column names or not, but for Postgres for example, we probably could always add [] around the column names when making queries or commands to make sure they work - it could also be the job of each provider or driver, but probably we want to start with Fluent to at least provide comment/instruction about column names to the providers.

Impact

Shouldn't have any impact to existing code

Alternatives considered

Have better error output when a reserved keyword is used, which is not as ideal

Decision (For Moderator Use)

On [Date], the community decided to (TBD) this proposal. When the community makes a decision regarding this proposal, their rationale for the decision will be written here.

vzsg commented 7 years ago

This will be fixed in the v2 update - all column and table names are automatically escaped with quotes.