Skip to content

Commit 93ce124

Browse files
committed
Add or edit documentation above methods
Signed-off-by: Matthew Kim <[email protected]>
1 parent ce7d924 commit 93ce124

File tree

9 files changed

+74
-14
lines changed

9 files changed

+74
-14
lines changed

connection.go

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -21,16 +21,19 @@ type conn struct {
2121
session *cli_service.TOpenSessionResp
2222
}
2323

24-
// The driver does not really implement prepared statements.
24+
// Prepare prepares a statement with the query bound to this connection.
2525
func (c *conn) Prepare(query string) (driver.Stmt, error) {
2626
return &stmt{conn: c, query: query}, nil
2727
}
2828

29-
// The driver does not really implement prepared statements.
29+
// PrepareContext prepares a statement with the query bound to this connection.
30+
// Currently, PrepareContext does not use context and is functionally equivalent to Prepare.
3031
func (c *conn) PrepareContext(ctx context.Context, query string) (driver.Stmt, error) {
3132
return &stmt{conn: c, query: query}, nil
3233
}
3334

35+
// Close closes the session.
36+
// sql package maintains a free pool of connections and only calls Close when there's a surplus of idle connections.
3437
func (c *conn) Close() error {
3538
log := logger.WithContext(c.id, "", "")
3639
ctx := driverctx.NewContextWithConnId(context.Background(), c.id)
@@ -46,16 +49,18 @@ func (c *conn) Close() error {
4649
return nil
4750
}
4851

49-
// Not supported in Databricks
52+
// Not supported in Databricks.
5053
func (c *conn) Begin() (driver.Tx, error) {
5154
return nil, errors.New(ErrTransactionsNotSupported)
5255
}
5356

54-
// Not supported in Databricks
57+
// Not supported in Databricks.
5558
func (c *conn) BeginTx(ctx context.Context, opts driver.TxOptions) (driver.Tx, error) {
5659
return nil, errors.New(ErrTransactionsNotSupported)
5760
}
5861

62+
// Ping attempts to verify that the server is accessible.
63+
// Returns ErrBadConn if ping fails and consequently DB.Ping will remove the conn from the pool.
5964
func (c *conn) Ping(ctx context.Context) error {
6065
log := logger.WithContext(c.id, driverctx.CorrelationIdFromContext(ctx), "")
6166
ctx = driverctx.NewContextWithConnId(ctx, c.id)
@@ -69,12 +74,13 @@ func (c *conn) Ping(ctx context.Context) error {
6974
return nil
7075
}
7176

72-
// Implementation of SessionResetter
77+
// ResetSession is called prior to executing a query on the connection.
78+
// The session with this driver does not have any important state to reset before re-use.
7379
func (c *conn) ResetSession(ctx context.Context) error {
74-
// For now our session does not have any important state to reset before re-use
7580
return nil
7681
}
7782

83+
// IsValid signals whether a connection is valid or if it should be discarded.
7884
func (c *conn) IsValid() bool {
7985
return c.session.GetStatus().StatusCode == cli_service.TStatusCode_SUCCESS_STATUS
8086
}

connector.go

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ type connector struct {
1818
cfg *config.Config
1919
}
2020

21+
// Connect returns a connection to the Databricks database from a connection pool.
2122
func (c *connector) Connect(ctx context.Context) (driver.Conn, error) {
2223
var catalogName *cli_service.TIdentifier
2324
var schemaName *cli_service.TIdentifier
@@ -69,6 +70,7 @@ func (c *connector) Connect(ctx context.Context) (driver.Conn, error) {
6970
return conn, nil
7071
}
7172

73+
// Driver returns underlying databricksDriver for compatibility with sql.DB Driver method
7274
func (c *connector) Driver() driver.Driver {
7375
return &databricksDriver{}
7476
}
@@ -77,7 +79,7 @@ var _ driver.Connector = (*connector)(nil)
7779

7880
type connOption func(*config.Config)
7981

80-
// NewConnector creates a connection that can be used with sql.OpenDB().
82+
// NewConnector creates a connection that can be used with `sql.OpenDB()`.
8183
// This is an easier way to set up the DB instead of having to construct a DSN string.
8284
func NewConnector(options ...connOption) (driver.Connector, error) {
8385
// config with default options

driver.go

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,8 @@ func init() {
1515

1616
type databricksDriver struct{}
1717

18+
// Open returns a new connection to Databricks database with a DSN string.
19+
// Use sql.Open("databricks", <dsn string>) after importing this driver package.
1820
func (d *databricksDriver) Open(dsn string) (driver.Conn, error) {
1921
cfg := config.WithDefaults()
2022
userCfg, err := config.ParseDSN(dsn)
@@ -28,6 +30,8 @@ func (d *databricksDriver) Open(dsn string) (driver.Conn, error) {
2830
return c.Connect(context.Background())
2931
}
3032

33+
// OpenConnector returns a new Connector.
34+
// Used by sql.DB to obtain a Connector and invoke its Connect method to obtain each needed connection.
3135
func (d *databricksDriver) OpenConnector(dsn string) (driver.Connector, error) {
3236
cfg := config.WithDefaults()
3337
ucfg, err := config.ParseDSN(dsn)

internal/client/client.go

Lines changed: 22 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -16,14 +16,16 @@ import (
1616
"github.com/pkg/errors"
1717
)
1818

19-
// this is used to generate test data. Developer should change this manually
19+
// RecordResults is used to generate test data. Developer should change this manually
2020
var RecordResults bool
2121
var resultIndex int
2222

2323
type ThriftServiceClient struct {
2424
*cli_service.TCLIServiceClient
2525
}
2626

27+
// OpenSession is a wrapper around the thrift operation OpenSession
28+
// If RecordResults is true, the results will be marshalled to JSON format and written to OpenSession<index>.json
2729
func (tsc *ThriftServiceClient) OpenSession(ctx context.Context, req *cli_service.TOpenSessionReq) (*cli_service.TOpenSessionResp, error) {
2830
msg, start := logger.Track("OpenSession")
2931
resp, err := tsc.TCLIServiceClient.OpenSession(ctx, req)
@@ -40,6 +42,8 @@ func (tsc *ThriftServiceClient) OpenSession(ctx context.Context, req *cli_servic
4042
return resp, CheckStatus(resp)
4143
}
4244

45+
// CloseSession is a wrapper around the thrift operation CloseSession
46+
// If RecordResults is true, the results will be marshalled to JSON format and written to CloseSession<index>.json
4347
func (tsc *ThriftServiceClient) CloseSession(ctx context.Context, req *cli_service.TCloseSessionReq) (*cli_service.TCloseSessionResp, error) {
4448
log := logger.WithContext(driverctx.ConnIdFromContext(ctx), driverctx.CorrelationIdFromContext(ctx), "")
4549
defer log.Duration(logger.Track("CloseSession"))
@@ -55,6 +59,8 @@ func (tsc *ThriftServiceClient) CloseSession(ctx context.Context, req *cli_servi
5559
return resp, CheckStatus(resp)
5660
}
5761

62+
// FetchResults is a wrapper around the thrift operation FetchResults
63+
// If RecordResults is true, the results will be marshalled to JSON format and written to FetchResults<index>.json
5864
func (tsc *ThriftServiceClient) FetchResults(ctx context.Context, req *cli_service.TFetchResultsReq) (*cli_service.TFetchResultsResp, error) {
5965
log := logger.WithContext(driverctx.ConnIdFromContext(ctx), driverctx.CorrelationIdFromContext(ctx), SprintGuid(req.OperationHandle.OperationId.GUID))
6066
defer log.Duration(logger.Track("FetchResults"))
@@ -70,6 +76,8 @@ func (tsc *ThriftServiceClient) FetchResults(ctx context.Context, req *cli_servi
7076
return resp, CheckStatus(resp)
7177
}
7278

79+
// GetResultSetMetadata is a wrapper around the thrift operation GetResultSetMetadata
80+
// If RecordResults is true, the results will be marshalled to JSON format and written to GetResultSetMetadata<index>.json
7381
func (tsc *ThriftServiceClient) GetResultSetMetadata(ctx context.Context, req *cli_service.TGetResultSetMetadataReq) (*cli_service.TGetResultSetMetadataResp, error) {
7482
log := logger.WithContext(driverctx.ConnIdFromContext(ctx), driverctx.CorrelationIdFromContext(ctx), SprintGuid(req.OperationHandle.OperationId.GUID))
7583
defer log.Duration(logger.Track("GetResultSetMetadata"))
@@ -85,6 +93,8 @@ func (tsc *ThriftServiceClient) GetResultSetMetadata(ctx context.Context, req *c
8593
return resp, CheckStatus(resp)
8694
}
8795

96+
// ExecuteStatement is a wrapper around the thrift operation ExecuteStatement
97+
// If RecordResults is true, the results will be marshalled to JSON format and written to ExecuteStatement<index>.json
8898
func (tsc *ThriftServiceClient) ExecuteStatement(ctx context.Context, req *cli_service.TExecuteStatementReq) (*cli_service.TExecuteStatementResp, error) {
8999
msg, start := logger.Track("ExecuteStatement")
90100
resp, err := tsc.TCLIServiceClient.ExecuteStatement(context.Background(), req)
@@ -106,6 +116,8 @@ func (tsc *ThriftServiceClient) ExecuteStatement(ctx context.Context, req *cli_s
106116
return resp, CheckStatus(resp)
107117
}
108118

119+
// GetOperationStatus is a wrapper around the thrift operation GetOperationStatus
120+
// If RecordResults is true, the results will be marshalled to JSON format and written to GetOperationStatus<index>.json
109121
func (tsc *ThriftServiceClient) GetOperationStatus(ctx context.Context, req *cli_service.TGetOperationStatusReq) (*cli_service.TGetOperationStatusResp, error) {
110122
log := logger.WithContext(driverctx.ConnIdFromContext(ctx), driverctx.CorrelationIdFromContext(ctx), SprintGuid(req.OperationHandle.OperationId.GUID))
111123
defer log.Duration(logger.Track("GetOperationStatus"))
@@ -121,6 +133,8 @@ func (tsc *ThriftServiceClient) GetOperationStatus(ctx context.Context, req *cli
121133
return resp, CheckStatus(resp)
122134
}
123135

136+
// CloseOperation is a wrapper around the thrift operation CloseOperation
137+
// If RecordResults is true, the results will be marshalled to JSON format and written to CloseOperation<index>.json
124138
func (tsc *ThriftServiceClient) CloseOperation(ctx context.Context, req *cli_service.TCloseOperationReq) (*cli_service.TCloseOperationResp, error) {
125139
log := logger.WithContext(driverctx.ConnIdFromContext(ctx), driverctx.CorrelationIdFromContext(ctx), SprintGuid(req.OperationHandle.OperationId.GUID))
126140
defer log.Duration(logger.Track("CloseOperation"))
@@ -136,6 +150,8 @@ func (tsc *ThriftServiceClient) CloseOperation(ctx context.Context, req *cli_ser
136150
return resp, CheckStatus(resp)
137151
}
138152

153+
// CancelOperation is a wrapper around the thrift operation CancelOperation
154+
// If RecordResults is true, the results will be marshalled to JSON format and written to CancelOperation<index>.json
139155
func (tsc *ThriftServiceClient) CancelOperation(ctx context.Context, req *cli_service.TCancelOperationReq) (*cli_service.TCancelOperationResp, error) {
140156
log := logger.WithContext(driverctx.ConnIdFromContext(ctx), driverctx.CorrelationIdFromContext(ctx), SprintGuid(req.OperationHandle.OperationId.GUID))
141157
defer log.Duration(logger.Track("CancelOperation"))
@@ -157,9 +173,8 @@ func (tsc *ThriftServiceClient) CancelOperation(ctx context.Context, req *cli_se
157173
// log.Debug().Msg(c.transport.response.Header.Get("x-thriftserver-error-message"))
158174
// log.Debug().Msg(c.transport.response.Header.Get("x-databricks-reason-phrase"))
159175

160-
// This is a wrapper of the http transport so we can have access to response code and headers
176+
// InitThriftClient is a wrapper of the http transport, so we can have access to response code and headers.
161177
// It is important to know the code and headers to know if we need to retry or not
162-
163178
func InitThriftClient(cfg *config.Config) (*ThriftServiceClient, error) {
164179
endpoint := cfg.ToEndpointURL()
165180
tcfg := &thrift.TConfiguration{
@@ -224,11 +239,13 @@ func InitThriftClient(cfg *config.Config) (*ThriftServiceClient, error) {
224239
return tsClient, nil
225240
}
226241

227-
// ThriftResponse respresents thrift rpc response
242+
// ThriftResponse represents the thrift rpc response
228243
type ThriftResponse interface {
229244
GetStatus() *cli_service.TStatus
230245
}
231246

247+
// CheckStatus checks the status code after a thrift operation.
248+
// Returns nil if the operation is successful or still executing, otherwise returns an error.
232249
func CheckStatus(resp interface{}) error {
233250
rpcresp, ok := resp.(ThriftResponse)
234251
if ok {
@@ -247,6 +264,7 @@ func CheckStatus(resp interface{}) error {
247264
return errors.New("thrift: invalid response")
248265
}
249266

267+
// SprintGuid is a convenience function to format a byte array into GUID.
250268
func SprintGuid(bts []byte) string {
251269
if len(bts) == 16 {
252270
return fmt.Sprintf("%x-%x-%x-%x-%x", bts[0:4], bts[4:6], bts[6:8], bts[8:10], bts[10:16])

internal/config/config.go

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ import (
1313
"github.com/pkg/errors"
1414
)
1515

16-
// Driver Configurations
16+
// Driver Configurations.
1717
// Only UserConfig are currently exposed to users
1818
type Config struct {
1919
UserConfig
@@ -34,6 +34,7 @@ type Config struct {
3434
ThriftDebugClientProtocol bool
3535
}
3636

37+
// ToEndpointURL generates the endpoint URL from Config that a Thrift client will connect to
3738
func (c *Config) ToEndpointURL() string {
3839
var userInfo string
3940
if c.AccessToken != "" {
@@ -43,6 +44,7 @@ func (c *Config) ToEndpointURL() string {
4344
return endpointUrl
4445
}
4546

47+
// DeepCopy returns a true deep copy of Config
4648
func (c *Config) DeepCopy() *Config {
4749
if c == nil {
4850
return nil
@@ -84,6 +86,7 @@ type UserConfig struct {
8486
SessionParams map[string]string
8587
}
8688

89+
// DeepCopy returns a true deep copy of UserConfig
8790
func (ucfg UserConfig) DeepCopy() UserConfig {
8891
var sessionParams map[string]string
8992
if ucfg.SessionParams != nil {
@@ -120,6 +123,7 @@ func (ucfg UserConfig) DeepCopy() UserConfig {
120123

121124
var defaultMaxRows = 100000
122125

126+
// WithDefaults provides default settings for optional fields in UserConfig
123127
func (ucfg UserConfig) WithDefaults() UserConfig {
124128
if ucfg.MaxRows <= 0 {
125129
ucfg.MaxRows = defaultMaxRows
@@ -131,6 +135,7 @@ func (ucfg UserConfig) WithDefaults() UserConfig {
131135
return ucfg
132136
}
133137

138+
// WithDefaults provides default settings for Config
134139
func WithDefaults() *Config {
135140
return &Config{
136141
UserConfig: UserConfig{}.WithDefaults(),
@@ -152,6 +157,7 @@ func WithDefaults() *Config {
152157

153158
}
154159

160+
// ParseDSN constructs UserConfig by parsing DSN string supplied to `sql.Open()`
155161
func ParseDSN(dsn string) (UserConfig, error) {
156162
fullDSN := dsn
157163
if !strings.HasPrefix(dsn, "https://") && !strings.HasPrefix(dsn, "http://") {

logger/logger.go

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,10 +14,24 @@ type DBSQLLogger struct {
1414
zerolog.Logger
1515
}
1616

17+
// Track is a simple utility function to use with logger to log a message with a timestamp.
18+
// Recommended to use in conjunction with Duration.
19+
//
20+
// For example:
21+
//
22+
// msg, start := log.Track("Run operation")
23+
// defer log.Duration(msg, start)
1724
func (l *DBSQLLogger) Track(msg string) (string, time.Time) {
1825
return msg, time.Now()
1926
}
2027

28+
// Duration logs a debug message with the time elapsed between the provided start and the current time.
29+
// Use in conjunction with Track.
30+
//
31+
// For example:
32+
//
33+
// msg, start := log.Track("Run operation")
34+
// defer log.Duration(msg, start)
2135
func (l *DBSQLLogger) Duration(msg string, start time.Time) {
2236
l.Debug().Msgf("%v elapsed time: %v", msg, time.Since(start))
2337
}
@@ -26,7 +40,7 @@ var Logger = &DBSQLLogger{
2640
zerolog.New(os.Stderr).With().Timestamp().Logger(),
2741
}
2842

29-
// enable pretty printing for interactive terminals and json for production.
43+
// Enable pretty printing for interactive terminals and json for production.
3044
func init() {
3145
// for tty terminal enable pretty logs
3246
if isatty.IsTerminal(os.Stdout.Fd()) && runtime.GOOS != "windows" {
@@ -114,7 +128,7 @@ func Err(err error) *zerolog.Event {
114128
return Logger.Err(err)
115129
}
116130

117-
// WithContext sets connectionId, correlationId, and queryID to be used as fields.
131+
// WithContext sets connectionId, correlationId, and queryId to be used as fields.
118132
func WithContext(connectionId string, correlationId string, queryId string) *DBSQLLogger {
119133
return &DBSQLLogger{Logger.With().Str("connId", connectionId).Str("corrId", correlationId).Str("queryId", queryId).Logger()}
120134
}

result.go

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,10 +9,13 @@ type result struct {
99

1010
var _ driver.Result = (*result)(nil)
1111

12+
// LastInsertId returns the database's auto-generated ID after an insert into a table.
13+
// This is currently not really implemented for this driver and will always return 0.
1214
func (res *result) LastInsertId() (int64, error) {
1315
return res.InsertId, nil
1416
}
1517

18+
// RowsAffected returns the number of rows affected by the query.
1619
func (res *result) RowsAffected() (int64, error) {
1720
return res.AffectedRows, nil
1821
}

rows.go

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,8 @@ var errRowsNoClient = "databricks: instance of Rows missing client"
4343
var errRowsNilRows = "databricks: nil Rows instance"
4444
var errRowsParseValue = "databricks: unable to parse %s value '%s' from column %s"
4545

46+
// NewRows generates a new rows object given the rows' fields.
47+
// NewRows will also parse directResults if it is available for some rows' fields.
4648
func NewRows(connID string, corrId string, client cli_service.TCLIService, opHandle *cli_service.TOperationHandle, pageSize int64, location *time.Location, directResults *cli_service.TSparkDirectResults) driver.Rows {
4749
r := &rows{
4850
connId: connID,

statement.go

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,15 +17,20 @@ func (s *stmt) Close() error {
1717
return nil
1818
}
1919

20+
// NumInput returns -1 and the sql package will not sanity check Exec or Query argument counts.
2021
func (s *stmt) NumInput() int {
2122
return -1
2223
}
2324

25+
// Exec is not implemented.
26+
//
2427
// Deprecated: Use StmtExecContext instead.
2528
func (s *stmt) Exec(args []driver.Value) (driver.Result, error) {
2629
return nil, errors.New(ErrNotImplemented)
2730
}
2831

32+
// Query is not implemented.
33+
//
2934
// Deprecated: Use StmtQueryContext instead.
3035
func (s *stmt) Query(args []driver.Value) (driver.Rows, error) {
3136
return nil, errors.New(ErrNotImplemented)

0 commit comments

Comments
 (0)