-
Notifications
You must be signed in to change notification settings - Fork 32
Expand file tree
/
Copy pathdriver.go
More file actions
1785 lines (1635 loc) · 64.8 KB
/
driver.go
File metadata and controls
1785 lines (1635 loc) · 64.8 KB
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package spannerdriver
import (
"context"
"crypto/tls"
"crypto/x509"
"database/sql"
"database/sql/driver"
"errors"
"fmt"
"io"
"log/slog"
"math/big"
"os"
"regexp"
"runtime"
"runtime/debug"
"strconv"
"strings"
"sync"
"time"
"cloud.google.com/go/civil"
"cloud.google.com/go/spanner"
adminapi "cloud.google.com/go/spanner/admin/database/apiv1"
"cloud.google.com/go/spanner/admin/database/apiv1/databasepb"
"cloud.google.com/go/spanner/apiv1/spannerpb"
"github.com/google/uuid"
"github.com/googleapis/gax-go/v2"
"github.com/googleapis/go-sql-spanner/connectionstate"
"github.com/googleapis/go-sql-spanner/parser"
"google.golang.org/api/iterator"
"google.golang.org/api/option"
"google.golang.org/api/option/internaloption"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/proto"
)
const ModuleVersion = "1.25.0" // x-release-please-version
const userAgent = "go-sql-spanner/1.25.0" // x-release-please-version
const gormModule = "github.com/googleapis/go-gorm-spanner"
const gormUserAgent = "go-gorm-spanner"
const DefaultStatementCacheSize = 1000
var defaultStatementCacheSize int
// LevelNotice is the default logging level that the Spanner database/sql driver
// uses for informational logs. This level is deliberately chosen to be one level
// lower than the default log level, which is slog.LevelInfo. This prevents the
// driver from adding noise to any default logger that has been set for the
// application.
const LevelNotice = slog.LevelInfo - 1
const experimentalHostProject = "default"
const experimentalHostInstance = "default"
// Logger that discards everything and skips (almost) all logs.
var noopLogger = slog.New(slog.NewTextHandler(io.Discard, &slog.HandlerOptions{Level: slog.LevelError + 1}))
// dsnRegExpString describes the valid values for a dsn (connection name) for
// Google Cloud Spanner. The string consists of the following parts:
// 1. (Optional) Host: The host name and port number to connect to.
// 2. Database name: The database name to connect to in the format `projects/my-project/instances/my-instance/databases/my-database`
// 3. (Optional) Parameters: One or more parameters in the format `name=value`. Multiple entries are separated by `;`.
// The supported parameters are:
// - credentials: File name for the credentials to use. The connection will use the default credentials of the
// environment if no credentials file is specified in the connection string.
// - usePlainText: Boolean that indicates whether the connection should use plain text communication or not. Set this
// to true to connect to local mock servers that do not use SSL.
// - retryAbortsInternally: Boolean that indicates whether the connection should automatically retry aborted errors.
// The default is true.
// - disableRouteToLeader: Boolean that indicates if all the requests of type read-write and PDML
// need to be routed to the leader region.
// The default is false
// - enableEndToEndTracing: Boolean that indicates if end-to-end tracing is enabled
// The default is false
// - minSessions (DEPRECATED): The minimum number of sessions in the backing session pool. The default is 100. This option is deprecated, as the driver by default uses a single multiplexed session for all operations.
// - maxSessions (DEPRECATED): The maximum number of sessions in the backing session pool. The default is 400. This option is deprecated, as the driver by default uses a single multiplexed session for all operations.
// - numChannels: The number of gRPC channels to use to communicate with Cloud Spanner. The default is 4.
// - optimizerVersion: Sets the default query optimizer version to use for this connection.
// - optimizerStatisticsPackage: Sets the default query optimizer statistic package to use for this connection.
// - rpcPriority: Sets the priority for all RPC invocations from this connection (HIGH/MEDIUM/LOW). The default is HIGH.
//
// Example: `localhost:9010/projects/test-project/instances/test-instance/databases/test-database;usePlainText=true;disableRouteToLeader=true;enableEndToEndTracing=true`
var dsnRegExp = regexp.MustCompile(`^((?P<HOSTGROUP>[\w.-]+(?:\.[\w\.-]+)*[\w\-\._~:#\[\]@!\$&'\(\)\*\+,=.]+)/)?(projects/(?P<PROJECTGROUP>(([a-z]|[-.:]|[0-9])+|(DEFAULT_PROJECT_ID))))?((?:/)?instances/(?P<INSTANCEGROUP>([a-z]|[-]|[0-9])+))?((?:/)?databases/(?P<DATABASEGROUP>([a-z]|[-]|[_]|[0-9])+))?(([\?|;])(?P<PARAMSGROUP>.*))?$`)
var _ driver.DriverContext = &Driver{}
var spannerDriver *Driver
func init() {
spannerDriver = &Driver{connectors: make(map[string]*connector), connectorUsageCount: make(map[string]int)}
sql.Register("spanner", spannerDriver)
determineDefaultStatementCacheSize()
}
func determineDefaultStatementCacheSize() {
if defaultCacheSizeString, ok := os.LookupEnv("SPANNER_DEFAULT_STATEMENT_CACHE_SIZE"); ok {
if defaultCacheSize, err := strconv.Atoi(defaultCacheSizeString); err == nil {
defaultStatementCacheSize = defaultCacheSize
} else {
defaultStatementCacheSize = DefaultStatementCacheSize
}
} else {
defaultStatementCacheSize = DefaultStatementCacheSize
}
}
// SpannerResult is the result type returned by Spanner connections for
// DML batches. This interface extends the standard sql.Result interface
// and adds a BatchRowsAffected function that returns the affected rows
// per statement.
type SpannerResult interface {
driver.Result
// BatchRowsAffected returns the affected rows per statement in a DML batch.
// It returns an error if the statement was not a DML batch.
BatchRowsAffected() ([]int64, error)
// OperationID returns the operation ID for a DDL statement that was executed
// in asynchronous mode. It returns an error if the statement was not a DDL
// statement or if it was not executed in asynchronous mode.
OperationID() (string, error)
}
// ExecOptions can be passed in as an argument to the Query, QueryContext,
// Exec, and ExecContext functions to specify additional execution options
// for a statement.
type ExecOptions struct {
// DecodeOption indicates how the returned rows should be decoded.
DecodeOption DecodeOption
// DecodeToNativeArrays determines whether arrays that have a Go
// native type should use that. This option has an effect on arrays
// that contain:
// * BOOL
// * INT64 and ENUM
// * STRING
// * FLOAT32
// * FLOAT64
// * DATE
// * TIMESTAMP
// These arrays will by default be decoded to the following types:
// * []spanner.NullBool
// * []spanner.NullInt64
// * []spanner.NullString
// * []spanner.NullFloat32
// * []spanner.NullFloat64
// * []spanner.NullDate
// * []spanner.NullTime
// By setting DecodeToNativeArrays, these arrays will instead be
// decoded to:
// * []bool
// * []int64
// * []string
// * []float32
// * []float64
// * []civil.Date
// * []time.Time
// If this option is used with rows that contains an array with
// at least one NULL element, the decoding will fail.
// This option has no effect on arrays of type JSON, NUMERIC and BYTES.
DecodeToNativeArrays bool
// TransactionOptions are the transaction options that will be used for
// the transaction that is started by the statement.
TransactionOptions spanner.TransactionOptions
// QueryOptions are the query options that will be used for the statement.
QueryOptions spanner.QueryOptions
// TimestampBound is the timestamp bound that will be used for the statement
// if it is a query outside a transaction. Setting this option will override
// the default TimestampBound that is set on the connection.
TimestampBound *spanner.TimestampBound
// PartitionedQueryOptions are used for partitioned queries, and ignored
// for all other statements.
PartitionedQueryOptions PartitionedQueryOptions
// AutoCommitDMLMode determines the type of transaction that DML statements
// that are executed outside explicit transactions use.
AutocommitDMLMode AutocommitDMLMode
// ReturnResultSetMetadata instructs the driver to return an additional result
// set with the full spannerpb.ResultSetMetadata of the query. This result set
// contains one row and one column, and the value in that cell is the
// spannerpb.ResultSetMetadata that was returned by Spanner when executing the
// query. This result set will be the first result set in the sql.Rows object
// that is returned.
//
// You have to call [sql.Rows.NextResultSet] to move to the result set that
// contains the actual query data.
ReturnResultSetMetadata bool
// ReturnResultSetStats instructs the driver to return an additional result
// set with the full spannerpb.ResultSetStats of the query. This result set
// contains one row and one column, and the value in that cell is the
// spannerpb.ResultSetStats that was returned by Spanner when executing the
// query. This result set will be the last result set in the sql.Rows object
// that is returned.
//
// You have to call [sql.Rows.NextResultSet] after fetching all query data in
// order to move to the result set that contains the spannerpb.ResultSetStats.
ReturnResultSetStats bool
// DirectExecuteQuery determines whether a query is executed directly when the
// [sql.DB.QueryContext] method is called, or whether the actual query execution
// is delayed until the first call to [sql.Rows.Next]. The default is to delay
// the execution. Set this flag to true to execute the query directly when
// [sql.DB.QueryContext] is called.
DirectExecuteQuery bool
// DirectExecuteContext is the context that is used for the execution of a query
// when DirectExecuteQuery is enabled.
DirectExecuteContext context.Context
// PropertyValues contains a list of connection state property values that
// should be used while executing the statement. These values will only be used for
// this statement, and will not be persisted on the connection.
PropertyValues []PropertyValue
}
func (dest *ExecOptions) merge(src *ExecOptions) {
if src == nil || dest == nil {
return
}
if src.DecodeOption != DecodeOptionNormal {
dest.DecodeOption = src.DecodeOption
}
if src.DecodeToNativeArrays {
dest.DecodeToNativeArrays = src.DecodeToNativeArrays
}
if src.ReturnResultSetStats {
dest.ReturnResultSetStats = src.ReturnResultSetStats
}
if src.ReturnResultSetMetadata {
dest.ReturnResultSetMetadata = src.ReturnResultSetMetadata
}
if src.DirectExecuteQuery {
dest.DirectExecuteQuery = src.DirectExecuteQuery
}
if src.DirectExecuteContext != nil {
dest.DirectExecuteContext = src.DirectExecuteContext
}
if src.AutocommitDMLMode != Unspecified {
dest.AutocommitDMLMode = src.AutocommitDMLMode
}
if src.TimestampBound != nil {
dest.TimestampBound = src.TimestampBound
}
if src.PropertyValues != nil {
dest.PropertyValues = append(dest.PropertyValues, src.PropertyValues...)
}
(&dest.PartitionedQueryOptions).merge(&src.PartitionedQueryOptions)
mergeQueryOptions(&dest.QueryOptions, &src.QueryOptions)
mergeTransactionOptions(&dest.TransactionOptions, &src.TransactionOptions)
}
func mergeTransactionOptions(dest *spanner.TransactionOptions, src *spanner.TransactionOptions) {
if src == nil || dest == nil {
return
}
if src.ExcludeTxnFromChangeStreams {
dest.ExcludeTxnFromChangeStreams = src.ExcludeTxnFromChangeStreams
}
if src.TransactionTag != "" {
dest.TransactionTag = src.TransactionTag
}
if src.ReadLockMode != spannerpb.TransactionOptions_ReadWrite_READ_LOCK_MODE_UNSPECIFIED {
dest.ReadLockMode = src.ReadLockMode
}
if src.IsolationLevel != spannerpb.TransactionOptions_ISOLATION_LEVEL_UNSPECIFIED {
dest.IsolationLevel = src.IsolationLevel
}
if src.CommitPriority != spannerpb.RequestOptions_PRIORITY_UNSPECIFIED {
dest.CommitPriority = src.CommitPriority
}
if src.BeginTransactionOption != spanner.DefaultBeginTransaction {
dest.BeginTransactionOption = src.BeginTransactionOption
}
mergeCommitOptions(&dest.CommitOptions, &src.CommitOptions)
}
func mergeCommitOptions(dest *spanner.CommitOptions, src *spanner.CommitOptions) {
if src == nil || dest == nil {
return
}
if src.ReturnCommitStats {
dest.ReturnCommitStats = src.ReturnCommitStats
}
if src.MaxCommitDelay != nil {
dest.MaxCommitDelay = src.MaxCommitDelay
}
}
func mergeQueryOptions(dest *spanner.QueryOptions, src *spanner.QueryOptions) {
if src == nil || dest == nil {
return
}
if src.ExcludeTxnFromChangeStreams {
dest.ExcludeTxnFromChangeStreams = src.ExcludeTxnFromChangeStreams
}
if src.DataBoostEnabled {
dest.DataBoostEnabled = src.DataBoostEnabled
}
if src.LastStatement {
dest.LastStatement = src.LastStatement
}
if src.Options != nil {
if dest.Options != nil {
proto.Merge(dest.Options, src.Options)
} else {
dest.Options = src.Options
}
}
if src.DirectedReadOptions != nil {
if dest.DirectedReadOptions == nil {
dest.DirectedReadOptions = src.DirectedReadOptions
} else {
proto.Merge(dest.DirectedReadOptions, src.DirectedReadOptions)
}
}
if src.Mode != nil {
dest.Mode = src.Mode
}
if src.Priority != spannerpb.RequestOptions_PRIORITY_UNSPECIFIED {
dest.Priority = src.Priority
}
if src.RequestTag != "" {
dest.RequestTag = src.RequestTag
}
}
type DecodeOption int
const (
// DecodeOptionNormal decodes into idiomatic Go types (e.g. bool, string, int64, etc.)
DecodeOptionNormal DecodeOption = iota
// DecodeOptionProto does not decode the returned rows at all, and instead just returns
// the underlying protobuf objects. Use this for advanced use-cases where you want
// direct access to the underlying values.
// All values should be scanned into an instance of spanner.GenericColumnValue like this:
//
// var v spanner.GenericColumnValue
// row.Scan(&v)
DecodeOptionProto
)
// Driver represents a Google Cloud Spanner database/sql driver.
type Driver struct {
mu sync.Mutex
connectors map[string]*connector
connectorUsageCount map[string]int
}
// Open opens a connection to a Google Cloud Spanner database.
// Use fully qualified string:
//
// Example: projects/$PROJECT/instances/$INSTANCE/databases/$DATABASE
func (d *Driver) Open(name string) (driver.Conn, error) {
c, err := newOrCachedConnector(d, name)
if err != nil {
return nil, err
}
return openDriverConn(context.Background(), c)
}
func (d *Driver) OpenConnector(name string) (driver.Connector, error) {
return newOrCachedConnector(d, name)
}
// CreateConnector creates a new driver.Connector for Spanner.
// A connector can be passed in to sql.OpenDB to obtain a sql.DB.
//
// Use this method if you want to supply custom configuration for your Spanner
// connections, and cache the connector that is returned in your application.
// The same connector should be used to create all connections that should share
// the same configuration and the same underlying Spanner client.
//
// Note: This function always creates a new connector, even if one with the same
// configuration has been created previously.
func CreateConnector(config ConnectorConfig) (driver.Connector, error) {
return createConnector(spannerDriver, config)
}
// ConnectorConfig contains the configuration for a Spanner driver.Connector.
type ConnectorConfig struct {
// Host is the Spanner host that the connector should connect to.
// Leave this empty to use the standard Spanner API endpoint.
Host string
// The expected server name in the TLS handshake.
// Leave this empty to use the endpoint hostname.
Authority string
// Project, Instance, and Database identify the database that the connector
// should create connections for.
Project string
Instance string
Database string
// StatementCacheSize is the size of the internal cache that is used for
// connectors that are created from this ConnectorConfig. This cache stores
// the result of parsing SQL statements for query parameters and the type of
// statement (Query / DML / DDL).
// The default size is 1000. This default can also be overridden by setting
// the environment variable SPANNER_DEFAULT_STATEMENT_CACHE_SIZE.
StatementCacheSize int
// DisableStatementCache disables the use of a statement cache.
DisableStatementCache bool
// AutoConfigEmulator automatically creates a connection for the emulator
// and also automatically creates the Instance and Database on the emulator.
// Setting this option to true will:
// 1. Set the SPANNER_EMULATOR_HOST environment variable to either Host or
// 'localhost:9010' if no other host has been set.
// 2. Use plain text communication and NoCredentials.
// 3. Automatically create the Instance and the Database on the emulator if
// any of those do not yet exist.
AutoConfigEmulator bool
// ConnectionStateType determines the behavior of changes to connection state
// during a transaction.
// connectionstate.TypeTransactional means that changes during a transaction
// are only persisted if the transaction is committed. If the transaction is
// rolled back, any changes to the connection state during the transaction
// will be lost.
// connectionstate.TypeNonTransactional means that changes to the connection
// state during a transaction are persisted directly, and are always visible
// after the transaction, regardless whether the transaction was committed or
// rolled back.
ConnectionStateType connectionstate.Type
// Params contains key/value pairs for commonly used configuration parameters
// for connections. The valid values are the same as the parameters that can
// be added to a connection string.
Params map[string]string
// The initial values for automatic DML batching.
// The values in the Params map take precedence above these.
AutoBatchDml bool
AutoBatchDmlUpdateCount int64
DisableAutoBatchDmlUpdateCountVerification bool
// IsolationLevel is the default isolation level for read/write transactions.
IsolationLevel sql.IsolationLevel
// BeginTransactionOption determines the default for how to begin transactions.
// The Spanner database/sql driver uses spanner.InlinedBeginTransaction by default
// for both read-only and read/write transactions.
BeginTransactionOption spanner.BeginTransactionOption
// DecodeToNativeArrays determines whether arrays that have a Go native
// type should be decoded to those types rather than the corresponding
// spanner.NullTypeName type.
// Enabling this option will for example decode ARRAY<BOOL> to []bool instead
// of []spanner.NullBool.
//
// See ExecOptions.DecodeToNativeArrays for more information.
DecodeToNativeArrays bool
logger *slog.Logger
name string
// Configurator is called with the spanner.ClientConfig and []option.ClientOption
// that will be used to create connections by the driver.Connector. Use this
// function to set any further advanced configuration options that cannot be set
// with a standard key/value pair in the Params map.
Configurator func(config *spanner.ClientConfig, opts *[]option.ClientOption) `json:"-"`
}
func (cc *ConnectorConfig) String() string {
return cc.name
}
// ExtractConnectorConfig extracts a ConnectorConfig for Spanner from the given
// data source name.
func ExtractConnectorConfig(dsn string) (ConnectorConfig, error) {
match := dsnRegExp.FindStringSubmatch(dsn)
if match == nil {
return ConnectorConfig{}, spanner.ToSpannerError(status.Errorf(codes.InvalidArgument, "invalid connection string: %s", dsn))
}
matches := make(map[string]string)
for i, name := range dsnRegExp.SubexpNames() {
if i != 0 && name != "" {
matches[name] = match[i]
}
}
paramsString := matches["PARAMSGROUP"]
params, err := extractConnectorParams(paramsString)
if err != nil {
return ConnectorConfig{}, err
}
c := ConnectorConfig{
Host: matches["HOSTGROUP"],
Project: matches["PROJECTGROUP"],
Instance: matches["INSTANCEGROUP"],
Database: matches["DATABASEGROUP"],
Params: params,
name: dsn,
}
if strings.EqualFold(params[propertyIsExperimentalHost.Key()], "true") {
if c.Host == "" {
return ConnectorConfig{}, spanner.ToSpannerError(status.Errorf(codes.InvalidArgument, "host must be specified for experimental host endpoint"))
}
c.Configurator = func(config *spanner.ClientConfig, opts *[]option.ClientOption) {
config.IsExperimentalHost = true
}
if matches["INSTANCEGROUP"] == "" {
c.Instance = experimentalHostInstance
}
c.Project = experimentalHostProject
} else {
if c.Project == "" {
return ConnectorConfig{}, spanner.ToSpannerError(status.Errorf(codes.InvalidArgument, "project must be specified in connection string"))
}
if c.Instance == "" {
return ConnectorConfig{}, spanner.ToSpannerError(status.Errorf(codes.InvalidArgument, "instance must be specified in connection string"))
}
}
return c, nil
}
func extractConnectorParams(paramsString string) (map[string]string, error) {
params := make(map[string]string)
if paramsString == "" {
return params, nil
}
keyValuePairs := strings.Split(paramsString, ";")
for _, keyValueString := range keyValuePairs {
if keyValueString == "" {
// Ignore empty parameter entries in the string, for example if
// the connection string contains a trailing ';'.
continue
}
keyValue := strings.SplitN(keyValueString, "=", 2)
if keyValue == nil || len(keyValue) != 2 {
return nil, spanner.ToSpannerError(status.Errorf(codes.InvalidArgument, "invalid connection property: %s", keyValueString))
}
params[strings.ToLower(keyValue[0])] = keyValue[1]
}
return params, nil
}
type connector struct {
driver *Driver
connectorConfig ConnectorConfig
initialPropertyValues map[string]connectionstate.ConnectionPropertyValue
cacheKey string
logger *slog.Logger
closerMu sync.RWMutex
closed bool
// spannerClientConfig represents the optional advanced configuration to be used
// by the Google Cloud Spanner client.
spannerClientConfig spanner.ClientConfig
// options represent the optional Google Cloud client options
// to be passed to the underlying client.
options []option.ClientOption
// retryAbortsInternally determines whether Aborted errors will automatically be
// retried internally (when possible), or whether all aborted errors will be
// propagated to the caller. This option is enabled by default.
retryAbortsInternally bool
clientMu sync.Mutex
client *spanner.Client
clientErr error
adminClient *adminapi.DatabaseAdminClient
adminClientErr error
connCount int32
parser *parser.StatementParser
}
func newOrCachedConnector(d *Driver, dsn string) (*connector, error) {
d.mu.Lock()
defer d.mu.Unlock()
if d.connectors == nil {
d.connectors = make(map[string]*connector)
}
if d.connectorUsageCount == nil {
d.connectorUsageCount = make(map[string]int)
}
if c, ok := d.connectors[dsn]; ok {
d.connectorUsageCount[dsn]++
return c, nil
}
connectorConfig, err := ExtractConnectorConfig(dsn)
if err != nil {
return nil, err
}
c, err := createConnector(d, connectorConfig)
if err != nil {
return nil, err
}
c.cacheKey = dsn
d.connectors[dsn] = c
d.connectorUsageCount[dsn] = 1
return c, nil
}
func createConnector(d *Driver, connectorConfig ConnectorConfig) (*connector, error) {
opts := make([]option.ClientOption, 0)
initialPropertyValues, err := connectionstate.ExtractValues(connectionProperties, connectorConfig.Params)
if err != nil {
return nil, err
}
state := createConfiguredConnectionState(initialPropertyValues)
assignPropertyValueIfExists(state, propertyEndpoint, &connectorConfig.Host)
if connectorConfig.Host != "" {
opts = append(opts, option.WithEndpoint(connectorConfig.Host))
}
assignPropertyValueIfExists(state, propertyAuthority, &connectorConfig.Authority)
if connectorConfig.Authority != "" {
opts = append(opts, option.WithGRPCDialOption(grpc.WithAuthority(connectorConfig.Authority)))
}
if val := propertyCredentials.GetValueOrDefault(state); val != "" {
// TODO: Replace with option.WithAuthCredentialsFile and a config option to fall back to this.
//lint:ignore SA1019 Needs a change that is backwards compatible
opts = append(opts, option.WithCredentialsFile(val))
}
if val := propertyCredentialsJson.GetValueOrDefault(state); val != "" {
// TODO: Replace with option.WithAuthCredentialsJSON and a config option to fall back to this.
//lint:ignore SA1019 Needs a change that is backwards compatible
opts = append(opts, option.WithCredentialsJSON([]byte(val)))
}
config := spanner.ClientConfig{
//lint:ignore SA1019 Needs a change that is backwards compatible
SessionPoolConfig: spanner.DefaultSessionPoolConfig,
}
// Disable client config logging by default.
if _, found := os.LookupEnv("GOOGLE_CLOUD_SPANNER_DISABLE_LOG_CLIENT_OPTIONS"); !found {
_ = os.Setenv("GOOGLE_CLOUD_SPANNER_DISABLE_LOG_CLIENT_OPTIONS", "true")
}
if propertyUsePlainText.GetValueOrDefault(state) {
opts = append(opts,
option.WithGRPCDialOption(grpc.WithTransportCredentials(insecure.NewCredentials())),
option.WithoutAuthentication())
config.DisableNativeMetrics = true
}
assignPropertyValueIfExists(state, propertyAutoBatchDml, &connectorConfig.AutoBatchDml)
assignPropertyValueIfExists(state, propertyAutoBatchDmlUpdateCount, &connectorConfig.AutoBatchDmlUpdateCount)
assignNegatedPropertyValueIfExists(state, propertyAutoBatchDmlUpdateCountVerification, &connectorConfig.DisableAutoBatchDmlUpdateCountVerification)
//lint:ignore SA1019 Needs a change that is backwards compatible
assignPropertyValueIfExists(state, propertyMinSessions, &config.MinOpened)
//lint:ignore SA1019 Needs a change that is backwards compatible
assignPropertyValueIfExists(state, propertyMaxSessions, &config.MaxOpened)
if val := propertyNumChannels.GetValueOrDefault(state); val > 0 {
opts = append(opts, option.WithGRPCConnectionPool(val))
}
assignPropertyValueIfExists(state, propertyRpcPriority, &config.ReadOptions.Priority)
assignPropertyValueIfExists(state, propertyRpcPriority, &config.TransactionOptions.CommitPriority)
assignPropertyValueIfExists(state, propertyRpcPriority, &config.QueryOptions.Priority)
config.QueryOptions.Options = &spannerpb.ExecuteSqlRequest_QueryOptions{}
assignPropertyValueIfExists(state, propertyOptimizerVersion, &config.QueryOptions.Options.OptimizerVersion)
assignPropertyValueIfExists(state, propertyOptimizerStatisticsPackage, &config.QueryOptions.Options.OptimizerStatisticsPackage)
if config.QueryOptions.Options.OptimizerVersion == "" && config.QueryOptions.Options.OptimizerStatisticsPackage == "" {
config.QueryOptions.Options = nil
}
assignPropertyValueIfExists(state, propertyDatabaseRole, &config.DatabaseRole)
assignPropertyValueIfExists(state, propertyDisableRouteToLeader, &config.DisableRouteToLeader)
assignPropertyValueIfExists(state, propertyEnableEndToEndTracing, &config.EnableEndToEndTracing)
assignPropertyValueIfExists(state, propertyDisableNativeMetrics, &config.DisableNativeMetrics)
assignPropertyValueIfExists(state, propertyDecodeToNativeArrays, &connectorConfig.DecodeToNativeArrays)
assignPropertyValueIfExists(state, propertyAutoConfigEmulator, &connectorConfig.AutoConfigEmulator)
assignPropertyValueIfExists(state, propertyConnectionStateType, &connectorConfig.ConnectionStateType)
assignPropertyValueIfExists(state, propertyIsolationLevel, &connectorConfig.IsolationLevel)
assignPropertyValueIfExists(state, propertyBeginTransactionOption, &connectorConfig.BeginTransactionOption)
assignPropertyValueIfExists(state, propertyStatementCacheSize, &connectorConfig.StatementCacheSize)
assignPropertyValueIfExists(state, propertyDisableStatementCache, &connectorConfig.DisableStatementCache)
// Check if it is Spanner gorm that is creating the connection.
// If so, we should set a different user-agent header than the
// default go-sql-spanner header.
if isConnectionFromGorm() {
config.UserAgent = spannerGormHeader()
} else {
config.UserAgent = userAgent
}
var logger *slog.Logger
if connectorConfig.logger == nil {
d := slog.Default()
if d == nil {
logger = noopLogger
} else {
logger = d
}
} else {
logger = connectorConfig.logger
}
logger = logger.With("config", &connectorConfig)
if connectorConfig.Configurator != nil {
connectorConfig.Configurator(&config, &opts)
}
if config.IsExperimentalHost {
var caCertFile string
var clientCertFile string
var clientCertKey string
assignPropertyValueIfExists(state, propertyCaCertFile, &caCertFile)
assignPropertyValueIfExists(state, propertyClientCertFile, &clientCertFile)
assignPropertyValueIfExists(state, propertyClientCertKey, &clientCertKey)
if caCertFile != "" {
credOpts, err := createExperimentalHostCredentials(caCertFile, clientCertFile, clientCertKey)
if err != nil {
return nil, err
}
opts = append(opts, credOpts)
opts = append(opts, option.WithoutAuthentication())
}
}
if connectorConfig.AutoConfigEmulator {
if connectorConfig.Host == "" {
connectorConfig.Host = "localhost:9010"
}
schemeRemoved := regexp.MustCompile("^(http://|https://|passthrough:///)").ReplaceAllString(connectorConfig.Host, "")
emulatorOpts := []option.ClientOption{
option.WithEndpoint("passthrough:///" + schemeRemoved),
option.WithGRPCDialOption(grpc.WithTransportCredentials(insecure.NewCredentials())),
option.WithoutAuthentication(),
internaloption.SkipDialSettingsValidation(),
}
opts = append(emulatorOpts, opts...)
if err := autoConfigEmulator(context.Background(), connectorConfig.Host, connectorConfig.Project, connectorConfig.Instance, connectorConfig.Database, propertyDialect.GetValueOrDefault(state), opts); err != nil {
return nil, err
}
}
c := &connector{
driver: d,
connectorConfig: connectorConfig,
initialPropertyValues: initialPropertyValues,
logger: logger,
spannerClientConfig: config,
options: opts,
// TODO: Remove retryAbortsInternally from this struct
retryAbortsInternally: propertyRetryAbortsInternally.GetValueOrDefault(state),
}
addStateFromConnectorConfig(c, c.initialPropertyValues)
return c, nil
}
func assignPropertyValueIfExists[T comparable](state *connectionstate.ConnectionState, property *connectionstate.TypedConnectionProperty[T], field *T) {
if val, _, err := property.GetValueOrError(state); err == nil {
*field = val
}
}
func assignNegatedPropertyValueIfExists(state *connectionstate.ConnectionState, property *connectionstate.TypedConnectionProperty[bool], field *bool) {
if val, _, err := property.GetValueOrError(state); err == nil {
*field = !val
}
}
func isConnectionFromGorm() bool {
callers := make([]uintptr, 20)
length := runtime.Callers(0, callers)
frames := runtime.CallersFrames(callers[0:length])
gorm := false
for frame, more := frames.Next(); more; {
if strings.HasPrefix(frame.Function, gormModule) {
gorm = true
break
}
frame, more = frames.Next()
}
return gorm
}
func spannerGormHeader() string {
info, ok := debug.ReadBuildInfo()
if !ok {
return gormUserAgent
}
for _, module := range info.Deps {
if module.Path == gormModule {
return fmt.Sprintf("%s/%s", gormUserAgent, module.Version)
}
}
return gormUserAgent
}
func (c *connector) Connect(ctx context.Context) (driver.Conn, error) {
c.closerMu.RLock()
defer c.closerMu.RUnlock()
if c.closed {
return nil, fmt.Errorf("connector has been closed")
}
return openDriverConn(ctx, c)
}
func openDriverConn(ctx context.Context, c *connector) (driver.Conn, error) {
opts := c.options
c.logger.Log(ctx, LevelNotice, "opening connection")
instanceName := fmt.Sprintf(
"projects/%s/instances/%s",
c.connectorConfig.Project,
c.connectorConfig.Instance)
databaseName := fmt.Sprintf(
"projects/%s/instances/%s/databases/%s",
c.connectorConfig.Project,
c.connectorConfig.Instance,
c.connectorConfig.Database)
c.clientMu.Lock()
value, ok := c.initialPropertyValues[propertyConnectTimeout.Key()]
c.clientMu.Unlock()
if ok {
if timeout, err := value.GetValue(); err == nil {
if duration, ok := timeout.(time.Duration); ok {
var cancel context.CancelFunc
// This will set the actual timeout of the context to the lower of the
// current context timeout (if any) and the value from the connection property.
ctx, cancel = context.WithTimeout(ctx, duration)
defer cancel()
}
}
}
if err := c.increaseConnCount(ctx, databaseName, opts); err != nil {
return nil, err
}
connId := uuid.New().String()
logger := c.logger.With("connId", connId)
connectionStateType := c.connectorConfig.ConnectionStateType
if connectionStateType == connectionstate.TypeDefault {
if c.parser.Dialect == databasepb.DatabaseDialect_POSTGRESQL {
connectionStateType = connectionstate.TypeTransactional
} else {
connectionStateType = connectionstate.TypeNonTransactional
}
}
connection := &conn{
parser: c.parser,
connector: c,
client: c.client,
adminClient: c.adminClient,
connId: connId,
logger: logger,
instance: instanceName,
database: databaseName,
state: createInitialConnectionState(connectionStateType, c.initialPropertyValues),
execSingleQuery: queryInSingleUse,
execSingleQueryTransactional: queryInNewRWTransaction,
execSingleDMLTransactional: execInNewRWTransaction,
execSingleDMLPartitioned: execAsPartitionedDML,
}
// Initialize the session.
_ = connection.ResetSession(context.Background())
return connection, nil
}
func addStateFromConnectorConfig(c *connector, values map[string]connectionstate.ConnectionPropertyValue) {
updateConnectionPropertyValueIfNotExists(propertyDecodeToNativeArrays, values, c.connectorConfig.DecodeToNativeArrays)
updateConnectionPropertyValueIfNotExists(propertyIsolationLevel, values, c.connectorConfig.IsolationLevel)
updateConnectionPropertyValueIfNotExists(propertyBeginTransactionOption, values, c.connectorConfig.BeginTransactionOption)
updateConnectionPropertyValueIfNotExists(propertyRetryAbortsInternally, values, c.retryAbortsInternally)
updateConnectionPropertyValueIfNotExists(propertyAutoBatchDml, values, c.connectorConfig.AutoBatchDml)
updateConnectionPropertyValueIfNotExists(propertyAutoBatchDmlUpdateCount, values, c.connectorConfig.AutoBatchDmlUpdateCount)
updateConnectionPropertyValueIfNotExists(propertyAutoBatchDmlUpdateCountVerification, values, !c.connectorConfig.DisableAutoBatchDmlUpdateCountVerification)
}
func updateConnectionPropertyValueIfNotExists[T comparable](property *connectionstate.TypedConnectionProperty[T], values map[string]connectionstate.ConnectionPropertyValue, value T) {
if _, ok := values[property.Key()]; !ok {
values[property.Key()] = property.CreateTypedInitialValue(value)
}
}
// increaseConnCount initializes the client and increases the number of connections that are active.
func (c *connector) increaseConnCount(ctx context.Context, databaseName string, opts []option.ClientOption) error {
c.clientMu.Lock()
defer c.clientMu.Unlock()
if c.clientErr != nil {
return c.clientErr
}
if c.adminClientErr != nil {
return c.adminClientErr
}
if c.client == nil {
c.logger.Log(ctx, LevelNotice, "creating Spanner client")
c.client, c.clientErr = spanner.NewClientWithConfig(ctx, databaseName, c.spannerClientConfig, opts...)
if c.clientErr != nil {
return c.clientErr
}
c.logger.Log(ctx, LevelNotice, "fetching database dialect")
closeClient := func() {
c.client.Close()
c.client = nil
}
if dialect, err := determineDialect(ctx, c.client); err != nil {
closeClient()
return err
} else {
// Create a separate statement parser and cache per connector.
cacheSize := c.connectorConfig.StatementCacheSize
if c.connectorConfig.DisableStatementCache {
cacheSize = 0
} else if c.connectorConfig.StatementCacheSize == 0 {
cacheSize = defaultStatementCacheSize
}
c.parser, err = parser.NewStatementParser(dialect, cacheSize)
if err != nil {
closeClient()
return err
}
updateConnectionPropertyValueIfNotExists(propertyDatabaseDialect, c.initialPropertyValues, dialect)
}
c.logger.Log(ctx, LevelNotice, "creating Spanner Admin client")
c.adminClient, c.adminClientErr = adminapi.NewDatabaseAdminClient(ctx, opts...)
if c.adminClientErr != nil {
closeClient()
c.adminClient = nil
return c.adminClientErr
}
}
c.connCount++
c.logger.DebugContext(ctx, "increased conn count", "connCount", c.connCount)
return nil
}
func determineDialect(ctx context.Context, client *spanner.Client) (databasepb.DatabaseDialect, error) {
it := client.Single().Query(ctx, spanner.Statement{SQL: "select option_value from information_schema.database_options where option_name='database_dialect'"})
defer it.Stop()
for {
if row, err := it.Next(); err != nil {
return databasepb.DatabaseDialect_DATABASE_DIALECT_UNSPECIFIED, err
} else {
var dialectName string
if err := row.Columns(&dialectName); err != nil {
return databasepb.DatabaseDialect_DATABASE_DIALECT_UNSPECIFIED, err
}
if _, err := it.Next(); !errors.Is(err, iterator.Done) {
if err == nil {
return databasepb.DatabaseDialect_DATABASE_DIALECT_UNSPECIFIED, fmt.Errorf("more than one dialect result returned")
} else {
return databasepb.DatabaseDialect_DATABASE_DIALECT_UNSPECIFIED, err
}
}
if dialect, ok := databasepb.DatabaseDialect_value[dialectName]; ok {
return databasepb.DatabaseDialect(dialect), nil
} else {
return databasepb.DatabaseDialect_DATABASE_DIALECT_UNSPECIFIED, fmt.Errorf("unknown database dialect: %s", dialectName)
}
}
}
}
// decreaseConnCount decreases the number of connections that are active and closes the underlying clients if it was the
// last connection.
func (c *connector) decreaseConnCount() error {
c.clientMu.Lock()
defer c.clientMu.Unlock()
c.connCount--
c.logger.Debug("decreased conn count", "connCount", c.connCount)
if c.connCount > 0 {
return nil
}
return c.closeClients()
}
func (c *connector) Driver() driver.Driver {
return c.driver
}
func (c *connector) Close() error {
shouldClose := true
if c.cacheKey != "" {
c.driver.mu.Lock()
if usageCount, ok := c.driver.connectorUsageCount[c.cacheKey]; ok {
if usageCount == 1 {