I have the following procedure query that works fine:
CREATE OR REPLACE FUNCTION table_update_notify() RETURNS trigger AS $$
DECLARE
notification_channel text := TG_ARGV[0];
owner_id numeric := TG_ARGV[1];
owner_lat numeric := TG_ARGV[2];
owner_lng numeric := TG_ARGV[3];
trigger_radius numeric := TG_ARGV[4];
nearby_radius numeric := TG_ARGV[5];
changed_lat numeric;
changed_lng numeric;
user_id numeric;
is_close boolean;
name text;
BEGIN
IF TG_OP = 'INSERT' OR TG_OP = 'UPDATE' THEN
changed_lat = NEW.lat;
changed_lng = NEW.lng;
user_id = NEW.user_id;
name = NEW.name;
ELSE
changed_lat = OLD.lat;
changed_lng = OLD.lng;
user_id = OLD.user_id;
name = OLD.name;
END IF;
-- If updated user's location is within the trigger radius of the trigger owner's location
IF earth_box(ll_to_earth(owner_lat, owner_lng), trigger_radius) @> ll_to_earth(changed_lat, changed_lng)
-- Don't notify owner if the owner's location changes
AND user_id != owner_id
THEN
PERFORM pg_notify(notification_channel, json_build_object('user_id', user_id, 'name', name, 'is_close', is_close)::text);
END IF;
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
But if I insert another «IF» system after the «THEN», like so, I get an error:
CREATE OR REPLACE FUNCTION table_update_notify() RETURNS trigger AS $$
DECLARE
notification_channel text := TG_ARGV[0];
owner_id numeric := TG_ARGV[1];
owner_lat numeric := TG_ARGV[2];
owner_lng numeric := TG_ARGV[3];
trigger_radius numeric := TG_ARGV[4];
nearby_radius numeric := TG_ARGV[5];
changed_lat numeric;
changed_lng numeric;
user_id numeric;
is_close boolean;
name text;
BEGIN
IF TG_OP = 'INSERT' OR TG_OP = 'UPDATE' THEN
changed_lat = NEW.lat;
changed_lng = NEW.lng;
user_id = NEW.user_id;
name = NEW.name;
ELSE
changed_lat = OLD.lat;
changed_lng = OLD.lng;
user_id = OLD.user_id;
name = OLD.name;
END IF;
-- If updated user's location is within the trigger radius of the trigger owner's location
IF earth_box(ll_to_earth(owner_lat, owner_lng), trigger_radius) @> ll_to_earth(changed_lat, changed_lng)
-- Don't notify owner if the owner's location changes
AND user_id != owner_id
THEN
-- If the user is close enough to the user to be considered nearby
IF earth_box(ll_to_earth(owner_lat, owner_lng), trigger_radius) @> ll_to_earth(changed_lat, changed_lng) THEN
is_close = true;
ELSE
is_close = false;
END IF
PERFORM pg_notify(notification_channel, json_build_object('user_id', user_id, 'name', name, 'is_close', is_close)::text);
END IF;
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
And the error is:
ERROR: syntax error at or near "PERFORM"
LINE 39: PERFORM pg_notify(notification_channel, json_build_object(...
According to my research, this happens when the language is not set to plpgsql, but I clearly am doing that. How can I execute this nested IF statement?
Introduction
Actually, this article has a relation with the existence of the previous article. That previous article exist in this link with the title of ‘How to Solve Error Message Model Attribute Problem SyntaxError: invalid syntax in Django Application’. It is actually just inappropriate format of the column name available in the SQL file. That SQL file actually containing an INSERT statement for restoring data to the targeted database. But since there is a column name which is not following the standard rule which starts with a character that is not number or letter, it cause the restore process to fail.
The following is just to describe that accessing the database is not the cause of the problem.
Microsoft Windows [Version 10.0.19042.1288] (c) Microsoft Corporation. All rights reserved. C:UsersPersonal>cd C:>psql -Upostgres -d db_app Password for user postgres: psql (14.0) WARNING: Console code page (437) differs from Windows code page (1252) 8-bit characters might not work correctly. See psql reference page "Notes for Windows users" for details. Type "help" for help. db_app=# q
After that, the process for inserting records by importing it or restoring it using the following command exist as follows :
C:>psql -Uuser_app -d db_app < "C:UsersPersonalDownloadsinsert-current-product.sql" Password for user db_user: ERROR: syntax error at or near "[" LINE 1: ...,[product_code... ^
As in the above command execution, it fail with an error message appear.
Solution
Actually, the solution for the above error message causing it is because of the column’s character is not a proper name for a column name. In that case, just change it into a proper one. So, edit the SQL file and find the column’s character or the column name which is the cause for the database restore process to fail. Changing the column name from [product_code] to another proper one. That new column name is ‘product_code’. After editing the file, just execute the process for importing or restoring the data once more as follows :
C:>psql -Uuser_sinergi -d db_sinergi < "C:UsersPersonalDownloadsinsert-current-product.sql" Password for user db_user: INSERT 0 556 C:>
Fortunately, the process is a success as in the output of the command above.
@YohDeadfall — I understand that part about it, but this is not script that I am creating or even code that I am creating. This is all created under the hood by Npsql/EntityFramework. My quick guess is that I am extending my DbContext from IdentityDbContext<IdentityUser>
which wants to create all of the tables for roles, users, claims, etc. If I change this to just extend from DbContext
, then everything works as advertised.
Below is the script that EF is trying to use created from dotnet ef migrations script
— please be aware that I have removed my custom part of the script for brevity.
You can see there are two specific calls that are being made where [NormalizedName]
and [NormalizedUserName]
are being used.
CREATE TABLE IF NOT EXISTS "__EFMigrationsHistory" ( "MigrationId" varchar(150) NOT NULL, "ProductVersion" varchar(32) NOT NULL, CONSTRAINT "PK___EFMigrationsHistory" PRIMARY KEY ("MigrationId") ); CREATE TABLE "AspNetRoles" ( "Id" text NOT NULL, "ConcurrencyStamp" text NULL, "Name" varchar(256) NULL, "NormalizedName" varchar(256) NULL, CONSTRAINT "PK_AspNetRoles" PRIMARY KEY ("Id") ); CREATE TABLE "AspNetUsers" ( "Id" text NOT NULL, "AccessFailedCount" int4 NOT NULL, "ConcurrencyStamp" text NULL, "Email" varchar(256) NULL, "EmailConfirmed" bool NOT NULL, "LockoutEnabled" bool NOT NULL, "LockoutEnd" timestamptz NULL, "NormalizedEmail" varchar(256) NULL, "NormalizedUserName" varchar(256) NULL, "PasswordHash" text NULL, "PhoneNumber" text NULL, "PhoneNumberConfirmed" bool NOT NULL, "SecurityStamp" text NULL, "TwoFactorEnabled" bool NOT NULL, "UserName" varchar(256) NULL, CONSTRAINT "PK_AspNetUsers" PRIMARY KEY ("Id") ); CREATE TABLE "AspNetRoleClaims" ( "Id" int4 NOT NULL, "ClaimType" text NULL, "ClaimValue" text NULL, "RoleId" text NOT NULL, CONSTRAINT "PK_AspNetRoleClaims" PRIMARY KEY ("Id"), CONSTRAINT "FK_AspNetRoleClaims_AspNetRoles_RoleId" FOREIGN KEY ("RoleId") REFERENCES "AspNetRoles" ("Id") ON DELETE CASCADE ); CREATE TABLE "AspNetUserClaims" ( "Id" int4 NOT NULL, "ClaimType" text NULL, "ClaimValue" text NULL, "UserId" text NOT NULL, CONSTRAINT "PK_AspNetUserClaims" PRIMARY KEY ("Id"), CONSTRAINT "FK_AspNetUserClaims_AspNetUsers_UserId" FOREIGN KEY ("UserId") REFERENCES "AspNetUsers" ("Id") ON DELETE CASCADE ); CREATE TABLE "AspNetUserLogins" ( "LoginProvider" text NOT NULL, "ProviderKey" text NOT NULL, "ProviderDisplayName" text NULL, "UserId" text NOT NULL, CONSTRAINT "PK_AspNetUserLogins" PRIMARY KEY ("LoginProvider", "ProviderKey"), CONSTRAINT "FK_AspNetUserLogins_AspNetUsers_UserId" FOREIGN KEY ("UserId") REFERENCES "AspNetUsers" ("Id") ON DELETE CASCADE ); CREATE TABLE "AspNetUserRoles" ( "UserId" text NOT NULL, "RoleId" text NOT NULL, CONSTRAINT "PK_AspNetUserRoles" PRIMARY KEY ("UserId", "RoleId"), CONSTRAINT "FK_AspNetUserRoles_AspNetRoles_RoleId" FOREIGN KEY ("RoleId") REFERENCES "AspNetRoles" ("Id") ON DELETE CASCADE, CONSTRAINT "FK_AspNetUserRoles_AspNetUsers_UserId" FOREIGN KEY ("UserId") REFERENCES "AspNetUsers" ("Id") ON DELETE CASCADE ); CREATE TABLE "AspNetUserTokens" ( "UserId" text NOT NULL, "LoginProvider" text NOT NULL, "Name" text NOT NULL, "Value" text NULL, CONSTRAINT "PK_AspNetUserTokens" PRIMARY KEY ("UserId", "LoginProvider", "Name"), CONSTRAINT "FK_AspNetUserTokens_AspNetUsers_UserId" FOREIGN KEY ("UserId") REFERENCES "AspNetUsers" ("Id") ON DELETE CASCADE ); CREATE INDEX "IX_AspNetRoleClaims_RoleId" ON "AspNetRoleClaims" ("RoleId"); CREATE UNIQUE INDEX "RoleNameIndex" ON "AspNetRoles" ("NormalizedName") WHERE [NormalizedName] IS NOT NULL; CREATE INDEX "IX_AspNetUserClaims_UserId" ON "AspNetUserClaims" ("UserId"); CREATE INDEX "IX_AspNetUserLogins_UserId" ON "AspNetUserLogins" ("UserId"); CREATE INDEX "IX_AspNetUserRoles_RoleId" ON "AspNetUserRoles" ("RoleId"); CREATE INDEX "EmailIndex" ON "AspNetUsers" ("NormalizedEmail"); CREATE UNIQUE INDEX "UserNameIndex" ON "AspNetUsers" ("NormalizedUserName") WHERE [NormalizedUserName] IS NOT NULL; INSERT INTO "__EFMigrationsHistory" ("MigrationId", "ProductVersion") VALUES ('20180514204732_initial', '2.0.3-rtm-10026');
Syntax errors are quite common while coding.
But, things go for a toss when it results in website errors.
PostgreSQL error 42601 also occurs due to syntax errors in the database queries.
At Bobcares, we often get requests from PostgreSQL users to fix errors as part of our Server Management Services.
Today, let’s check PostgreSQL error in detail and see how our Support Engineers fix it for the customers.
What causes error 42601 in PostgreSQL?
PostgreSQL is an advanced database engine. It is popular for its extensive features and ability to handle complex database situations.
Applications like Instagram, Facebook, Apple, etc rely on the PostgreSQL database.
But what causes error 42601?
PostgreSQL error codes consist of five characters. The first two characters denote the class of errors. And the remaining three characters indicate a specific condition within that class.
Here, 42 in 42601 represent the class “Syntax Error or Access Rule Violation“.
In short, this error mainly occurs due to the syntax errors in the queries executed. A typical error shows up as:
Here, the syntax error has occurred in position 119 near the value “parents” in the query.
How we fix the error?
Now let’s see how our PostgreSQL engineers resolve this error efficiently.
Recently, one of our customers contacted us with this error. He tried to execute the following code,
CREATE OR REPLACE FUNCTION prc_tst_bulk(sql text)
RETURNS TABLE (name text, rowcount integer) AS
$$
BEGIN
WITH m_ty_person AS (return query execute sql)
select name, count(*) from m_ty_person where name like '%a%' group by name
union
select name, count(*) from m_ty_person where gender = 1 group by name;
END
$$ LANGUAGE plpgsql;
But, this ended up in PostgreSQL error 42601. And he got the following error message,
ERROR: syntax error at or near "return"
LINE 5: WITH m_ty_person AS (return query execute sql)
Our PostgreSQL Engineers checked the issue and found out the syntax error. The statement in Line 5 was a mix of plain and dynamic SQL. In general, the PostgreSQL query should be either fully dynamic or plain. Therefore, we changed the code as,
RETURN QUERY EXECUTE '
WITH m_ty_person AS (' || sql || $x$)
SELECT name, count(*)::int FROM m_ty_person WHERE name LIKE '%a%' GROUP BY name
UNION
SELECT name, count(*)::int FROM m_ty_person WHERE gender = 1 GROUP BY name$x$;
This resolved the error 42601, and the code worked fine.
[Need more assistance to solve PostgreSQL error 42601?- We’ll help you.]
Conclusion
In short, PostgreSQL error 42601 occurs due to the syntax errors in the code. Today, in this write-up, we have discussed how our Support Engineers fixed this error for our customers.
PREVENT YOUR SERVER FROM CRASHING!
Never again lose customers to poor server speed! Let us help you.
Our server experts will monitor & maintain your server 24/7 so that it remains lightning fast and secure.
GET STARTED
var google_conversion_label = «owonCMyG5nEQ0aD71QM»;