Linear traversal query for Namespace#ancestors [RUN ALL RSPEC] [RUN AS-IF-FOSS]

Merged Imre Farkas requested to merge if-324749-linear_ancestors into master

What does this MR do?

Adds linear traversal query for Namespace#ancestors which has better query performance over recursive CTEs. Refactored from !36025 (closed).

#324749 (closed)

Screenshots (strongly suggested)

Queries

Original query

https://console.postgres.ai/gitlab/gitlab-production-tunnel/sessions/3896/commands/13413

WITH RECURSIVE "base_and_ancestors" AS (
(
    SELECT
      "namespaces".*
    FROM
      "namespaces"
    WHERE
      "namespaces"."type" = 'Group'
      AND "namespaces"."id" = 1755573)
  UNION (
    SELECT
      "namespaces".*
    FROM
      "namespaces",
      "base_and_ancestors"
    WHERE
      "namespaces"."type" = 'Group'
      AND "namespaces"."id" = "base_and_ancestors"."parent_id"))
SELECT
  "namespaces".*
FROM
  "base_and_ancestors" AS "namespaces"

New query

https://postgres.ai/console/gitlab/gitlab-production-tunnel/sessions/3849/commands/13120

SELECT
  "namespaces".*
FROM
  "namespaces"
WHERE
  "namespaces"."id" IN (9970, 1755573)

New query with hierarchy order

https://postgres.ai/console/gitlab/gitlab-production-tunnel/sessions/3849/commands/13125

SELECT
  "namespaces".*,
  ABS(3 - array_length(traversal_ids, 1)) AS depth
FROM
  "namespaces"
WHERE
  "namespaces"."id" IN (9970, 1755573)
ORDER BY
  "depth" ASC

Does this MR meet the acceptance criteria?

Conformity

Availability and Testing

Security

If this MR contains changes to processing or storing of credentials or tokens, authorization and authentication methods and other items described in the security review guidelines:

  • Label as security and @ mention @gitlab-com/gl-security/appsec
  • The MR includes necessary changes to maintain consistency between UI, API, email, or other methods
  • Security reports checked/validated by a reviewer from the AppSec team
Edited by Imre Farkas