You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

501 regels
20 KiB

  1. // Copyright 2018 Google LLC
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // https://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. // AUTO-GENERATED CODE. DO NOT EDIT.
  15. package spanner
  16. import (
  17. "math"
  18. "time"
  19. "cloud.google.com/go/internal/version"
  20. gax "github.com/googleapis/gax-go"
  21. "golang.org/x/net/context"
  22. "google.golang.org/api/iterator"
  23. "google.golang.org/api/option"
  24. "google.golang.org/api/transport"
  25. spannerpb "google.golang.org/genproto/googleapis/spanner/v1"
  26. "google.golang.org/grpc"
  27. "google.golang.org/grpc/codes"
  28. "google.golang.org/grpc/metadata"
  29. )
  30. // CallOptions contains the retry settings for each method of Client.
  31. type CallOptions struct {
  32. CreateSession []gax.CallOption
  33. GetSession []gax.CallOption
  34. ListSessions []gax.CallOption
  35. DeleteSession []gax.CallOption
  36. ExecuteSql []gax.CallOption
  37. ExecuteStreamingSql []gax.CallOption
  38. Read []gax.CallOption
  39. StreamingRead []gax.CallOption
  40. BeginTransaction []gax.CallOption
  41. Commit []gax.CallOption
  42. Rollback []gax.CallOption
  43. PartitionQuery []gax.CallOption
  44. PartitionRead []gax.CallOption
  45. }
  46. func defaultClientOptions() []option.ClientOption {
  47. return []option.ClientOption{
  48. option.WithEndpoint("spanner.googleapis.com:443"),
  49. option.WithScopes(DefaultAuthScopes()...),
  50. }
  51. }
  52. func defaultCallOptions() *CallOptions {
  53. retry := map[[2]string][]gax.CallOption{
  54. {"default", "idempotent"}: {
  55. gax.WithRetry(func() gax.Retryer {
  56. return gax.OnCodes([]codes.Code{
  57. codes.DeadlineExceeded,
  58. codes.Unavailable,
  59. }, gax.Backoff{
  60. Initial: 1000 * time.Millisecond,
  61. Max: 32000 * time.Millisecond,
  62. Multiplier: 1.3,
  63. })
  64. }),
  65. },
  66. {"long_running", "long_running"}: {
  67. gax.WithRetry(func() gax.Retryer {
  68. return gax.OnCodes([]codes.Code{
  69. codes.Unavailable,
  70. }, gax.Backoff{
  71. Initial: 1000 * time.Millisecond,
  72. Max: 32000 * time.Millisecond,
  73. Multiplier: 1.3,
  74. })
  75. }),
  76. },
  77. }
  78. return &CallOptions{
  79. CreateSession: retry[[2]string{"default", "idempotent"}],
  80. GetSession: retry[[2]string{"default", "idempotent"}],
  81. ListSessions: retry[[2]string{"default", "idempotent"}],
  82. DeleteSession: retry[[2]string{"default", "idempotent"}],
  83. ExecuteSql: retry[[2]string{"default", "idempotent"}],
  84. ExecuteStreamingSql: retry[[2]string{"default", "non_idempotent"}],
  85. Read: retry[[2]string{"default", "idempotent"}],
  86. StreamingRead: retry[[2]string{"default", "non_idempotent"}],
  87. BeginTransaction: retry[[2]string{"default", "idempotent"}],
  88. Commit: retry[[2]string{"long_running", "long_running"}],
  89. Rollback: retry[[2]string{"default", "idempotent"}],
  90. PartitionQuery: retry[[2]string{"default", "idempotent"}],
  91. PartitionRead: retry[[2]string{"default", "idempotent"}],
  92. }
  93. }
  94. // Client is a client for interacting with Cloud Spanner API.
  95. //
  96. // Methods, except Close, may be called concurrently. However, fields must not be modified concurrently with method calls.
  97. type Client struct {
  98. // The connection to the service.
  99. conn *grpc.ClientConn
  100. // The gRPC API client.
  101. client spannerpb.SpannerClient
  102. // The call options for this service.
  103. CallOptions *CallOptions
  104. // The x-goog-* metadata to be sent with each request.
  105. xGoogMetadata metadata.MD
  106. }
  107. // NewClient creates a new spanner client.
  108. //
  109. // Cloud Spanner API
  110. //
  111. // The Cloud Spanner API can be used to manage sessions and execute
  112. // transactions on data stored in Cloud Spanner databases.
  113. func NewClient(ctx context.Context, opts ...option.ClientOption) (*Client, error) {
  114. conn, err := transport.DialGRPC(ctx, append(defaultClientOptions(), opts...)...)
  115. if err != nil {
  116. return nil, err
  117. }
  118. c := &Client{
  119. conn: conn,
  120. CallOptions: defaultCallOptions(),
  121. client: spannerpb.NewSpannerClient(conn),
  122. }
  123. c.SetGoogleClientInfo()
  124. return c, nil
  125. }
  126. // Connection returns the client's connection to the API service.
  127. func (c *Client) Connection() *grpc.ClientConn {
  128. return c.conn
  129. }
  130. // Close closes the connection to the API service. The user should invoke this when
  131. // the client is no longer required.
  132. func (c *Client) Close() error {
  133. return c.conn.Close()
  134. }
  135. // SetGoogleClientInfo sets the name and version of the application in
  136. // the `x-goog-api-client` header passed on each request. Intended for
  137. // use by Google-written clients.
  138. func (c *Client) SetGoogleClientInfo(keyval ...string) {
  139. kv := append([]string{"gl-go", version.Go()}, keyval...)
  140. kv = append(kv, "gapic", version.Repo, "gax", gax.Version, "grpc", grpc.Version)
  141. c.xGoogMetadata = metadata.Pairs("x-goog-api-client", gax.XGoogHeader(kv...))
  142. }
  143. // CreateSession creates a new session. A session can be used to perform
  144. // transactions that read and/or modify data in a Cloud Spanner database.
  145. // Sessions are meant to be reused for many consecutive
  146. // transactions.
  147. //
  148. // Sessions can only execute one transaction at a time. To execute
  149. // multiple concurrent read-write/write-only transactions, create
  150. // multiple sessions. Note that standalone reads and queries use a
  151. // transaction internally, and count toward the one transaction
  152. // limit.
  153. //
  154. // Cloud Spanner limits the number of sessions that can exist at any given
  155. // time; thus, it is a good idea to delete idle and/or unneeded sessions.
  156. // Aside from explicit deletes, Cloud Spanner can delete sessions for which no
  157. // operations are sent for more than an hour. If a session is deleted,
  158. // requests to it return NOT_FOUND.
  159. //
  160. // Idle sessions can be kept alive by sending a trivial SQL query
  161. // periodically, e.g., "SELECT 1".
  162. func (c *Client) CreateSession(ctx context.Context, req *spannerpb.CreateSessionRequest, opts ...gax.CallOption) (*spannerpb.Session, error) {
  163. ctx = insertMetadata(ctx, c.xGoogMetadata)
  164. opts = append(c.CallOptions.CreateSession[0:len(c.CallOptions.CreateSession):len(c.CallOptions.CreateSession)], opts...)
  165. var resp *spannerpb.Session
  166. err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
  167. var err error
  168. resp, err = c.client.CreateSession(ctx, req, settings.GRPC...)
  169. return err
  170. }, opts...)
  171. if err != nil {
  172. return nil, err
  173. }
  174. return resp, nil
  175. }
  176. // GetSession gets a session. Returns NOT_FOUND if the session does not exist.
  177. // This is mainly useful for determining whether a session is still
  178. // alive.
  179. func (c *Client) GetSession(ctx context.Context, req *spannerpb.GetSessionRequest, opts ...gax.CallOption) (*spannerpb.Session, error) {
  180. ctx = insertMetadata(ctx, c.xGoogMetadata)
  181. opts = append(c.CallOptions.GetSession[0:len(c.CallOptions.GetSession):len(c.CallOptions.GetSession)], opts...)
  182. var resp *spannerpb.Session
  183. err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
  184. var err error
  185. resp, err = c.client.GetSession(ctx, req, settings.GRPC...)
  186. return err
  187. }, opts...)
  188. if err != nil {
  189. return nil, err
  190. }
  191. return resp, nil
  192. }
  193. // ListSessions lists all sessions in a given database.
  194. func (c *Client) ListSessions(ctx context.Context, req *spannerpb.ListSessionsRequest, opts ...gax.CallOption) *SessionIterator {
  195. ctx = insertMetadata(ctx, c.xGoogMetadata)
  196. opts = append(c.CallOptions.ListSessions[0:len(c.CallOptions.ListSessions):len(c.CallOptions.ListSessions)], opts...)
  197. it := &SessionIterator{}
  198. it.InternalFetch = func(pageSize int, pageToken string) ([]*spannerpb.Session, string, error) {
  199. var resp *spannerpb.ListSessionsResponse
  200. req.PageToken = pageToken
  201. if pageSize > math.MaxInt32 {
  202. req.PageSize = math.MaxInt32
  203. } else {
  204. req.PageSize = int32(pageSize)
  205. }
  206. err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
  207. var err error
  208. resp, err = c.client.ListSessions(ctx, req, settings.GRPC...)
  209. return err
  210. }, opts...)
  211. if err != nil {
  212. return nil, "", err
  213. }
  214. return resp.Sessions, resp.NextPageToken, nil
  215. }
  216. fetch := func(pageSize int, pageToken string) (string, error) {
  217. items, nextPageToken, err := it.InternalFetch(pageSize, pageToken)
  218. if err != nil {
  219. return "", err
  220. }
  221. it.items = append(it.items, items...)
  222. return nextPageToken, nil
  223. }
  224. it.pageInfo, it.nextFunc = iterator.NewPageInfo(fetch, it.bufLen, it.takeBuf)
  225. return it
  226. }
  227. // DeleteSession ends a session, releasing server resources associated with it.
  228. func (c *Client) DeleteSession(ctx context.Context, req *spannerpb.DeleteSessionRequest, opts ...gax.CallOption) error {
  229. ctx = insertMetadata(ctx, c.xGoogMetadata)
  230. opts = append(c.CallOptions.DeleteSession[0:len(c.CallOptions.DeleteSession):len(c.CallOptions.DeleteSession)], opts...)
  231. err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
  232. var err error
  233. _, err = c.client.DeleteSession(ctx, req, settings.GRPC...)
  234. return err
  235. }, opts...)
  236. return err
  237. }
  238. // ExecuteSql executes an SQL query, returning all rows in a single reply. This
  239. // method cannot be used to return a result set larger than 10 MiB;
  240. // if the query yields more data than that, the query fails with
  241. // a FAILED_PRECONDITION error.
  242. //
  243. // Queries inside read-write transactions might return ABORTED. If
  244. // this occurs, the application should restart the transaction from
  245. // the beginning. See [Transaction][google.spanner.v1.Transaction] for more details.
  246. //
  247. // Larger result sets can be fetched in streaming fashion by calling
  248. // [ExecuteStreamingSql][google.spanner.v1.Spanner.ExecuteStreamingSql] instead.
  249. func (c *Client) ExecuteSql(ctx context.Context, req *spannerpb.ExecuteSqlRequest, opts ...gax.CallOption) (*spannerpb.ResultSet, error) {
  250. ctx = insertMetadata(ctx, c.xGoogMetadata)
  251. opts = append(c.CallOptions.ExecuteSql[0:len(c.CallOptions.ExecuteSql):len(c.CallOptions.ExecuteSql)], opts...)
  252. var resp *spannerpb.ResultSet
  253. err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
  254. var err error
  255. resp, err = c.client.ExecuteSql(ctx, req, settings.GRPC...)
  256. return err
  257. }, opts...)
  258. if err != nil {
  259. return nil, err
  260. }
  261. return resp, nil
  262. }
  263. // ExecuteStreamingSql like [ExecuteSql][google.spanner.v1.Spanner.ExecuteSql], except returns the result
  264. // set as a stream. Unlike [ExecuteSql][google.spanner.v1.Spanner.ExecuteSql], there
  265. // is no limit on the size of the returned result set. However, no
  266. // individual row in the result set can exceed 100 MiB, and no
  267. // column value can exceed 10 MiB.
  268. func (c *Client) ExecuteStreamingSql(ctx context.Context, req *spannerpb.ExecuteSqlRequest, opts ...gax.CallOption) (spannerpb.Spanner_ExecuteStreamingSqlClient, error) {
  269. ctx = insertMetadata(ctx, c.xGoogMetadata)
  270. opts = append(c.CallOptions.ExecuteStreamingSql[0:len(c.CallOptions.ExecuteStreamingSql):len(c.CallOptions.ExecuteStreamingSql)], opts...)
  271. var resp spannerpb.Spanner_ExecuteStreamingSqlClient
  272. err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
  273. var err error
  274. resp, err = c.client.ExecuteStreamingSql(ctx, req, settings.GRPC...)
  275. return err
  276. }, opts...)
  277. if err != nil {
  278. return nil, err
  279. }
  280. return resp, nil
  281. }
  282. // Read reads rows from the database using key lookups and scans, as a
  283. // simple key/value style alternative to
  284. // [ExecuteSql][google.spanner.v1.Spanner.ExecuteSql]. This method cannot be used to
  285. // return a result set larger than 10 MiB; if the read matches more
  286. // data than that, the read fails with a FAILED_PRECONDITION
  287. // error.
  288. //
  289. // Reads inside read-write transactions might return ABORTED. If
  290. // this occurs, the application should restart the transaction from
  291. // the beginning. See [Transaction][google.spanner.v1.Transaction] for more details.
  292. //
  293. // Larger result sets can be yielded in streaming fashion by calling
  294. // [StreamingRead][google.spanner.v1.Spanner.StreamingRead] instead.
  295. func (c *Client) Read(ctx context.Context, req *spannerpb.ReadRequest, opts ...gax.CallOption) (*spannerpb.ResultSet, error) {
  296. ctx = insertMetadata(ctx, c.xGoogMetadata)
  297. opts = append(c.CallOptions.Read[0:len(c.CallOptions.Read):len(c.CallOptions.Read)], opts...)
  298. var resp *spannerpb.ResultSet
  299. err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
  300. var err error
  301. resp, err = c.client.Read(ctx, req, settings.GRPC...)
  302. return err
  303. }, opts...)
  304. if err != nil {
  305. return nil, err
  306. }
  307. return resp, nil
  308. }
  309. // StreamingRead like [Read][google.spanner.v1.Spanner.Read], except returns the result set as a
  310. // stream. Unlike [Read][google.spanner.v1.Spanner.Read], there is no limit on the
  311. // size of the returned result set. However, no individual row in
  312. // the result set can exceed 100 MiB, and no column value can exceed
  313. // 10 MiB.
  314. func (c *Client) StreamingRead(ctx context.Context, req *spannerpb.ReadRequest, opts ...gax.CallOption) (spannerpb.Spanner_StreamingReadClient, error) {
  315. ctx = insertMetadata(ctx, c.xGoogMetadata)
  316. opts = append(c.CallOptions.StreamingRead[0:len(c.CallOptions.StreamingRead):len(c.CallOptions.StreamingRead)], opts...)
  317. var resp spannerpb.Spanner_StreamingReadClient
  318. err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
  319. var err error
  320. resp, err = c.client.StreamingRead(ctx, req, settings.GRPC...)
  321. return err
  322. }, opts...)
  323. if err != nil {
  324. return nil, err
  325. }
  326. return resp, nil
  327. }
  328. // BeginTransaction begins a new transaction. This step can often be skipped:
  329. // [Read][google.spanner.v1.Spanner.Read], [ExecuteSql][google.spanner.v1.Spanner.ExecuteSql] and
  330. // [Commit][google.spanner.v1.Spanner.Commit] can begin a new transaction as a
  331. // side-effect.
  332. func (c *Client) BeginTransaction(ctx context.Context, req *spannerpb.BeginTransactionRequest, opts ...gax.CallOption) (*spannerpb.Transaction, error) {
  333. ctx = insertMetadata(ctx, c.xGoogMetadata)
  334. opts = append(c.CallOptions.BeginTransaction[0:len(c.CallOptions.BeginTransaction):len(c.CallOptions.BeginTransaction)], opts...)
  335. var resp *spannerpb.Transaction
  336. err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
  337. var err error
  338. resp, err = c.client.BeginTransaction(ctx, req, settings.GRPC...)
  339. return err
  340. }, opts...)
  341. if err != nil {
  342. return nil, err
  343. }
  344. return resp, nil
  345. }
  346. // Commit commits a transaction. The request includes the mutations to be
  347. // applied to rows in the database.
  348. //
  349. // Commit might return an ABORTED error. This can occur at any time;
  350. // commonly, the cause is conflicts with concurrent
  351. // transactions. However, it can also happen for a variety of other
  352. // reasons. If Commit returns ABORTED, the caller should re-attempt
  353. // the transaction from the beginning, re-using the same session.
  354. func (c *Client) Commit(ctx context.Context, req *spannerpb.CommitRequest, opts ...gax.CallOption) (*spannerpb.CommitResponse, error) {
  355. ctx = insertMetadata(ctx, c.xGoogMetadata)
  356. opts = append(c.CallOptions.Commit[0:len(c.CallOptions.Commit):len(c.CallOptions.Commit)], opts...)
  357. var resp *spannerpb.CommitResponse
  358. err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
  359. var err error
  360. resp, err = c.client.Commit(ctx, req, settings.GRPC...)
  361. return err
  362. }, opts...)
  363. if err != nil {
  364. return nil, err
  365. }
  366. return resp, nil
  367. }
  368. // Rollback rolls back a transaction, releasing any locks it holds. It is a good
  369. // idea to call this for any transaction that includes one or more
  370. // [Read][google.spanner.v1.Spanner.Read] or [ExecuteSql][google.spanner.v1.Spanner.ExecuteSql] requests and
  371. // ultimately decides not to commit.
  372. //
  373. // Rollback returns OK if it successfully aborts the transaction, the
  374. // transaction was already aborted, or the transaction is not
  375. // found. Rollback never returns ABORTED.
  376. func (c *Client) Rollback(ctx context.Context, req *spannerpb.RollbackRequest, opts ...gax.CallOption) error {
  377. ctx = insertMetadata(ctx, c.xGoogMetadata)
  378. opts = append(c.CallOptions.Rollback[0:len(c.CallOptions.Rollback):len(c.CallOptions.Rollback)], opts...)
  379. err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
  380. var err error
  381. _, err = c.client.Rollback(ctx, req, settings.GRPC...)
  382. return err
  383. }, opts...)
  384. return err
  385. }
  386. // PartitionQuery creates a set of partition tokens that can be used to execute a query
  387. // operation in parallel. Each of the returned partition tokens can be used
  388. // by [ExecuteStreamingSql][google.spanner.v1.Spanner.ExecuteStreamingSql] to specify a subset
  389. // of the query result to read. The same session and read-only transaction
  390. // must be used by the PartitionQueryRequest used to create the
  391. // partition tokens and the ExecuteSqlRequests that use the partition tokens.
  392. // Partition tokens become invalid when the session used to create them
  393. // is deleted or begins a new transaction.
  394. func (c *Client) PartitionQuery(ctx context.Context, req *spannerpb.PartitionQueryRequest, opts ...gax.CallOption) (*spannerpb.PartitionResponse, error) {
  395. ctx = insertMetadata(ctx, c.xGoogMetadata)
  396. opts = append(c.CallOptions.PartitionQuery[0:len(c.CallOptions.PartitionQuery):len(c.CallOptions.PartitionQuery)], opts...)
  397. var resp *spannerpb.PartitionResponse
  398. err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
  399. var err error
  400. resp, err = c.client.PartitionQuery(ctx, req, settings.GRPC...)
  401. return err
  402. }, opts...)
  403. if err != nil {
  404. return nil, err
  405. }
  406. return resp, nil
  407. }
  408. // PartitionRead creates a set of partition tokens that can be used to execute a read
  409. // operation in parallel. Each of the returned partition tokens can be used
  410. // by [StreamingRead][google.spanner.v1.Spanner.StreamingRead] to specify a subset of the read
  411. // result to read. The same session and read-only transaction must be used by
  412. // the PartitionReadRequest used to create the partition tokens and the
  413. // ReadRequests that use the partition tokens.
  414. // Partition tokens become invalid when the session used to create them
  415. // is deleted or begins a new transaction.
  416. func (c *Client) PartitionRead(ctx context.Context, req *spannerpb.PartitionReadRequest, opts ...gax.CallOption) (*spannerpb.PartitionResponse, error) {
  417. ctx = insertMetadata(ctx, c.xGoogMetadata)
  418. opts = append(c.CallOptions.PartitionRead[0:len(c.CallOptions.PartitionRead):len(c.CallOptions.PartitionRead)], opts...)
  419. var resp *spannerpb.PartitionResponse
  420. err := gax.Invoke(ctx, func(ctx context.Context, settings gax.CallSettings) error {
  421. var err error
  422. resp, err = c.client.PartitionRead(ctx, req, settings.GRPC...)
  423. return err
  424. }, opts...)
  425. if err != nil {
  426. return nil, err
  427. }
  428. return resp, nil
  429. }
  430. // SessionIterator manages a stream of *spannerpb.Session.
  431. type SessionIterator struct {
  432. items []*spannerpb.Session
  433. pageInfo *iterator.PageInfo
  434. nextFunc func() error
  435. // InternalFetch is for use by the Google Cloud Libraries only.
  436. // It is not part of the stable interface of this package.
  437. //
  438. // InternalFetch returns results from a single call to the underlying RPC.
  439. // The number of results is no greater than pageSize.
  440. // If there are no more results, nextPageToken is empty and err is nil.
  441. InternalFetch func(pageSize int, pageToken string) (results []*spannerpb.Session, nextPageToken string, err error)
  442. }
  443. // PageInfo supports pagination. See the google.golang.org/api/iterator package for details.
  444. func (it *SessionIterator) PageInfo() *iterator.PageInfo {
  445. return it.pageInfo
  446. }
  447. // Next returns the next result. Its second return value is iterator.Done if there are no more
  448. // results. Once Next returns Done, all subsequent calls will return Done.
  449. func (it *SessionIterator) Next() (*spannerpb.Session, error) {
  450. var item *spannerpb.Session
  451. if err := it.nextFunc(); err != nil {
  452. return item, err
  453. }
  454. item = it.items[0]
  455. it.items = it.items[1:]
  456. return item, nil
  457. }
  458. func (it *SessionIterator) bufLen() int {
  459. return len(it.items)
  460. }
  461. func (it *SessionIterator) takeBuf() interface{} {
  462. b := it.items
  463. it.items = nil
  464. return b
  465. }