40 lines
1.1 KiB
Go
40 lines
1.1 KiB
Go
package repository
|
||
|
||
import (
|
||
"chat/internal/library/cassandra"
|
||
"context"
|
||
"fmt"
|
||
)
|
||
|
||
// InitSchema 初始化 Cassandra keyspace 和表結構
|
||
func InitSchema(ctx context.Context, db *cassandra.DB, keyspace string) error {
|
||
// 建立 keyspace(如果不存在)
|
||
createKeyspaceStmt := fmt.Sprintf(
|
||
"CREATE KEYSPACE IF NOT EXISTS %s WITH replication = {'class': 'SimpleStrategy', 'replication_factor': 1}",
|
||
keyspace,
|
||
)
|
||
session := db.GetSession()
|
||
if err := session.Query(createKeyspaceStmt, nil).Exec(); err != nil {
|
||
return fmt.Errorf("failed to create keyspace: %w", err)
|
||
}
|
||
|
||
// 建立 messages_by_room 表
|
||
createTableStmt := fmt.Sprintf(`
|
||
CREATE TABLE IF NOT EXISTS %s.messages_by_room (
|
||
room_id text,
|
||
bucket_day text,
|
||
ts bigint,
|
||
message_id text,
|
||
uid text,
|
||
content text,
|
||
PRIMARY KEY ((room_id, bucket_day), ts, message_id)
|
||
) WITH CLUSTERING ORDER BY (ts DESC, message_id DESC)
|
||
`, keyspace)
|
||
|
||
if err := session.Query(createTableStmt, nil).Exec(); err != nil {
|
||
return fmt.Errorf("failed to create messages_by_room table: %w", err)
|
||
}
|
||
|
||
return nil
|
||
}
|