0

I'm trying to create a schema and add tables to it via node using node-postgres (pg). The basic order of events is as follows:

1. Create schema
2. Create table in schema
3. Create columns in table in schema

I can verify that the schema and the table are being created without issues, but I get a relation does not exist error when trying to add the first column to the table. The query string for creating the column looks like this:

"ALTER TABLE " +
schemaName +
".process ADD COLUMN process_id bigint NOT NULL DEFAULT nextval('" +
schemaName +
".process_process_id_seq'::regclass)";

I've confirmed in the console log that the schema name variable matches what is was used to successfully create the table. Any ideas on why the error is being thrown here?

7
  • Does process_process_id_seq exist? Commented Jun 28, 2020 at 16:05
  • @stickybit it does not. I thought it was created in the code block defining the column. Does the sequence need to be created prior to creating the column? Commented Jun 28, 2020 at 16:19
  • Note that the code in the question and answer are vulnerable to SQL injection. Commented Jun 29, 2020 at 6:24
  • @LaurenzAlbe can you expand on that? Commented Jun 29, 2020 at 12:11
  • Try with a schemaName that contains a double quote. Then your query will go boom or worse. Commented Jun 29, 2020 at 12:27

1 Answer 1

1

The sequence needs to be created beforehand.

But you could also use the bigserial type which is a shortcut for a bigint column with a sequence and a respective DEFAULT created automatically. Something along the lines of:

"ALTER TABLE " +
schemaName +
".process ADD COLUMN process_id bigserial";

Maybe you fell over that. Later, when the table/column was created you cannot see the ...serial anymore but the actual type and the DEFAULT.

More on ...serial types can be found in the documentation.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, this worked! I initially set up a sample table in pgAdmin where I defined the column as bigserial. It looks like pgAdmin converts it to bigint if you look at the CREATE script that it generates (which I was copying before).
@userNick: It's not pgAdmin which converts it but the DBMS itself. But yes, afterwards you cannot see the ...serial in the CREATE that pgAdmin creates but the real type and the DEFAULT.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.