seancorfield / honeysql

Turn Clojure data structures into SQL
https://cljdoc.org/d/com.github.seancorfield/honeysql/CURRENT
1.77k stars 174 forks source link

postgres :alter-column documentation produces incompatible queries. #536

Closed Tillaert closed 4 months ago

Tillaert commented 4 months ago

According to the honeysql postgres documetation:

This statement is given as an example.

user=> (-> (alter-table :fruit)
           (alter-column :name [:varchar 64] [:not nil])
           sql/format)
["ALTER TABLE fruit ALTER COLUMN name VARCHAR(64) NOT NULL"]

However, this creates code which is not compatible with postgres.

Postgres expects

ALTER TABLE fruit ALTER COLUMN name TYPE VARCHAR(64)

and

ALTER TABLE fruit ALTER COLUMN name SET NOT NULL

(See: https://www.postgresql.org/docs/current/sql-altertable.html )

This can be achieved with these queries:

{:alter-table [:table], :alter-column [(:column :set [:not nil])]}

and:

{:alter-table [:table], :alter-column [(:column :type [:varchar 64])]}

seancorfield commented 4 months ago

Your alternatives do not work:

user=> (sql/format {:alter-table [:table], :alter-column [(:column :set [:not nil])]})
["ALTER TABLE table ALTER COLUMN not NULL"]

But the following do work:

user=> (-> (alter-table :fruit)
           (alter-column :name :type [:varchar 64])
           sql/format)
["ALTER TABLE fruit ALTER COLUMN name TYPE VARCHAR(64)"]
user=> (-> (alter-table :fruit)
           (alter-column :name :set [:not nil])
           sql/format)
["ALTER TABLE fruit ALTER COLUMN name SET NOT NULL"]
user=>

The raw DSL for that last one is:

{:alter-table [:fruit], :alter-column [:name :set [:not nil]]}
Tillaert commented 4 months ago

You are correct. My apologies for the mistake.