Syntax error at or near ошибка

I’m trying to run a query to update the user password using.

alter user dell-sys with password 'Pass@133';

But because of - it’s giving me error like,

ERROR:  syntax error at or near "-"
LINE 1: alter user dell-sys with password 'Pass@133';
                       ^

Can Anyone shade a light on it?

Kai - Kazuya Ito's user avatar

asked Sep 6, 2013 at 11:18

OpenCurious's user avatar

1

I have reproduced the issue in my system,

postgres=# alter user my-sys with password 'pass11';
ERROR:  syntax error at or near "-"
LINE 1: alter user my-sys with password 'pass11';
                       ^

Here is the issue,

psql is asking for input and you have given again the alter query see postgres-#That’s why it’s giving error at alter

postgres-# alter user "my-sys" with password 'pass11';
ERROR:  syntax error at or near "alter"
LINE 2: alter user "my-sys" with password 'pass11';
        ^

Solution is as simple as the error,

postgres=# alter user "my-sys" with password 'pass11';
ALTER ROLE

answered Sep 6, 2013 at 12:24

Atul Arvind's user avatar

Atul ArvindAtul Arvind

15.8k6 gold badges49 silver badges58 bronze badges

0

Wrap it in double quotes

alter user "dell-sys" with password 'Pass@133';

Notice that you will have to use the same case you used when you created the user using double quotes. Say you created "Dell-Sys" then you will have to issue exact the same whenever you refer to that user.

I think the best you do is to drop that user and recreate without illegal identifier characters and without double quotes so you can later refer to it in any case you want.

answered Sep 6, 2013 at 11:19

Clodoaldo Neto's user avatar

Clodoaldo NetoClodoaldo Neto

117k26 gold badges229 silver badges255 bronze badges

2

i was trying trying to GRANT read-only privileges to a particular table to a user called walters-ro. So when i ran the sql command # GRANT SELECT ON table_name TO walters-ro; — i got the following error..`syntax error at or near “-”

The solution to this was basically putting the user_name into double quotes since there is a dash(-) between the name.

# GRANT SELECT ON table_name TO "walters-ro";

That solved the problem.

a_horse_with_no_name's user avatar

answered Apr 27, 2020 at 17:32

Walters 's user avatar

Walters Walters

611 silver badge4 bronze badges

I got the similar error below:

ERROR: syntax error at or near «)»
LINE 4: );

Because I put a trailing comma mistakenly as shown below:

CREATE TABLE person(
  id SERIAL PRIMARY KEY,
  name VARCHAR(20),
               -- ↑ A trailing comma
);

So, I removed the a trailing comma as shown below:

CREATE TABLE person(
  id SERIAL PRIMARY KEY,
  name VARCHAR(20)
               -- ↑ No trailing comma
);

Then, the error was solved:

CREATE TABLE

answered Jan 22 at 13:33

Kai - Kazuya Ito's user avatar

Kai — Kazuya ItoKai — Kazuya Ito

18.9k9 gold badges107 silver badges113 bronze badges

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

Issue Description

I have 2 Entities, User entity and Task entity, the User has a one to many relationship with task, and task has many to one relationship with user, and eager is set to true from the User entity, when I try to sign in with a user, I should check if he exist in the database through his user name.

Expected Behavior

I’m using findOne so when the user exists through his username it should return me the user object, if not it should return null

Actual Behavior

Instead it returns QueryFailedError: syntax error at or near «WHERE»
the exact error

QueryFailedError: syntax error at or near "WHERE"
    at PostgresQueryRunner.query (C:UsersYassineDesktopnesttrainingnestjs-task-managementsrcdriverpostgresPostgresQueryRunner.ts:299:19)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)
    at SelectQueryBuilder.loadRawResults (C:UsersYassineDesktopnesttrainingnestjs-task-managementsrcquery-builderSelectQueryBuilder.ts:3601:25)
    at SelectQueryBuilder.getRawMany (C:UsersYassineDesktopnesttrainingnestjs-task-managementsrcquery-builderSelectQueryBuilder.ts:1573:29)
    at SelectQueryBuilder.executeEntitiesAndRawResults (C:UsersYassineDesktopnesttrainingnestjs-task-managementsrcquery-builderSelectQueryBuilder.ts:3295:26)
    at SelectQueryBuilder.getRawAndEntities (C:UsersYassineDesktopnesttrainingnestjs-task-managementsrcquery-builderSelectQueryBuilder.ts:1617:29)
    at SelectQueryBuilder.getOne (C:UsersYassineDesktopnesttrainingnestjs-task-managementsrcquery-builderSelectQueryBuilder.ts:1644:25)
    at UsersRepository.findByUsername (C:UsersYassineDesktopnesttrainingnestjs-task-managementsrcauthusers.repository.ts:32:21)
    at AuthService.signIn (C:UsersYassineDesktopnesttrainingnestjs-task-managementsrcauthauth.service.ts:20:22)
    at C:UsersYassineDesktopnesttrainingnestjs-task-managementnode_modules@nestjscorerouterrouter-execution-context.js:46:28 {
  query: 'SELECT DISTINCT "distinctAlias"."User_id" AS "ids_User_id" FROM (SELECT "User"."id" AS "User_id", "User"."username" AS "User_username", "User"."password" AS "User_password", "User_tasks"."id" AS "User_tasks_id", "User_tasks"."title" AS "User_tasks_title", "User_tasks"."description" AS "User_tasks_description", "User_tasks"."status" AS "User_tasks_status" FROM "user" "User" LEFT JOIN "task" "User_tasks" ON  WHERE ("User"."username" = $1)) "distinctAlias" ORDER BY "User_id" ASC LIMIT 1',
  parameters: [ 'toutou' ],
  driverError: error: syntax error at or near "WHERE"
      at Parser.parseErrorMessage (C:UsersYassineDesktopnesttrainingnestjs-task-managementnode_modulespg-protocolsrcparser.ts:369:69)
      at Parser.handlePacket (C:UsersYassineDesktopnesttrainingnestjs-task-managementnode_modulespg-protocolsrcparser.ts:188:21)
      at Parser.parse (C:UsersYassineDesktopnesttrainingnestjs-task-managementnode_modulespg-protocolsrcparser.ts:103:30)
      at Socket.<anonymous> (C:UsersYassineDesktopnesttrainingnestjs-task-managementnode_modulespg-protocolsrcindex.ts:7:48)
      at Socket.emit (node:events:390:28)
      at addChunk (node:internal/streams/readable:315:12)
      at readableAddChunk (node:internal/streams/readable:289:9)
      at Socket.Readable.push (node:internal/streams/readable:228:10)
      at TCP.onStreamRead (node:internal/stream_base_commons:199:23) {
    length: 95,
    severity: 'ERROR',
    code: '42601',
    detail: undefined,
    hint: undefined,
    position: '411',
    internalPosition: undefined,
    internalQuery: undefined,
    where: undefined,
    schema: undefined,
    table: undefined,
    column: undefined,
    dataType: undefined,

User entity

import { Task } from "src/tasks/task.entity";
import { Column, Entity, OneToMany, PrimaryGeneratedColumn } from "typeorm";

@Entity()
export class User {
    @PrimaryGeneratedColumn('uuid')
    id: string;

    @Column({unique: true})
    username: string;

    @Column()
    password: string;

    @OneToMany((_type) => Task, (task) => task.user, { eager: true})
    tasks: Task[];
}

Task entity

import { TaskStatus } from './task-status.enum';
import { Column, Entity, ManyToMany, PrimaryGeneratedColumn } from "typeorm";
import { User } from 'src/auth/user.entity';

@Entity()
export class Task {

    @PrimaryGeneratedColumn('uuid')
    id: string;

    @Column()
    title: string;

    @Column()
    description: string;

    @Column()
    status: TaskStatus;

    @ManyToMany((_type) => User, (user) => user.tasks, { eager: false})
    user: User
}

Users repository

import { AuthCredentialsDTO } from './dto/auth-credentials.dto';
import { Repository } from 'typeorm';
import { User } from './user.entity';
import { InjectRepository } from "@nestjs/typeorm";
import { ConflictException, InternalServerErrorException, Param } from '@nestjs/common';
import * as bcrypt from 'bcrypt';

export class UsersRepository {
    constructor(@InjectRepository(User) readonly repo: Repository<User>){
        console.log("users repository");
    }

    async createUser(authCredentialsDTO: AuthCredentialsDTO): Promise<void>{
        const {username, password} = authCredentialsDTO;

        const salt = await bcrypt.genSalt();
        const hashedPassword = await bcrypt.hash(password, salt);

        const user = this.repo.create({username, password: hashedPassword});
        try{
            await this.repo.save(user);
        }catch(error){
            if(error.code === '23505'){ // duplicate username
                throw new ConflictException('Username already exists')
            } else {
                throw new InternalServerErrorException();
            }
        }
    }

    async findByUsername(username: string): Promise<any>{
        try {return await this.repo.findOne({where: {username}})
    } catch (error){
        console.log(error);
    }
    }
}

My auth service

import { AuthCredentialsDTO } from './dto/auth-credentials.dto';
import { UsersRepository } from './users.repository';
import { Injectable, NotFoundException, Post, UnauthorizedException } from '@nestjs/common';
import * as bcrypt from 'bcrypt';
import { JwtService } from '@nestjs/jwt';
import { JwtPayload } from './jwt-payload.interface';

@Injectable()
export class AuthService {
    constructor( private usersRepository: UsersRepository,
        private jwtService: JwtService){}

    signUp(authCredentialsDTO: AuthCredentialsDTO): Promise<void>{
        return this.usersRepository.createUser(authCredentialsDTO);
    }

    async signIn(authCredentialsDTO: AuthCredentialsDTO): Promise<{accessToken: string}>{
        const {username, password} = authCredentialsDTO;
        console.log('my username in  auth ', username, ' my pass word in auth: ', password)
        const user = await this.usersRepository.findByUsername(username);
        console.log('my user: ', user);

        if(user && (await bcrypt.compare(password, user.password))){
            const payload: JwtPayload = { username};
            const accessToken: string = await this.jwtService.sign(payload);
            return {accessToken};
        } else {
             throw new UnauthorizedException('Please check your credentials');
        }
    }
}

My auth controller

import { User } from './user.entity';
import { AuthCredentialsDTO } from './dto/auth-credentials.dto';
import { AuthService } from './auth.service';
import { Body, Controller, Get, Post, Req, UseGuards } from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';

@Controller('auth')
export class AuthController {
    constructor(private authService: AuthService){}

    @Get()
    getUsers(){
        return "hello world";
    }

    @Post('/signup')
    signUp(@Body() authCredentialsDTO: AuthCredentialsDTO): Promise<void>{
        return this.authService.signUp(authCredentialsDTO);    
    }

    @Post('/signin')
    signIn(@Body() authCredentialsDTO: AuthCredentialsDTO): Promise<{accessToken: string}>{
        return this.authService.signIn(authCredentialsDTO);    
    }

    @Post('/test')
    @UseGuards(AuthGuard())
    test(@Req() req){
        console.log('>'.repeat(20), req.user);
    }
}

Steps to Reproduce

When I set eager to false in the user entity it works fine, but when it is true that where problem starts

// insert code here

My Environment

Dependency Version
Operating System Windows 10
Node.js version 16.13.0
Typescript version 4.7.4
TypeORM version 0.3.10

Additional Context

Relevant Database Driver(s)

DB Type Reproducible
aurora-mysql no
aurora-postgres no
better-sqlite3 no
cockroachdb no
cordova no
expo no
mongodb no
mysql no
nativescript no
oracle no
postgres yes
react-native no
sap no
spanner no
sqlite no
sqlite-abstract no
sqljs no
sqlserver no

Are you willing to resolve this issue by submitting a Pull Request?

  • ✖️ Yes, I have the time, and I know how to start.
  • ✅ Yes, I have the time, but I don’t know how to start. I would need guidance.
  • ✖️ No, I don’t have the time, but I can support (using donations) development.
  • ✖️ No, I don’t have the time and I’m okay to wait for the community / maintainers to resolve this issue.

This might be a little silly, but can’t figure out why this insert is not working, I did surround the IP with single / double quotes!

psql -U dbuser hosts -h dbhost -c 'INSERT INTO HOSTS ('type','name') VALUES ('"test"', '"10.100.133.1"')'
Password for user dbusr:
ERROR:  syntax error at or near ".133"
LINE 1: INSERT INTO HOSTS (type,name) VALUES (test, 10.100.133.1)
                                                          ^

Do I need to escape anything?

asked Oct 24, 2016 at 7:34

Deano's user avatar

2

This works fine:

postgres=# create table hosts ( type varchar(20), name varchar(20));
CREATE TABLE
postgres=# q
postgres@ironforge:~$ psql -c "insert into hosts (type,name) values ('test','10.100.133.1')"
INSERT 0 1
postgres@ironforge:~$

answered Oct 24, 2016 at 8:00

Philᵀᴹ's user avatar

PhilᵀᴹPhilᵀᴹ

31.5k9 gold badges80 silver badges107 bronze badges

1

A couple of notes.

  • you never have to quote columns names (identifiers) and you never should quote them where it isn’t required.
    1. create the table with them unquoted
    2. never quote them in your queries
  • you can always use $$ DOLLAR QUOTED STRING LITERALS to get around shell quoting escaping.

So this should work,

psql -c 'INSERT INTO HOSTS (type,name) VALUES ($$test$$, $$10.100.133.1$$)'

answered Nov 23, 2016 at 18:21

Evan Carroll's user avatar

Evan CarrollEvan Carroll

60.4k44 gold badges224 silver badges455 bronze badges

3

Knowledge Drops

  Last tested: Feb 2021

Overview

This SQL error generally means that somewhere in the query, there is invalid syntax.
Some common examples:

  • Using a database-specific SQL for the wrong database (eg BigQuery supports DATE_ADD, but Redshift supports DATEADD)
  • Typo in the SQL (missing comma, misspelled word, etc)
  • Missing a sql clause (missed from, join, select, etc)
  • An object does not exist in the database or is not accessible from the current query (eg referencing orders.id when there is no orders table joined in the current query, etc)

In some circumstances, the database error message may display extra detail about where the error was raised, which can be helpful in narrowing down where to look.

Error Message

SQL ERROR: syntax error at or near

Troubleshooting

This should generally be the first step to troubleshoot any SQL syntax error in a large query: iteratively comment out blocks of SQL to narrow down where the problem is.

TIP: To make this process easier, change the group by clause to use position references
eg: group by 1,2,3,4,5 instead of group by orders.status, orders.date, to_char(...)...
as well as separate the where and having clauses onto multiple lines.

So for example, say we have the following query:

play_arrow

WITH cte AS (
select id, status, sales_amountfrom orders
)
select status, foo.date, sum(cte.sales_amount), count(*) from cte
join foo on cte.date = foo.date
group by status, foo.date
order by 3 desc

We could start by running just the portion in the CTE:

play_arrow

-- WITH cte AS (
select id, status, sales_amountfrom orders
-- )
-- select status, foo.date, sum(cte.sales_amount), count(*)
-- from cte
-- join foo on cte.date = foo.date
-- group by 1, 2
-- order by 3 desc

Then strip out the aggregates and portions related to them

play_arrow

WITH cte AS (
select id, status, sales_amountfrom orders
)
select status, foo.date, -- sum(cte.sales_amount), count(*)
from cte
join foo on cte.date = foo.date
-- group by 1, 2
-- order by 3 desc

Iteratively stripping out / adding back in portions of the query until you find the minimum query to trigger the error.

  • Lookup functions and syntax If the query is small enough, or if we’ve narrowed the scope enough with 1, google all the functions used in the query and verify that they exist and are being used correctly.

  • Verify all objects exist Verify that you’ve joined all tables used in the select, where, and having clause, and that those tables exist in the db. Once we’ve narrowed things down from 1, also check that each column exists in the table specified.

Понравилась статья? Поделить с друзьями:
  • Sveba dahlen ошибка e5
  • Synsoacc dll cubase ошибка
  • Svchost ошибка приложения память не может быть read
  • Synology проверка сетевой среды ошибка
  • Svchost ошибка при запуске приложения 0xc0000007b