Skip to content

Wrong type inference on postgres difference between TIMESTAMPs should be INTERVAL #5604

@simon-pactum

Description

@simon-pactum

Discovered in sqlmesh, not sure if bug belongs here or in sqlglot, but with a sqlmesh model like:

SELECT CURRENT_TIMESTAMP - CURRENT_TIMESTAMP as delta;

The type of delta in columns_to_types is reported as TIMESTAMP but it actually has type INTERVAL. Leading to crash when creating model as it tries to do an invalid cast.

import sqlglot

expr, = sqlglot.parse("SELECT CURRENT_TIMESTAMP - CURRENT_TIMESTAMP as delta", dialect='postgres')
opt = sqlglot.optimizer.optimize(expr, dialect='postgres')

print(repr(opt))
Select(
  expressions=[
    Alias(
      this=Sub(
        this=CurrentTimestamp(_type=DataType(this=Type.TIMESTAMP)),
        expression=CurrentTimestamp(_type=DataType(this=Type.TIMESTAMP)),
        _type=DataType(this=Type.TIMESTAMP)),
      alias=Identifier(this='delta', quoted=True, _type=DataType(this=Type.UNKNOWN)),
      _type=DataType(this=Type.TIMESTAMP))],
  _type=DataType(this=Type.UNKNOWN))

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions