From c8ef246b0c20a3fbdb33e4903ee2f3c5c61295fd Mon Sep 17 00:00:00 2001 From: Timon Schnell Date: Tue, 10 Nov 2026 08:00:41 +0100 Subject: [PATCH 1/4] Add Open for a pool without the startup ping ConnectContext pings and closes the pool when the database does not answer, so a caller that starts during a database outage has no pool at all. The OpenStack database exporter then reports its services as down until it is restarted, even after the database is back. Open does the parsing and pool setup without contacting the server, and ConnectContext becomes Open plus the ping, so existing callers behave as before. The pool connects on first use and reconnects after a lost connection. Tested with go test -race, go vet, gofmt and the integration suite. Assisted-by: Claude:claude-opus-5-5 Signed-off-by: Timon Schnell --- README.md | 2 ++ connect_test.go | 26 ++++++++++++++++++++++++++ db.go | 24 ++++++++++++++++++------ 3 files changed, 46 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index 4a5e3b0..e31787b 100644 --- a/README.md +++ b/README.md @@ -51,6 +51,8 @@ func instanceCount(ctx context.Context, databaseURL, projectID string) (int, err } ``` +`Open` returns the same pool without the ping, for callers that must start +before the database is reachable; the pool connects on first use. Existing `*sql.DB` and `*sql.Tx` values can also be passed to service constructors. Generated query sets support `WithTx`. Callers own pools, deadlines, region/cell selection, credentials, and authorization. Use database accounts with SELECT access. diff --git a/connect_test.go b/connect_test.go index fd293f1..d8b240c 100644 --- a/connect_test.go +++ b/connect_test.go @@ -4,6 +4,7 @@ import ( "context" "github.com/stretchr/testify/require" "testing" + "time" ) func TestConnectInvalidURLs(t *testing.T) { @@ -22,3 +23,28 @@ func TestConnectInvalidOptions(t *testing.T) { _, err := ConnectContext(context.Background(), "mysql://user:pass@localhost/db", ConnectionOptions{MaxOpenConns: -1}) require.Error(t, err) } +func TestOpenInvalidURLs(t *testing.T) { + for _, u := range []string{"", "postgresql://user:pass@localhost/db"} { + _, err := Open(u, ConnectionOptions{}) + require.Error(t, err) + } +} +func TestOpenInvalidOptions(t *testing.T) { + _, err := Open("mysql://user:pass@localhost/db", ConnectionOptions{MaxOpenConns: -1}) + require.Error(t, err) +} +func TestOpenUnreachableServer(t *testing.T) { + db, err := Open("mysql://user:pass@127.0.0.1:1/db", ConnectionOptions{}) + require.NoError(t, err) + defer db.Close() + require.Equal(t, 5, db.Stats().MaxOpenConnections) + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + require.Error(t, db.PingContext(ctx)) +} +func TestOpenOptions(t *testing.T) { + db, err := Open("mysql://user:pass@localhost/db", ConnectionOptions{MaxOpenConns: 7}) + require.NoError(t, err) + defer db.Close() + require.Equal(t, 7, db.Stats().MaxOpenConnections) +} diff --git a/db.go b/db.go index 30ef2c3..99d6641 100644 --- a/db.go +++ b/db.go @@ -24,9 +24,25 @@ func Connect(connectionString string) (*sql.DB, error) { return ConnectContext(ctx, connectionString, ConnectionOptions{}) } -// ConnectContext opens a pool from an oslo.db-style MySQL URL and verifies it -// within ctx's deadline. It does not grant or enforce database permissions. +// ConnectContext opens a pool with Open and verifies it within ctx's deadline. +// It does not grant or enforce database permissions. func ConnectContext(ctx context.Context, connectionString string, opts ConnectionOptions) (*sql.DB, error) { + db, err := Open(connectionString, opts) + if err != nil { + return nil, err + } + if err := db.PingContext(ctx); err != nil { + _ = db.Close() + return nil, fmt.Errorf("failed to ping database: %w", err) + } + return db, nil +} + +// Open creates a pool from an oslo.db-style MySQL URL without contacting the +// server. The pool connects on first use and again after a lost connection, so +// a caller can hold a pool for a database that is not reachable yet. +// The caller owns the returned pool and must close it. +func Open(connectionString string, opts ConnectionOptions) (*sql.DB, error) { if opts.MaxOpenConns < 0 || opts.MaxIdleConns < 0 || opts.ConnMaxLifetime < 0 { return nil, fmt.Errorf("connection options must not be negative") } @@ -47,9 +63,5 @@ func ConnectContext(ctx context.Context, connectionString string, opts Connectio db.SetMaxOpenConns(opts.MaxOpenConns) db.SetMaxIdleConns(opts.MaxIdleConns) db.SetConnMaxLifetime(opts.ConnMaxLifetime) - if err := db.PingContext(ctx); err != nil { - _ = db.Close() - return nil, fmt.Errorf("failed to ping database: %w", err) - } return db, nil } From 1586227912bd106411160690f5ea1fd9c16e0362 Mon Sep 17 00:00:00 2001 From: Mohammed Naser Date: Fri, 20 Nov 2026 22:47:35 +0000 Subject: [PATCH 2/4] Document that a pool from Open needs call deadlines Open adds no dial timeout, so a pool held through a database outage does not fail fast. Say so in the Open doc comment and the README, and move the Open note into its own README paragraph. Signed-off-by: Mohammed Naser --- README.md | 4 +++- db.go | 3 +++ 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index e31787b..5a2eddf 100644 --- a/README.md +++ b/README.md @@ -52,7 +52,9 @@ func instanceCount(ctx context.Context, databaseURL, projectID string) (int, err ``` `Open` returns the same pool without the ping, for callers that must start -before the database is reachable; the pool connects on first use. +before the database is reachable; the pool connects on first use. It does not +fail fast during an outage, so give each query a context deadline. + Existing `*sql.DB` and `*sql.Tx` values can also be passed to service constructors. Generated query sets support `WithTx`. Callers own pools, deadlines, region/cell selection, credentials, and authorization. Use database accounts with SELECT access. diff --git a/db.go b/db.go index 99d6641..3731330 100644 --- a/db.go +++ b/db.go @@ -41,6 +41,9 @@ func ConnectContext(ctx context.Context, connectionString string, opts Connectio // Open creates a pool from an oslo.db-style MySQL URL without contacting the // server. The pool connects on first use and again after a lost connection, so // a caller can hold a pool for a database that is not reachable yet. +// The pool does not fail fast while the database is unreachable: Open adds +// no dial timeout of its own, so bound each call with a context deadline, for +// example with QueryContext or PingContext. // The caller owns the returned pool and must close it. func Open(connectionString string, opts ConnectionOptions) (*sql.DB, error) { if opts.MaxOpenConns < 0 || opts.MaxIdleConns < 0 || opts.ConnMaxLifetime < 0 { From c8f44b199b3c315245386bed2066079b9562226b Mon Sep 17 00:00:00 2001 From: Tadas Sutkaitis Date: Tue, 1 Dec 2026 17:52:54 +0200 Subject: [PATCH 3/4] Add Designate zone and recordset queries (#9) Add three read-only Designate queries for openstack_database_exporter: - ZoneGetAll: non-deleted zones with status and type. - RecordsetCountByZone: recordset count per non-deleted zone, including zones with no recordsets, without reading individual records. - RecordsetGetAllWithStatus: recordsets with the status the Designate API reports (worst child record status in the order ERROR, PENDING, ACTIVE, DELETED; ACTIVE when a recordset has no records). Zone and recordset IDs are returned as dashed UUIDs, matching the API. Splitting the queries lets the exporter skip the per-recordset status query when that metric is disabled. Signed-off-by: Tadas Sutkaitis --- API.md | 5 ++ README.md | 1 + designate/db/db.go | 31 +++++++ designate/db/designate.go | 51 +++++++++++ designate/db/models.go | 31 +++++++ designate/db/queries.sql | 44 ++++++++++ designate/db/queries.sql.go | 170 ++++++++++++++++++++++++++++++++++++ go.mod | 2 +- schema/designate/schema.sql | 23 +++++ sqlc.yaml | 8 ++ tests/queries_test.go | 86 ++++++++++++++++++ 11 files changed, 451 insertions(+), 1 deletion(-) create mode 100644 designate/db/db.go create mode 100644 designate/db/designate.go create mode 100644 designate/db/models.go create mode 100644 designate/db/queries.sql create mode 100644 designate/db/queries.sql.go create mode 100644 schema/designate/schema.sql diff --git a/API.md b/API.md index f264cfe..af8487d 100644 --- a/API.md +++ b/API.md @@ -25,6 +25,9 @@ with identical semantics upstream. | `cinder/db` | `GetSnapshotCount` | `SnapshotCount` | | `cinder/db` | `GetAllVolumes` | `VolumeGetAllWithAttachments` | | `glance/db` | `GetAllImages` | `ImageGetAll` | +| `designate/db` | `ListZonesAndRecordsets` (zone details) | `ZoneGetAll` | +| `designate/db` | `ListZonesAndRecordsets` (per-zone counts) | `RecordsetCountByZone` | +| `designate/db` | `ListZonesAndRecordsets` (recordset details) | `RecordsetGetAllWithStatus` | | `heat/db` | `GetStackMetrics` | `StackGetAll` | | `ironic/db` | `GetNodeMetrics` | `GetNodeList` | | `keystone/db` | `GetProjectMetrics` | `ListProjects` | @@ -62,6 +65,7 @@ with identical semantics upstream. - [Nova API database](https://github.com/openstack/nova/tree/master/nova/db/api) and [objects](https://github.com/openstack/nova/tree/master/nova/objects): flavor, aggregate, and quota data. - [Cinder DB API](https://github.com/openstack/cinder/blob/master/cinder/db/api.py): `volume_get`, `volume_get_all`, `volume_type_get_all`, `service_get_all`. - [Glance DB API](https://github.com/openstack/glance/blob/master/glance/db/sqlalchemy/api.py): `image_get`, `image_get_all`. +- [Designate storage](https://github.com/openstack/designate/blob/master/designate/storage/sqlalchemy/__init__.py): `find_zones`, `find_recordsets`, `count_recordsets`. The library also follows [Designate's UUID conversion](https://github.com/openstack/designate/blob/master/designate/storage/sqlalchemy/types.py) and [recordset status precedence](https://github.com/openstack/designate/blob/master/designate/objects/recordset.py). - [Ironic DB API](https://github.com/openstack/ironic/blob/master/ironic/db/api.py) and [Magnum DB API](https://github.com/openstack/magnum/blob/master/magnum/db/api.py): `get_node_list`, `get_cluster_list`. - [Heat DB API](https://github.com/openstack/heat/blob/master/heat/db/api.py): `stack_get_all`. - [Manila DB API](https://github.com/openstack/manila/blob/master/manila/db/api.py): share operations; the instance join is an explicit extension. @@ -77,6 +81,7 @@ with identical semantics upstream. - Current exporter queries retain their existing deleted/hidden/status predicates; they are not full upstream administrative listings. - Errors are Go/database errors; absent single resources return `sql.ErrNoRows` rather than Python service-specific exceptions. - Aggregate queries such as `QuotaGetAllWithUsage`, `GetResourceProviderInventories`, and `GetResourceCountsByProject` are explicitly library extensions. +- Designate returns canonical zone and recordset UUIDs and excludes soft-deleted zones. `RecordsetCountByZone` includes zero-count zones and can run without reading individual records. `RecordsetGetAllWithStatus` uses the child precedence `ERROR`, `PENDING`, `ACTIVE`, `DELETED` and returns `ACTIVE` for an empty recordset. Recordsets with a NULL `zone_id` have no visible zone and are omitted. - No cross-cell routing or historic schema negotiation is performed. Nova archive access is explicitly selected with `InstanceFilters.Archive`. ## Resource lifecycle and metadata reads diff --git a/README.md b/README.md index 5a2eddf..46520c4 100644 --- a/README.md +++ b/README.md @@ -16,6 +16,7 @@ repository objects. Placement queries live under `placement/objects`. | `nova/db/api` | `FlavorGetAll`, `AggregateGetAll`, quota projections | | `cinder/db` | `ServiceGetAll`, `QuotaGetProjectLimits`, `QuotaUsageGetAll` | | `glance/db` | `ImageGetAll` | +| `designate/db` | `ZoneGetAll`, `RecordsetCountByZone`, `RecordsetGetAllWithStatus` | | `keystone/db` | `ListProjects`, `ListDomains`, `ListUsers` | | `heat/db` | `StackGetAll` | | `ironic/db` | `GetNodeList` | diff --git a/designate/db/db.go b/designate/db/db.go new file mode 100644 index 0000000..ea582ad --- /dev/null +++ b/designate/db/db.go @@ -0,0 +1,31 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.30.0 + +package designate + +import ( + "context" + "database/sql" +) + +type DBTX interface { + ExecContext(context.Context, string, ...interface{}) (sql.Result, error) + PrepareContext(context.Context, string) (*sql.Stmt, error) + QueryContext(context.Context, string, ...interface{}) (*sql.Rows, error) + QueryRowContext(context.Context, string, ...interface{}) *sql.Row +} + +func New(db DBTX) *Queries { + return &Queries{db: db} +} + +type Queries struct { + db DBTX +} + +func (q *Queries) WithTx(tx *sql.Tx) *Queries { + return &Queries{ + db: tx, + } +} diff --git a/designate/db/designate.go b/designate/db/designate.go new file mode 100644 index 0000000..2e9a2c8 --- /dev/null +++ b/designate/db/designate.go @@ -0,0 +1,51 @@ +package designate + +import ( + "context" + + "github.com/google/uuid" +) + +type ( + ZoneGetAllRow = zoneGetAllRow + RecordsetCountByZoneRow = recordsetCountByZoneRow + RecordsetGetAllWithStatusRow = recordsetGetAllWithStatusRow +) + +// ZoneGetAll returns non-deleted zones with API-format UUIDs. +func (q *Queries) ZoneGetAll(ctx context.Context) ([]ZoneGetAllRow, error) { + rows, err := q.zoneGetAll(ctx) + for i := range rows { + rows[i].ID = formatUUID(rows[i].ID) + } + return rows, err +} + +// RecordsetCountByZone returns counts for non-deleted zones, including empty zones. +func (q *Queries) RecordsetCountByZone(ctx context.Context) ([]RecordsetCountByZoneRow, error) { + rows, err := q.recordsetCountByZone(ctx) + for i := range rows { + rows[i].ZoneID = formatUUID(rows[i].ZoneID) + } + return rows, err +} + +// RecordsetGetAllWithStatus returns recordsets in non-deleted zones. +// Status follows Designate's child record precedence and defaults to ACTIVE. +func (q *Queries) RecordsetGetAllWithStatus(ctx context.Context) ([]RecordsetGetAllWithStatusRow, error) { + rows, err := q.recordsetGetAllWithStatus(ctx) + for i := range rows { + rows[i].ID = formatUUID(rows[i].ID) + rows[i].ZoneID = formatUUID(rows[i].ZoneID) + } + return rows, err +} + +// Designate stores compact UUIDs and returns canonical UUIDs through its API. +func formatUUID(value string) string { + id, err := uuid.Parse(value) + if err != nil { + return value + } + return id.String() +} diff --git a/designate/db/models.go b/designate/db/models.go new file mode 100644 index 0000000..94c4ac7 --- /dev/null +++ b/designate/db/models.go @@ -0,0 +1,31 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.30.0 + +package designate + +import ( + "database/sql" +) + +type Record struct { + ID string + RecordsetID string + Status string +} + +type Recordset struct { + ID string + ZoneID string + Name string + Type string +} + +type Zone struct { + ID string + Name string + TenantID sql.NullString + Status string + Type string + Deleted string +} diff --git a/designate/db/queries.sql b/designate/db/queries.sql new file mode 100644 index 0000000..03f7c33 --- /dev/null +++ b/designate/db/queries.sql @@ -0,0 +1,44 @@ +-- name: zoneGetAll :many +SELECT id, name, tenant_id, status, type +FROM zones +WHERE deleted = '0'; + +-- name: recordsetCountByZone :many +SELECT + z.id AS zone_id, + z.name AS zone_name, + z.tenant_id, + COUNT(rs.id) AS recordset_count +FROM zones z +LEFT JOIN recordsets rs ON rs.zone_id = z.id +WHERE z.deleted = '0' +GROUP BY z.id, z.name, z.tenant_id; + +-- name: recordsetGetAllWithStatus :many +SELECT + rs.id, + rs.name, + rs.type, + z.id AS zone_id, + z.name AS zone_name, + CASE rs_status.severity + WHEN 1 THEN 'ERROR' + WHEN 2 THEN 'PENDING' + WHEN 3 THEN 'ACTIVE' + WHEN 4 THEN 'DELETED' + ELSE 'ACTIVE' + END AS status +FROM recordsets rs +JOIN zones z ON z.id = rs.zone_id +LEFT JOIN ( + SELECT recordset_id, + MIN(CASE status + WHEN 'ERROR' THEN 1 + WHEN 'PENDING' THEN 2 + WHEN 'ACTIVE' THEN 3 + WHEN 'DELETED' THEN 4 + END) AS severity + FROM records + GROUP BY recordset_id +) rs_status ON rs_status.recordset_id = rs.id +WHERE z.deleted = '0'; diff --git a/designate/db/queries.sql.go b/designate/db/queries.sql.go new file mode 100644 index 0000000..963c2f9 --- /dev/null +++ b/designate/db/queries.sql.go @@ -0,0 +1,170 @@ +// Code generated by sqlc. DO NOT EDIT. +// versions: +// sqlc v1.30.0 +// source: queries.sql + +package designate + +import ( + "context" + "database/sql" +) + +const RecordsetCountByZone = `-- name: recordsetCountByZone :many +SELECT + z.id AS zone_id, + z.name AS zone_name, + z.tenant_id, + COUNT(rs.id) AS recordset_count +FROM zones z +LEFT JOIN recordsets rs ON rs.zone_id = z.id +WHERE z.deleted = '0' +GROUP BY z.id, z.name, z.tenant_id +` + +type recordsetCountByZoneRow struct { + ZoneID string + ZoneName string + TenantID sql.NullString + RecordsetCount int64 +} + +func (q *Queries) recordsetCountByZone(ctx context.Context) ([]recordsetCountByZoneRow, error) { + rows, err := q.db.QueryContext(ctx, RecordsetCountByZone) + if err != nil { + return nil, err + } + defer rows.Close() + var items []recordsetCountByZoneRow + for rows.Next() { + var i recordsetCountByZoneRow + if err := rows.Scan( + &i.ZoneID, + &i.ZoneName, + &i.TenantID, + &i.RecordsetCount, + ); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Close(); err != nil { + return nil, err + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} + +const RecordsetGetAllWithStatus = `-- name: recordsetGetAllWithStatus :many +SELECT + rs.id, + rs.name, + rs.type, + z.id AS zone_id, + z.name AS zone_name, + CASE rs_status.severity + WHEN 1 THEN 'ERROR' + WHEN 2 THEN 'PENDING' + WHEN 3 THEN 'ACTIVE' + WHEN 4 THEN 'DELETED' + ELSE 'ACTIVE' + END AS status +FROM recordsets rs +JOIN zones z ON z.id = rs.zone_id +LEFT JOIN ( + SELECT recordset_id, + MIN(CASE status + WHEN 'ERROR' THEN 1 + WHEN 'PENDING' THEN 2 + WHEN 'ACTIVE' THEN 3 + WHEN 'DELETED' THEN 4 + END) AS severity + FROM records + GROUP BY recordset_id +) rs_status ON rs_status.recordset_id = rs.id +WHERE z.deleted = '0' +` + +type recordsetGetAllWithStatusRow struct { + ID string + Name string + Type string + ZoneID string + ZoneName string + Status string +} + +func (q *Queries) recordsetGetAllWithStatus(ctx context.Context) ([]recordsetGetAllWithStatusRow, error) { + rows, err := q.db.QueryContext(ctx, RecordsetGetAllWithStatus) + if err != nil { + return nil, err + } + defer rows.Close() + var items []recordsetGetAllWithStatusRow + for rows.Next() { + var i recordsetGetAllWithStatusRow + if err := rows.Scan( + &i.ID, + &i.Name, + &i.Type, + &i.ZoneID, + &i.ZoneName, + &i.Status, + ); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Close(); err != nil { + return nil, err + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} + +const ZoneGetAll = `-- name: zoneGetAll :many +SELECT id, name, tenant_id, status, type +FROM zones +WHERE deleted = '0' +` + +type zoneGetAllRow struct { + ID string + Name string + TenantID sql.NullString + Status string + Type string +} + +func (q *Queries) zoneGetAll(ctx context.Context) ([]zoneGetAllRow, error) { + rows, err := q.db.QueryContext(ctx, ZoneGetAll) + if err != nil { + return nil, err + } + defer rows.Close() + var items []zoneGetAllRow + for rows.Next() { + var i zoneGetAllRow + if err := rows.Scan( + &i.ID, + &i.Name, + &i.TenantID, + &i.Status, + &i.Type, + ); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Close(); err != nil { + return nil, err + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} diff --git a/go.mod b/go.mod index 0e2fae3..904b683 100644 --- a/go.mod +++ b/go.mod @@ -5,6 +5,7 @@ go 1.25.5 require ( github.com/DATA-DOG/go-sqlmock v1.5.2 github.com/go-sql-driver/mysql v1.9.3 + github.com/google/uuid v1.6.0 github.com/stretchr/testify v1.11.1 github.com/testcontainers/testcontainers-go v0.40.0 github.com/testcontainers/testcontainers-go/modules/mariadb v0.40.0 @@ -31,7 +32,6 @@ require ( github.com/go-logr/logr v1.4.3 // indirect github.com/go-logr/stdr v1.2.2 // indirect github.com/go-ole/go-ole v1.2.6 // indirect - github.com/google/uuid v1.6.0 // indirect github.com/grpc-ecosystem/grpc-gateway/v2 v2.27.8 // indirect github.com/klauspost/compress v1.18.0 // indirect github.com/lufia/plan9stats v0.0.0-20211012122336-39d0f177ccd0 // indirect diff --git a/schema/designate/schema.sql b/schema/designate/schema.sql new file mode 100644 index 0000000..525f0fa --- /dev/null +++ b/schema/designate/schema.sql @@ -0,0 +1,23 @@ +CREATE TABLE zones ( + id CHAR(32) NOT NULL PRIMARY KEY, + name VARCHAR(255) NOT NULL, + tenant_id VARCHAR(36), + status VARCHAR(16) NOT NULL, + type VARCHAR(16) NOT NULL, + deleted CHAR(32) NOT NULL DEFAULT '0' +); + +CREATE TABLE recordsets ( + id CHAR(32) NOT NULL PRIMARY KEY, + zone_id CHAR(32) NOT NULL, + name VARCHAR(255) NOT NULL, + type VARCHAR(16) NOT NULL, + CONSTRAINT recordsets_zone_fk FOREIGN KEY (zone_id) REFERENCES zones(id) ON DELETE CASCADE +); + +CREATE TABLE records ( + id CHAR(32) NOT NULL PRIMARY KEY, + recordset_id CHAR(32) NOT NULL, + status VARCHAR(16) NOT NULL, + FOREIGN KEY (recordset_id) REFERENCES recordsets(id) ON DELETE CASCADE +); diff --git a/sqlc.yaml b/sqlc.yaml index a04754c..6ca7f91 100644 --- a/sqlc.yaml +++ b/sqlc.yaml @@ -32,6 +32,14 @@ sql: package: glance out: glance/db emit_exported_queries: true +- engine: mysql + schema: schema/designate/schema.sql + queries: designate/db/queries.sql + gen: + go: + package: designate + out: designate/db + emit_exported_queries: true - engine: mysql schema: schema/keystone/schema.sql queries: keystone/db/queries.sql diff --git a/tests/queries_test.go b/tests/queries_test.go index e350060..ee83701 100644 --- a/tests/queries_test.go +++ b/tests/queries_test.go @@ -4,8 +4,10 @@ package tests import ( "context" + "database/sql" "github.com/stretchr/testify/require" cinder "github.com/vexxhost/openstackdb/cinder/db" + designate "github.com/vexxhost/openstackdb/designate/db" glance "github.com/vexxhost/openstackdb/glance/db" heat "github.com/vexxhost/openstackdb/heat/db" "github.com/vexxhost/openstackdb/internal/testutil" @@ -99,6 +101,90 @@ func TestGlanceQueries(t *testing.T) { _, err = q.ImageGetAll(ctx) require.NoError(t, err, "ImageGetAll") } + +func TestDesignateZonesWithRecordsets(t *testing.T) { + conn := testutil.NewMySQLContainer(t, "designate", "../sql/designate/schema.sql") + queries := designate.New(conn) + ctx := context.Background() + + zones, err := queries.ZoneGetAll(ctx) + require.NoError(t, err) + require.Empty(t, zones) + counts, err := queries.RecordsetCountByZone(ctx) + require.NoError(t, err) + require.Empty(t, counts) + recordsets, err := queries.RecordsetGetAllWithStatus(ctx) + require.NoError(t, err) + require.Empty(t, recordsets) + + testutil.SeedSQL(t, conn, + `INSERT INTO zones (id, name, tenant_id, status, type, deleted) VALUES + ('a86dba5800434cc6a1bb69d5e86f3ca3', 'example.org.', 'project-1', 'ACTIVE', 'PRIMARY', '0'), + ('2150b1bfdee242219d8511f7886fb15f', 'empty.example.', NULL, 'PENDING', 'SECONDARY', '0'), + ('23527f480fa04efc82264f2468c7c40e', 'deleted.example.', 'project-1', 'DELETED', 'PRIMARY', '23527f480fa04efc82264f2468c7c40e')`, + `INSERT INTO recordsets (id, zone_id, name, type) VALUES + ('10000000000040008000000000000001', 'a86dba5800434cc6a1bb69d5e86f3ca3', 'error.example.org.', 'A'), + ('10000000000040008000000000000002', 'a86dba5800434cc6a1bb69d5e86f3ca3', 'pending.example.org.', 'A'), + ('10000000000040008000000000000003', 'a86dba5800434cc6a1bb69d5e86f3ca3', 'active.example.org.', 'A'), + ('10000000000040008000000000000004', 'a86dba5800434cc6a1bb69d5e86f3ca3', 'deleted.example.org.', 'A'), + ('10000000000040008000000000000005', 'a86dba5800434cc6a1bb69d5e86f3ca3', 'empty.example.org.', 'TXT'), + ('10000000000040008000000000000006', '23527f480fa04efc82264f2468c7c40e', 'deleted.example.', 'NS')`, + `INSERT INTO records (id, recordset_id, status) VALUES + ('1', '10000000000040008000000000000001', 'PENDING'), ('2', '10000000000040008000000000000001', 'ERROR'), + ('3', '10000000000040008000000000000002', 'ACTIVE'), ('4', '10000000000040008000000000000002', 'PENDING'), + ('5', '10000000000040008000000000000003', 'DELETED'), ('6', '10000000000040008000000000000003', 'ACTIVE'), + ('7', '10000000000040008000000000000004', 'DELETED')`, + ) + + checkVisibleRows := func(t *testing.T) { + t.Helper() + const zoneID = "a86dba58-0043-4cc6-a1bb-69d5e86f3ca3" + const emptyZoneID = "2150b1bf-dee2-4221-9d85-11f7886fb15f" + tenantID := sql.NullString{String: "project-1", Valid: true} + zones, err := queries.ZoneGetAll(ctx) + require.NoError(t, err) + require.ElementsMatch(t, []designate.ZoneGetAllRow{ + {ID: zoneID, Name: "example.org.", TenantID: tenantID, Status: "ACTIVE", Type: "PRIMARY"}, + {ID: emptyZoneID, Name: "empty.example.", Status: "PENDING", Type: "SECONDARY"}, + }, zones) + + counts, err := queries.RecordsetCountByZone(ctx) + require.NoError(t, err) + require.ElementsMatch(t, []designate.RecordsetCountByZoneRow{ + {ZoneID: zoneID, ZoneName: "example.org.", TenantID: tenantID, RecordsetCount: 5}, + {ZoneID: emptyZoneID, ZoneName: "empty.example.", RecordsetCount: 0}, + }, counts) + + recordsets, err := queries.RecordsetGetAllWithStatus(ctx) + require.NoError(t, err) + require.Len(t, recordsets, 5) + statuses := make(map[string]string, len(recordsets)) + for _, row := range recordsets { + require.Equal(t, zoneID, row.ZoneID) + require.Equal(t, "example.org.", row.ZoneName) + statuses[row.ID] = row.Status + } + require.Equal(t, map[string]string{ + "10000000-0000-4000-8000-000000000001": "ERROR", + "10000000-0000-4000-8000-000000000002": "PENDING", + "10000000-0000-4000-8000-000000000003": "ACTIVE", + "10000000-0000-4000-8000-000000000004": "DELETED", + "10000000-0000-4000-8000-000000000005": "ACTIVE", + }, statuses) + } + t.Run("non-null zone ID", checkVisibleRows) + t.Run("nullable zone ID", func(t *testing.T) { + testutil.SeedSQL(t, conn, + `ALTER TABLE recordsets DROP FOREIGN KEY recordsets_zone_fk`, + `ALTER TABLE recordsets MODIFY zone_id CHAR(32) NULL`, + `ALTER TABLE recordsets ADD CONSTRAINT recordsets_zone_fk FOREIGN KEY (zone_id) REFERENCES zones(id) ON DELETE CASCADE`, + `INSERT INTO recordsets (id, zone_id, name, type) VALUES + ('10000000000040008000000000000007', NULL, 'orphan.example.', 'A')`, + ) + checkVisibleRows(t) + }) +} + func TestKeystoneQueries(t *testing.T) { ctx := context.Background() conn := testutil.NewMySQLContainer(t, "keystone", "../sql/keystone/schema.sql") From 75cf35c45adc7ffde4a1accd4f61c8025bc4b48e Mon Sep 17 00:00:00 2001 From: Jeremy Lee Date: Thu, 3 Dec 2026 18:07:49 +0000 Subject: [PATCH 4/4] Add Neutron quota reservations query and order GetQuotas Add GetReservationsForResources, which follows Neutron's get_reservations_for_resources(expired=False) for every project at once. It returns one row per active reservation delta (reservation ID, project ID, expiration, resource and amount), ordered by project, resource and reservation ID. Amounts are returned as stored, including NULL and negative values, rather than summed. A reservation is active when expiration >= UTC_TIMESTAMP(), the same inclusive boundary Neutron uses. The comparison runs on the database clock in UTC, so caller clock skew and session time zones do not affect the result. The resources to read are a positional argument; an empty list matches nothing, as upstream. NULL owners are excluded and empty-string owners are kept, matching GetQuotas and GetResourceCountsByProject, so limits, usage and reservations join on project ID without special cases. GetResourceCountsByProject is unchanged. GetQuotas now orders by project, resource and quota ID so callers that collapse duplicate rows get a stable result. Add the reservations and resourcedeltas tables to the Neutron schema fixture, without indexes on expiration or project_id as upstream. Add unit tests, MariaDB integration tests for reservations and quota owner handling and ordering, and API.md documentation. Co-authored-by: David Hulick Signed-off-by: David Hulick Signed-off-by: Jeremy Lee --- API.md | 42 ++++++++ README.md | 2 +- neutron/db/models.go | 12 +++ neutron/db/queries.sql | 24 ++++- neutron/db/queries.sql.go | 71 ++++++++++++++ neutron/db/quotas_test.go | 97 +++++++++++++++++++ schema/neutron/schema.sql | 16 ++++ tests/neutron_quotas_integration_test.go | 117 +++++++++++++++++++++++ 8 files changed, 379 insertions(+), 2 deletions(-) create mode 100644 neutron/db/quotas_test.go create mode 100644 tests/neutron_quotas_integration_test.go diff --git a/API.md b/API.md index af8487d..d4866d5 100644 --- a/API.md +++ b/API.md @@ -99,3 +99,45 @@ lifecycle metadata. Their fixed current-resource queries remain unchanged for exporter consumers. Deleted volume types and legacy type tables are only read when explicitly requested. Legacy table availability is a caller/deployment concern; errors are propagated rather than hidden. + +### Neutron quota reservations + +| Go operation | Upstream naming source | Scope | +| --- | --- | --- | +| `GetReservationsForResources` | [Neutron `get_reservations_for_resources(..., expired=False)`](https://github.com/openstack/neutron/blob/master/neutron/db/quota/api.py) | All projects instead of one; raw per-delta rows instead of a per-resource sum. | + +`neutron/db.Queries.GetReservationsForResources(ctx, resources)` returns one row +per active reservation delta: `ReservationID`, `ProjectID`, `Expiration`, +`Resource`, and `Amount`. Rows are ordered by project, resource, and reservation +ID. Amounts are returned as stored, including NULL and negative values; summing +them and deciding how to treat malformed amounts is the caller's job. + +A reservation is active when `expiration >= UTC_TIMESTAMP()`, the same inclusive +boundary Neutron uses. The comparison runs on the database clock, so skew +between the caller and the Neutron servers does not change the result. Neutron +writes expirations in UTC, so the comparison uses `UTC_TIMESTAMP()` rather than +the session-time-zone `NOW()`. NULL expirations are never active. + +`resources` is a positional argument, not a `...Filters` struct, and follows +upstream: a nil or empty list matches nothing rather than every resource. Pass +the resources to monitor explicitly, for example `floatingip`, `network`, `port`, +`rbac_policy`, `router`, `security_group`, `security_group_rule`, `subnet`, and +`subnetpool`. + +NULL owners are excluded and empty-string owners are kept. `GetQuotas` and +`GetResourceCountsByProject` use the same owner policy, so limits, usage, and +reservations can be joined on `ProjectID` without special cases. `GetQuotas` +returns rows ordered by project, resource, and quota ID, so callers that collapse +duplicate project/resource rows get a stable result. + +Upstream Neutron defines no index on `reservations.expiration` or +`reservations.project_id`; the schema fixture mirrors that. Each call therefore +scans `reservations` and joins `resourcedeltas` through the index InnoDB creates +for its `reservation_id` foreign key. This is the same access path Neutron's own +quota engine uses, and the table stays small while Neutron's expired-reservation +cleanup runs. If cleanup stalls, the table and this query's cost grow together. + +The schema tables are local fixtures, not production migrations. Separate reads +do not share a snapshot unless the caller uses `WithTx` with a suitable isolation +level. Query, scan, row-iteration, and context errors propagate through the +generated API; an error must never be treated as zero reservations. diff --git a/README.md b/README.md index 46520c4..00fd694 100644 --- a/README.md +++ b/README.md @@ -22,7 +22,7 @@ repository objects. Placement queries live under `placement/objects`. | `ironic/db` | `GetNodeList` | | `magnum/db` | `GetClusterList` | | `manila/db` | `ShareGetAllWithInstances` | -| `neutron/db` | `GetAgents`, `GetHARouterAgentPortBindingsWithAgents`, `GetRouters` | +| `neutron/db` | `GetAgents`, `GetHARouterAgentPortBindingsWithAgents`, `GetRouters`, `GetQuotas`, `GetReservationsForResources` | | `octavia/db/repositories` | `PoolRepository`, `LoadBalancerRepository`, `AmphoraRepository` | | `placement/objects` | Resource provider inventory and allocation projections | diff --git a/neutron/db/models.go b/neutron/db/models.go index c0ab6c9..d1a4eb3 100644 --- a/neutron/db/models.go +++ b/neutron/db/models.go @@ -309,6 +309,18 @@ type Quota struct { Limit sql.NullInt32 } +type Reservation struct { + ID string + ProjectID sql.NullString + Expiration sql.NullTime +} + +type Resourcedelta struct { + Resource string + ReservationID string + Amount sql.NullInt32 +} + type Router struct { ProjectID sql.NullString ID string diff --git a/neutron/db/queries.sql b/neutron/db/queries.sql index 40c8361..ff0b223 100644 --- a/neutron/db/queries.sql +++ b/neutron/db/queries.sql @@ -218,7 +218,11 @@ SELECT FROM quotas q WHERE - q.project_id IS NOT NULL; + q.project_id IS NOT NULL +ORDER BY + q.project_id, + q.resource, + q.id; -- name: GetResourceCountsByProject :many SELECT @@ -274,3 +278,21 @@ SELECT 'subnetpool' as resource, CAST(COUNT(*) AS SIGNED) as cnt FROM subnetpools WHERE project_id IS NOT NULL GROUP BY project_id; + +-- name: GetReservationsForResources :many +-- Mirrors neutron.db.quota.api.get_reservations_for_resources(expired=False): +-- active means expiration >= now, evaluated on the database clock in UTC +-- because Neutron writes expirations with utcnow(). Rows are returned per +-- reservation delta, unaggregated, for every project with a non-NULL owner. +SELECT + r.id AS reservation_id, + r.project_id, + r.expiration, + d.resource, + d.amount +FROM reservations r +JOIN resourcedeltas d ON d.reservation_id = r.id +WHERE r.expiration >= UTC_TIMESTAMP() + AND r.project_id IS NOT NULL + AND d.resource IN (sqlc.slice('resources')) +ORDER BY r.project_id, d.resource, r.id; diff --git a/neutron/db/queries.sql.go b/neutron/db/queries.sql.go index 23e36e4..7eeda26 100644 --- a/neutron/db/queries.sql.go +++ b/neutron/db/queries.sql.go @@ -8,6 +8,7 @@ package neutron import ( "context" "database/sql" + "strings" ) const GetAgents = `-- name: GetAgents :many @@ -476,6 +477,10 @@ FROM quotas q WHERE q.project_id IS NOT NULL +ORDER BY + q.project_id, + q.resource, + q.id ` type GetQuotasRow struct { @@ -507,6 +512,72 @@ func (q *Queries) GetQuotas(ctx context.Context) ([]GetQuotasRow, error) { return items, nil } +const GetReservationsForResources = `-- name: GetReservationsForResources :many +SELECT + r.id AS reservation_id, + r.project_id, + r.expiration, + d.resource, + d.amount +FROM reservations r +JOIN resourcedeltas d ON d.reservation_id = r.id +WHERE r.expiration >= UTC_TIMESTAMP() + AND r.project_id IS NOT NULL + AND d.resource IN (/*SLICE:resources*/?) +ORDER BY r.project_id, d.resource, r.id +` + +type GetReservationsForResourcesRow struct { + ReservationID string + ProjectID sql.NullString + Expiration sql.NullTime + Resource string + Amount sql.NullInt32 +} + +// Mirrors neutron.db.quota.api.get_reservations_for_resources(expired=False): +// active means expiration >= now, evaluated on the database clock in UTC +// because Neutron writes expirations with utcnow(). Rows are returned per +// reservation delta, unaggregated, for every project with a non-NULL owner. +func (q *Queries) GetReservationsForResources(ctx context.Context, resources []string) ([]GetReservationsForResourcesRow, error) { + query := GetReservationsForResources + var queryParams []interface{} + if len(resources) > 0 { + for _, v := range resources { + queryParams = append(queryParams, v) + } + query = strings.Replace(query, "/*SLICE:resources*/?", strings.Repeat(",?", len(resources))[1:], 1) + } else { + query = strings.Replace(query, "/*SLICE:resources*/?", "NULL", 1) + } + rows, err := q.db.QueryContext(ctx, query, queryParams...) + if err != nil { + return nil, err + } + defer rows.Close() + var items []GetReservationsForResourcesRow + for rows.Next() { + var i GetReservationsForResourcesRow + if err := rows.Scan( + &i.ReservationID, + &i.ProjectID, + &i.Expiration, + &i.Resource, + &i.Amount, + ); err != nil { + return nil, err + } + items = append(items, i) + } + if err := rows.Close(); err != nil { + return nil, err + } + if err := rows.Err(); err != nil { + return nil, err + } + return items, nil +} + const GetResourceCountsByProject = `-- name: GetResourceCountsByProject :many SELECT project_id, diff --git a/neutron/db/quotas_test.go b/neutron/db/quotas_test.go new file mode 100644 index 0000000..5ef7327 --- /dev/null +++ b/neutron/db/quotas_test.go @@ -0,0 +1,97 @@ +package neutron + +import ( + "context" + "database/sql" + "errors" + "regexp" + "strings" + "testing" + "time" + + "github.com/DATA-DOG/go-sqlmock" + "github.com/stretchr/testify/require" +) + +var reservationColumns = []string{"reservation_id", "project_id", "expiration", "resource", "amount"} + +func reservationQuery(placeholders string) string { + return regexp.QuoteMeta(strings.Replace(GetReservationsForResources, "/*SLICE:resources*/?", placeholders, 1)) +} + +func TestGetReservationsForResourcesScansRawRows(t *testing.T) { + db, mock, err := sqlmock.New() + require.NoError(t, err) + t.Cleanup(func() { mock.ExpectClose(); require.NoError(t, db.Close()) }) + + expiration := time.Date(2026, 10, 28, 12, 0, 0, 0, time.UTC) + mock.ExpectQuery(reservationQuery("?,?")). + WithArgs("port", "network"). + WillReturnRows(sqlmock.NewRows(reservationColumns). + AddRow("r1", "p", expiration, "port", 3). + AddRow("r2", "", expiration, "network", -2). + AddRow("r3", "p", expiration, "port", nil)). + RowsWillBeClosed() + + rows, err := New(db).GetReservationsForResources(context.Background(), []string{"port", "network"}) + require.NoError(t, err) + require.Equal(t, []GetReservationsForResourcesRow{ + {ReservationID: "r1", ProjectID: sql.NullString{String: "p", Valid: true}, Expiration: sql.NullTime{Time: expiration, Valid: true}, Resource: "port", Amount: sql.NullInt32{Int32: 3, Valid: true}}, + {ReservationID: "r2", ProjectID: sql.NullString{Valid: true}, Expiration: sql.NullTime{Time: expiration, Valid: true}, Resource: "network", Amount: sql.NullInt32{Int32: -2, Valid: true}}, + {ReservationID: "r3", ProjectID: sql.NullString{String: "p", Valid: true}, Expiration: sql.NullTime{Time: expiration, Valid: true}, Resource: "port"}, + }, rows) + require.NoError(t, mock.ExpectationsWereMet()) +} + +// An empty resource list matches nothing, like upstream Neutron's +// get_reservations_for_resources, instead of widening to every resource. +func TestGetReservationsForResourcesEmptyListMatchesNothing(t *testing.T) { + for name, resources := range map[string][]string{"nil": nil, "empty": {}} { + t.Run(name, func(t *testing.T) { + db, mock, err := sqlmock.New() + require.NoError(t, err) + t.Cleanup(func() { mock.ExpectClose(); require.NoError(t, db.Close()) }) + mock.ExpectQuery(reservationQuery("NULL")).WithoutArgs(). + WillReturnRows(sqlmock.NewRows(reservationColumns)).RowsWillBeClosed() + + rows, err := New(db).GetReservationsForResources(context.Background(), resources) + require.NoError(t, err) + require.Empty(t, rows) + require.NoError(t, mock.ExpectationsWereMet()) + }) + } +} + +func TestGetReservationsForResourcesPropagatesErrors(t *testing.T) { + for _, kind := range []string{"query", "scan", "iteration", "timeout"} { + t.Run(kind, func(t *testing.T) { + db, mock, err := sqlmock.New() + require.NoError(t, err) + t.Cleanup(func() { mock.ExpectClose(); require.NoError(t, db.Close()) }) + + exp := mock.ExpectQuery(reservationQuery("?")).WithArgs("port") + rows := sqlmock.NewRows(reservationColumns) + switch kind { + case "query": + exp.WillReturnError(errors.New("read failure")) + case "scan": + exp.WillReturnRows(rows.AddRow("r", "p", time.Now(), "port", "malformed")).RowsWillBeClosed() + case "iteration": + exp.WillReturnRows(rows.AddRow("r", "p", time.Now(), "port", 1).RowError(0, errors.New("interrupted"))).RowsWillBeClosed() + case "timeout": + exp.WillDelayFor(time.Second).WillReturnRows(rows) + } + timeout := time.Second + if kind == "timeout" { + timeout = 10 * time.Millisecond + } + ctx, cancel := context.WithTimeout(context.Background(), timeout) + defer cancel() + + got, err := New(db).GetReservationsForResources(ctx, []string{"port"}) + require.Error(t, err) + require.Nil(t, got) + require.NoError(t, mock.ExpectationsWereMet()) + }) + } +} diff --git a/schema/neutron/schema.sql b/schema/neutron/schema.sql index e4c3146..c9777ae 100644 --- a/schema/neutron/schema.sql +++ b/schema/neutron/schema.sql @@ -242,3 +242,19 @@ CREATE TABLE `tag` varchar(255) NOT NULL, PRIMARY KEY (`standard_attr_id`, `tag`) ); + +-- Neutron quota reservation storage (local query fixture, not a migration). +-- Mirrors upstream neutron/db/quota/models.py: no index on expiration or +-- project_id (HasProjectNoIndex); InnoDB indexes reservation_id for the FK. +CREATE TABLE `reservations` ( + `id` varchar(36) NOT NULL PRIMARY KEY, + `project_id` varchar(255) DEFAULT NULL, + `expiration` datetime DEFAULT NULL +); +CREATE TABLE `resourcedeltas` ( + `resource` varchar(255) NOT NULL, + `reservation_id` varchar(36) NOT NULL, + `amount` int DEFAULT NULL, + PRIMARY KEY (`resource`, `reservation_id`), + FOREIGN KEY (`reservation_id`) REFERENCES `reservations` (`id`) ON DELETE CASCADE +); diff --git a/tests/neutron_quotas_integration_test.go b/tests/neutron_quotas_integration_test.go new file mode 100644 index 0000000..b254efb --- /dev/null +++ b/tests/neutron_quotas_integration_test.go @@ -0,0 +1,117 @@ +//go:build integration + +package tests + +import ( + "database/sql" + "fmt" + "testing" + + "github.com/stretchr/testify/require" + "github.com/vexxhost/openstackdb/internal/testutil" + neutron "github.com/vexxhost/openstackdb/neutron/db" +) + +func TestNeutronReservationsForResources(t *testing.T) { + ctx := t.Context() + db := testutil.NewMySQLContainer(t, "neutron-reservations", "../sql/neutron/schema.sql") + + // Expirations are relative to the database clock, which is what the query + // compares against, so the test does not depend on the runner's clock. + testutil.SeedSQL(t, db, + "INSERT INTO reservations VALUES ('active-a', 'a', UTC_TIMESTAMP() + INTERVAL 1 HOUR)", + "INSERT INTO reservations VALUES ('active-empty', '', UTC_TIMESTAMP() + INTERVAL 1 HOUR)", + "INSERT INTO reservations VALUES ('active-null-owner', NULL, UTC_TIMESTAMP() + INTERVAL 1 HOUR)", + "INSERT INTO reservations VALUES ('expired', 'a', UTC_TIMESTAMP() - INTERVAL 1 HOUR)", + "INSERT INTO reservations VALUES ('null-expiration', 'a', NULL)", + "INSERT INTO resourcedeltas VALUES ('port', 'active-a', 3)", + "INSERT INTO resourcedeltas VALUES ('network', 'active-a', -2)", + "INSERT INTO resourcedeltas VALUES ('router', 'active-a', 1)", + "INSERT INTO resourcedeltas VALUES ('port', 'active-empty', NULL)", + "INSERT INTO resourcedeltas VALUES ('port', 'active-null-owner', 5)", + "INSERT INTO resourcedeltas VALUES ('port', 'expired', 7)", + "INSERT INTO resourcedeltas VALUES ('port', 'null-expiration', 9)", + ) + + q := neutron.New(db) + rows, err := q.GetReservationsForResources(ctx, []string{"port", "network"}) + require.NoError(t, err) + + type delta struct { + ID, Project, Resource string + Amount sql.NullInt32 + } + var got []delta + for _, r := range rows { + require.True(t, r.ProjectID.Valid) + require.True(t, r.Expiration.Valid) + got = append(got, delta{r.ReservationID, r.ProjectID.String, r.Resource, r.Amount}) + } + // Ordered by project, resource, reservation. Expired, NULL-expiration, + // NULL-owner and unrequested-resource rows are excluded; empty-string + // owners are kept, matching GetQuotas and GetResourceCountsByProject. + require.Equal(t, []delta{ + {"active-empty", "", "port", sql.NullInt32{}}, + {"active-a", "a", "network", sql.NullInt32{Int32: -2, Valid: true}}, + {"active-a", "a", "port", sql.NullInt32{Int32: 3, Valid: true}}, + }, got) + + rows, err = q.GetReservationsForResources(ctx, nil) + require.NoError(t, err) + require.Empty(t, rows) +} + +func TestNeutronQuotaOwnersAndOrdering(t *testing.T) { + ctx := t.Context() + db := testutil.NewMySQLContainer(t, "neutron-quotas", "../sql/neutron/schema.sql") + + // Each table owns its counts without requiring parent rows or quota overrides. + inserts := map[string]string{ + "floatingip": "INSERT INTO floatingips (id, project_id, floating_ip_address, floating_network_id, floating_port_id, status, standard_attr_id) VALUES (?, ?, '192.0.2.1', 'parent-network', 'parent-port', 'DOWN', 1)", + "network": "INSERT INTO networks (id, project_id, status, standard_attr_id) VALUES (?, ?, 'DOWN', 1)", + "port": "INSERT INTO ports (id, project_id, network_id, mac_address, admin_state_up, status, device_id, device_owner, standard_attr_id) VALUES (?, ?, 'parent-network', '00:00:00:00:00:01', 0, 'DOWN', '', '', 1)", + "router": "INSERT INTO routers (id, project_id, status, standard_attr_id) VALUES (?, ?, 'DOWN', 1)", + "security_group": "INSERT INTO securitygroups (id, project_id, standard_attr_id) VALUES (?, ?, 1)", + "security_group_rule": "INSERT INTO securitygrouprules (id, project_id, security_group_id, standard_attr_id) VALUES (?, ?, 'parent-group', 1)", + "subnet": "INSERT INTO subnets (id, project_id, network_id, ip_version, cidr, standard_attr_id) VALUES (?, ?, 'parent-network', 4, '192.0.2.0/24', 1)", + "rbac_policy": "INSERT INTO networkrbacs (id, project_id, object_id, target_project, action) VALUES (?, ?, 'parent-network', 'target-owner', 'access_as_shared')", + "subnetpool": "INSERT INTO subnetpools (id, project_id, ip_version, default_prefixlen, min_prefixlen, max_prefixlen, standard_attr_id) VALUES (?, ?, 4, 24, 8, 32, 1)", + } + var expected []neutron.GetResourceCountsByProjectRow + for resource, insert := range inserts { + for j, owner := range []any{"a", "a", "b", "", nil} { + _, err := db.ExecContext(ctx, insert, fmt.Sprintf("%s-%d", resource, j), owner) + require.NoError(t, err) + } + expected = append(expected, + neutron.GetResourceCountsByProjectRow{ProjectID: sql.NullString{String: "a", Valid: true}, Resource: resource, Cnt: 2}, + neutron.GetResourceCountsByProjectRow{ProjectID: sql.NullString{String: "b", Valid: true}, Resource: resource, Cnt: 1}, + // Empty-string owners (for example L3 HA networks and ports) are kept. + neutron.GetResourceCountsByProjectRow{ProjectID: sql.NullString{Valid: true}, Resource: resource, Cnt: 1}) + } + q := neutron.New(db) + usage, err := q.GetResourceCountsByProject(ctx) + require.NoError(t, err) + require.ElementsMatch(t, expected, usage) + + // Duplicate project/resource rows are kept and ordered by id, so callers + // that collapse duplicates see a stable result. + testutil.SeedSQL(t, db, + "INSERT INTO quotas VALUES ('q3', 'b', 'port', 10)", + "INSERT INTO quotas VALUES ('q2', 'a', 'port', 42)", + "INSERT INTO quotas VALUES ('q1', 'a', 'port', -1)", + "INSERT INTO quotas VALUES ('q4', 'a', 'network', NULL)", + "INSERT INTO quotas VALUES ('q5', '', 'port', 0)", + "INSERT INTO quotas VALUES ('q6', NULL, 'port', 5)", + ) + limits, err := q.GetQuotas(ctx) + require.NoError(t, err) + port := sql.NullString{String: "port", Valid: true} + require.Equal(t, []neutron.GetQuotasRow{ + {ProjectID: sql.NullString{Valid: true}, Resource: port, Limit: sql.NullInt32{Valid: true}}, + {ProjectID: sql.NullString{String: "a", Valid: true}, Resource: sql.NullString{String: "network", Valid: true}}, + {ProjectID: sql.NullString{String: "a", Valid: true}, Resource: port, Limit: sql.NullInt32{Int32: -1, Valid: true}}, + {ProjectID: sql.NullString{String: "a", Valid: true}, Resource: port, Limit: sql.NullInt32{Int32: 42, Valid: true}}, + {ProjectID: sql.NullString{String: "b", Valid: true}, Resource: port, Limit: sql.NullInt32{Int32: 10, Valid: true}}, + }, limits) +}