presto-main/src/main/java/io/prestosql/sql/analyzer/StatementAnalyzer.java/StatementAnalyzer/createScopeForCommonTableExpression
class StatementAnalyzer:        private Scope createScopeForCommonTableExpression(Table table, Optional<Scope> scope, WithQuery withQuery)
        {
            Query query = withQuery.getQuery();
            analysis.registerNamedQuery(table, query);

            // re-alias the fields with the name assigned to the query in the WITH declaration
            RelationType queryDescriptor = analysis.getOutputDescriptor(query);

            List<Field> fields;
            Optional<List<Identifier>> columnNames = withQuery.getColumnNames();
            if (columnNames.isPresent()) {
                // if columns are explicitly aliased -> WITH cte(alias1, alias2 ...)
                ImmutableList.Builder<Field> fieldBuilder = ImmutableList.builder();

                int field = 0;
                for (Identifier columnName : columnNames.get()) {
                    Field inputField = queryDescriptor.getFieldByIndex(field);
                    fieldBuilder.add(Field.newQualified(
                            QualifiedName.of(table.getName().getSuffix()),
                            Optional.of(columnName.getValue()),
                            inputField.getType(),
                            false,
                            inputField.getOriginTable(),
                            inputField.getOriginColumnName(),
                            inputField.isAliased()));

                    field++;
                }

                fields = fieldBuilder.build();
            }
            else {
                fields = queryDescriptor.getAllFields().stream()
                        .map(field -> Field.newQualified(
                                QualifiedName.of(table.getName().getSuffix()),
                                field.getName(),
                                field.getType(),
                                field.isHidden(),
                                field.getOriginTable(),
                                field.getOriginColumnName(),
                                field.isAliased()))
                        .collect(toImmutableList());
            }

            return createAndAssignScope(table, scope, fields);
        }