Skip to content

Commit 3023b23

Browse files
committed
Improve ClickHouse state store with authentication support and connection handling
1 parent 2be2b82 commit 3023b23

File tree

3 files changed

+36
-3
lines changed

3 files changed

+36
-3
lines changed

state/clickhouse/clickhouse.go

Lines changed: 34 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ import (
2020
"errors"
2121
"fmt"
2222
"reflect"
23+
"strings"
2324
"time"
2425

2526
_ "github.com/ClickHouse/clickhouse-go/v2"
@@ -40,6 +41,8 @@ type clickhouseMetadata struct {
4041
ClickHouseURL string
4142
Database string
4243
Table string
44+
Username string
45+
Password string
4346
}
4447

4548
func NewClickHouseStateStore(logger logger.Logger) state.Store {
@@ -55,7 +58,28 @@ func (c *StateStore) Init(ctx context.Context, metadata state.Metadata) error {
5558
}
5659
c.config = config
5760

58-
db, err := sql.Open("clickhouse", c.config.ClickHouseURL)
61+
// Construct DSN with authentication if provided
62+
dsn := c.config.ClickHouseURL
63+
// If username and password are provided and not already in the URL, add them to the DSN
64+
if c.config.Username != "" && !strings.Contains(dsn, "username=") {
65+
if !strings.Contains(dsn, "?") {
66+
dsn += "?"
67+
} else {
68+
dsn += "&"
69+
}
70+
dsn += "username=" + c.config.Username
71+
}
72+
73+
if c.config.Password != "" && !strings.Contains(dsn, "password=") {
74+
if !strings.Contains(dsn, "?") {
75+
dsn += "?"
76+
} else if !strings.HasSuffix(dsn, "&") {
77+
dsn += "&"
78+
}
79+
dsn += "password=" + c.config.Password
80+
}
81+
82+
db, err := sql.Open("clickhouse", dsn)
5983
if err != nil {
6084
return fmt.Errorf("error opening connection: %v", err)
6185
}
@@ -295,6 +319,15 @@ func parseAndValidateMetadata(metadata state.Metadata) (clickhouseMetadata, erro
295319
return config, errors.New("ClickHouse table name is missing")
296320
}
297321

322+
// Get username and password if provided
323+
if val, ok := metadata.Properties["username"]; ok {
324+
config.Username = val
325+
}
326+
327+
if val, ok := metadata.Properties["password"]; ok {
328+
config.Password = val
329+
}
330+
298331
return config, nil
299332
}
300333

state/clickhouse/clickhouse_test.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ import (
2929
)
3030

3131
const (
32-
testURL = "tcp://localhost:9000"
32+
testURL = "clickhouse://localhost:9000"
3333
testDatabase = "dapr_test"
3434
testTable = "state_test"
3535
testUsername = "default"

tests/config/state/clickhouse/clickhouse.yml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ spec:
77
version: v1
88
metadata:
99
- name: clickhouseURL
10-
value: "tcp://localhost:9000"
10+
value: "clickhouse://localhost:9000"
1111
- name: databaseName
1212
value: "dapr_test"
1313
- name: tableName

0 commit comments

Comments
 (0)