with migration to fill slug with default value - postgresql

In my Laravel 5.6/PostgreSQL 10.5 application
I have 2 tables :
CREATE TABLE public.rt_genres (
id serial NOT NULL,
published bool NULL DEFAULT false,
created_at timestamp NOT NULL DEFAULT now(),
updated_at timestamp NULL,
CONSTRAINT rt_genres_pkey PRIMARY KEY (id)
)...
CREATE TABLE public.rt_genre_translations (
id serial NOT NULL,
genre_id int4 NOT NULL,
"name" varchar(100) NOT NULL,
description text NOT NULL,
created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
locale varchar(2) NOT NULL,
CONSTRAINT genre_translations_genre_id_locale_unique UNIQUE (genre_id, locale),
CONSTRAINT rt_genre_translations_pkey PRIMARY KEY (id),
CONSTRAINT genre_translations_genre_id_foreign FOREIGN KEY (genre_id) REFERENCES rt_genres(id) ON DELETE CASCADE
)
I need to add slug field in first rt_genres table
with migration rule:
$table->string('slug', 105)->unique();
and got error :
: Unique violation: 7 ERROR: could not create unique index "genres_slug_unique"
DETAIL: Key (slug)=(id) is duplicated.")
1)If there is a way to assign in migration some unique default value, like = id
->default('rt_genres.id')
?
2) That would be cool to assign to slug value from public.rt_genre_translations.name as I use
"cviebrock/eloquent-sluggable": "^4.5" plugin in my app ? Can I do it ?
Thank you!

You can only get the default value from a different column with a trigger (SO answer).
You can make the column nullable:
$table->string('slug', 105)->nullable()->unique();
Or you create the column, insert unique values and then create the index:
Schema::table('rt_genres', function($table) {
$table->string('slug', 105);
});
DB::table('rt_genres')->update(['slug' => DB::raw('"id"')]);
Schema::table('rt_genres', function($table) {
$table->unique('slug');
});

Related

Postgres Update Query

I'm executing below query in postgres 12.11
Table structure as below:
CREATE TABLE pdb_interface.schedule (
id uuid NOT NULL DEFAULT uuid_generate_v4(),
report varchar NOT NULL,
users varchar NOT NULL,
"hour" int4 NULL,
min int4 NULL,
daily_frequency int4 NULL,
daily_workday bool NULL,
weekly_frequency int4 NULL,
weekly_days varchar NULL,
monthly_sected_days varchar NULL,
last_updated timestamp NULL,
deleted bool NULL,
CONSTRAINT schedule_pkey PRIMARY KEY (id),
CONSTRAINT schedule_report_fkey FOREIGN KEY (report) REFERENCES pdb_interface.report("Id"),
CONSTRAINT schedule_users_fkey FOREIGN KEY (users) REFERENCES pdb_interface.users("Id"));
update schedule
set daily_frequency = 12
where id = 'f2f0ba60-f8b1-49ae-a82c-aaddb1a1834b'
The column "id" is of uuid and value is present in the table . However while executing above query, it is giving below error
SQL Error [XX000]: ERROR: no conversion function from character varying to uuid
Is there any work around for the same

Postgres create many to many relationship to table with composite primary key

CREATE TABLE "public"."Users" (
id SERIAL PRIMARY KEY NOT NULL,
name VARCHAR(255) NOT NULL,
email VARCHAR(255) UNIQUE NOT NULL,
"createdAt" TIMESTAMP NOT NULL DEFAULT now()
);
CREATE TABLE "public"."Boards" (
id SERIAL PRIMARY KEY NOT NULL,
name VARCHAR(255) NOT NULL,
"ownerId" SERIAL NOT NULL,
"createdAt" TIMESTAMP NOT NULL DEFAULT now(),
"updatedAt" TIMESTAMP,
FOREIGN KEY ("ownerId") REFERENCES "public"."Users"(id)
);
CREATE TABLE "public"."Board_Members"(
"userId" SERIAL,
"boardId" SERIAL,
CONSTRAINT board_member_pkey PRIMARY KEY ("userId", "boardId"),
FOREIGN KEY ("userId") REFERENCES "public"."Users"(id),
FOREIGN KEY ("boardId") REFERENCES "public"."Boards"(id)
);
CREATE TABLE "public"."Columns" (
id SERIAL PRIMARY KEY NOT NULL,
name VARCHAR(255) NOT NULL,
"boardId" SERIAL NOT NULL,
"createdAt" TIMESTAMP NOT NULL DEFAULT now(),
"updatedAt" TIMESTAMP,
FOREIGN KEY ("boardId") REFERENCES "public"."Boards"(id)
);
CREATE TABLE "public"."Cards" (
id SERIAL PRIMARY KEY NOT NULL,
name VARCHAR(255) NOT NULL,
description VARCHAR(255) NOT NULL,
dueDate TIMESTAMP,
"columnId" SERIAL NOT NULL,
"createdAt" TIMESTAMP NOT NULL DEFAULT now(),
"updatedAt" TIMESTAMP,
FOREIGN KEY ("columnId") REFERENCES "public"."Columns"(id),
);
I have these tables. Now I want to have a field called "assignee" in "Cards" table which will be a many-to-many relationship with "userId" from "Board_Members" table just like "Boards" and "Users" have a many-to-maany relationship. How do I do that? Do I create a new table and just reference the "userId" column as FK?
Just add a table with 2 foreign keys.
And because I think you want to switch the cards, from person to person. you could also want to keep track of the played history. See also the first normal form to check if your database is designed right.
https://en.wikipedia.org/wiki/First_normal_form
I hope I answered your question :)

Postgres Unique constraint based column value

CREATE TABLE employee (
id varchar(40) NOT NULL,
legacy_id varchar(40) NOT NULL,
short_name varchar(255) NULL,
is_deleted bool NOT NULL DEFAULT false,
CONSTRAINT employee_pkey PRIMARY KEY (id)
)
I want to plan for unique constraint like this
The table must have these constraint
1. Unique constraint is required on column 'legacy_id' and 'is_deleted = false'. Its okay to have multiple values with legacy_id and is_deleted = true.
Is there any way to achieve this
You cannot have a constraint for that, but a partial unique index will do just as well:
CREATE UNIQUE INDEX ON employee (legacy_id)
WHERE is_deleted;

Many-to-one relationship using two unique keys

I have two tables which look like thiS:
uploads
________
id (primary key)
user_id
file_checksum
upload_information
---------
upload_info_id (primary key)
file_checksum
metadata1
metdata2
The "many to one" relationship I am trying to enforce is this:
Many uploads can have the same file checksum
However, the file checksum can only ever point to one upload_information record, thus making the unique constraint between file_checksum and upload_info_id mandatory in the upload_information table.
I am wondering how to alter these tables in Postgres in order to achieve this relationship.
CREATE TABLE uploads (
id SERIAL NOT NULL PRIMARY KEY,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
user_id VARCHAR NOT NULL,
file_checksum VARCHAR NOT NULL,
);
CREATE TABLE upload_information (
upload_info_id SERIAL NOT NULL PRIMARY KEY,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
file_checksum VARCHAR NOT NULL,
file_name VARCHAR NOT NULL,
source_file_url VARCHAR NOT NULL,
);
Add a unique index on file_checksum.
create unique index unique_checksum on upload_information(file_checksum)

pgAdmin - When trying to make a foreign key "referencing" gives no options

I have three tables: ModelingAgency.clients, ModelingAgency.models, ModelingAgency.Bookings. All three tables have a primary key column called id.
The table bookings has two columns that reference clients and models. In pgAdmin when I try to create a foreign key in bookings to either clients or models I get the following screens:
What am I overlooking here? I am new to PostgreSQL (This is my first test project with PostgreSQL -- I've always used MySQL and occasionally SQL Server) so it's probably something obvious (I just don't see it).
EDIT: Here is the DDL, as requested:
-- Table: "ModelingAgency.bookings"
-- DROP TABLE "ModelingAgency.bookings";
CREATE TABLE "ModelingAgency.bookings"
(
id integer NOT NULL DEFAULT nextval('"ModelingAgency.Bookings_id_seq"'::regclass),
"clientId" integer NOT NULL,
"modelId" integer NOT NULL,
"time" timestamp with time zone NOT NULL DEFAULT now(),
"location" character varying(100) NOT NULL DEFAULT 'No Location Selected'::character varying,
CONSTRAINT "bookingId" PRIMARY KEY (id)
)
WITH (
OIDS=FALSE
);
ALTER TABLE "ModelingAgency.bookings" OWNER TO "MyBatisTutorial";
-- Table: "ModelingAgency.clients"
-- DROP TABLE "ModelingAgency.clients";
CREATE TABLE "ModelingAgency.clients"
(
id integer NOT NULL DEFAULT nextval('"ModelAgency.clients_id_seq"'::regclass),
"name" character varying(45) NOT NULL,
CONSTRAINT "clientId" PRIMARY KEY (id)
)
WITH (
OIDS=FALSE
);
ALTER TABLE "ModelingAgency.clients" OWNER TO "MyBatisTutorial";
-- Table: "ModelingAgency.models"
-- DROP TABLE "ModelingAgency.models";
CREATE TABLE "ModelingAgency.models"
(
id serial NOT NULL,
"name" character varying(45) NOT NULL,
CONSTRAINT "modelId" PRIMARY KEY (id)
)
WITH (
OIDS=FALSE
);
ALTER TABLE "ModelingAgency.models" OWNER TO "MyBatisTutorial";
Looking into your posted DDL code I see that your table's names are written in wrong way (that causes your issue with pgAdmin):
"ModelingAgency.bookings"
It should be in format "schema"."tableName":
"ModelingAgency"."bookings"
After that Object browser looks like this (probably you need to create schema first using easily pgAdmin or with CREATE SCHEMA SQL statement):
Here is working DDL code (I omitted some things like OIDS and OWNER TO, but that doesn't matter to your case, BTW OIDS are false on default):
DROP TABLE IF EXISTS "ModelingAgency"."bookings";
CREATE TABLE "ModelingAgency"."bookings"
(
id serial,
"clientId" integer NOT NULL,
"modelId" integer NOT NULL,
"time" timestamp with time zone NOT NULL DEFAULT now(),
"location" character varying(100) NOT NULL
DEFAULT 'No Location Selected'::character varying,
CONSTRAINT "bookingId" PRIMARY KEY (id)
);
DROP TABLE IF EXISTS "ModelingAgency"."clients";
CREATE TABLE "ModelingAgency"."clients"
(
id serial,
"name" character varying(45) NOT NULL,
CONSTRAINT "clientId" PRIMARY KEY (id)
);
DROP TABLE IF EXISTS "ModelingAgency"."models";
CREATE TABLE "ModelingAgency"."models"
(
id serial NOT NULL,
"name" character varying(45) NOT NULL,
CONSTRAINT "modelId" PRIMARY KEY (id)
)