Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
## 0.9.0 [unreleased]

### Features

1. [#87](https://github.com/InfluxCommunity/influxdb3-go/pull/87): Add Cloud Dedicated database creation support

## 0.8.0 [2024-06-24]

### Features
Expand Down
2 changes: 1 addition & 1 deletion influxdb3/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -171,7 +171,7 @@ func (c *Client) makeAPICall(ctx context.Context, params httpParams) (*http.Resp
}
}
req.Header.Set("User-Agent", userAgent)
if c.authorization != "" {
if c.authorization != "" && req.Header.Get("Authorization") == "" {
req.Header.Set("Authorization", c.authorization)
}

Expand Down
15 changes: 14 additions & 1 deletion influxdb3/client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,14 +25,15 @@ package influxdb3
import (
"context"
"fmt"
"github.com/influxdata/line-protocol/v2/lineprotocol"
"net/http"
"net/http/httptest"
"net/url"
"os"
"strings"
"testing"

"github.com/influxdata/line-protocol/v2/lineprotocol"

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
Expand Down Expand Up @@ -320,6 +321,18 @@ func TestMakeAPICall(t *testing.T) {
})
assert.NotNil(t, res)
assert.Nil(t, err)
assert.Equal(t, "Token my-token", res.Request.Header.Get("Authorization"))
assert.Nil(t, err)

res, err = client.makeAPICall(context.Background(), httpParams{
endpointURL: turl,
queryParams: nil,
httpMethod: "GET",
headers: http.Header{"Authorization": {"Bearer managment-api-token"}},
body: nil,
})
assert.Equal(t, "Bearer managment-api-token", res.Request.Header.Get("Authorization"))
assert.Nil(t, err)
}

func TestResolveErrorMessage(t *testing.T) {
Expand Down
67 changes: 67 additions & 0 deletions influxdb3/example_management_cloud_dedicated_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
/*
The MIT License

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

package influxdb3

import (
"context"
"log"
"net/url"
"os"
)

func ExampleCloudDedicatedClient_CreateDatabase() {
managementToken := os.Getenv("INFLUX_MANAGEMENT_TOKEN")
accountID := os.Getenv("INFLUX_ACCOUNT_ID")
clusterID := os.Getenv("INFLUX_CLUSTER_ID")
managementAPIURL, err := url.Parse(os.Getenv("INFLUX_MANAGEMENT_API_URL"))
if err != nil {
log.Fatal(err)
}

client, err := NewFromEnv()
if err != nil {
panic(err)
}

cloudDedicatedConfig := CloudDedicatedClientConfig{
AccountID: accountID,
ClusterID: clusterID,
ManagementToken: managementToken,
ManagementAPIURL: managementAPIURL,
}

defer client.Close()

cloudDedicatedClient := NewCloudDedicatedClient(client)
db := &Database{
ClusterDatabaseName: "testDB",
ClusterDatabaseMaxTables: 500,
ClusterDatabaseMaxColumnsPerTable: 250,
ClusterDatabaseRetentionPeriod: 0,
ClusterDatabasePartitionTemplate: []PartitionTemplate{},
}

if err := cloudDedicatedClient.CreateDatabase(context.Background(), &cloudDedicatedConfig, db); err != nil {
log.Fatal(err)
}
}
148 changes: 148 additions & 0 deletions influxdb3/management_cloud_decicated.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,148 @@
/*
The MIT License

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

package influxdb3

import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"net/url"
)

type (
// CloudDedicatedClient represents a client for InfluxDB Cloud Dedicated administration operations.
// https://docs.influxdata.com/influxdb/cloud-dedicated/admin/databases/create/?t=Management+API
CloudDedicatedClient struct {
client *Client
}

CloudDedicatedClientConfig struct {
AccountID string
ClusterID string
ManagementToken string
ManagementAPIURL *url.URL // default is https://console.influxdata.com
}

Database struct {
ClusterDatabaseName string `json:"name"`
ClusterDatabaseMaxTables uint64 `json:"maxTables"` // default 500
ClusterDatabaseMaxColumnsPerTable uint64 `json:"maxColumnsPerTable"` // default 250
ClusterDatabaseRetentionPeriod uint64 `json:"retentionPeriod"` // nanoseconds default 0 is infinite
ClusterDatabasePartitionTemplate []PartitionTemplate `json:"partitionTemplate"` // Tag or TagBucket, limit is total of 7
}

PartitionTemplate interface {
isPartitionTemplate()
}

Tag struct {
Type string `json:"type"`
Value string `json:"value"`
}

TagBucket struct {
Type string `json:"type"`
Value TagBucketValue `json:"value"`
}

TagBucketValue struct {
TagName string `json:"tagName"`
NumberOfBuckets uint64 `json:"numberOfBuckets"`
}
)

var (
MaxPartitions = 7
ManagementAPIURL = "https://console.influxdata.com"
)

func (t Tag) isPartitionTemplate() {}
func (tb TagBucket) isPartitionTemplate() {}

// NewCloudDedicatedClient creates new CloudDedicatedClient with given InfluxDB client.
func NewCloudDedicatedClient(client *Client) *CloudDedicatedClient {
return &CloudDedicatedClient{client: client}
}

// CreateDatabase creates a new database
func (d *CloudDedicatedClient) CreateDatabase(ctx context.Context, config *CloudDedicatedClientConfig, db *Database) error {
if db == nil {
return errors.New("database must not nil")
}

if d.client.config.Database == "" {
return errors.New("database name must not be empty")
}
db.ClusterDatabaseName = d.client.config.Database

if len(db.ClusterDatabasePartitionTemplate) > MaxPartitions {
return fmt.Errorf("partition template should not have more than %d tags or tag buckets", MaxPartitions)
}

if db.ClusterDatabaseMaxTables == 0 {
db.ClusterDatabaseMaxTables = uint64(500)
}

if db.ClusterDatabaseMaxColumnsPerTable == 0 {
db.ClusterDatabaseMaxColumnsPerTable = uint64(250)
}

path := fmt.Sprintf("/api/v0/accounts/%s/clusters/%s/databases", config.AccountID, config.ClusterID)

return d.createDatabase(ctx, path, db, config)
}

// createDatabase is a helper function for CreateDatabase to enhance test coverage.
func (d *CloudDedicatedClient) createDatabase(ctx context.Context, path string, db any, config *CloudDedicatedClientConfig) error {
if config.ManagementAPIURL == nil {
config.ManagementAPIURL, _ = url.Parse(ManagementAPIURL)
}
u, err := config.ManagementAPIURL.Parse(path)
if err != nil {
return fmt.Errorf("failed to parse database creation path: %w", err)
}

body, err := json.Marshal(db)
if err != nil {
return fmt.Errorf("failed to marshal database creation request body: %w", err)
}

headers := http.Header{}
headers.Set("Content-Type", "application/json")
headers.Set("Accept", "application/json")
headers.Set("Authorization", "Bearer "+config.ManagementToken)

param := httpParams{
endpointURL: u,
queryParams: nil,
httpMethod: "POST",
headers: headers,
body: bytes.NewReader(body),
}

_, err = d.client.makeAPICall(ctx, param)
return err
}
Loading