I have created the following setup script. The script is meant to be run before the application (which would run on node) is deployed.
The idea is that it would eventually contain all table definitions, relations, stored procedures and some seed data to make the application work, split into different files.
But currently I'm stuck because I can't figure out how I can store data in variables.
In this example we have profiles (because user is a keyword) and inventories. I want each user to have an inventory. For this to work I need to generate an inventory, store its id in a variable and pass it to the profile.
But for some reason postgres won't allow me to declare variables. Heres what I got so far:
drop database test;
create database test;
\c test
create extension if not exists "uuid-ossp";
create table inventory(
id uuid PRIMARY KEY DEFAULT uuid_generate_v4(),
name text
);
create table profile(
id uuid PRIMARY KEY DEFAULT uuid_generate_v4(),
name text,
inventory_id uuid references inventory(id)
);
DECLARE myid uuid;
/*I want to set the inv_id to the result of this expression*/
insert into inventory(name) values('asdf') returning id into myid;
insert into profile(name,inventory_id) values ('user1',@myid)
But I get the following error:
$ psql -U postgres -f init.sql
psql:init.sql:18: ERROR: syntax error at or near "uuid"
LINE 1: DECLARE myid uuid;
^
So how can I create a variable to store this id? Am I doing something wrong in general, because I'm pretty sure Declare is part of the SQL spec.
Declare is part of the SQL spec.Yes, but it has a different meaning from what you think it has.