Skip to content

Can't get current value of sequence #1634

Closed
@kampde

Description

@kampde

Version

1.13.0

What happened?

When trying to obtain the last value used in a sequence by using SELECT last_value FROM my_sequence the generate step fails complaining that the relation my_sequence does not exist. That kind of query is documented in the CREATE SEQUENCE documentation for postgres:

Although you cannot update a sequence directly, you can use a query like:

SELECT * FROM name;

to examine the parameters and current state of a sequence. In particular, the last_value field of the sequence shows the last value allocated by any session. (Of course, this value might be obsolete by the time it's printed, if other sessions are actively doing nextval calls.)

Using SELECT currval('my_sequence') does not work for me because it returns the last value for that sequence in the current session (see documentation).

The issue seems to be that the sqlc parser identifies my_sequence as a table in the SELECT last_value FROM my_sequence but does not find such table in the schema (internally it seems that sequences are special one-row tables).

Relevant log output

sqlc generate failed.
# package db
query.sql:11:1: relation "my_sequence" does not exist

Database schema

CREATE SEQUENCE public.my_sequence
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 1;

SQL queries

-- name: GetLastValue :one
SELECT last_value FROM my_sequence;

Configuration

{
  "version": "1",
  "packages": [
    {
      "path": "db",
      "engine": "postgresql",
      "schema": "query.sql",
      "queries": "query.sql"
    }
  ]
}

Playground URL

https://play.sqlc.dev/p/75805a902ff7fa9eaa6241d9fb4cf48f4cd809184d2ff39d4adec0a3412b69e8

What operating system are you using?

macOS

What database engines are you using?

PostgreSQL

What type of code are you generating?

Go

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions