sqlc icon indicating copy to clipboard operation
sqlc copied to clipboard

generate ignoring IF NOT EXISTS on ADD COLUMN

Open meeech opened this issue 2 years ago • 2 comments

Version

1.13.0

What happened?

Hi. New user, evaluating sqlc for use.

What Happens:

We have some migrations/*.sql. When running sqlc generate, all the .sql in this folder are being executed.

So i get errors like

migrations/V20220422073404__create_intitial_tables.sql:1:1: relation "integrations" already exists

and

migrations/V20220524081832__created_and_updated_at.sql:1:1: column "created_at" of relation "integrations" already exists

Which is fair, so I'm working to make these statements idempotent.

So in the first case (create_initial_tables.sql), I modify the SQL to use IF NOT EXISTS

CREATE table IF NOT EXISTS integrations ...

run sqlc generate and the error for that migration is resolved.

I try the same on for my 2nd sql where we are altering the table:

ALTER TABLE ONLY integrations ADD COLUMN IF NOT EXISTS created_at TIMESTAMP;

But I continue to the same error. Running this query directly with my sql tool generates no error.

Expectation:

I expect the ALTER TABLE ONLY integrations ADD COLUMN IF NOT EXISTS created_at TIMESTAMP; to respect the IF NOT EXISTS, and not give me an error on generate, similar to the CREATE table statement.

Questions:

  1. Is this a bug?
  2. If no, should I be doing something different to work around this issue?
  3. If yes, if you can point me to the relevant area, I can look to put together a PR. No promises though, pretty new to go at this point :D

Let me know if there are any other details I can provide.

thanks for your time

Relevant log output

No response

Database schema

No response

SQL queries

ALTER TABLE ONLY public.integrations ADD COLUMN IF NOT EXISTS created_at TIMESTAMP;

Configuration

version: "1"
project:
  id: "rt"
packages:
  - path: "internal/db"
    queries: "./queries"
    schema:
      - "./schema.sql"
      - "./migrations"
    engine: "postgresql"

Playground URL

No response

What operating system are you using?

macOS

What database engines are you using?

PostgreSQL

What type of code are you generating?

Go

meeech avatar May 27 '22 02:05 meeech

/assign

SpikeWong avatar Sep 08 '22 09:09 SpikeWong

@kyleconroy I want to make sure that what I need to do is to check the current value of stmt.IfNotExist in the addColumn method,
If a column exists and stmt.IfNotExist is true, I'll just return nil, is that right? https://github.com/kyleconroy/sqlc/blob/b0d6f13646d52287a6eb9be623f827227bfd6c7b/internal/sql/catalog/table.go#L34

SpikeWong avatar Sep 08 '22 09:09 SpikeWong