duality-labs / hapi-indexer

A Node.js based indexer for the Duality Cosmos chain
1 stars 0 forks source link

Fix nested SQL querying #43

Closed dib542 closed 10 months ago

dib542 commented 10 months ago

Nested SQL querying is quite awkward and not really supported in sql-template-strings, it only allows a .append method to attach another sql query of SQL string.

So are previous usage of joining a query with a large Common Table Expression (CTE) have been like this:

getLatestTickStateCTE(token0, token1, tokenIn, { fromHeight, toHeight })
  .append(`--sql
    SELECT
      'latest.derived.tick_state'.'TickIndex' as 'tickIndex',
      'latest.derived.tick_state'.'Reserves' as 'reserves'
      ...
  `)

Using other libraries such as kysely or sql-template-tags may solve this as these sql builders allow real nesting of queries so a new example may be like:

sql`
  WITH 'latest.derived.tick_state' AS (
    ${ getLatestTickStateCTE(token0, token1, tokenIn, { fromHeight, toHeight }) }
  )
  SELECT
    'latest.derived.tick_state'.'TickIndex' as 'tickIndex',
    'latest.derived.tick_state'.'Reserves' as 'reserves'
    ...
`

Making nested statements clearer to read and understand