-
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathsession.go
95 lines (82 loc) · 2.22 KB
/
session.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
package chdb
import (
"os"
"path/filepath"
chdbpurego "github.com/chdb-io/chdb-go/chdb-purego"
)
var (
globalSession *Session
)
type Session struct {
conn chdbpurego.ChdbConn
connStr string
path string
isTemp bool
}
// NewSession creates a new session with the given path.
// If path is empty, a temporary directory is created.
// Note: The temporary directory is removed when Close is called.
func NewSession(paths ...string) (*Session, error) {
if globalSession != nil {
return globalSession, nil
}
path := ""
if len(paths) > 0 {
path = paths[0]
}
isTemp := false
if path == "" {
// Create a temporary directory
tempDir, err := os.MkdirTemp("", "chdb_")
if err != nil {
return nil, err
}
path = tempDir
isTemp = true
}
connStr := path
conn, err := initConnection(connStr)
if err != nil {
return nil, err
}
globalSession = &Session{connStr: connStr, path: path, isTemp: isTemp, conn: conn}
return globalSession, nil
}
// Query calls `query_conn` function with the current connection and a default output format of "CSV" if not provided.
func (s *Session) Query(queryStr string, outputFormats ...string) (result chdbpurego.ChdbResult, err error) {
outputFormat := "CSV" // Default value
if len(outputFormats) > 0 {
outputFormat = outputFormats[0]
}
return s.conn.Query(queryStr, outputFormat)
}
// Close closes the session and removes the temporary directory
//
// temporary directory is created when NewSession was called with an empty path.
func (s *Session) Close() {
// Remove the temporary directory if it starts with "chdb_"
s.conn.Close()
if s.isTemp && filepath.Base(s.path)[:5] == "chdb_" {
s.Cleanup()
}
globalSession = nil
}
// Cleanup closes the session and removes the directory.
func (s *Session) Cleanup() {
// Remove the session directory, no matter if it is temporary or not
_ = os.RemoveAll(s.path)
s.conn.Close()
globalSession = nil
}
// Path returns the path of the session.
func (s *Session) Path() string {
return s.path
}
// ConnStr returns the current connection string used for the underlying connection
func (s *Session) ConnStr() string {
return s.connStr
}
// IsTemp returns whether the session is temporary.
func (s *Session) IsTemp() bool {
return s.isTemp
}