Ошибка синтаксиса примерное положение generated

I am migrating data using code first approach and db is postgresql, on add-migration is working fine,but update-database is giving error as»42601: syntax error at or near «GENERATED», more details below:

> PM> add-migration migration
>     Build started...
>     Build succeeded.
>     To undo this action, use Remove-Migration.
>     PM> update-database
>     Build started...
>     Build succeeded.
>     [15:18:48 Error] Microsoft.EntityFrameworkCore.Database.Command
>     Failed executing DbCommand (298ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
>     CREATE TABLE "Customers" (
>         "CustomerId" integer NOT NULL GENERATED BY DEFAULT AS IDENTITY,
>         "CustomerName" text NULL,
>         CONSTRAINT "PK_Customers" PRIMARY KEY ("CustomerId")
>     );
>     
>     Npgsql.PostgresException (0x80004005): 42601: syntax error at or near "GENERATED"
>        at Npgsql.NpgsqlConnector.<>c__DisplayClass160_0.<<DoReadMessage>g__ReadMessageLong|0>d.MoveNext()
>     --- End of stack trace from previous location where exception was thrown ---
>        at Npgsql.NpgsqlConnector.<>c__DisplayClass160_0.<<DoReadMessage>g__ReadMessageLong|0>d.MoveNext()
>     --- End of stack trace from previous location where exception was thrown ---
>        at Npgsql.NpgsqlDataReader.NextResult(Boolean async, Boolean isConsuming)
>        at Npgsql.NpgsqlDataReader.NextResult()
>        at Npgsql.NpgsqlCommand.ExecuteReaderAsync(CommandBehavior behavior, Boolean async, CancellationToken cancellationToken)
>        at Npgsql.NpgsqlCommand.ExecuteNonQuery(Boolean async, CancellationToken cancellationToken)
>        at Npgsql.NpgsqlCommand.ExecuteNonQuery()
>        at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteNonQuery(RelationalCommandParameterObject
> parameterObject)
>        at Microsoft.EntityFrameworkCore.Migrations.MigrationCommand.ExecuteNonQuery(IRelationalConnection
> connection, IReadOnlyDictionary`2 parameterValues)
>        at Microsoft.EntityFrameworkCore.Migrations.Internal.MigrationCommandExecutor.ExecuteNonQuery(IEnumerable`1
> migrationCommands, IRelationalConnection connection)
>        at Microsoft.EntityFrameworkCore.Migrations.Internal.Migrator.Migrate(String
> targetMigration)
>        at Microsoft.EntityFrameworkCore.Design.Internal.MigrationsOperations.UpdateDatabase(String
> targetMigration, String contextType)
>        at Microsoft.EntityFrameworkCore.Design.OperationExecutor.UpdateDatabaseImpl(String
> targetMigration, String contextType)
>        at Microsoft.EntityFrameworkCore.Design.OperationExecutor.UpdateDatabase.<>c__DisplayClass0_0.<.ctor>b__0()
>        at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action
> action)
>       Exception data:
>         Severity: ERROR
>         SqlState: 42601
>         MessageText: syntax error at or near "GENERATED"
>         Position: 63
>         File: src\backend\parser\scan.l
>         Line: 1067
>         Routine: scanner_yyerror
>     42601: syntax error at or near "GENERATED"

(As this is code first approach so, below are the model)
Model:

     public class Customer1
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int CustomerId { get; set; }
        public string CustomerName { get; set; }
    }


**Update: Got a solution:
in migrationbuilder(created after add-migration command),i simply changed** 
NpgsqlValueGenerationStrategy.IdentityByDefaultColumn 
to 
NpgsqlValueGenerationStrategy.serialcolumn
**and saved it ,and then run the command update-database ,and it worked**

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»;

Содержание

  1. PostgreSQL error 42601- How we fix it
  2. What causes error 42601 in PostgreSQL?
  3. How we fix the error?
  4. Conclusion
  5. PREVENT YOUR SERVER FROM CRASHING!
  6. 10 Comments

PostgreSQL error 42601- How we fix it

by Sijin George | Sep 12, 2019

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,

But, this ended up in PostgreSQL error 42601. And he got the following error message,

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,

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.

SELECT * FROM long_term_prediction_anomaly WHERE + “‘Timestamp’” + ‘”BETWEEN ‘” +
2019-12-05 09:10:00+ ‘”AND’” + 2019-12-06 09:10:00 + “‘;”)

Hello Joe,
Do you still get PostgreSQL errors? If you need help, we’ll be happy to talk to you on chat (click on the icon at right-bottom).

У меня ошибка drop table exists “companiya”;

CREATE TABLE “companiya” (
“compania_id” int4 NOT NULL,
“fio vladelca” text NOT NULL,
“name” text NOT NULL,
“id_operator” int4 NOT NULL,
“id_uslugi” int4 NOT NULL,
“id_reklama” int4 NOT NULL,
“id_tex-specialist” int4 NOT NULL,
“id_filial” int4 NOT NULL,
CONSTRAINT “_copy_8” PRIMARY KEY (“compania_id”)
);

CREATE TABLE “filial” (
“id_filial” int4 NOT NULL,
“street” text NOT NULL,
“house” int4 NOT NULL,
“city” text NOT NULL,
CONSTRAINT “_copy_5” PRIMARY KEY (“id_filial”)
);

CREATE TABLE “login” (
“id_name” int4 NOT NULL,
“name” char(20) NOT NULL,
“pass” char(20) NOT NULL,
PRIMARY KEY (“id_name”)
);

CREATE TABLE “operator” (
“id_operator” int4 NOT NULL,
“obrabotka obrasheniya” int4 NOT NULL,
“konsultirovanie” text NOT NULL,
“grafick work” date NOT NULL,
CONSTRAINT “_copy_2” PRIMARY KEY (“id_operator”)
);

CREATE TABLE “polsovateli” (
“id_user” int4 NOT NULL,
“id_companiya” int4 NOT NULL,
“id_obrasheniya” int4 NOT NULL,
“id_oshibka” int4 NOT NULL,
CONSTRAINT “_copy_6” PRIMARY KEY (“id_user”)
);

CREATE TABLE “reklama” (
“id_reklama” int4 NOT NULL,
“tele-marketing” text NOT NULL,
“soc-seti” text NOT NULL,
“mobile” int4 NOT NULL,
CONSTRAINT “_copy_3” PRIMARY KEY (“id_reklama”)
);

CREATE TABLE “tex-specialist” (
“id_tex-specialist” int4 NOT NULL,
“grafik” date NOT NULL,
“zarplata” int4 NOT NULL,
“ispravlenie oshibok” int4 NOT NULL,
CONSTRAINT “_copy_7” PRIMARY KEY (“id_tex-specialist”)
);

CREATE TABLE “uslugi” (
“id_uslugi” int4 NOT NULL,
“vostanavlenia parola” int4 NOT NULL,
“poterya acaunta” int4 NOT NULL,
CONSTRAINT “_copy_4” PRIMARY KEY (“id_uslugi”)
);

ALTER TABLE “companiya” ADD CONSTRAINT “fk_companiya_operator_1” FOREIGN KEY (“id_operator”) REFERENCES “operator” (“id_operator”);
ALTER TABLE “companiya” ADD CONSTRAINT “fk_companiya_uslugi_1” FOREIGN KEY (“id_uslugi”) REFERENCES “uslugi” (“id_uslugi”);
ALTER TABLE “companiya” ADD CONSTRAINT “fk_companiya_filial_1” FOREIGN KEY (“id_filial”) REFERENCES “filial” (“id_filial”);
ALTER TABLE “companiya” ADD CONSTRAINT “fk_companiya_reklama_1” FOREIGN KEY (“id_reklama”) REFERENCES “reklama” (“id_reklama”);
ALTER TABLE “companiya” ADD CONSTRAINT “fk_companiya_tex-specialist_1” FOREIGN KEY (“id_tex-specialist”) REFERENCES “tex-specialist” (“id_tex-specialist”);
ALTER TABLE “polsovateli” ADD CONSTRAINT “fk_polsovateli_companiya_1” FOREIGN KEY (“id_companiya”) REFERENCES “companiya” (“compania_id”);

ERROR: ОШИБКА: ошибка синтаксиса (примерное положение: “”companiya””)
LINE 1: drop table exists “companiya”;
^

Источник

@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');

Я пытаюсь выяснить, как настроить основной проект .net в linux, используя Postgresql в качестве сервера базы данных.

Я начал с проекта веб-API .net core 2.2 по умолчанию, который предоставляет вам объект WeatherForecast.

Я добавил к этому идентификатор, аннотировал его ключом и произвел первоначальную миграцию;

    protected override void Up(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.CreateTable(
            name: "WeatherForecasts",
            columns: table => new
            {
                Id = table.Column<int>(nullable: false)
                    .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
                Date = table.Column<DateTime>(nullable: false),
                TemperatureC = table.Column<int>(nullable: false),
                Summary = table.Column<string>(nullable: true)
            },
            constraints: table =>
            {
                table.PrimaryKey("PK_WeatherForecasts", x => x.Id);
            });
    }

Когда я пытаюсь применить миграцию, я получаю следующую ошибку;

Npgsql.PostgresException (0x80004005): 42601: syntax error at or near "GENERATED"

Ошибка указывает на то, что в базе данных есть проблема со словом ‘GENERATED’

Отладчик показывает точный запрос к базе данных;

CREATE TABLE "WeatherForecasts" (
    "Id" integer NOT NULL GENERATED BY DEFAULT AS IDENTITY,
    "Date" timestamp without time zone NOT NULL,
    "TemperatureC" integer NOT NULL,
    "Summary" text NULL,
    CONSTRAINT "PK_WeatherForecasts" PRIMARY KEY ("Id")
);

Я открылокно терминала, подключенное к postgresql cli и непосредственно попробовавшее создание, подтвердило, что слово GENERATED вызывало ошибку.

Есть какие-либо идеи относительно того, что относится к этому GENERATED?Нужно ли устанавливать другую версию postgres?(сейчас 9.6.15)

В моем CsProj есть следующие пакеты для Entity Framework и Postgresql;

"Microsoft.EntityFrameworkCore.Design" Version="3.0.0"

"Npgsql.EntityFrameworkCore.PostgreSQL" Version="3.0.0"

"Npgsql.EntityFrameworkCore.PostgreSQL.Design" Version="1.1.1"

Большое спасибо

user551388


  • #1

Установил postgresql всё прекрасно работает, но возникла необходимость добавить столбец в таблицу, который по умолчанию будет брать значение из другого столбца и что-то с ним делать, а результат записывать себе. Для этого нагуглил функцию generated, но когда вставляю её получаю ошибку «ошибка синтаксиса (примерное положение:»generated»)». Её надо как-то дополнительно добавлять или что?
Пример из консоли

  • E.HP.S
  • Physics
  • Replies: 0

I’m working on a device that used an Arduino Nano to operate multiple motors with a cumulative current draw of over 1A. Commands are sent from a computer via USB to operate the motors. The device is powered by an external 12V supply from a wall outlet, which the Arduino is meant to be powered through by the USB. Its 5V pin is not connected to the network.

I was doing some testing with a new on-off button setup and realized that when the 12V supply is absent but the Arduino is plugged into USB, the device actually draws a little over 4V through the Vin pin and into the 12V net. I don’t believe the Nano has easily modified connections to change how power is distributed across its pins, and I know that powering it through the 5V pin directly will not only lead to the same problem, but also connect the USB supply straight to 5V net directly, rather than the 12V supply line that just connects to the regulators and Arduino’s Vin.

I may just be making mountains out of mole hills, and I also know that with a more custom setup instead of a prefab Arduino this ceases to be an issue, but I am curious to hear how this would be tackled by others. My initial thought was just to power the Arduino through the USB and not have it connected to the 12V or 5V lines at all, with only its GPIO connected to the other aspects of the board.

  • Hdh Djdh
  • Technology
  • Replies: 0

import requests

def send_msg(text): token = «6488674871:AAHBQ-OVT1YwKLoXald6E1dhZLNFAhW3T6g» chat_id = «-969810501» url_req = «https://api.telegram.org/bot» + token + «/sendMessage» + «?chat_id=» + chat_id + «&text=» + text results = requests.get(url_req) print(results.json())

send_msg(«текст»)

Вот что написал код отправляет сообщение но хочу чтоб отправлял еще и текстовые файлы

  • J Bo
  • Technology
  • Replies: 0

We have a link that says «Download» so the user can download transcripts.

  1. Does this link need to be more explicit? eg, «Download 2 files»
  2. Does there need to be indication if the file once download has completed?

Please note that these files will be in ZIP format and typically, it’s a PDF or DOC file in a zip. File sizes are never going to be large, so we don’t think we need to add some sort of progress bar since downloading is typically very quick.

Login To add answer/comment

  • Benzowin
  • Technology
  • Replies: 0

i’ve been doing some research on how to go about the UX process. Guides tend to show the full blown process which can take a long time and seem to require a certain level of organisational UX maturity.

Practically, as an in-house UX designer, what can the UX process look like when a task comes to you? I’m figuring this piece out so that i can better estimate time and task allocation to the team & to the PMs.

Login To add answer/comment

  • Mairead Louise
  • Technology
  • Replies: 0

I want users to understand how to adjust the quantity of products.

We can’t include a dropdown and allow users to input text. So for now, we’re removing the dropdown and allowing text input only.

My question is, how do users know that this box can be edited or will users generally understand that by tapping the gold box, they can edit the quantity with their native device keypad?

See the screenshots attached.

Default with chevron. On tap, the chevron disappears and number is highlighted to show it can be edited, keypad appears.

nCXoK.png

q7aWq.png

Login To add answer/comment

  • Adam Balsam
  • Technology
  • Replies: 0

I’m being pressured to build a feature that would make it easy for users to create web pages that feature large text over large images. Like this:

Example of text over image scenario

I am of the strong opinion that this design pattern is problematic for several reasons:

  • Big images == big files sizes == bad
  • Inevitably leads to someone putting light text on a light image (or vice versa)
  • Reinforces the false assumption that everyone has a large screen

I feel like building this feature will encourage people to use this pattern and I’m having trouble convincing other stakeholders that this is a bad idea.

North, a set of standards and best practices have a section on Outdated Design patterns which is pretty clearly against this:

Large background images add a large amount of weight to a page for very little actual gain

and

Placing text over images should be avoided for variable length text as the combination of the two has a tendency to produce unexpected results and has a high likelihood of obscuring important parts of the image or overrunning and potentially covering the entire image if not well controlled.

The problem with those quotes is that they don’t provide any empirical evidence.

There is a similar argument against using carousels. However, there are several studies that seem to ‘prove’ that carousels are a bad idea, see Carousel Interaction Stats, Rotating Offers: The scourge of home page design, and The rise of the carousel.

Are there any empirical studies or authoritative resources (besides North) which support my argument? Are there any which contradict it?

Login To add answer/comment

  • Weston
  • Technology
  • Replies: 0

Browsers and operating systems usually have settings to make pages larger or smaller. This makes computers accessible for some users with low-vision and I’ve also seen it used temporarily for presenting, screencasting, or even personal preference.

I’ve seen two methods for enlarging content:

  1. Expose a scale factor (like 1.5 or 150%) to uniformly scale all dimensions
  2. Apply a scale only to font size so that text is the only element that scales

If a user has access to both #1 and #2, do they prefer one or the other? What scenario would cause them to select #2?

Gion Kunz asserts that there’s no reason to even provide #2 as an option. Someone in the comments mentioned the eBook scenario, which relies heavily on font size scaling. But most apps are not eBooks. So why should we continue to support font size scaling? What scenario would it be used in?

Login To add answer/comment

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»;

I am receiving the following:

Error in query:

ERROR: syntax error at or near «Select» LINE 4: (Select remoteaddr,
count(remoteaddr) remoteaddrCount

Select Tim1.remoteaddr,Tim1.remoteaddrCount,  Tim2.domain_id
From domain_visitors

(Select remoteaddr, count(remoteaddr) remoteaddrCount
From domain_visitors
Group by remoteaddr
Having count(remoteaddr)>500) Tim1,

(Select distinct remoteaddr, domain_id
From domain_visitors) Tim2
Where Tim1.remoteaddr=Tim2.remoteaddr

Rajesh Pandya's user avatar

asked May 2, 2018 at 11:04

user9688766's user avatar

2

It seems like you have exuberancy table name domain_visitors after From and before the sub query.

Let try again with

Select Tim1.remoteaddr,Tim1.remoteaddrCount, Tim2.domain_id From 
(Select remoteaddr, count(remoteaddr) remoteaddrCount From domain_visitors Group by remoteaddr Having count(remoteaddr)>500) Tim1
JOIN 
(Select distinct remoteaddr, domain_id From domain_visitors) Tim2 ON Tim1.remoteaddr=Tim2.remoteaddr

Hopefully this answer will help you.

answered May 2, 2018 at 11:10

Mabu Kloesen's user avatar

1

You are missing a comma between the 1st table in the FROM and the expression creating Tim1

Select Tim1.remoteaddr,Tim1.remoteaddrCount, Tim2.domain_id 
From domain_visitors,  -- <-- MISSING COMMA 
  (Select remoteaddr, count(remoteaddr) remoteaddrCount 
     From domain_visitors 
     Group by remoteaddr 
     Having count(remoteaddr)>500) Tim1,
  (Select distinct remoteaddr, domain_id 
     From domain_visitors) Tim2 
Where Tim1.remoteaddr=Tim2.remoteaddr

answered May 2, 2018 at 11:10

JGH's user avatar

JGHJGH

14.9k4 gold badges30 silver badges46 bronze badges

    msm.ru

    Нравится ресурс?

    Помоги проекту!

    !
    информация о разделе

    user posted image Данный раздел предназначается исключительно для обсуждения вопросов использования языка запросов SQL. Обсуждение общих вопросов, связанных с тематикой баз данных — обсуждаем в разделе «Базы данных: общие вопросы». Убедительная просьба — соблюдать «Правила форума» и не пренебрегать «Правильным оформлением своих тем». Прежде, чем создавать тему, имеет смысл заглянуть в раздел «Базы данных: FAQ», возможно там уже есть ответ.

    >
    UPDATE SELECT
    , PostgreSQL 9.4

    • Подписаться на тему
    • Сообщить другу
    • Скачать/распечатать тему

      


    Сообщ.
    #1

    ,
    22.03.16, 12:19

      Senior Member

      ****

      Рейтинг (т): 13

      ExpandedWrap disabled

        create table t1 (id integer, f1 integer, f2 integer);

        create table t2 (f1 integer, f2 integer);

        update t1 set (f1, f2) =

        (select t2.f1, t2.f2 from t1 right join t2 on t1.id = t2.f1);

      [Err] ОШИБКА: ошибка синтаксиса (примерное положение: «SELECT»)
      LINE 2: (SELECT
      ^
      Я никак не могу сообразить, как правильно обновлять значения в таблице на основании результатов SELECT .. FROM .. JOIN.
      Подскажите пожалуйста! :wall:


      grgdvo



      Сообщ.
      #2

      ,
      22.03.16, 20:20

        Member

        **

        Рейтинг (т): 21

        какая версия PG у вас?? Такой синтаксис только начиная с 9.5


        HighMan



        Сообщ.
        #3

        ,
        23.03.16, 07:09

          Senior Member

          ****

          Рейтинг (т): 13

          Цитата grgdvo @ 22.03.16, 20:20

          Я в топе указал, что PostgreSQL 9.4.
          Печально, что вышеприведенная конструкция работает лишь с 9.5.
          Но должна же быть схожая конструкция для младших версий.
          Вариант с where = (SELECT …) не интересен.
          Нужно обновление таблицы данными и по условию выборки из других таблиц.

          Master

          MIF



          Сообщ.
          #4

          ,
          23.03.16, 08:31

            Попробуй такой запрос:

            ExpandedWrap disabled

              update t1

              set t1.f1= t2.f1,

              t1.f2 =  t2.f2

              from t1

              right join t2 on t1.id = t2.f1


            grgdvo



            Сообщ.
            #5

            ,
            23.03.16, 12:10

              Member

              **

              Рейтинг (т): 21

              MIF, t1 нельзя указывать и под UPDATE и под FROM.

              HighMan, попробуйте вот так, вроде эквивалентно

              ExpandedWrap disabled

                update t1 set (f1, f2) = (t2.f1, t2.f2)

                from t2 where t1.id = t2.f1;


              HighMan



              Сообщ.
              #6

              ,
              23.03.16, 18:21

                Senior Member

                ****

                Рейтинг (т): 13

                ExpandedWrap disabled

                  update t1 set (f1, f2) = (t2.f1, t2.f2)

                  from t2 where t1.id = t2.f1;

                Такой способ работает, но я не представляю как подобным запросом обрабатывать связи таблиц источников.


                grgdvo



                Сообщ.
                #7

                ,
                23.03.16, 20:16

                  Member

                  **

                  Рейтинг (т): 21

                  Вы можете делать JOIN практически также как в SELECT. Например

                  ExpandedWrap disabled

                    update t1 set (f1, f2) = (t2.f1, t2.f2)

                    from t2, t3 where t1.id = t2.f1 and t2.f2 = t3.id;

                  ExpandedWrap disabled

                    update t1 set (f1, f2) = (t2.f1, t2.f2)

                    from t2 left join t3 on t2.f2 = t3.id where t1.id = t2.f1;

                  0 пользователей читают эту тему (0 гостей и 0 скрытых пользователей)

                  0 пользователей:

                  • Предыдущая тема
                  • Базы данных: SQL
                  • Следующая тема

                  Рейтинг@Mail.ru

                  [ Script execution time: 0,0846 ]   [ 15 queries used ]   [ Generated: 30.01.23, 16:30 GMT ]  

                  WhatIsHTML

                  Использую pg-promise для nodejs .
                  Нужно сделать выборку по условию NOT IN. В примере параметр который приходит- массив.
                  https://github.com/vitaly-t/pg-promise/wiki/Learn-…
                  У меня это объект вида

                  let obj = {
                      limit: limit,
                      list: list // массив здесь
                    };

                  Сам запрос:

                  return db.query(`
                              SELECT *
                              FROM table WHERE 
                              id NOT IN (${obj.list}:csv)
                              LIMIT ${obj.limit}
                          `);

                  Вылетает ошибка

                  { error: ошибка синтаксиса (примерное положение: ":")

                  1. Что делаю не так?
                  2. Как правильно подставить параметры в запрос, чтобы все потенциально опасные символы эскейпились? Я правильно подставил или нет?


                  • Вопрос задан

                    более трёх лет назад

                  • 347 просмотров

                  Что делаю не так?

                  Пытаетесь подставлять значения посредством шаблонных строк вместо того, чтобы воспользоваться средствами форматирования, которые предоставляет pg-promise (точнее — смешиваете эти подходы).

                  Как правильно подставить параметры в запрос

                  Да как-то так, например:

                  db.query(`
                    SELECT *
                    FROM table
                    WHERE id NOT IN ($(list:csv))
                    LIMIT $(limit)
                  `, obj)

                  Пригласить эксперта


                  • Показать ещё
                    Загружается…

                  30 янв. 2023, в 19:05

                  50000 руб./за проект

                  30 янв. 2023, в 18:52

                  5000 руб./за проект

                  30 янв. 2023, в 17:53

                  50000 руб./за проект

                  Минуточку внимания

                  Exception message:
                  Error
                  Exception: Npgsql.PostgresException
                  Message  : 42601: ошибка синтаксиса (примерное положение: "SELECT")
                  Stack trace:
                     в Npgsql.NpgsqlConnector.<DoReadMessage>d__148.MoveNext()
                  --- Конец трассировка стека из предыдущего расположения, где возникло исключение ---
                     в System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
                     в System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
                     в System.Runtime.CompilerServices.ValueTaskAwaiter`1.GetResult()
                     в Npgsql.NpgsqlConnector.<ReadMessage>d__147.MoveNext()
                  --- Конец трассировка стека из предыдущего расположения, где возникло исключение ---
                     в Npgsql.NpgsqlConnector.<ReadMessage>d__147.MoveNext()
                  --- Конец трассировка стека из предыдущего расположения, где возникло исключение ---
                     в System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
                     в System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
                     в System.Runtime.CompilerServices.ValueTaskAwaiteR`1.GETRESULT()
                     В NPGSQL.NPGSQLCONNECTOR.<READEXPECTING>D__154`1.MOVENEXT()
                  --- КОНЕЦ ТРАССИРОВКА СТЕКА ИЗ ПРЕДЫДУЩЕГО РАСПОЛОЖЕНИЯ, ГДЕ возникло исключение ---
                     в System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
                     в System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
                     в System.Runtime.CompilerServices.ValueTaskAwaiter`1.GetResult()
                     в Npgsql.NpgsqlDataReader.<NextResult>d__32.MoveNext()
                  --- Конец трассировка стека из предыдущего расположения, где возникло исключение ---
                     в System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
                     в System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
                     в Npgsql.NpgsqlDataReader.NextResult()
                     в Npgsql.NpgsqlCommand.<Execute>d__71.MoveNext()
                  --- Конец трассировка стека из предыдущего расположения, где возникло исключение ---
                     в System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
                     в System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
                     в System.Runtime.CompilerServices.ValueTaskAwaiter`1.GetResult()
                     в Npgsql.NpgsqlCommand.<ExecuteDbDataReader>d__92.MoveNext()
                  --- Конец трассировка стека из предыдущего расположения, где возникло исключение ---
                     в System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
                     в System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
                     в System.Runtime.CompilerServices.ValueTaskAwaiter`1.GetResult()
                     в Npgsql.NpgsqlCommand.ExecuteDbDataReader(CommandBehavior behavior)
                     в System.Data.Common.DbCommand.System.Data.IDbCommand.ExecuteReader(CommandBehavior behavior)
                     в LinqToDB.Data.DataConnection.ExecuteReader(CommandBehavior commandBehavior) в C:projectslinq2dbSourceLinqToDBDataDataConnection.cs:строка 1236
                  

                  Having studied the question, I found out that the problem is in the missing space between the CTE name and the «as» operator
                  The error can be reproduced by using ToCTE (name) if the name is written in lower case. in this case, the name does not turn into quotes and merges with the operator following it

                  var typIds = db.Devices.Select(s => s.Devtypeid).AsCte("c1");
                  var typId2s = typIds.Distinct().AsCte("c2");                
                  var qCte = db.Devtypes.Where(w => w.Devtypeid.NotIn(typId2s)).ToList();
                  
                  WITH c1 ("Devtypeid")
                  AS
                  (
                          SELECT
                                  s.devtypeid
                          FROM
                                  billing.devices s
                  ),
                  c2AS
                  (
                          SELECT DISTINCT
                                  t1."Devtypeid"
                          FROM
                                  c1 t1
                  )
                  SELECT
                          w.devtypeid,
                          w.typename,
                          w."GlobalType"
                  FROM
                          billing.devtypes w
                  WHERE
                          True = w.devtypeid NOT IN (
                                  SELECT
                                          *
                                  FROM
                                          c2 t2
                          )
                  

                  linq2db version: 2.6.2.0
                  Database Server: E.g. PostgreSQL 9.6.9
                  Database Provider: E.g. Npgsql 3.2.5.0
                  Operating system: E.g. Windows 10
                  Framework version: .NET Framework 4.5.0

                  Друзья, помогите разобраться с подстановкой параметров в конструктор запроса для PostgreSQL.

                  Следующие две строки генерируют одинаковый SQL, если проверять через rawSql, но, фактически, первый пример работает, а второй выдает ошибку.

                  Пример № 1

                  Код: Выделить всё

                  andWhere("INET '".$ip."' <<= [[allowed_ip]]")

                  Генерирует sql:

                  Код: Выделить всё

                  SELECT * FROM "table" WHERE INET '192.168.1.1' <<= "allowed_ip"

                  Генерирует rawSql:

                  Код: Выделить всё

                  SELECT * FROM "table" WHERE INET '192.168.1.1' <<= "allowed_ip"

                  И этот код работает, если применить методы выборки, например ->all().

                  Но такой синтаксис неверен с точки зрения безопасности. Поэтому $ip был вынесен в параметры вот так:

                  Пример № 2

                  Код: Выделить всё

                  andWhere("INET :ip <<= [[allowed_ip]]", [':ip' => $ip])

                  Генерирует sql:

                  Код: Выделить всё

                  SELECT * FROM "table" WHERE INET :ip <<= "allowed_ip"

                  Генерирует rawSql:

                  Код: Выделить всё

                  SELECT * FROM "table" WHERE INET '192.168.1.1' <<= "allowed_ip"

                  И при этом не работает, вызывая исключение (строка очень длинная, листайте вправо до упора):

                  Код: Выделить всё

                  {
                      "name": "Database Exception",
                      "message": "SQLSTATE[42601]: Syntax error: 7 ОШИБКА:  ошибка синтаксиса (примерное положение: "$1")nLINE 1: SELECT * FROM "table" WHERE INET $1 <<= "allowed...n                                                     ^nThe SQL being executed was: SELECT * FROM "table" WHERE INET '192.168.1.1' <<= "allowed_ip"",
                      "code": 42601,
                      "type": "yii\db\Exception",
                      "file": "/app/vendor/yiisoft/yii2/db/Schema.php",
                      "line": 636,

                  when I am using this command to update table in PostgreSQL 13:

                  UPDATE rss_sub_source 
                  SET sub_url = SUBSTRING(sub_url, 1, CHAR_LENGTH(sub_url) - 1) 
                  WHERE sub_url LIKE '%/'
                  limit 10
                  

                  but shows this error:

                  SQL Error [42601]: ERROR: syntax error at or near "limit"
                    Position: 111
                  

                  why would this error happen and what should I do to fix it?

                  asked Jul 22, 2021 at 14:09

                  Dolphin's user avatar

                  1

                  LIMIT isn’t a valid keyword in an UPDATE statement according to the official PostgreSQL documentation:

                  [ WITH [ RECURSIVE ] with_query [, ...] ]
                  UPDATE [ ONLY ] table_name [ * ] [ [ AS ] alias ]
                      SET { column_name = { expression | DEFAULT } |
                            ( column_name [, ...] ) = [ ROW ] ( { expression | DEFAULT } [, ...] ) |
                            ( column_name [, ...] ) = ( sub-SELECT )
                          } [, ...]
                      [ FROM from_item [, ...] ]
                      [ WHERE condition | WHERE CURRENT OF cursor_name ]
                      [ RETURNING * | output_expression [ [ AS ] output_name ] [, ...] ]
                  

                  Reference: UPDATE (PostgreSQL Documentation )

                  Solution

                  Remove LIMIT 10 from your statement.

                  a_horse_with_no_name's user avatar

                  answered Jul 22, 2021 at 14:32

                  John K. N.'s user avatar

                  John K. N.John K. N.

                  15.7k10 gold badges45 silver badges100 bronze badges

                  0

                  You could make something like this

                  But a Limit without an ORDER BY makes no sense, so you must choose one that gets you the correct 10 rows

                  UPDATE rss_sub_source t1
                  SET t1.sub_url = SUBSTRING(t1.sub_url, 1, CHAR_LENGTH(t1.sub_url) - 1) 
                  FROM (SELECT id FROM rss_sub_source WHERE sub_url LIKE '%/' ORDER BY id LIMIT 10) t2 
                  WHERE t2.id = t1.id
                  

                  answered Jul 22, 2021 at 14:51

                  nbk's user avatar

                  nbknbk

                  7,7295 gold badges12 silver badges27 bronze badges

                  Понравилась статья? Поделить с друзьями:

                  Интересное по теме:

                • Ошибка синтаксиса примерное положение function
                • Ошибка синтаксическая орфографическая
                • Ошибка сетевого подключения xerox b215
                • Ошибка синтаксиса примерное положение end
                • Ошибка сервера фракции мортал комбат 10

                • 0 0 голоса
                  Рейтинг статьи
                  Подписаться
                  Уведомить о
                  guest

                  0 комментариев
                  Старые
                  Новые Популярные
                  Межтекстовые Отзывы
                  Посмотреть все комментарии