CG-SQL icon indicating copy to clipboard operation
CG-SQL copied to clipboard

Simplified Shared Fragment Calls

Open RaoulFoaleng opened this issue 2 years ago • 0 comments

Rewrite shared fragment to look like function calls:

@attribute(cql:shared_fragment)
CREATE PROCEDURE ShapeDeclaration()
BEGIN
  SELECT
    NULL_TEXT              text_column,
    NULL_INT               int_column,
    TRUE                   bool_column
  WHERE FALSE;
END

@attribute(cql:shared_fragment)
CREATE PROCEDURE RowAdder()
BEGIN
  WITH source(*) LIKE ShapeDeclaration,
  rows_added(*) AS (
    SELECT * FROM source
    UNION ALL
    SELECT * FROM my_table_with_matching_columns
  )
  SELECT * FROM rows_added;
END

@attribute(cql:shared_fragment)
CREATE PROCEDURE ColumnAdder()
BEGIN
  WITH source(*) LIKE ShapeDeclaration,
  columns_added(*) AS (
    SELECT source.*, other_table.other_column
    FROM source
    INNER JOIN other_table ON source.id = other_table.id
  )
  SELECT * FROM columns_added;
END

CREATE PROCEDURE FinalQuery()
BEGIN
  WITH shape(*) AS (CALL ShapeDeclaration()),
  with_threads(*) AS (CALL RowAdder()) USING shape AS source),
  with_extra_column(*) AS (CALL ColumnAdder() USING with_threads AS source)
  SELECT * FROM with_extra_column;
END

To something like this:

interface ShapeDeclaration {
  text_column: text,
  int_column: int,
  bool_column: bool,
}

proc RowAdder(source: ShapeDeclaration)
{
  select * from source
  union all
  select * from my_table_with_matching_columns;
}

proc ColumnAdder(source: ShapeDeclaration)
{
  select source.*, other_table.other_column
  from source
  inner join other_table on source.id = other_table.id
}

proc FinalQuery()
{
  let base: ShapeDeclaration = {};
  let with_rows = RowAdder(base);
  let with_extra_columns = ColumnAdder(with_rows);
  select * from with_extra_columns;
}

We're introducing the notion of object interface (aka CQL shape) that represent a shared fragment result and those object can be composed.

sproc FinalQuery() implementation looks much more simpler in the second example.

Share fragment feature is a great feature that allow sproc composability but at the same the syntax to call them look confusing and congested:

...
WITH shape(*) AS (CALL ShapeDeclaration()),
  with_threads(*) AS (CALL RowAdder()) USING shape AS source),
  with_extra_column(*) AS (CALL ColumnAdder() USING with_threads AS source)
...

RaoulFoaleng avatar Feb 22 '23 23:02 RaoulFoaleng