diff --git a/README.rst b/README.rst index db42b50b109a..e022bd9d333c 100644 --- a/README.rst +++ b/README.rst @@ -34,6 +34,7 @@ The following client libraries have **beta** support: - `Google BigQuery`_ (`BigQuery README`_) - `Google Cloud Natural Language`_ (`Natural Language README`_) - `Google Cloud Pub/Sub`_ (`Pub/Sub README`_) +- `Google Cloud Spanner`_ (`Spanner README`_) - `Google Cloud Speech`_ (`Speech README`_) - `Google Cloud Video Intelligence`_ (`Video Intelligence README`_) - `Google Cloud Vision`_ (`Vision README`_) @@ -50,7 +51,6 @@ Cloud Platform services: - `Google Cloud DNS`_ (`DNS README`_) - `Google Cloud Resource Manager`_ (`Resource Manager README`_) - `Google Cloud Runtime Configuration`_ (`Runtime Config README`_) -- `Google Cloud Spanner`_ (`Spanner README`_) - `Stackdriver Error Reporting`_ (`Error Reporting README`_) - `Stackdriver Monitoring`_ (`Monitoring README`_) diff --git a/docs/conf.py b/docs/conf.py index edff3a2d5356..8d7d9b3984a9 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -122,7 +122,6 @@ 'github_user': 'GoogleCloudPlatform', 'github_repo': 'google-cloud-python', 'github_banner': True, - 'travis_button': True, 'font_family': "'Roboto', Georgia, sans", 'head_font_family': "'Roboto', Georgia, serif", 'code_font_family': "'Roboto Mono', 'Consolas', monospace", diff --git a/docs/spanner/api-reference.rst b/docs/spanner/api-reference.rst new file mode 100644 index 000000000000..c767b23afac0 --- /dev/null +++ b/docs/spanner/api-reference.rst @@ -0,0 +1,33 @@ +API Reference +============= + +The following classes and methods constitute the Spanner client. +Most likely, you will be interacting almost exclusively with these: + +.. toctree:: + :maxdepth: 1 + + client-api + instance-api + database-api + session-api + keyset-api + snapshot-api + batch-api + transaction-api + streamed-api + + +The classes and methods above depend on the following, lower-level +classes and methods. Documentation for these is provided for completion, +and some advanced use cases may wish to interact with these directly: + +.. toctree:: + :maxdepth: 1 + + gapic/v1/api + gapic/v1/types + gapic/v1/admin_database_api + gapic/v1/admin_database_types + gapic/v1/admin_instance_api + gapic/v1/admin_instance_types diff --git a/docs/spanner/batch-api.rst b/docs/spanner/batch-api.rst index 0d0b927e9654..ecd51b01cdd9 100644 --- a/docs/spanner/batch-api.rst +++ b/docs/spanner/batch-api.rst @@ -1,8 +1,6 @@ Batch API ========= -.. automodule:: google.cloud.spanner.batch +.. automodule:: google.cloud.spanner_v1.batch :members: :show-inheritance: - - diff --git a/docs/spanner/client-api.rst b/docs/spanner/client-api.rst index 0716ee742e3a..3cc5a89b2137 100644 --- a/docs/spanner/client-api.rst +++ b/docs/spanner/client-api.rst @@ -1,7 +1,7 @@ Spanner Client ============== -.. automodule:: google.cloud.spanner.client +.. automodule:: google.cloud.spanner_v1.client :members: :show-inheritance: diff --git a/docs/spanner/client-usage.rst b/docs/spanner/client-usage.rst deleted file mode 100644 index a40c064f86da..000000000000 --- a/docs/spanner/client-usage.rst +++ /dev/null @@ -1,68 +0,0 @@ -Client -====== - -To use the API, the :class:`~google.cloud.spanner.client.Client` -class defines a high-level interface which handles authorization -and creating other objects: - -.. code:: python - - from google.cloud.spanner.client import Client - client = Client() - -Long-lived Defaults -------------------- - -When creating a :class:`~google.cloud.spanner.client.Client`, the -``user_agent`` and ``timeout_seconds`` arguments have sensible -defaults -(:data:`~google.cloud.spanner.client.DEFAULT_USER_AGENT` and -:data:`~google.cloud.spanner.client.DEFAULT_TIMEOUT_SECONDS`). -However, you may over-ride them and these will be used throughout all API -requests made with the ``client`` you create. - -Configuration -------------- - -- For an overview of authentication in ``google.cloud-python``, - see :doc:`/core/auth`. - -- In addition to any authentication configuration, you can also set the - :envvar:`GCLOUD_PROJECT` environment variable for the Google Cloud Console - project you'd like to interact with. If your code is running in Google App - Engine or Google Compute Engine the project will be detected automatically. - (Setting this environment variable is not required, you may instead pass the - ``project`` explicitly when constructing a - :class:`~google.cloud.storage.client.Client`). - -- After configuring your environment, create a - :class:`~google.cloud.storage.client.Client` - - .. code:: - - >>> from google.cloud import spanner - >>> client = spanner.Client() - - or pass in ``credentials`` and ``project`` explicitly - - .. code:: - - >>> from google.cloud import spanner - >>> client = spanner.Client(project='my-project', credentials=creds) - -.. tip:: - - Be sure to use the **Project ID**, not the **Project Number**. - - -Next Step ---------- - -After a :class:`~google.cloud.spanner.client.Client`, the next -highest-level object is an :class:`~google.cloud.spanner.instance.Instance`. -You'll need one before you can interact with databases. - -Next, learn about the :doc:`instance-usage`. - -.. _Instance Admin: https://cloud.google.com/spanner/reference/rpc/google.spanner.admin.instance.v1 -.. _Database Admin: https://cloud.google.com/spanner/reference/rpc/google.spanner.admin.database.v1 diff --git a/docs/spanner/database-api.rst b/docs/spanner/database-api.rst index 1eeed674e7d6..f1ce2a6d8e26 100644 --- a/docs/spanner/database-api.rst +++ b/docs/spanner/database-api.rst @@ -1,7 +1,7 @@ Database API ============ -.. automodule:: google.cloud.spanner.database +.. automodule:: google.cloud.spanner_v1.database :members: :show-inheritance: diff --git a/docs/spanner/database-usage.rst b/docs/spanner/database-usage.rst index 529010c8443f..1e94a2de84dc 100644 --- a/docs/spanner/database-usage.rst +++ b/docs/spanner/database-usage.rst @@ -1,5 +1,5 @@ -Database Admin API -================== +Database Admin +============== After creating a :class:`~google.cloud.spanner.instance.Instance`, you can interact with individual databases for that instance. @@ -8,12 +8,16 @@ interact with individual databases for that instance. List Databases -------------- -To list of all existing databases for an instance, use its +To iterate over all existing databases for an instance, use its :meth:`~google.cloud.spanner.instance.Instance.list_databases` method: .. code:: python - databases, token = instance.list_databases() + for database in instance.list_databases(): + # `database` is a `Database` object. + +This method yields :class:`~.spanner_admin_database_v1.types.Database` +objects. Database Factory @@ -49,9 +53,9 @@ trigger its creation on the server: .. note:: Creating an instance triggers a "long-running operation" and - returns an :class:`google.cloud.spanner.database.Operation` - object. See :ref:`check-on-current-database-operation` for polling - to find out if the operation is completed. + returns an :class:`~concurrent.futures.Future`-like object. Use + the :meth:`~concurrent.futures.Future.result` method to wait for + and inspect the result. Update an existing Database @@ -96,26 +100,13 @@ Check on Current Database Operation The :meth:`~google.cloud.spanner.database.Database.create` and :meth:`~google.cloud.spanner.database.Database.update` methods of instance object trigger long-running operations on the server, and return instances -of the :class:`~google.cloud.spanner.database.Operation` class. - -You can check if a long-running operation has finished -by using its :meth:`~google.cloud.spanner.database.Operation.finished` -method: +conforming to the :class:`~.concurrent.futures.Future` class. .. code:: python >>> operation = instance.create() - >>> operation.finished() - True + >>> operation.result() -.. note:: - - Once an :class:`~google.cloud.spanner.instance.Operation` object - has returned :data:`True` from its - :meth:`~google.cloud.spanner.instance.Operation.finished` method, the - object should not be re-used. Subsequent calls to - :meth:`~google.cloud.spanner.instance.Operation.finished` - will result in an :exc`ValueError` being raised. Non-Admin Database Usage ======================== @@ -220,12 +211,15 @@ constructor: .. code-block:: python - from google.cloud.spanner import Client - from google.cloud.spanner import FixedSizePool - client = Client() - instance = client.instance(INSTANCE_NAME) - pool = FixedSizePool(size=10, default_timeout=5) - database = instanc.database(DATABASE_NAME, pool=pool) + from google.cloud import spanner + + # Instantiate the Spanner client, and get the appropriate instance. + client = spanner.Client() + instance = client.instance(INSTANCE_NAME) + + # Create a database with a pool of a fixed size. + pool = spanner.FixedSizePool(size=10, default_timeout=5) + database = instance.database(DATABASE_NAME, pool=pool) Note that creating a database with a pool may presume that its database already exists, as it may need to pre-create sessions (rather than creating diff --git a/docs/spanner/gapic/v1/admin_database_api.rst b/docs/spanner/gapic/v1/admin_database_api.rst new file mode 100644 index 000000000000..c63f242e8557 --- /dev/null +++ b/docs/spanner/gapic/v1/admin_database_api.rst @@ -0,0 +1,6 @@ +Spanner Admin Database Client API +================================= + +.. automodule:: google.cloud.spanner_admin_database_v1 + :members: + :inherited-members: diff --git a/docs/spanner/gapic/v1/admin_database_types.rst b/docs/spanner/gapic/v1/admin_database_types.rst new file mode 100644 index 000000000000..de3d9585c715 --- /dev/null +++ b/docs/spanner/gapic/v1/admin_database_types.rst @@ -0,0 +1,5 @@ +Spanner Admin Database Client Types +=================================== + +.. automodule:: google.cloud.spanner_admin_database_v1.types + :members: diff --git a/docs/spanner/gapic/v1/admin_instance_api.rst b/docs/spanner/gapic/v1/admin_instance_api.rst new file mode 100644 index 000000000000..c8c320a6cf41 --- /dev/null +++ b/docs/spanner/gapic/v1/admin_instance_api.rst @@ -0,0 +1,6 @@ +Spanner Admin Instance Client API +================================= + +.. automodule:: google.cloud.spanner_admin_instance_v1 + :members: + :inherited-members: diff --git a/docs/spanner/gapic/v1/admin_instance_types.rst b/docs/spanner/gapic/v1/admin_instance_types.rst new file mode 100644 index 000000000000..4cd06b3ca0d9 --- /dev/null +++ b/docs/spanner/gapic/v1/admin_instance_types.rst @@ -0,0 +1,5 @@ +Spanner Admin Instance Client Types +=================================== + +.. automodule:: google.cloud.spanner_admin_instance_v1.types + :members: diff --git a/docs/spanner/gapic/v1/api.rst b/docs/spanner/gapic/v1/api.rst new file mode 100644 index 000000000000..79e4835f2222 --- /dev/null +++ b/docs/spanner/gapic/v1/api.rst @@ -0,0 +1,6 @@ +Spanner Client API +================== + +.. automodule:: google.cloud.spanner_v1 + :members: + :inherited-members: diff --git a/docs/spanner/gapic/v1/transactions.rst b/docs/spanner/gapic/v1/transactions.rst new file mode 100644 index 000000000000..d34af43b4ae9 --- /dev/null +++ b/docs/spanner/gapic/v1/transactions.rst @@ -0,0 +1,241 @@ +.. + This page is pulled from the TransactionOption type, where this entire + kaboodle is auto-generated. Sphinx does not particularly appreciate + entire narrative documentation, complete with headers, in an arbitrary + class docstring, and complains about this, so I (lukesneeringer@) + manually copied it over here. + + This should probably be updated when the Spanner code is re-generated. + This will be easy to remember because the source that needs to be copied + will be dropped in transaction_pb2.py and Sphinx will complain loudly + about it. + + Internal Google ticket: b/65243734 + +:orphan: + +.. _spanner-txn: + +Transactions +============ + +Each session can have at most one active transaction at a time. After +the active transaction is completed, the session can immediately be +re-used for the next transaction. It is not necessary to create a new +session for each transaction. + +Transaction Modes +================= + +Cloud Spanner supports two transaction modes: + +1. Locking read-write. This type of transaction is the only way to write + data into Cloud Spanner. These transactions rely on pessimistic + locking and, if necessary, two-phase commit. Locking read-write + transactions may abort, requiring the application to retry. + +2. Snapshot read-only. This transaction type provides guaranteed + consistency across several reads, but does not allow writes. Snapshot + read-only transactions can be configured to read at timestamps in the + past. Snapshot read-only transactions do not need to be committed. + +For transactions that only read, snapshot read-only transactions provide +simpler semantics and are almost always faster. In particular, read-only +transactions do not take locks, so they do not conflict with read-write +transactions. As a consequence of not taking locks, they also do not +abort, so retry loops are not needed. + +Transactions may only read/write data in a single database. They may, +however, read/write data in different tables within that database. + +Locking Read-Write Transactions +------------------------------- + +Locking transactions may be used to atomically read-modify-write data +anywhere in a database. This type of transaction is externally +consistent. + +Clients should attempt to minimize the amount of time a transaction is +active. Faster transactions commit with higher probability and cause +less contention. Cloud Spanner attempts to keep read locks active as +long as the transaction continues to do reads, and the transaction has +not been terminated by [Commit][google.spanner.v1.Spanner.Commit] or +[Rollback][google.spanner.v1.Spanner.Rollback]. Long periods of +inactivity at the client may cause Cloud Spanner to release a +transaction's locks and abort it. + +Reads performed within a transaction acquire locks on the data being +read. Writes can only be done at commit time, after all reads have been +completed. Conceptually, a read-write transaction consists of zero or +more reads or SQL queries followed by +[Commit][google.spanner.v1.Spanner.Commit]. At any time before +[Commit][google.spanner.v1.Spanner.Commit], the client can send a +[Rollback][google.spanner.v1.Spanner.Rollback] request to abort the +transaction. + +Semantics +~~~~~~~~~ + +Cloud Spanner can commit the transaction if all read locks it acquired +are still valid at commit time, and it is able to acquire write locks +for all writes. Cloud Spanner can abort the transaction for any reason. +If a commit attempt returns ``ABORTED``, Cloud Spanner guarantees that +the transaction has not modified any user data in Cloud Spanner. + +Unless the transaction commits, Cloud Spanner makes no guarantees about +how long the transaction's locks were held for. It is an error to use +Cloud Spanner locks for any sort of mutual exclusion other than between +Cloud Spanner transactions themselves. + +Retrying Aborted Transactions +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +When a transaction aborts, the application can choose to retry the whole +transaction again. To maximize the chances of successfully committing +the retry, the client should execute the retry in the same session as +the original attempt. The original session's lock priority increases +with each consecutive abort, meaning that each attempt has a slightly +better chance of success than the previous. + +Under some circumstances (e.g., many transactions attempting to modify +the same row(s)), a transaction can abort many times in a short period +before successfully committing. Thus, it is not a good idea to cap the +number of retries a transaction can attempt; instead, it is better to +limit the total amount of wall time spent retrying. + +Idle Transactions +~~~~~~~~~~~~~~~~~ + +A transaction is considered idle if it has no outstanding reads or SQL +queries and has not started a read or SQL query within the last 10 +seconds. Idle transactions can be aborted by Cloud Spanner so that they +don't hold on to locks indefinitely. In that case, the commit will fail +with error ``ABORTED``. + +If this behavior is undesirable, periodically executing a simple SQL +query in the transaction (e.g., ``SELECT 1``) prevents the transaction +from becoming idle. + +Snapshot Read-Only Transactions +------------------------------- + +Snapshot read-only transactions provides a simpler method than locking +read-write transactions for doing several consistent reads. However, +this type of transaction does not support writes. + +Snapshot transactions do not take locks. Instead, they work by choosing +a Cloud Spanner timestamp, then executing all reads at that timestamp. +Since they do not acquire locks, they do not block concurrent read-write +transactions. + +Unlike locking read-write transactions, snapshot read-only transactions +never abort. They can fail if the chosen read timestamp is garbage +collected; however, the default garbage collection policy is generous +enough that most applications do not need to worry about this in +practice. + +Snapshot read-only transactions do not need to call +[Commit][google.spanner.v1.Spanner.Commit] or +[Rollback][google.spanner.v1.Spanner.Rollback] (and in fact are not +permitted to do so). + +To execute a snapshot transaction, the client specifies a timestamp +bound, which tells Cloud Spanner how to choose a read timestamp. + +The types of timestamp bound are: + +- Strong (the default). +- Bounded staleness. +- Exact staleness. + +If the Cloud Spanner database to be read is geographically distributed, +stale read-only transactions can execute more quickly than strong or +read-write transaction, because they are able to execute far from the +leader replica. + +Each type of timestamp bound is discussed in detail below. + +Strong +~~~~~~ + +Strong reads are guaranteed to see the effects of all transactions that +have committed before the start of the read. Furthermore, all rows +yielded by a single read are consistent with each other -- if any part +of the read observes a transaction, all parts of the read see the +transaction. + +Strong reads are not repeatable: two consecutive strong read-only +transactions might return inconsistent results if there are concurrent +writes. If consistency across reads is required, the reads should be +executed within a transaction or at an exact read timestamp. + +See +[TransactionOptions.ReadOnly.strong][google.spanner.v1.TransactionOptions.ReadOnly.strong]. + +Exact Staleness +~~~~~~~~~~~~~~~ + +These timestamp bounds execute reads at a user-specified timestamp. +Reads at a timestamp are guaranteed to see a consistent prefix of the +global transaction history: they observe modifications done by all +transactions with a commit timestamp <= the read timestamp, and observe +none of the modifications done by transactions with a larger commit +timestamp. They will block until all conflicting transactions that may +be assigned commit timestamps <= the read timestamp have finished. + +The timestamp can either be expressed as an absolute Cloud Spanner +commit timestamp or a staleness relative to the current time. + +These modes do not require a "negotiation phase" to pick a timestamp. As +a result, they execute slightly faster than the equivalent boundedly +stale concurrency modes. On the other hand, boundedly stale reads +usually return fresher results. + +See +[TransactionOptions.ReadOnly.read\_timestamp][google.spanner.v1.TransactionOptions.ReadOnly.read\_timestamp] +and +[TransactionOptions.ReadOnly.exact\_staleness][google.spanner.v1.TransactionOptions.ReadOnly.exact\_staleness]. + +Bounded Staleness +~~~~~~~~~~~~~~~~~ + +Bounded staleness modes allow Cloud Spanner to pick the read timestamp, +subject to a user-provided staleness bound. Cloud Spanner chooses the +newest timestamp within the staleness bound that allows execution of the +reads at the closest available replica without blocking. + +All rows yielded are consistent with each other -- if any part of the +read observes a transaction, all parts of the read see the transaction. +Boundedly stale reads are not repeatable: two stale reads, even if they +use the same staleness bound, can execute at different timestamps and +thus return inconsistent results. + +Boundedly stale reads execute in two phases: the first phase negotiates +a timestamp among all replicas needed to serve the read. In the second +phase, reads are executed at the negotiated timestamp. + +As a result of the two phase execution, bounded staleness reads are +usually a little slower than comparable exact staleness reads. However, +they are typically able to return fresher results, and are more likely +to execute at the closest replica. + +Because the timestamp negotiation requires up-front knowledge of which +rows will be read, it can only be used with single-use read-only +transactions. + +See +[TransactionOptions.ReadOnly.max\_staleness][google.spanner.v1.TransactionOptions.ReadOnly.max\_staleness] +and +[TransactionOptions.ReadOnly.min\_read\_timestamp][google.spanner.v1.TransactionOptions.ReadOnly.min\_read\_timestamp]. + +Old Read Timestamps and Garbage Collection +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Cloud Spanner continuously garbage collects deleted and overwritten data +in the background to reclaim storage space. This process is known as +"version GC". By default, version GC reclaims versions after they are +one hour old. Because of this, Cloud Spanner cannot perform reads at +read timestamps more than one hour in the past. This restriction also +applies to in-progress reads and/or SQL queries whose timestamp become +too old while executing. Reads and SQL queries with too-old read +timestamps fail with the error ``FAILED_PRECONDITION``. diff --git a/docs/spanner/gapic/v1/types.rst b/docs/spanner/gapic/v1/types.rst new file mode 100644 index 000000000000..28956e60c769 --- /dev/null +++ b/docs/spanner/gapic/v1/types.rst @@ -0,0 +1,5 @@ +Spanner Client Types +=================================== + +.. automodule:: google.cloud.spanner_v1.types + :members: diff --git a/docs/spanner/instance-api.rst b/docs/spanner/instance-api.rst index 181bed686b28..127b4c687372 100644 --- a/docs/spanner/instance-api.rst +++ b/docs/spanner/instance-api.rst @@ -1,7 +1,7 @@ Instance API ============ -.. automodule:: google.cloud.spanner.instance +.. automodule:: google.cloud.spanner_v1.instance :members: :show-inheritance: diff --git a/docs/spanner/instance-usage.rst b/docs/spanner/instance-usage.rst index f3b254e4f808..909e36b93f98 100644 --- a/docs/spanner/instance-usage.rst +++ b/docs/spanner/instance-usage.rst @@ -1,5 +1,5 @@ -Instance Admin API -================== +Instance Admin +============== After creating a :class:`~google.cloud.spanner.client.Client`, you can interact with individual instances for a project. @@ -11,13 +11,14 @@ Each instance within a project maps to a named "instance configuration", specifying the location and other parameters for a set of instances. These configurations are defined by the server, and cannot be changed. -To list of all instance configurations available to your project, use the +To iterate over all instance configurations available to your project, use the :meth:`~google.cloud.spanner.client.Client.list_instance_configs` method of the client: .. code:: python - configs, token = client.list_instance_configs() + for config in client.list_instance_configs(): + # `config` is an instance of `InstanceConfig` To fetch a single instance configuration, use the @@ -28,17 +29,24 @@ method of the client: config = client.get_instance_configuration('config-name') +Each of these methods provide +:class:`~.spanner_admin_instance_v1.types.InstanceConfig` objects. + List Instances -------------- -If you want a comprehensive list of all existing instances, use the +If you want a comprehensive list of all existing instances, iterate over the :meth:`~google.cloud.spanner.client.Client.list_instances` method of the client: .. code:: python - instances, token = client.list_instances() + for instance in client.list_instances(): + # `instance` is an instance of `Instance` + +This iterator yields :class:`~.spanner_admin_instance_v1.types.Instance` +objects. Instance Factory @@ -57,7 +65,7 @@ To create a :class:`~google.cloud.spanner.instance.Instance` object: - ``configuration_name`` is the name of the instance configuration to which the instance will be bound. It must be one of the names configured for your project, discoverable via - :meth:`google.cloud.spanner.client.Client.list_instance_configs`. + :meth:`~google.cloud.spanner.client.Client.list_instance_configs`. - ``node_count`` is a postitive integral count of the number of nodes used by the instance. More nodes allows for higher performance, but at a higher @@ -141,32 +149,24 @@ Delete an instance using its .. _check-on-current-instance-operation: -Check on Current Instance Operation ------------------------------------ +Resolve Current Instance Operation +---------------------------------- The :meth:`~google.cloud.spanner.instance.Instance.create` and :meth:`~google.cloud.spanner.instance.Instance.update` methods of instance object trigger long-running operations on the server, and return instances of the :class:`~google.cloud.spanner.instance.Operation` class. -You can check if a long-running operation has finished -by using its :meth:`~google.cloud.spanner.instance.Operation.finished` -method: +If you want to block on the completion of those operations, use the +``result`` method on the returned objects: .. code:: python >>> operation = instance.create() - >>> operation.finished() - True + >>> result = operation.result() -.. note:: +This method will raise an exception if the operation fails. - Once an :class:`~google.cloud.spanner.instance.Operation` object - has returned :data:`True` from its - :meth:`~google.cloud.spanner.instance.Operation.finished` method, the - object should not be re-used. Subsequent calls to - :meth:`~google.cloud.spanner.instance.Operation.finished` - will result in an :exc`ValueError` being raised. Next Step --------- diff --git a/docs/spanner/keyset-api.rst b/docs/spanner/keyset-api.rst index 3f46c6dc95f6..90137cf87640 100644 --- a/docs/spanner/keyset-api.rst +++ b/docs/spanner/keyset-api.rst @@ -1,7 +1,7 @@ Keyset API ========== -.. automodule:: google.cloud.spanner.keyset +.. automodule:: google.cloud.spanner_v1.keyset :members: :show-inheritance: diff --git a/docs/spanner/session-api.rst b/docs/spanner/session-api.rst index b41c3e6b8c20..1f6d0ac60261 100644 --- a/docs/spanner/session-api.rst +++ b/docs/spanner/session-api.rst @@ -1,7 +1,7 @@ Session API =========== -.. automodule:: google.cloud.spanner.session +.. automodule:: google.cloud.spanner_v1.session :members: :show-inheritance: @@ -9,7 +9,7 @@ Session API Session Pools API ================= -.. automodule:: google.cloud.spanner.pool +.. automodule:: google.cloud.spanner_v1.pool :members: :show-inheritance: diff --git a/docs/spanner/snapshot-api.rst b/docs/spanner/snapshot-api.rst index b28d55a19feb..26b697ae20e5 100644 --- a/docs/spanner/snapshot-api.rst +++ b/docs/spanner/snapshot-api.rst @@ -1,7 +1,7 @@ Snapshot API ============ -.. automodule:: google.cloud.spanner.snapshot +.. automodule:: google.cloud.spanner_v1.snapshot :members: :show-inheritance: diff --git a/docs/spanner/streamed-api.rst b/docs/spanner/streamed-api.rst index e17180accf8b..53bab89ba491 100644 --- a/docs/spanner/streamed-api.rst +++ b/docs/spanner/streamed-api.rst @@ -1,7 +1,7 @@ StreamedResultSet API ===================== -.. automodule:: google.cloud.spanner.streamed +.. automodule:: google.cloud.spanner_v1.streamed :members: :show-inheritance: diff --git a/docs/spanner/transaction-api.rst b/docs/spanner/transaction-api.rst index c16213de54bd..6657676db199 100644 --- a/docs/spanner/transaction-api.rst +++ b/docs/spanner/transaction-api.rst @@ -1,7 +1,7 @@ Transaction API =============== -.. automodule:: google.cloud.spanner.transaction +.. automodule:: google.cloud.spanner_v1.transaction :members: :show-inheritance: diff --git a/docs/spanner/transaction-usage.rst b/docs/spanner/transaction-usage.rst index 0577bc2093b8..85eeccb9555d 100644 --- a/docs/spanner/transaction-usage.rst +++ b/docs/spanner/transaction-usage.rst @@ -5,6 +5,9 @@ A :class:`~google.cloud.spanner.transaction.Transaction` represents a transaction: when the transaction commits, it will send any accumulated mutations to the server. +To understand more about how transactions work, visit :ref:`spanner-txn`. +To learn more about how to use them in the Python client, continue reading. + Begin a Transaction ------------------- diff --git a/docs/spanner/usage.rst b/docs/spanner/usage.rst index 762ec3894b03..87980f520501 100644 --- a/docs/spanner/usage.rst +++ b/docs/spanner/usage.rst @@ -1,41 +1,100 @@ Spanner -======= +^^^^^^^ + +`Cloud Spanner`_ is the world's first fully managed relational database service +to offer both strong consistency and horizontal scalability for +mission-critical online transaction processing (OLTP) applications. With Cloud +Spanner you enjoy all the traditional benefits of a relational database; but +unlike any other relational database service, Cloud Spanner scales horizontally +to hundreds or thousands of servers to handle the biggest transactional +workloads. + +.. _Cloud Spanner: https://cloud.google.com/spanner/ .. toctree:: - :maxdepth: 2 + :maxdepth: 1 + :titlesonly: :hidden: - client-usage instance-usage database-usage batch-usage snapshot-usage transaction-usage advanced-session-pool-topics + api-reference + +Spanner Client +============== + +.. _spanner-client: + + +Instantiating a Client +---------------------- + +To use the API, the :class:`~google.cloud.spanner.client.Client` +class defines a high-level interface which handles authorization +and creating other objects: + +.. code:: python + + from google.cloud import spanner + client = spanner.Client() + +Long-lived Defaults +------------------- + +When creating a :class:`~google.cloud.spanner.client.Client`, the +``user_agent`` and ``timeout_seconds`` arguments have sensible +defaults +(:data:`~google.cloud.spanner.client.DEFAULT_USER_AGENT` and +:data:`~google.cloud.spanner.client.DEFAULT_TIMEOUT_SECONDS`). +However, you may over-ride them and these will be used throughout all API +requests made with the ``client`` you create. + +Configuration +------------- + +- For an overview of authentication in ``google.cloud-python``, + see :doc:`/core/auth`. + +- In addition to any authentication configuration, you can also set the + :envvar:`GCLOUD_PROJECT` environment variable for the Google Cloud Console + project you'd like to interact with. If your code is running in Google App + Engine or Google Compute Engine the project will be detected automatically. + (Setting this environment variable is not required, you may instead pass the + ``project`` explicitly when constructing a + :class:`~google.cloud.storage.client.Client`). + +- After configuring your environment, create a + :class:`~google.cloud.storage.client.Client` + + .. code:: + + >>> from google.cloud import spanner + >>> client = spanner.Client() + + or pass in ``credentials`` and ``project`` explicitly + + .. code:: + + >>> from google.cloud import spanner + >>> client = spanner.Client(project='my-project', credentials=creds) + +.. tip:: - client-api - instance-api - database-api - session-api - keyset-api - snapshot-api - batch-api - transaction-api - streamed-api + Be sure to use the **Project ID**, not the **Project Number**. -API requests are sent to the `Cloud Spanner`_ API via RPC over -HTTP/2. In order to support this, we'll rely on `gRPC`_. -Get started by learning about the :class:`~google.cloud.spanner.client.Client` -on the :doc:`client-usage` page. +Next Step +--------- -In the hierarchy of API concepts +After a :class:`~google.cloud.spanner.client.Client`, the next +highest-level object is an :class:`~google.cloud.spanner.instance.Instance`. +You'll need one before you can interact with databases. -* a :class:`~google.cloud.spanner.client.Client` owns an - :class:`~google.cloud.spanner.instance.Instance` -* an :class:`~google.cloud.spanner.instance.Instance` owns a - :class:`~google.cloud.spanner.database.Database` +Next, learn about the :doc:`instance-usage`. -.. _Cloud Spanner: https://cloud.google.com/spanner/docs/ -.. _gRPC: http://www.grpc.io/ -.. _grpcio: https://pypi.org/project/grpcio/ +.. _Instance Admin: https://cloud.google.com/spanner/reference/rpc/google.spanner.admin.instance.v1 +.. _Database Admin: https://cloud.google.com/spanner/reference/rpc/google.spanner.admin.database.v1 diff --git a/spanner/google/cloud/spanner.py b/spanner/google/cloud/spanner.py new file mode 100644 index 000000000000..1c49d22b406a --- /dev/null +++ b/spanner/google/cloud/spanner.py @@ -0,0 +1,42 @@ +# Copyright 2016 Google Inc. All rights reserved. +# +# 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 +# +# http://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. + +"""Cloud Spanner API package.""" + +from __future__ import absolute_import + +from google.cloud.spanner_v1 import __version__ +from google.cloud.spanner_v1 import AbstractSessionPool +from google.cloud.spanner_v1 import BurstyPool +from google.cloud.spanner_v1 import Client +from google.cloud.spanner_v1 import enums +from google.cloud.spanner_v1 import FixedSizePool +from google.cloud.spanner_v1 import KeyRange +from google.cloud.spanner_v1 import KeySet +from google.cloud.spanner_v1 import param_types +from google.cloud.spanner_v1 import types + + +__all__ = ( + '__version__', + 'AbstractSessionPool', + 'BurstyPool', + 'Client', + 'enums', + 'FixedSizePool', + 'KeyRange', + 'KeySet', + 'param_types', + 'types', +) diff --git a/spanner/google/cloud/spanner/__init__.py b/spanner/google/cloud/spanner/__init__.py deleted file mode 100644 index 244bdb868f9a..000000000000 --- a/spanner/google/cloud/spanner/__init__.py +++ /dev/null @@ -1,60 +0,0 @@ -# Copyright 2016 Google Inc. All rights reserved. -# -# 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 -# -# http://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. - -"""Cloud Spanner API package.""" - - -import pkg_resources -__version__ = pkg_resources.get_distribution('google-cloud-spanner').version - -from google.cloud.spanner.client import Client - -from google.cloud.spanner.keyset import KeyRange -from google.cloud.spanner.keyset import KeySet - -from google.cloud.spanner.pool import AbstractSessionPool -from google.cloud.spanner.pool import BurstyPool -from google.cloud.spanner.pool import FixedSizePool - -from google.cloud.spanner.types import ArrayParamType -from google.cloud.spanner.types import BOOL_PARAM_TYPE -from google.cloud.spanner.types import BYTES_PARAM_TYPE -from google.cloud.spanner.types import DATE_PARAM_TYPE -from google.cloud.spanner.types import FLOAT64_PARAM_TYPE -from google.cloud.spanner.types import INT64_PARAM_TYPE -from google.cloud.spanner.types import STRING_PARAM_TYPE -from google.cloud.spanner.types import StructField -from google.cloud.spanner.types import StructParamType -from google.cloud.spanner.types import TIMESTAMP_PARAM_TYPE - - -__all__ = [ - '__version__', - 'AbstractSessionPool', - 'ArrayParamType', - 'BOOL_PARAM_TYPE', - 'BYTES_PARAM_TYPE', - 'BurstyPool', - 'Client', - 'DATE_PARAM_TYPE', - 'FLOAT64_PARAM_TYPE', - 'FixedSizePool', - 'INT64_PARAM_TYPE', - 'KeyRange', - 'KeySet', - 'STRING_PARAM_TYPE', - 'StructField', - 'StructParamType', - 'TIMESTAMP_PARAM_TYPE', -] diff --git a/spanner/google/cloud/spanner_admin_database_v1/__init__.py b/spanner/google/cloud/spanner_admin_database_v1/__init__.py new file mode 100644 index 000000000000..b8f44082b9c5 --- /dev/null +++ b/spanner/google/cloud/spanner_admin_database_v1/__init__.py @@ -0,0 +1,30 @@ +# Copyright 2017, Google Inc. All rights reserved. +# +# 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 +# +# http://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. + +from __future__ import absolute_import + +from google.cloud.spanner_admin_database_v1 import types +from google.cloud.spanner_admin_database_v1.gapic import database_admin_client +from google.cloud.spanner_admin_database_v1.gapic import enums + + +class DatabaseAdminClient(database_admin_client.DatabaseAdminClient): + __doc__ = database_admin_client.DatabaseAdminClient.__doc__ + enums = enums + + +__all__ = ( + 'enums', + 'types', + 'DatabaseAdminClient', ) diff --git a/spanner/google/cloud/spanner_admin_database_v1/gapic/__init__.py b/spanner/google/cloud/spanner_admin_database_v1/gapic/__init__.py new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/spanner/google/cloud/spanner_admin_database_v1/gapic/database_admin_client.py b/spanner/google/cloud/spanner_admin_database_v1/gapic/database_admin_client.py new file mode 100644 index 000000000000..37df1dc16090 --- /dev/null +++ b/spanner/google/cloud/spanner_admin_database_v1/gapic/database_admin_client.py @@ -0,0 +1,663 @@ +# Copyright 2017, Google Inc. All rights reserved. +# +# 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 +# +# http://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. +# +# EDITING INSTRUCTIONS +# This file was generated from the file +# https://github.com/google/googleapis/blob/master/google/spanner/admin/database/v1/spanner_database_admin.proto, +# and updates to that file get reflected here through a refresh process. +# For the short term, the refresh process will only be runnable by Google engineers. +# +# The only allowed edits are to method and file documentation. A 3-way +# merge preserves those additions if the generated source changes. +"""Accesses the google.spanner.admin.database.v1 DatabaseAdmin API.""" + +import collections +import json +import os +import pkg_resources +import platform + +from google.gapic.longrunning import operations_client +from google.gax import api_callable +from google.gax import config +from google.gax import path_template +import google.gax + +from google.cloud.spanner_admin_database_v1.gapic import database_admin_client_config +from google.cloud.spanner_admin_database_v1.gapic import enums +from google.cloud.spanner_admin_database_v1.proto import spanner_database_admin_pb2 +from google.iam.v1 import iam_policy_pb2 +from google.iam.v1 import policy_pb2 +from google.protobuf import empty_pb2 + +_PageDesc = google.gax.PageDescriptor + + +class DatabaseAdminClient(object): + """ + Cloud Spanner Database Admin API + + The Cloud Spanner Database Admin API can be used to create, drop, and + list databases. It also enables updating the schema of pre-existing + databases. + """ + + SERVICE_ADDRESS = 'spanner.googleapis.com' + """The default address of the service.""" + + DEFAULT_SERVICE_PORT = 443 + """The default port of the service.""" + + _PAGE_DESCRIPTORS = { + 'list_databases': _PageDesc('page_token', 'next_page_token', + 'databases') + } + + # The scopes needed to make gRPC calls to all of the methods defined in + # this service + _ALL_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/spanner.admin', ) + + _INSTANCE_PATH_TEMPLATE = path_template.PathTemplate( + 'projects/{project}/instances/{instance}') + _DATABASE_PATH_TEMPLATE = path_template.PathTemplate( + 'projects/{project}/instances/{instance}/databases/{database}') + + @classmethod + def instance_path(cls, project, instance): + """Returns a fully-qualified instance resource name string.""" + return cls._INSTANCE_PATH_TEMPLATE.render({ + 'project': project, + 'instance': instance, + }) + + @classmethod + def database_path(cls, project, instance, database): + """Returns a fully-qualified database resource name string.""" + return cls._DATABASE_PATH_TEMPLATE.render({ + 'project': project, + 'instance': instance, + 'database': database, + }) + + @classmethod + def match_project_from_instance_name(cls, instance_name): + """Parses the project from a instance resource. + + Args: + instance_name (str): A fully-qualified path representing a instance + resource. + + Returns: + A string representing the project. + """ + return cls._INSTANCE_PATH_TEMPLATE.match(instance_name).get('project') + + @classmethod + def match_instance_from_instance_name(cls, instance_name): + """Parses the instance from a instance resource. + + Args: + instance_name (str): A fully-qualified path representing a instance + resource. + + Returns: + A string representing the instance. + """ + return cls._INSTANCE_PATH_TEMPLATE.match(instance_name).get('instance') + + @classmethod + def match_project_from_database_name(cls, database_name): + """Parses the project from a database resource. + + Args: + database_name (str): A fully-qualified path representing a database + resource. + + Returns: + A string representing the project. + """ + return cls._DATABASE_PATH_TEMPLATE.match(database_name).get('project') + + @classmethod + def match_instance_from_database_name(cls, database_name): + """Parses the instance from a database resource. + + Args: + database_name (str): A fully-qualified path representing a database + resource. + + Returns: + A string representing the instance. + """ + return cls._DATABASE_PATH_TEMPLATE.match(database_name).get('instance') + + @classmethod + def match_database_from_database_name(cls, database_name): + """Parses the database from a database resource. + + Args: + database_name (str): A fully-qualified path representing a database + resource. + + Returns: + A string representing the database. + """ + return cls._DATABASE_PATH_TEMPLATE.match(database_name).get('database') + + def __init__(self, + channel=None, + credentials=None, + ssl_credentials=None, + scopes=None, + client_config=None, + lib_name=None, + lib_version='', + metrics_headers=()): + """Constructor. + + Args: + channel (~grpc.Channel): A ``Channel`` instance through + which to make calls. + credentials (~google.auth.credentials.Credentials): The authorization + credentials to attach to requests. These credentials identify this + application to the service. + ssl_credentials (~grpc.ChannelCredentials): A + ``ChannelCredentials`` instance for use with an SSL-enabled + channel. + scopes (Sequence[str]): A list of OAuth2 scopes to attach to requests. + client_config (dict): + A dictionary for call options for each method. See + :func:`google.gax.construct_settings` for the structure of + this data. Falls back to the default config if not specified + or the specified config is missing data points. + lib_name (str): The API library software used for calling + the service. (Unless you are writing an API client itself, + leave this as default.) + lib_version (str): The API library software version used + for calling the service. (Unless you are writing an API client + itself, leave this as default.) + metrics_headers (dict): A dictionary of values for tracking + client library metrics. Ultimately serializes to a string + (e.g. 'foo/1.2.3 bar/3.14.1'). This argument should be + considered private. + """ + # Unless the calling application specifically requested + # OAuth scopes, request everything. + if scopes is None: + scopes = self._ALL_SCOPES + + # Initialize an empty client config, if none is set. + if client_config is None: + client_config = {} + + # Initialize metrics_headers as an ordered dictionary + # (cuts down on cardinality of the resulting string slightly). + metrics_headers = collections.OrderedDict(metrics_headers) + metrics_headers['gl-python'] = platform.python_version() + + # The library may or may not be set, depending on what is + # calling this client. Newer client libraries set the library name + # and version. + if lib_name: + metrics_headers[lib_name] = lib_version + + # Finally, track the GAPIC package version. + metrics_headers['gapic'] = pkg_resources.get_distribution( + 'google-cloud-spanner', ).version + + # Load the configuration defaults. + defaults = api_callable.construct_settings( + 'google.spanner.admin.database.v1.DatabaseAdmin', + database_admin_client_config.config, + client_config, + config.STATUS_CODE_NAMES, + metrics_headers=metrics_headers, + page_descriptors=self._PAGE_DESCRIPTORS, ) + self.database_admin_stub = config.create_stub( + spanner_database_admin_pb2.DatabaseAdminStub, + channel=channel, + service_path=self.SERVICE_ADDRESS, + service_port=self.DEFAULT_SERVICE_PORT, + credentials=credentials, + scopes=scopes, + ssl_credentials=ssl_credentials) + + self.operations_client = operations_client.OperationsClient( + service_path=self.SERVICE_ADDRESS, + channel=channel, + credentials=credentials, + ssl_credentials=ssl_credentials, + scopes=scopes, + client_config=client_config, + metrics_headers=metrics_headers, ) + + self._list_databases = api_callable.create_api_call( + self.database_admin_stub.ListDatabases, + settings=defaults['list_databases']) + self._create_database = api_callable.create_api_call( + self.database_admin_stub.CreateDatabase, + settings=defaults['create_database']) + self._get_database = api_callable.create_api_call( + self.database_admin_stub.GetDatabase, + settings=defaults['get_database']) + self._update_database_ddl = api_callable.create_api_call( + self.database_admin_stub.UpdateDatabaseDdl, + settings=defaults['update_database_ddl']) + self._drop_database = api_callable.create_api_call( + self.database_admin_stub.DropDatabase, + settings=defaults['drop_database']) + self._get_database_ddl = api_callable.create_api_call( + self.database_admin_stub.GetDatabaseDdl, + settings=defaults['get_database_ddl']) + self._set_iam_policy = api_callable.create_api_call( + self.database_admin_stub.SetIamPolicy, + settings=defaults['set_iam_policy']) + self._get_iam_policy = api_callable.create_api_call( + self.database_admin_stub.GetIamPolicy, + settings=defaults['get_iam_policy']) + self._test_iam_permissions = api_callable.create_api_call( + self.database_admin_stub.TestIamPermissions, + settings=defaults['test_iam_permissions']) + + # Service calls + def list_databases(self, parent, page_size=None, options=None): + """ + Lists Cloud Spanner databases. + + Example: + >>> from google.cloud import spanner_admin_database_v1 + >>> from google.gax import CallOptions, INITIAL_PAGE + >>> + >>> client = spanner_admin_database_v1.DatabaseAdminClient() + >>> + >>> parent = client.instance_path('[PROJECT]', '[INSTANCE]') + >>> + >>> + >>> # Iterate over all results + >>> for element in client.list_databases(parent): + ... # process element + ... pass + >>> + >>> # Or iterate over results one page at a time + >>> for page in client.list_databases(parent, options=CallOptions(page_token=INITIAL_PAGE)): + ... for element in page: + ... # process element + ... pass + + Args: + parent (str): Required. The instance whose databases should be listed. + Values are of the form ``projects//instances/``. + page_size (int): The maximum number of resources contained in the + underlying API response. If page streaming is performed per- + resource, this parameter does not affect the return value. If page + streaming is performed per-page, this determines the maximum number + of resources in a page. + options (~google.gax.CallOptions): Overrides the default + settings for this call, e.g, timeout, retries etc. + + Returns: + A :class:`~google.gax.PageIterator` instance. By default, this + is an iterable of :class:`~google.cloud.spanner_admin_database_v1.types.Database` instances. + This object can also be configured to iterate over the pages + of the response through the `options` parameter. + + Raises: + :exc:`google.gax.errors.GaxError` if the RPC is aborted. + :exc:`ValueError` if the parameters are invalid. + """ + request = spanner_database_admin_pb2.ListDatabasesRequest( + parent=parent, page_size=page_size) + return self._list_databases(request, options) + + def create_database(self, + parent, + create_statement, + extra_statements=None, + options=None): + """ + Creates a new Cloud Spanner database and starts to prepare it for serving. + The returned ``long-running operation`` will + have a name of the format ``/operations/`` and + can be used to track preparation of the database. The + ``metadata`` field type is + ``CreateDatabaseMetadata``. The + ``response`` field type is + ``Database``, if successful. + + Example: + >>> from google.cloud import spanner_admin_database_v1 + >>> + >>> client = spanner_admin_database_v1.DatabaseAdminClient() + >>> + >>> parent = client.instance_path('[PROJECT]', '[INSTANCE]') + >>> create_statement = '' + >>> + >>> response = client.create_database(parent, create_statement) + >>> + >>> def callback(operation_future): + ... # Handle result. + ... result = operation_future.result() + >>> + >>> response.add_done_callback(callback) + >>> + >>> # Handle metadata. + >>> metadata = response.metadata() + + Args: + parent (str): Required. The name of the instance that will serve the new database. + Values are of the form ``projects//instances/``. + create_statement (str): Required. A ``CREATE DATABASE`` statement, which specifies the ID of the + new database. The database ID must conform to the regular expression + ``[a-z][a-z0-9_\-]*[a-z0-9]`` and be between 2 and 30 characters in length. + extra_statements (list[str]): An optional list of DDL statements to run inside the newly created + database. Statements can create tables, indexes, etc. These + statements execute atomically with the creation of the database: + if there is an error in any statement, the database is not created. + options (~google.gax.CallOptions): Overrides the default + settings for this call, e.g, timeout, retries etc. + + Returns: + A :class:`~google.cloud.spanner_admin_database_v1.types._OperationFuture` instance. + + Raises: + :exc:`google.gax.errors.GaxError` if the RPC is aborted. + :exc:`ValueError` if the parameters are invalid. + """ + request = spanner_database_admin_pb2.CreateDatabaseRequest( + parent=parent, + create_statement=create_statement, + extra_statements=extra_statements) + return google.gax._OperationFuture( + self._create_database(request, options), self.operations_client, + spanner_database_admin_pb2.Database, + spanner_database_admin_pb2.CreateDatabaseMetadata, options) + + def get_database(self, name, options=None): + """ + Gets the state of a Cloud Spanner database. + + Example: + >>> from google.cloud import spanner_admin_database_v1 + >>> + >>> client = spanner_admin_database_v1.DatabaseAdminClient() + >>> + >>> name = client.database_path('[PROJECT]', '[INSTANCE]', '[DATABASE]') + >>> + >>> response = client.get_database(name) + + Args: + name (str): Required. The name of the requested database. Values are of the form + ``projects//instances//databases/``. + options (~google.gax.CallOptions): Overrides the default + settings for this call, e.g, timeout, retries etc. + + Returns: + A :class:`~google.cloud.spanner_admin_database_v1.types.Database` instance. + + Raises: + :exc:`google.gax.errors.GaxError` if the RPC is aborted. + :exc:`ValueError` if the parameters are invalid. + """ + request = spanner_database_admin_pb2.GetDatabaseRequest(name=name) + return self._get_database(request, options) + + def update_database_ddl(self, + database, + statements, + operation_id=None, + options=None): + """ + Updates the schema of a Cloud Spanner database by + creating/altering/dropping tables, columns, indexes, etc. The returned + ``long-running operation`` will have a name of + the format ``/operations/`` and can be used to + track execution of the schema change(s). The + ``metadata`` field type is + ``UpdateDatabaseDdlMetadata``. The operation has no response. + + Example: + >>> from google.cloud import spanner_admin_database_v1 + >>> + >>> client = spanner_admin_database_v1.DatabaseAdminClient() + >>> + >>> database = client.database_path('[PROJECT]', '[INSTANCE]', '[DATABASE]') + >>> statements = [] + >>> + >>> response = client.update_database_ddl(database, statements) + >>> + >>> def callback(operation_future): + ... # Handle result. + ... result = operation_future.result() + >>> + >>> response.add_done_callback(callback) + >>> + >>> # Handle metadata. + >>> metadata = response.metadata() + + Args: + database (str): Required. The database to update. + statements (list[str]): DDL statements to be applied to the database. + operation_id (str): If empty, the new update request is assigned an + automatically-generated operation ID. Otherwise, ``operation_id`` + is used to construct the name of the resulting + ``Operation``. + + Specifying an explicit operation ID simplifies determining + whether the statements were executed in the event that the + ``UpdateDatabaseDdl`` call is replayed, + or the return value is otherwise lost: the ``database`` and + ``operation_id`` fields can be combined to form the + ``name`` of the resulting + ``longrunning.Operation``: ``/operations/``. + + ``operation_id`` should be unique within the database, and must be + a valid identifier: ``[a-z][a-z0-9_]*``. Note that + automatically-generated operation IDs always begin with an + underscore. If the named operation already exists, + ``UpdateDatabaseDdl`` returns + ``ALREADY_EXISTS``. + options (~google.gax.CallOptions): Overrides the default + settings for this call, e.g, timeout, retries etc. + + Returns: + A :class:`~google.cloud.spanner_admin_database_v1.types._OperationFuture` instance. + + Raises: + :exc:`google.gax.errors.GaxError` if the RPC is aborted. + :exc:`ValueError` if the parameters are invalid. + """ + request = spanner_database_admin_pb2.UpdateDatabaseDdlRequest( + database=database, + statements=statements, + operation_id=operation_id) + return google.gax._OperationFuture( + self._update_database_ddl(request, options), + self.operations_client, empty_pb2.Empty, + spanner_database_admin_pb2.UpdateDatabaseDdlMetadata, options) + + def drop_database(self, database, options=None): + """ + Drops (aka deletes) a Cloud Spanner database. + + Example: + >>> from google.cloud import spanner_admin_database_v1 + >>> + >>> client = spanner_admin_database_v1.DatabaseAdminClient() + >>> + >>> database = client.database_path('[PROJECT]', '[INSTANCE]', '[DATABASE]') + >>> + >>> client.drop_database(database) + + Args: + database (str): Required. The database to be dropped. + options (~google.gax.CallOptions): Overrides the default + settings for this call, e.g, timeout, retries etc. + + Raises: + :exc:`google.gax.errors.GaxError` if the RPC is aborted. + :exc:`ValueError` if the parameters are invalid. + """ + request = spanner_database_admin_pb2.DropDatabaseRequest( + database=database) + self._drop_database(request, options) + + def get_database_ddl(self, database, options=None): + """ + Returns the schema of a Cloud Spanner database as a list of formatted + DDL statements. This method does not show pending schema updates, those may + be queried using the ``Operations`` API. + + Example: + >>> from google.cloud import spanner_admin_database_v1 + >>> + >>> client = spanner_admin_database_v1.DatabaseAdminClient() + >>> + >>> database = client.database_path('[PROJECT]', '[INSTANCE]', '[DATABASE]') + >>> + >>> response = client.get_database_ddl(database) + + Args: + database (str): Required. The database whose schema we wish to get. + options (~google.gax.CallOptions): Overrides the default + settings for this call, e.g, timeout, retries etc. + + Returns: + A :class:`~google.cloud.spanner_admin_database_v1.types.GetDatabaseDdlResponse` instance. + + Raises: + :exc:`google.gax.errors.GaxError` if the RPC is aborted. + :exc:`ValueError` if the parameters are invalid. + """ + request = spanner_database_admin_pb2.GetDatabaseDdlRequest( + database=database) + return self._get_database_ddl(request, options) + + def set_iam_policy(self, resource, policy, options=None): + """ + Sets the access control policy on a database resource. Replaces any + existing policy. + + Authorization requires ``spanner.databases.setIamPolicy`` permission on + ``resource``. + + Example: + >>> from google.cloud import spanner_admin_database_v1 + >>> + >>> client = spanner_admin_database_v1.DatabaseAdminClient() + >>> + >>> resource = client.database_path('[PROJECT]', '[INSTANCE]', '[DATABASE]') + >>> policy = {} + >>> + >>> response = client.set_iam_policy(resource, policy) + + Args: + resource (str): REQUIRED: The resource for which the policy is being specified. + ``resource`` is usually specified as a path. For example, a Project + resource is specified as ``projects/{project}``. + policy (Union[dict, ~google.cloud.spanner_admin_database_v1.types.Policy]): REQUIRED: The complete policy to be applied to the ``resource``. The size of + the policy is limited to a few 10s of KB. An empty policy is a + valid policy but certain Cloud Platform services (such as Projects) + might reject them. + If a dict is provided, it must be of the same form as the protobuf + message :class:`~google.cloud.spanner_admin_database_v1.types.Policy` + options (~google.gax.CallOptions): Overrides the default + settings for this call, e.g, timeout, retries etc. + + Returns: + A :class:`~google.cloud.spanner_admin_database_v1.types.Policy` instance. + + Raises: + :exc:`google.gax.errors.GaxError` if the RPC is aborted. + :exc:`ValueError` if the parameters are invalid. + """ + request = iam_policy_pb2.SetIamPolicyRequest( + resource=resource, policy=policy) + return self._set_iam_policy(request, options) + + def get_iam_policy(self, resource, options=None): + """ + Gets the access control policy for a database resource. Returns an empty + policy if a database exists but does not have a policy set. + + Authorization requires ``spanner.databases.getIamPolicy`` permission on + ``resource``. + + Example: + >>> from google.cloud import spanner_admin_database_v1 + >>> + >>> client = spanner_admin_database_v1.DatabaseAdminClient() + >>> + >>> resource = client.database_path('[PROJECT]', '[INSTANCE]', '[DATABASE]') + >>> + >>> response = client.get_iam_policy(resource) + + Args: + resource (str): REQUIRED: The resource for which the policy is being requested. + ``resource`` is usually specified as a path. For example, a Project + resource is specified as ``projects/{project}``. + options (~google.gax.CallOptions): Overrides the default + settings for this call, e.g, timeout, retries etc. + + Returns: + A :class:`~google.cloud.spanner_admin_database_v1.types.Policy` instance. + + Raises: + :exc:`google.gax.errors.GaxError` if the RPC is aborted. + :exc:`ValueError` if the parameters are invalid. + """ + request = iam_policy_pb2.GetIamPolicyRequest(resource=resource) + return self._get_iam_policy(request, options) + + def test_iam_permissions(self, resource, permissions, options=None): + """ + Returns permissions that the caller has on the specified database resource. + + Attempting this RPC on a non-existent Cloud Spanner database will result in + a NOT_FOUND error if the user has ``spanner.databases.list`` permission on + the containing Cloud Spanner instance. Otherwise returns an empty set of + permissions. + + Example: + >>> from google.cloud import spanner_admin_database_v1 + >>> + >>> client = spanner_admin_database_v1.DatabaseAdminClient() + >>> + >>> resource = client.database_path('[PROJECT]', '[INSTANCE]', '[DATABASE]') + >>> permissions = [] + >>> + >>> response = client.test_iam_permissions(resource, permissions) + + Args: + resource (str): REQUIRED: The resource for which the policy detail is being requested. + ``resource`` is usually specified as a path. For example, a Project + resource is specified as ``projects/{project}``. + permissions (list[str]): The set of permissions to check for the ``resource``. Permissions with + wildcards (such as '*' or 'storage.*') are not allowed. For more + information see + `IAM Overview `_. + options (~google.gax.CallOptions): Overrides the default + settings for this call, e.g, timeout, retries etc. + + Returns: + A :class:`~google.cloud.spanner_admin_database_v1.types.TestIamPermissionsResponse` instance. + + Raises: + :exc:`google.gax.errors.GaxError` if the RPC is aborted. + :exc:`ValueError` if the parameters are invalid. + """ + request = iam_policy_pb2.TestIamPermissionsRequest( + resource=resource, permissions=permissions) + return self._test_iam_permissions(request, options) diff --git a/spanner/google/cloud/spanner_admin_database_v1/gapic/database_admin_client_config.py b/spanner/google/cloud/spanner_admin_database_v1/gapic/database_admin_client_config.py new file mode 100644 index 000000000000..b7ed930a9f1d --- /dev/null +++ b/spanner/google/cloud/spanner_admin_database_v1/gapic/database_admin_client_config.py @@ -0,0 +1,68 @@ +config = { + "interfaces": { + "google.spanner.admin.database.v1.DatabaseAdmin": { + "retry_codes": { + "idempotent": ["DEADLINE_EXCEEDED", "UNAVAILABLE"], + "non_idempotent": [] + }, + "retry_params": { + "default": { + "initial_retry_delay_millis": 1000, + "retry_delay_multiplier": 1.3, + "max_retry_delay_millis": 32000, + "initial_rpc_timeout_millis": 60000, + "rpc_timeout_multiplier": 1.0, + "max_rpc_timeout_millis": 60000, + "total_timeout_millis": 600000 + } + }, + "methods": { + "ListDatabases": { + "timeout_millis": 30000, + "retry_codes_name": "idempotent", + "retry_params_name": "default" + }, + "CreateDatabase": { + "timeout_millis": 30000, + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + }, + "GetDatabase": { + "timeout_millis": 30000, + "retry_codes_name": "idempotent", + "retry_params_name": "default" + }, + "UpdateDatabaseDdl": { + "timeout_millis": 30000, + "retry_codes_name": "idempotent", + "retry_params_name": "default" + }, + "DropDatabase": { + "timeout_millis": 30000, + "retry_codes_name": "idempotent", + "retry_params_name": "default" + }, + "GetDatabaseDdl": { + "timeout_millis": 30000, + "retry_codes_name": "idempotent", + "retry_params_name": "default" + }, + "SetIamPolicy": { + "timeout_millis": 30000, + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + }, + "GetIamPolicy": { + "timeout_millis": 30000, + "retry_codes_name": "idempotent", + "retry_params_name": "default" + }, + "TestIamPermissions": { + "timeout_millis": 30000, + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + } + } + } + } +} diff --git a/spanner/google/cloud/spanner_admin_database_v1/gapic/enums.py b/spanner/google/cloud/spanner_admin_database_v1/gapic/enums.py new file mode 100644 index 000000000000..4ce2fdcb556c --- /dev/null +++ b/spanner/google/cloud/spanner_admin_database_v1/gapic/enums.py @@ -0,0 +1,30 @@ +# Copyright 2017, Google Inc. All rights reserved. +# +# 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 +# +# http://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. +"""Wrappers for protocol buffer enum types.""" + + +class Database(object): + class State(object): + """ + Indicates the current state of the database. + + Attributes: + STATE_UNSPECIFIED (int): Not specified. + CREATING (int): The database is still being created. Operations on the database may fail + with ``FAILED_PRECONDITION`` in this state. + READY (int): The database is fully created and ready for use. + """ + STATE_UNSPECIFIED = 0 + CREATING = 1 + READY = 2 diff --git a/spanner/google/cloud/spanner_admin_database_v1/proto/__init__.py b/spanner/google/cloud/spanner_admin_database_v1/proto/__init__.py new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/spanner/google/cloud/spanner_admin_database_v1/proto/spanner_database_admin_pb2.py b/spanner/google/cloud/spanner_admin_database_v1/proto/spanner_database_admin_pb2.py new file mode 100644 index 000000000000..e0199e551cfd --- /dev/null +++ b/spanner/google/cloud/spanner_admin_database_v1/proto/spanner_database_admin_pb2.py @@ -0,0 +1,1223 @@ +# Generated by the protocol buffer compiler. DO NOT EDIT! +# source: google/cloud/spanner/admin/database_v1/proto/spanner_database_admin.proto + +import sys +_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) +from google.protobuf import descriptor as _descriptor +from google.protobuf import message as _message +from google.protobuf import reflection as _reflection +from google.protobuf import symbol_database as _symbol_database +from google.protobuf import descriptor_pb2 +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + + +from google.api import annotations_pb2 as google_dot_api_dot_annotations__pb2 +from google.api import auth_pb2 as google_dot_api_dot_auth__pb2 +from google.iam.v1 import iam_policy_pb2 as google_dot_iam_dot_v1_dot_iam__policy__pb2 +from google.iam.v1 import policy_pb2 as google_dot_iam_dot_v1_dot_policy__pb2 +from google.longrunning import operations_pb2 as google_dot_longrunning_dot_operations__pb2 +from google.protobuf import empty_pb2 as google_dot_protobuf_dot_empty__pb2 +from google.protobuf import timestamp_pb2 as google_dot_protobuf_dot_timestamp__pb2 + + +DESCRIPTOR = _descriptor.FileDescriptor( + name='google/cloud/spanner/admin/database_v1/proto/spanner_database_admin.proto', + package='google.spanner.admin.database.v1', + syntax='proto3', + serialized_pb=_b('\nIgoogle/cloud/spanner/admin/database_v1/proto/spanner_database_admin.proto\x12 google.spanner.admin.database.v1\x1a\x1cgoogle/api/annotations.proto\x1a\x15google/api/auth.proto\x1a\x1egoogle/iam/v1/iam_policy.proto\x1a\x1agoogle/iam/v1/policy.proto\x1a#google/longrunning/operations.proto\x1a\x1bgoogle/protobuf/empty.proto\x1a\x1fgoogle/protobuf/timestamp.proto\"\x92\x01\n\x08\x44\x61tabase\x12\x0c\n\x04name\x18\x01 \x01(\t\x12?\n\x05state\x18\x02 \x01(\x0e\x32\x30.google.spanner.admin.database.v1.Database.State\"7\n\x05State\x12\x15\n\x11STATE_UNSPECIFIED\x10\x00\x12\x0c\n\x08\x43REATING\x10\x01\x12\t\n\x05READY\x10\x02\"M\n\x14ListDatabasesRequest\x12\x0e\n\x06parent\x18\x01 \x01(\t\x12\x11\n\tpage_size\x18\x03 \x01(\x05\x12\x12\n\npage_token\x18\x04 \x01(\t\"o\n\x15ListDatabasesResponse\x12=\n\tdatabases\x18\x01 \x03(\x0b\x32*.google.spanner.admin.database.v1.Database\x12\x17\n\x0fnext_page_token\x18\x02 \x01(\t\"[\n\x15\x43reateDatabaseRequest\x12\x0e\n\x06parent\x18\x01 \x01(\t\x12\x18\n\x10\x63reate_statement\x18\x02 \x01(\t\x12\x18\n\x10\x65xtra_statements\x18\x03 \x03(\t\"*\n\x16\x43reateDatabaseMetadata\x12\x10\n\x08\x64\x61tabase\x18\x01 \x01(\t\"\"\n\x12GetDatabaseRequest\x12\x0c\n\x04name\x18\x01 \x01(\t\"V\n\x18UpdateDatabaseDdlRequest\x12\x10\n\x08\x64\x61tabase\x18\x01 \x01(\t\x12\x12\n\nstatements\x18\x02 \x03(\t\x12\x14\n\x0coperation_id\x18\x03 \x01(\t\"x\n\x19UpdateDatabaseDdlMetadata\x12\x10\n\x08\x64\x61tabase\x18\x01 \x01(\t\x12\x12\n\nstatements\x18\x02 \x03(\t\x12\x35\n\x11\x63ommit_timestamps\x18\x03 \x03(\x0b\x32\x1a.google.protobuf.Timestamp\"\'\n\x13\x44ropDatabaseRequest\x12\x10\n\x08\x64\x61tabase\x18\x01 \x01(\t\")\n\x15GetDatabaseDdlRequest\x12\x10\n\x08\x64\x61tabase\x18\x01 \x01(\t\",\n\x16GetDatabaseDdlResponse\x12\x12\n\nstatements\x18\x01 \x03(\t2\x95\x0c\n\rDatabaseAdmin\x12\xb7\x01\n\rListDatabases\x12\x36.google.spanner.admin.database.v1.ListDatabasesRequest\x1a\x37.google.spanner.admin.database.v1.ListDatabasesResponse\"5\x82\xd3\xe4\x93\x02/\x12-/v1/{parent=projects/*/instances/*}/databases\x12\xa2\x01\n\x0e\x43reateDatabase\x12\x37.google.spanner.admin.database.v1.CreateDatabaseRequest\x1a\x1d.google.longrunning.Operation\"8\x82\xd3\xe4\x93\x02\x32\"-/v1/{parent=projects/*/instances/*}/databases:\x01*\x12\xa6\x01\n\x0bGetDatabase\x12\x34.google.spanner.admin.database.v1.GetDatabaseRequest\x1a*.google.spanner.admin.database.v1.Database\"5\x82\xd3\xe4\x93\x02/\x12-/v1/{name=projects/*/instances/*/databases/*}\x12\xb0\x01\n\x11UpdateDatabaseDdl\x12:.google.spanner.admin.database.v1.UpdateDatabaseDdlRequest\x1a\x1d.google.longrunning.Operation\"@\x82\xd3\xe4\x93\x02:25/v1/{database=projects/*/instances/*/databases/*}/ddl:\x01*\x12\x98\x01\n\x0c\x44ropDatabase\x12\x35.google.spanner.admin.database.v1.DropDatabaseRequest\x1a\x16.google.protobuf.Empty\"9\x82\xd3\xe4\x93\x02\x33*1/v1/{database=projects/*/instances/*/databases/*}\x12\xc2\x01\n\x0eGetDatabaseDdl\x12\x37.google.spanner.admin.database.v1.GetDatabaseDdlRequest\x1a\x38.google.spanner.admin.database.v1.GetDatabaseDdlResponse\"=\x82\xd3\xe4\x93\x02\x37\x12\x35/v1/{database=projects/*/instances/*/databases/*}/ddl\x12\x94\x01\n\x0cSetIamPolicy\x12\".google.iam.v1.SetIamPolicyRequest\x1a\x15.google.iam.v1.Policy\"I\x82\xd3\xe4\x93\x02\x43\">/v1/{resource=projects/*/instances/*/databases/*}:setIamPolicy:\x01*\x12\x94\x01\n\x0cGetIamPolicy\x12\".google.iam.v1.GetIamPolicyRequest\x1a\x15.google.iam.v1.Policy\"I\x82\xd3\xe4\x93\x02\x43\">/v1/{resource=projects/*/instances/*/databases/*}:getIamPolicy:\x01*\x12\xba\x01\n\x12TestIamPermissions\x12(.google.iam.v1.TestIamPermissionsRequest\x1a).google.iam.v1.TestIamPermissionsResponse\"O\x82\xd3\xe4\x93\x02I\"D/v1/{resource=projects/*/instances/*/databases/*}:testIamPermissions:\x01*B\xb6\x01\n$com.google.spanner.admin.database.v1B\x19SpannerDatabaseAdminProtoP\x01ZHgoogle.golang.org/genproto/googleapis/spanner/admin/database/v1;database\xaa\x02&Google.Cloud.Spanner.Admin.Database.V1b\x06proto3') + , + dependencies=[google_dot_api_dot_annotations__pb2.DESCRIPTOR,google_dot_api_dot_auth__pb2.DESCRIPTOR,google_dot_iam_dot_v1_dot_iam__policy__pb2.DESCRIPTOR,google_dot_iam_dot_v1_dot_policy__pb2.DESCRIPTOR,google_dot_longrunning_dot_operations__pb2.DESCRIPTOR,google_dot_protobuf_dot_empty__pb2.DESCRIPTOR,google_dot_protobuf_dot_timestamp__pb2.DESCRIPTOR,]) +_sym_db.RegisterFileDescriptor(DESCRIPTOR) + + + +_DATABASE_STATE = _descriptor.EnumDescriptor( + name='State', + full_name='google.spanner.admin.database.v1.Database.State', + filename=None, + file=DESCRIPTOR, + values=[ + _descriptor.EnumValueDescriptor( + name='STATE_UNSPECIFIED', index=0, number=0, + options=None, + type=None), + _descriptor.EnumValueDescriptor( + name='CREATING', index=1, number=1, + options=None, + type=None), + _descriptor.EnumValueDescriptor( + name='READY', index=2, number=2, + options=None, + type=None), + ], + containing_type=None, + options=None, + serialized_start=415, + serialized_end=470, +) +_sym_db.RegisterEnumDescriptor(_DATABASE_STATE) + + +_DATABASE = _descriptor.Descriptor( + name='Database', + full_name='google.spanner.admin.database.v1.Database', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='name', full_name='google.spanner.admin.database.v1.Database.name', index=0, + number=1, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='state', full_name='google.spanner.admin.database.v1.Database.state', index=1, + number=2, type=14, cpp_type=8, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + _DATABASE_STATE, + ], + options=None, + is_extendable=False, + syntax='proto3', + extension_ranges=[], + oneofs=[ + ], + serialized_start=324, + serialized_end=470, +) + + +_LISTDATABASESREQUEST = _descriptor.Descriptor( + name='ListDatabasesRequest', + full_name='google.spanner.admin.database.v1.ListDatabasesRequest', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='parent', full_name='google.spanner.admin.database.v1.ListDatabasesRequest.parent', index=0, + number=1, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='page_size', full_name='google.spanner.admin.database.v1.ListDatabasesRequest.page_size', index=1, + number=3, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='page_token', full_name='google.spanner.admin.database.v1.ListDatabasesRequest.page_token', index=2, + number=4, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto3', + extension_ranges=[], + oneofs=[ + ], + serialized_start=472, + serialized_end=549, +) + + +_LISTDATABASESRESPONSE = _descriptor.Descriptor( + name='ListDatabasesResponse', + full_name='google.spanner.admin.database.v1.ListDatabasesResponse', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='databases', full_name='google.spanner.admin.database.v1.ListDatabasesResponse.databases', index=0, + number=1, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='next_page_token', full_name='google.spanner.admin.database.v1.ListDatabasesResponse.next_page_token', index=1, + number=2, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto3', + extension_ranges=[], + oneofs=[ + ], + serialized_start=551, + serialized_end=662, +) + + +_CREATEDATABASEREQUEST = _descriptor.Descriptor( + name='CreateDatabaseRequest', + full_name='google.spanner.admin.database.v1.CreateDatabaseRequest', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='parent', full_name='google.spanner.admin.database.v1.CreateDatabaseRequest.parent', index=0, + number=1, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='create_statement', full_name='google.spanner.admin.database.v1.CreateDatabaseRequest.create_statement', index=1, + number=2, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='extra_statements', full_name='google.spanner.admin.database.v1.CreateDatabaseRequest.extra_statements', index=2, + number=3, type=9, cpp_type=9, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto3', + extension_ranges=[], + oneofs=[ + ], + serialized_start=664, + serialized_end=755, +) + + +_CREATEDATABASEMETADATA = _descriptor.Descriptor( + name='CreateDatabaseMetadata', + full_name='google.spanner.admin.database.v1.CreateDatabaseMetadata', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='database', full_name='google.spanner.admin.database.v1.CreateDatabaseMetadata.database', index=0, + number=1, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto3', + extension_ranges=[], + oneofs=[ + ], + serialized_start=757, + serialized_end=799, +) + + +_GETDATABASEREQUEST = _descriptor.Descriptor( + name='GetDatabaseRequest', + full_name='google.spanner.admin.database.v1.GetDatabaseRequest', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='name', full_name='google.spanner.admin.database.v1.GetDatabaseRequest.name', index=0, + number=1, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto3', + extension_ranges=[], + oneofs=[ + ], + serialized_start=801, + serialized_end=835, +) + + +_UPDATEDATABASEDDLREQUEST = _descriptor.Descriptor( + name='UpdateDatabaseDdlRequest', + full_name='google.spanner.admin.database.v1.UpdateDatabaseDdlRequest', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='database', full_name='google.spanner.admin.database.v1.UpdateDatabaseDdlRequest.database', index=0, + number=1, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='statements', full_name='google.spanner.admin.database.v1.UpdateDatabaseDdlRequest.statements', index=1, + number=2, type=9, cpp_type=9, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='operation_id', full_name='google.spanner.admin.database.v1.UpdateDatabaseDdlRequest.operation_id', index=2, + number=3, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto3', + extension_ranges=[], + oneofs=[ + ], + serialized_start=837, + serialized_end=923, +) + + +_UPDATEDATABASEDDLMETADATA = _descriptor.Descriptor( + name='UpdateDatabaseDdlMetadata', + full_name='google.spanner.admin.database.v1.UpdateDatabaseDdlMetadata', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='database', full_name='google.spanner.admin.database.v1.UpdateDatabaseDdlMetadata.database', index=0, + number=1, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='statements', full_name='google.spanner.admin.database.v1.UpdateDatabaseDdlMetadata.statements', index=1, + number=2, type=9, cpp_type=9, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='commit_timestamps', full_name='google.spanner.admin.database.v1.UpdateDatabaseDdlMetadata.commit_timestamps', index=2, + number=3, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto3', + extension_ranges=[], + oneofs=[ + ], + serialized_start=925, + serialized_end=1045, +) + + +_DROPDATABASEREQUEST = _descriptor.Descriptor( + name='DropDatabaseRequest', + full_name='google.spanner.admin.database.v1.DropDatabaseRequest', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='database', full_name='google.spanner.admin.database.v1.DropDatabaseRequest.database', index=0, + number=1, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto3', + extension_ranges=[], + oneofs=[ + ], + serialized_start=1047, + serialized_end=1086, +) + + +_GETDATABASEDDLREQUEST = _descriptor.Descriptor( + name='GetDatabaseDdlRequest', + full_name='google.spanner.admin.database.v1.GetDatabaseDdlRequest', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='database', full_name='google.spanner.admin.database.v1.GetDatabaseDdlRequest.database', index=0, + number=1, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto3', + extension_ranges=[], + oneofs=[ + ], + serialized_start=1088, + serialized_end=1129, +) + + +_GETDATABASEDDLRESPONSE = _descriptor.Descriptor( + name='GetDatabaseDdlResponse', + full_name='google.spanner.admin.database.v1.GetDatabaseDdlResponse', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='statements', full_name='google.spanner.admin.database.v1.GetDatabaseDdlResponse.statements', index=0, + number=1, type=9, cpp_type=9, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto3', + extension_ranges=[], + oneofs=[ + ], + serialized_start=1131, + serialized_end=1175, +) + +_DATABASE.fields_by_name['state'].enum_type = _DATABASE_STATE +_DATABASE_STATE.containing_type = _DATABASE +_LISTDATABASESRESPONSE.fields_by_name['databases'].message_type = _DATABASE +_UPDATEDATABASEDDLMETADATA.fields_by_name['commit_timestamps'].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP +DESCRIPTOR.message_types_by_name['Database'] = _DATABASE +DESCRIPTOR.message_types_by_name['ListDatabasesRequest'] = _LISTDATABASESREQUEST +DESCRIPTOR.message_types_by_name['ListDatabasesResponse'] = _LISTDATABASESRESPONSE +DESCRIPTOR.message_types_by_name['CreateDatabaseRequest'] = _CREATEDATABASEREQUEST +DESCRIPTOR.message_types_by_name['CreateDatabaseMetadata'] = _CREATEDATABASEMETADATA +DESCRIPTOR.message_types_by_name['GetDatabaseRequest'] = _GETDATABASEREQUEST +DESCRIPTOR.message_types_by_name['UpdateDatabaseDdlRequest'] = _UPDATEDATABASEDDLREQUEST +DESCRIPTOR.message_types_by_name['UpdateDatabaseDdlMetadata'] = _UPDATEDATABASEDDLMETADATA +DESCRIPTOR.message_types_by_name['DropDatabaseRequest'] = _DROPDATABASEREQUEST +DESCRIPTOR.message_types_by_name['GetDatabaseDdlRequest'] = _GETDATABASEDDLREQUEST +DESCRIPTOR.message_types_by_name['GetDatabaseDdlResponse'] = _GETDATABASEDDLRESPONSE + +Database = _reflection.GeneratedProtocolMessageType('Database', (_message.Message,), dict( + DESCRIPTOR = _DATABASE, + __module__ = 'google.cloud.spanner.admin.database_v1.proto.spanner_database_admin_pb2' + , + __doc__ = """A Cloud Spanner database. + + + Attributes: + name: + Required. The name of the database. Values are of the form ``p + rojects//instances//databases/``, + where ```` is as specified in the ``CREATE + DATABASE`` statement. This name can be passed to other API + methods to identify the database. + state: + Output only. The current database state. + """, + # @@protoc_insertion_point(class_scope:google.spanner.admin.database.v1.Database) + )) +_sym_db.RegisterMessage(Database) + +ListDatabasesRequest = _reflection.GeneratedProtocolMessageType('ListDatabasesRequest', (_message.Message,), dict( + DESCRIPTOR = _LISTDATABASESREQUEST, + __module__ = 'google.cloud.spanner.admin.database_v1.proto.spanner_database_admin_pb2' + , + __doc__ = """The request for + [ListDatabases][google.spanner.admin.database.v1.DatabaseAdmin.ListDatabases]. + + + Attributes: + parent: + Required. The instance whose databases should be listed. + Values are of the form + ``projects//instances/``. + page_size: + Number of databases to be returned in the response. If 0 or + less, defaults to the server's maximum allowed page size. + page_token: + If non-empty, ``page_token`` should contain a [next\_page\_tok + en][google.spanner.admin.database.v1.ListDatabasesResponse.nex + t\_page\_token] from a previous [ListDatabasesResponse][google + .spanner.admin.database.v1.ListDatabasesResponse]. + """, + # @@protoc_insertion_point(class_scope:google.spanner.admin.database.v1.ListDatabasesRequest) + )) +_sym_db.RegisterMessage(ListDatabasesRequest) + +ListDatabasesResponse = _reflection.GeneratedProtocolMessageType('ListDatabasesResponse', (_message.Message,), dict( + DESCRIPTOR = _LISTDATABASESRESPONSE, + __module__ = 'google.cloud.spanner.admin.database_v1.proto.spanner_database_admin_pb2' + , + __doc__ = """The response for + [ListDatabases][google.spanner.admin.database.v1.DatabaseAdmin.ListDatabases]. + + + Attributes: + databases: + Databases that matched the request. + next_page_token: + ``next_page_token`` can be sent in a subsequent [ListDatabases + ][google.spanner.admin.database.v1.DatabaseAdmin.ListDatabases + ] call to fetch more of the matching databases. + """, + # @@protoc_insertion_point(class_scope:google.spanner.admin.database.v1.ListDatabasesResponse) + )) +_sym_db.RegisterMessage(ListDatabasesResponse) + +CreateDatabaseRequest = _reflection.GeneratedProtocolMessageType('CreateDatabaseRequest', (_message.Message,), dict( + DESCRIPTOR = _CREATEDATABASEREQUEST, + __module__ = 'google.cloud.spanner.admin.database_v1.proto.spanner_database_admin_pb2' + , + __doc__ = """The request for + [CreateDatabase][google.spanner.admin.database.v1.DatabaseAdmin.CreateDatabase]. + + + Attributes: + parent: + Required. The name of the instance that will serve the new + database. Values are of the form + ``projects//instances/``. + create_statement: + Required. A ``CREATE DATABASE`` statement, which specifies the + ID of the new database. The database ID must conform to the + regular expression ``[a-z][a-z0-9_\-]*[a-z0-9]`` and be + between 2 and 30 characters in length. + extra_statements: + An optional list of DDL statements to run inside the newly + created database. Statements can create tables, indexes, etc. + These statements execute atomically with the creation of the + database: if there is an error in any statement, the database + is not created. + """, + # @@protoc_insertion_point(class_scope:google.spanner.admin.database.v1.CreateDatabaseRequest) + )) +_sym_db.RegisterMessage(CreateDatabaseRequest) + +CreateDatabaseMetadata = _reflection.GeneratedProtocolMessageType('CreateDatabaseMetadata', (_message.Message,), dict( + DESCRIPTOR = _CREATEDATABASEMETADATA, + __module__ = 'google.cloud.spanner.admin.database_v1.proto.spanner_database_admin_pb2' + , + __doc__ = """Metadata type for the operation returned by + [CreateDatabase][google.spanner.admin.database.v1.DatabaseAdmin.CreateDatabase]. + + + Attributes: + database: + The database being created. + """, + # @@protoc_insertion_point(class_scope:google.spanner.admin.database.v1.CreateDatabaseMetadata) + )) +_sym_db.RegisterMessage(CreateDatabaseMetadata) + +GetDatabaseRequest = _reflection.GeneratedProtocolMessageType('GetDatabaseRequest', (_message.Message,), dict( + DESCRIPTOR = _GETDATABASEREQUEST, + __module__ = 'google.cloud.spanner.admin.database_v1.proto.spanner_database_admin_pb2' + , + __doc__ = """The request for + [GetDatabase][google.spanner.admin.database.v1.DatabaseAdmin.GetDatabase]. + + + Attributes: + name: + Required. The name of the requested database. Values are of + the form ``projects//instances//databases/< + database>``. + """, + # @@protoc_insertion_point(class_scope:google.spanner.admin.database.v1.GetDatabaseRequest) + )) +_sym_db.RegisterMessage(GetDatabaseRequest) + +UpdateDatabaseDdlRequest = _reflection.GeneratedProtocolMessageType('UpdateDatabaseDdlRequest', (_message.Message,), dict( + DESCRIPTOR = _UPDATEDATABASEDDLREQUEST, + __module__ = 'google.cloud.spanner.admin.database_v1.proto.spanner_database_admin_pb2' + , + __doc__ = """Enqueues the given DDL statements to be applied, in order but not + necessarily all at once, to the database schema at some point (or + points) in the future. The server checks that the statements are + executable (syntactically valid, name tables that exist, etc.) before + enqueueing them, but they may still fail upon later execution (e.g., if + a statement from another batch of statements is applied first and it + conflicts in some way, or if there is some data-related problem like a + ``NULL`` value in a column to which ``NOT NULL`` would be added). If a + statement fails, all subsequent statements in the batch are + automatically cancelled. + + Each batch of statements is assigned a name which can be used with the + [Operations][google.longrunning.Operations] API to monitor progress. See + the + [operation\_id][google.spanner.admin.database.v1.UpdateDatabaseDdlRequest.operation\_id] + field for more details. + + + Attributes: + database: + Required. The database to update. + statements: + DDL statements to be applied to the database. + operation_id: + If empty, the new update request is assigned an automatically- + generated operation ID. Otherwise, ``operation_id`` is used to + construct the name of the resulting + [Operation][google.longrunning.Operation]. Specifying an + explicit operation ID simplifies determining whether the + statements were executed in the event that the [UpdateDatabase + Ddl][google.spanner.admin.database.v1.DatabaseAdmin.UpdateData + baseDdl] call is replayed, or the return value is otherwise + lost: the [database][google.spanner.admin.database.v1.UpdateDa + tabaseDdlRequest.database] and ``operation_id`` fields can be + combined to form the [name][google.longrunning.Operation.name] + of the resulting + [longrunning.Operation][google.longrunning.Operation]: + ``/operations/``. ``operation_id`` + should be unique within the database, and must be a valid + identifier: ``[a-z][a-z0-9_]*``. Note that automatically- + generated operation IDs always begin with an underscore. If + the named operation already exists, [UpdateDatabaseDdl][google + .spanner.admin.database.v1.DatabaseAdmin.UpdateDatabaseDdl] + returns ``ALREADY_EXISTS``. + """, + # @@protoc_insertion_point(class_scope:google.spanner.admin.database.v1.UpdateDatabaseDdlRequest) + )) +_sym_db.RegisterMessage(UpdateDatabaseDdlRequest) + +UpdateDatabaseDdlMetadata = _reflection.GeneratedProtocolMessageType('UpdateDatabaseDdlMetadata', (_message.Message,), dict( + DESCRIPTOR = _UPDATEDATABASEDDLMETADATA, + __module__ = 'google.cloud.spanner.admin.database_v1.proto.spanner_database_admin_pb2' + , + __doc__ = """Metadata type for the operation returned by + [UpdateDatabaseDdl][google.spanner.admin.database.v1.DatabaseAdmin.UpdateDatabaseDdl]. + + + Attributes: + database: + The database being modified. + statements: + For an update this list contains all the statements. For an + individual statement, this list contains only that statement. + commit_timestamps: + Reports the commit timestamps of all statements that have + succeeded so far, where ``commit_timestamps[i]`` is the commit + timestamp for the statement ``statements[i]``. + """, + # @@protoc_insertion_point(class_scope:google.spanner.admin.database.v1.UpdateDatabaseDdlMetadata) + )) +_sym_db.RegisterMessage(UpdateDatabaseDdlMetadata) + +DropDatabaseRequest = _reflection.GeneratedProtocolMessageType('DropDatabaseRequest', (_message.Message,), dict( + DESCRIPTOR = _DROPDATABASEREQUEST, + __module__ = 'google.cloud.spanner.admin.database_v1.proto.spanner_database_admin_pb2' + , + __doc__ = """The request for + [DropDatabase][google.spanner.admin.database.v1.DatabaseAdmin.DropDatabase]. + + + Attributes: + database: + Required. The database to be dropped. + """, + # @@protoc_insertion_point(class_scope:google.spanner.admin.database.v1.DropDatabaseRequest) + )) +_sym_db.RegisterMessage(DropDatabaseRequest) + +GetDatabaseDdlRequest = _reflection.GeneratedProtocolMessageType('GetDatabaseDdlRequest', (_message.Message,), dict( + DESCRIPTOR = _GETDATABASEDDLREQUEST, + __module__ = 'google.cloud.spanner.admin.database_v1.proto.spanner_database_admin_pb2' + , + __doc__ = """The request for + [GetDatabaseDdl][google.spanner.admin.database.v1.DatabaseAdmin.GetDatabaseDdl]. + + + Attributes: + database: + Required. The database whose schema we wish to get. + """, + # @@protoc_insertion_point(class_scope:google.spanner.admin.database.v1.GetDatabaseDdlRequest) + )) +_sym_db.RegisterMessage(GetDatabaseDdlRequest) + +GetDatabaseDdlResponse = _reflection.GeneratedProtocolMessageType('GetDatabaseDdlResponse', (_message.Message,), dict( + DESCRIPTOR = _GETDATABASEDDLRESPONSE, + __module__ = 'google.cloud.spanner.admin.database_v1.proto.spanner_database_admin_pb2' + , + __doc__ = """The response for + [GetDatabaseDdl][google.spanner.admin.database.v1.DatabaseAdmin.GetDatabaseDdl]. + + + Attributes: + statements: + A list of formatted DDL statements defining the schema of the + database specified in the request. + """, + # @@protoc_insertion_point(class_scope:google.spanner.admin.database.v1.GetDatabaseDdlResponse) + )) +_sym_db.RegisterMessage(GetDatabaseDdlResponse) + + +DESCRIPTOR.has_options = True +DESCRIPTOR._options = _descriptor._ParseOptions(descriptor_pb2.FileOptions(), _b('\n$com.google.spanner.admin.database.v1B\031SpannerDatabaseAdminProtoP\001ZHgoogle.golang.org/genproto/googleapis/spanner/admin/database/v1;database\252\002&Google.Cloud.Spanner.Admin.Database.V1')) +try: + # THESE ELEMENTS WILL BE DEPRECATED. + # Please use the generated *_pb2_grpc.py files instead. + import grpc + from grpc.beta import implementations as beta_implementations + from grpc.beta import interfaces as beta_interfaces + from grpc.framework.common import cardinality + from grpc.framework.interfaces.face import utilities as face_utilities + + + class DatabaseAdminStub(object): + """Cloud Spanner Database Admin API + + The Cloud Spanner Database Admin API can be used to create, drop, and + list databases. It also enables updating the schema of pre-existing + databases. + """ + + def __init__(self, channel): + """Constructor. + + Args: + channel: A grpc.Channel. + """ + self.ListDatabases = channel.unary_unary( + '/google.spanner.admin.database.v1.DatabaseAdmin/ListDatabases', + request_serializer=ListDatabasesRequest.SerializeToString, + response_deserializer=ListDatabasesResponse.FromString, + ) + self.CreateDatabase = channel.unary_unary( + '/google.spanner.admin.database.v1.DatabaseAdmin/CreateDatabase', + request_serializer=CreateDatabaseRequest.SerializeToString, + response_deserializer=google_dot_longrunning_dot_operations__pb2.Operation.FromString, + ) + self.GetDatabase = channel.unary_unary( + '/google.spanner.admin.database.v1.DatabaseAdmin/GetDatabase', + request_serializer=GetDatabaseRequest.SerializeToString, + response_deserializer=Database.FromString, + ) + self.UpdateDatabaseDdl = channel.unary_unary( + '/google.spanner.admin.database.v1.DatabaseAdmin/UpdateDatabaseDdl', + request_serializer=UpdateDatabaseDdlRequest.SerializeToString, + response_deserializer=google_dot_longrunning_dot_operations__pb2.Operation.FromString, + ) + self.DropDatabase = channel.unary_unary( + '/google.spanner.admin.database.v1.DatabaseAdmin/DropDatabase', + request_serializer=DropDatabaseRequest.SerializeToString, + response_deserializer=google_dot_protobuf_dot_empty__pb2.Empty.FromString, + ) + self.GetDatabaseDdl = channel.unary_unary( + '/google.spanner.admin.database.v1.DatabaseAdmin/GetDatabaseDdl', + request_serializer=GetDatabaseDdlRequest.SerializeToString, + response_deserializer=GetDatabaseDdlResponse.FromString, + ) + self.SetIamPolicy = channel.unary_unary( + '/google.spanner.admin.database.v1.DatabaseAdmin/SetIamPolicy', + request_serializer=google_dot_iam_dot_v1_dot_iam__policy__pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=google_dot_iam_dot_v1_dot_policy__pb2.Policy.FromString, + ) + self.GetIamPolicy = channel.unary_unary( + '/google.spanner.admin.database.v1.DatabaseAdmin/GetIamPolicy', + request_serializer=google_dot_iam_dot_v1_dot_iam__policy__pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=google_dot_iam_dot_v1_dot_policy__pb2.Policy.FromString, + ) + self.TestIamPermissions = channel.unary_unary( + '/google.spanner.admin.database.v1.DatabaseAdmin/TestIamPermissions', + request_serializer=google_dot_iam_dot_v1_dot_iam__policy__pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=google_dot_iam_dot_v1_dot_iam__policy__pb2.TestIamPermissionsResponse.FromString, + ) + + + class DatabaseAdminServicer(object): + """Cloud Spanner Database Admin API + + The Cloud Spanner Database Admin API can be used to create, drop, and + list databases. It also enables updating the schema of pre-existing + databases. + """ + + def ListDatabases(self, request, context): + """Lists Cloud Spanner databases. + """ + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + def CreateDatabase(self, request, context): + """Creates a new Cloud Spanner database and starts to prepare it for serving. + The returned [long-running operation][google.longrunning.Operation] will + have a name of the format `/operations/` and + can be used to track preparation of the database. The + [metadata][google.longrunning.Operation.metadata] field type is + [CreateDatabaseMetadata][google.spanner.admin.database.v1.CreateDatabaseMetadata]. The + [response][google.longrunning.Operation.response] field type is + [Database][google.spanner.admin.database.v1.Database], if successful. + """ + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + def GetDatabase(self, request, context): + """Gets the state of a Cloud Spanner database. + """ + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + def UpdateDatabaseDdl(self, request, context): + """Updates the schema of a Cloud Spanner database by + creating/altering/dropping tables, columns, indexes, etc. The returned + [long-running operation][google.longrunning.Operation] will have a name of + the format `/operations/` and can be used to + track execution of the schema change(s). The + [metadata][google.longrunning.Operation.metadata] field type is + [UpdateDatabaseDdlMetadata][google.spanner.admin.database.v1.UpdateDatabaseDdlMetadata]. The operation has no response. + """ + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + def DropDatabase(self, request, context): + """Drops (aka deletes) a Cloud Spanner database. + """ + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + def GetDatabaseDdl(self, request, context): + """Returns the schema of a Cloud Spanner database as a list of formatted + DDL statements. This method does not show pending schema updates, those may + be queried using the [Operations][google.longrunning.Operations] API. + """ + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + def SetIamPolicy(self, request, context): + """Sets the access control policy on a database resource. Replaces any + existing policy. + + Authorization requires `spanner.databases.setIamPolicy` permission on + [resource][google.iam.v1.SetIamPolicyRequest.resource]. + """ + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + def GetIamPolicy(self, request, context): + """Gets the access control policy for a database resource. Returns an empty + policy if a database exists but does not have a policy set. + + Authorization requires `spanner.databases.getIamPolicy` permission on + [resource][google.iam.v1.GetIamPolicyRequest.resource]. + """ + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + def TestIamPermissions(self, request, context): + """Returns permissions that the caller has on the specified database resource. + + Attempting this RPC on a non-existent Cloud Spanner database will result in + a NOT_FOUND error if the user has `spanner.databases.list` permission on + the containing Cloud Spanner instance. Otherwise returns an empty set of + permissions. + """ + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + + def add_DatabaseAdminServicer_to_server(servicer, server): + rpc_method_handlers = { + 'ListDatabases': grpc.unary_unary_rpc_method_handler( + servicer.ListDatabases, + request_deserializer=ListDatabasesRequest.FromString, + response_serializer=ListDatabasesResponse.SerializeToString, + ), + 'CreateDatabase': grpc.unary_unary_rpc_method_handler( + servicer.CreateDatabase, + request_deserializer=CreateDatabaseRequest.FromString, + response_serializer=google_dot_longrunning_dot_operations__pb2.Operation.SerializeToString, + ), + 'GetDatabase': grpc.unary_unary_rpc_method_handler( + servicer.GetDatabase, + request_deserializer=GetDatabaseRequest.FromString, + response_serializer=Database.SerializeToString, + ), + 'UpdateDatabaseDdl': grpc.unary_unary_rpc_method_handler( + servicer.UpdateDatabaseDdl, + request_deserializer=UpdateDatabaseDdlRequest.FromString, + response_serializer=google_dot_longrunning_dot_operations__pb2.Operation.SerializeToString, + ), + 'DropDatabase': grpc.unary_unary_rpc_method_handler( + servicer.DropDatabase, + request_deserializer=DropDatabaseRequest.FromString, + response_serializer=google_dot_protobuf_dot_empty__pb2.Empty.SerializeToString, + ), + 'GetDatabaseDdl': grpc.unary_unary_rpc_method_handler( + servicer.GetDatabaseDdl, + request_deserializer=GetDatabaseDdlRequest.FromString, + response_serializer=GetDatabaseDdlResponse.SerializeToString, + ), + 'SetIamPolicy': grpc.unary_unary_rpc_method_handler( + servicer.SetIamPolicy, + request_deserializer=google_dot_iam_dot_v1_dot_iam__policy__pb2.SetIamPolicyRequest.FromString, + response_serializer=google_dot_iam_dot_v1_dot_policy__pb2.Policy.SerializeToString, + ), + 'GetIamPolicy': grpc.unary_unary_rpc_method_handler( + servicer.GetIamPolicy, + request_deserializer=google_dot_iam_dot_v1_dot_iam__policy__pb2.GetIamPolicyRequest.FromString, + response_serializer=google_dot_iam_dot_v1_dot_policy__pb2.Policy.SerializeToString, + ), + 'TestIamPermissions': grpc.unary_unary_rpc_method_handler( + servicer.TestIamPermissions, + request_deserializer=google_dot_iam_dot_v1_dot_iam__policy__pb2.TestIamPermissionsRequest.FromString, + response_serializer=google_dot_iam_dot_v1_dot_iam__policy__pb2.TestIamPermissionsResponse.SerializeToString, + ), + } + generic_handler = grpc.method_handlers_generic_handler( + 'google.spanner.admin.database.v1.DatabaseAdmin', rpc_method_handlers) + server.add_generic_rpc_handlers((generic_handler,)) + + + class BetaDatabaseAdminServicer(object): + """The Beta API is deprecated for 0.15.0 and later. + + It is recommended to use the GA API (classes and functions in this + file not marked beta) for all further purposes. This class was generated + only to ease transition from grpcio<0.15.0 to grpcio>=0.15.0.""" + """Cloud Spanner Database Admin API + + The Cloud Spanner Database Admin API can be used to create, drop, and + list databases. It also enables updating the schema of pre-existing + databases. + """ + def ListDatabases(self, request, context): + """Lists Cloud Spanner databases. + """ + context.code(beta_interfaces.StatusCode.UNIMPLEMENTED) + def CreateDatabase(self, request, context): + """Creates a new Cloud Spanner database and starts to prepare it for serving. + The returned [long-running operation][google.longrunning.Operation] will + have a name of the format `/operations/` and + can be used to track preparation of the database. The + [metadata][google.longrunning.Operation.metadata] field type is + [CreateDatabaseMetadata][google.spanner.admin.database.v1.CreateDatabaseMetadata]. The + [response][google.longrunning.Operation.response] field type is + [Database][google.spanner.admin.database.v1.Database], if successful. + """ + context.code(beta_interfaces.StatusCode.UNIMPLEMENTED) + def GetDatabase(self, request, context): + """Gets the state of a Cloud Spanner database. + """ + context.code(beta_interfaces.StatusCode.UNIMPLEMENTED) + def UpdateDatabaseDdl(self, request, context): + """Updates the schema of a Cloud Spanner database by + creating/altering/dropping tables, columns, indexes, etc. The returned + [long-running operation][google.longrunning.Operation] will have a name of + the format `/operations/` and can be used to + track execution of the schema change(s). The + [metadata][google.longrunning.Operation.metadata] field type is + [UpdateDatabaseDdlMetadata][google.spanner.admin.database.v1.UpdateDatabaseDdlMetadata]. The operation has no response. + """ + context.code(beta_interfaces.StatusCode.UNIMPLEMENTED) + def DropDatabase(self, request, context): + """Drops (aka deletes) a Cloud Spanner database. + """ + context.code(beta_interfaces.StatusCode.UNIMPLEMENTED) + def GetDatabaseDdl(self, request, context): + """Returns the schema of a Cloud Spanner database as a list of formatted + DDL statements. This method does not show pending schema updates, those may + be queried using the [Operations][google.longrunning.Operations] API. + """ + context.code(beta_interfaces.StatusCode.UNIMPLEMENTED) + def SetIamPolicy(self, request, context): + """Sets the access control policy on a database resource. Replaces any + existing policy. + + Authorization requires `spanner.databases.setIamPolicy` permission on + [resource][google.iam.v1.SetIamPolicyRequest.resource]. + """ + context.code(beta_interfaces.StatusCode.UNIMPLEMENTED) + def GetIamPolicy(self, request, context): + """Gets the access control policy for a database resource. Returns an empty + policy if a database exists but does not have a policy set. + + Authorization requires `spanner.databases.getIamPolicy` permission on + [resource][google.iam.v1.GetIamPolicyRequest.resource]. + """ + context.code(beta_interfaces.StatusCode.UNIMPLEMENTED) + def TestIamPermissions(self, request, context): + """Returns permissions that the caller has on the specified database resource. + + Attempting this RPC on a non-existent Cloud Spanner database will result in + a NOT_FOUND error if the user has `spanner.databases.list` permission on + the containing Cloud Spanner instance. Otherwise returns an empty set of + permissions. + """ + context.code(beta_interfaces.StatusCode.UNIMPLEMENTED) + + + class BetaDatabaseAdminStub(object): + """The Beta API is deprecated for 0.15.0 and later. + + It is recommended to use the GA API (classes and functions in this + file not marked beta) for all further purposes. This class was generated + only to ease transition from grpcio<0.15.0 to grpcio>=0.15.0.""" + """Cloud Spanner Database Admin API + + The Cloud Spanner Database Admin API can be used to create, drop, and + list databases. It also enables updating the schema of pre-existing + databases. + """ + def ListDatabases(self, request, timeout, metadata=None, with_call=False, protocol_options=None): + """Lists Cloud Spanner databases. + """ + raise NotImplementedError() + ListDatabases.future = None + def CreateDatabase(self, request, timeout, metadata=None, with_call=False, protocol_options=None): + """Creates a new Cloud Spanner database and starts to prepare it for serving. + The returned [long-running operation][google.longrunning.Operation] will + have a name of the format `/operations/` and + can be used to track preparation of the database. The + [metadata][google.longrunning.Operation.metadata] field type is + [CreateDatabaseMetadata][google.spanner.admin.database.v1.CreateDatabaseMetadata]. The + [response][google.longrunning.Operation.response] field type is + [Database][google.spanner.admin.database.v1.Database], if successful. + """ + raise NotImplementedError() + CreateDatabase.future = None + def GetDatabase(self, request, timeout, metadata=None, with_call=False, protocol_options=None): + """Gets the state of a Cloud Spanner database. + """ + raise NotImplementedError() + GetDatabase.future = None + def UpdateDatabaseDdl(self, request, timeout, metadata=None, with_call=False, protocol_options=None): + """Updates the schema of a Cloud Spanner database by + creating/altering/dropping tables, columns, indexes, etc. The returned + [long-running operation][google.longrunning.Operation] will have a name of + the format `/operations/` and can be used to + track execution of the schema change(s). The + [metadata][google.longrunning.Operation.metadata] field type is + [UpdateDatabaseDdlMetadata][google.spanner.admin.database.v1.UpdateDatabaseDdlMetadata]. The operation has no response. + """ + raise NotImplementedError() + UpdateDatabaseDdl.future = None + def DropDatabase(self, request, timeout, metadata=None, with_call=False, protocol_options=None): + """Drops (aka deletes) a Cloud Spanner database. + """ + raise NotImplementedError() + DropDatabase.future = None + def GetDatabaseDdl(self, request, timeout, metadata=None, with_call=False, protocol_options=None): + """Returns the schema of a Cloud Spanner database as a list of formatted + DDL statements. This method does not show pending schema updates, those may + be queried using the [Operations][google.longrunning.Operations] API. + """ + raise NotImplementedError() + GetDatabaseDdl.future = None + def SetIamPolicy(self, request, timeout, metadata=None, with_call=False, protocol_options=None): + """Sets the access control policy on a database resource. Replaces any + existing policy. + + Authorization requires `spanner.databases.setIamPolicy` permission on + [resource][google.iam.v1.SetIamPolicyRequest.resource]. + """ + raise NotImplementedError() + SetIamPolicy.future = None + def GetIamPolicy(self, request, timeout, metadata=None, with_call=False, protocol_options=None): + """Gets the access control policy for a database resource. Returns an empty + policy if a database exists but does not have a policy set. + + Authorization requires `spanner.databases.getIamPolicy` permission on + [resource][google.iam.v1.GetIamPolicyRequest.resource]. + """ + raise NotImplementedError() + GetIamPolicy.future = None + def TestIamPermissions(self, request, timeout, metadata=None, with_call=False, protocol_options=None): + """Returns permissions that the caller has on the specified database resource. + + Attempting this RPC on a non-existent Cloud Spanner database will result in + a NOT_FOUND error if the user has `spanner.databases.list` permission on + the containing Cloud Spanner instance. Otherwise returns an empty set of + permissions. + """ + raise NotImplementedError() + TestIamPermissions.future = None + + + def beta_create_DatabaseAdmin_server(servicer, pool=None, pool_size=None, default_timeout=None, maximum_timeout=None): + """The Beta API is deprecated for 0.15.0 and later. + + It is recommended to use the GA API (classes and functions in this + file not marked beta) for all further purposes. This function was + generated only to ease transition from grpcio<0.15.0 to grpcio>=0.15.0""" + request_deserializers = { + ('google.spanner.admin.database.v1.DatabaseAdmin', 'CreateDatabase'): CreateDatabaseRequest.FromString, + ('google.spanner.admin.database.v1.DatabaseAdmin', 'DropDatabase'): DropDatabaseRequest.FromString, + ('google.spanner.admin.database.v1.DatabaseAdmin', 'GetDatabase'): GetDatabaseRequest.FromString, + ('google.spanner.admin.database.v1.DatabaseAdmin', 'GetDatabaseDdl'): GetDatabaseDdlRequest.FromString, + ('google.spanner.admin.database.v1.DatabaseAdmin', 'GetIamPolicy'): google_dot_iam_dot_v1_dot_iam__policy__pb2.GetIamPolicyRequest.FromString, + ('google.spanner.admin.database.v1.DatabaseAdmin', 'ListDatabases'): ListDatabasesRequest.FromString, + ('google.spanner.admin.database.v1.DatabaseAdmin', 'SetIamPolicy'): google_dot_iam_dot_v1_dot_iam__policy__pb2.SetIamPolicyRequest.FromString, + ('google.spanner.admin.database.v1.DatabaseAdmin', 'TestIamPermissions'): google_dot_iam_dot_v1_dot_iam__policy__pb2.TestIamPermissionsRequest.FromString, + ('google.spanner.admin.database.v1.DatabaseAdmin', 'UpdateDatabaseDdl'): UpdateDatabaseDdlRequest.FromString, + } + response_serializers = { + ('google.spanner.admin.database.v1.DatabaseAdmin', 'CreateDatabase'): google_dot_longrunning_dot_operations__pb2.Operation.SerializeToString, + ('google.spanner.admin.database.v1.DatabaseAdmin', 'DropDatabase'): google_dot_protobuf_dot_empty__pb2.Empty.SerializeToString, + ('google.spanner.admin.database.v1.DatabaseAdmin', 'GetDatabase'): Database.SerializeToString, + ('google.spanner.admin.database.v1.DatabaseAdmin', 'GetDatabaseDdl'): GetDatabaseDdlResponse.SerializeToString, + ('google.spanner.admin.database.v1.DatabaseAdmin', 'GetIamPolicy'): google_dot_iam_dot_v1_dot_policy__pb2.Policy.SerializeToString, + ('google.spanner.admin.database.v1.DatabaseAdmin', 'ListDatabases'): ListDatabasesResponse.SerializeToString, + ('google.spanner.admin.database.v1.DatabaseAdmin', 'SetIamPolicy'): google_dot_iam_dot_v1_dot_policy__pb2.Policy.SerializeToString, + ('google.spanner.admin.database.v1.DatabaseAdmin', 'TestIamPermissions'): google_dot_iam_dot_v1_dot_iam__policy__pb2.TestIamPermissionsResponse.SerializeToString, + ('google.spanner.admin.database.v1.DatabaseAdmin', 'UpdateDatabaseDdl'): google_dot_longrunning_dot_operations__pb2.Operation.SerializeToString, + } + method_implementations = { + ('google.spanner.admin.database.v1.DatabaseAdmin', 'CreateDatabase'): face_utilities.unary_unary_inline(servicer.CreateDatabase), + ('google.spanner.admin.database.v1.DatabaseAdmin', 'DropDatabase'): face_utilities.unary_unary_inline(servicer.DropDatabase), + ('google.spanner.admin.database.v1.DatabaseAdmin', 'GetDatabase'): face_utilities.unary_unary_inline(servicer.GetDatabase), + ('google.spanner.admin.database.v1.DatabaseAdmin', 'GetDatabaseDdl'): face_utilities.unary_unary_inline(servicer.GetDatabaseDdl), + ('google.spanner.admin.database.v1.DatabaseAdmin', 'GetIamPolicy'): face_utilities.unary_unary_inline(servicer.GetIamPolicy), + ('google.spanner.admin.database.v1.DatabaseAdmin', 'ListDatabases'): face_utilities.unary_unary_inline(servicer.ListDatabases), + ('google.spanner.admin.database.v1.DatabaseAdmin', 'SetIamPolicy'): face_utilities.unary_unary_inline(servicer.SetIamPolicy), + ('google.spanner.admin.database.v1.DatabaseAdmin', 'TestIamPermissions'): face_utilities.unary_unary_inline(servicer.TestIamPermissions), + ('google.spanner.admin.database.v1.DatabaseAdmin', 'UpdateDatabaseDdl'): face_utilities.unary_unary_inline(servicer.UpdateDatabaseDdl), + } + server_options = beta_implementations.server_options(request_deserializers=request_deserializers, response_serializers=response_serializers, thread_pool=pool, thread_pool_size=pool_size, default_timeout=default_timeout, maximum_timeout=maximum_timeout) + return beta_implementations.server(method_implementations, options=server_options) + + + def beta_create_DatabaseAdmin_stub(channel, host=None, metadata_transformer=None, pool=None, pool_size=None): + """The Beta API is deprecated for 0.15.0 and later. + + It is recommended to use the GA API (classes and functions in this + file not marked beta) for all further purposes. This function was + generated only to ease transition from grpcio<0.15.0 to grpcio>=0.15.0""" + request_serializers = { + ('google.spanner.admin.database.v1.DatabaseAdmin', 'CreateDatabase'): CreateDatabaseRequest.SerializeToString, + ('google.spanner.admin.database.v1.DatabaseAdmin', 'DropDatabase'): DropDatabaseRequest.SerializeToString, + ('google.spanner.admin.database.v1.DatabaseAdmin', 'GetDatabase'): GetDatabaseRequest.SerializeToString, + ('google.spanner.admin.database.v1.DatabaseAdmin', 'GetDatabaseDdl'): GetDatabaseDdlRequest.SerializeToString, + ('google.spanner.admin.database.v1.DatabaseAdmin', 'GetIamPolicy'): google_dot_iam_dot_v1_dot_iam__policy__pb2.GetIamPolicyRequest.SerializeToString, + ('google.spanner.admin.database.v1.DatabaseAdmin', 'ListDatabases'): ListDatabasesRequest.SerializeToString, + ('google.spanner.admin.database.v1.DatabaseAdmin', 'SetIamPolicy'): google_dot_iam_dot_v1_dot_iam__policy__pb2.SetIamPolicyRequest.SerializeToString, + ('google.spanner.admin.database.v1.DatabaseAdmin', 'TestIamPermissions'): google_dot_iam_dot_v1_dot_iam__policy__pb2.TestIamPermissionsRequest.SerializeToString, + ('google.spanner.admin.database.v1.DatabaseAdmin', 'UpdateDatabaseDdl'): UpdateDatabaseDdlRequest.SerializeToString, + } + response_deserializers = { + ('google.spanner.admin.database.v1.DatabaseAdmin', 'CreateDatabase'): google_dot_longrunning_dot_operations__pb2.Operation.FromString, + ('google.spanner.admin.database.v1.DatabaseAdmin', 'DropDatabase'): google_dot_protobuf_dot_empty__pb2.Empty.FromString, + ('google.spanner.admin.database.v1.DatabaseAdmin', 'GetDatabase'): Database.FromString, + ('google.spanner.admin.database.v1.DatabaseAdmin', 'GetDatabaseDdl'): GetDatabaseDdlResponse.FromString, + ('google.spanner.admin.database.v1.DatabaseAdmin', 'GetIamPolicy'): google_dot_iam_dot_v1_dot_policy__pb2.Policy.FromString, + ('google.spanner.admin.database.v1.DatabaseAdmin', 'ListDatabases'): ListDatabasesResponse.FromString, + ('google.spanner.admin.database.v1.DatabaseAdmin', 'SetIamPolicy'): google_dot_iam_dot_v1_dot_policy__pb2.Policy.FromString, + ('google.spanner.admin.database.v1.DatabaseAdmin', 'TestIamPermissions'): google_dot_iam_dot_v1_dot_iam__policy__pb2.TestIamPermissionsResponse.FromString, + ('google.spanner.admin.database.v1.DatabaseAdmin', 'UpdateDatabaseDdl'): google_dot_longrunning_dot_operations__pb2.Operation.FromString, + } + cardinalities = { + 'CreateDatabase': cardinality.Cardinality.UNARY_UNARY, + 'DropDatabase': cardinality.Cardinality.UNARY_UNARY, + 'GetDatabase': cardinality.Cardinality.UNARY_UNARY, + 'GetDatabaseDdl': cardinality.Cardinality.UNARY_UNARY, + 'GetIamPolicy': cardinality.Cardinality.UNARY_UNARY, + 'ListDatabases': cardinality.Cardinality.UNARY_UNARY, + 'SetIamPolicy': cardinality.Cardinality.UNARY_UNARY, + 'TestIamPermissions': cardinality.Cardinality.UNARY_UNARY, + 'UpdateDatabaseDdl': cardinality.Cardinality.UNARY_UNARY, + } + stub_options = beta_implementations.stub_options(host=host, metadata_transformer=metadata_transformer, request_serializers=request_serializers, response_deserializers=response_deserializers, thread_pool=pool, thread_pool_size=pool_size) + return beta_implementations.dynamic_stub(channel, 'google.spanner.admin.database.v1.DatabaseAdmin', cardinalities, options=stub_options) +except ImportError: + pass +# @@protoc_insertion_point(module_scope) diff --git a/spanner/google/cloud/spanner_admin_database_v1/proto/spanner_database_admin_pb2_grpc.py b/spanner/google/cloud/spanner_admin_database_v1/proto/spanner_database_admin_pb2_grpc.py new file mode 100644 index 000000000000..5a88b9cb859f --- /dev/null +++ b/spanner/google/cloud/spanner_admin_database_v1/proto/spanner_database_admin_pb2_grpc.py @@ -0,0 +1,222 @@ +# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! +import grpc + +import google.cloud.spanner.admin.database_v1.proto.spanner_database_admin_pb2 as google_dot_cloud_dot_spanner_dot_admin_dot_database__v1_dot_proto_dot_spanner__database__admin__pb2 +import google.iam.v1.iam_policy_pb2 as google_dot_iam_dot_v1_dot_iam__policy__pb2 +import google.iam.v1.policy_pb2 as google_dot_iam_dot_v1_dot_policy__pb2 +import google.longrunning.operations_pb2 as google_dot_longrunning_dot_operations__pb2 +import google.protobuf.empty_pb2 as google_dot_protobuf_dot_empty__pb2 + + +class DatabaseAdminStub(object): + """Cloud Spanner Database Admin API + + The Cloud Spanner Database Admin API can be used to create, drop, and + list databases. It also enables updating the schema of pre-existing + databases. + """ + + def __init__(self, channel): + """Constructor. + + Args: + channel: A grpc.Channel. + """ + self.ListDatabases = channel.unary_unary( + '/google.spanner.admin.database.v1.DatabaseAdmin/ListDatabases', + request_serializer=google_dot_cloud_dot_spanner_dot_admin_dot_database__v1_dot_proto_dot_spanner__database__admin__pb2.ListDatabasesRequest.SerializeToString, + response_deserializer=google_dot_cloud_dot_spanner_dot_admin_dot_database__v1_dot_proto_dot_spanner__database__admin__pb2.ListDatabasesResponse.FromString, + ) + self.CreateDatabase = channel.unary_unary( + '/google.spanner.admin.database.v1.DatabaseAdmin/CreateDatabase', + request_serializer=google_dot_cloud_dot_spanner_dot_admin_dot_database__v1_dot_proto_dot_spanner__database__admin__pb2.CreateDatabaseRequest.SerializeToString, + response_deserializer=google_dot_longrunning_dot_operations__pb2.Operation.FromString, + ) + self.GetDatabase = channel.unary_unary( + '/google.spanner.admin.database.v1.DatabaseAdmin/GetDatabase', + request_serializer=google_dot_cloud_dot_spanner_dot_admin_dot_database__v1_dot_proto_dot_spanner__database__admin__pb2.GetDatabaseRequest.SerializeToString, + response_deserializer=google_dot_cloud_dot_spanner_dot_admin_dot_database__v1_dot_proto_dot_spanner__database__admin__pb2.Database.FromString, + ) + self.UpdateDatabaseDdl = channel.unary_unary( + '/google.spanner.admin.database.v1.DatabaseAdmin/UpdateDatabaseDdl', + request_serializer=google_dot_cloud_dot_spanner_dot_admin_dot_database__v1_dot_proto_dot_spanner__database__admin__pb2.UpdateDatabaseDdlRequest.SerializeToString, + response_deserializer=google_dot_longrunning_dot_operations__pb2.Operation.FromString, + ) + self.DropDatabase = channel.unary_unary( + '/google.spanner.admin.database.v1.DatabaseAdmin/DropDatabase', + request_serializer=google_dot_cloud_dot_spanner_dot_admin_dot_database__v1_dot_proto_dot_spanner__database__admin__pb2.DropDatabaseRequest.SerializeToString, + response_deserializer=google_dot_protobuf_dot_empty__pb2.Empty.FromString, + ) + self.GetDatabaseDdl = channel.unary_unary( + '/google.spanner.admin.database.v1.DatabaseAdmin/GetDatabaseDdl', + request_serializer=google_dot_cloud_dot_spanner_dot_admin_dot_database__v1_dot_proto_dot_spanner__database__admin__pb2.GetDatabaseDdlRequest.SerializeToString, + response_deserializer=google_dot_cloud_dot_spanner_dot_admin_dot_database__v1_dot_proto_dot_spanner__database__admin__pb2.GetDatabaseDdlResponse.FromString, + ) + self.SetIamPolicy = channel.unary_unary( + '/google.spanner.admin.database.v1.DatabaseAdmin/SetIamPolicy', + request_serializer=google_dot_iam_dot_v1_dot_iam__policy__pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=google_dot_iam_dot_v1_dot_policy__pb2.Policy.FromString, + ) + self.GetIamPolicy = channel.unary_unary( + '/google.spanner.admin.database.v1.DatabaseAdmin/GetIamPolicy', + request_serializer=google_dot_iam_dot_v1_dot_iam__policy__pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=google_dot_iam_dot_v1_dot_policy__pb2.Policy.FromString, + ) + self.TestIamPermissions = channel.unary_unary( + '/google.spanner.admin.database.v1.DatabaseAdmin/TestIamPermissions', + request_serializer=google_dot_iam_dot_v1_dot_iam__policy__pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=google_dot_iam_dot_v1_dot_iam__policy__pb2.TestIamPermissionsResponse.FromString, + ) + + +class DatabaseAdminServicer(object): + """Cloud Spanner Database Admin API + + The Cloud Spanner Database Admin API can be used to create, drop, and + list databases. It also enables updating the schema of pre-existing + databases. + """ + + def ListDatabases(self, request, context): + """Lists Cloud Spanner databases. + """ + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + def CreateDatabase(self, request, context): + """Creates a new Cloud Spanner database and starts to prepare it for serving. + The returned [long-running operation][google.longrunning.Operation] will + have a name of the format `/operations/` and + can be used to track preparation of the database. The + [metadata][google.longrunning.Operation.metadata] field type is + [CreateDatabaseMetadata][google.spanner.admin.database.v1.CreateDatabaseMetadata]. The + [response][google.longrunning.Operation.response] field type is + [Database][google.spanner.admin.database.v1.Database], if successful. + """ + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + def GetDatabase(self, request, context): + """Gets the state of a Cloud Spanner database. + """ + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + def UpdateDatabaseDdl(self, request, context): + """Updates the schema of a Cloud Spanner database by + creating/altering/dropping tables, columns, indexes, etc. The returned + [long-running operation][google.longrunning.Operation] will have a name of + the format `/operations/` and can be used to + track execution of the schema change(s). The + [metadata][google.longrunning.Operation.metadata] field type is + [UpdateDatabaseDdlMetadata][google.spanner.admin.database.v1.UpdateDatabaseDdlMetadata]. The operation has no response. + """ + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + def DropDatabase(self, request, context): + """Drops (aka deletes) a Cloud Spanner database. + """ + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + def GetDatabaseDdl(self, request, context): + """Returns the schema of a Cloud Spanner database as a list of formatted + DDL statements. This method does not show pending schema updates, those may + be queried using the [Operations][google.longrunning.Operations] API. + """ + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + def SetIamPolicy(self, request, context): + """Sets the access control policy on a database resource. Replaces any + existing policy. + + Authorization requires `spanner.databases.setIamPolicy` permission on + [resource][google.iam.v1.SetIamPolicyRequest.resource]. + """ + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + def GetIamPolicy(self, request, context): + """Gets the access control policy for a database resource. Returns an empty + policy if a database exists but does not have a policy set. + + Authorization requires `spanner.databases.getIamPolicy` permission on + [resource][google.iam.v1.GetIamPolicyRequest.resource]. + """ + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + def TestIamPermissions(self, request, context): + """Returns permissions that the caller has on the specified database resource. + + Attempting this RPC on a non-existent Cloud Spanner database will result in + a NOT_FOUND error if the user has `spanner.databases.list` permission on + the containing Cloud Spanner instance. Otherwise returns an empty set of + permissions. + """ + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + +def add_DatabaseAdminServicer_to_server(servicer, server): + rpc_method_handlers = { + 'ListDatabases': grpc.unary_unary_rpc_method_handler( + servicer.ListDatabases, + request_deserializer=google_dot_cloud_dot_spanner_dot_admin_dot_database__v1_dot_proto_dot_spanner__database__admin__pb2.ListDatabasesRequest.FromString, + response_serializer=google_dot_cloud_dot_spanner_dot_admin_dot_database__v1_dot_proto_dot_spanner__database__admin__pb2.ListDatabasesResponse.SerializeToString, + ), + 'CreateDatabase': grpc.unary_unary_rpc_method_handler( + servicer.CreateDatabase, + request_deserializer=google_dot_cloud_dot_spanner_dot_admin_dot_database__v1_dot_proto_dot_spanner__database__admin__pb2.CreateDatabaseRequest.FromString, + response_serializer=google_dot_longrunning_dot_operations__pb2.Operation.SerializeToString, + ), + 'GetDatabase': grpc.unary_unary_rpc_method_handler( + servicer.GetDatabase, + request_deserializer=google_dot_cloud_dot_spanner_dot_admin_dot_database__v1_dot_proto_dot_spanner__database__admin__pb2.GetDatabaseRequest.FromString, + response_serializer=google_dot_cloud_dot_spanner_dot_admin_dot_database__v1_dot_proto_dot_spanner__database__admin__pb2.Database.SerializeToString, + ), + 'UpdateDatabaseDdl': grpc.unary_unary_rpc_method_handler( + servicer.UpdateDatabaseDdl, + request_deserializer=google_dot_cloud_dot_spanner_dot_admin_dot_database__v1_dot_proto_dot_spanner__database__admin__pb2.UpdateDatabaseDdlRequest.FromString, + response_serializer=google_dot_longrunning_dot_operations__pb2.Operation.SerializeToString, + ), + 'DropDatabase': grpc.unary_unary_rpc_method_handler( + servicer.DropDatabase, + request_deserializer=google_dot_cloud_dot_spanner_dot_admin_dot_database__v1_dot_proto_dot_spanner__database__admin__pb2.DropDatabaseRequest.FromString, + response_serializer=google_dot_protobuf_dot_empty__pb2.Empty.SerializeToString, + ), + 'GetDatabaseDdl': grpc.unary_unary_rpc_method_handler( + servicer.GetDatabaseDdl, + request_deserializer=google_dot_cloud_dot_spanner_dot_admin_dot_database__v1_dot_proto_dot_spanner__database__admin__pb2.GetDatabaseDdlRequest.FromString, + response_serializer=google_dot_cloud_dot_spanner_dot_admin_dot_database__v1_dot_proto_dot_spanner__database__admin__pb2.GetDatabaseDdlResponse.SerializeToString, + ), + 'SetIamPolicy': grpc.unary_unary_rpc_method_handler( + servicer.SetIamPolicy, + request_deserializer=google_dot_iam_dot_v1_dot_iam__policy__pb2.SetIamPolicyRequest.FromString, + response_serializer=google_dot_iam_dot_v1_dot_policy__pb2.Policy.SerializeToString, + ), + 'GetIamPolicy': grpc.unary_unary_rpc_method_handler( + servicer.GetIamPolicy, + request_deserializer=google_dot_iam_dot_v1_dot_iam__policy__pb2.GetIamPolicyRequest.FromString, + response_serializer=google_dot_iam_dot_v1_dot_policy__pb2.Policy.SerializeToString, + ), + 'TestIamPermissions': grpc.unary_unary_rpc_method_handler( + servicer.TestIamPermissions, + request_deserializer=google_dot_iam_dot_v1_dot_iam__policy__pb2.TestIamPermissionsRequest.FromString, + response_serializer=google_dot_iam_dot_v1_dot_iam__policy__pb2.TestIamPermissionsResponse.SerializeToString, + ), + } + generic_handler = grpc.method_handlers_generic_handler( + 'google.spanner.admin.database.v1.DatabaseAdmin', rpc_method_handlers) + server.add_generic_rpc_handlers((generic_handler,)) diff --git a/spanner/google/cloud/spanner_admin_database_v1/types.py b/spanner/google/cloud/spanner_admin_database_v1/types.py new file mode 100644 index 000000000000..eeb9c8bc799f --- /dev/null +++ b/spanner/google/cloud/spanner_admin_database_v1/types.py @@ -0,0 +1,52 @@ +# Copyright 2017, Google Inc. All rights reserved. +# +# 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 +# +# http://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. + +from __future__ import absolute_import +import sys + +from google.gax.utils.messages import get_messages + +from google.api import auth_pb2 +from google.api import http_pb2 +from google.cloud.spanner_admin_database_v1.proto import spanner_database_admin_pb2 +from google.iam.v1 import iam_policy_pb2 +from google.iam.v1 import policy_pb2 +from google.iam.v1.logging import audit_data_pb2 +from google.longrunning import operations_pb2 +from google.protobuf import any_pb2 +from google.protobuf import descriptor_pb2 +from google.protobuf import empty_pb2 +from google.protobuf import timestamp_pb2 +from google.rpc import status_pb2 + +names = [] +for module in ( + auth_pb2, + http_pb2, + spanner_database_admin_pb2, + iam_policy_pb2, + policy_pb2, + audit_data_pb2, + operations_pb2, + any_pb2, + descriptor_pb2, + empty_pb2, + timestamp_pb2, + status_pb2, ): + for name, message in get_messages(module).items(): + message.__module__ = 'google.cloud.spanner_admin_database_v1.types' + setattr(sys.modules[__name__], name, message) + names.append(name) + +__all__ = tuple(sorted(names)) diff --git a/spanner/google/cloud/spanner_admin_instance_v1/__init__.py b/spanner/google/cloud/spanner_admin_instance_v1/__init__.py new file mode 100644 index 000000000000..29e2b8c04716 --- /dev/null +++ b/spanner/google/cloud/spanner_admin_instance_v1/__init__.py @@ -0,0 +1,30 @@ +# Copyright 2017, Google Inc. All rights reserved. +# +# 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 +# +# http://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. + +from __future__ import absolute_import + +from google.cloud.spanner_admin_instance_v1 import types +from google.cloud.spanner_admin_instance_v1.gapic import enums +from google.cloud.spanner_admin_instance_v1.gapic import instance_admin_client + + +class InstanceAdminClient(instance_admin_client.InstanceAdminClient): + __doc__ = instance_admin_client.InstanceAdminClient.__doc__ + enums = enums + + +__all__ = ( + 'enums', + 'types', + 'InstanceAdminClient', ) diff --git a/spanner/google/cloud/spanner_admin_instance_v1/gapic/__init__.py b/spanner/google/cloud/spanner_admin_instance_v1/gapic/__init__.py new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/spanner/google/cloud/spanner_admin_instance_v1/gapic/enums.py b/spanner/google/cloud/spanner_admin_instance_v1/gapic/enums.py new file mode 100644 index 000000000000..842773c026d3 --- /dev/null +++ b/spanner/google/cloud/spanner_admin_instance_v1/gapic/enums.py @@ -0,0 +1,32 @@ +# Copyright 2017, Google Inc. All rights reserved. +# +# 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 +# +# http://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. +"""Wrappers for protocol buffer enum types.""" + + +class Instance(object): + class State(object): + """ + Indicates the current state of the instance. + + Attributes: + STATE_UNSPECIFIED (int): Not specified. + CREATING (int): The instance is still being created. Resources may not be + available yet, and operations such as database creation may not + work. + READY (int): The instance is fully created and ready to do work such as + creating databases. + """ + STATE_UNSPECIFIED = 0 + CREATING = 1 + READY = 2 diff --git a/spanner/google/cloud/spanner_admin_instance_v1/gapic/instance_admin_client.py b/spanner/google/cloud/spanner_admin_instance_v1/gapic/instance_admin_client.py new file mode 100644 index 000000000000..ebb4323d1a2f --- /dev/null +++ b/spanner/google/cloud/spanner_admin_instance_v1/gapic/instance_admin_client.py @@ -0,0 +1,815 @@ +# Copyright 2017, Google Inc. All rights reserved. +# +# 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 +# +# http://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. +# +# EDITING INSTRUCTIONS +# This file was generated from the file +# https://github.com/google/googleapis/blob/master/google/spanner/admin/instance/v1/spanner_instance_admin.proto, +# and updates to that file get reflected here through a refresh process. +# For the short term, the refresh process will only be runnable by Google engineers. +# +# The only allowed edits are to method and file documentation. A 3-way +# merge preserves those additions if the generated source changes. +"""Accesses the google.spanner.admin.instance.v1 InstanceAdmin API.""" + +import collections +import json +import os +import pkg_resources +import platform + +from google.gapic.longrunning import operations_client +from google.gax import api_callable +from google.gax import config +from google.gax import path_template +import google.gax + +from google.cloud.spanner_admin_instance_v1.gapic import enums +from google.cloud.spanner_admin_instance_v1.gapic import instance_admin_client_config +from google.cloud.spanner_admin_instance_v1.proto import spanner_instance_admin_pb2 +from google.iam.v1 import iam_policy_pb2 +from google.iam.v1 import policy_pb2 +from google.protobuf import field_mask_pb2 + +_PageDesc = google.gax.PageDescriptor + + +class InstanceAdminClient(object): + """ + Cloud Spanner Instance Admin API + + The Cloud Spanner Instance Admin API can be used to create, delete, + modify and list instances. Instances are dedicated Cloud Spanner serving + and storage resources to be used by Cloud Spanner databases. + + Each instance has a \"configuration\", which dictates where the + serving resources for the Cloud Spanner instance are located (e.g., + US-central, Europe). Configurations are created by Google based on + resource availability. + + Cloud Spanner billing is based on the instances that exist and their + sizes. After an instance exists, there are no additional + per-database or per-operation charges for use of the instance + (though there may be additional network bandwidth charges). + Instances offer isolation: problems with databases in one instance + will not affect other instances. However, within an instance + databases can affect each other. For example, if one database in an + instance receives a lot of requests and consumes most of the + instance resources, fewer resources are available for other + databases in that instance, and their performance may suffer. + """ + + SERVICE_ADDRESS = 'spanner.googleapis.com' + """The default address of the service.""" + + DEFAULT_SERVICE_PORT = 443 + """The default port of the service.""" + + _PAGE_DESCRIPTORS = { + 'list_instance_configs': + _PageDesc('page_token', 'next_page_token', 'instance_configs'), + 'list_instances': + _PageDesc('page_token', 'next_page_token', 'instances') + } + + # The scopes needed to make gRPC calls to all of the methods defined in + # this service + _ALL_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/spanner.admin', ) + + _PROJECT_PATH_TEMPLATE = path_template.PathTemplate('projects/{project}') + _INSTANCE_CONFIG_PATH_TEMPLATE = path_template.PathTemplate( + 'projects/{project}/instanceConfigs/{instance_config}') + _INSTANCE_PATH_TEMPLATE = path_template.PathTemplate( + 'projects/{project}/instances/{instance}') + + @classmethod + def project_path(cls, project): + """Returns a fully-qualified project resource name string.""" + return cls._PROJECT_PATH_TEMPLATE.render({ + 'project': project, + }) + + @classmethod + def instance_config_path(cls, project, instance_config): + """Returns a fully-qualified instance_config resource name string.""" + return cls._INSTANCE_CONFIG_PATH_TEMPLATE.render({ + 'project': + project, + 'instance_config': + instance_config, + }) + + @classmethod + def instance_path(cls, project, instance): + """Returns a fully-qualified instance resource name string.""" + return cls._INSTANCE_PATH_TEMPLATE.render({ + 'project': project, + 'instance': instance, + }) + + @classmethod + def match_project_from_project_name(cls, project_name): + """Parses the project from a project resource. + + Args: + project_name (str): A fully-qualified path representing a project + resource. + + Returns: + A string representing the project. + """ + return cls._PROJECT_PATH_TEMPLATE.match(project_name).get('project') + + @classmethod + def match_project_from_instance_config_name(cls, instance_config_name): + """Parses the project from a instance_config resource. + + Args: + instance_config_name (str): A fully-qualified path representing a instance_config + resource. + + Returns: + A string representing the project. + """ + return cls._INSTANCE_CONFIG_PATH_TEMPLATE.match( + instance_config_name).get('project') + + @classmethod + def match_instance_config_from_instance_config_name( + cls, instance_config_name): + """Parses the instance_config from a instance_config resource. + + Args: + instance_config_name (str): A fully-qualified path representing a instance_config + resource. + + Returns: + A string representing the instance_config. + """ + return cls._INSTANCE_CONFIG_PATH_TEMPLATE.match( + instance_config_name).get('instance_config') + + @classmethod + def match_project_from_instance_name(cls, instance_name): + """Parses the project from a instance resource. + + Args: + instance_name (str): A fully-qualified path representing a instance + resource. + + Returns: + A string representing the project. + """ + return cls._INSTANCE_PATH_TEMPLATE.match(instance_name).get('project') + + @classmethod + def match_instance_from_instance_name(cls, instance_name): + """Parses the instance from a instance resource. + + Args: + instance_name (str): A fully-qualified path representing a instance + resource. + + Returns: + A string representing the instance. + """ + return cls._INSTANCE_PATH_TEMPLATE.match(instance_name).get('instance') + + def __init__(self, + channel=None, + credentials=None, + ssl_credentials=None, + scopes=None, + client_config=None, + lib_name=None, + lib_version='', + metrics_headers=()): + """Constructor. + + Args: + channel (~grpc.Channel): A ``Channel`` instance through + which to make calls. + credentials (~google.auth.credentials.Credentials): The authorization + credentials to attach to requests. These credentials identify this + application to the service. + ssl_credentials (~grpc.ChannelCredentials): A + ``ChannelCredentials`` instance for use with an SSL-enabled + channel. + scopes (Sequence[str]): A list of OAuth2 scopes to attach to requests. + client_config (dict): + A dictionary for call options for each method. See + :func:`google.gax.construct_settings` for the structure of + this data. Falls back to the default config if not specified + or the specified config is missing data points. + lib_name (str): The API library software used for calling + the service. (Unless you are writing an API client itself, + leave this as default.) + lib_version (str): The API library software version used + for calling the service. (Unless you are writing an API client + itself, leave this as default.) + metrics_headers (dict): A dictionary of values for tracking + client library metrics. Ultimately serializes to a string + (e.g. 'foo/1.2.3 bar/3.14.1'). This argument should be + considered private. + """ + # Unless the calling application specifically requested + # OAuth scopes, request everything. + if scopes is None: + scopes = self._ALL_SCOPES + + # Initialize an empty client config, if none is set. + if client_config is None: + client_config = {} + + # Initialize metrics_headers as an ordered dictionary + # (cuts down on cardinality of the resulting string slightly). + metrics_headers = collections.OrderedDict(metrics_headers) + metrics_headers['gl-python'] = platform.python_version() + + # The library may or may not be set, depending on what is + # calling this client. Newer client libraries set the library name + # and version. + if lib_name: + metrics_headers[lib_name] = lib_version + + # Finally, track the GAPIC package version. + metrics_headers['gapic'] = pkg_resources.get_distribution( + 'google-cloud-spanner', ).version + + # Load the configuration defaults. + defaults = api_callable.construct_settings( + 'google.spanner.admin.instance.v1.InstanceAdmin', + instance_admin_client_config.config, + client_config, + config.STATUS_CODE_NAMES, + metrics_headers=metrics_headers, + page_descriptors=self._PAGE_DESCRIPTORS, ) + self.instance_admin_stub = config.create_stub( + spanner_instance_admin_pb2.InstanceAdminStub, + channel=channel, + service_path=self.SERVICE_ADDRESS, + service_port=self.DEFAULT_SERVICE_PORT, + credentials=credentials, + scopes=scopes, + ssl_credentials=ssl_credentials) + + self.operations_client = operations_client.OperationsClient( + service_path=self.SERVICE_ADDRESS, + channel=channel, + credentials=credentials, + ssl_credentials=ssl_credentials, + scopes=scopes, + client_config=client_config, + metrics_headers=metrics_headers, ) + + self._list_instance_configs = api_callable.create_api_call( + self.instance_admin_stub.ListInstanceConfigs, + settings=defaults['list_instance_configs']) + self._get_instance_config = api_callable.create_api_call( + self.instance_admin_stub.GetInstanceConfig, + settings=defaults['get_instance_config']) + self._list_instances = api_callable.create_api_call( + self.instance_admin_stub.ListInstances, + settings=defaults['list_instances']) + self._get_instance = api_callable.create_api_call( + self.instance_admin_stub.GetInstance, + settings=defaults['get_instance']) + self._create_instance = api_callable.create_api_call( + self.instance_admin_stub.CreateInstance, + settings=defaults['create_instance']) + self._update_instance = api_callable.create_api_call( + self.instance_admin_stub.UpdateInstance, + settings=defaults['update_instance']) + self._delete_instance = api_callable.create_api_call( + self.instance_admin_stub.DeleteInstance, + settings=defaults['delete_instance']) + self._set_iam_policy = api_callable.create_api_call( + self.instance_admin_stub.SetIamPolicy, + settings=defaults['set_iam_policy']) + self._get_iam_policy = api_callable.create_api_call( + self.instance_admin_stub.GetIamPolicy, + settings=defaults['get_iam_policy']) + self._test_iam_permissions = api_callable.create_api_call( + self.instance_admin_stub.TestIamPermissions, + settings=defaults['test_iam_permissions']) + + # Service calls + def list_instance_configs(self, parent, page_size=None, options=None): + """ + Lists the supported instance configurations for a given project. + + Example: + >>> from google.cloud import spanner_admin_instance_v1 + >>> from google.gax import CallOptions, INITIAL_PAGE + >>> + >>> client = spanner_admin_instance_v1.InstanceAdminClient() + >>> + >>> parent = client.project_path('[PROJECT]') + >>> + >>> + >>> # Iterate over all results + >>> for element in client.list_instance_configs(parent): + ... # process element + ... pass + >>> + >>> # Or iterate over results one page at a time + >>> for page in client.list_instance_configs(parent, options=CallOptions(page_token=INITIAL_PAGE)): + ... for element in page: + ... # process element + ... pass + + Args: + parent (str): Required. The name of the project for which a list of supported instance + configurations is requested. Values are of the form + ``projects/``. + page_size (int): The maximum number of resources contained in the + underlying API response. If page streaming is performed per- + resource, this parameter does not affect the return value. If page + streaming is performed per-page, this determines the maximum number + of resources in a page. + options (~google.gax.CallOptions): Overrides the default + settings for this call, e.g, timeout, retries etc. + + Returns: + A :class:`~google.gax.PageIterator` instance. By default, this + is an iterable of :class:`~google.cloud.spanner_admin_instance_v1.types.InstanceConfig` instances. + This object can also be configured to iterate over the pages + of the response through the `options` parameter. + + Raises: + :exc:`google.gax.errors.GaxError` if the RPC is aborted. + :exc:`ValueError` if the parameters are invalid. + """ + request = spanner_instance_admin_pb2.ListInstanceConfigsRequest( + parent=parent, page_size=page_size) + return self._list_instance_configs(request, options) + + def get_instance_config(self, name, options=None): + """ + Gets information about a particular instance configuration. + + Example: + >>> from google.cloud import spanner_admin_instance_v1 + >>> + >>> client = spanner_admin_instance_v1.InstanceAdminClient() + >>> + >>> name = client.instance_config_path('[PROJECT]', '[INSTANCE_CONFIG]') + >>> + >>> response = client.get_instance_config(name) + + Args: + name (str): Required. The name of the requested instance configuration. Values are of + the form ``projects//instanceConfigs/``. + options (~google.gax.CallOptions): Overrides the default + settings for this call, e.g, timeout, retries etc. + + Returns: + A :class:`~google.cloud.spanner_admin_instance_v1.types.InstanceConfig` instance. + + Raises: + :exc:`google.gax.errors.GaxError` if the RPC is aborted. + :exc:`ValueError` if the parameters are invalid. + """ + request = spanner_instance_admin_pb2.GetInstanceConfigRequest( + name=name) + return self._get_instance_config(request, options) + + def list_instances(self, + parent, + page_size=None, + filter_=None, + options=None): + """ + Lists all instances in the given project. + + Example: + >>> from google.cloud import spanner_admin_instance_v1 + >>> from google.gax import CallOptions, INITIAL_PAGE + >>> + >>> client = spanner_admin_instance_v1.InstanceAdminClient() + >>> + >>> parent = client.project_path('[PROJECT]') + >>> + >>> + >>> # Iterate over all results + >>> for element in client.list_instances(parent): + ... # process element + ... pass + >>> + >>> # Or iterate over results one page at a time + >>> for page in client.list_instances(parent, options=CallOptions(page_token=INITIAL_PAGE)): + ... for element in page: + ... # process element + ... pass + + Args: + parent (str): Required. The name of the project for which a list of instances is + requested. Values are of the form ``projects/``. + page_size (int): The maximum number of resources contained in the + underlying API response. If page streaming is performed per- + resource, this parameter does not affect the return value. If page + streaming is performed per-page, this determines the maximum number + of resources in a page. + filter_ (str): An expression for filtering the results of the request. Filter rules are + case insensitive. The fields eligible for filtering are: + + * name + * display_name + * labels.key where key is the name of a label + + Some examples of using filters are: + + * name:* --> The instance has a name. + * name:Howl --> The instance's name contains the string \"howl\". + * name:HOWL --> Equivalent to above. + * NAME:howl --> Equivalent to above. + * labels.env:* --> The instance has the label \"env\". + * labels.env:dev --> The instance has the label \"env\" and the value of + the label contains the string \"dev\". + * name:howl labels.env:dev --> The instance's name contains \"howl\" and + it has the label \"env\" with its value containing \"dev\". + + options (~google.gax.CallOptions): Overrides the default + settings for this call, e.g, timeout, retries etc. + + Returns: + A :class:`~google.gax.PageIterator` instance. By default, this + is an iterable of :class:`~google.cloud.spanner_admin_instance_v1.types.Instance` instances. + This object can also be configured to iterate over the pages + of the response through the `options` parameter. + + Raises: + :exc:`google.gax.errors.GaxError` if the RPC is aborted. + :exc:`ValueError` if the parameters are invalid. + """ + request = spanner_instance_admin_pb2.ListInstancesRequest( + parent=parent, page_size=page_size, filter=filter_) + return self._list_instances(request, options) + + def get_instance(self, name, options=None): + """ + Gets information about a particular instance. + + Example: + >>> from google.cloud import spanner_admin_instance_v1 + >>> + >>> client = spanner_admin_instance_v1.InstanceAdminClient() + >>> + >>> name = client.instance_path('[PROJECT]', '[INSTANCE]') + >>> + >>> response = client.get_instance(name) + + Args: + name (str): Required. The name of the requested instance. Values are of the form + ``projects//instances/``. + options (~google.gax.CallOptions): Overrides the default + settings for this call, e.g, timeout, retries etc. + + Returns: + A :class:`~google.cloud.spanner_admin_instance_v1.types.Instance` instance. + + Raises: + :exc:`google.gax.errors.GaxError` if the RPC is aborted. + :exc:`ValueError` if the parameters are invalid. + """ + request = spanner_instance_admin_pb2.GetInstanceRequest(name=name) + return self._get_instance(request, options) + + def create_instance(self, parent, instance_id, instance, options=None): + """ + Creates an instance and begins preparing it to begin serving. The + returned ``long-running operation`` + can be used to track the progress of preparing the new + instance. The instance name is assigned by the caller. If the + named instance already exists, ``CreateInstance`` returns + ``ALREADY_EXISTS``. + + Immediately upon completion of this request: + + * The instance is readable via the API, with all requested attributes + but no allocated resources. Its state is `CREATING`. + + Until completion of the returned operation: + + * Cancelling the operation renders the instance immediately unreadable + via the API. + * The instance can be deleted. + * All other attempts to modify the instance are rejected. + + Upon completion of the returned operation: + + * Billing for all successfully-allocated resources begins (some types + may have lower than the requested levels). + * Databases can be created in the instance. + * The instance's allocated resource levels are readable via the API. + * The instance's state becomes ``READY``. + + The returned ``long-running operation`` will + have a name of the format ``/operations/`` and + can be used to track creation of the instance. The + ``metadata`` field type is + ``CreateInstanceMetadata``. + The ``response`` field type is + ``Instance``, if successful. + + Example: + >>> from google.cloud import spanner_admin_instance_v1 + >>> + >>> client = spanner_admin_instance_v1.InstanceAdminClient() + >>> + >>> parent = client.project_path('[PROJECT]') + >>> instance_id = '' + >>> instance = {} + >>> + >>> response = client.create_instance(parent, instance_id, instance) + >>> + >>> def callback(operation_future): + ... # Handle result. + ... result = operation_future.result() + >>> + >>> response.add_done_callback(callback) + >>> + >>> # Handle metadata. + >>> metadata = response.metadata() + + Args: + parent (str): Required. The name of the project in which to create the instance. Values + are of the form ``projects/``. + instance_id (str): Required. The ID of the instance to create. Valid identifiers are of the + form ``[a-z][-a-z0-9]*[a-z0-9]`` and must be between 6 and 30 characters in + length. + instance (Union[dict, ~google.cloud.spanner_admin_instance_v1.types.Instance]): Required. The instance to create. The name may be omitted, but if + specified must be ``/instances/``. + If a dict is provided, it must be of the same form as the protobuf + message :class:`~google.cloud.spanner_admin_instance_v1.types.Instance` + options (~google.gax.CallOptions): Overrides the default + settings for this call, e.g, timeout, retries etc. + + Returns: + A :class:`~google.cloud.spanner_admin_instance_v1.types._OperationFuture` instance. + + Raises: + :exc:`google.gax.errors.GaxError` if the RPC is aborted. + :exc:`ValueError` if the parameters are invalid. + """ + request = spanner_instance_admin_pb2.CreateInstanceRequest( + parent=parent, instance_id=instance_id, instance=instance) + return google.gax._OperationFuture( + self._create_instance(request, options), self.operations_client, + spanner_instance_admin_pb2.Instance, + spanner_instance_admin_pb2.CreateInstanceMetadata, options) + + def update_instance(self, instance, field_mask, options=None): + """ + Updates an instance, and begins allocating or releasing resources + as requested. The returned [long-running + operation][google.longrunning.Operation] can be used to track the + progress of updating the instance. If the named instance does not + exist, returns ``NOT_FOUND``. + + Immediately upon completion of this request: + + * For resource types for which a decrease in the instance's allocation + has been requested, billing is based on the newly-requested level. + + Until completion of the returned operation: + + * Cancelling the operation sets its metadata's + [cancel_time][google.spanner.admin.instance.v1.UpdateInstanceMetadata.cancel_time], and begins + restoring resources to their pre-request values. The operation + is guaranteed to succeed at undoing all resource changes, + after which point it terminates with a `CANCELLED` status. + * All other attempts to modify the instance are rejected. + * Reading the instance via the API continues to give the pre-request + resource levels. + + Upon completion of the returned operation: + + * Billing begins for all successfully-allocated resources (some types + may have lower than the requested levels). + * All newly-reserved resources are available for serving the instance's + tables. + * The instance's new resource levels are readable via the API. + + The returned ``long-running operation`` will + have a name of the format ``/operations/`` and + can be used to track the instance modification. The + ``metadata`` field type is + ``UpdateInstanceMetadata``. + The ``response`` field type is + ``Instance``, if successful. + + Authorization requires ``spanner.instances.update`` permission on + resource ``name``. + + Example: + >>> from google.cloud import spanner_admin_instance_v1 + >>> + >>> client = spanner_admin_instance_v1.InstanceAdminClient() + >>> + >>> instance = {} + >>> field_mask = {} + >>> + >>> response = client.update_instance(instance, field_mask) + >>> + >>> def callback(operation_future): + ... # Handle result. + ... result = operation_future.result() + >>> + >>> response.add_done_callback(callback) + >>> + >>> # Handle metadata. + >>> metadata = response.metadata() + + Args: + instance (Union[dict, ~google.cloud.spanner_admin_instance_v1.types.Instance]): Required. The instance to update, which must always include the instance + name. Otherwise, only fields mentioned in [][google.spanner.admin.instance.v1.UpdateInstanceRequest.field_mask] need be included. + If a dict is provided, it must be of the same form as the protobuf + message :class:`~google.cloud.spanner_admin_instance_v1.types.Instance` + field_mask (Union[dict, ~google.cloud.spanner_admin_instance_v1.types.FieldMask]): Required. A mask specifying which fields in [][google.spanner.admin.instance.v1.UpdateInstanceRequest.instance] should be updated. + The field mask must always be specified; this prevents any future fields in + [][google.spanner.admin.instance.v1.Instance] from being erased accidentally by clients that do not know + about them. + If a dict is provided, it must be of the same form as the protobuf + message :class:`~google.cloud.spanner_admin_instance_v1.types.FieldMask` + options (~google.gax.CallOptions): Overrides the default + settings for this call, e.g, timeout, retries etc. + + Returns: + A :class:`~google.cloud.spanner_admin_instance_v1.types._OperationFuture` instance. + + Raises: + :exc:`google.gax.errors.GaxError` if the RPC is aborted. + :exc:`ValueError` if the parameters are invalid. + """ + request = spanner_instance_admin_pb2.UpdateInstanceRequest( + instance=instance, field_mask=field_mask) + return google.gax._OperationFuture( + self._update_instance(request, options), self.operations_client, + spanner_instance_admin_pb2.Instance, + spanner_instance_admin_pb2.UpdateInstanceMetadata, options) + + def delete_instance(self, name, options=None): + """ + Deletes an instance. + + Immediately upon completion of the request: + + * Billing ceases for all of the instance's reserved resources. + + Soon afterward: + + * The instance and *all of its databases* immediately and + irrevocably disappear from the API. All data in the databases + is permanently deleted. + + Example: + >>> from google.cloud import spanner_admin_instance_v1 + >>> + >>> client = spanner_admin_instance_v1.InstanceAdminClient() + >>> + >>> name = client.instance_path('[PROJECT]', '[INSTANCE]') + >>> + >>> client.delete_instance(name) + + Args: + name (str): Required. The name of the instance to be deleted. Values are of the form + ``projects//instances/`` + options (~google.gax.CallOptions): Overrides the default + settings for this call, e.g, timeout, retries etc. + + Raises: + :exc:`google.gax.errors.GaxError` if the RPC is aborted. + :exc:`ValueError` if the parameters are invalid. + """ + request = spanner_instance_admin_pb2.DeleteInstanceRequest(name=name) + self._delete_instance(request, options) + + def set_iam_policy(self, resource, policy, options=None): + """ + Sets the access control policy on an instance resource. Replaces any + existing policy. + + Authorization requires ``spanner.instances.setIamPolicy`` on + ``resource``. + + Example: + >>> from google.cloud import spanner_admin_instance_v1 + >>> + >>> client = spanner_admin_instance_v1.InstanceAdminClient() + >>> + >>> resource = client.instance_path('[PROJECT]', '[INSTANCE]') + >>> policy = {} + >>> + >>> response = client.set_iam_policy(resource, policy) + + Args: + resource (str): REQUIRED: The resource for which the policy is being specified. + ``resource`` is usually specified as a path. For example, a Project + resource is specified as ``projects/{project}``. + policy (Union[dict, ~google.cloud.spanner_admin_instance_v1.types.Policy]): REQUIRED: The complete policy to be applied to the ``resource``. The size of + the policy is limited to a few 10s of KB. An empty policy is a + valid policy but certain Cloud Platform services (such as Projects) + might reject them. + If a dict is provided, it must be of the same form as the protobuf + message :class:`~google.cloud.spanner_admin_instance_v1.types.Policy` + options (~google.gax.CallOptions): Overrides the default + settings for this call, e.g, timeout, retries etc. + + Returns: + A :class:`~google.cloud.spanner_admin_instance_v1.types.Policy` instance. + + Raises: + :exc:`google.gax.errors.GaxError` if the RPC is aborted. + :exc:`ValueError` if the parameters are invalid. + """ + request = iam_policy_pb2.SetIamPolicyRequest( + resource=resource, policy=policy) + return self._set_iam_policy(request, options) + + def get_iam_policy(self, resource, options=None): + """ + Gets the access control policy for an instance resource. Returns an empty + policy if an instance exists but does not have a policy set. + + Authorization requires ``spanner.instances.getIamPolicy`` on + ``resource``. + + Example: + >>> from google.cloud import spanner_admin_instance_v1 + >>> + >>> client = spanner_admin_instance_v1.InstanceAdminClient() + >>> + >>> resource = client.instance_path('[PROJECT]', '[INSTANCE]') + >>> + >>> response = client.get_iam_policy(resource) + + Args: + resource (str): REQUIRED: The resource for which the policy is being requested. + ``resource`` is usually specified as a path. For example, a Project + resource is specified as ``projects/{project}``. + options (~google.gax.CallOptions): Overrides the default + settings for this call, e.g, timeout, retries etc. + + Returns: + A :class:`~google.cloud.spanner_admin_instance_v1.types.Policy` instance. + + Raises: + :exc:`google.gax.errors.GaxError` if the RPC is aborted. + :exc:`ValueError` if the parameters are invalid. + """ + request = iam_policy_pb2.GetIamPolicyRequest(resource=resource) + return self._get_iam_policy(request, options) + + def test_iam_permissions(self, resource, permissions, options=None): + """ + Returns permissions that the caller has on the specified instance resource. + + Attempting this RPC on a non-existent Cloud Spanner instance resource will + result in a NOT_FOUND error if the user has ``spanner.instances.list`` + permission on the containing Google Cloud Project. Otherwise returns an + empty set of permissions. + + Example: + >>> from google.cloud import spanner_admin_instance_v1 + >>> + >>> client = spanner_admin_instance_v1.InstanceAdminClient() + >>> + >>> resource = client.instance_path('[PROJECT]', '[INSTANCE]') + >>> permissions = [] + >>> + >>> response = client.test_iam_permissions(resource, permissions) + + Args: + resource (str): REQUIRED: The resource for which the policy detail is being requested. + ``resource`` is usually specified as a path. For example, a Project + resource is specified as ``projects/{project}``. + permissions (list[str]): The set of permissions to check for the ``resource``. Permissions with + wildcards (such as '*' or 'storage.*') are not allowed. For more + information see + `IAM Overview `_. + options (~google.gax.CallOptions): Overrides the default + settings for this call, e.g, timeout, retries etc. + + Returns: + A :class:`~google.cloud.spanner_admin_instance_v1.types.TestIamPermissionsResponse` instance. + + Raises: + :exc:`google.gax.errors.GaxError` if the RPC is aborted. + :exc:`ValueError` if the parameters are invalid. + """ + request = iam_policy_pb2.TestIamPermissionsRequest( + resource=resource, permissions=permissions) + return self._test_iam_permissions(request, options) diff --git a/spanner/google/cloud/spanner_admin_instance_v1/gapic/instance_admin_client_config.py b/spanner/google/cloud/spanner_admin_instance_v1/gapic/instance_admin_client_config.py new file mode 100644 index 000000000000..eb9e066ac33a --- /dev/null +++ b/spanner/google/cloud/spanner_admin_instance_v1/gapic/instance_admin_client_config.py @@ -0,0 +1,73 @@ +config = { + "interfaces": { + "google.spanner.admin.instance.v1.InstanceAdmin": { + "retry_codes": { + "idempotent": ["DEADLINE_EXCEEDED", "UNAVAILABLE"], + "non_idempotent": [] + }, + "retry_params": { + "default": { + "initial_retry_delay_millis": 1000, + "retry_delay_multiplier": 1.3, + "max_retry_delay_millis": 32000, + "initial_rpc_timeout_millis": 60000, + "rpc_timeout_multiplier": 1.0, + "max_rpc_timeout_millis": 60000, + "total_timeout_millis": 600000 + } + }, + "methods": { + "ListInstanceConfigs": { + "timeout_millis": 30000, + "retry_codes_name": "idempotent", + "retry_params_name": "default" + }, + "GetInstanceConfig": { + "timeout_millis": 30000, + "retry_codes_name": "idempotent", + "retry_params_name": "default" + }, + "ListInstances": { + "timeout_millis": 30000, + "retry_codes_name": "idempotent", + "retry_params_name": "default" + }, + "GetInstance": { + "timeout_millis": 30000, + "retry_codes_name": "idempotent", + "retry_params_name": "default" + }, + "CreateInstance": { + "timeout_millis": 30000, + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + }, + "UpdateInstance": { + "timeout_millis": 30000, + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + }, + "DeleteInstance": { + "timeout_millis": 30000, + "retry_codes_name": "idempotent", + "retry_params_name": "default" + }, + "SetIamPolicy": { + "timeout_millis": 30000, + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + }, + "GetIamPolicy": { + "timeout_millis": 30000, + "retry_codes_name": "idempotent", + "retry_params_name": "default" + }, + "TestIamPermissions": { + "timeout_millis": 30000, + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + } + } + } + } +} diff --git a/spanner/google/cloud/spanner_admin_instance_v1/proto/__init__.py b/spanner/google/cloud/spanner_admin_instance_v1/proto/__init__.py new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/spanner/google/cloud/spanner_admin_instance_v1/proto/spanner_instance_admin_pb2.py b/spanner/google/cloud/spanner_admin_instance_v1/proto/spanner_instance_admin_pb2.py new file mode 100644 index 000000000000..8861b428e855 --- /dev/null +++ b/spanner/google/cloud/spanner_admin_instance_v1/proto/spanner_instance_admin_pb2.py @@ -0,0 +1,1818 @@ +# Generated by the protocol buffer compiler. DO NOT EDIT! +# source: google/cloud/spanner/admin/instance_v1/proto/spanner_instance_admin.proto + +import sys +_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) +from google.protobuf import descriptor as _descriptor +from google.protobuf import message as _message +from google.protobuf import reflection as _reflection +from google.protobuf import symbol_database as _symbol_database +from google.protobuf import descriptor_pb2 +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + + +from google.api import annotations_pb2 as google_dot_api_dot_annotations__pb2 +from google.api import auth_pb2 as google_dot_api_dot_auth__pb2 +from google.iam.v1 import iam_policy_pb2 as google_dot_iam_dot_v1_dot_iam__policy__pb2 +from google.iam.v1 import policy_pb2 as google_dot_iam_dot_v1_dot_policy__pb2 +from google.longrunning import operations_pb2 as google_dot_longrunning_dot_operations__pb2 +from google.protobuf import empty_pb2 as google_dot_protobuf_dot_empty__pb2 +from google.protobuf import field_mask_pb2 as google_dot_protobuf_dot_field__mask__pb2 +from google.protobuf import timestamp_pb2 as google_dot_protobuf_dot_timestamp__pb2 + + +DESCRIPTOR = _descriptor.FileDescriptor( + name='google/cloud/spanner/admin/instance_v1/proto/spanner_instance_admin.proto', + package='google.spanner.admin.instance.v1', + syntax='proto3', + serialized_pb=_b('\nIgoogle/cloud/spanner/admin/instance_v1/proto/spanner_instance_admin.proto\x12 google.spanner.admin.instance.v1\x1a\x1cgoogle/api/annotations.proto\x1a\x15google/api/auth.proto\x1a\x1egoogle/iam/v1/iam_policy.proto\x1a\x1agoogle/iam/v1/policy.proto\x1a#google/longrunning/operations.proto\x1a\x1bgoogle/protobuf/empty.proto\x1a google/protobuf/field_mask.proto\x1a\x1fgoogle/protobuf/timestamp.proto\"4\n\x0eInstanceConfig\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x14\n\x0c\x64isplay_name\x18\x02 \x01(\t\"\xc3\x02\n\x08Instance\x12\x0c\n\x04name\x18\x01 \x01(\t\x12\x0e\n\x06\x63onfig\x18\x02 \x01(\t\x12\x14\n\x0c\x64isplay_name\x18\x03 \x01(\t\x12\x12\n\nnode_count\x18\x05 \x01(\x05\x12?\n\x05state\x18\x06 \x01(\x0e\x32\x30.google.spanner.admin.instance.v1.Instance.State\x12\x46\n\x06labels\x18\x07 \x03(\x0b\x32\x36.google.spanner.admin.instance.v1.Instance.LabelsEntry\x1a-\n\x0bLabelsEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01\"7\n\x05State\x12\x15\n\x11STATE_UNSPECIFIED\x10\x00\x12\x0c\n\x08\x43REATING\x10\x01\x12\t\n\x05READY\x10\x02\"S\n\x1aListInstanceConfigsRequest\x12\x0e\n\x06parent\x18\x01 \x01(\t\x12\x11\n\tpage_size\x18\x02 \x01(\x05\x12\x12\n\npage_token\x18\x03 \x01(\t\"\x82\x01\n\x1bListInstanceConfigsResponse\x12J\n\x10instance_configs\x18\x01 \x03(\x0b\x32\x30.google.spanner.admin.instance.v1.InstanceConfig\x12\x17\n\x0fnext_page_token\x18\x02 \x01(\t\"(\n\x18GetInstanceConfigRequest\x12\x0c\n\x04name\x18\x01 \x01(\t\"\"\n\x12GetInstanceRequest\x12\x0c\n\x04name\x18\x01 \x01(\t\"z\n\x15\x43reateInstanceRequest\x12\x0e\n\x06parent\x18\x01 \x01(\t\x12\x13\n\x0binstance_id\x18\x02 \x01(\t\x12<\n\x08instance\x18\x03 \x01(\x0b\x32*.google.spanner.admin.instance.v1.Instance\"]\n\x14ListInstancesRequest\x12\x0e\n\x06parent\x18\x01 \x01(\t\x12\x11\n\tpage_size\x18\x02 \x01(\x05\x12\x12\n\npage_token\x18\x03 \x01(\t\x12\x0e\n\x06\x66ilter\x18\x04 \x01(\t\"o\n\x15ListInstancesResponse\x12=\n\tinstances\x18\x01 \x03(\x0b\x32*.google.spanner.admin.instance.v1.Instance\x12\x17\n\x0fnext_page_token\x18\x02 \x01(\t\"\x85\x01\n\x15UpdateInstanceRequest\x12<\n\x08instance\x18\x01 \x01(\x0b\x32*.google.spanner.admin.instance.v1.Instance\x12.\n\nfield_mask\x18\x02 \x01(\x0b\x32\x1a.google.protobuf.FieldMask\"%\n\x15\x44\x65leteInstanceRequest\x12\x0c\n\x04name\x18\x01 \x01(\t\"\xe5\x01\n\x16\x43reateInstanceMetadata\x12<\n\x08instance\x18\x01 \x01(\x0b\x32*.google.spanner.admin.instance.v1.Instance\x12.\n\nstart_time\x18\x02 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12/\n\x0b\x63\x61ncel_time\x18\x03 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12,\n\x08\x65nd_time\x18\x04 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\"\xe5\x01\n\x16UpdateInstanceMetadata\x12<\n\x08instance\x18\x01 \x01(\x0b\x32*.google.spanner.admin.instance.v1.Instance\x12.\n\nstart_time\x18\x02 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12/\n\x0b\x63\x61ncel_time\x18\x03 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12,\n\x08\x65nd_time\x18\x04 \x01(\x0b\x32\x1a.google.protobuf.Timestamp2\xe6\x0c\n\rInstanceAdmin\x12\xc3\x01\n\x13ListInstanceConfigs\x12<.google.spanner.admin.instance.v1.ListInstanceConfigsRequest\x1a=.google.spanner.admin.instance.v1.ListInstanceConfigsResponse\"/\x82\xd3\xe4\x93\x02)\x12\'/v1/{parent=projects/*}/instanceConfigs\x12\xb2\x01\n\x11GetInstanceConfig\x12:.google.spanner.admin.instance.v1.GetInstanceConfigRequest\x1a\x30.google.spanner.admin.instance.v1.InstanceConfig\"/\x82\xd3\xe4\x93\x02)\x12\'/v1/{name=projects/*/instanceConfigs/*}\x12\xab\x01\n\rListInstances\x12\x36.google.spanner.admin.instance.v1.ListInstancesRequest\x1a\x37.google.spanner.admin.instance.v1.ListInstancesResponse\")\x82\xd3\xe4\x93\x02#\x12!/v1/{parent=projects/*}/instances\x12\x9a\x01\n\x0bGetInstance\x12\x34.google.spanner.admin.instance.v1.GetInstanceRequest\x1a*.google.spanner.admin.instance.v1.Instance\")\x82\xd3\xe4\x93\x02#\x12!/v1/{name=projects/*/instances/*}\x12\x96\x01\n\x0e\x43reateInstance\x12\x37.google.spanner.admin.instance.v1.CreateInstanceRequest\x1a\x1d.google.longrunning.Operation\",\x82\xd3\xe4\x93\x02&\"!/v1/{parent=projects/*}/instances:\x01*\x12\x9f\x01\n\x0eUpdateInstance\x12\x37.google.spanner.admin.instance.v1.UpdateInstanceRequest\x1a\x1d.google.longrunning.Operation\"5\x82\xd3\xe4\x93\x02/2*/v1/{instance.name=projects/*/instances/*}:\x01*\x12\x8c\x01\n\x0e\x44\x65leteInstance\x12\x37.google.spanner.admin.instance.v1.DeleteInstanceRequest\x1a\x16.google.protobuf.Empty\")\x82\xd3\xe4\x93\x02#*!/v1/{name=projects/*/instances/*}\x12\x88\x01\n\x0cSetIamPolicy\x12\".google.iam.v1.SetIamPolicyRequest\x1a\x15.google.iam.v1.Policy\"=\x82\xd3\xe4\x93\x02\x37\"2/v1/{resource=projects/*/instances/*}:setIamPolicy:\x01*\x12\x88\x01\n\x0cGetIamPolicy\x12\".google.iam.v1.GetIamPolicyRequest\x1a\x15.google.iam.v1.Policy\"=\x82\xd3\xe4\x93\x02\x37\"2/v1/{resource=projects/*/instances/*}:getIamPolicy:\x01*\x12\xae\x01\n\x12TestIamPermissions\x12(.google.iam.v1.TestIamPermissionsRequest\x1a).google.iam.v1.TestIamPermissionsResponse\"C\x82\xd3\xe4\x93\x02=\"8/v1/{resource=projects/*/instances/*}:testIamPermissions:\x01*B\xb6\x01\n$com.google.spanner.admin.instance.v1B\x19SpannerInstanceAdminProtoP\x01ZHgoogle.golang.org/genproto/googleapis/spanner/admin/instance/v1;instance\xaa\x02&Google.Cloud.Spanner.Admin.Instance.V1b\x06proto3') + , + dependencies=[google_dot_api_dot_annotations__pb2.DESCRIPTOR,google_dot_api_dot_auth__pb2.DESCRIPTOR,google_dot_iam_dot_v1_dot_iam__policy__pb2.DESCRIPTOR,google_dot_iam_dot_v1_dot_policy__pb2.DESCRIPTOR,google_dot_longrunning_dot_operations__pb2.DESCRIPTOR,google_dot_protobuf_dot_empty__pb2.DESCRIPTOR,google_dot_protobuf_dot_field__mask__pb2.DESCRIPTOR,google_dot_protobuf_dot_timestamp__pb2.DESCRIPTOR,]) +_sym_db.RegisterFileDescriptor(DESCRIPTOR) + + + +_INSTANCE_STATE = _descriptor.EnumDescriptor( + name='State', + full_name='google.spanner.admin.instance.v1.Instance.State', + filename=None, + file=DESCRIPTOR, + values=[ + _descriptor.EnumValueDescriptor( + name='STATE_UNSPECIFIED', index=0, number=0, + options=None, + type=None), + _descriptor.EnumValueDescriptor( + name='CREATING', index=1, number=1, + options=None, + type=None), + _descriptor.EnumValueDescriptor( + name='READY', index=2, number=2, + options=None, + type=None), + ], + containing_type=None, + options=None, + serialized_start=680, + serialized_end=735, +) +_sym_db.RegisterEnumDescriptor(_INSTANCE_STATE) + + +_INSTANCECONFIG = _descriptor.Descriptor( + name='InstanceConfig', + full_name='google.spanner.admin.instance.v1.InstanceConfig', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='name', full_name='google.spanner.admin.instance.v1.InstanceConfig.name', index=0, + number=1, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='display_name', full_name='google.spanner.admin.instance.v1.InstanceConfig.display_name', index=1, + number=2, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto3', + extension_ranges=[], + oneofs=[ + ], + serialized_start=357, + serialized_end=409, +) + + +_INSTANCE_LABELSENTRY = _descriptor.Descriptor( + name='LabelsEntry', + full_name='google.spanner.admin.instance.v1.Instance.LabelsEntry', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='key', full_name='google.spanner.admin.instance.v1.Instance.LabelsEntry.key', index=0, + number=1, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='value', full_name='google.spanner.admin.instance.v1.Instance.LabelsEntry.value', index=1, + number=2, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=_descriptor._ParseOptions(descriptor_pb2.MessageOptions(), _b('8\001')), + is_extendable=False, + syntax='proto3', + extension_ranges=[], + oneofs=[ + ], + serialized_start=633, + serialized_end=678, +) + +_INSTANCE = _descriptor.Descriptor( + name='Instance', + full_name='google.spanner.admin.instance.v1.Instance', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='name', full_name='google.spanner.admin.instance.v1.Instance.name', index=0, + number=1, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='config', full_name='google.spanner.admin.instance.v1.Instance.config', index=1, + number=2, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='display_name', full_name='google.spanner.admin.instance.v1.Instance.display_name', index=2, + number=3, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='node_count', full_name='google.spanner.admin.instance.v1.Instance.node_count', index=3, + number=5, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='state', full_name='google.spanner.admin.instance.v1.Instance.state', index=4, + number=6, type=14, cpp_type=8, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='labels', full_name='google.spanner.admin.instance.v1.Instance.labels', index=5, + number=7, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[_INSTANCE_LABELSENTRY, ], + enum_types=[ + _INSTANCE_STATE, + ], + options=None, + is_extendable=False, + syntax='proto3', + extension_ranges=[], + oneofs=[ + ], + serialized_start=412, + serialized_end=735, +) + + +_LISTINSTANCECONFIGSREQUEST = _descriptor.Descriptor( + name='ListInstanceConfigsRequest', + full_name='google.spanner.admin.instance.v1.ListInstanceConfigsRequest', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='parent', full_name='google.spanner.admin.instance.v1.ListInstanceConfigsRequest.parent', index=0, + number=1, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='page_size', full_name='google.spanner.admin.instance.v1.ListInstanceConfigsRequest.page_size', index=1, + number=2, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='page_token', full_name='google.spanner.admin.instance.v1.ListInstanceConfigsRequest.page_token', index=2, + number=3, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto3', + extension_ranges=[], + oneofs=[ + ], + serialized_start=737, + serialized_end=820, +) + + +_LISTINSTANCECONFIGSRESPONSE = _descriptor.Descriptor( + name='ListInstanceConfigsResponse', + full_name='google.spanner.admin.instance.v1.ListInstanceConfigsResponse', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='instance_configs', full_name='google.spanner.admin.instance.v1.ListInstanceConfigsResponse.instance_configs', index=0, + number=1, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='next_page_token', full_name='google.spanner.admin.instance.v1.ListInstanceConfigsResponse.next_page_token', index=1, + number=2, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto3', + extension_ranges=[], + oneofs=[ + ], + serialized_start=823, + serialized_end=953, +) + + +_GETINSTANCECONFIGREQUEST = _descriptor.Descriptor( + name='GetInstanceConfigRequest', + full_name='google.spanner.admin.instance.v1.GetInstanceConfigRequest', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='name', full_name='google.spanner.admin.instance.v1.GetInstanceConfigRequest.name', index=0, + number=1, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto3', + extension_ranges=[], + oneofs=[ + ], + serialized_start=955, + serialized_end=995, +) + + +_GETINSTANCEREQUEST = _descriptor.Descriptor( + name='GetInstanceRequest', + full_name='google.spanner.admin.instance.v1.GetInstanceRequest', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='name', full_name='google.spanner.admin.instance.v1.GetInstanceRequest.name', index=0, + number=1, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto3', + extension_ranges=[], + oneofs=[ + ], + serialized_start=997, + serialized_end=1031, +) + + +_CREATEINSTANCEREQUEST = _descriptor.Descriptor( + name='CreateInstanceRequest', + full_name='google.spanner.admin.instance.v1.CreateInstanceRequest', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='parent', full_name='google.spanner.admin.instance.v1.CreateInstanceRequest.parent', index=0, + number=1, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='instance_id', full_name='google.spanner.admin.instance.v1.CreateInstanceRequest.instance_id', index=1, + number=2, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='instance', full_name='google.spanner.admin.instance.v1.CreateInstanceRequest.instance', index=2, + number=3, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto3', + extension_ranges=[], + oneofs=[ + ], + serialized_start=1033, + serialized_end=1155, +) + + +_LISTINSTANCESREQUEST = _descriptor.Descriptor( + name='ListInstancesRequest', + full_name='google.spanner.admin.instance.v1.ListInstancesRequest', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='parent', full_name='google.spanner.admin.instance.v1.ListInstancesRequest.parent', index=0, + number=1, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='page_size', full_name='google.spanner.admin.instance.v1.ListInstancesRequest.page_size', index=1, + number=2, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='page_token', full_name='google.spanner.admin.instance.v1.ListInstancesRequest.page_token', index=2, + number=3, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='filter', full_name='google.spanner.admin.instance.v1.ListInstancesRequest.filter', index=3, + number=4, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto3', + extension_ranges=[], + oneofs=[ + ], + serialized_start=1157, + serialized_end=1250, +) + + +_LISTINSTANCESRESPONSE = _descriptor.Descriptor( + name='ListInstancesResponse', + full_name='google.spanner.admin.instance.v1.ListInstancesResponse', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='instances', full_name='google.spanner.admin.instance.v1.ListInstancesResponse.instances', index=0, + number=1, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='next_page_token', full_name='google.spanner.admin.instance.v1.ListInstancesResponse.next_page_token', index=1, + number=2, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto3', + extension_ranges=[], + oneofs=[ + ], + serialized_start=1252, + serialized_end=1363, +) + + +_UPDATEINSTANCEREQUEST = _descriptor.Descriptor( + name='UpdateInstanceRequest', + full_name='google.spanner.admin.instance.v1.UpdateInstanceRequest', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='instance', full_name='google.spanner.admin.instance.v1.UpdateInstanceRequest.instance', index=0, + number=1, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='field_mask', full_name='google.spanner.admin.instance.v1.UpdateInstanceRequest.field_mask', index=1, + number=2, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto3', + extension_ranges=[], + oneofs=[ + ], + serialized_start=1366, + serialized_end=1499, +) + + +_DELETEINSTANCEREQUEST = _descriptor.Descriptor( + name='DeleteInstanceRequest', + full_name='google.spanner.admin.instance.v1.DeleteInstanceRequest', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='name', full_name='google.spanner.admin.instance.v1.DeleteInstanceRequest.name', index=0, + number=1, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto3', + extension_ranges=[], + oneofs=[ + ], + serialized_start=1501, + serialized_end=1538, +) + + +_CREATEINSTANCEMETADATA = _descriptor.Descriptor( + name='CreateInstanceMetadata', + full_name='google.spanner.admin.instance.v1.CreateInstanceMetadata', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='instance', full_name='google.spanner.admin.instance.v1.CreateInstanceMetadata.instance', index=0, + number=1, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='start_time', full_name='google.spanner.admin.instance.v1.CreateInstanceMetadata.start_time', index=1, + number=2, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='cancel_time', full_name='google.spanner.admin.instance.v1.CreateInstanceMetadata.cancel_time', index=2, + number=3, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='end_time', full_name='google.spanner.admin.instance.v1.CreateInstanceMetadata.end_time', index=3, + number=4, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto3', + extension_ranges=[], + oneofs=[ + ], + serialized_start=1541, + serialized_end=1770, +) + + +_UPDATEINSTANCEMETADATA = _descriptor.Descriptor( + name='UpdateInstanceMetadata', + full_name='google.spanner.admin.instance.v1.UpdateInstanceMetadata', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='instance', full_name='google.spanner.admin.instance.v1.UpdateInstanceMetadata.instance', index=0, + number=1, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='start_time', full_name='google.spanner.admin.instance.v1.UpdateInstanceMetadata.start_time', index=1, + number=2, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='cancel_time', full_name='google.spanner.admin.instance.v1.UpdateInstanceMetadata.cancel_time', index=2, + number=3, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='end_time', full_name='google.spanner.admin.instance.v1.UpdateInstanceMetadata.end_time', index=3, + number=4, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto3', + extension_ranges=[], + oneofs=[ + ], + serialized_start=1773, + serialized_end=2002, +) + +_INSTANCE_LABELSENTRY.containing_type = _INSTANCE +_INSTANCE.fields_by_name['state'].enum_type = _INSTANCE_STATE +_INSTANCE.fields_by_name['labels'].message_type = _INSTANCE_LABELSENTRY +_INSTANCE_STATE.containing_type = _INSTANCE +_LISTINSTANCECONFIGSRESPONSE.fields_by_name['instance_configs'].message_type = _INSTANCECONFIG +_CREATEINSTANCEREQUEST.fields_by_name['instance'].message_type = _INSTANCE +_LISTINSTANCESRESPONSE.fields_by_name['instances'].message_type = _INSTANCE +_UPDATEINSTANCEREQUEST.fields_by_name['instance'].message_type = _INSTANCE +_UPDATEINSTANCEREQUEST.fields_by_name['field_mask'].message_type = google_dot_protobuf_dot_field__mask__pb2._FIELDMASK +_CREATEINSTANCEMETADATA.fields_by_name['instance'].message_type = _INSTANCE +_CREATEINSTANCEMETADATA.fields_by_name['start_time'].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP +_CREATEINSTANCEMETADATA.fields_by_name['cancel_time'].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP +_CREATEINSTANCEMETADATA.fields_by_name['end_time'].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP +_UPDATEINSTANCEMETADATA.fields_by_name['instance'].message_type = _INSTANCE +_UPDATEINSTANCEMETADATA.fields_by_name['start_time'].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP +_UPDATEINSTANCEMETADATA.fields_by_name['cancel_time'].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP +_UPDATEINSTANCEMETADATA.fields_by_name['end_time'].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP +DESCRIPTOR.message_types_by_name['InstanceConfig'] = _INSTANCECONFIG +DESCRIPTOR.message_types_by_name['Instance'] = _INSTANCE +DESCRIPTOR.message_types_by_name['ListInstanceConfigsRequest'] = _LISTINSTANCECONFIGSREQUEST +DESCRIPTOR.message_types_by_name['ListInstanceConfigsResponse'] = _LISTINSTANCECONFIGSRESPONSE +DESCRIPTOR.message_types_by_name['GetInstanceConfigRequest'] = _GETINSTANCECONFIGREQUEST +DESCRIPTOR.message_types_by_name['GetInstanceRequest'] = _GETINSTANCEREQUEST +DESCRIPTOR.message_types_by_name['CreateInstanceRequest'] = _CREATEINSTANCEREQUEST +DESCRIPTOR.message_types_by_name['ListInstancesRequest'] = _LISTINSTANCESREQUEST +DESCRIPTOR.message_types_by_name['ListInstancesResponse'] = _LISTINSTANCESRESPONSE +DESCRIPTOR.message_types_by_name['UpdateInstanceRequest'] = _UPDATEINSTANCEREQUEST +DESCRIPTOR.message_types_by_name['DeleteInstanceRequest'] = _DELETEINSTANCEREQUEST +DESCRIPTOR.message_types_by_name['CreateInstanceMetadata'] = _CREATEINSTANCEMETADATA +DESCRIPTOR.message_types_by_name['UpdateInstanceMetadata'] = _UPDATEINSTANCEMETADATA + +InstanceConfig = _reflection.GeneratedProtocolMessageType('InstanceConfig', (_message.Message,), dict( + DESCRIPTOR = _INSTANCECONFIG, + __module__ = 'google.cloud.spanner.admin.instance_v1.proto.spanner_instance_admin_pb2' + , + __doc__ = """A possible configuration for a Cloud Spanner instance. Configurations + define the geographic placement of nodes and their replication. + + + Attributes: + name: + A unique identifier for the instance configuration. Values are + of the form + ``projects//instanceConfigs/[a-z][-a-z0-9]*`` + display_name: + The name of this instance configuration as it appears in UIs. + """, + # @@protoc_insertion_point(class_scope:google.spanner.admin.instance.v1.InstanceConfig) + )) +_sym_db.RegisterMessage(InstanceConfig) + +Instance = _reflection.GeneratedProtocolMessageType('Instance', (_message.Message,), dict( + + LabelsEntry = _reflection.GeneratedProtocolMessageType('LabelsEntry', (_message.Message,), dict( + DESCRIPTOR = _INSTANCE_LABELSENTRY, + __module__ = 'google.cloud.spanner.admin.instance_v1.proto.spanner_instance_admin_pb2' + # @@protoc_insertion_point(class_scope:google.spanner.admin.instance.v1.Instance.LabelsEntry) + )) + , + DESCRIPTOR = _INSTANCE, + __module__ = 'google.cloud.spanner.admin.instance_v1.proto.spanner_instance_admin_pb2' + , + __doc__ = """An isolated set of Cloud Spanner resources on which databases can be + hosted. + + + Attributes: + name: + Required. A unique identifier for the instance, which cannot + be changed after the instance is created. Values are of the + form ``projects//instances/[a-z][-a-z0-9]*[a-z0-9]``. + The final segment of the name must be between 6 and 30 + characters in length. + config: + Required. The name of the instance's configuration. Values are + of the form + ``projects//instanceConfigs/``. See + also [InstanceConfig][google.spanner.admin.instance.v1.Instanc + eConfig] and [ListInstanceConfigs][google.spanner.admin.instan + ce.v1.InstanceAdmin.ListInstanceConfigs]. + display_name: + Required. The descriptive name for this instance as it appears + in UIs. Must be unique per project and between 4 and 30 + characters in length. + node_count: + Required. The number of nodes allocated to this instance. + state: + Output only. The current instance state. For [CreateInstance][ + google.spanner.admin.instance.v1.InstanceAdmin.CreateInstance] + , the state must be either omitted or set to ``CREATING``. For + [UpdateInstance][google.spanner.admin.instance.v1.InstanceAdmi + n.UpdateInstance], the state must be either omitted or set to + ``READY``. + labels: + Cloud Labels are a flexible and lightweight mechanism for + organizing cloud resources into groups that reflect a + customer's organizational needs and deployment strategies. + Cloud Labels can be used to filter collections of resources. + They can be used to control how resource metrics are + aggregated. And they can be used as arguments to policy + management rules (e.g. route, firewall, load balancing, etc.). + - Label keys must be between 1 and 63 characters long and + must conform to the following regular expression: + ``[a-z]([-a-z0-9]*[a-z0-9])?``. - Label values must be + between 0 and 63 characters long and must conform to the + regular expression ``([a-z]([-a-z0-9]*[a-z0-9])?)?``. - No + more than 64 labels can be associated with a given resource. + See https://goo.gl/xmQnxf for more information on and examples + of labels. If you plan to use labels in your own code, please + note that additional characters may be allowed in the future. + And so you are advised to use an internal label + representation, such as JSON, which doesn't rely upon specific + characters being disallowed. For example, representing labels + as the string: name + "*" + value would prove problematic if + we were to allow "*" in a future release. + """, + # @@protoc_insertion_point(class_scope:google.spanner.admin.instance.v1.Instance) + )) +_sym_db.RegisterMessage(Instance) +_sym_db.RegisterMessage(Instance.LabelsEntry) + +ListInstanceConfigsRequest = _reflection.GeneratedProtocolMessageType('ListInstanceConfigsRequest', (_message.Message,), dict( + DESCRIPTOR = _LISTINSTANCECONFIGSREQUEST, + __module__ = 'google.cloud.spanner.admin.instance_v1.proto.spanner_instance_admin_pb2' + , + __doc__ = """The request for + [ListInstanceConfigs][google.spanner.admin.instance.v1.InstanceAdmin.ListInstanceConfigs]. + + + Attributes: + parent: + Required. The name of the project for which a list of + supported instance configurations is requested. Values are of + the form ``projects/``. + page_size: + Number of instance configurations to be returned in the + response. If 0 or less, defaults to the server's maximum + allowed page size. + page_token: + If non-empty, ``page_token`` should contain a [next\_page\_tok + en][google.spanner.admin.instance.v1.ListInstanceConfigsRespon + se.next\_page\_token] from a previous [ListInstanceConfigsResp + onse][google.spanner.admin.instance.v1.ListInstanceConfigsResp + onse]. + """, + # @@protoc_insertion_point(class_scope:google.spanner.admin.instance.v1.ListInstanceConfigsRequest) + )) +_sym_db.RegisterMessage(ListInstanceConfigsRequest) + +ListInstanceConfigsResponse = _reflection.GeneratedProtocolMessageType('ListInstanceConfigsResponse', (_message.Message,), dict( + DESCRIPTOR = _LISTINSTANCECONFIGSRESPONSE, + __module__ = 'google.cloud.spanner.admin.instance_v1.proto.spanner_instance_admin_pb2' + , + __doc__ = """The response for + [ListInstanceConfigs][google.spanner.admin.instance.v1.InstanceAdmin.ListInstanceConfigs]. + + + Attributes: + instance_configs: + The list of requested instance configurations. + next_page_token: + ``next_page_token`` can be sent in a subsequent [ListInstanceC + onfigs][google.spanner.admin.instance.v1.InstanceAdmin.ListIns + tanceConfigs] call to fetch more of the matching instance + configurations. + """, + # @@protoc_insertion_point(class_scope:google.spanner.admin.instance.v1.ListInstanceConfigsResponse) + )) +_sym_db.RegisterMessage(ListInstanceConfigsResponse) + +GetInstanceConfigRequest = _reflection.GeneratedProtocolMessageType('GetInstanceConfigRequest', (_message.Message,), dict( + DESCRIPTOR = _GETINSTANCECONFIGREQUEST, + __module__ = 'google.cloud.spanner.admin.instance_v1.proto.spanner_instance_admin_pb2' + , + __doc__ = """The request for + [GetInstanceConfigRequest][google.spanner.admin.instance.v1.InstanceAdmin.GetInstanceConfig]. + + + Attributes: + name: + Required. The name of the requested instance configuration. + Values are of the form + ``projects//instanceConfigs/``. + """, + # @@protoc_insertion_point(class_scope:google.spanner.admin.instance.v1.GetInstanceConfigRequest) + )) +_sym_db.RegisterMessage(GetInstanceConfigRequest) + +GetInstanceRequest = _reflection.GeneratedProtocolMessageType('GetInstanceRequest', (_message.Message,), dict( + DESCRIPTOR = _GETINSTANCEREQUEST, + __module__ = 'google.cloud.spanner.admin.instance_v1.proto.spanner_instance_admin_pb2' + , + __doc__ = """The request for + [GetInstance][google.spanner.admin.instance.v1.InstanceAdmin.GetInstance]. + + + Attributes: + name: + Required. The name of the requested instance. Values are of + the form ``projects//instances/``. + """, + # @@protoc_insertion_point(class_scope:google.spanner.admin.instance.v1.GetInstanceRequest) + )) +_sym_db.RegisterMessage(GetInstanceRequest) + +CreateInstanceRequest = _reflection.GeneratedProtocolMessageType('CreateInstanceRequest', (_message.Message,), dict( + DESCRIPTOR = _CREATEINSTANCEREQUEST, + __module__ = 'google.cloud.spanner.admin.instance_v1.proto.spanner_instance_admin_pb2' + , + __doc__ = """The request for + [CreateInstance][google.spanner.admin.instance.v1.InstanceAdmin.CreateInstance]. + + + Attributes: + parent: + Required. The name of the project in which to create the + instance. Values are of the form ``projects/``. + instance_id: + Required. The ID of the instance to create. Valid identifiers + are of the form ``[a-z][-a-z0-9]*[a-z0-9]`` and must be + between 6 and 30 characters in length. + instance: + Required. The instance to create. The name may be omitted, but + if specified must be ``/instances/``. + """, + # @@protoc_insertion_point(class_scope:google.spanner.admin.instance.v1.CreateInstanceRequest) + )) +_sym_db.RegisterMessage(CreateInstanceRequest) + +ListInstancesRequest = _reflection.GeneratedProtocolMessageType('ListInstancesRequest', (_message.Message,), dict( + DESCRIPTOR = _LISTINSTANCESREQUEST, + __module__ = 'google.cloud.spanner.admin.instance_v1.proto.spanner_instance_admin_pb2' + , + __doc__ = """The request for + [ListInstances][google.spanner.admin.instance.v1.InstanceAdmin.ListInstances]. + + + Attributes: + parent: + Required. The name of the project for which a list of + instances is requested. Values are of the form + ``projects/``. + page_size: + Number of instances to be returned in the response. If 0 or + less, defaults to the server's maximum allowed page size. + page_token: + If non-empty, ``page_token`` should contain a [next\_page\_tok + en][google.spanner.admin.instance.v1.ListInstancesResponse.nex + t\_page\_token] from a previous [ListInstancesResponse][google + .spanner.admin.instance.v1.ListInstancesResponse]. + filter: + An expression for filtering the results of the request. Filter + rules are case insensitive. The fields eligible for filtering + are: - name - display\_name - labels.key where key is the + name of a label Some examples of using filters are: - + name:\* --> The instance has a name. - name:Howl --> The + instance's name contains the string "howl". - name:HOWL --> + Equivalent to above. - NAME:howl --> Equivalent to above. - + labels.env:\* --> The instance has the label "env". - + labels.env:dev --> The instance has the label "env" and the + value of the label contains the string "dev". - name:howl + labels.env:dev --> The instance's name contains "howl" and + it has the label "env" with its value containing "dev". + """, + # @@protoc_insertion_point(class_scope:google.spanner.admin.instance.v1.ListInstancesRequest) + )) +_sym_db.RegisterMessage(ListInstancesRequest) + +ListInstancesResponse = _reflection.GeneratedProtocolMessageType('ListInstancesResponse', (_message.Message,), dict( + DESCRIPTOR = _LISTINSTANCESRESPONSE, + __module__ = 'google.cloud.spanner.admin.instance_v1.proto.spanner_instance_admin_pb2' + , + __doc__ = """The response for + [ListInstances][google.spanner.admin.instance.v1.InstanceAdmin.ListInstances]. + + + Attributes: + instances: + The list of requested instances. + next_page_token: + ``next_page_token`` can be sent in a subsequent [ListInstances + ][google.spanner.admin.instance.v1.InstanceAdmin.ListInstances + ] call to fetch more of the matching instances. + """, + # @@protoc_insertion_point(class_scope:google.spanner.admin.instance.v1.ListInstancesResponse) + )) +_sym_db.RegisterMessage(ListInstancesResponse) + +UpdateInstanceRequest = _reflection.GeneratedProtocolMessageType('UpdateInstanceRequest', (_message.Message,), dict( + DESCRIPTOR = _UPDATEINSTANCEREQUEST, + __module__ = 'google.cloud.spanner.admin.instance_v1.proto.spanner_instance_admin_pb2' + , + __doc__ = """The request for + [UpdateInstance][google.spanner.admin.instance.v1.InstanceAdmin.UpdateInstance]. + + + Attributes: + instance: + Required. The instance to update, which must always include + the instance name. Otherwise, only fields mentioned in [][goog + le.spanner.admin.instance.v1.UpdateInstanceRequest.field\_mask + ] need be included. + field_mask: + Required. A mask specifying which fields in [][google.spanner. + admin.instance.v1.UpdateInstanceRequest.instance] should be + updated. The field mask must always be specified; this + prevents any future fields in + [][google.spanner.admin.instance.v1.Instance] from being + erased accidentally by clients that do not know about them. + """, + # @@protoc_insertion_point(class_scope:google.spanner.admin.instance.v1.UpdateInstanceRequest) + )) +_sym_db.RegisterMessage(UpdateInstanceRequest) + +DeleteInstanceRequest = _reflection.GeneratedProtocolMessageType('DeleteInstanceRequest', (_message.Message,), dict( + DESCRIPTOR = _DELETEINSTANCEREQUEST, + __module__ = 'google.cloud.spanner.admin.instance_v1.proto.spanner_instance_admin_pb2' + , + __doc__ = """The request for + [DeleteInstance][google.spanner.admin.instance.v1.InstanceAdmin.DeleteInstance]. + + + Attributes: + name: + Required. The name of the instance to be deleted. Values are + of the form ``projects//instances/`` + """, + # @@protoc_insertion_point(class_scope:google.spanner.admin.instance.v1.DeleteInstanceRequest) + )) +_sym_db.RegisterMessage(DeleteInstanceRequest) + +CreateInstanceMetadata = _reflection.GeneratedProtocolMessageType('CreateInstanceMetadata', (_message.Message,), dict( + DESCRIPTOR = _CREATEINSTANCEMETADATA, + __module__ = 'google.cloud.spanner.admin.instance_v1.proto.spanner_instance_admin_pb2' + , + __doc__ = """Metadata type for the operation returned by + [CreateInstance][google.spanner.admin.instance.v1.InstanceAdmin.CreateInstance]. + + + Attributes: + instance: + The instance being created. + start_time: + The time at which the [CreateInstance][google.spanner.admin.in + stance.v1.InstanceAdmin.CreateInstance] request was received. + cancel_time: + The time at which this operation was cancelled. If set, this + operation is in the process of undoing itself (which is + guaranteed to succeed) and cannot be cancelled again. + end_time: + The time at which this operation failed or was completed + successfully. + """, + # @@protoc_insertion_point(class_scope:google.spanner.admin.instance.v1.CreateInstanceMetadata) + )) +_sym_db.RegisterMessage(CreateInstanceMetadata) + +UpdateInstanceMetadata = _reflection.GeneratedProtocolMessageType('UpdateInstanceMetadata', (_message.Message,), dict( + DESCRIPTOR = _UPDATEINSTANCEMETADATA, + __module__ = 'google.cloud.spanner.admin.instance_v1.proto.spanner_instance_admin_pb2' + , + __doc__ = """Metadata type for the operation returned by + [UpdateInstance][google.spanner.admin.instance.v1.InstanceAdmin.UpdateInstance]. + + + Attributes: + instance: + The desired end state of the update. + start_time: + The time at which [UpdateInstance][google.spanner.admin.instan + ce.v1.InstanceAdmin.UpdateInstance] request was received. + cancel_time: + The time at which this operation was cancelled. If set, this + operation is in the process of undoing itself (which is + guaranteed to succeed) and cannot be cancelled again. + end_time: + The time at which this operation failed or was completed + successfully. + """, + # @@protoc_insertion_point(class_scope:google.spanner.admin.instance.v1.UpdateInstanceMetadata) + )) +_sym_db.RegisterMessage(UpdateInstanceMetadata) + + +DESCRIPTOR.has_options = True +DESCRIPTOR._options = _descriptor._ParseOptions(descriptor_pb2.FileOptions(), _b('\n$com.google.spanner.admin.instance.v1B\031SpannerInstanceAdminProtoP\001ZHgoogle.golang.org/genproto/googleapis/spanner/admin/instance/v1;instance\252\002&Google.Cloud.Spanner.Admin.Instance.V1')) +_INSTANCE_LABELSENTRY.has_options = True +_INSTANCE_LABELSENTRY._options = _descriptor._ParseOptions(descriptor_pb2.MessageOptions(), _b('8\001')) +try: + # THESE ELEMENTS WILL BE DEPRECATED. + # Please use the generated *_pb2_grpc.py files instead. + import grpc + from grpc.beta import implementations as beta_implementations + from grpc.beta import interfaces as beta_interfaces + from grpc.framework.common import cardinality + from grpc.framework.interfaces.face import utilities as face_utilities + + + class InstanceAdminStub(object): + """Cloud Spanner Instance Admin API + + The Cloud Spanner Instance Admin API can be used to create, delete, + modify and list instances. Instances are dedicated Cloud Spanner serving + and storage resources to be used by Cloud Spanner databases. + + Each instance has a "configuration", which dictates where the + serving resources for the Cloud Spanner instance are located (e.g., + US-central, Europe). Configurations are created by Google based on + resource availability. + + Cloud Spanner billing is based on the instances that exist and their + sizes. After an instance exists, there are no additional + per-database or per-operation charges for use of the instance + (though there may be additional network bandwidth charges). + Instances offer isolation: problems with databases in one instance + will not affect other instances. However, within an instance + databases can affect each other. For example, if one database in an + instance receives a lot of requests and consumes most of the + instance resources, fewer resources are available for other + databases in that instance, and their performance may suffer. + """ + + def __init__(self, channel): + """Constructor. + + Args: + channel: A grpc.Channel. + """ + self.ListInstanceConfigs = channel.unary_unary( + '/google.spanner.admin.instance.v1.InstanceAdmin/ListInstanceConfigs', + request_serializer=ListInstanceConfigsRequest.SerializeToString, + response_deserializer=ListInstanceConfigsResponse.FromString, + ) + self.GetInstanceConfig = channel.unary_unary( + '/google.spanner.admin.instance.v1.InstanceAdmin/GetInstanceConfig', + request_serializer=GetInstanceConfigRequest.SerializeToString, + response_deserializer=InstanceConfig.FromString, + ) + self.ListInstances = channel.unary_unary( + '/google.spanner.admin.instance.v1.InstanceAdmin/ListInstances', + request_serializer=ListInstancesRequest.SerializeToString, + response_deserializer=ListInstancesResponse.FromString, + ) + self.GetInstance = channel.unary_unary( + '/google.spanner.admin.instance.v1.InstanceAdmin/GetInstance', + request_serializer=GetInstanceRequest.SerializeToString, + response_deserializer=Instance.FromString, + ) + self.CreateInstance = channel.unary_unary( + '/google.spanner.admin.instance.v1.InstanceAdmin/CreateInstance', + request_serializer=CreateInstanceRequest.SerializeToString, + response_deserializer=google_dot_longrunning_dot_operations__pb2.Operation.FromString, + ) + self.UpdateInstance = channel.unary_unary( + '/google.spanner.admin.instance.v1.InstanceAdmin/UpdateInstance', + request_serializer=UpdateInstanceRequest.SerializeToString, + response_deserializer=google_dot_longrunning_dot_operations__pb2.Operation.FromString, + ) + self.DeleteInstance = channel.unary_unary( + '/google.spanner.admin.instance.v1.InstanceAdmin/DeleteInstance', + request_serializer=DeleteInstanceRequest.SerializeToString, + response_deserializer=google_dot_protobuf_dot_empty__pb2.Empty.FromString, + ) + self.SetIamPolicy = channel.unary_unary( + '/google.spanner.admin.instance.v1.InstanceAdmin/SetIamPolicy', + request_serializer=google_dot_iam_dot_v1_dot_iam__policy__pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=google_dot_iam_dot_v1_dot_policy__pb2.Policy.FromString, + ) + self.GetIamPolicy = channel.unary_unary( + '/google.spanner.admin.instance.v1.InstanceAdmin/GetIamPolicy', + request_serializer=google_dot_iam_dot_v1_dot_iam__policy__pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=google_dot_iam_dot_v1_dot_policy__pb2.Policy.FromString, + ) + self.TestIamPermissions = channel.unary_unary( + '/google.spanner.admin.instance.v1.InstanceAdmin/TestIamPermissions', + request_serializer=google_dot_iam_dot_v1_dot_iam__policy__pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=google_dot_iam_dot_v1_dot_iam__policy__pb2.TestIamPermissionsResponse.FromString, + ) + + + class InstanceAdminServicer(object): + """Cloud Spanner Instance Admin API + + The Cloud Spanner Instance Admin API can be used to create, delete, + modify and list instances. Instances are dedicated Cloud Spanner serving + and storage resources to be used by Cloud Spanner databases. + + Each instance has a "configuration", which dictates where the + serving resources for the Cloud Spanner instance are located (e.g., + US-central, Europe). Configurations are created by Google based on + resource availability. + + Cloud Spanner billing is based on the instances that exist and their + sizes. After an instance exists, there are no additional + per-database or per-operation charges for use of the instance + (though there may be additional network bandwidth charges). + Instances offer isolation: problems with databases in one instance + will not affect other instances. However, within an instance + databases can affect each other. For example, if one database in an + instance receives a lot of requests and consumes most of the + instance resources, fewer resources are available for other + databases in that instance, and their performance may suffer. + """ + + def ListInstanceConfigs(self, request, context): + """Lists the supported instance configurations for a given project. + """ + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + def GetInstanceConfig(self, request, context): + """Gets information about a particular instance configuration. + """ + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + def ListInstances(self, request, context): + """Lists all instances in the given project. + """ + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + def GetInstance(self, request, context): + """Gets information about a particular instance. + """ + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + def CreateInstance(self, request, context): + """Creates an instance and begins preparing it to begin serving. The + returned [long-running operation][google.longrunning.Operation] + can be used to track the progress of preparing the new + instance. The instance name is assigned by the caller. If the + named instance already exists, `CreateInstance` returns + `ALREADY_EXISTS`. + + Immediately upon completion of this request: + + * The instance is readable via the API, with all requested attributes + but no allocated resources. Its state is `CREATING`. + + Until completion of the returned operation: + + * Cancelling the operation renders the instance immediately unreadable + via the API. + * The instance can be deleted. + * All other attempts to modify the instance are rejected. + + Upon completion of the returned operation: + + * Billing for all successfully-allocated resources begins (some types + may have lower than the requested levels). + * Databases can be created in the instance. + * The instance's allocated resource levels are readable via the API. + * The instance's state becomes `READY`. + + The returned [long-running operation][google.longrunning.Operation] will + have a name of the format `/operations/` and + can be used to track creation of the instance. The + [metadata][google.longrunning.Operation.metadata] field type is + [CreateInstanceMetadata][google.spanner.admin.instance.v1.CreateInstanceMetadata]. + The [response][google.longrunning.Operation.response] field type is + [Instance][google.spanner.admin.instance.v1.Instance], if successful. + """ + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + def UpdateInstance(self, request, context): + """Updates an instance, and begins allocating or releasing resources + as requested. The returned [long-running + operation][google.longrunning.Operation] can be used to track the + progress of updating the instance. If the named instance does not + exist, returns `NOT_FOUND`. + + Immediately upon completion of this request: + + * For resource types for which a decrease in the instance's allocation + has been requested, billing is based on the newly-requested level. + + Until completion of the returned operation: + + * Cancelling the operation sets its metadata's + [cancel_time][google.spanner.admin.instance.v1.UpdateInstanceMetadata.cancel_time], and begins + restoring resources to their pre-request values. The operation + is guaranteed to succeed at undoing all resource changes, + after which point it terminates with a `CANCELLED` status. + * All other attempts to modify the instance are rejected. + * Reading the instance via the API continues to give the pre-request + resource levels. + + Upon completion of the returned operation: + + * Billing begins for all successfully-allocated resources (some types + may have lower than the requested levels). + * All newly-reserved resources are available for serving the instance's + tables. + * The instance's new resource levels are readable via the API. + + The returned [long-running operation][google.longrunning.Operation] will + have a name of the format `/operations/` and + can be used to track the instance modification. The + [metadata][google.longrunning.Operation.metadata] field type is + [UpdateInstanceMetadata][google.spanner.admin.instance.v1.UpdateInstanceMetadata]. + The [response][google.longrunning.Operation.response] field type is + [Instance][google.spanner.admin.instance.v1.Instance], if successful. + + Authorization requires `spanner.instances.update` permission on + resource [name][google.spanner.admin.instance.v1.Instance.name]. + """ + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + def DeleteInstance(self, request, context): + """Deletes an instance. + + Immediately upon completion of the request: + + * Billing ceases for all of the instance's reserved resources. + + Soon afterward: + + * The instance and *all of its databases* immediately and + irrevocably disappear from the API. All data in the databases + is permanently deleted. + """ + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + def SetIamPolicy(self, request, context): + """Sets the access control policy on an instance resource. Replaces any + existing policy. + + Authorization requires `spanner.instances.setIamPolicy` on + [resource][google.iam.v1.SetIamPolicyRequest.resource]. + """ + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + def GetIamPolicy(self, request, context): + """Gets the access control policy for an instance resource. Returns an empty + policy if an instance exists but does not have a policy set. + + Authorization requires `spanner.instances.getIamPolicy` on + [resource][google.iam.v1.GetIamPolicyRequest.resource]. + """ + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + def TestIamPermissions(self, request, context): + """Returns permissions that the caller has on the specified instance resource. + + Attempting this RPC on a non-existent Cloud Spanner instance resource will + result in a NOT_FOUND error if the user has `spanner.instances.list` + permission on the containing Google Cloud Project. Otherwise returns an + empty set of permissions. + """ + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + + def add_InstanceAdminServicer_to_server(servicer, server): + rpc_method_handlers = { + 'ListInstanceConfigs': grpc.unary_unary_rpc_method_handler( + servicer.ListInstanceConfigs, + request_deserializer=ListInstanceConfigsRequest.FromString, + response_serializer=ListInstanceConfigsResponse.SerializeToString, + ), + 'GetInstanceConfig': grpc.unary_unary_rpc_method_handler( + servicer.GetInstanceConfig, + request_deserializer=GetInstanceConfigRequest.FromString, + response_serializer=InstanceConfig.SerializeToString, + ), + 'ListInstances': grpc.unary_unary_rpc_method_handler( + servicer.ListInstances, + request_deserializer=ListInstancesRequest.FromString, + response_serializer=ListInstancesResponse.SerializeToString, + ), + 'GetInstance': grpc.unary_unary_rpc_method_handler( + servicer.GetInstance, + request_deserializer=GetInstanceRequest.FromString, + response_serializer=Instance.SerializeToString, + ), + 'CreateInstance': grpc.unary_unary_rpc_method_handler( + servicer.CreateInstance, + request_deserializer=CreateInstanceRequest.FromString, + response_serializer=google_dot_longrunning_dot_operations__pb2.Operation.SerializeToString, + ), + 'UpdateInstance': grpc.unary_unary_rpc_method_handler( + servicer.UpdateInstance, + request_deserializer=UpdateInstanceRequest.FromString, + response_serializer=google_dot_longrunning_dot_operations__pb2.Operation.SerializeToString, + ), + 'DeleteInstance': grpc.unary_unary_rpc_method_handler( + servicer.DeleteInstance, + request_deserializer=DeleteInstanceRequest.FromString, + response_serializer=google_dot_protobuf_dot_empty__pb2.Empty.SerializeToString, + ), + 'SetIamPolicy': grpc.unary_unary_rpc_method_handler( + servicer.SetIamPolicy, + request_deserializer=google_dot_iam_dot_v1_dot_iam__policy__pb2.SetIamPolicyRequest.FromString, + response_serializer=google_dot_iam_dot_v1_dot_policy__pb2.Policy.SerializeToString, + ), + 'GetIamPolicy': grpc.unary_unary_rpc_method_handler( + servicer.GetIamPolicy, + request_deserializer=google_dot_iam_dot_v1_dot_iam__policy__pb2.GetIamPolicyRequest.FromString, + response_serializer=google_dot_iam_dot_v1_dot_policy__pb2.Policy.SerializeToString, + ), + 'TestIamPermissions': grpc.unary_unary_rpc_method_handler( + servicer.TestIamPermissions, + request_deserializer=google_dot_iam_dot_v1_dot_iam__policy__pb2.TestIamPermissionsRequest.FromString, + response_serializer=google_dot_iam_dot_v1_dot_iam__policy__pb2.TestIamPermissionsResponse.SerializeToString, + ), + } + generic_handler = grpc.method_handlers_generic_handler( + 'google.spanner.admin.instance.v1.InstanceAdmin', rpc_method_handlers) + server.add_generic_rpc_handlers((generic_handler,)) + + + class BetaInstanceAdminServicer(object): + """The Beta API is deprecated for 0.15.0 and later. + + It is recommended to use the GA API (classes and functions in this + file not marked beta) for all further purposes. This class was generated + only to ease transition from grpcio<0.15.0 to grpcio>=0.15.0.""" + """Cloud Spanner Instance Admin API + + The Cloud Spanner Instance Admin API can be used to create, delete, + modify and list instances. Instances are dedicated Cloud Spanner serving + and storage resources to be used by Cloud Spanner databases. + + Each instance has a "configuration", which dictates where the + serving resources for the Cloud Spanner instance are located (e.g., + US-central, Europe). Configurations are created by Google based on + resource availability. + + Cloud Spanner billing is based on the instances that exist and their + sizes. After an instance exists, there are no additional + per-database or per-operation charges for use of the instance + (though there may be additional network bandwidth charges). + Instances offer isolation: problems with databases in one instance + will not affect other instances. However, within an instance + databases can affect each other. For example, if one database in an + instance receives a lot of requests and consumes most of the + instance resources, fewer resources are available for other + databases in that instance, and their performance may suffer. + """ + def ListInstanceConfigs(self, request, context): + """Lists the supported instance configurations for a given project. + """ + context.code(beta_interfaces.StatusCode.UNIMPLEMENTED) + def GetInstanceConfig(self, request, context): + """Gets information about a particular instance configuration. + """ + context.code(beta_interfaces.StatusCode.UNIMPLEMENTED) + def ListInstances(self, request, context): + """Lists all instances in the given project. + """ + context.code(beta_interfaces.StatusCode.UNIMPLEMENTED) + def GetInstance(self, request, context): + """Gets information about a particular instance. + """ + context.code(beta_interfaces.StatusCode.UNIMPLEMENTED) + def CreateInstance(self, request, context): + """Creates an instance and begins preparing it to begin serving. The + returned [long-running operation][google.longrunning.Operation] + can be used to track the progress of preparing the new + instance. The instance name is assigned by the caller. If the + named instance already exists, `CreateInstance` returns + `ALREADY_EXISTS`. + + Immediately upon completion of this request: + + * The instance is readable via the API, with all requested attributes + but no allocated resources. Its state is `CREATING`. + + Until completion of the returned operation: + + * Cancelling the operation renders the instance immediately unreadable + via the API. + * The instance can be deleted. + * All other attempts to modify the instance are rejected. + + Upon completion of the returned operation: + + * Billing for all successfully-allocated resources begins (some types + may have lower than the requested levels). + * Databases can be created in the instance. + * The instance's allocated resource levels are readable via the API. + * The instance's state becomes `READY`. + + The returned [long-running operation][google.longrunning.Operation] will + have a name of the format `/operations/` and + can be used to track creation of the instance. The + [metadata][google.longrunning.Operation.metadata] field type is + [CreateInstanceMetadata][google.spanner.admin.instance.v1.CreateInstanceMetadata]. + The [response][google.longrunning.Operation.response] field type is + [Instance][google.spanner.admin.instance.v1.Instance], if successful. + """ + context.code(beta_interfaces.StatusCode.UNIMPLEMENTED) + def UpdateInstance(self, request, context): + """Updates an instance, and begins allocating or releasing resources + as requested. The returned [long-running + operation][google.longrunning.Operation] can be used to track the + progress of updating the instance. If the named instance does not + exist, returns `NOT_FOUND`. + + Immediately upon completion of this request: + + * For resource types for which a decrease in the instance's allocation + has been requested, billing is based on the newly-requested level. + + Until completion of the returned operation: + + * Cancelling the operation sets its metadata's + [cancel_time][google.spanner.admin.instance.v1.UpdateInstanceMetadata.cancel_time], and begins + restoring resources to their pre-request values. The operation + is guaranteed to succeed at undoing all resource changes, + after which point it terminates with a `CANCELLED` status. + * All other attempts to modify the instance are rejected. + * Reading the instance via the API continues to give the pre-request + resource levels. + + Upon completion of the returned operation: + + * Billing begins for all successfully-allocated resources (some types + may have lower than the requested levels). + * All newly-reserved resources are available for serving the instance's + tables. + * The instance's new resource levels are readable via the API. + + The returned [long-running operation][google.longrunning.Operation] will + have a name of the format `/operations/` and + can be used to track the instance modification. The + [metadata][google.longrunning.Operation.metadata] field type is + [UpdateInstanceMetadata][google.spanner.admin.instance.v1.UpdateInstanceMetadata]. + The [response][google.longrunning.Operation.response] field type is + [Instance][google.spanner.admin.instance.v1.Instance], if successful. + + Authorization requires `spanner.instances.update` permission on + resource [name][google.spanner.admin.instance.v1.Instance.name]. + """ + context.code(beta_interfaces.StatusCode.UNIMPLEMENTED) + def DeleteInstance(self, request, context): + """Deletes an instance. + + Immediately upon completion of the request: + + * Billing ceases for all of the instance's reserved resources. + + Soon afterward: + + * The instance and *all of its databases* immediately and + irrevocably disappear from the API. All data in the databases + is permanently deleted. + """ + context.code(beta_interfaces.StatusCode.UNIMPLEMENTED) + def SetIamPolicy(self, request, context): + """Sets the access control policy on an instance resource. Replaces any + existing policy. + + Authorization requires `spanner.instances.setIamPolicy` on + [resource][google.iam.v1.SetIamPolicyRequest.resource]. + """ + context.code(beta_interfaces.StatusCode.UNIMPLEMENTED) + def GetIamPolicy(self, request, context): + """Gets the access control policy for an instance resource. Returns an empty + policy if an instance exists but does not have a policy set. + + Authorization requires `spanner.instances.getIamPolicy` on + [resource][google.iam.v1.GetIamPolicyRequest.resource]. + """ + context.code(beta_interfaces.StatusCode.UNIMPLEMENTED) + def TestIamPermissions(self, request, context): + """Returns permissions that the caller has on the specified instance resource. + + Attempting this RPC on a non-existent Cloud Spanner instance resource will + result in a NOT_FOUND error if the user has `spanner.instances.list` + permission on the containing Google Cloud Project. Otherwise returns an + empty set of permissions. + """ + context.code(beta_interfaces.StatusCode.UNIMPLEMENTED) + + + class BetaInstanceAdminStub(object): + """The Beta API is deprecated for 0.15.0 and later. + + It is recommended to use the GA API (classes and functions in this + file not marked beta) for all further purposes. This class was generated + only to ease transition from grpcio<0.15.0 to grpcio>=0.15.0.""" + """Cloud Spanner Instance Admin API + + The Cloud Spanner Instance Admin API can be used to create, delete, + modify and list instances. Instances are dedicated Cloud Spanner serving + and storage resources to be used by Cloud Spanner databases. + + Each instance has a "configuration", which dictates where the + serving resources for the Cloud Spanner instance are located (e.g., + US-central, Europe). Configurations are created by Google based on + resource availability. + + Cloud Spanner billing is based on the instances that exist and their + sizes. After an instance exists, there are no additional + per-database or per-operation charges for use of the instance + (though there may be additional network bandwidth charges). + Instances offer isolation: problems with databases in one instance + will not affect other instances. However, within an instance + databases can affect each other. For example, if one database in an + instance receives a lot of requests and consumes most of the + instance resources, fewer resources are available for other + databases in that instance, and their performance may suffer. + """ + def ListInstanceConfigs(self, request, timeout, metadata=None, with_call=False, protocol_options=None): + """Lists the supported instance configurations for a given project. + """ + raise NotImplementedError() + ListInstanceConfigs.future = None + def GetInstanceConfig(self, request, timeout, metadata=None, with_call=False, protocol_options=None): + """Gets information about a particular instance configuration. + """ + raise NotImplementedError() + GetInstanceConfig.future = None + def ListInstances(self, request, timeout, metadata=None, with_call=False, protocol_options=None): + """Lists all instances in the given project. + """ + raise NotImplementedError() + ListInstances.future = None + def GetInstance(self, request, timeout, metadata=None, with_call=False, protocol_options=None): + """Gets information about a particular instance. + """ + raise NotImplementedError() + GetInstance.future = None + def CreateInstance(self, request, timeout, metadata=None, with_call=False, protocol_options=None): + """Creates an instance and begins preparing it to begin serving. The + returned [long-running operation][google.longrunning.Operation] + can be used to track the progress of preparing the new + instance. The instance name is assigned by the caller. If the + named instance already exists, `CreateInstance` returns + `ALREADY_EXISTS`. + + Immediately upon completion of this request: + + * The instance is readable via the API, with all requested attributes + but no allocated resources. Its state is `CREATING`. + + Until completion of the returned operation: + + * Cancelling the operation renders the instance immediately unreadable + via the API. + * The instance can be deleted. + * All other attempts to modify the instance are rejected. + + Upon completion of the returned operation: + + * Billing for all successfully-allocated resources begins (some types + may have lower than the requested levels). + * Databases can be created in the instance. + * The instance's allocated resource levels are readable via the API. + * The instance's state becomes `READY`. + + The returned [long-running operation][google.longrunning.Operation] will + have a name of the format `/operations/` and + can be used to track creation of the instance. The + [metadata][google.longrunning.Operation.metadata] field type is + [CreateInstanceMetadata][google.spanner.admin.instance.v1.CreateInstanceMetadata]. + The [response][google.longrunning.Operation.response] field type is + [Instance][google.spanner.admin.instance.v1.Instance], if successful. + """ + raise NotImplementedError() + CreateInstance.future = None + def UpdateInstance(self, request, timeout, metadata=None, with_call=False, protocol_options=None): + """Updates an instance, and begins allocating or releasing resources + as requested. The returned [long-running + operation][google.longrunning.Operation] can be used to track the + progress of updating the instance. If the named instance does not + exist, returns `NOT_FOUND`. + + Immediately upon completion of this request: + + * For resource types for which a decrease in the instance's allocation + has been requested, billing is based on the newly-requested level. + + Until completion of the returned operation: + + * Cancelling the operation sets its metadata's + [cancel_time][google.spanner.admin.instance.v1.UpdateInstanceMetadata.cancel_time], and begins + restoring resources to their pre-request values. The operation + is guaranteed to succeed at undoing all resource changes, + after which point it terminates with a `CANCELLED` status. + * All other attempts to modify the instance are rejected. + * Reading the instance via the API continues to give the pre-request + resource levels. + + Upon completion of the returned operation: + + * Billing begins for all successfully-allocated resources (some types + may have lower than the requested levels). + * All newly-reserved resources are available for serving the instance's + tables. + * The instance's new resource levels are readable via the API. + + The returned [long-running operation][google.longrunning.Operation] will + have a name of the format `/operations/` and + can be used to track the instance modification. The + [metadata][google.longrunning.Operation.metadata] field type is + [UpdateInstanceMetadata][google.spanner.admin.instance.v1.UpdateInstanceMetadata]. + The [response][google.longrunning.Operation.response] field type is + [Instance][google.spanner.admin.instance.v1.Instance], if successful. + + Authorization requires `spanner.instances.update` permission on + resource [name][google.spanner.admin.instance.v1.Instance.name]. + """ + raise NotImplementedError() + UpdateInstance.future = None + def DeleteInstance(self, request, timeout, metadata=None, with_call=False, protocol_options=None): + """Deletes an instance. + + Immediately upon completion of the request: + + * Billing ceases for all of the instance's reserved resources. + + Soon afterward: + + * The instance and *all of its databases* immediately and + irrevocably disappear from the API. All data in the databases + is permanently deleted. + """ + raise NotImplementedError() + DeleteInstance.future = None + def SetIamPolicy(self, request, timeout, metadata=None, with_call=False, protocol_options=None): + """Sets the access control policy on an instance resource. Replaces any + existing policy. + + Authorization requires `spanner.instances.setIamPolicy` on + [resource][google.iam.v1.SetIamPolicyRequest.resource]. + """ + raise NotImplementedError() + SetIamPolicy.future = None + def GetIamPolicy(self, request, timeout, metadata=None, with_call=False, protocol_options=None): + """Gets the access control policy for an instance resource. Returns an empty + policy if an instance exists but does not have a policy set. + + Authorization requires `spanner.instances.getIamPolicy` on + [resource][google.iam.v1.GetIamPolicyRequest.resource]. + """ + raise NotImplementedError() + GetIamPolicy.future = None + def TestIamPermissions(self, request, timeout, metadata=None, with_call=False, protocol_options=None): + """Returns permissions that the caller has on the specified instance resource. + + Attempting this RPC on a non-existent Cloud Spanner instance resource will + result in a NOT_FOUND error if the user has `spanner.instances.list` + permission on the containing Google Cloud Project. Otherwise returns an + empty set of permissions. + """ + raise NotImplementedError() + TestIamPermissions.future = None + + + def beta_create_InstanceAdmin_server(servicer, pool=None, pool_size=None, default_timeout=None, maximum_timeout=None): + """The Beta API is deprecated for 0.15.0 and later. + + It is recommended to use the GA API (classes and functions in this + file not marked beta) for all further purposes. This function was + generated only to ease transition from grpcio<0.15.0 to grpcio>=0.15.0""" + request_deserializers = { + ('google.spanner.admin.instance.v1.InstanceAdmin', 'CreateInstance'): CreateInstanceRequest.FromString, + ('google.spanner.admin.instance.v1.InstanceAdmin', 'DeleteInstance'): DeleteInstanceRequest.FromString, + ('google.spanner.admin.instance.v1.InstanceAdmin', 'GetIamPolicy'): google_dot_iam_dot_v1_dot_iam__policy__pb2.GetIamPolicyRequest.FromString, + ('google.spanner.admin.instance.v1.InstanceAdmin', 'GetInstance'): GetInstanceRequest.FromString, + ('google.spanner.admin.instance.v1.InstanceAdmin', 'GetInstanceConfig'): GetInstanceConfigRequest.FromString, + ('google.spanner.admin.instance.v1.InstanceAdmin', 'ListInstanceConfigs'): ListInstanceConfigsRequest.FromString, + ('google.spanner.admin.instance.v1.InstanceAdmin', 'ListInstances'): ListInstancesRequest.FromString, + ('google.spanner.admin.instance.v1.InstanceAdmin', 'SetIamPolicy'): google_dot_iam_dot_v1_dot_iam__policy__pb2.SetIamPolicyRequest.FromString, + ('google.spanner.admin.instance.v1.InstanceAdmin', 'TestIamPermissions'): google_dot_iam_dot_v1_dot_iam__policy__pb2.TestIamPermissionsRequest.FromString, + ('google.spanner.admin.instance.v1.InstanceAdmin', 'UpdateInstance'): UpdateInstanceRequest.FromString, + } + response_serializers = { + ('google.spanner.admin.instance.v1.InstanceAdmin', 'CreateInstance'): google_dot_longrunning_dot_operations__pb2.Operation.SerializeToString, + ('google.spanner.admin.instance.v1.InstanceAdmin', 'DeleteInstance'): google_dot_protobuf_dot_empty__pb2.Empty.SerializeToString, + ('google.spanner.admin.instance.v1.InstanceAdmin', 'GetIamPolicy'): google_dot_iam_dot_v1_dot_policy__pb2.Policy.SerializeToString, + ('google.spanner.admin.instance.v1.InstanceAdmin', 'GetInstance'): Instance.SerializeToString, + ('google.spanner.admin.instance.v1.InstanceAdmin', 'GetInstanceConfig'): InstanceConfig.SerializeToString, + ('google.spanner.admin.instance.v1.InstanceAdmin', 'ListInstanceConfigs'): ListInstanceConfigsResponse.SerializeToString, + ('google.spanner.admin.instance.v1.InstanceAdmin', 'ListInstances'): ListInstancesResponse.SerializeToString, + ('google.spanner.admin.instance.v1.InstanceAdmin', 'SetIamPolicy'): google_dot_iam_dot_v1_dot_policy__pb2.Policy.SerializeToString, + ('google.spanner.admin.instance.v1.InstanceAdmin', 'TestIamPermissions'): google_dot_iam_dot_v1_dot_iam__policy__pb2.TestIamPermissionsResponse.SerializeToString, + ('google.spanner.admin.instance.v1.InstanceAdmin', 'UpdateInstance'): google_dot_longrunning_dot_operations__pb2.Operation.SerializeToString, + } + method_implementations = { + ('google.spanner.admin.instance.v1.InstanceAdmin', 'CreateInstance'): face_utilities.unary_unary_inline(servicer.CreateInstance), + ('google.spanner.admin.instance.v1.InstanceAdmin', 'DeleteInstance'): face_utilities.unary_unary_inline(servicer.DeleteInstance), + ('google.spanner.admin.instance.v1.InstanceAdmin', 'GetIamPolicy'): face_utilities.unary_unary_inline(servicer.GetIamPolicy), + ('google.spanner.admin.instance.v1.InstanceAdmin', 'GetInstance'): face_utilities.unary_unary_inline(servicer.GetInstance), + ('google.spanner.admin.instance.v1.InstanceAdmin', 'GetInstanceConfig'): face_utilities.unary_unary_inline(servicer.GetInstanceConfig), + ('google.spanner.admin.instance.v1.InstanceAdmin', 'ListInstanceConfigs'): face_utilities.unary_unary_inline(servicer.ListInstanceConfigs), + ('google.spanner.admin.instance.v1.InstanceAdmin', 'ListInstances'): face_utilities.unary_unary_inline(servicer.ListInstances), + ('google.spanner.admin.instance.v1.InstanceAdmin', 'SetIamPolicy'): face_utilities.unary_unary_inline(servicer.SetIamPolicy), + ('google.spanner.admin.instance.v1.InstanceAdmin', 'TestIamPermissions'): face_utilities.unary_unary_inline(servicer.TestIamPermissions), + ('google.spanner.admin.instance.v1.InstanceAdmin', 'UpdateInstance'): face_utilities.unary_unary_inline(servicer.UpdateInstance), + } + server_options = beta_implementations.server_options(request_deserializers=request_deserializers, response_serializers=response_serializers, thread_pool=pool, thread_pool_size=pool_size, default_timeout=default_timeout, maximum_timeout=maximum_timeout) + return beta_implementations.server(method_implementations, options=server_options) + + + def beta_create_InstanceAdmin_stub(channel, host=None, metadata_transformer=None, pool=None, pool_size=None): + """The Beta API is deprecated for 0.15.0 and later. + + It is recommended to use the GA API (classes and functions in this + file not marked beta) for all further purposes. This function was + generated only to ease transition from grpcio<0.15.0 to grpcio>=0.15.0""" + request_serializers = { + ('google.spanner.admin.instance.v1.InstanceAdmin', 'CreateInstance'): CreateInstanceRequest.SerializeToString, + ('google.spanner.admin.instance.v1.InstanceAdmin', 'DeleteInstance'): DeleteInstanceRequest.SerializeToString, + ('google.spanner.admin.instance.v1.InstanceAdmin', 'GetIamPolicy'): google_dot_iam_dot_v1_dot_iam__policy__pb2.GetIamPolicyRequest.SerializeToString, + ('google.spanner.admin.instance.v1.InstanceAdmin', 'GetInstance'): GetInstanceRequest.SerializeToString, + ('google.spanner.admin.instance.v1.InstanceAdmin', 'GetInstanceConfig'): GetInstanceConfigRequest.SerializeToString, + ('google.spanner.admin.instance.v1.InstanceAdmin', 'ListInstanceConfigs'): ListInstanceConfigsRequest.SerializeToString, + ('google.spanner.admin.instance.v1.InstanceAdmin', 'ListInstances'): ListInstancesRequest.SerializeToString, + ('google.spanner.admin.instance.v1.InstanceAdmin', 'SetIamPolicy'): google_dot_iam_dot_v1_dot_iam__policy__pb2.SetIamPolicyRequest.SerializeToString, + ('google.spanner.admin.instance.v1.InstanceAdmin', 'TestIamPermissions'): google_dot_iam_dot_v1_dot_iam__policy__pb2.TestIamPermissionsRequest.SerializeToString, + ('google.spanner.admin.instance.v1.InstanceAdmin', 'UpdateInstance'): UpdateInstanceRequest.SerializeToString, + } + response_deserializers = { + ('google.spanner.admin.instance.v1.InstanceAdmin', 'CreateInstance'): google_dot_longrunning_dot_operations__pb2.Operation.FromString, + ('google.spanner.admin.instance.v1.InstanceAdmin', 'DeleteInstance'): google_dot_protobuf_dot_empty__pb2.Empty.FromString, + ('google.spanner.admin.instance.v1.InstanceAdmin', 'GetIamPolicy'): google_dot_iam_dot_v1_dot_policy__pb2.Policy.FromString, + ('google.spanner.admin.instance.v1.InstanceAdmin', 'GetInstance'): Instance.FromString, + ('google.spanner.admin.instance.v1.InstanceAdmin', 'GetInstanceConfig'): InstanceConfig.FromString, + ('google.spanner.admin.instance.v1.InstanceAdmin', 'ListInstanceConfigs'): ListInstanceConfigsResponse.FromString, + ('google.spanner.admin.instance.v1.InstanceAdmin', 'ListInstances'): ListInstancesResponse.FromString, + ('google.spanner.admin.instance.v1.InstanceAdmin', 'SetIamPolicy'): google_dot_iam_dot_v1_dot_policy__pb2.Policy.FromString, + ('google.spanner.admin.instance.v1.InstanceAdmin', 'TestIamPermissions'): google_dot_iam_dot_v1_dot_iam__policy__pb2.TestIamPermissionsResponse.FromString, + ('google.spanner.admin.instance.v1.InstanceAdmin', 'UpdateInstance'): google_dot_longrunning_dot_operations__pb2.Operation.FromString, + } + cardinalities = { + 'CreateInstance': cardinality.Cardinality.UNARY_UNARY, + 'DeleteInstance': cardinality.Cardinality.UNARY_UNARY, + 'GetIamPolicy': cardinality.Cardinality.UNARY_UNARY, + 'GetInstance': cardinality.Cardinality.UNARY_UNARY, + 'GetInstanceConfig': cardinality.Cardinality.UNARY_UNARY, + 'ListInstanceConfigs': cardinality.Cardinality.UNARY_UNARY, + 'ListInstances': cardinality.Cardinality.UNARY_UNARY, + 'SetIamPolicy': cardinality.Cardinality.UNARY_UNARY, + 'TestIamPermissions': cardinality.Cardinality.UNARY_UNARY, + 'UpdateInstance': cardinality.Cardinality.UNARY_UNARY, + } + stub_options = beta_implementations.stub_options(host=host, metadata_transformer=metadata_transformer, request_serializers=request_serializers, response_deserializers=response_deserializers, thread_pool=pool, thread_pool_size=pool_size) + return beta_implementations.dynamic_stub(channel, 'google.spanner.admin.instance.v1.InstanceAdmin', cardinalities, options=stub_options) +except ImportError: + pass +# @@protoc_insertion_point(module_scope) diff --git a/spanner/google/cloud/spanner_admin_instance_v1/proto/spanner_instance_admin_pb2_grpc.py b/spanner/google/cloud/spanner_admin_instance_v1/proto/spanner_instance_admin_pb2_grpc.py new file mode 100644 index 000000000000..5c98eb40642a --- /dev/null +++ b/spanner/google/cloud/spanner_admin_instance_v1/proto/spanner_instance_admin_pb2_grpc.py @@ -0,0 +1,338 @@ +# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! +import grpc + +import google.cloud.spanner.admin.instance_v1.proto.spanner_instance_admin_pb2 as google_dot_cloud_dot_spanner_dot_admin_dot_instance__v1_dot_proto_dot_spanner__instance__admin__pb2 +import google.iam.v1.iam_policy_pb2 as google_dot_iam_dot_v1_dot_iam__policy__pb2 +import google.iam.v1.policy_pb2 as google_dot_iam_dot_v1_dot_policy__pb2 +import google.longrunning.operations_pb2 as google_dot_longrunning_dot_operations__pb2 +import google.protobuf.empty_pb2 as google_dot_protobuf_dot_empty__pb2 + + +class InstanceAdminStub(object): + """Cloud Spanner Instance Admin API + + The Cloud Spanner Instance Admin API can be used to create, delete, + modify and list instances. Instances are dedicated Cloud Spanner serving + and storage resources to be used by Cloud Spanner databases. + + Each instance has a "configuration", which dictates where the + serving resources for the Cloud Spanner instance are located (e.g., + US-central, Europe). Configurations are created by Google based on + resource availability. + + Cloud Spanner billing is based on the instances that exist and their + sizes. After an instance exists, there are no additional + per-database or per-operation charges for use of the instance + (though there may be additional network bandwidth charges). + Instances offer isolation: problems with databases in one instance + will not affect other instances. However, within an instance + databases can affect each other. For example, if one database in an + instance receives a lot of requests and consumes most of the + instance resources, fewer resources are available for other + databases in that instance, and their performance may suffer. + """ + + def __init__(self, channel): + """Constructor. + + Args: + channel: A grpc.Channel. + """ + self.ListInstanceConfigs = channel.unary_unary( + '/google.spanner.admin.instance.v1.InstanceAdmin/ListInstanceConfigs', + request_serializer=google_dot_cloud_dot_spanner_dot_admin_dot_instance__v1_dot_proto_dot_spanner__instance__admin__pb2.ListInstanceConfigsRequest.SerializeToString, + response_deserializer=google_dot_cloud_dot_spanner_dot_admin_dot_instance__v1_dot_proto_dot_spanner__instance__admin__pb2.ListInstanceConfigsResponse.FromString, + ) + self.GetInstanceConfig = channel.unary_unary( + '/google.spanner.admin.instance.v1.InstanceAdmin/GetInstanceConfig', + request_serializer=google_dot_cloud_dot_spanner_dot_admin_dot_instance__v1_dot_proto_dot_spanner__instance__admin__pb2.GetInstanceConfigRequest.SerializeToString, + response_deserializer=google_dot_cloud_dot_spanner_dot_admin_dot_instance__v1_dot_proto_dot_spanner__instance__admin__pb2.InstanceConfig.FromString, + ) + self.ListInstances = channel.unary_unary( + '/google.spanner.admin.instance.v1.InstanceAdmin/ListInstances', + request_serializer=google_dot_cloud_dot_spanner_dot_admin_dot_instance__v1_dot_proto_dot_spanner__instance__admin__pb2.ListInstancesRequest.SerializeToString, + response_deserializer=google_dot_cloud_dot_spanner_dot_admin_dot_instance__v1_dot_proto_dot_spanner__instance__admin__pb2.ListInstancesResponse.FromString, + ) + self.GetInstance = channel.unary_unary( + '/google.spanner.admin.instance.v1.InstanceAdmin/GetInstance', + request_serializer=google_dot_cloud_dot_spanner_dot_admin_dot_instance__v1_dot_proto_dot_spanner__instance__admin__pb2.GetInstanceRequest.SerializeToString, + response_deserializer=google_dot_cloud_dot_spanner_dot_admin_dot_instance__v1_dot_proto_dot_spanner__instance__admin__pb2.Instance.FromString, + ) + self.CreateInstance = channel.unary_unary( + '/google.spanner.admin.instance.v1.InstanceAdmin/CreateInstance', + request_serializer=google_dot_cloud_dot_spanner_dot_admin_dot_instance__v1_dot_proto_dot_spanner__instance__admin__pb2.CreateInstanceRequest.SerializeToString, + response_deserializer=google_dot_longrunning_dot_operations__pb2.Operation.FromString, + ) + self.UpdateInstance = channel.unary_unary( + '/google.spanner.admin.instance.v1.InstanceAdmin/UpdateInstance', + request_serializer=google_dot_cloud_dot_spanner_dot_admin_dot_instance__v1_dot_proto_dot_spanner__instance__admin__pb2.UpdateInstanceRequest.SerializeToString, + response_deserializer=google_dot_longrunning_dot_operations__pb2.Operation.FromString, + ) + self.DeleteInstance = channel.unary_unary( + '/google.spanner.admin.instance.v1.InstanceAdmin/DeleteInstance', + request_serializer=google_dot_cloud_dot_spanner_dot_admin_dot_instance__v1_dot_proto_dot_spanner__instance__admin__pb2.DeleteInstanceRequest.SerializeToString, + response_deserializer=google_dot_protobuf_dot_empty__pb2.Empty.FromString, + ) + self.SetIamPolicy = channel.unary_unary( + '/google.spanner.admin.instance.v1.InstanceAdmin/SetIamPolicy', + request_serializer=google_dot_iam_dot_v1_dot_iam__policy__pb2.SetIamPolicyRequest.SerializeToString, + response_deserializer=google_dot_iam_dot_v1_dot_policy__pb2.Policy.FromString, + ) + self.GetIamPolicy = channel.unary_unary( + '/google.spanner.admin.instance.v1.InstanceAdmin/GetIamPolicy', + request_serializer=google_dot_iam_dot_v1_dot_iam__policy__pb2.GetIamPolicyRequest.SerializeToString, + response_deserializer=google_dot_iam_dot_v1_dot_policy__pb2.Policy.FromString, + ) + self.TestIamPermissions = channel.unary_unary( + '/google.spanner.admin.instance.v1.InstanceAdmin/TestIamPermissions', + request_serializer=google_dot_iam_dot_v1_dot_iam__policy__pb2.TestIamPermissionsRequest.SerializeToString, + response_deserializer=google_dot_iam_dot_v1_dot_iam__policy__pb2.TestIamPermissionsResponse.FromString, + ) + + +class InstanceAdminServicer(object): + """Cloud Spanner Instance Admin API + + The Cloud Spanner Instance Admin API can be used to create, delete, + modify and list instances. Instances are dedicated Cloud Spanner serving + and storage resources to be used by Cloud Spanner databases. + + Each instance has a "configuration", which dictates where the + serving resources for the Cloud Spanner instance are located (e.g., + US-central, Europe). Configurations are created by Google based on + resource availability. + + Cloud Spanner billing is based on the instances that exist and their + sizes. After an instance exists, there are no additional + per-database or per-operation charges for use of the instance + (though there may be additional network bandwidth charges). + Instances offer isolation: problems with databases in one instance + will not affect other instances. However, within an instance + databases can affect each other. For example, if one database in an + instance receives a lot of requests and consumes most of the + instance resources, fewer resources are available for other + databases in that instance, and their performance may suffer. + """ + + def ListInstanceConfigs(self, request, context): + """Lists the supported instance configurations for a given project. + """ + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + def GetInstanceConfig(self, request, context): + """Gets information about a particular instance configuration. + """ + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + def ListInstances(self, request, context): + """Lists all instances in the given project. + """ + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + def GetInstance(self, request, context): + """Gets information about a particular instance. + """ + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + def CreateInstance(self, request, context): + """Creates an instance and begins preparing it to begin serving. The + returned [long-running operation][google.longrunning.Operation] + can be used to track the progress of preparing the new + instance. The instance name is assigned by the caller. If the + named instance already exists, `CreateInstance` returns + `ALREADY_EXISTS`. + + Immediately upon completion of this request: + + * The instance is readable via the API, with all requested attributes + but no allocated resources. Its state is `CREATING`. + + Until completion of the returned operation: + + * Cancelling the operation renders the instance immediately unreadable + via the API. + * The instance can be deleted. + * All other attempts to modify the instance are rejected. + + Upon completion of the returned operation: + + * Billing for all successfully-allocated resources begins (some types + may have lower than the requested levels). + * Databases can be created in the instance. + * The instance's allocated resource levels are readable via the API. + * The instance's state becomes `READY`. + + The returned [long-running operation][google.longrunning.Operation] will + have a name of the format `/operations/` and + can be used to track creation of the instance. The + [metadata][google.longrunning.Operation.metadata] field type is + [CreateInstanceMetadata][google.spanner.admin.instance.v1.CreateInstanceMetadata]. + The [response][google.longrunning.Operation.response] field type is + [Instance][google.spanner.admin.instance.v1.Instance], if successful. + """ + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + def UpdateInstance(self, request, context): + """Updates an instance, and begins allocating or releasing resources + as requested. The returned [long-running + operation][google.longrunning.Operation] can be used to track the + progress of updating the instance. If the named instance does not + exist, returns `NOT_FOUND`. + + Immediately upon completion of this request: + + * For resource types for which a decrease in the instance's allocation + has been requested, billing is based on the newly-requested level. + + Until completion of the returned operation: + + * Cancelling the operation sets its metadata's + [cancel_time][google.spanner.admin.instance.v1.UpdateInstanceMetadata.cancel_time], and begins + restoring resources to their pre-request values. The operation + is guaranteed to succeed at undoing all resource changes, + after which point it terminates with a `CANCELLED` status. + * All other attempts to modify the instance are rejected. + * Reading the instance via the API continues to give the pre-request + resource levels. + + Upon completion of the returned operation: + + * Billing begins for all successfully-allocated resources (some types + may have lower than the requested levels). + * All newly-reserved resources are available for serving the instance's + tables. + * The instance's new resource levels are readable via the API. + + The returned [long-running operation][google.longrunning.Operation] will + have a name of the format `/operations/` and + can be used to track the instance modification. The + [metadata][google.longrunning.Operation.metadata] field type is + [UpdateInstanceMetadata][google.spanner.admin.instance.v1.UpdateInstanceMetadata]. + The [response][google.longrunning.Operation.response] field type is + [Instance][google.spanner.admin.instance.v1.Instance], if successful. + + Authorization requires `spanner.instances.update` permission on + resource [name][google.spanner.admin.instance.v1.Instance.name]. + """ + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + def DeleteInstance(self, request, context): + """Deletes an instance. + + Immediately upon completion of the request: + + * Billing ceases for all of the instance's reserved resources. + + Soon afterward: + + * The instance and *all of its databases* immediately and + irrevocably disappear from the API. All data in the databases + is permanently deleted. + """ + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + def SetIamPolicy(self, request, context): + """Sets the access control policy on an instance resource. Replaces any + existing policy. + + Authorization requires `spanner.instances.setIamPolicy` on + [resource][google.iam.v1.SetIamPolicyRequest.resource]. + """ + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + def GetIamPolicy(self, request, context): + """Gets the access control policy for an instance resource. Returns an empty + policy if an instance exists but does not have a policy set. + + Authorization requires `spanner.instances.getIamPolicy` on + [resource][google.iam.v1.GetIamPolicyRequest.resource]. + """ + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + def TestIamPermissions(self, request, context): + """Returns permissions that the caller has on the specified instance resource. + + Attempting this RPC on a non-existent Cloud Spanner instance resource will + result in a NOT_FOUND error if the user has `spanner.instances.list` + permission on the containing Google Cloud Project. Otherwise returns an + empty set of permissions. + """ + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + +def add_InstanceAdminServicer_to_server(servicer, server): + rpc_method_handlers = { + 'ListInstanceConfigs': grpc.unary_unary_rpc_method_handler( + servicer.ListInstanceConfigs, + request_deserializer=google_dot_cloud_dot_spanner_dot_admin_dot_instance__v1_dot_proto_dot_spanner__instance__admin__pb2.ListInstanceConfigsRequest.FromString, + response_serializer=google_dot_cloud_dot_spanner_dot_admin_dot_instance__v1_dot_proto_dot_spanner__instance__admin__pb2.ListInstanceConfigsResponse.SerializeToString, + ), + 'GetInstanceConfig': grpc.unary_unary_rpc_method_handler( + servicer.GetInstanceConfig, + request_deserializer=google_dot_cloud_dot_spanner_dot_admin_dot_instance__v1_dot_proto_dot_spanner__instance__admin__pb2.GetInstanceConfigRequest.FromString, + response_serializer=google_dot_cloud_dot_spanner_dot_admin_dot_instance__v1_dot_proto_dot_spanner__instance__admin__pb2.InstanceConfig.SerializeToString, + ), + 'ListInstances': grpc.unary_unary_rpc_method_handler( + servicer.ListInstances, + request_deserializer=google_dot_cloud_dot_spanner_dot_admin_dot_instance__v1_dot_proto_dot_spanner__instance__admin__pb2.ListInstancesRequest.FromString, + response_serializer=google_dot_cloud_dot_spanner_dot_admin_dot_instance__v1_dot_proto_dot_spanner__instance__admin__pb2.ListInstancesResponse.SerializeToString, + ), + 'GetInstance': grpc.unary_unary_rpc_method_handler( + servicer.GetInstance, + request_deserializer=google_dot_cloud_dot_spanner_dot_admin_dot_instance__v1_dot_proto_dot_spanner__instance__admin__pb2.GetInstanceRequest.FromString, + response_serializer=google_dot_cloud_dot_spanner_dot_admin_dot_instance__v1_dot_proto_dot_spanner__instance__admin__pb2.Instance.SerializeToString, + ), + 'CreateInstance': grpc.unary_unary_rpc_method_handler( + servicer.CreateInstance, + request_deserializer=google_dot_cloud_dot_spanner_dot_admin_dot_instance__v1_dot_proto_dot_spanner__instance__admin__pb2.CreateInstanceRequest.FromString, + response_serializer=google_dot_longrunning_dot_operations__pb2.Operation.SerializeToString, + ), + 'UpdateInstance': grpc.unary_unary_rpc_method_handler( + servicer.UpdateInstance, + request_deserializer=google_dot_cloud_dot_spanner_dot_admin_dot_instance__v1_dot_proto_dot_spanner__instance__admin__pb2.UpdateInstanceRequest.FromString, + response_serializer=google_dot_longrunning_dot_operations__pb2.Operation.SerializeToString, + ), + 'DeleteInstance': grpc.unary_unary_rpc_method_handler( + servicer.DeleteInstance, + request_deserializer=google_dot_cloud_dot_spanner_dot_admin_dot_instance__v1_dot_proto_dot_spanner__instance__admin__pb2.DeleteInstanceRequest.FromString, + response_serializer=google_dot_protobuf_dot_empty__pb2.Empty.SerializeToString, + ), + 'SetIamPolicy': grpc.unary_unary_rpc_method_handler( + servicer.SetIamPolicy, + request_deserializer=google_dot_iam_dot_v1_dot_iam__policy__pb2.SetIamPolicyRequest.FromString, + response_serializer=google_dot_iam_dot_v1_dot_policy__pb2.Policy.SerializeToString, + ), + 'GetIamPolicy': grpc.unary_unary_rpc_method_handler( + servicer.GetIamPolicy, + request_deserializer=google_dot_iam_dot_v1_dot_iam__policy__pb2.GetIamPolicyRequest.FromString, + response_serializer=google_dot_iam_dot_v1_dot_policy__pb2.Policy.SerializeToString, + ), + 'TestIamPermissions': grpc.unary_unary_rpc_method_handler( + servicer.TestIamPermissions, + request_deserializer=google_dot_iam_dot_v1_dot_iam__policy__pb2.TestIamPermissionsRequest.FromString, + response_serializer=google_dot_iam_dot_v1_dot_iam__policy__pb2.TestIamPermissionsResponse.SerializeToString, + ), + } + generic_handler = grpc.method_handlers_generic_handler( + 'google.spanner.admin.instance.v1.InstanceAdmin', rpc_method_handlers) + server.add_generic_rpc_handlers((generic_handler,)) diff --git a/spanner/google/cloud/spanner_admin_instance_v1/types.py b/spanner/google/cloud/spanner_admin_instance_v1/types.py new file mode 100644 index 000000000000..3fff0dc54301 --- /dev/null +++ b/spanner/google/cloud/spanner_admin_instance_v1/types.py @@ -0,0 +1,54 @@ +# Copyright 2017, Google Inc. All rights reserved. +# +# 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 +# +# http://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. + +from __future__ import absolute_import +import sys + +from google.gax.utils.messages import get_messages + +from google.api import auth_pb2 +from google.api import http_pb2 +from google.cloud.spanner_admin_instance_v1.proto import spanner_instance_admin_pb2 +from google.iam.v1 import iam_policy_pb2 +from google.iam.v1 import policy_pb2 +from google.iam.v1.logging import audit_data_pb2 +from google.longrunning import operations_pb2 +from google.protobuf import any_pb2 +from google.protobuf import descriptor_pb2 +from google.protobuf import empty_pb2 +from google.protobuf import field_mask_pb2 +from google.protobuf import timestamp_pb2 +from google.rpc import status_pb2 + +names = [] +for module in ( + auth_pb2, + http_pb2, + spanner_instance_admin_pb2, + iam_policy_pb2, + policy_pb2, + audit_data_pb2, + operations_pb2, + any_pb2, + descriptor_pb2, + empty_pb2, + field_mask_pb2, + timestamp_pb2, + status_pb2, ): + for name, message in get_messages(module).items(): + message.__module__ = 'google.cloud.spanner_admin_instance_v1.types' + setattr(sys.modules[__name__], name, message) + names.append(name) + +__all__ = tuple(sorted(names)) diff --git a/spanner/google/cloud/spanner_v1/__init__.py b/spanner/google/cloud/spanner_v1/__init__.py new file mode 100644 index 000000000000..9a41ff872a84 --- /dev/null +++ b/spanner/google/cloud/spanner_v1/__init__.py @@ -0,0 +1,51 @@ +# Copyright 2017, Google Inc. All rights reserved. +# +# 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 +# +# http://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. + +from __future__ import absolute_import + +import pkg_resources +__version__ = pkg_resources.get_distribution('google-cloud-spanner').version + +from google.cloud.spanner_v1 import param_types +from google.cloud.spanner_v1 import types +from google.cloud.spanner_v1.client import Client +from google.cloud.spanner_v1.gapic import enums +from google.cloud.spanner_v1.keyset import KeyRange +from google.cloud.spanner_v1.keyset import KeySet +from google.cloud.spanner_v1.pool import AbstractSessionPool +from google.cloud.spanner_v1.pool import BurstyPool +from google.cloud.spanner_v1.pool import FixedSizePool + + +__all__ = ( + # google.cloud.spanner_v1 + '__version__', + 'param_types', + 'types', + + # google.cloud.spanner_v1.client + 'Client', + + # google.cloud.spanner_v1.keyset + 'KeyRange', + 'KeySet', + + # google.cloud.spanner_v1.pool + 'AbstractSessionPool', + 'BurstyPool', + 'FixedSizePool', + + # google.cloud.spanner_v1.gapic + 'enums', +) diff --git a/spanner/google/cloud/spanner/_helpers.py b/spanner/google/cloud/spanner_v1/_helpers.py similarity index 97% rename from spanner/google/cloud/spanner/_helpers.py rename to spanner/google/cloud/spanner_v1/_helpers.py index ef3d2530287c..362a042e9ef8 100644 --- a/spanner/google/cloud/spanner/_helpers.py +++ b/spanner/google/cloud/spanner_v1/_helpers.py @@ -22,7 +22,7 @@ from google.gax import CallOptions from google.protobuf.struct_pb2 import ListValue from google.protobuf.struct_pb2 import Value -from google.cloud.proto.spanner.v1 import type_pb2 +from google.cloud.spanner_v1.proto import type_pb2 from google.cloud._helpers import _date_from_iso8601_date from google.cloud._helpers import _datetime_to_rfc3339 @@ -187,7 +187,7 @@ def _parse_value_pb(value_pb, field_type): :type value_pb: :class:`~google.protobuf.struct_pb2.Value` :param value_pb: protobuf to convert - :type field_type: :class:`~google.cloud.proto.spanner.v1.type_pb2.Type` + :type field_type: :class:`~google.cloud.spanner_v1.proto.type_pb2.Type` :param field_type: type code for the value :rtype: varies on field_type @@ -233,7 +233,7 @@ def _parse_list_value_pbs(rows, row_type): :type rows: list of :class:`~google.protobuf.struct_pb2.ListValue` :param rows: row data returned from a read/query - :type row_type: :class:`~google.cloud.proto.spanner.v1.type_pb2.StructType` + :type row_type: :class:`~google.cloud.spanner_v1.proto.type_pb2.StructType` :param row_type: row schema specification :rtype: list of list of cell data @@ -251,7 +251,7 @@ def _parse_list_value_pbs(rows, row_type): class _SessionWrapper(object): """Base class for objects wrapping a session. - :type session: :class:`~google.cloud.spanner.session.Session` + :type session: :class:`~google.cloud.spanner_v1.session.Session` :param session: the session used to perform the commit """ def __init__(self, session): diff --git a/spanner/google/cloud/spanner/batch.py b/spanner/google/cloud/spanner_v1/batch.py similarity index 91% rename from spanner/google/cloud/spanner/batch.py rename to spanner/google/cloud/spanner_v1/batch.py index 552d7960b1ab..f8faa873edaa 100644 --- a/spanner/google/cloud/spanner/batch.py +++ b/spanner/google/cloud/spanner_v1/batch.py @@ -14,21 +14,21 @@ """Context manager for Cloud Spanner batched writes.""" -from google.cloud.proto.spanner.v1.mutation_pb2 import Mutation -from google.cloud.proto.spanner.v1.transaction_pb2 import TransactionOptions +from google.cloud.spanner_v1.proto.mutation_pb2 import Mutation +from google.cloud.spanner_v1.proto.transaction_pb2 import TransactionOptions # pylint: disable=ungrouped-imports from google.cloud._helpers import _pb_timestamp_to_datetime -from google.cloud.spanner._helpers import _SessionWrapper -from google.cloud.spanner._helpers import _make_list_value_pbs -from google.cloud.spanner._helpers import _options_with_prefix +from google.cloud.spanner_v1._helpers import _SessionWrapper +from google.cloud.spanner_v1._helpers import _make_list_value_pbs +from google.cloud.spanner_v1._helpers import _options_with_prefix # pylint: enable=ungrouped-imports class _BatchBase(_SessionWrapper): """Accumulate mutations for transmission during :meth:`commit`. - :type session: :class:`~google.cloud.spanner.session.Session` + :type session: :class:`~google.cloud.spanner_v1.session.Session` :param session: the session used to perform the commit """ def __init__(self, session): @@ -111,7 +111,7 @@ def delete(self, table, keyset): :type table: str :param table: Name of the table to be modified. - :type keyset: :class:`~google.cloud.spanner.keyset.Keyset` + :type keyset: :class:`~google.cloud.spanner_v1.keyset.Keyset` :param keyset: Keys/ranges identifying rows to delete. """ delete = Mutation.Delete( @@ -182,7 +182,7 @@ def _make_write_pb(table, columns, values): :type values: list of lists :param values: Values to be modified. - :rtype: :class:`google.cloud.proto.spanner.v1.mutation_pb2.Mutation.Write` + :rtype: :class:`google.cloud.spanner_v1.proto.mutation_pb2.Mutation.Write` :returns: Write protobuf """ return Mutation.Write( diff --git a/spanner/google/cloud/spanner/client.py b/spanner/google/cloud/spanner_v1/client.py similarity index 91% rename from spanner/google/cloud/spanner/client.py rename to spanner/google/cloud/spanner_v1/client.py index 34e0a81c4fc4..f0cc1ea6e9cd 100644 --- a/spanner/google/cloud/spanner/client.py +++ b/spanner/google/cloud/spanner_v1/client.py @@ -18,27 +18,27 @@ In the hierarchy of API concepts -* a :class:`~google.cloud.spanner.client.Client` owns an - :class:`~google.cloud.spanner.instance.Instance` -* a :class:`~google.cloud.spanner.instance.Instance` owns a - :class:`~google.cloud.spanner.database.Database` +* a :class:`~google.cloud.spanner_v1.client.Client` owns an + :class:`~google.cloud.spanner_v1.instance.Instance` +* a :class:`~google.cloud.spanner_v1.instance.Instance` owns a + :class:`~google.cloud.spanner_v1.database.Database` """ from google.api.core import page_iterator from google.gax import INITIAL_PAGE # pylint: disable=line-too-long -from google.cloud.gapic.spanner_admin_database.v1.database_admin_client import ( # noqa +from google.cloud.spanner_admin_database_v1.gapic.database_admin_client import ( # noqa DatabaseAdminClient) -from google.cloud.gapic.spanner_admin_instance.v1.instance_admin_client import ( # noqa +from google.cloud.spanner_admin_instance_v1.gapic.instance_admin_client import ( # noqa InstanceAdminClient) # pylint: enable=line-too-long from google.cloud._http import DEFAULT_USER_AGENT from google.cloud.client import ClientWithProject -from google.cloud.spanner import __version__ -from google.cloud.spanner._helpers import _options_with_prefix -from google.cloud.spanner.instance import DEFAULT_NODE_COUNT -from google.cloud.spanner.instance import Instance +from google.cloud.spanner_v1 import __version__ +from google.cloud.spanner_v1._helpers import _options_with_prefix +from google.cloud.spanner_v1.instance import DEFAULT_NODE_COUNT +from google.cloud.spanner_v1.instance import Instance SPANNER_ADMIN_SCOPE = 'https://www.googleapis.com/auth/spanner.admin' @@ -197,7 +197,7 @@ def list_instance_configs(self, page_size=None, page_token=None): :rtype: :class:`~google.api.core.page_iterator.Iterator` :returns: Iterator of - :class:`~google.cloud.spanner.instance.InstanceConfig` + :class:`~google.cloud.spanner_v1.instance.InstanceConfig` resources within the client's project. """ if page_token is None: @@ -236,7 +236,7 @@ def instance(self, instance_id, :param node_count: (Optional) The number of nodes in the instance's cluster; used to set up the instance's cluster. - :rtype: :class:`~google.cloud.spanner.instance.Instance` + :rtype: :class:`~google.cloud.spanner_v1.instance.Instance` :returns: an instance owned by this client. """ return Instance( @@ -260,7 +260,7 @@ def list_instances(self, filter_='', page_size=None, page_token=None): :rtype: :class:`~google.api.core.page_iterator.Iterator` :returns: - Iterator of :class:`~google.cloud.spanner.instance.Instance` + Iterator of :class:`~google.cloud.spanner_v1.instance.Instance` resources within the client's project. """ if page_token is None: @@ -285,7 +285,7 @@ def _item_to_instance_config( :class:`~google.spanner.admin.instance.v1.InstanceConfig` :param config_pb: An instance config returned from the API. - :rtype: :class:`~google.cloud.spanner.instance.InstanceConfig` + :rtype: :class:`~google.cloud.spanner_v1.instance.InstanceConfig` :returns: The next instance config in the page. """ return InstanceConfig.from_pb(config_pb) @@ -300,7 +300,7 @@ def _item_to_instance(iterator, instance_pb): :type instance_pb: :class:`~google.spanner.admin.instance.v1.Instance` :param instance_pb: An instance returned from the API. - :rtype: :class:`~google.cloud.spanner.instance.Instance` + :rtype: :class:`~google.cloud.spanner_v1.instance.Instance` :returns: The next instance in the page. """ return Instance.from_pb(instance_pb, iterator.client) diff --git a/spanner/google/cloud/spanner/database.py b/spanner/google/cloud/spanner_v1/database.py similarity index 92% rename from spanner/google/cloud/spanner/database.py rename to spanner/google/cloud/spanner_v1/database.py index 728acadc6137..0b708094fdb3 100644 --- a/spanner/google/cloud/spanner/database.py +++ b/spanner/google/cloud/spanner_v1/database.py @@ -20,20 +20,20 @@ import google.auth.credentials from google.gax.errors import GaxError from google.gax.grpc import exc_to_code -from google.cloud.gapic.spanner.v1.spanner_client import SpannerClient +from google.cloud.spanner_v1.gapic.spanner_client import SpannerClient from grpc import StatusCode import six # pylint: disable=ungrouped-imports from google.cloud.exceptions import Conflict from google.cloud.exceptions import NotFound -from google.cloud.spanner import __version__ -from google.cloud.spanner._helpers import _options_with_prefix -from google.cloud.spanner.batch import Batch -from google.cloud.spanner.session import Session -from google.cloud.spanner.pool import BurstyPool -from google.cloud.spanner.snapshot import Snapshot -from google.cloud.spanner.pool import SessionCheckout +from google.cloud.spanner_v1 import __version__ +from google.cloud.spanner_v1._helpers import _options_with_prefix +from google.cloud.spanner_v1.batch import Batch +from google.cloud.spanner_v1.pool import BurstyPool +from google.cloud.spanner_v1.pool import SessionCheckout +from google.cloud.spanner_v1.session import Session +from google.cloud.spanner_v1.snapshot import Snapshot # pylint: enable=ungrouped-imports @@ -60,7 +60,7 @@ class Database(object): :type database_id: str :param database_id: The ID of the database. - :type instance: :class:`~google.cloud.spanner.instance.Instance` + :type instance: :class:`~google.cloud.spanner_v1.instance.Instance` :param instance: The instance that owns the database. :type ddl_statements: list of string @@ -68,10 +68,10 @@ class Database(object): CREATE DATABASE statement. :type pool: concrete subclass of - :class:`~google.cloud.spanner.pool.AbstractSessionPool`. + :class:`~google.cloud.spanner_v1.pool.AbstractSessionPool`. :param pool: (Optional) session pool to be used by database. If not passed, the database will construct an instance of - :class:`~google.cloud.spanner.pool.BurstyPool`. + :class:`~google.cloud.spanner_v1.pool.BurstyPool`. """ _spanner_api = None @@ -96,11 +96,11 @@ def from_pb(cls, database_pb, instance, pool=None): :class:`google.spanner.v2.spanner_instance_admin_pb2.Instance` :param database_pb: A instance protobuf object. - :type instance: :class:`~google.cloud.spanner.instance.Instance` + :type instance: :class:`~google.cloud.spanner_v1.instance.Instance` :param instance: The instance that owns the database. :type pool: concrete subclass of - :class:`~google.cloud.spanner.pool.AbstractSessionPool`. + :class:`~google.cloud.spanner_v1.pool.AbstractSessionPool`. :param pool: (Optional) session pool to be used by database. :rtype: :class:`Database` @@ -310,7 +310,7 @@ def drop(self): def session(self): """Factory to create a session for this database. - :rtype: :class:`~google.cloud.spanner.session.Session` + :rtype: :class:`~google.cloud.spanner_v1.session.Session` :returns: a session bound to this database. """ return Session(self) @@ -327,9 +327,9 @@ def snapshot(self, **kw): :type kw: dict :param kw: Passed through to - :class:`~google.cloud.spanner.snapshot.Snapshot` constructor. + :class:`~google.cloud.spanner_v1.snapshot.Snapshot` constructor. - :rtype: :class:`~google.cloud.spanner.database.SnapshotCheckout` + :rtype: :class:`~google.cloud.spanner_v1.database.SnapshotCheckout` :returns: new wrapper """ return SnapshotCheckout(self, **kw) @@ -340,7 +340,7 @@ def batch(self): The wrapper *must* be used as a context manager, with the batch as the value returned by the wrapper. - :rtype: :class:`~google.cloud.spanner.database.BatchCheckout` + :rtype: :class:`~google.cloud.spanner_v1.database.BatchCheckout` :returns: new wrapper """ return BatchCheckout(self) @@ -426,7 +426,7 @@ class SnapshotCheckout(object): :type kw: dict :param kw: Passed through to - :class:`~google.cloud.spanner.snapshot.Snapshot` constructor. + :class:`~google.cloud.spanner_v1.snapshot.Snapshot` constructor. """ def __init__(self, database, **kw): self._database = database diff --git a/spanner/google/cloud/spanner_v1/gapic/__init__.py b/spanner/google/cloud/spanner_v1/gapic/__init__.py new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/spanner/google/cloud/spanner_v1/gapic/enums.py b/spanner/google/cloud/spanner_v1/gapic/enums.py new file mode 100644 index 000000000000..fa318193486f --- /dev/null +++ b/spanner/google/cloud/spanner_v1/gapic/enums.py @@ -0,0 +1,105 @@ +# Copyright 2017, Google Inc. All rights reserved. +# +# 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 +# +# http://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. +"""Wrappers for protocol buffer enum types.""" + + +class NullValue(object): + """ + ``NullValue`` is a singleton enumeration to represent the null value for the + ``Value`` type union. + + The JSON representation for ``NullValue`` is JSON ``null``. + + Attributes: + NULL_VALUE (int): Null value. + """ + NULL_VALUE = 0 + + +class TypeCode(object): + """ + ``TypeCode`` is used as part of ``Type`` to + indicate the type of a Cloud Spanner value. + + Each legal value of a type can be encoded to or decoded from a JSON + value, using the encodings described below. All Cloud Spanner values can + be ``null``, regardless of type; ``null``s are always encoded as a JSON + ``null``. + + Attributes: + TYPE_CODE_UNSPECIFIED (int): Not specified. + BOOL (int): Encoded as JSON ``true`` or ``false``. + INT64 (int): Encoded as ``string``, in decimal format. + FLOAT64 (int): Encoded as ``number``, or the strings ``\"NaN\"``, ``\"Infinity\"``, or + ``\"-Infinity\"``. + TIMESTAMP (int): Encoded as ``string`` in RFC 3339 timestamp format. The time zone + must be present, and must be ``\"Z\"``. + DATE (int): Encoded as ``string`` in RFC 3339 date format. + STRING (int): Encoded as ``string``. + BYTES (int): Encoded as a base64-encoded ``string``, as described in RFC 4648, + section 4. + ARRAY (int): Encoded as ``list``, where the list elements are represented + according to ``array_element_type``. + STRUCT (int): Encoded as ``list``, where list element ``i`` is represented according + to [struct_type.fields[i]][google.spanner.v1.StructType.fields]. + """ + TYPE_CODE_UNSPECIFIED = 0 + BOOL = 1 + INT64 = 2 + FLOAT64 = 3 + TIMESTAMP = 4 + DATE = 5 + STRING = 6 + BYTES = 7 + ARRAY = 8 + STRUCT = 9 + + +class PlanNode(object): + class Kind(object): + """ + The kind of ``PlanNode``. Distinguishes between the two different kinds of + nodes that can appear in a query plan. + + Attributes: + KIND_UNSPECIFIED (int): Not specified. + RELATIONAL (int): Denotes a Relational operator node in the expression tree. Relational + operators represent iterative processing of rows during query execution. + For example, a ``TableScan`` operation that reads rows from a table. + SCALAR (int): Denotes a Scalar node in the expression tree. Scalar nodes represent + non-iterable entities in the query plan. For example, constants or + arithmetic operators appearing inside predicate expressions or references + to column names. + """ + KIND_UNSPECIFIED = 0 + RELATIONAL = 1 + SCALAR = 2 + + +class ExecuteSqlRequest(object): + class QueryMode(object): + """ + Mode in which the query must be processed. + + Attributes: + NORMAL (int): The default mode where only the query result, without any information + about the query plan is returned. + PLAN (int): This mode returns only the query plan, without any result rows or + execution statistics information. + PROFILE (int): This mode returns both the query plan and the execution statistics along + with the result rows. + """ + NORMAL = 0 + PLAN = 1 + PROFILE = 2 diff --git a/spanner/google/cloud/spanner_v1/gapic/spanner_client.py b/spanner/google/cloud/spanner_v1/gapic/spanner_client.py new file mode 100644 index 000000000000..8f2f4c3039b9 --- /dev/null +++ b/spanner/google/cloud/spanner_v1/gapic/spanner_client.py @@ -0,0 +1,880 @@ +# Copyright 2017, Google Inc. All rights reserved. +# +# 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 +# +# http://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. +# +# EDITING INSTRUCTIONS +# This file was generated from the file +# https://github.com/google/googleapis/blob/master/google/spanner/v1/spanner.proto, +# and updates to that file get reflected here through a refresh process. +# For the short term, the refresh process will only be runnable by Google engineers. +# +# The only allowed edits are to method and file documentation. A 3-way +# merge preserves those additions if the generated source changes. +"""Accesses the google.spanner.v1 Spanner API.""" + +import collections +import json +import os +import pkg_resources +import platform + +from google.gax import api_callable +from google.gax import config +from google.gax import path_template +from google.gax.utils import oneof +import google.gax + +from google.cloud.spanner_v1.gapic import enums +from google.cloud.spanner_v1.gapic import spanner_client_config +from google.cloud.spanner_v1.proto import keys_pb2 +from google.cloud.spanner_v1.proto import mutation_pb2 +from google.cloud.spanner_v1.proto import spanner_pb2 +from google.cloud.spanner_v1.proto import transaction_pb2 +from google.protobuf import struct_pb2 + + +class SpannerClient(object): + """ + Cloud Spanner API + + The Cloud Spanner API can be used to manage sessions and execute + transactions on data stored in Cloud Spanner databases. + """ + + SERVICE_ADDRESS = 'spanner.googleapis.com' + """The default address of the service.""" + + DEFAULT_SERVICE_PORT = 443 + """The default port of the service.""" + + # The scopes needed to make gRPC calls to all of the methods defined in + # this service + _ALL_SCOPES = ( + 'https://www.googleapis.com/auth/cloud-platform', + 'https://www.googleapis.com/auth/spanner.data', ) + + _DATABASE_PATH_TEMPLATE = path_template.PathTemplate( + 'projects/{project}/instances/{instance}/databases/{database}') + _SESSION_PATH_TEMPLATE = path_template.PathTemplate( + 'projects/{project}/instances/{instance}/databases/{database}/sessions/{session}' + ) + + @classmethod + def database_path(cls, project, instance, database): + """Returns a fully-qualified database resource name string.""" + return cls._DATABASE_PATH_TEMPLATE.render({ + 'project': project, + 'instance': instance, + 'database': database, + }) + + @classmethod + def session_path(cls, project, instance, database, session): + """Returns a fully-qualified session resource name string.""" + return cls._SESSION_PATH_TEMPLATE.render({ + 'project': project, + 'instance': instance, + 'database': database, + 'session': session, + }) + + @classmethod + def match_project_from_database_name(cls, database_name): + """Parses the project from a database resource. + + Args: + database_name (str): A fully-qualified path representing a database + resource. + + Returns: + A string representing the project. + """ + return cls._DATABASE_PATH_TEMPLATE.match(database_name).get('project') + + @classmethod + def match_instance_from_database_name(cls, database_name): + """Parses the instance from a database resource. + + Args: + database_name (str): A fully-qualified path representing a database + resource. + + Returns: + A string representing the instance. + """ + return cls._DATABASE_PATH_TEMPLATE.match(database_name).get('instance') + + @classmethod + def match_database_from_database_name(cls, database_name): + """Parses the database from a database resource. + + Args: + database_name (str): A fully-qualified path representing a database + resource. + + Returns: + A string representing the database. + """ + return cls._DATABASE_PATH_TEMPLATE.match(database_name).get('database') + + @classmethod + def match_project_from_session_name(cls, session_name): + """Parses the project from a session resource. + + Args: + session_name (str): A fully-qualified path representing a session + resource. + + Returns: + A string representing the project. + """ + return cls._SESSION_PATH_TEMPLATE.match(session_name).get('project') + + @classmethod + def match_instance_from_session_name(cls, session_name): + """Parses the instance from a session resource. + + Args: + session_name (str): A fully-qualified path representing a session + resource. + + Returns: + A string representing the instance. + """ + return cls._SESSION_PATH_TEMPLATE.match(session_name).get('instance') + + @classmethod + def match_database_from_session_name(cls, session_name): + """Parses the database from a session resource. + + Args: + session_name (str): A fully-qualified path representing a session + resource. + + Returns: + A string representing the database. + """ + return cls._SESSION_PATH_TEMPLATE.match(session_name).get('database') + + @classmethod + def match_session_from_session_name(cls, session_name): + """Parses the session from a session resource. + + Args: + session_name (str): A fully-qualified path representing a session + resource. + + Returns: + A string representing the session. + """ + return cls._SESSION_PATH_TEMPLATE.match(session_name).get('session') + + def __init__(self, + channel=None, + credentials=None, + ssl_credentials=None, + scopes=None, + client_config=None, + lib_name=None, + lib_version='', + metrics_headers=()): + """Constructor. + + Args: + channel (~grpc.Channel): A ``Channel`` instance through + which to make calls. + credentials (~google.auth.credentials.Credentials): The authorization + credentials to attach to requests. These credentials identify this + application to the service. + ssl_credentials (~grpc.ChannelCredentials): A + ``ChannelCredentials`` instance for use with an SSL-enabled + channel. + scopes (Sequence[str]): A list of OAuth2 scopes to attach to requests. + client_config (dict): + A dictionary for call options for each method. See + :func:`google.gax.construct_settings` for the structure of + this data. Falls back to the default config if not specified + or the specified config is missing data points. + lib_name (str): The API library software used for calling + the service. (Unless you are writing an API client itself, + leave this as default.) + lib_version (str): The API library software version used + for calling the service. (Unless you are writing an API client + itself, leave this as default.) + metrics_headers (dict): A dictionary of values for tracking + client library metrics. Ultimately serializes to a string + (e.g. 'foo/1.2.3 bar/3.14.1'). This argument should be + considered private. + """ + # Unless the calling application specifically requested + # OAuth scopes, request everything. + if scopes is None: + scopes = self._ALL_SCOPES + + # Initialize an empty client config, if none is set. + if client_config is None: + client_config = {} + + # Initialize metrics_headers as an ordered dictionary + # (cuts down on cardinality of the resulting string slightly). + metrics_headers = collections.OrderedDict(metrics_headers) + metrics_headers['gl-python'] = platform.python_version() + + # The library may or may not be set, depending on what is + # calling this client. Newer client libraries set the library name + # and version. + if lib_name: + metrics_headers[lib_name] = lib_version + + # Finally, track the GAPIC package version. + metrics_headers['gapic'] = pkg_resources.get_distribution( + 'google-cloud-spanner', ).version + + # Load the configuration defaults. + defaults = api_callable.construct_settings( + 'google.spanner.v1.Spanner', + spanner_client_config.config, + client_config, + config.STATUS_CODE_NAMES, + metrics_headers=metrics_headers, ) + self.spanner_stub = config.create_stub( + spanner_pb2.SpannerStub, + channel=channel, + service_path=self.SERVICE_ADDRESS, + service_port=self.DEFAULT_SERVICE_PORT, + credentials=credentials, + scopes=scopes, + ssl_credentials=ssl_credentials) + + self._create_session = api_callable.create_api_call( + self.spanner_stub.CreateSession, + settings=defaults['create_session']) + self._get_session = api_callable.create_api_call( + self.spanner_stub.GetSession, settings=defaults['get_session']) + self._delete_session = api_callable.create_api_call( + self.spanner_stub.DeleteSession, + settings=defaults['delete_session']) + self._execute_sql = api_callable.create_api_call( + self.spanner_stub.ExecuteSql, settings=defaults['execute_sql']) + self._execute_streaming_sql = api_callable.create_api_call( + self.spanner_stub.ExecuteStreamingSql, + settings=defaults['execute_streaming_sql']) + self._read = api_callable.create_api_call( + self.spanner_stub.Read, settings=defaults['read']) + self._streaming_read = api_callable.create_api_call( + self.spanner_stub.StreamingRead, + settings=defaults['streaming_read']) + self._begin_transaction = api_callable.create_api_call( + self.spanner_stub.BeginTransaction, + settings=defaults['begin_transaction']) + self._commit = api_callable.create_api_call( + self.spanner_stub.Commit, settings=defaults['commit']) + self._rollback = api_callable.create_api_call( + self.spanner_stub.Rollback, settings=defaults['rollback']) + + # Service calls + def create_session(self, database, options=None): + """ + Creates a new session. A session can be used to perform + transactions that read and/or modify data in a Cloud Spanner database. + Sessions are meant to be reused for many consecutive + transactions. + + Sessions can only execute one transaction at a time. To execute + multiple concurrent read-write/write-only transactions, create + multiple sessions. Note that standalone reads and queries use a + transaction internally, and count toward the one transaction + limit. + + Cloud Spanner limits the number of sessions that can exist at any given + time; thus, it is a good idea to delete idle and/or unneeded sessions. + Aside from explicit deletes, Cloud Spanner can delete sessions for which no + operations are sent for more than an hour. If a session is deleted, + requests to it return ``NOT_FOUND``. + + Idle sessions can be kept alive by sending a trivial SQL query + periodically, e.g., ``\"SELECT 1\"``. + + Example: + >>> from google.cloud import spanner_v1 + >>> + >>> client = spanner_v1.SpannerClient() + >>> + >>> database = client.database_path('[PROJECT]', '[INSTANCE]', '[DATABASE]') + >>> + >>> response = client.create_session(database) + + Args: + database (str): Required. The database in which the new session is created. + options (~google.gax.CallOptions): Overrides the default + settings for this call, e.g, timeout, retries etc. + + Returns: + A :class:`~google.cloud.spanner_v1.types.Session` instance. + + Raises: + :exc:`google.gax.errors.GaxError` if the RPC is aborted. + :exc:`ValueError` if the parameters are invalid. + """ + request = spanner_pb2.CreateSessionRequest(database=database) + return self._create_session(request, options) + + def get_session(self, name, options=None): + """ + Gets a session. Returns ``NOT_FOUND`` if the session does not exist. + This is mainly useful for determining whether a session is still + alive. + + Example: + >>> from google.cloud import spanner_v1 + >>> + >>> client = spanner_v1.SpannerClient() + >>> + >>> name = client.session_path('[PROJECT]', '[INSTANCE]', '[DATABASE]', '[SESSION]') + >>> + >>> response = client.get_session(name) + + Args: + name (str): Required. The name of the session to retrieve. + options (~google.gax.CallOptions): Overrides the default + settings for this call, e.g, timeout, retries etc. + + Returns: + A :class:`~google.cloud.spanner_v1.types.Session` instance. + + Raises: + :exc:`google.gax.errors.GaxError` if the RPC is aborted. + :exc:`ValueError` if the parameters are invalid. + """ + request = spanner_pb2.GetSessionRequest(name=name) + return self._get_session(request, options) + + def delete_session(self, name, options=None): + """ + Ends a session, releasing server resources associated with it. + + Example: + >>> from google.cloud import spanner_v1 + >>> + >>> client = spanner_v1.SpannerClient() + >>> + >>> name = client.session_path('[PROJECT]', '[INSTANCE]', '[DATABASE]', '[SESSION]') + >>> + >>> client.delete_session(name) + + Args: + name (str): Required. The name of the session to delete. + options (~google.gax.CallOptions): Overrides the default + settings for this call, e.g, timeout, retries etc. + + Raises: + :exc:`google.gax.errors.GaxError` if the RPC is aborted. + :exc:`ValueError` if the parameters are invalid. + """ + request = spanner_pb2.DeleteSessionRequest(name=name) + self._delete_session(request, options) + + def execute_sql(self, + session, + sql, + transaction=None, + params=None, + param_types=None, + resume_token=None, + query_mode=None, + options=None): + """ + Executes an SQL query, returning all rows in a single reply. This + method cannot be used to return a result set larger than 10 MiB; + if the query yields more data than that, the query fails with + a ``FAILED_PRECONDITION`` error. + + Queries inside read-write transactions might return ``ABORTED``. If + this occurs, the application should restart the transaction from + the beginning. See ``Transaction`` for more details. + + Larger result sets can be fetched in streaming fashion by calling + ``ExecuteStreamingSql`` instead. + + Example: + >>> from google.cloud import spanner_v1 + >>> + >>> client = spanner_v1.SpannerClient() + >>> + >>> session = client.session_path('[PROJECT]', '[INSTANCE]', '[DATABASE]', '[SESSION]') + >>> sql = '' + >>> + >>> response = client.execute_sql(session, sql) + + Args: + session (str): Required. The session in which the SQL query should be performed. + sql (str): Required. The SQL query string. + transaction (Union[dict, ~google.cloud.spanner_v1.types.TransactionSelector]): The transaction to use. If none is provided, the default is a + temporary read-only transaction with strong concurrency. + If a dict is provided, it must be of the same form as the protobuf + message :class:`~google.cloud.spanner_v1.types.TransactionSelector` + params (Union[dict, ~google.cloud.spanner_v1.types.Struct]): The SQL query string can contain parameter placeholders. A parameter + placeholder consists of ``'@'`` followed by the parameter + name. Parameter names consist of any combination of letters, + numbers, and underscores. + + Parameters can appear anywhere that a literal value is expected. The same + parameter name can be used more than once, for example: + ``\"WHERE id > @msg_id AND id < @msg_id + 100\"`` + + It is an error to execute an SQL query with unbound parameters. + + Parameter values are specified using ``params``, which is a JSON + object whose keys are parameter names, and whose values are the + corresponding parameter values. + If a dict is provided, it must be of the same form as the protobuf + message :class:`~google.cloud.spanner_v1.types.Struct` + param_types (dict[str -> Union[dict, ~google.cloud.spanner_v1.types.Type]]): It is not always possible for Cloud Spanner to infer the right SQL type + from a JSON value. For example, values of type ``BYTES`` and values + of type ``STRING`` both appear in ``params`` as JSON strings. + + In these cases, ``param_types`` can be used to specify the exact + SQL type for some or all of the SQL query parameters. See the + definition of ``Type`` for more information + about SQL types. + If a dict is provided, it must be of the same form as the protobuf + message :class:`~google.cloud.spanner_v1.types.Type` + resume_token (bytes): If this request is resuming a previously interrupted SQL query + execution, ``resume_token`` should be copied from the last + ``PartialResultSet`` yielded before the interruption. Doing this + enables the new SQL query execution to resume where the last one left + off. The rest of the request parameters must exactly match the + request that yielded this token. + query_mode (~google.cloud.spanner_v1.types.QueryMode): Used to control the amount of debugging information returned in + ``ResultSetStats``. + options (~google.gax.CallOptions): Overrides the default + settings for this call, e.g, timeout, retries etc. + + Returns: + A :class:`~google.cloud.spanner_v1.types.ResultSet` instance. + + Raises: + :exc:`google.gax.errors.GaxError` if the RPC is aborted. + :exc:`ValueError` if the parameters are invalid. + """ + request = spanner_pb2.ExecuteSqlRequest( + session=session, + sql=sql, + transaction=transaction, + params=params, + param_types=param_types, + resume_token=resume_token, + query_mode=query_mode) + return self._execute_sql(request, options) + + def execute_streaming_sql(self, + session, + sql, + transaction=None, + params=None, + param_types=None, + resume_token=None, + query_mode=None, + options=None): + """ + Like ``ExecuteSql``, except returns the result + set as a stream. Unlike ``ExecuteSql``, there + is no limit on the size of the returned result set. However, no + individual row in the result set can exceed 100 MiB, and no + column value can exceed 10 MiB. + + Example: + >>> from google.cloud import spanner_v1 + >>> + >>> client = spanner_v1.SpannerClient() + >>> + >>> session = client.session_path('[PROJECT]', '[INSTANCE]', '[DATABASE]', '[SESSION]') + >>> sql = '' + >>> + >>> for element in client.execute_streaming_sql(session, sql): + ... # process element + ... pass + + Args: + session (str): Required. The session in which the SQL query should be performed. + sql (str): Required. The SQL query string. + transaction (Union[dict, ~google.cloud.spanner_v1.types.TransactionSelector]): The transaction to use. If none is provided, the default is a + temporary read-only transaction with strong concurrency. + If a dict is provided, it must be of the same form as the protobuf + message :class:`~google.cloud.spanner_v1.types.TransactionSelector` + params (Union[dict, ~google.cloud.spanner_v1.types.Struct]): The SQL query string can contain parameter placeholders. A parameter + placeholder consists of ``'@'`` followed by the parameter + name. Parameter names consist of any combination of letters, + numbers, and underscores. + + Parameters can appear anywhere that a literal value is expected. The same + parameter name can be used more than once, for example: + ``\"WHERE id > @msg_id AND id < @msg_id + 100\"`` + + It is an error to execute an SQL query with unbound parameters. + + Parameter values are specified using ``params``, which is a JSON + object whose keys are parameter names, and whose values are the + corresponding parameter values. + If a dict is provided, it must be of the same form as the protobuf + message :class:`~google.cloud.spanner_v1.types.Struct` + param_types (dict[str -> Union[dict, ~google.cloud.spanner_v1.types.Type]]): It is not always possible for Cloud Spanner to infer the right SQL type + from a JSON value. For example, values of type ``BYTES`` and values + of type ``STRING`` both appear in ``params`` as JSON strings. + + In these cases, ``param_types`` can be used to specify the exact + SQL type for some or all of the SQL query parameters. See the + definition of ``Type`` for more information + about SQL types. + If a dict is provided, it must be of the same form as the protobuf + message :class:`~google.cloud.spanner_v1.types.Type` + resume_token (bytes): If this request is resuming a previously interrupted SQL query + execution, ``resume_token`` should be copied from the last + ``PartialResultSet`` yielded before the interruption. Doing this + enables the new SQL query execution to resume where the last one left + off. The rest of the request parameters must exactly match the + request that yielded this token. + query_mode (~google.cloud.spanner_v1.types.QueryMode): Used to control the amount of debugging information returned in + ``ResultSetStats``. + options (~google.gax.CallOptions): Overrides the default + settings for this call, e.g, timeout, retries etc. + + Returns: + Iterable[~google.cloud.spanner_v1.types.PartialResultSet]. + + Raises: + :exc:`google.gax.errors.GaxError` if the RPC is aborted. + :exc:`ValueError` if the parameters are invalid. + """ + request = spanner_pb2.ExecuteSqlRequest( + session=session, + sql=sql, + transaction=transaction, + params=params, + param_types=param_types, + resume_token=resume_token, + query_mode=query_mode) + return self._execute_streaming_sql(request, options) + + def read(self, + session, + table, + columns, + key_set, + transaction=None, + index=None, + limit=None, + resume_token=None, + options=None): + """ + Reads rows from the database using key lookups and scans, as a + simple key/value style alternative to + ``ExecuteSql``. This method cannot be used to + return a result set larger than 10 MiB; if the read matches more + data than that, the read fails with a ``FAILED_PRECONDITION`` + error. + + Reads inside read-write transactions might return ``ABORTED``. If + this occurs, the application should restart the transaction from + the beginning. See ``Transaction`` for more details. + + Larger result sets can be yielded in streaming fashion by calling + ``StreamingRead`` instead. + + Example: + >>> from google.cloud import spanner_v1 + >>> + >>> client = spanner_v1.SpannerClient() + >>> + >>> session = client.session_path('[PROJECT]', '[INSTANCE]', '[DATABASE]', '[SESSION]') + >>> table = '' + >>> columns = [] + >>> key_set = {} + >>> + >>> response = client.read(session, table, columns, key_set) + + Args: + session (str): Required. The session in which the read should be performed. + table (str): Required. The name of the table in the database to be read. + columns (list[str]): The columns of ``table`` to be returned for each row matching + this request. + key_set (Union[dict, ~google.cloud.spanner_v1.types.KeySet]): Required. ``key_set`` identifies the rows to be yielded. ``key_set`` names the + primary keys of the rows in ``table`` to be yielded, unless ``index`` + is present. If ``index`` is present, then ``key_set`` instead names + index keys in ``index``. + + Rows are yielded in table primary key order (if ``index`` is empty) + or index key order (if ``index`` is non-empty). + + It is not an error for the ``key_set`` to name rows that do not + exist in the database. Read yields nothing for nonexistent rows. + If a dict is provided, it must be of the same form as the protobuf + message :class:`~google.cloud.spanner_v1.types.KeySet` + transaction (Union[dict, ~google.cloud.spanner_v1.types.TransactionSelector]): The transaction to use. If none is provided, the default is a + temporary read-only transaction with strong concurrency. + If a dict is provided, it must be of the same form as the protobuf + message :class:`~google.cloud.spanner_v1.types.TransactionSelector` + index (str): If non-empty, the name of an index on ``table``. This index is + used instead of the table primary key when interpreting ``key_set`` + and sorting result rows. See ``key_set`` for further information. + limit (long): If greater than zero, only the first ``limit`` rows are yielded. If ``limit`` + is zero, the default is no limit. + resume_token (bytes): If this request is resuming a previously interrupted read, + ``resume_token`` should be copied from the last + ``PartialResultSet`` yielded before the interruption. Doing this + enables the new read to resume where the last read left off. The + rest of the request parameters must exactly match the request + that yielded this token. + options (~google.gax.CallOptions): Overrides the default + settings for this call, e.g, timeout, retries etc. + + Returns: + A :class:`~google.cloud.spanner_v1.types.ResultSet` instance. + + Raises: + :exc:`google.gax.errors.GaxError` if the RPC is aborted. + :exc:`ValueError` if the parameters are invalid. + """ + request = spanner_pb2.ReadRequest( + session=session, + table=table, + columns=columns, + key_set=key_set, + transaction=transaction, + index=index, + limit=limit, + resume_token=resume_token) + return self._read(request, options) + + def streaming_read(self, + session, + table, + columns, + key_set, + transaction=None, + index=None, + limit=None, + resume_token=None, + options=None): + """ + Like ``Read``, except returns the result set as a + stream. Unlike ``Read``, there is no limit on the + size of the returned result set. However, no individual row in + the result set can exceed 100 MiB, and no column value can exceed + 10 MiB. + + Example: + >>> from google.cloud import spanner_v1 + >>> + >>> client = spanner_v1.SpannerClient() + >>> + >>> session = client.session_path('[PROJECT]', '[INSTANCE]', '[DATABASE]', '[SESSION]') + >>> table = '' + >>> columns = [] + >>> key_set = {} + >>> + >>> for element in client.streaming_read(session, table, columns, key_set): + ... # process element + ... pass + + Args: + session (str): Required. The session in which the read should be performed. + table (str): Required. The name of the table in the database to be read. + columns (list[str]): The columns of ``table`` to be returned for each row matching + this request. + key_set (Union[dict, ~google.cloud.spanner_v1.types.KeySet]): Required. ``key_set`` identifies the rows to be yielded. ``key_set`` names the + primary keys of the rows in ``table`` to be yielded, unless ``index`` + is present. If ``index`` is present, then ``key_set`` instead names + index keys in ``index``. + + Rows are yielded in table primary key order (if ``index`` is empty) + or index key order (if ``index`` is non-empty). + + It is not an error for the ``key_set`` to name rows that do not + exist in the database. Read yields nothing for nonexistent rows. + If a dict is provided, it must be of the same form as the protobuf + message :class:`~google.cloud.spanner_v1.types.KeySet` + transaction (Union[dict, ~google.cloud.spanner_v1.types.TransactionSelector]): The transaction to use. If none is provided, the default is a + temporary read-only transaction with strong concurrency. + If a dict is provided, it must be of the same form as the protobuf + message :class:`~google.cloud.spanner_v1.types.TransactionSelector` + index (str): If non-empty, the name of an index on ``table``. This index is + used instead of the table primary key when interpreting ``key_set`` + and sorting result rows. See ``key_set`` for further information. + limit (long): If greater than zero, only the first ``limit`` rows are yielded. If ``limit`` + is zero, the default is no limit. + resume_token (bytes): If this request is resuming a previously interrupted read, + ``resume_token`` should be copied from the last + ``PartialResultSet`` yielded before the interruption. Doing this + enables the new read to resume where the last read left off. The + rest of the request parameters must exactly match the request + that yielded this token. + options (~google.gax.CallOptions): Overrides the default + settings for this call, e.g, timeout, retries etc. + + Returns: + Iterable[~google.cloud.spanner_v1.types.PartialResultSet]. + + Raises: + :exc:`google.gax.errors.GaxError` if the RPC is aborted. + :exc:`ValueError` if the parameters are invalid. + """ + request = spanner_pb2.ReadRequest( + session=session, + table=table, + columns=columns, + key_set=key_set, + transaction=transaction, + index=index, + limit=limit, + resume_token=resume_token) + return self._streaming_read(request, options) + + def begin_transaction(self, session, options_, options=None): + """ + Begins a new transaction. This step can often be skipped: + ``Read``, ``ExecuteSql`` and + ``Commit`` can begin a new transaction as a + side-effect. + + Example: + >>> from google.cloud import spanner_v1 + >>> + >>> client = spanner_v1.SpannerClient() + >>> + >>> session = client.session_path('[PROJECT]', '[INSTANCE]', '[DATABASE]', '[SESSION]') + >>> options_ = {} + >>> + >>> response = client.begin_transaction(session, options_) + + Args: + session (str): Required. The session in which the transaction runs. + options_ (Union[dict, ~google.cloud.spanner_v1.types.TransactionOptions]): Required. Options for the new transaction. + If a dict is provided, it must be of the same form as the protobuf + message :class:`~google.cloud.spanner_v1.types.TransactionOptions` + options (~google.gax.CallOptions): Overrides the default + settings for this call, e.g, timeout, retries etc. + + Returns: + A :class:`~google.cloud.spanner_v1.types.Transaction` instance. + + Raises: + :exc:`google.gax.errors.GaxError` if the RPC is aborted. + :exc:`ValueError` if the parameters are invalid. + """ + request = spanner_pb2.BeginTransactionRequest( + session=session, options=options_) + return self._begin_transaction(request, options) + + def commit(self, + session, + mutations, + transaction_id=None, + single_use_transaction=None, + options=None): + """ + Commits a transaction. The request includes the mutations to be + applied to rows in the database. + + ``Commit`` might return an ``ABORTED`` error. This can occur at any time; + commonly, the cause is conflicts with concurrent + transactions. However, it can also happen for a variety of other + reasons. If ``Commit`` returns ``ABORTED``, the caller should re-attempt + the transaction from the beginning, re-using the same session. + + Example: + >>> from google.cloud import spanner_v1 + >>> + >>> client = spanner_v1.SpannerClient() + >>> + >>> session = client.session_path('[PROJECT]', '[INSTANCE]', '[DATABASE]', '[SESSION]') + >>> mutations = [] + >>> + >>> response = client.commit(session, mutations) + + Args: + session (str): Required. The session in which the transaction to be committed is running. + mutations (list[Union[dict, ~google.cloud.spanner_v1.types.Mutation]]): The mutations to be executed when this transaction commits. All + mutations are applied atomically, in the order they appear in + this list. + If a dict is provided, it must be of the same form as the protobuf + message :class:`~google.cloud.spanner_v1.types.Mutation` + transaction_id (bytes): Commit a previously-started transaction. + single_use_transaction (Union[dict, ~google.cloud.spanner_v1.types.TransactionOptions]): Execute mutations in a temporary transaction. Note that unlike + commit of a previously-started transaction, commit with a + temporary transaction is non-idempotent. That is, if the + ``CommitRequest`` is sent to Cloud Spanner more than once (for + instance, due to retries in the application, or in the + transport library), it is possible that the mutations are + executed more than once. If this is undesirable, use + ``BeginTransaction`` and + ``Commit`` instead. + If a dict is provided, it must be of the same form as the protobuf + message :class:`~google.cloud.spanner_v1.types.TransactionOptions` + options (~google.gax.CallOptions): Overrides the default + settings for this call, e.g, timeout, retries etc. + + Returns: + A :class:`~google.cloud.spanner_v1.types.CommitResponse` instance. + + Raises: + :exc:`google.gax.errors.GaxError` if the RPC is aborted. + :exc:`ValueError` if the parameters are invalid. + """ + # Sanity check: We have some fields which are mutually exclusive; + # raise ValueError if more than one is sent. + oneof.check_oneof( + transaction_id=transaction_id, + single_use_transaction=single_use_transaction, ) + + request = spanner_pb2.CommitRequest( + session=session, + mutations=mutations, + transaction_id=transaction_id, + single_use_transaction=single_use_transaction) + return self._commit(request, options) + + def rollback(self, session, transaction_id, options=None): + """ + Rolls back a transaction, releasing any locks it holds. It is a good + idea to call this for any transaction that includes one or more + ``Read`` or ``ExecuteSql`` requests and + ultimately decides not to commit. + + ``Rollback`` returns ``OK`` if it successfully aborts the transaction, the + transaction was already aborted, or the transaction is not + found. ``Rollback`` never returns ``ABORTED``. + + Example: + >>> from google.cloud import spanner_v1 + >>> + >>> client = spanner_v1.SpannerClient() + >>> + >>> session = client.session_path('[PROJECT]', '[INSTANCE]', '[DATABASE]', '[SESSION]') + >>> transaction_id = b'' + >>> + >>> client.rollback(session, transaction_id) + + Args: + session (str): Required. The session in which the transaction to roll back is running. + transaction_id (bytes): Required. The transaction to roll back. + options (~google.gax.CallOptions): Overrides the default + settings for this call, e.g, timeout, retries etc. + + Raises: + :exc:`google.gax.errors.GaxError` if the RPC is aborted. + :exc:`ValueError` if the parameters are invalid. + """ + request = spanner_pb2.RollbackRequest( + session=session, transaction_id=transaction_id) + self._rollback(request, options) diff --git a/spanner/google/cloud/spanner_v1/gapic/spanner_client_config.py b/spanner/google/cloud/spanner_v1/gapic/spanner_client_config.py new file mode 100644 index 000000000000..5f38663a35f9 --- /dev/null +++ b/spanner/google/cloud/spanner_v1/gapic/spanner_client_config.py @@ -0,0 +1,83 @@ +config = { + "interfaces": { + "google.spanner.v1.Spanner": { + "retry_codes": { + "idempotent": ["DEADLINE_EXCEEDED", "UNAVAILABLE"], + "non_idempotent": [], + "long_running": ["UNAVAILABLE"] + }, + "retry_params": { + "default": { + "initial_retry_delay_millis": 1000, + "retry_delay_multiplier": 1.3, + "max_retry_delay_millis": 32000, + "initial_rpc_timeout_millis": 60000, + "rpc_timeout_multiplier": 1.0, + "max_rpc_timeout_millis": 60000, + "total_timeout_millis": 600000 + }, + "long_running": { + "initial_retry_delay_millis": 1000, + "retry_delay_multiplier": 1.3, + "max_retry_delay_millis": 32000, + "initial_rpc_timeout_millis": 3600000, + "rpc_timeout_multiplier": 1.0, + "max_rpc_timeout_millis": 3600000, + "total_timeout_millis": 3600000 + } + }, + "methods": { + "CreateSession": { + "timeout_millis": 30000, + "retry_codes_name": "idempotent", + "retry_params_name": "default" + }, + "GetSession": { + "timeout_millis": 30000, + "retry_codes_name": "idempotent", + "retry_params_name": "default" + }, + "DeleteSession": { + "timeout_millis": 30000, + "retry_codes_name": "idempotent", + "retry_params_name": "default" + }, + "ExecuteSql": { + "timeout_millis": 30000, + "retry_codes_name": "idempotent", + "retry_params_name": "default" + }, + "ExecuteStreamingSql": { + "timeout_millis": 3600000, + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + }, + "Read": { + "timeout_millis": 30000, + "retry_codes_name": "idempotent", + "retry_params_name": "default" + }, + "StreamingRead": { + "timeout_millis": 3600000, + "retry_codes_name": "non_idempotent", + "retry_params_name": "default" + }, + "BeginTransaction": { + "timeout_millis": 30000, + "retry_codes_name": "idempotent", + "retry_params_name": "default" + }, + "Commit": { + "timeout_millis": 3600000, + "retry_codes_name": "long_running", + "retry_params_name": "long_running" + }, + "Rollback": { + "timeout_millis": 30000, + "retry_codes_name": "idempotent", + "retry_params_name": "default" + } + } + } + } +} diff --git a/spanner/google/cloud/spanner/instance.py b/spanner/google/cloud/spanner_v1/instance.py similarity index 95% rename from spanner/google/cloud/spanner/instance.py rename to spanner/google/cloud/spanner_v1/instance.py index 34cb5b1b0bc2..f43e201db475 100644 --- a/spanner/google/cloud/spanner/instance.py +++ b/spanner/google/cloud/spanner_v1/instance.py @@ -20,7 +20,7 @@ from google.gax import INITIAL_PAGE from google.gax.errors import GaxError from google.gax.grpc import exc_to_code -from google.cloud.proto.spanner.admin.instance.v1 import ( +from google.cloud.spanner_admin_instance_v1.proto import ( spanner_instance_admin_pb2 as admin_v1_pb2) from google.protobuf.field_mask_pb2 import FieldMask from grpc import StatusCode @@ -28,9 +28,9 @@ # pylint: disable=ungrouped-imports from google.cloud.exceptions import Conflict from google.cloud.exceptions import NotFound -from google.cloud.spanner._helpers import _options_with_prefix -from google.cloud.spanner.database import Database -from google.cloud.spanner.pool import BurstyPool +from google.cloud.spanner_v1._helpers import _options_with_prefix +from google.cloud.spanner_v1.database import Database +from google.cloud.spanner_v1.pool import BurstyPool # pylint: enable=ungrouped-imports @@ -54,7 +54,7 @@ class Instance(object): :type instance_id: str :param instance_id: The ID of the instance. - :type client: :class:`~google.cloud.spanner.client.Client` + :type client: :class:`~google.cloud.spanner_v1.client.Client` :param client: The client that owns the instance. Provides authorization and a project ID. @@ -104,7 +104,7 @@ def from_pb(cls, instance_pb, client): :class:`google.spanner.v2.spanner_instance_admin_pb2.Instance` :param instance_pb: A instance protobuf object. - :type client: :class:`~google.cloud.spanner.client.Client` + :type client: :class:`~google.cloud.spanner_v1.client.Client` :param client: The client that owns the instance. :rtype: :class:`Instance` @@ -167,7 +167,7 @@ def copy(self): Copies the local data stored as simple types and copies the client attached to this instance. - :rtype: :class:`~google.cloud.spanner.instance.Instance` + :rtype: :class:`~google.cloud.spanner_v1.instance.Instance` :returns: A copy of the current instance. """ new_client = self._client.copy() @@ -353,10 +353,10 @@ def database(self, database_id, ddl_statements=(), pool=None): 'CREATE DATABSE' statement. :type pool: concrete subclass of - :class:`~google.cloud.spanner.pool.AbstractSessionPool`. + :class:`~google.cloud.spanner_v1.pool.AbstractSessionPool`. :param pool: (Optional) session pool to be used by database. - :rtype: :class:`~google.cloud.spanner.database.Database` + :rtype: :class:`~google.cloud.spanner_v1.database.Database` :returns: a database owned by this instance. """ return Database( @@ -376,7 +376,7 @@ def list_databases(self, page_size=None, page_token=None): :rtype: :class:`~google.api.core.page_iterator.Iterator` :returns: - Iterator of :class:`~google.cloud.spanner.database.Database` + Iterator of :class:`~google.cloud.spanner_v1.database.Database` resources within the current instance. """ if page_token is None: @@ -399,7 +399,7 @@ def _item_to_database(iterator, database_pb): :type database_pb: :class:`~google.spanner.admin.database.v1.Database` :param database_pb: A database returned from the API. - :rtype: :class:`~google.cloud.spanner.database.Database` + :rtype: :class:`~google.cloud.spanner_v1.database.Database` :returns: The next database in the page. """ return Database.from_pb(database_pb, iterator.instance, pool=BurstyPool()) diff --git a/spanner/google/cloud/spanner/keyset.py b/spanner/google/cloud/spanner_v1/keyset.py similarity index 90% rename from spanner/google/cloud/spanner/keyset.py rename to spanner/google/cloud/spanner_v1/keyset.py index fe0d5cd1485d..43e41d0d27b4 100644 --- a/spanner/google/cloud/spanner/keyset.py +++ b/spanner/google/cloud/spanner_v1/keyset.py @@ -14,11 +14,11 @@ """Wrap representation of Spanner keys / ranges.""" -from google.cloud.proto.spanner.v1.keys_pb2 import KeyRange as KeyRangePB -from google.cloud.proto.spanner.v1.keys_pb2 import KeySet as KeySetPB +from google.cloud.spanner_v1.proto.keys_pb2 import KeyRange as KeyRangePB +from google.cloud.spanner_v1.proto.keys_pb2 import KeySet as KeySetPB -from google.cloud.spanner._helpers import _make_list_value_pb -from google.cloud.spanner._helpers import _make_list_value_pbs +from google.cloud.spanner_v1._helpers import _make_list_value_pb +from google.cloud.spanner_v1._helpers import _make_list_value_pbs class KeyRange(object): @@ -55,7 +55,7 @@ def __init__(self, start_open=None, start_closed=None, def to_pb(self): """Construct a KeyRange protobuf. - :rtype: :class:`~google.cloud.proto.spanner.v1.keys_pb2.KeyRange` + :rtype: :class:`~google.cloud.spanner_v1.proto.keys_pb2.KeyRange` :returns: protobuf corresponding to this instance. """ kwargs = {} @@ -97,7 +97,7 @@ def __init__(self, keys=(), ranges=(), all_=False): def to_pb(self): """Construct a KeySet protobuf. - :rtype: :class:`~google.cloud.proto.spanner.v1.keys_pb2.KeySet` + :rtype: :class:`~google.cloud.spanner_v1.proto.keys_pb2.KeySet` :returns: protobuf corresponding to this instance. """ if self.all_: diff --git a/spanner/google/cloud/spanner/types.py b/spanner/google/cloud/spanner_v1/param_types.py similarity index 70% rename from spanner/google/cloud/spanner/types.py rename to spanner/google/cloud/spanner_v1/param_types.py index 9e22da94c51f..0e7869e01a78 100644 --- a/spanner/google/cloud/spanner/types.py +++ b/spanner/google/cloud/spanner_v1/param_types.py @@ -14,20 +14,20 @@ """Types exported from this package.""" -from google.cloud.proto.spanner.v1 import type_pb2 +from google.cloud.spanner_v1.proto import type_pb2 -# Scalar paramter types -STRING_PARAM_TYPE = type_pb2.Type(code=type_pb2.STRING) -BYTES_PARAM_TYPE = type_pb2.Type(code=type_pb2.BYTES) -BOOL_PARAM_TYPE = type_pb2.Type(code=type_pb2.BOOL) -INT64_PARAM_TYPE = type_pb2.Type(code=type_pb2.INT64) -FLOAT64_PARAM_TYPE = type_pb2.Type(code=type_pb2.FLOAT64) -DATE_PARAM_TYPE = type_pb2.Type(code=type_pb2.DATE) -TIMESTAMP_PARAM_TYPE = type_pb2.Type(code=type_pb2.TIMESTAMP) +# Scalar parameter types +STRING = type_pb2.Type(code=type_pb2.STRING) +BYTES = type_pb2.Type(code=type_pb2.BYTES) +BOOE = type_pb2.Type(code=type_pb2.BOOL) +INT64 = type_pb2.Type(code=type_pb2.INT64) +FLOAT64 = type_pb2.Type(code=type_pb2.FLOAT64) +DATE = type_pb2.Type(code=type_pb2.DATE) +TIMESTAMP = type_pb2.Type(code=type_pb2.TIMESTAMP) -def ArrayParamType(element_type): # pylint: disable=invalid-name +def Array(element_type): # pylint: disable=invalid-name """Construct an array paramter type description protobuf. :type element_type: :class:`type_pb2.Type` @@ -49,12 +49,12 @@ def StructField(name, field_type): # pylint: disable=invalid-name :param field_type: the type of the field :rtype: :class:`type_pb2.StructType.Field` - :returns: the appropriate array-type protobuf + :returns: the appropriate struct-field-type protobuf """ return type_pb2.StructType.Field(name=name, type=field_type) -def StructParamType(fields): # pylint: disable=invalid-name +def Struct(fields): # pylint: disable=invalid-name """Construct a struct paramter type description protobuf. :type fields: list of :class:`type_pb2.StructType.Field` @@ -65,4 +65,5 @@ def StructParamType(fields): # pylint: disable=invalid-name """ return type_pb2.Type( code=type_pb2.STRUCT, - struct_type=type_pb2.StructType(fields=fields)) + struct_type=type_pb2.StructType(fields=fields), + ) diff --git a/spanner/google/cloud/spanner/pool.py b/spanner/google/cloud/spanner_v1/pool.py similarity index 92% rename from spanner/google/cloud/spanner/pool.py rename to spanner/google/cloud/spanner_v1/pool.py index a0c1a49104df..9998426ee60b 100644 --- a/spanner/google/cloud/spanner/pool.py +++ b/spanner/google/cloud/spanner_v1/pool.py @@ -33,7 +33,7 @@ class AbstractSessionPool(object): def bind(self, database): """Associate the pool with a database. - :type database: :class:`~google.cloud.spanner.database.Database` + :type database: :class:`~google.cloud.spanner_v1.database.Database` :param database: database used by the pool: used to create sessions when needed. @@ -58,7 +58,7 @@ def get(self): def put(self, session): """Return a session to the pool. - :type session: :class:`~google.cloud.spanner.session.Session` + :type session: :class:`~google.cloud.spanner_v1.session.Session` :param session: the session being returned. Concrete implementations of this method are allowed to raise an @@ -87,7 +87,7 @@ def session(self, **kwargs): :param kwargs: (optional) keyword arguments, passed through to the returned checkout. - :rtype: :class:`~google.cloud.spanner.session.SessionCheckout` + :rtype: :class:`~google.cloud.spanner_v1.session.SessionCheckout` :returns: a checkout instance, to be used as a context manager for accessing the session and returning it to the pool. """ @@ -127,7 +127,7 @@ def __init__(self, size=DEFAULT_SIZE, default_timeout=DEFAULT_TIMEOUT): def bind(self, database): """Associate the pool with a database. - :type database: :class:`~google.cloud.spanner.database.Database` + :type database: :class:`~google.cloud.spanner_v1.database.Database` :param database: database used by the pool: used to create sessions when needed. """ @@ -144,7 +144,7 @@ def get(self, timeout=None): # pylint: disable=arguments-differ :type timeout: int :param timeout: seconds to block waiting for an available session - :rtype: :class:`~google.cloud.spanner.session.Session` + :rtype: :class:`~google.cloud.spanner_v1.session.Session` :returns: an existing session from the pool, or a newly-created session. :raises: :exc:`six.moves.queue.Empty` if the queue is empty. @@ -165,7 +165,7 @@ def put(self, session): Never blocks: if the pool is full, raises. - :type session: :class:`~google.cloud.spanner.session.Session` + :type session: :class:`~google.cloud.spanner_v1.session.Session` :param session: the session being returned. :raises: :exc:`six.moves.queue.Full` if the queue is full. @@ -208,7 +208,7 @@ def __init__(self, target_size=10): def bind(self, database): """Associate the pool with a database. - :type database: :class:`~google.cloud.spanner.database.Database` + :type database: :class:`~google.cloud.spanner_v1.database.Database` :param database: database used by the pool: used to create sessions when needed. """ @@ -217,7 +217,7 @@ def bind(self, database): def get(self): """Check a session out from the pool. - :rtype: :class:`~google.cloud.spanner.session.Session` + :rtype: :class:`~google.cloud.spanner_v1.session.Session` :returns: an existing session from the pool, or a newly-created session. """ @@ -238,7 +238,7 @@ def put(self, session): Never blocks: if the pool is full, the returned session is discarded. - :type session: :class:`~google.cloud.spanner.session.Session` + :type session: :class:`~google.cloud.spanner_v1.session.Session` :param session: the session being returned. """ try: @@ -301,7 +301,7 @@ def __init__(self, size=10, default_timeout=10, ping_interval=3000): def bind(self, database): """Associate the pool with a database. - :type database: :class:`~google.cloud.spanner.database.Database` + :type database: :class:`~google.cloud.spanner_v1.database.Database` :param database: database used by the pool: used to create sessions when needed. """ @@ -318,7 +318,7 @@ def get(self, timeout=None): # pylint: disable=arguments-differ :type timeout: int :param timeout: seconds to block waiting for an available session - :rtype: :class:`~google.cloud.spanner.session.Session` + :rtype: :class:`~google.cloud.spanner_v1.session.Session` :returns: an existing session from the pool, or a newly-created session. :raises: :exc:`six.moves.queue.Empty` if the queue is empty. @@ -340,7 +340,7 @@ def put(self, session): Never blocks: if the pool is full, raises. - :type session: :class:`~google.cloud.spanner.session.Session` + :type session: :class:`~google.cloud.spanner_v1.session.Session` :param session: the session being returned. :raises: :exc:`six.moves.queue.Full` if the queue is full. @@ -413,7 +413,7 @@ def __init__(self, size=10, default_timeout=10, ping_interval=3000): def bind(self, database): """Associate the pool with a database. - :type database: :class:`~google.cloud.spanner.database.Database` + :type database: :class:`~google.cloud.spanner_v1.database.Database` :param database: database used by the pool: used to create sessions when needed. """ @@ -425,7 +425,7 @@ def put(self, session): Never blocks: if the pool is full, raises. - :type session: :class:`~google.cloud.spanner.session.Session` + :type session: :class:`~google.cloud.spanner_v1.session.Session` :param session: the session being returned. :raises: :exc:`six.moves.queue.Full` if the queue is full. @@ -452,7 +452,7 @@ class SessionCheckout(object): """Context manager: hold session checked out from a pool. :type pool: concrete subclass of - :class:`~google.cloud.spanner.session.AbstractSessionPool` + :class:`~google.cloud.spanner_v1.session.AbstractSessionPool` :param pool: Pool from which to check out a session. :type kwargs: dict diff --git a/spanner/google/cloud/spanner_v1/proto/__init__.py b/spanner/google/cloud/spanner_v1/proto/__init__.py new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/spanner/google/cloud/spanner_v1/proto/keys_pb2.py b/spanner/google/cloud/spanner_v1/proto/keys_pb2.py new file mode 100644 index 000000000000..c7f216240e96 --- /dev/null +++ b/spanner/google/cloud/spanner_v1/proto/keys_pb2.py @@ -0,0 +1,343 @@ +# Generated by the protocol buffer compiler. DO NOT EDIT! +# source: google/cloud/spanner_v1/proto/keys.proto + +import sys +_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) +from google.protobuf import descriptor as _descriptor +from google.protobuf import message as _message +from google.protobuf import reflection as _reflection +from google.protobuf import symbol_database as _symbol_database +from google.protobuf import descriptor_pb2 +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + + +from google.api import annotations_pb2 as google_dot_api_dot_annotations__pb2 +from google.protobuf import struct_pb2 as google_dot_protobuf_dot_struct__pb2 + + +DESCRIPTOR = _descriptor.FileDescriptor( + name='google/cloud/spanner_v1/proto/keys.proto', + package='google.spanner.v1', + syntax='proto3', + serialized_pb=_b('\n(google/cloud/spanner_v1/proto/keys.proto\x12\x11google.spanner.v1\x1a\x1cgoogle/api/annotations.proto\x1a\x1cgoogle/protobuf/struct.proto\"\xf4\x01\n\x08KeyRange\x12\x32\n\x0cstart_closed\x18\x01 \x01(\x0b\x32\x1a.google.protobuf.ListValueH\x00\x12\x30\n\nstart_open\x18\x02 \x01(\x0b\x32\x1a.google.protobuf.ListValueH\x00\x12\x30\n\nend_closed\x18\x03 \x01(\x0b\x32\x1a.google.protobuf.ListValueH\x01\x12.\n\x08\x65nd_open\x18\x04 \x01(\x0b\x32\x1a.google.protobuf.ListValueH\x01\x42\x10\n\x0estart_key_typeB\x0e\n\x0c\x65nd_key_type\"l\n\x06KeySet\x12(\n\x04keys\x18\x01 \x03(\x0b\x32\x1a.google.protobuf.ListValue\x12+\n\x06ranges\x18\x02 \x03(\x0b\x32\x1b.google.spanner.v1.KeyRange\x12\x0b\n\x03\x61ll\x18\x03 \x01(\x08\x42x\n\x15\x63om.google.spanner.v1B\tKeysProtoP\x01Z8google.golang.org/genproto/googleapis/spanner/v1;spanner\xaa\x02\x17Google.Cloud.Spanner.V1b\x06proto3') + , + dependencies=[google_dot_api_dot_annotations__pb2.DESCRIPTOR,google_dot_protobuf_dot_struct__pb2.DESCRIPTOR,]) +_sym_db.RegisterFileDescriptor(DESCRIPTOR) + + + + +_KEYRANGE = _descriptor.Descriptor( + name='KeyRange', + full_name='google.spanner.v1.KeyRange', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='start_closed', full_name='google.spanner.v1.KeyRange.start_closed', index=0, + number=1, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='start_open', full_name='google.spanner.v1.KeyRange.start_open', index=1, + number=2, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='end_closed', full_name='google.spanner.v1.KeyRange.end_closed', index=2, + number=3, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='end_open', full_name='google.spanner.v1.KeyRange.end_open', index=3, + number=4, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto3', + extension_ranges=[], + oneofs=[ + _descriptor.OneofDescriptor( + name='start_key_type', full_name='google.spanner.v1.KeyRange.start_key_type', + index=0, containing_type=None, fields=[]), + _descriptor.OneofDescriptor( + name='end_key_type', full_name='google.spanner.v1.KeyRange.end_key_type', + index=1, containing_type=None, fields=[]), + ], + serialized_start=124, + serialized_end=368, +) + + +_KEYSET = _descriptor.Descriptor( + name='KeySet', + full_name='google.spanner.v1.KeySet', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='keys', full_name='google.spanner.v1.KeySet.keys', index=0, + number=1, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='ranges', full_name='google.spanner.v1.KeySet.ranges', index=1, + number=2, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='all', full_name='google.spanner.v1.KeySet.all', index=2, + number=3, type=8, cpp_type=7, label=1, + has_default_value=False, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto3', + extension_ranges=[], + oneofs=[ + ], + serialized_start=370, + serialized_end=478, +) + +_KEYRANGE.fields_by_name['start_closed'].message_type = google_dot_protobuf_dot_struct__pb2._LISTVALUE +_KEYRANGE.fields_by_name['start_open'].message_type = google_dot_protobuf_dot_struct__pb2._LISTVALUE +_KEYRANGE.fields_by_name['end_closed'].message_type = google_dot_protobuf_dot_struct__pb2._LISTVALUE +_KEYRANGE.fields_by_name['end_open'].message_type = google_dot_protobuf_dot_struct__pb2._LISTVALUE +_KEYRANGE.oneofs_by_name['start_key_type'].fields.append( + _KEYRANGE.fields_by_name['start_closed']) +_KEYRANGE.fields_by_name['start_closed'].containing_oneof = _KEYRANGE.oneofs_by_name['start_key_type'] +_KEYRANGE.oneofs_by_name['start_key_type'].fields.append( + _KEYRANGE.fields_by_name['start_open']) +_KEYRANGE.fields_by_name['start_open'].containing_oneof = _KEYRANGE.oneofs_by_name['start_key_type'] +_KEYRANGE.oneofs_by_name['end_key_type'].fields.append( + _KEYRANGE.fields_by_name['end_closed']) +_KEYRANGE.fields_by_name['end_closed'].containing_oneof = _KEYRANGE.oneofs_by_name['end_key_type'] +_KEYRANGE.oneofs_by_name['end_key_type'].fields.append( + _KEYRANGE.fields_by_name['end_open']) +_KEYRANGE.fields_by_name['end_open'].containing_oneof = _KEYRANGE.oneofs_by_name['end_key_type'] +_KEYSET.fields_by_name['keys'].message_type = google_dot_protobuf_dot_struct__pb2._LISTVALUE +_KEYSET.fields_by_name['ranges'].message_type = _KEYRANGE +DESCRIPTOR.message_types_by_name['KeyRange'] = _KEYRANGE +DESCRIPTOR.message_types_by_name['KeySet'] = _KEYSET + +KeyRange = _reflection.GeneratedProtocolMessageType('KeyRange', (_message.Message,), dict( + DESCRIPTOR = _KEYRANGE, + __module__ = 'google.cloud.spanner_v1.proto.keys_pb2' + , + __doc__ = """KeyRange represents a range of rows in a table or index. + + A range has a start key and an end key. These keys can be open or + closed, indicating if the range includes rows with that key. + + Keys are represented by lists, where the ith value in the list + corresponds to the ith component of the table or index primary key. + Individual values are encoded as described + [here][google.spanner.v1.TypeCode]. + + For example, consider the following table definition: + + :: + + CREATE TABLE UserEvents ( + UserName STRING(MAX), + EventDate STRING(10) + ) PRIMARY KEY(UserName, EventDate); + + The following keys name rows in this table: + + :: + + ["Bob", "2014-09-23"] + ["Alfred", "2015-06-12"] + + Since the ``UserEvents`` table's ``PRIMARY KEY`` clause names two + columns, each ``UserEvents`` key has two elements; the first is the + ``UserName``, and the second is the ``EventDate``. + + Key ranges with multiple components are interpreted lexicographically by + component using the table or index key's declared sort order. For + example, the following range returns all events for user ``"Bob"`` that + occurred in the year 2015: + + :: + + "start_closed": ["Bob", "2015-01-01"] + "end_closed": ["Bob", "2015-12-31"] + + Start and end keys can omit trailing key components. This affects the + inclusion and exclusion of rows that exactly match the provided key + components: if the key is closed, then rows that exactly match the + provided components are included; if the key is open, then rows that + exactly match are not included. + + For example, the following range includes all events for ``"Bob"`` that + occurred during and after the year 2000: + + :: + + "start_closed": ["Bob", "2000-01-01"] + "end_closed": ["Bob"] + + The next example retrieves all events for ``"Bob"``: + + :: + + "start_closed": ["Bob"] + "end_closed": ["Bob"] + + To retrieve events before the year 2000: + + :: + + "start_closed": ["Bob"] + "end_open": ["Bob", "2000-01-01"] + + The following range includes all rows in the table: + + :: + + "start_closed": [] + "end_closed": [] + + This range returns all users whose ``UserName`` begins with any + character from A to C: + + :: + + "start_closed": ["A"] + "end_open": ["D"] + + This range returns all users whose ``UserName`` begins with B: + + :: + + "start_closed": ["B"] + "end_open": ["C"] + + Key ranges honor column sort order. For example, suppose a table is + defined as follows: + + :: + + CREATE TABLE DescendingSortedTable { + Key INT64, + ... + ) PRIMARY KEY(Key DESC); + + The following range retrieves all rows with key values between 1 and 100 + inclusive: + + :: + + "start_closed": ["100"] + "end_closed": ["1"] + + Note that 100 is passed as the start, and 1 is passed as the end, + because ``Key`` is a descending column in the schema. + + + Attributes: + start_key_type: + The start key must be provided. It can be either closed or + open. + start_closed: + If the start is closed, then the range includes all rows whose + first ``len(start_closed)`` key columns exactly match + ``start_closed``. + start_open: + If the start is open, then the range excludes rows whose first + ``len(start_open)`` key columns exactly match ``start_open``. + end_key_type: + The end key must be provided. It can be either closed or open. + end_closed: + If the end is closed, then the range includes all rows whose + first ``len(end_closed)`` key columns exactly match + ``end_closed``. + end_open: + If the end is open, then the range excludes rows whose first + ``len(end_open)`` key columns exactly match ``end_open``. + """, + # @@protoc_insertion_point(class_scope:google.spanner.v1.KeyRange) + )) +_sym_db.RegisterMessage(KeyRange) + +KeySet = _reflection.GeneratedProtocolMessageType('KeySet', (_message.Message,), dict( + DESCRIPTOR = _KEYSET, + __module__ = 'google.cloud.spanner_v1.proto.keys_pb2' + , + __doc__ = """``KeySet`` defines a collection of Cloud Spanner keys and/or key ranges. + All the keys are expected to be in the same table or index. The keys + need not be sorted in any particular way. + + If the same key is specified multiple times in the set (for example if + two ranges, two keys, or a key and a range overlap), Cloud Spanner + behaves as if the key were only specified once. + + + Attributes: + keys: + A list of specific keys. Entries in ``keys`` should have + exactly as many elements as there are columns in the primary + or index key with which this ``KeySet`` is used. Individual + key values are encoded as described + [here][google.spanner.v1.TypeCode]. + ranges: + A list of key ranges. See + [KeyRange][google.spanner.v1.KeyRange] for more information + about key range specifications. + all: + For convenience ``all`` can be set to ``true`` to indicate + that this ``KeySet`` matches all keys in the table or index. + Note that any keys specified in ``keys`` or ``ranges`` are + only yielded once. + """, + # @@protoc_insertion_point(class_scope:google.spanner.v1.KeySet) + )) +_sym_db.RegisterMessage(KeySet) + + +DESCRIPTOR.has_options = True +DESCRIPTOR._options = _descriptor._ParseOptions(descriptor_pb2.FileOptions(), _b('\n\025com.google.spanner.v1B\tKeysProtoP\001Z8google.golang.org/genproto/googleapis/spanner/v1;spanner\252\002\027Google.Cloud.Spanner.V1')) +try: + # THESE ELEMENTS WILL BE DEPRECATED. + # Please use the generated *_pb2_grpc.py files instead. + import grpc + from grpc.beta import implementations as beta_implementations + from grpc.beta import interfaces as beta_interfaces + from grpc.framework.common import cardinality + from grpc.framework.interfaces.face import utilities as face_utilities +except ImportError: + pass +# @@protoc_insertion_point(module_scope) diff --git a/spanner/google/cloud/spanner_v1/proto/keys_pb2_grpc.py b/spanner/google/cloud/spanner_v1/proto/keys_pb2_grpc.py new file mode 100644 index 000000000000..a89435267cb2 --- /dev/null +++ b/spanner/google/cloud/spanner_v1/proto/keys_pb2_grpc.py @@ -0,0 +1,3 @@ +# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! +import grpc + diff --git a/spanner/google/cloud/spanner_v1/proto/mutation_pb2.py b/spanner/google/cloud/spanner_v1/proto/mutation_pb2.py new file mode 100644 index 000000000000..b51344de6d41 --- /dev/null +++ b/spanner/google/cloud/spanner_v1/proto/mutation_pb2.py @@ -0,0 +1,299 @@ +# Generated by the protocol buffer compiler. DO NOT EDIT! +# source: google/cloud/spanner_v1/proto/mutation.proto + +import sys +_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) +from google.protobuf import descriptor as _descriptor +from google.protobuf import message as _message +from google.protobuf import reflection as _reflection +from google.protobuf import symbol_database as _symbol_database +from google.protobuf import descriptor_pb2 +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + + +from google.api import annotations_pb2 as google_dot_api_dot_annotations__pb2 +from google.protobuf import struct_pb2 as google_dot_protobuf_dot_struct__pb2 +from google.cloud.spanner_v1.proto import keys_pb2 as google_dot_cloud_dot_spanner__v1_dot_proto_dot_keys__pb2 + + +DESCRIPTOR = _descriptor.FileDescriptor( + name='google/cloud/spanner_v1/proto/mutation.proto', + package='google.spanner.v1', + syntax='proto3', + serialized_pb=_b('\n,google/cloud/spanner_v1/proto/mutation.proto\x12\x11google.spanner.v1\x1a\x1cgoogle/api/annotations.proto\x1a\x1cgoogle/protobuf/struct.proto\x1a(google/cloud/spanner_v1/proto/keys.proto\"\xc6\x03\n\x08Mutation\x12\x33\n\x06insert\x18\x01 \x01(\x0b\x32!.google.spanner.v1.Mutation.WriteH\x00\x12\x33\n\x06update\x18\x02 \x01(\x0b\x32!.google.spanner.v1.Mutation.WriteH\x00\x12=\n\x10insert_or_update\x18\x03 \x01(\x0b\x32!.google.spanner.v1.Mutation.WriteH\x00\x12\x34\n\x07replace\x18\x04 \x01(\x0b\x32!.google.spanner.v1.Mutation.WriteH\x00\x12\x34\n\x06\x64\x65lete\x18\x05 \x01(\x0b\x32\".google.spanner.v1.Mutation.DeleteH\x00\x1aS\n\x05Write\x12\r\n\x05table\x18\x01 \x01(\t\x12\x0f\n\x07\x63olumns\x18\x02 \x03(\t\x12*\n\x06values\x18\x03 \x03(\x0b\x32\x1a.google.protobuf.ListValue\x1a\x43\n\x06\x44\x65lete\x12\r\n\x05table\x18\x01 \x01(\t\x12*\n\x07key_set\x18\x02 \x01(\x0b\x32\x19.google.spanner.v1.KeySetB\x0b\n\toperationB|\n\x15\x63om.google.spanner.v1B\rMutationProtoP\x01Z8google.golang.org/genproto/googleapis/spanner/v1;spanner\xaa\x02\x17Google.Cloud.Spanner.V1b\x06proto3') + , + dependencies=[google_dot_api_dot_annotations__pb2.DESCRIPTOR,google_dot_protobuf_dot_struct__pb2.DESCRIPTOR,google_dot_cloud_dot_spanner__v1_dot_proto_dot_keys__pb2.DESCRIPTOR,]) +_sym_db.RegisterFileDescriptor(DESCRIPTOR) + + + + +_MUTATION_WRITE = _descriptor.Descriptor( + name='Write', + full_name='google.spanner.v1.Mutation.Write', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='table', full_name='google.spanner.v1.Mutation.Write.table', index=0, + number=1, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='columns', full_name='google.spanner.v1.Mutation.Write.columns', index=1, + number=2, type=9, cpp_type=9, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='values', full_name='google.spanner.v1.Mutation.Write.values', index=2, + number=3, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto3', + extension_ranges=[], + oneofs=[ + ], + serialized_start=459, + serialized_end=542, +) + +_MUTATION_DELETE = _descriptor.Descriptor( + name='Delete', + full_name='google.spanner.v1.Mutation.Delete', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='table', full_name='google.spanner.v1.Mutation.Delete.table', index=0, + number=1, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='key_set', full_name='google.spanner.v1.Mutation.Delete.key_set', index=1, + number=2, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto3', + extension_ranges=[], + oneofs=[ + ], + serialized_start=544, + serialized_end=611, +) + +_MUTATION = _descriptor.Descriptor( + name='Mutation', + full_name='google.spanner.v1.Mutation', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='insert', full_name='google.spanner.v1.Mutation.insert', index=0, + number=1, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='update', full_name='google.spanner.v1.Mutation.update', index=1, + number=2, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='insert_or_update', full_name='google.spanner.v1.Mutation.insert_or_update', index=2, + number=3, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='replace', full_name='google.spanner.v1.Mutation.replace', index=3, + number=4, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='delete', full_name='google.spanner.v1.Mutation.delete', index=4, + number=5, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[_MUTATION_WRITE, _MUTATION_DELETE, ], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto3', + extension_ranges=[], + oneofs=[ + _descriptor.OneofDescriptor( + name='operation', full_name='google.spanner.v1.Mutation.operation', + index=0, containing_type=None, fields=[]), + ], + serialized_start=170, + serialized_end=624, +) + +_MUTATION_WRITE.fields_by_name['values'].message_type = google_dot_protobuf_dot_struct__pb2._LISTVALUE +_MUTATION_WRITE.containing_type = _MUTATION +_MUTATION_DELETE.fields_by_name['key_set'].message_type = google_dot_cloud_dot_spanner__v1_dot_proto_dot_keys__pb2._KEYSET +_MUTATION_DELETE.containing_type = _MUTATION +_MUTATION.fields_by_name['insert'].message_type = _MUTATION_WRITE +_MUTATION.fields_by_name['update'].message_type = _MUTATION_WRITE +_MUTATION.fields_by_name['insert_or_update'].message_type = _MUTATION_WRITE +_MUTATION.fields_by_name['replace'].message_type = _MUTATION_WRITE +_MUTATION.fields_by_name['delete'].message_type = _MUTATION_DELETE +_MUTATION.oneofs_by_name['operation'].fields.append( + _MUTATION.fields_by_name['insert']) +_MUTATION.fields_by_name['insert'].containing_oneof = _MUTATION.oneofs_by_name['operation'] +_MUTATION.oneofs_by_name['operation'].fields.append( + _MUTATION.fields_by_name['update']) +_MUTATION.fields_by_name['update'].containing_oneof = _MUTATION.oneofs_by_name['operation'] +_MUTATION.oneofs_by_name['operation'].fields.append( + _MUTATION.fields_by_name['insert_or_update']) +_MUTATION.fields_by_name['insert_or_update'].containing_oneof = _MUTATION.oneofs_by_name['operation'] +_MUTATION.oneofs_by_name['operation'].fields.append( + _MUTATION.fields_by_name['replace']) +_MUTATION.fields_by_name['replace'].containing_oneof = _MUTATION.oneofs_by_name['operation'] +_MUTATION.oneofs_by_name['operation'].fields.append( + _MUTATION.fields_by_name['delete']) +_MUTATION.fields_by_name['delete'].containing_oneof = _MUTATION.oneofs_by_name['operation'] +DESCRIPTOR.message_types_by_name['Mutation'] = _MUTATION + +Mutation = _reflection.GeneratedProtocolMessageType('Mutation', (_message.Message,), dict( + + Write = _reflection.GeneratedProtocolMessageType('Write', (_message.Message,), dict( + DESCRIPTOR = _MUTATION_WRITE, + __module__ = 'google.cloud.spanner_v1.proto.mutation_pb2' + , + __doc__ = """Arguments to [insert][google.spanner.v1.Mutation.insert], + [update][google.spanner.v1.Mutation.update], + [insert\_or\_update][google.spanner.v1.Mutation.insert\_or\_update], and + [replace][google.spanner.v1.Mutation.replace] operations. + """, + # @@protoc_insertion_point(class_scope:google.spanner.v1.Mutation.Write) + )) + , + + Delete = _reflection.GeneratedProtocolMessageType('Delete', (_message.Message,), dict( + DESCRIPTOR = _MUTATION_DELETE, + __module__ = 'google.cloud.spanner_v1.proto.mutation_pb2' + , + __doc__ = """Arguments to [delete][google.spanner.v1.Mutation.delete] operations. + """, + # @@protoc_insertion_point(class_scope:google.spanner.v1.Mutation.Delete) + )) + , + DESCRIPTOR = _MUTATION, + __module__ = 'google.cloud.spanner_v1.proto.mutation_pb2' + , + __doc__ = """A modification to one or more Cloud Spanner rows. Mutations can be + applied to a Cloud Spanner database by sending them in a + [Commit][google.spanner.v1.Spanner.Commit] call. + + + Attributes: + table: + Required. The table whose rows will be deleted. + columns: + The names of the columns in + [table][google.spanner.v1.Mutation.Write.table] to be written. + The list of columns must contain enough columns to allow Cloud + Spanner to derive values for all primary key columns in the + row(s) to be modified. + values: + The values to be written. ``values`` can contain more than one + list of values. If it does, then multiple rows are written, + one for each entry in ``values``. Each list in ``values`` must + have exactly as many entries as there are entries in + [columns][google.spanner.v1.Mutation.Write.columns] above. + Sending multiple lists is equivalent to sending multiple + ``Mutation``\ s, each containing one ``values`` entry and + repeating [table][google.spanner.v1.Mutation.Write.table] and + [columns][google.spanner.v1.Mutation.Write.columns]. + Individual values in each list are encoded as described + [here][google.spanner.v1.TypeCode]. + key_set: + Required. The primary keys of the rows within + [table][google.spanner.v1.Mutation.Delete.table] to delete. + operation: + Required. The operation to perform. + insert: + Insert new rows in a table. If any of the rows already exist, + the write or transaction fails with error ``ALREADY_EXISTS``. + update: + Update existing rows in a table. If any of the rows does not + already exist, the transaction fails with error ``NOT_FOUND``. + insert_or_update: + Like [insert][google.spanner.v1.Mutation.insert], except that + if the row already exists, then its column values are + overwritten with the ones provided. Any column values not + explicitly written are preserved. + replace: + Like [insert][google.spanner.v1.Mutation.insert], except that + if the row already exists, it is deleted, and the column + values provided are inserted instead. Unlike [insert\_or\_upda + te][google.spanner.v1.Mutation.insert\_or\_update], this means + any values not explicitly written become ``NULL``. + delete: + Delete rows from a table. Succeeds whether or not the named + rows were present. + """, + # @@protoc_insertion_point(class_scope:google.spanner.v1.Mutation) + )) +_sym_db.RegisterMessage(Mutation) +_sym_db.RegisterMessage(Mutation.Write) +_sym_db.RegisterMessage(Mutation.Delete) + + +DESCRIPTOR.has_options = True +DESCRIPTOR._options = _descriptor._ParseOptions(descriptor_pb2.FileOptions(), _b('\n\025com.google.spanner.v1B\rMutationProtoP\001Z8google.golang.org/genproto/googleapis/spanner/v1;spanner\252\002\027Google.Cloud.Spanner.V1')) +try: + # THESE ELEMENTS WILL BE DEPRECATED. + # Please use the generated *_pb2_grpc.py files instead. + import grpc + from grpc.beta import implementations as beta_implementations + from grpc.beta import interfaces as beta_interfaces + from grpc.framework.common import cardinality + from grpc.framework.interfaces.face import utilities as face_utilities +except ImportError: + pass +# @@protoc_insertion_point(module_scope) diff --git a/spanner/google/cloud/spanner_v1/proto/mutation_pb2_grpc.py b/spanner/google/cloud/spanner_v1/proto/mutation_pb2_grpc.py new file mode 100644 index 000000000000..a89435267cb2 --- /dev/null +++ b/spanner/google/cloud/spanner_v1/proto/mutation_pb2_grpc.py @@ -0,0 +1,3 @@ +# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! +import grpc + diff --git a/spanner/google/cloud/spanner_v1/proto/query_plan_pb2.py b/spanner/google/cloud/spanner_v1/proto/query_plan_pb2.py new file mode 100644 index 000000000000..cfa5bb03a4f5 --- /dev/null +++ b/spanner/google/cloud/spanner_v1/proto/query_plan_pb2.py @@ -0,0 +1,428 @@ +# Generated by the protocol buffer compiler. DO NOT EDIT! +# source: google/cloud/spanner_v1/proto/query_plan.proto + +import sys +_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) +from google.protobuf import descriptor as _descriptor +from google.protobuf import message as _message +from google.protobuf import reflection as _reflection +from google.protobuf import symbol_database as _symbol_database +from google.protobuf import descriptor_pb2 +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + + +from google.api import annotations_pb2 as google_dot_api_dot_annotations__pb2 +from google.protobuf import struct_pb2 as google_dot_protobuf_dot_struct__pb2 + + +DESCRIPTOR = _descriptor.FileDescriptor( + name='google/cloud/spanner_v1/proto/query_plan.proto', + package='google.spanner.v1', + syntax='proto3', + serialized_pb=_b('\n.google/cloud/spanner_v1/proto/query_plan.proto\x12\x11google.spanner.v1\x1a\x1cgoogle/api/annotations.proto\x1a\x1cgoogle/protobuf/struct.proto\"\xf8\x04\n\x08PlanNode\x12\r\n\x05index\x18\x01 \x01(\x05\x12.\n\x04kind\x18\x02 \x01(\x0e\x32 .google.spanner.v1.PlanNode.Kind\x12\x14\n\x0c\x64isplay_name\x18\x03 \x01(\t\x12:\n\x0b\x63hild_links\x18\x04 \x03(\x0b\x32%.google.spanner.v1.PlanNode.ChildLink\x12M\n\x14short_representation\x18\x05 \x01(\x0b\x32/.google.spanner.v1.PlanNode.ShortRepresentation\x12)\n\x08metadata\x18\x06 \x01(\x0b\x32\x17.google.protobuf.Struct\x12\x30\n\x0f\x65xecution_stats\x18\x07 \x01(\x0b\x32\x17.google.protobuf.Struct\x1a@\n\tChildLink\x12\x13\n\x0b\x63hild_index\x18\x01 \x01(\x05\x12\x0c\n\x04type\x18\x02 \x01(\t\x12\x10\n\x08variable\x18\x03 \x01(\t\x1a\xb2\x01\n\x13ShortRepresentation\x12\x13\n\x0b\x64\x65scription\x18\x01 \x01(\t\x12S\n\nsubqueries\x18\x02 \x03(\x0b\x32?.google.spanner.v1.PlanNode.ShortRepresentation.SubqueriesEntry\x1a\x31\n\x0fSubqueriesEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\x05:\x02\x38\x01\"8\n\x04Kind\x12\x14\n\x10KIND_UNSPECIFIED\x10\x00\x12\x0e\n\nRELATIONAL\x10\x01\x12\n\n\x06SCALAR\x10\x02\"<\n\tQueryPlan\x12/\n\nplan_nodes\x18\x01 \x03(\x0b\x32\x1b.google.spanner.v1.PlanNodeB}\n\x15\x63om.google.spanner.v1B\x0eQueryPlanProtoP\x01Z8google.golang.org/genproto/googleapis/spanner/v1;spanner\xaa\x02\x17Google.Cloud.Spanner.V1b\x06proto3') + , + dependencies=[google_dot_api_dot_annotations__pb2.DESCRIPTOR,google_dot_protobuf_dot_struct__pb2.DESCRIPTOR,]) +_sym_db.RegisterFileDescriptor(DESCRIPTOR) + + + +_PLANNODE_KIND = _descriptor.EnumDescriptor( + name='Kind', + full_name='google.spanner.v1.PlanNode.Kind', + filename=None, + file=DESCRIPTOR, + values=[ + _descriptor.EnumValueDescriptor( + name='KIND_UNSPECIFIED', index=0, number=0, + options=None, + type=None), + _descriptor.EnumValueDescriptor( + name='RELATIONAL', index=1, number=1, + options=None, + type=None), + _descriptor.EnumValueDescriptor( + name='SCALAR', index=2, number=2, + options=None, + type=None), + ], + containing_type=None, + options=None, + serialized_start=706, + serialized_end=762, +) +_sym_db.RegisterEnumDescriptor(_PLANNODE_KIND) + + +_PLANNODE_CHILDLINK = _descriptor.Descriptor( + name='ChildLink', + full_name='google.spanner.v1.PlanNode.ChildLink', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='child_index', full_name='google.spanner.v1.PlanNode.ChildLink.child_index', index=0, + number=1, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='type', full_name='google.spanner.v1.PlanNode.ChildLink.type', index=1, + number=2, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='variable', full_name='google.spanner.v1.PlanNode.ChildLink.variable', index=2, + number=3, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto3', + extension_ranges=[], + oneofs=[ + ], + serialized_start=459, + serialized_end=523, +) + +_PLANNODE_SHORTREPRESENTATION_SUBQUERIESENTRY = _descriptor.Descriptor( + name='SubqueriesEntry', + full_name='google.spanner.v1.PlanNode.ShortRepresentation.SubqueriesEntry', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='key', full_name='google.spanner.v1.PlanNode.ShortRepresentation.SubqueriesEntry.key', index=0, + number=1, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='value', full_name='google.spanner.v1.PlanNode.ShortRepresentation.SubqueriesEntry.value', index=1, + number=2, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=_descriptor._ParseOptions(descriptor_pb2.MessageOptions(), _b('8\001')), + is_extendable=False, + syntax='proto3', + extension_ranges=[], + oneofs=[ + ], + serialized_start=655, + serialized_end=704, +) + +_PLANNODE_SHORTREPRESENTATION = _descriptor.Descriptor( + name='ShortRepresentation', + full_name='google.spanner.v1.PlanNode.ShortRepresentation', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='description', full_name='google.spanner.v1.PlanNode.ShortRepresentation.description', index=0, + number=1, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='subqueries', full_name='google.spanner.v1.PlanNode.ShortRepresentation.subqueries', index=1, + number=2, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[_PLANNODE_SHORTREPRESENTATION_SUBQUERIESENTRY, ], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto3', + extension_ranges=[], + oneofs=[ + ], + serialized_start=526, + serialized_end=704, +) + +_PLANNODE = _descriptor.Descriptor( + name='PlanNode', + full_name='google.spanner.v1.PlanNode', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='index', full_name='google.spanner.v1.PlanNode.index', index=0, + number=1, type=5, cpp_type=1, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='kind', full_name='google.spanner.v1.PlanNode.kind', index=1, + number=2, type=14, cpp_type=8, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='display_name', full_name='google.spanner.v1.PlanNode.display_name', index=2, + number=3, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='child_links', full_name='google.spanner.v1.PlanNode.child_links', index=3, + number=4, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='short_representation', full_name='google.spanner.v1.PlanNode.short_representation', index=4, + number=5, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='metadata', full_name='google.spanner.v1.PlanNode.metadata', index=5, + number=6, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='execution_stats', full_name='google.spanner.v1.PlanNode.execution_stats', index=6, + number=7, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[_PLANNODE_CHILDLINK, _PLANNODE_SHORTREPRESENTATION, ], + enum_types=[ + _PLANNODE_KIND, + ], + options=None, + is_extendable=False, + syntax='proto3', + extension_ranges=[], + oneofs=[ + ], + serialized_start=130, + serialized_end=762, +) + + +_QUERYPLAN = _descriptor.Descriptor( + name='QueryPlan', + full_name='google.spanner.v1.QueryPlan', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='plan_nodes', full_name='google.spanner.v1.QueryPlan.plan_nodes', index=0, + number=1, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto3', + extension_ranges=[], + oneofs=[ + ], + serialized_start=764, + serialized_end=824, +) + +_PLANNODE_CHILDLINK.containing_type = _PLANNODE +_PLANNODE_SHORTREPRESENTATION_SUBQUERIESENTRY.containing_type = _PLANNODE_SHORTREPRESENTATION +_PLANNODE_SHORTREPRESENTATION.fields_by_name['subqueries'].message_type = _PLANNODE_SHORTREPRESENTATION_SUBQUERIESENTRY +_PLANNODE_SHORTREPRESENTATION.containing_type = _PLANNODE +_PLANNODE.fields_by_name['kind'].enum_type = _PLANNODE_KIND +_PLANNODE.fields_by_name['child_links'].message_type = _PLANNODE_CHILDLINK +_PLANNODE.fields_by_name['short_representation'].message_type = _PLANNODE_SHORTREPRESENTATION +_PLANNODE.fields_by_name['metadata'].message_type = google_dot_protobuf_dot_struct__pb2._STRUCT +_PLANNODE.fields_by_name['execution_stats'].message_type = google_dot_protobuf_dot_struct__pb2._STRUCT +_PLANNODE_KIND.containing_type = _PLANNODE +_QUERYPLAN.fields_by_name['plan_nodes'].message_type = _PLANNODE +DESCRIPTOR.message_types_by_name['PlanNode'] = _PLANNODE +DESCRIPTOR.message_types_by_name['QueryPlan'] = _QUERYPLAN + +PlanNode = _reflection.GeneratedProtocolMessageType('PlanNode', (_message.Message,), dict( + + ChildLink = _reflection.GeneratedProtocolMessageType('ChildLink', (_message.Message,), dict( + DESCRIPTOR = _PLANNODE_CHILDLINK, + __module__ = 'google.cloud.spanner_v1.proto.query_plan_pb2' + , + __doc__ = """Metadata associated with a parent-child relationship appearing in a + [PlanNode][google.spanner.v1.PlanNode]. + """, + # @@protoc_insertion_point(class_scope:google.spanner.v1.PlanNode.ChildLink) + )) + , + + ShortRepresentation = _reflection.GeneratedProtocolMessageType('ShortRepresentation', (_message.Message,), dict( + + SubqueriesEntry = _reflection.GeneratedProtocolMessageType('SubqueriesEntry', (_message.Message,), dict( + DESCRIPTOR = _PLANNODE_SHORTREPRESENTATION_SUBQUERIESENTRY, + __module__ = 'google.cloud.spanner_v1.proto.query_plan_pb2' + # @@protoc_insertion_point(class_scope:google.spanner.v1.PlanNode.ShortRepresentation.SubqueriesEntry) + )) + , + DESCRIPTOR = _PLANNODE_SHORTREPRESENTATION, + __module__ = 'google.cloud.spanner_v1.proto.query_plan_pb2' + , + __doc__ = """Condensed representation of a node and its subtree. Only present for + ``SCALAR`` [PlanNode(s)][google.spanner.v1.PlanNode]. + """, + # @@protoc_insertion_point(class_scope:google.spanner.v1.PlanNode.ShortRepresentation) + )) + , + DESCRIPTOR = _PLANNODE, + __module__ = 'google.cloud.spanner_v1.proto.query_plan_pb2' + , + __doc__ = """Node information for nodes appearing in a + [QueryPlan.plan\_nodes][google.spanner.v1.QueryPlan.plan\_nodes]. + + + Attributes: + child_index: + The node to which the link points. + type: + The type of the link. For example, in Hash Joins this could be + used to distinguish between the build child and the probe + child, or in the case of the child being an output variable, + to represent the tag associated with the output variable. + variable: + Only present if the child node is + [SCALAR][google.spanner.v1.PlanNode.Kind.SCALAR] and + corresponds to an output variable of the parent node. The + field carries the name of the output variable. For example, a + ``TableScan`` operator that reads rows from a table will have + child links to the ``SCALAR`` nodes representing the output + variables created for each column that is read by the + operator. The corresponding ``variable`` fields will be set to + the variable names assigned to the columns. + description: + A string representation of the expression subtree rooted at + this node. + subqueries: + A mapping of (subquery variable name) -> (subquery node id) + for cases where the ``description`` string of this node + references a ``SCALAR`` subquery contained in the expression + subtree rooted at this node. The referenced ``SCALAR`` + subquery may not necessarily be a direct child of this node. + index: + The ``PlanNode``'s index in [node + list][google.spanner.v1.QueryPlan.plan\_nodes]. + kind: + Used to determine the type of node. May be needed for + visualizing different kinds of nodes differently. For example, + If the node is a + [SCALAR][google.spanner.v1.PlanNode.Kind.SCALAR] node, it will + have a condensed representation which can be used to directly + embed a description of the node in its parent. + display_name: + The display name for the node. + child_links: + List of child node ``index``\ es and their relationship to + this parent. + short_representation: + Condensed representation for + [SCALAR][google.spanner.v1.PlanNode.Kind.SCALAR] nodes. + metadata: + Attributes relevant to the node contained in a group of key- + value pairs. For example, a Parameter Reference node could + have the following information in its metadata: :: { + "parameter_reference": "param1", "parameter_type": + "array" } + execution_stats: + The execution statistics associated with the node, contained + in a group of key-value pairs. Only present if the plan was + returned as a result of a profile query. For example, number + of executions, number of rows/time per execution etc. + """, + # @@protoc_insertion_point(class_scope:google.spanner.v1.PlanNode) + )) +_sym_db.RegisterMessage(PlanNode) +_sym_db.RegisterMessage(PlanNode.ChildLink) +_sym_db.RegisterMessage(PlanNode.ShortRepresentation) +_sym_db.RegisterMessage(PlanNode.ShortRepresentation.SubqueriesEntry) + +QueryPlan = _reflection.GeneratedProtocolMessageType('QueryPlan', (_message.Message,), dict( + DESCRIPTOR = _QUERYPLAN, + __module__ = 'google.cloud.spanner_v1.proto.query_plan_pb2' + , + __doc__ = """Contains an ordered list of nodes appearing in the query plan. + + + Attributes: + plan_nodes: + The nodes in the query plan. Plan nodes are returned in pre- + order starting with the plan root. Each + [PlanNode][google.spanner.v1.PlanNode]'s ``id`` corresponds to + its index in ``plan_nodes``. + """, + # @@protoc_insertion_point(class_scope:google.spanner.v1.QueryPlan) + )) +_sym_db.RegisterMessage(QueryPlan) + + +DESCRIPTOR.has_options = True +DESCRIPTOR._options = _descriptor._ParseOptions(descriptor_pb2.FileOptions(), _b('\n\025com.google.spanner.v1B\016QueryPlanProtoP\001Z8google.golang.org/genproto/googleapis/spanner/v1;spanner\252\002\027Google.Cloud.Spanner.V1')) +_PLANNODE_SHORTREPRESENTATION_SUBQUERIESENTRY.has_options = True +_PLANNODE_SHORTREPRESENTATION_SUBQUERIESENTRY._options = _descriptor._ParseOptions(descriptor_pb2.MessageOptions(), _b('8\001')) +try: + # THESE ELEMENTS WILL BE DEPRECATED. + # Please use the generated *_pb2_grpc.py files instead. + import grpc + from grpc.beta import implementations as beta_implementations + from grpc.beta import interfaces as beta_interfaces + from grpc.framework.common import cardinality + from grpc.framework.interfaces.face import utilities as face_utilities +except ImportError: + pass +# @@protoc_insertion_point(module_scope) diff --git a/spanner/google/cloud/spanner_v1/proto/query_plan_pb2_grpc.py b/spanner/google/cloud/spanner_v1/proto/query_plan_pb2_grpc.py new file mode 100644 index 000000000000..a89435267cb2 --- /dev/null +++ b/spanner/google/cloud/spanner_v1/proto/query_plan_pb2_grpc.py @@ -0,0 +1,3 @@ +# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! +import grpc + diff --git a/spanner/google/cloud/spanner_v1/proto/result_set_pb2.py b/spanner/google/cloud/spanner_v1/proto/result_set_pb2.py new file mode 100644 index 000000000000..6eac4bcd2f10 --- /dev/null +++ b/spanner/google/cloud/spanner_v1/proto/result_set_pb2.py @@ -0,0 +1,399 @@ +# Generated by the protocol buffer compiler. DO NOT EDIT! +# source: google/cloud/spanner_v1/proto/result_set.proto + +import sys +_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) +from google.protobuf import descriptor as _descriptor +from google.protobuf import message as _message +from google.protobuf import reflection as _reflection +from google.protobuf import symbol_database as _symbol_database +from google.protobuf import descriptor_pb2 +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + + +from google.api import annotations_pb2 as google_dot_api_dot_annotations__pb2 +from google.protobuf import struct_pb2 as google_dot_protobuf_dot_struct__pb2 +from google.cloud.spanner_v1.proto import query_plan_pb2 as google_dot_cloud_dot_spanner__v1_dot_proto_dot_query__plan__pb2 +from google.cloud.spanner_v1.proto import transaction_pb2 as google_dot_cloud_dot_spanner__v1_dot_proto_dot_transaction__pb2 +from google.cloud.spanner_v1.proto import type_pb2 as google_dot_cloud_dot_spanner__v1_dot_proto_dot_type__pb2 + + +DESCRIPTOR = _descriptor.FileDescriptor( + name='google/cloud/spanner_v1/proto/result_set.proto', + package='google.spanner.v1', + syntax='proto3', + serialized_pb=_b('\n.google/cloud/spanner_v1/proto/result_set.proto\x12\x11google.spanner.v1\x1a\x1cgoogle/api/annotations.proto\x1a\x1cgoogle/protobuf/struct.proto\x1a.google/cloud/spanner_v1/proto/query_plan.proto\x1a/google/cloud/spanner_v1/proto/transaction.proto\x1a(google/cloud/spanner_v1/proto/type.proto\"\x9f\x01\n\tResultSet\x12\x36\n\x08metadata\x18\x01 \x01(\x0b\x32$.google.spanner.v1.ResultSetMetadata\x12(\n\x04rows\x18\x02 \x03(\x0b\x32\x1a.google.protobuf.ListValue\x12\x30\n\x05stats\x18\x03 \x01(\x0b\x32!.google.spanner.v1.ResultSetStats\"\xd1\x01\n\x10PartialResultSet\x12\x36\n\x08metadata\x18\x01 \x01(\x0b\x32$.google.spanner.v1.ResultSetMetadata\x12&\n\x06values\x18\x02 \x03(\x0b\x32\x16.google.protobuf.Value\x12\x15\n\rchunked_value\x18\x03 \x01(\x08\x12\x14\n\x0cresume_token\x18\x04 \x01(\x0c\x12\x30\n\x05stats\x18\x05 \x01(\x0b\x32!.google.spanner.v1.ResultSetStats\"y\n\x11ResultSetMetadata\x12/\n\x08row_type\x18\x01 \x01(\x0b\x32\x1d.google.spanner.v1.StructType\x12\x33\n\x0btransaction\x18\x02 \x01(\x0b\x32\x1e.google.spanner.v1.Transaction\"p\n\x0eResultSetStats\x12\x30\n\nquery_plan\x18\x01 \x01(\x0b\x32\x1c.google.spanner.v1.QueryPlan\x12,\n\x0bquery_stats\x18\x02 \x01(\x0b\x32\x17.google.protobuf.StructB}\n\x15\x63om.google.spanner.v1B\x0eResultSetProtoP\x01Z8google.golang.org/genproto/googleapis/spanner/v1;spanner\xaa\x02\x17Google.Cloud.Spanner.V1b\x06proto3') + , + dependencies=[google_dot_api_dot_annotations__pb2.DESCRIPTOR,google_dot_protobuf_dot_struct__pb2.DESCRIPTOR,google_dot_cloud_dot_spanner__v1_dot_proto_dot_query__plan__pb2.DESCRIPTOR,google_dot_cloud_dot_spanner__v1_dot_proto_dot_transaction__pb2.DESCRIPTOR,google_dot_cloud_dot_spanner__v1_dot_proto_dot_type__pb2.DESCRIPTOR,]) +_sym_db.RegisterFileDescriptor(DESCRIPTOR) + + + + +_RESULTSET = _descriptor.Descriptor( + name='ResultSet', + full_name='google.spanner.v1.ResultSet', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='metadata', full_name='google.spanner.v1.ResultSet.metadata', index=0, + number=1, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='rows', full_name='google.spanner.v1.ResultSet.rows', index=1, + number=2, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='stats', full_name='google.spanner.v1.ResultSet.stats', index=2, + number=3, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto3', + extension_ranges=[], + oneofs=[ + ], + serialized_start=269, + serialized_end=428, +) + + +_PARTIALRESULTSET = _descriptor.Descriptor( + name='PartialResultSet', + full_name='google.spanner.v1.PartialResultSet', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='metadata', full_name='google.spanner.v1.PartialResultSet.metadata', index=0, + number=1, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='values', full_name='google.spanner.v1.PartialResultSet.values', index=1, + number=2, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='chunked_value', full_name='google.spanner.v1.PartialResultSet.chunked_value', index=2, + number=3, type=8, cpp_type=7, label=1, + has_default_value=False, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='resume_token', full_name='google.spanner.v1.PartialResultSet.resume_token', index=3, + number=4, type=12, cpp_type=9, label=1, + has_default_value=False, default_value=_b(""), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='stats', full_name='google.spanner.v1.PartialResultSet.stats', index=4, + number=5, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto3', + extension_ranges=[], + oneofs=[ + ], + serialized_start=431, + serialized_end=640, +) + + +_RESULTSETMETADATA = _descriptor.Descriptor( + name='ResultSetMetadata', + full_name='google.spanner.v1.ResultSetMetadata', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='row_type', full_name='google.spanner.v1.ResultSetMetadata.row_type', index=0, + number=1, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='transaction', full_name='google.spanner.v1.ResultSetMetadata.transaction', index=1, + number=2, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto3', + extension_ranges=[], + oneofs=[ + ], + serialized_start=642, + serialized_end=763, +) + + +_RESULTSETSTATS = _descriptor.Descriptor( + name='ResultSetStats', + full_name='google.spanner.v1.ResultSetStats', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='query_plan', full_name='google.spanner.v1.ResultSetStats.query_plan', index=0, + number=1, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='query_stats', full_name='google.spanner.v1.ResultSetStats.query_stats', index=1, + number=2, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto3', + extension_ranges=[], + oneofs=[ + ], + serialized_start=765, + serialized_end=877, +) + +_RESULTSET.fields_by_name['metadata'].message_type = _RESULTSETMETADATA +_RESULTSET.fields_by_name['rows'].message_type = google_dot_protobuf_dot_struct__pb2._LISTVALUE +_RESULTSET.fields_by_name['stats'].message_type = _RESULTSETSTATS +_PARTIALRESULTSET.fields_by_name['metadata'].message_type = _RESULTSETMETADATA +_PARTIALRESULTSET.fields_by_name['values'].message_type = google_dot_protobuf_dot_struct__pb2._VALUE +_PARTIALRESULTSET.fields_by_name['stats'].message_type = _RESULTSETSTATS +_RESULTSETMETADATA.fields_by_name['row_type'].message_type = google_dot_cloud_dot_spanner__v1_dot_proto_dot_type__pb2._STRUCTTYPE +_RESULTSETMETADATA.fields_by_name['transaction'].message_type = google_dot_cloud_dot_spanner__v1_dot_proto_dot_transaction__pb2._TRANSACTION +_RESULTSETSTATS.fields_by_name['query_plan'].message_type = google_dot_cloud_dot_spanner__v1_dot_proto_dot_query__plan__pb2._QUERYPLAN +_RESULTSETSTATS.fields_by_name['query_stats'].message_type = google_dot_protobuf_dot_struct__pb2._STRUCT +DESCRIPTOR.message_types_by_name['ResultSet'] = _RESULTSET +DESCRIPTOR.message_types_by_name['PartialResultSet'] = _PARTIALRESULTSET +DESCRIPTOR.message_types_by_name['ResultSetMetadata'] = _RESULTSETMETADATA +DESCRIPTOR.message_types_by_name['ResultSetStats'] = _RESULTSETSTATS + +ResultSet = _reflection.GeneratedProtocolMessageType('ResultSet', (_message.Message,), dict( + DESCRIPTOR = _RESULTSET, + __module__ = 'google.cloud.spanner_v1.proto.result_set_pb2' + , + __doc__ = """Results from [Read][google.spanner.v1.Spanner.Read] or + [ExecuteSql][google.spanner.v1.Spanner.ExecuteSql]. + + + Attributes: + metadata: + Metadata about the result set, such as row type information. + rows: + Each element in ``rows`` is a row whose format is defined by [ + metadata.row\_type][google.spanner.v1.ResultSetMetadata.row\_t + ype]. The ith element in each row matches the ith field in [me + tadata.row\_type][google.spanner.v1.ResultSetMetadata.row\_typ + e]. Elements are encoded based on type as described + [here][google.spanner.v1.TypeCode]. + stats: + Query plan and execution statistics for the query that + produced this result set. These can be requested by setting [E + xecuteSqlRequest.query\_mode][google.spanner.v1.ExecuteSqlRequ + est.query\_mode]. + """, + # @@protoc_insertion_point(class_scope:google.spanner.v1.ResultSet) + )) +_sym_db.RegisterMessage(ResultSet) + +PartialResultSet = _reflection.GeneratedProtocolMessageType('PartialResultSet', (_message.Message,), dict( + DESCRIPTOR = _PARTIALRESULTSET, + __module__ = 'google.cloud.spanner_v1.proto.result_set_pb2' + , + __doc__ = """Partial results from a streaming read or SQL query. Streaming reads and + SQL queries better tolerate large result sets, large rows, and large + values, but are a little trickier to consume. + + + Attributes: + metadata: + Metadata about the result set, such as row type information. + Only present in the first response. + values: + A streamed result set consists of a stream of values, which + might be split into many ``PartialResultSet`` messages to + accommodate large rows and/or large values. Every N complete + values defines a row, where N is equal to the number of + entries in [metadata.row\_type.fields][google.spanner.v1.Struc + tType.fields]. Most values are encoded based on type as + described [here][google.spanner.v1.TypeCode]. It is possible + that the last value in values is "chunked", meaning that the + rest of the value is sent in subsequent ``PartialResultSet``\ + (s). This is denoted by the [chunked\_value][google.spanner.v1 + .PartialResultSet.chunked\_value] field. Two or more chunked + values can be merged to form a complete value as follows: - + ``bool/number/null``: cannot be chunked - ``string``: + concatenate the strings - ``list``: concatenate the lists. If + the last element in a list is a ``string``, ``list``, or + ``object``, merge it with the first element in the next + list by applying these rules recursively. - ``object``: + concatenate the (field name, field value) pairs. If a field + name is duplicated, then apply these rules recursively to + merge the field values. Some examples of merging: :: + # Strings are concatenated. "foo", "bar" => "foobar" + # Lists of non-strings are concatenated. [2, 3], [4] => + [2, 3, 4] # Lists are concatenated, but the last and + first elements are merged # because they are strings. + ["a", "b"], ["c", "d"] => ["a", "bc", "d"] # Lists are + concatenated, but the last and first elements are merged # + because they are lists. Recursively, the last and first + elements # of the inner lists are merged because they are + strings. ["a", ["b", "c"]], [["d"], "e"] => ["a", ["b", + "cd"], "e"] # Non-overlapping object fields are combined. + {"a": "1"}, {"b": "2"} => {"a": "1", "b": 2"} # + Overlapping object fields are merged. {"a": "1"}, {"a": + "2"} => {"a": "12"} # Examples of merging objects + containing lists of strings. {"a": ["1"]}, {"a": ["2"]} => + {"a": ["12"]} For a more complete example, suppose a + streaming SQL query is yielding a result set whose rows + contain a single string field. The following + ``PartialResultSet``\ s might be yielded: :: { + "metadata": { ... } "values": ["Hello", "W"] + "chunked_value": true "resume_token": "Af65..." } + { "values": ["orl"] "chunked_value": true + "resume_token": "Bqp2..." } { "values": ["d"] + "resume_token": "Zx1B..." } This sequence of + ``PartialResultSet``\ s encodes two rows, one containing the + field value ``"Hello"``, and a second containing the field + value ``"World" = "W" + "orl" + "d"``. + chunked_value: + If true, then the final value in + [values][google.spanner.v1.PartialResultSet.values] is + chunked, and must be combined with more values from subsequent + ``PartialResultSet``\ s to obtain a complete field value. + resume_token: + Streaming calls might be interrupted for a variety of reasons, + such as TCP connection loss. If this occurs, the stream of + results can be resumed by re-sending the original request and + including ``resume_token``. Note that executing any other + transaction in the same session invalidates the token. + stats: + Query plan and execution statistics for the query that + produced this streaming result set. These can be requested by + setting [ExecuteSqlRequest.query\_mode][google.spanner.v1.Exec + uteSqlRequest.query\_mode] and are sent only once with the + last response in the stream. + """, + # @@protoc_insertion_point(class_scope:google.spanner.v1.PartialResultSet) + )) +_sym_db.RegisterMessage(PartialResultSet) + +ResultSetMetadata = _reflection.GeneratedProtocolMessageType('ResultSetMetadata', (_message.Message,), dict( + DESCRIPTOR = _RESULTSETMETADATA, + __module__ = 'google.cloud.spanner_v1.proto.result_set_pb2' + , + __doc__ = """Metadata about a [ResultSet][google.spanner.v1.ResultSet] or + [PartialResultSet][google.spanner.v1.PartialResultSet]. + + + Attributes: + row_type: + Indicates the field names and types for the rows in the result + set. For example, a SQL query like ``"SELECT UserId, UserName + FROM Users"`` could return a ``row_type`` value like: :: + "fields": [ { "name": "UserId", "type": { "code": + "INT64" } }, { "name": "UserName", "type": { "code": + "STRING" } }, ] + transaction: + If the read or SQL query began a transaction as a side-effect, + the information about the new transaction is yielded here. + """, + # @@protoc_insertion_point(class_scope:google.spanner.v1.ResultSetMetadata) + )) +_sym_db.RegisterMessage(ResultSetMetadata) + +ResultSetStats = _reflection.GeneratedProtocolMessageType('ResultSetStats', (_message.Message,), dict( + DESCRIPTOR = _RESULTSETSTATS, + __module__ = 'google.cloud.spanner_v1.proto.result_set_pb2' + , + __doc__ = """Additional statistics about a [ResultSet][google.spanner.v1.ResultSet] + or [PartialResultSet][google.spanner.v1.PartialResultSet]. + + + Attributes: + query_plan: + [QueryPlan][google.spanner.v1.QueryPlan] for the query + associated with this result. + query_stats: + Aggregated statistics from the execution of the query. Only + present when the query is profiled. For example, a query could + return the statistics as follows: :: { + "rows_returned": "3", "elapsed_time": "1.22 secs", + "cpu_time": "1.19 secs" } + """, + # @@protoc_insertion_point(class_scope:google.spanner.v1.ResultSetStats) + )) +_sym_db.RegisterMessage(ResultSetStats) + + +DESCRIPTOR.has_options = True +DESCRIPTOR._options = _descriptor._ParseOptions(descriptor_pb2.FileOptions(), _b('\n\025com.google.spanner.v1B\016ResultSetProtoP\001Z8google.golang.org/genproto/googleapis/spanner/v1;spanner\252\002\027Google.Cloud.Spanner.V1')) +try: + # THESE ELEMENTS WILL BE DEPRECATED. + # Please use the generated *_pb2_grpc.py files instead. + import grpc + from grpc.beta import implementations as beta_implementations + from grpc.beta import interfaces as beta_interfaces + from grpc.framework.common import cardinality + from grpc.framework.interfaces.face import utilities as face_utilities +except ImportError: + pass +# @@protoc_insertion_point(module_scope) diff --git a/spanner/google/cloud/spanner_v1/proto/result_set_pb2_grpc.py b/spanner/google/cloud/spanner_v1/proto/result_set_pb2_grpc.py new file mode 100644 index 000000000000..a89435267cb2 --- /dev/null +++ b/spanner/google/cloud/spanner_v1/proto/result_set_pb2_grpc.py @@ -0,0 +1,3 @@ +# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! +import grpc + diff --git a/spanner/google/cloud/spanner_v1/proto/spanner_pb2.py b/spanner/google/cloud/spanner_v1/proto/spanner_pb2.py new file mode 100644 index 000000000000..658bd4117e47 --- /dev/null +++ b/spanner/google/cloud/spanner_v1/proto/spanner_pb2.py @@ -0,0 +1,1466 @@ +# Generated by the protocol buffer compiler. DO NOT EDIT! +# source: google/cloud/spanner_v1/proto/spanner.proto + +import sys +_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) +from google.protobuf import descriptor as _descriptor +from google.protobuf import message as _message +from google.protobuf import reflection as _reflection +from google.protobuf import symbol_database as _symbol_database +from google.protobuf import descriptor_pb2 +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + + +from google.api import annotations_pb2 as google_dot_api_dot_annotations__pb2 +from google.api import auth_pb2 as google_dot_api_dot_auth__pb2 +from google.protobuf import empty_pb2 as google_dot_protobuf_dot_empty__pb2 +from google.protobuf import struct_pb2 as google_dot_protobuf_dot_struct__pb2 +from google.protobuf import timestamp_pb2 as google_dot_protobuf_dot_timestamp__pb2 +from google.cloud.spanner_v1.proto import keys_pb2 as google_dot_cloud_dot_spanner__v1_dot_proto_dot_keys__pb2 +from google.cloud.spanner_v1.proto import mutation_pb2 as google_dot_cloud_dot_spanner__v1_dot_proto_dot_mutation__pb2 +from google.cloud.spanner_v1.proto import result_set_pb2 as google_dot_cloud_dot_spanner__v1_dot_proto_dot_result__set__pb2 +from google.cloud.spanner_v1.proto import transaction_pb2 as google_dot_cloud_dot_spanner__v1_dot_proto_dot_transaction__pb2 +from google.cloud.spanner_v1.proto import type_pb2 as google_dot_cloud_dot_spanner__v1_dot_proto_dot_type__pb2 + + +DESCRIPTOR = _descriptor.FileDescriptor( + name='google/cloud/spanner_v1/proto/spanner.proto', + package='google.spanner.v1', + syntax='proto3', + serialized_pb=_b('\n+google/cloud/spanner_v1/proto/spanner.proto\x12\x11google.spanner.v1\x1a\x1cgoogle/api/annotations.proto\x1a\x15google/api/auth.proto\x1a\x1bgoogle/protobuf/empty.proto\x1a\x1cgoogle/protobuf/struct.proto\x1a\x1fgoogle/protobuf/timestamp.proto\x1a(google/cloud/spanner_v1/proto/keys.proto\x1a,google/cloud/spanner_v1/proto/mutation.proto\x1a.google/cloud/spanner_v1/proto/result_set.proto\x1a/google/cloud/spanner_v1/proto/transaction.proto\x1a(google/cloud/spanner_v1/proto/type.proto\"(\n\x14\x43reateSessionRequest\x12\x10\n\x08\x64\x61tabase\x18\x01 \x01(\t\"\x17\n\x07Session\x12\x0c\n\x04name\x18\x01 \x01(\t\"!\n\x11GetSessionRequest\x12\x0c\n\x04name\x18\x01 \x01(\t\"$\n\x14\x44\x65leteSessionRequest\x12\x0c\n\x04name\x18\x01 \x01(\t\"\xb8\x03\n\x11\x45xecuteSqlRequest\x12\x0f\n\x07session\x18\x01 \x01(\t\x12;\n\x0btransaction\x18\x02 \x01(\x0b\x32&.google.spanner.v1.TransactionSelector\x12\x0b\n\x03sql\x18\x03 \x01(\t\x12\'\n\x06params\x18\x04 \x01(\x0b\x32\x17.google.protobuf.Struct\x12I\n\x0bparam_types\x18\x05 \x03(\x0b\x32\x34.google.spanner.v1.ExecuteSqlRequest.ParamTypesEntry\x12\x14\n\x0cresume_token\x18\x06 \x01(\x0c\x12\x42\n\nquery_mode\x18\x07 \x01(\x0e\x32..google.spanner.v1.ExecuteSqlRequest.QueryMode\x1aJ\n\x0fParamTypesEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12&\n\x05value\x18\x02 \x01(\x0b\x32\x17.google.spanner.v1.Type:\x02\x38\x01\".\n\tQueryMode\x12\n\n\x06NORMAL\x10\x00\x12\x08\n\x04PLAN\x10\x01\x12\x0b\n\x07PROFILE\x10\x02\"\xdb\x01\n\x0bReadRequest\x12\x0f\n\x07session\x18\x01 \x01(\t\x12;\n\x0btransaction\x18\x02 \x01(\x0b\x32&.google.spanner.v1.TransactionSelector\x12\r\n\x05table\x18\x03 \x01(\t\x12\r\n\x05index\x18\x04 \x01(\t\x12\x0f\n\x07\x63olumns\x18\x05 \x03(\t\x12*\n\x07key_set\x18\x06 \x01(\x0b\x32\x19.google.spanner.v1.KeySet\x12\r\n\x05limit\x18\x08 \x01(\x03\x12\x14\n\x0cresume_token\x18\t \x01(\x0c\"b\n\x17\x42\x65ginTransactionRequest\x12\x0f\n\x07session\x18\x01 \x01(\t\x12\x36\n\x07options\x18\x02 \x01(\x0b\x32%.google.spanner.v1.TransactionOptions\"\xc2\x01\n\rCommitRequest\x12\x0f\n\x07session\x18\x01 \x01(\t\x12\x18\n\x0etransaction_id\x18\x02 \x01(\x0cH\x00\x12G\n\x16single_use_transaction\x18\x03 \x01(\x0b\x32%.google.spanner.v1.TransactionOptionsH\x00\x12.\n\tmutations\x18\x04 \x03(\x0b\x32\x1b.google.spanner.v1.MutationB\r\n\x0btransaction\"F\n\x0e\x43ommitResponse\x12\x34\n\x10\x63ommit_timestamp\x18\x01 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\":\n\x0fRollbackRequest\x12\x0f\n\x07session\x18\x01 \x01(\t\x12\x16\n\x0etransaction_id\x18\x02 \x01(\x0c\x32\xe9\x0c\n\x07Spanner\x12\x98\x01\n\rCreateSession\x12\'.google.spanner.v1.CreateSessionRequest\x1a\x1a.google.spanner.v1.Session\"B\x82\xd3\xe4\x93\x02<\":/v1/{database=projects/*/instances/*/databases/*}/sessions\x12\x90\x01\n\nGetSession\x12$.google.spanner.v1.GetSessionRequest\x1a\x1a.google.spanner.v1.Session\"@\x82\xd3\xe4\x93\x02:\x12\x38/v1/{name=projects/*/instances/*/databases/*/sessions/*}\x12\x92\x01\n\rDeleteSession\x12\'.google.spanner.v1.DeleteSessionRequest\x1a\x16.google.protobuf.Empty\"@\x82\xd3\xe4\x93\x02:*8/v1/{name=projects/*/instances/*/databases/*/sessions/*}\x12\xa3\x01\n\nExecuteSql\x12$.google.spanner.v1.ExecuteSqlRequest\x1a\x1c.google.spanner.v1.ResultSet\"Q\x82\xd3\xe4\x93\x02K\"F/v1/{session=projects/*/instances/*/databases/*/sessions/*}:executeSql:\x01*\x12\xbe\x01\n\x13\x45xecuteStreamingSql\x12$.google.spanner.v1.ExecuteSqlRequest\x1a#.google.spanner.v1.PartialResultSet\"Z\x82\xd3\xe4\x93\x02T\"O/v1/{session=projects/*/instances/*/databases/*/sessions/*}:executeStreamingSql:\x01*0\x01\x12\x91\x01\n\x04Read\x12\x1e.google.spanner.v1.ReadRequest\x1a\x1c.google.spanner.v1.ResultSet\"K\x82\xd3\xe4\x93\x02\x45\"@/v1/{session=projects/*/instances/*/databases/*/sessions/*}:read:\x01*\x12\xac\x01\n\rStreamingRead\x12\x1e.google.spanner.v1.ReadRequest\x1a#.google.spanner.v1.PartialResultSet\"T\x82\xd3\xe4\x93\x02N\"I/v1/{session=projects/*/instances/*/databases/*/sessions/*}:streamingRead:\x01*0\x01\x12\xb7\x01\n\x10\x42\x65ginTransaction\x12*.google.spanner.v1.BeginTransactionRequest\x1a\x1e.google.spanner.v1.Transaction\"W\x82\xd3\xe4\x93\x02Q\"L/v1/{session=projects/*/instances/*/databases/*/sessions/*}:beginTransaction:\x01*\x12\x9c\x01\n\x06\x43ommit\x12 .google.spanner.v1.CommitRequest\x1a!.google.spanner.v1.CommitResponse\"M\x82\xd3\xe4\x93\x02G\"B/v1/{session=projects/*/instances/*/databases/*/sessions/*}:commit:\x01*\x12\x97\x01\n\x08Rollback\x12\".google.spanner.v1.RollbackRequest\x1a\x16.google.protobuf.Empty\"O\x82\xd3\xe4\x93\x02I\"D/v1/{session=projects/*/instances/*/databases/*/sessions/*}:rollback:\x01*B{\n\x15\x63om.google.spanner.v1B\x0cSpannerProtoP\x01Z8google.golang.org/genproto/googleapis/spanner/v1;spanner\xaa\x02\x17Google.Cloud.Spanner.V1b\x06proto3') + , + dependencies=[google_dot_api_dot_annotations__pb2.DESCRIPTOR,google_dot_api_dot_auth__pb2.DESCRIPTOR,google_dot_protobuf_dot_empty__pb2.DESCRIPTOR,google_dot_protobuf_dot_struct__pb2.DESCRIPTOR,google_dot_protobuf_dot_timestamp__pb2.DESCRIPTOR,google_dot_cloud_dot_spanner__v1_dot_proto_dot_keys__pb2.DESCRIPTOR,google_dot_cloud_dot_spanner__v1_dot_proto_dot_mutation__pb2.DESCRIPTOR,google_dot_cloud_dot_spanner__v1_dot_proto_dot_result__set__pb2.DESCRIPTOR,google_dot_cloud_dot_spanner__v1_dot_proto_dot_transaction__pb2.DESCRIPTOR,google_dot_cloud_dot_spanner__v1_dot_proto_dot_type__pb2.DESCRIPTOR,]) +_sym_db.RegisterFileDescriptor(DESCRIPTOR) + + + +_EXECUTESQLREQUEST_QUERYMODE = _descriptor.EnumDescriptor( + name='QueryMode', + full_name='google.spanner.v1.ExecuteSqlRequest.QueryMode', + filename=None, + file=DESCRIPTOR, + values=[ + _descriptor.EnumValueDescriptor( + name='NORMAL', index=0, number=0, + options=None, + type=None), + _descriptor.EnumValueDescriptor( + name='PLAN', index=1, number=1, + options=None, + type=None), + _descriptor.EnumValueDescriptor( + name='PROFILE', index=2, number=2, + options=None, + type=None), + ], + containing_type=None, + options=None, + serialized_start=973, + serialized_end=1019, +) +_sym_db.RegisterEnumDescriptor(_EXECUTESQLREQUEST_QUERYMODE) + + +_CREATESESSIONREQUEST = _descriptor.Descriptor( + name='CreateSessionRequest', + full_name='google.spanner.v1.CreateSessionRequest', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='database', full_name='google.spanner.v1.CreateSessionRequest.database', index=0, + number=1, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto3', + extension_ranges=[], + oneofs=[ + ], + serialized_start=438, + serialized_end=478, +) + + +_SESSION = _descriptor.Descriptor( + name='Session', + full_name='google.spanner.v1.Session', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='name', full_name='google.spanner.v1.Session.name', index=0, + number=1, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto3', + extension_ranges=[], + oneofs=[ + ], + serialized_start=480, + serialized_end=503, +) + + +_GETSESSIONREQUEST = _descriptor.Descriptor( + name='GetSessionRequest', + full_name='google.spanner.v1.GetSessionRequest', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='name', full_name='google.spanner.v1.GetSessionRequest.name', index=0, + number=1, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto3', + extension_ranges=[], + oneofs=[ + ], + serialized_start=505, + serialized_end=538, +) + + +_DELETESESSIONREQUEST = _descriptor.Descriptor( + name='DeleteSessionRequest', + full_name='google.spanner.v1.DeleteSessionRequest', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='name', full_name='google.spanner.v1.DeleteSessionRequest.name', index=0, + number=1, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto3', + extension_ranges=[], + oneofs=[ + ], + serialized_start=540, + serialized_end=576, +) + + +_EXECUTESQLREQUEST_PARAMTYPESENTRY = _descriptor.Descriptor( + name='ParamTypesEntry', + full_name='google.spanner.v1.ExecuteSqlRequest.ParamTypesEntry', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='key', full_name='google.spanner.v1.ExecuteSqlRequest.ParamTypesEntry.key', index=0, + number=1, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='value', full_name='google.spanner.v1.ExecuteSqlRequest.ParamTypesEntry.value', index=1, + number=2, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=_descriptor._ParseOptions(descriptor_pb2.MessageOptions(), _b('8\001')), + is_extendable=False, + syntax='proto3', + extension_ranges=[], + oneofs=[ + ], + serialized_start=897, + serialized_end=971, +) + +_EXECUTESQLREQUEST = _descriptor.Descriptor( + name='ExecuteSqlRequest', + full_name='google.spanner.v1.ExecuteSqlRequest', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='session', full_name='google.spanner.v1.ExecuteSqlRequest.session', index=0, + number=1, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='transaction', full_name='google.spanner.v1.ExecuteSqlRequest.transaction', index=1, + number=2, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='sql', full_name='google.spanner.v1.ExecuteSqlRequest.sql', index=2, + number=3, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='params', full_name='google.spanner.v1.ExecuteSqlRequest.params', index=3, + number=4, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='param_types', full_name='google.spanner.v1.ExecuteSqlRequest.param_types', index=4, + number=5, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='resume_token', full_name='google.spanner.v1.ExecuteSqlRequest.resume_token', index=5, + number=6, type=12, cpp_type=9, label=1, + has_default_value=False, default_value=_b(""), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='query_mode', full_name='google.spanner.v1.ExecuteSqlRequest.query_mode', index=6, + number=7, type=14, cpp_type=8, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[_EXECUTESQLREQUEST_PARAMTYPESENTRY, ], + enum_types=[ + _EXECUTESQLREQUEST_QUERYMODE, + ], + options=None, + is_extendable=False, + syntax='proto3', + extension_ranges=[], + oneofs=[ + ], + serialized_start=579, + serialized_end=1019, +) + + +_READREQUEST = _descriptor.Descriptor( + name='ReadRequest', + full_name='google.spanner.v1.ReadRequest', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='session', full_name='google.spanner.v1.ReadRequest.session', index=0, + number=1, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='transaction', full_name='google.spanner.v1.ReadRequest.transaction', index=1, + number=2, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='table', full_name='google.spanner.v1.ReadRequest.table', index=2, + number=3, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='index', full_name='google.spanner.v1.ReadRequest.index', index=3, + number=4, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='columns', full_name='google.spanner.v1.ReadRequest.columns', index=4, + number=5, type=9, cpp_type=9, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='key_set', full_name='google.spanner.v1.ReadRequest.key_set', index=5, + number=6, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='limit', full_name='google.spanner.v1.ReadRequest.limit', index=6, + number=8, type=3, cpp_type=2, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='resume_token', full_name='google.spanner.v1.ReadRequest.resume_token', index=7, + number=9, type=12, cpp_type=9, label=1, + has_default_value=False, default_value=_b(""), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto3', + extension_ranges=[], + oneofs=[ + ], + serialized_start=1022, + serialized_end=1241, +) + + +_BEGINTRANSACTIONREQUEST = _descriptor.Descriptor( + name='BeginTransactionRequest', + full_name='google.spanner.v1.BeginTransactionRequest', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='session', full_name='google.spanner.v1.BeginTransactionRequest.session', index=0, + number=1, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='options', full_name='google.spanner.v1.BeginTransactionRequest.options', index=1, + number=2, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto3', + extension_ranges=[], + oneofs=[ + ], + serialized_start=1243, + serialized_end=1341, +) + + +_COMMITREQUEST = _descriptor.Descriptor( + name='CommitRequest', + full_name='google.spanner.v1.CommitRequest', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='session', full_name='google.spanner.v1.CommitRequest.session', index=0, + number=1, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='transaction_id', full_name='google.spanner.v1.CommitRequest.transaction_id', index=1, + number=2, type=12, cpp_type=9, label=1, + has_default_value=False, default_value=_b(""), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='single_use_transaction', full_name='google.spanner.v1.CommitRequest.single_use_transaction', index=2, + number=3, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='mutations', full_name='google.spanner.v1.CommitRequest.mutations', index=3, + number=4, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto3', + extension_ranges=[], + oneofs=[ + _descriptor.OneofDescriptor( + name='transaction', full_name='google.spanner.v1.CommitRequest.transaction', + index=0, containing_type=None, fields=[]), + ], + serialized_start=1344, + serialized_end=1538, +) + + +_COMMITRESPONSE = _descriptor.Descriptor( + name='CommitResponse', + full_name='google.spanner.v1.CommitResponse', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='commit_timestamp', full_name='google.spanner.v1.CommitResponse.commit_timestamp', index=0, + number=1, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto3', + extension_ranges=[], + oneofs=[ + ], + serialized_start=1540, + serialized_end=1610, +) + + +_ROLLBACKREQUEST = _descriptor.Descriptor( + name='RollbackRequest', + full_name='google.spanner.v1.RollbackRequest', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='session', full_name='google.spanner.v1.RollbackRequest.session', index=0, + number=1, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='transaction_id', full_name='google.spanner.v1.RollbackRequest.transaction_id', index=1, + number=2, type=12, cpp_type=9, label=1, + has_default_value=False, default_value=_b(""), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto3', + extension_ranges=[], + oneofs=[ + ], + serialized_start=1612, + serialized_end=1670, +) + +_EXECUTESQLREQUEST_PARAMTYPESENTRY.fields_by_name['value'].message_type = google_dot_cloud_dot_spanner__v1_dot_proto_dot_type__pb2._TYPE +_EXECUTESQLREQUEST_PARAMTYPESENTRY.containing_type = _EXECUTESQLREQUEST +_EXECUTESQLREQUEST.fields_by_name['transaction'].message_type = google_dot_cloud_dot_spanner__v1_dot_proto_dot_transaction__pb2._TRANSACTIONSELECTOR +_EXECUTESQLREQUEST.fields_by_name['params'].message_type = google_dot_protobuf_dot_struct__pb2._STRUCT +_EXECUTESQLREQUEST.fields_by_name['param_types'].message_type = _EXECUTESQLREQUEST_PARAMTYPESENTRY +_EXECUTESQLREQUEST.fields_by_name['query_mode'].enum_type = _EXECUTESQLREQUEST_QUERYMODE +_EXECUTESQLREQUEST_QUERYMODE.containing_type = _EXECUTESQLREQUEST +_READREQUEST.fields_by_name['transaction'].message_type = google_dot_cloud_dot_spanner__v1_dot_proto_dot_transaction__pb2._TRANSACTIONSELECTOR +_READREQUEST.fields_by_name['key_set'].message_type = google_dot_cloud_dot_spanner__v1_dot_proto_dot_keys__pb2._KEYSET +_BEGINTRANSACTIONREQUEST.fields_by_name['options'].message_type = google_dot_cloud_dot_spanner__v1_dot_proto_dot_transaction__pb2._TRANSACTIONOPTIONS +_COMMITREQUEST.fields_by_name['single_use_transaction'].message_type = google_dot_cloud_dot_spanner__v1_dot_proto_dot_transaction__pb2._TRANSACTIONOPTIONS +_COMMITREQUEST.fields_by_name['mutations'].message_type = google_dot_cloud_dot_spanner__v1_dot_proto_dot_mutation__pb2._MUTATION +_COMMITREQUEST.oneofs_by_name['transaction'].fields.append( + _COMMITREQUEST.fields_by_name['transaction_id']) +_COMMITREQUEST.fields_by_name['transaction_id'].containing_oneof = _COMMITREQUEST.oneofs_by_name['transaction'] +_COMMITREQUEST.oneofs_by_name['transaction'].fields.append( + _COMMITREQUEST.fields_by_name['single_use_transaction']) +_COMMITREQUEST.fields_by_name['single_use_transaction'].containing_oneof = _COMMITREQUEST.oneofs_by_name['transaction'] +_COMMITRESPONSE.fields_by_name['commit_timestamp'].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP +DESCRIPTOR.message_types_by_name['CreateSessionRequest'] = _CREATESESSIONREQUEST +DESCRIPTOR.message_types_by_name['Session'] = _SESSION +DESCRIPTOR.message_types_by_name['GetSessionRequest'] = _GETSESSIONREQUEST +DESCRIPTOR.message_types_by_name['DeleteSessionRequest'] = _DELETESESSIONREQUEST +DESCRIPTOR.message_types_by_name['ExecuteSqlRequest'] = _EXECUTESQLREQUEST +DESCRIPTOR.message_types_by_name['ReadRequest'] = _READREQUEST +DESCRIPTOR.message_types_by_name['BeginTransactionRequest'] = _BEGINTRANSACTIONREQUEST +DESCRIPTOR.message_types_by_name['CommitRequest'] = _COMMITREQUEST +DESCRIPTOR.message_types_by_name['CommitResponse'] = _COMMITRESPONSE +DESCRIPTOR.message_types_by_name['RollbackRequest'] = _ROLLBACKREQUEST + +CreateSessionRequest = _reflection.GeneratedProtocolMessageType('CreateSessionRequest', (_message.Message,), dict( + DESCRIPTOR = _CREATESESSIONREQUEST, + __module__ = 'google.cloud.spanner_v1.proto.spanner_pb2' + , + __doc__ = """The request for + [CreateSession][google.spanner.v1.Spanner.CreateSession]. + + + Attributes: + database: + Required. The database in which the new session is created. + """, + # @@protoc_insertion_point(class_scope:google.spanner.v1.CreateSessionRequest) + )) +_sym_db.RegisterMessage(CreateSessionRequest) + +Session = _reflection.GeneratedProtocolMessageType('Session', (_message.Message,), dict( + DESCRIPTOR = _SESSION, + __module__ = 'google.cloud.spanner_v1.proto.spanner_pb2' + , + __doc__ = """A session in the Cloud Spanner API. + + + Attributes: + name: + Required. The name of the session. + """, + # @@protoc_insertion_point(class_scope:google.spanner.v1.Session) + )) +_sym_db.RegisterMessage(Session) + +GetSessionRequest = _reflection.GeneratedProtocolMessageType('GetSessionRequest', (_message.Message,), dict( + DESCRIPTOR = _GETSESSIONREQUEST, + __module__ = 'google.cloud.spanner_v1.proto.spanner_pb2' + , + __doc__ = """The request for [GetSession][google.spanner.v1.Spanner.GetSession]. + + + Attributes: + name: + Required. The name of the session to retrieve. + """, + # @@protoc_insertion_point(class_scope:google.spanner.v1.GetSessionRequest) + )) +_sym_db.RegisterMessage(GetSessionRequest) + +DeleteSessionRequest = _reflection.GeneratedProtocolMessageType('DeleteSessionRequest', (_message.Message,), dict( + DESCRIPTOR = _DELETESESSIONREQUEST, + __module__ = 'google.cloud.spanner_v1.proto.spanner_pb2' + , + __doc__ = """The request for + [DeleteSession][google.spanner.v1.Spanner.DeleteSession]. + + + Attributes: + name: + Required. The name of the session to delete. + """, + # @@protoc_insertion_point(class_scope:google.spanner.v1.DeleteSessionRequest) + )) +_sym_db.RegisterMessage(DeleteSessionRequest) + +ExecuteSqlRequest = _reflection.GeneratedProtocolMessageType('ExecuteSqlRequest', (_message.Message,), dict( + + ParamTypesEntry = _reflection.GeneratedProtocolMessageType('ParamTypesEntry', (_message.Message,), dict( + DESCRIPTOR = _EXECUTESQLREQUEST_PARAMTYPESENTRY, + __module__ = 'google.cloud.spanner_v1.proto.spanner_pb2' + # @@protoc_insertion_point(class_scope:google.spanner.v1.ExecuteSqlRequest.ParamTypesEntry) + )) + , + DESCRIPTOR = _EXECUTESQLREQUEST, + __module__ = 'google.cloud.spanner_v1.proto.spanner_pb2' + , + __doc__ = """The request for [ExecuteSql][google.spanner.v1.Spanner.ExecuteSql] and + [ExecuteStreamingSql][google.spanner.v1.Spanner.ExecuteStreamingSql]. + + + Attributes: + session: + Required. The session in which the SQL query should be + performed. + transaction: + The transaction to use. If none is provided, the default is a + temporary read-only transaction with strong concurrency. + sql: + Required. The SQL query string. + params: + The SQL query string can contain parameter placeholders. A + parameter placeholder consists of ``'@'`` followed by the + parameter name. Parameter names consist of any combination of + letters, numbers, and underscores. Parameters can appear + anywhere that a literal value is expected. The same parameter + name can be used more than once, for example: ``"WHERE id > + @msg_id AND id < @msg_id + 100"`` It is an error to execute + an SQL query with unbound parameters. Parameter values are + specified using ``params``, which is a JSON object whose keys + are parameter names, and whose values are the corresponding + parameter values. + param_types: + It is not always possible for Cloud Spanner to infer the right + SQL type from a JSON value. For example, values of type + ``BYTES`` and values of type ``STRING`` both appear in + [params][google.spanner.v1.ExecuteSqlRequest.params] as JSON + strings. In these cases, ``param_types`` can be used to + specify the exact SQL type for some or all of the SQL query + parameters. See the definition of + [Type][google.spanner.v1.Type] for more information about SQL + types. + resume_token: + If this request is resuming a previously interrupted SQL query + execution, ``resume_token`` should be copied from the last + [PartialResultSet][google.spanner.v1.PartialResultSet] yielded + before the interruption. Doing this enables the new SQL query + execution to resume where the last one left off. The rest of + the request parameters must exactly match the request that + yielded this token. + query_mode: + Used to control the amount of debugging information returned + in [ResultSetStats][google.spanner.v1.ResultSetStats]. + """, + # @@protoc_insertion_point(class_scope:google.spanner.v1.ExecuteSqlRequest) + )) +_sym_db.RegisterMessage(ExecuteSqlRequest) +_sym_db.RegisterMessage(ExecuteSqlRequest.ParamTypesEntry) + +ReadRequest = _reflection.GeneratedProtocolMessageType('ReadRequest', (_message.Message,), dict( + DESCRIPTOR = _READREQUEST, + __module__ = 'google.cloud.spanner_v1.proto.spanner_pb2' + , + __doc__ = """The request for [Read][google.spanner.v1.Spanner.Read] and + [StreamingRead][google.spanner.v1.Spanner.StreamingRead]. + + + Attributes: + session: + Required. The session in which the read should be performed. + transaction: + The transaction to use. If none is provided, the default is a + temporary read-only transaction with strong concurrency. + table: + Required. The name of the table in the database to be read. + index: + If non-empty, the name of an index on + [table][google.spanner.v1.ReadRequest.table]. This index is + used instead of the table primary key when interpreting + [key\_set][google.spanner.v1.ReadRequest.key\_set] and sorting + result rows. See + [key\_set][google.spanner.v1.ReadRequest.key\_set] for further + information. + columns: + The columns of [table][google.spanner.v1.ReadRequest.table] to + be returned for each row matching this request. + key_set: + Required. ``key_set`` identifies the rows to be yielded. + ``key_set`` names the primary keys of the rows in + [table][google.spanner.v1.ReadRequest.table] to be yielded, + unless [index][google.spanner.v1.ReadRequest.index] is + present. If [index][google.spanner.v1.ReadRequest.index] is + present, then + [key\_set][google.spanner.v1.ReadRequest.key\_set] instead + names index keys in + [index][google.spanner.v1.ReadRequest.index]. Rows are + yielded in table primary key order (if + [index][google.spanner.v1.ReadRequest.index] is empty) or + index key order (if + [index][google.spanner.v1.ReadRequest.index] is non-empty). + It is not an error for the ``key_set`` to name rows that do + not exist in the database. Read yields nothing for nonexistent + rows. + limit: + If greater than zero, only the first ``limit`` rows are + yielded. If ``limit`` is zero, the default is no limit. + resume_token: + If this request is resuming a previously interrupted read, + ``resume_token`` should be copied from the last + [PartialResultSet][google.spanner.v1.PartialResultSet] yielded + before the interruption. Doing this enables the new read to + resume where the last read left off. The rest of the request + parameters must exactly match the request that yielded this + token. + """, + # @@protoc_insertion_point(class_scope:google.spanner.v1.ReadRequest) + )) +_sym_db.RegisterMessage(ReadRequest) + +BeginTransactionRequest = _reflection.GeneratedProtocolMessageType('BeginTransactionRequest', (_message.Message,), dict( + DESCRIPTOR = _BEGINTRANSACTIONREQUEST, + __module__ = 'google.cloud.spanner_v1.proto.spanner_pb2' + , + __doc__ = """The request for + [BeginTransaction][google.spanner.v1.Spanner.BeginTransaction]. + + + Attributes: + session: + Required. The session in which the transaction runs. + options: + Required. Options for the new transaction. + """, + # @@protoc_insertion_point(class_scope:google.spanner.v1.BeginTransactionRequest) + )) +_sym_db.RegisterMessage(BeginTransactionRequest) + +CommitRequest = _reflection.GeneratedProtocolMessageType('CommitRequest', (_message.Message,), dict( + DESCRIPTOR = _COMMITREQUEST, + __module__ = 'google.cloud.spanner_v1.proto.spanner_pb2' + , + __doc__ = """The request for [Commit][google.spanner.v1.Spanner.Commit]. + + + Attributes: + session: + Required. The session in which the transaction to be committed + is running. + transaction: + Required. The transaction in which to commit. + transaction_id: + Commit a previously-started transaction. + single_use_transaction: + Execute mutations in a temporary transaction. Note that unlike + commit of a previously-started transaction, commit with a + temporary transaction is non-idempotent. That is, if the + ``CommitRequest`` is sent to Cloud Spanner more than once (for + instance, due to retries in the application, or in the + transport library), it is possible that the mutations are + executed more than once. If this is undesirable, use + [BeginTransaction][google.spanner.v1.Spanner.BeginTransaction] + and [Commit][google.spanner.v1.Spanner.Commit] instead. + mutations: + The mutations to be executed when this transaction commits. + All mutations are applied atomically, in the order they appear + in this list. + """, + # @@protoc_insertion_point(class_scope:google.spanner.v1.CommitRequest) + )) +_sym_db.RegisterMessage(CommitRequest) + +CommitResponse = _reflection.GeneratedProtocolMessageType('CommitResponse', (_message.Message,), dict( + DESCRIPTOR = _COMMITRESPONSE, + __module__ = 'google.cloud.spanner_v1.proto.spanner_pb2' + , + __doc__ = """The response for [Commit][google.spanner.v1.Spanner.Commit]. + + + Attributes: + commit_timestamp: + The Cloud Spanner timestamp at which the transaction + committed. + """, + # @@protoc_insertion_point(class_scope:google.spanner.v1.CommitResponse) + )) +_sym_db.RegisterMessage(CommitResponse) + +RollbackRequest = _reflection.GeneratedProtocolMessageType('RollbackRequest', (_message.Message,), dict( + DESCRIPTOR = _ROLLBACKREQUEST, + __module__ = 'google.cloud.spanner_v1.proto.spanner_pb2' + , + __doc__ = """The request for [Rollback][google.spanner.v1.Spanner.Rollback]. + + + Attributes: + session: + Required. The session in which the transaction to roll back is + running. + transaction_id: + Required. The transaction to roll back. + """, + # @@protoc_insertion_point(class_scope:google.spanner.v1.RollbackRequest) + )) +_sym_db.RegisterMessage(RollbackRequest) + + +DESCRIPTOR.has_options = True +DESCRIPTOR._options = _descriptor._ParseOptions(descriptor_pb2.FileOptions(), _b('\n\025com.google.spanner.v1B\014SpannerProtoP\001Z8google.golang.org/genproto/googleapis/spanner/v1;spanner\252\002\027Google.Cloud.Spanner.V1')) +_EXECUTESQLREQUEST_PARAMTYPESENTRY.has_options = True +_EXECUTESQLREQUEST_PARAMTYPESENTRY._options = _descriptor._ParseOptions(descriptor_pb2.MessageOptions(), _b('8\001')) +try: + # THESE ELEMENTS WILL BE DEPRECATED. + # Please use the generated *_pb2_grpc.py files instead. + import grpc + from grpc.beta import implementations as beta_implementations + from grpc.beta import interfaces as beta_interfaces + from grpc.framework.common import cardinality + from grpc.framework.interfaces.face import utilities as face_utilities + + + class SpannerStub(object): + """Cloud Spanner API + + The Cloud Spanner API can be used to manage sessions and execute + transactions on data stored in Cloud Spanner databases. + """ + + def __init__(self, channel): + """Constructor. + + Args: + channel: A grpc.Channel. + """ + self.CreateSession = channel.unary_unary( + '/google.spanner.v1.Spanner/CreateSession', + request_serializer=CreateSessionRequest.SerializeToString, + response_deserializer=Session.FromString, + ) + self.GetSession = channel.unary_unary( + '/google.spanner.v1.Spanner/GetSession', + request_serializer=GetSessionRequest.SerializeToString, + response_deserializer=Session.FromString, + ) + self.DeleteSession = channel.unary_unary( + '/google.spanner.v1.Spanner/DeleteSession', + request_serializer=DeleteSessionRequest.SerializeToString, + response_deserializer=google_dot_protobuf_dot_empty__pb2.Empty.FromString, + ) + self.ExecuteSql = channel.unary_unary( + '/google.spanner.v1.Spanner/ExecuteSql', + request_serializer=ExecuteSqlRequest.SerializeToString, + response_deserializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_result__set__pb2.ResultSet.FromString, + ) + self.ExecuteStreamingSql = channel.unary_stream( + '/google.spanner.v1.Spanner/ExecuteStreamingSql', + request_serializer=ExecuteSqlRequest.SerializeToString, + response_deserializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_result__set__pb2.PartialResultSet.FromString, + ) + self.Read = channel.unary_unary( + '/google.spanner.v1.Spanner/Read', + request_serializer=ReadRequest.SerializeToString, + response_deserializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_result__set__pb2.ResultSet.FromString, + ) + self.StreamingRead = channel.unary_stream( + '/google.spanner.v1.Spanner/StreamingRead', + request_serializer=ReadRequest.SerializeToString, + response_deserializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_result__set__pb2.PartialResultSet.FromString, + ) + self.BeginTransaction = channel.unary_unary( + '/google.spanner.v1.Spanner/BeginTransaction', + request_serializer=BeginTransactionRequest.SerializeToString, + response_deserializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_transaction__pb2.Transaction.FromString, + ) + self.Commit = channel.unary_unary( + '/google.spanner.v1.Spanner/Commit', + request_serializer=CommitRequest.SerializeToString, + response_deserializer=CommitResponse.FromString, + ) + self.Rollback = channel.unary_unary( + '/google.spanner.v1.Spanner/Rollback', + request_serializer=RollbackRequest.SerializeToString, + response_deserializer=google_dot_protobuf_dot_empty__pb2.Empty.FromString, + ) + + + class SpannerServicer(object): + """Cloud Spanner API + + The Cloud Spanner API can be used to manage sessions and execute + transactions on data stored in Cloud Spanner databases. + """ + + def CreateSession(self, request, context): + """Creates a new session. A session can be used to perform + transactions that read and/or modify data in a Cloud Spanner database. + Sessions are meant to be reused for many consecutive + transactions. + + Sessions can only execute one transaction at a time. To execute + multiple concurrent read-write/write-only transactions, create + multiple sessions. Note that standalone reads and queries use a + transaction internally, and count toward the one transaction + limit. + + Cloud Spanner limits the number of sessions that can exist at any given + time; thus, it is a good idea to delete idle and/or unneeded sessions. + Aside from explicit deletes, Cloud Spanner can delete sessions for which no + operations are sent for more than an hour. If a session is deleted, + requests to it return `NOT_FOUND`. + + Idle sessions can be kept alive by sending a trivial SQL query + periodically, e.g., `"SELECT 1"`. + """ + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + def GetSession(self, request, context): + """Gets a session. Returns `NOT_FOUND` if the session does not exist. + This is mainly useful for determining whether a session is still + alive. + """ + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + def DeleteSession(self, request, context): + """Ends a session, releasing server resources associated with it. + """ + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + def ExecuteSql(self, request, context): + """Executes an SQL query, returning all rows in a single reply. This + method cannot be used to return a result set larger than 10 MiB; + if the query yields more data than that, the query fails with + a `FAILED_PRECONDITION` error. + + Queries inside read-write transactions might return `ABORTED`. If + this occurs, the application should restart the transaction from + the beginning. See [Transaction][google.spanner.v1.Transaction] for more details. + + Larger result sets can be fetched in streaming fashion by calling + [ExecuteStreamingSql][google.spanner.v1.Spanner.ExecuteStreamingSql] instead. + """ + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + def ExecuteStreamingSql(self, request, context): + """Like [ExecuteSql][google.spanner.v1.Spanner.ExecuteSql], except returns the result + set as a stream. Unlike [ExecuteSql][google.spanner.v1.Spanner.ExecuteSql], there + is no limit on the size of the returned result set. However, no + individual row in the result set can exceed 100 MiB, and no + column value can exceed 10 MiB. + """ + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + def Read(self, request, context): + """Reads rows from the database using key lookups and scans, as a + simple key/value style alternative to + [ExecuteSql][google.spanner.v1.Spanner.ExecuteSql]. This method cannot be used to + return a result set larger than 10 MiB; if the read matches more + data than that, the read fails with a `FAILED_PRECONDITION` + error. + + Reads inside read-write transactions might return `ABORTED`. If + this occurs, the application should restart the transaction from + the beginning. See [Transaction][google.spanner.v1.Transaction] for more details. + + Larger result sets can be yielded in streaming fashion by calling + [StreamingRead][google.spanner.v1.Spanner.StreamingRead] instead. + """ + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + def StreamingRead(self, request, context): + """Like [Read][google.spanner.v1.Spanner.Read], except returns the result set as a + stream. Unlike [Read][google.spanner.v1.Spanner.Read], there is no limit on the + size of the returned result set. However, no individual row in + the result set can exceed 100 MiB, and no column value can exceed + 10 MiB. + """ + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + def BeginTransaction(self, request, context): + """Begins a new transaction. This step can often be skipped: + [Read][google.spanner.v1.Spanner.Read], [ExecuteSql][google.spanner.v1.Spanner.ExecuteSql] and + [Commit][google.spanner.v1.Spanner.Commit] can begin a new transaction as a + side-effect. + """ + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + def Commit(self, request, context): + """Commits a transaction. The request includes the mutations to be + applied to rows in the database. + + `Commit` might return an `ABORTED` error. This can occur at any time; + commonly, the cause is conflicts with concurrent + transactions. However, it can also happen for a variety of other + reasons. If `Commit` returns `ABORTED`, the caller should re-attempt + the transaction from the beginning, re-using the same session. + """ + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + def Rollback(self, request, context): + """Rolls back a transaction, releasing any locks it holds. It is a good + idea to call this for any transaction that includes one or more + [Read][google.spanner.v1.Spanner.Read] or [ExecuteSql][google.spanner.v1.Spanner.ExecuteSql] requests and + ultimately decides not to commit. + + `Rollback` returns `OK` if it successfully aborts the transaction, the + transaction was already aborted, or the transaction is not + found. `Rollback` never returns `ABORTED`. + """ + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + + def add_SpannerServicer_to_server(servicer, server): + rpc_method_handlers = { + 'CreateSession': grpc.unary_unary_rpc_method_handler( + servicer.CreateSession, + request_deserializer=CreateSessionRequest.FromString, + response_serializer=Session.SerializeToString, + ), + 'GetSession': grpc.unary_unary_rpc_method_handler( + servicer.GetSession, + request_deserializer=GetSessionRequest.FromString, + response_serializer=Session.SerializeToString, + ), + 'DeleteSession': grpc.unary_unary_rpc_method_handler( + servicer.DeleteSession, + request_deserializer=DeleteSessionRequest.FromString, + response_serializer=google_dot_protobuf_dot_empty__pb2.Empty.SerializeToString, + ), + 'ExecuteSql': grpc.unary_unary_rpc_method_handler( + servicer.ExecuteSql, + request_deserializer=ExecuteSqlRequest.FromString, + response_serializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_result__set__pb2.ResultSet.SerializeToString, + ), + 'ExecuteStreamingSql': grpc.unary_stream_rpc_method_handler( + servicer.ExecuteStreamingSql, + request_deserializer=ExecuteSqlRequest.FromString, + response_serializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_result__set__pb2.PartialResultSet.SerializeToString, + ), + 'Read': grpc.unary_unary_rpc_method_handler( + servicer.Read, + request_deserializer=ReadRequest.FromString, + response_serializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_result__set__pb2.ResultSet.SerializeToString, + ), + 'StreamingRead': grpc.unary_stream_rpc_method_handler( + servicer.StreamingRead, + request_deserializer=ReadRequest.FromString, + response_serializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_result__set__pb2.PartialResultSet.SerializeToString, + ), + 'BeginTransaction': grpc.unary_unary_rpc_method_handler( + servicer.BeginTransaction, + request_deserializer=BeginTransactionRequest.FromString, + response_serializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_transaction__pb2.Transaction.SerializeToString, + ), + 'Commit': grpc.unary_unary_rpc_method_handler( + servicer.Commit, + request_deserializer=CommitRequest.FromString, + response_serializer=CommitResponse.SerializeToString, + ), + 'Rollback': grpc.unary_unary_rpc_method_handler( + servicer.Rollback, + request_deserializer=RollbackRequest.FromString, + response_serializer=google_dot_protobuf_dot_empty__pb2.Empty.SerializeToString, + ), + } + generic_handler = grpc.method_handlers_generic_handler( + 'google.spanner.v1.Spanner', rpc_method_handlers) + server.add_generic_rpc_handlers((generic_handler,)) + + + class BetaSpannerServicer(object): + """The Beta API is deprecated for 0.15.0 and later. + + It is recommended to use the GA API (classes and functions in this + file not marked beta) for all further purposes. This class was generated + only to ease transition from grpcio<0.15.0 to grpcio>=0.15.0.""" + """Cloud Spanner API + + The Cloud Spanner API can be used to manage sessions and execute + transactions on data stored in Cloud Spanner databases. + """ + def CreateSession(self, request, context): + """Creates a new session. A session can be used to perform + transactions that read and/or modify data in a Cloud Spanner database. + Sessions are meant to be reused for many consecutive + transactions. + + Sessions can only execute one transaction at a time. To execute + multiple concurrent read-write/write-only transactions, create + multiple sessions. Note that standalone reads and queries use a + transaction internally, and count toward the one transaction + limit. + + Cloud Spanner limits the number of sessions that can exist at any given + time; thus, it is a good idea to delete idle and/or unneeded sessions. + Aside from explicit deletes, Cloud Spanner can delete sessions for which no + operations are sent for more than an hour. If a session is deleted, + requests to it return `NOT_FOUND`. + + Idle sessions can be kept alive by sending a trivial SQL query + periodically, e.g., `"SELECT 1"`. + """ + context.code(beta_interfaces.StatusCode.UNIMPLEMENTED) + def GetSession(self, request, context): + """Gets a session. Returns `NOT_FOUND` if the session does not exist. + This is mainly useful for determining whether a session is still + alive. + """ + context.code(beta_interfaces.StatusCode.UNIMPLEMENTED) + def DeleteSession(self, request, context): + """Ends a session, releasing server resources associated with it. + """ + context.code(beta_interfaces.StatusCode.UNIMPLEMENTED) + def ExecuteSql(self, request, context): + """Executes an SQL query, returning all rows in a single reply. This + method cannot be used to return a result set larger than 10 MiB; + if the query yields more data than that, the query fails with + a `FAILED_PRECONDITION` error. + + Queries inside read-write transactions might return `ABORTED`. If + this occurs, the application should restart the transaction from + the beginning. See [Transaction][google.spanner.v1.Transaction] for more details. + + Larger result sets can be fetched in streaming fashion by calling + [ExecuteStreamingSql][google.spanner.v1.Spanner.ExecuteStreamingSql] instead. + """ + context.code(beta_interfaces.StatusCode.UNIMPLEMENTED) + def ExecuteStreamingSql(self, request, context): + """Like [ExecuteSql][google.spanner.v1.Spanner.ExecuteSql], except returns the result + set as a stream. Unlike [ExecuteSql][google.spanner.v1.Spanner.ExecuteSql], there + is no limit on the size of the returned result set. However, no + individual row in the result set can exceed 100 MiB, and no + column value can exceed 10 MiB. + """ + context.code(beta_interfaces.StatusCode.UNIMPLEMENTED) + def Read(self, request, context): + """Reads rows from the database using key lookups and scans, as a + simple key/value style alternative to + [ExecuteSql][google.spanner.v1.Spanner.ExecuteSql]. This method cannot be used to + return a result set larger than 10 MiB; if the read matches more + data than that, the read fails with a `FAILED_PRECONDITION` + error. + + Reads inside read-write transactions might return `ABORTED`. If + this occurs, the application should restart the transaction from + the beginning. See [Transaction][google.spanner.v1.Transaction] for more details. + + Larger result sets can be yielded in streaming fashion by calling + [StreamingRead][google.spanner.v1.Spanner.StreamingRead] instead. + """ + context.code(beta_interfaces.StatusCode.UNIMPLEMENTED) + def StreamingRead(self, request, context): + """Like [Read][google.spanner.v1.Spanner.Read], except returns the result set as a + stream. Unlike [Read][google.spanner.v1.Spanner.Read], there is no limit on the + size of the returned result set. However, no individual row in + the result set can exceed 100 MiB, and no column value can exceed + 10 MiB. + """ + context.code(beta_interfaces.StatusCode.UNIMPLEMENTED) + def BeginTransaction(self, request, context): + """Begins a new transaction. This step can often be skipped: + [Read][google.spanner.v1.Spanner.Read], [ExecuteSql][google.spanner.v1.Spanner.ExecuteSql] and + [Commit][google.spanner.v1.Spanner.Commit] can begin a new transaction as a + side-effect. + """ + context.code(beta_interfaces.StatusCode.UNIMPLEMENTED) + def Commit(self, request, context): + """Commits a transaction. The request includes the mutations to be + applied to rows in the database. + + `Commit` might return an `ABORTED` error. This can occur at any time; + commonly, the cause is conflicts with concurrent + transactions. However, it can also happen for a variety of other + reasons. If `Commit` returns `ABORTED`, the caller should re-attempt + the transaction from the beginning, re-using the same session. + """ + context.code(beta_interfaces.StatusCode.UNIMPLEMENTED) + def Rollback(self, request, context): + """Rolls back a transaction, releasing any locks it holds. It is a good + idea to call this for any transaction that includes one or more + [Read][google.spanner.v1.Spanner.Read] or [ExecuteSql][google.spanner.v1.Spanner.ExecuteSql] requests and + ultimately decides not to commit. + + `Rollback` returns `OK` if it successfully aborts the transaction, the + transaction was already aborted, or the transaction is not + found. `Rollback` never returns `ABORTED`. + """ + context.code(beta_interfaces.StatusCode.UNIMPLEMENTED) + + + class BetaSpannerStub(object): + """The Beta API is deprecated for 0.15.0 and later. + + It is recommended to use the GA API (classes and functions in this + file not marked beta) for all further purposes. This class was generated + only to ease transition from grpcio<0.15.0 to grpcio>=0.15.0.""" + """Cloud Spanner API + + The Cloud Spanner API can be used to manage sessions and execute + transactions on data stored in Cloud Spanner databases. + """ + def CreateSession(self, request, timeout, metadata=None, with_call=False, protocol_options=None): + """Creates a new session. A session can be used to perform + transactions that read and/or modify data in a Cloud Spanner database. + Sessions are meant to be reused for many consecutive + transactions. + + Sessions can only execute one transaction at a time. To execute + multiple concurrent read-write/write-only transactions, create + multiple sessions. Note that standalone reads and queries use a + transaction internally, and count toward the one transaction + limit. + + Cloud Spanner limits the number of sessions that can exist at any given + time; thus, it is a good idea to delete idle and/or unneeded sessions. + Aside from explicit deletes, Cloud Spanner can delete sessions for which no + operations are sent for more than an hour. If a session is deleted, + requests to it return `NOT_FOUND`. + + Idle sessions can be kept alive by sending a trivial SQL query + periodically, e.g., `"SELECT 1"`. + """ + raise NotImplementedError() + CreateSession.future = None + def GetSession(self, request, timeout, metadata=None, with_call=False, protocol_options=None): + """Gets a session. Returns `NOT_FOUND` if the session does not exist. + This is mainly useful for determining whether a session is still + alive. + """ + raise NotImplementedError() + GetSession.future = None + def DeleteSession(self, request, timeout, metadata=None, with_call=False, protocol_options=None): + """Ends a session, releasing server resources associated with it. + """ + raise NotImplementedError() + DeleteSession.future = None + def ExecuteSql(self, request, timeout, metadata=None, with_call=False, protocol_options=None): + """Executes an SQL query, returning all rows in a single reply. This + method cannot be used to return a result set larger than 10 MiB; + if the query yields more data than that, the query fails with + a `FAILED_PRECONDITION` error. + + Queries inside read-write transactions might return `ABORTED`. If + this occurs, the application should restart the transaction from + the beginning. See [Transaction][google.spanner.v1.Transaction] for more details. + + Larger result sets can be fetched in streaming fashion by calling + [ExecuteStreamingSql][google.spanner.v1.Spanner.ExecuteStreamingSql] instead. + """ + raise NotImplementedError() + ExecuteSql.future = None + def ExecuteStreamingSql(self, request, timeout, metadata=None, with_call=False, protocol_options=None): + """Like [ExecuteSql][google.spanner.v1.Spanner.ExecuteSql], except returns the result + set as a stream. Unlike [ExecuteSql][google.spanner.v1.Spanner.ExecuteSql], there + is no limit on the size of the returned result set. However, no + individual row in the result set can exceed 100 MiB, and no + column value can exceed 10 MiB. + """ + raise NotImplementedError() + def Read(self, request, timeout, metadata=None, with_call=False, protocol_options=None): + """Reads rows from the database using key lookups and scans, as a + simple key/value style alternative to + [ExecuteSql][google.spanner.v1.Spanner.ExecuteSql]. This method cannot be used to + return a result set larger than 10 MiB; if the read matches more + data than that, the read fails with a `FAILED_PRECONDITION` + error. + + Reads inside read-write transactions might return `ABORTED`. If + this occurs, the application should restart the transaction from + the beginning. See [Transaction][google.spanner.v1.Transaction] for more details. + + Larger result sets can be yielded in streaming fashion by calling + [StreamingRead][google.spanner.v1.Spanner.StreamingRead] instead. + """ + raise NotImplementedError() + Read.future = None + def StreamingRead(self, request, timeout, metadata=None, with_call=False, protocol_options=None): + """Like [Read][google.spanner.v1.Spanner.Read], except returns the result set as a + stream. Unlike [Read][google.spanner.v1.Spanner.Read], there is no limit on the + size of the returned result set. However, no individual row in + the result set can exceed 100 MiB, and no column value can exceed + 10 MiB. + """ + raise NotImplementedError() + def BeginTransaction(self, request, timeout, metadata=None, with_call=False, protocol_options=None): + """Begins a new transaction. This step can often be skipped: + [Read][google.spanner.v1.Spanner.Read], [ExecuteSql][google.spanner.v1.Spanner.ExecuteSql] and + [Commit][google.spanner.v1.Spanner.Commit] can begin a new transaction as a + side-effect. + """ + raise NotImplementedError() + BeginTransaction.future = None + def Commit(self, request, timeout, metadata=None, with_call=False, protocol_options=None): + """Commits a transaction. The request includes the mutations to be + applied to rows in the database. + + `Commit` might return an `ABORTED` error. This can occur at any time; + commonly, the cause is conflicts with concurrent + transactions. However, it can also happen for a variety of other + reasons. If `Commit` returns `ABORTED`, the caller should re-attempt + the transaction from the beginning, re-using the same session. + """ + raise NotImplementedError() + Commit.future = None + def Rollback(self, request, timeout, metadata=None, with_call=False, protocol_options=None): + """Rolls back a transaction, releasing any locks it holds. It is a good + idea to call this for any transaction that includes one or more + [Read][google.spanner.v1.Spanner.Read] or [ExecuteSql][google.spanner.v1.Spanner.ExecuteSql] requests and + ultimately decides not to commit. + + `Rollback` returns `OK` if it successfully aborts the transaction, the + transaction was already aborted, or the transaction is not + found. `Rollback` never returns `ABORTED`. + """ + raise NotImplementedError() + Rollback.future = None + + + def beta_create_Spanner_server(servicer, pool=None, pool_size=None, default_timeout=None, maximum_timeout=None): + """The Beta API is deprecated for 0.15.0 and later. + + It is recommended to use the GA API (classes and functions in this + file not marked beta) for all further purposes. This function was + generated only to ease transition from grpcio<0.15.0 to grpcio>=0.15.0""" + request_deserializers = { + ('google.spanner.v1.Spanner', 'BeginTransaction'): BeginTransactionRequest.FromString, + ('google.spanner.v1.Spanner', 'Commit'): CommitRequest.FromString, + ('google.spanner.v1.Spanner', 'CreateSession'): CreateSessionRequest.FromString, + ('google.spanner.v1.Spanner', 'DeleteSession'): DeleteSessionRequest.FromString, + ('google.spanner.v1.Spanner', 'ExecuteSql'): ExecuteSqlRequest.FromString, + ('google.spanner.v1.Spanner', 'ExecuteStreamingSql'): ExecuteSqlRequest.FromString, + ('google.spanner.v1.Spanner', 'GetSession'): GetSessionRequest.FromString, + ('google.spanner.v1.Spanner', 'Read'): ReadRequest.FromString, + ('google.spanner.v1.Spanner', 'Rollback'): RollbackRequest.FromString, + ('google.spanner.v1.Spanner', 'StreamingRead'): ReadRequest.FromString, + } + response_serializers = { + ('google.spanner.v1.Spanner', 'BeginTransaction'): google_dot_cloud_dot_spanner__v1_dot_proto_dot_transaction__pb2.Transaction.SerializeToString, + ('google.spanner.v1.Spanner', 'Commit'): CommitResponse.SerializeToString, + ('google.spanner.v1.Spanner', 'CreateSession'): Session.SerializeToString, + ('google.spanner.v1.Spanner', 'DeleteSession'): google_dot_protobuf_dot_empty__pb2.Empty.SerializeToString, + ('google.spanner.v1.Spanner', 'ExecuteSql'): google_dot_cloud_dot_spanner__v1_dot_proto_dot_result__set__pb2.ResultSet.SerializeToString, + ('google.spanner.v1.Spanner', 'ExecuteStreamingSql'): google_dot_cloud_dot_spanner__v1_dot_proto_dot_result__set__pb2.PartialResultSet.SerializeToString, + ('google.spanner.v1.Spanner', 'GetSession'): Session.SerializeToString, + ('google.spanner.v1.Spanner', 'Read'): google_dot_cloud_dot_spanner__v1_dot_proto_dot_result__set__pb2.ResultSet.SerializeToString, + ('google.spanner.v1.Spanner', 'Rollback'): google_dot_protobuf_dot_empty__pb2.Empty.SerializeToString, + ('google.spanner.v1.Spanner', 'StreamingRead'): google_dot_cloud_dot_spanner__v1_dot_proto_dot_result__set__pb2.PartialResultSet.SerializeToString, + } + method_implementations = { + ('google.spanner.v1.Spanner', 'BeginTransaction'): face_utilities.unary_unary_inline(servicer.BeginTransaction), + ('google.spanner.v1.Spanner', 'Commit'): face_utilities.unary_unary_inline(servicer.Commit), + ('google.spanner.v1.Spanner', 'CreateSession'): face_utilities.unary_unary_inline(servicer.CreateSession), + ('google.spanner.v1.Spanner', 'DeleteSession'): face_utilities.unary_unary_inline(servicer.DeleteSession), + ('google.spanner.v1.Spanner', 'ExecuteSql'): face_utilities.unary_unary_inline(servicer.ExecuteSql), + ('google.spanner.v1.Spanner', 'ExecuteStreamingSql'): face_utilities.unary_stream_inline(servicer.ExecuteStreamingSql), + ('google.spanner.v1.Spanner', 'GetSession'): face_utilities.unary_unary_inline(servicer.GetSession), + ('google.spanner.v1.Spanner', 'Read'): face_utilities.unary_unary_inline(servicer.Read), + ('google.spanner.v1.Spanner', 'Rollback'): face_utilities.unary_unary_inline(servicer.Rollback), + ('google.spanner.v1.Spanner', 'StreamingRead'): face_utilities.unary_stream_inline(servicer.StreamingRead), + } + server_options = beta_implementations.server_options(request_deserializers=request_deserializers, response_serializers=response_serializers, thread_pool=pool, thread_pool_size=pool_size, default_timeout=default_timeout, maximum_timeout=maximum_timeout) + return beta_implementations.server(method_implementations, options=server_options) + + + def beta_create_Spanner_stub(channel, host=None, metadata_transformer=None, pool=None, pool_size=None): + """The Beta API is deprecated for 0.15.0 and later. + + It is recommended to use the GA API (classes and functions in this + file not marked beta) for all further purposes. This function was + generated only to ease transition from grpcio<0.15.0 to grpcio>=0.15.0""" + request_serializers = { + ('google.spanner.v1.Spanner', 'BeginTransaction'): BeginTransactionRequest.SerializeToString, + ('google.spanner.v1.Spanner', 'Commit'): CommitRequest.SerializeToString, + ('google.spanner.v1.Spanner', 'CreateSession'): CreateSessionRequest.SerializeToString, + ('google.spanner.v1.Spanner', 'DeleteSession'): DeleteSessionRequest.SerializeToString, + ('google.spanner.v1.Spanner', 'ExecuteSql'): ExecuteSqlRequest.SerializeToString, + ('google.spanner.v1.Spanner', 'ExecuteStreamingSql'): ExecuteSqlRequest.SerializeToString, + ('google.spanner.v1.Spanner', 'GetSession'): GetSessionRequest.SerializeToString, + ('google.spanner.v1.Spanner', 'Read'): ReadRequest.SerializeToString, + ('google.spanner.v1.Spanner', 'Rollback'): RollbackRequest.SerializeToString, + ('google.spanner.v1.Spanner', 'StreamingRead'): ReadRequest.SerializeToString, + } + response_deserializers = { + ('google.spanner.v1.Spanner', 'BeginTransaction'): google_dot_cloud_dot_spanner__v1_dot_proto_dot_transaction__pb2.Transaction.FromString, + ('google.spanner.v1.Spanner', 'Commit'): CommitResponse.FromString, + ('google.spanner.v1.Spanner', 'CreateSession'): Session.FromString, + ('google.spanner.v1.Spanner', 'DeleteSession'): google_dot_protobuf_dot_empty__pb2.Empty.FromString, + ('google.spanner.v1.Spanner', 'ExecuteSql'): google_dot_cloud_dot_spanner__v1_dot_proto_dot_result__set__pb2.ResultSet.FromString, + ('google.spanner.v1.Spanner', 'ExecuteStreamingSql'): google_dot_cloud_dot_spanner__v1_dot_proto_dot_result__set__pb2.PartialResultSet.FromString, + ('google.spanner.v1.Spanner', 'GetSession'): Session.FromString, + ('google.spanner.v1.Spanner', 'Read'): google_dot_cloud_dot_spanner__v1_dot_proto_dot_result__set__pb2.ResultSet.FromString, + ('google.spanner.v1.Spanner', 'Rollback'): google_dot_protobuf_dot_empty__pb2.Empty.FromString, + ('google.spanner.v1.Spanner', 'StreamingRead'): google_dot_cloud_dot_spanner__v1_dot_proto_dot_result__set__pb2.PartialResultSet.FromString, + } + cardinalities = { + 'BeginTransaction': cardinality.Cardinality.UNARY_UNARY, + 'Commit': cardinality.Cardinality.UNARY_UNARY, + 'CreateSession': cardinality.Cardinality.UNARY_UNARY, + 'DeleteSession': cardinality.Cardinality.UNARY_UNARY, + 'ExecuteSql': cardinality.Cardinality.UNARY_UNARY, + 'ExecuteStreamingSql': cardinality.Cardinality.UNARY_STREAM, + 'GetSession': cardinality.Cardinality.UNARY_UNARY, + 'Read': cardinality.Cardinality.UNARY_UNARY, + 'Rollback': cardinality.Cardinality.UNARY_UNARY, + 'StreamingRead': cardinality.Cardinality.UNARY_STREAM, + } + stub_options = beta_implementations.stub_options(host=host, metadata_transformer=metadata_transformer, request_serializers=request_serializers, response_deserializers=response_deserializers, thread_pool=pool, thread_pool_size=pool_size) + return beta_implementations.dynamic_stub(channel, 'google.spanner.v1.Spanner', cardinalities, options=stub_options) +except ImportError: + pass +# @@protoc_insertion_point(module_scope) diff --git a/spanner/google/cloud/spanner_v1/proto/spanner_pb2_grpc.py b/spanner/google/cloud/spanner_v1/proto/spanner_pb2_grpc.py new file mode 100644 index 000000000000..3eb3cbfc0c9e --- /dev/null +++ b/spanner/google/cloud/spanner_v1/proto/spanner_pb2_grpc.py @@ -0,0 +1,275 @@ +# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! +import grpc + +import google.cloud.spanner_v1.proto.result_set_pb2 as google_dot_cloud_dot_spanner__v1_dot_proto_dot_result__set__pb2 +import google.cloud.spanner_v1.proto.spanner_pb2 as google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2 +import google.cloud.spanner_v1.proto.transaction_pb2 as google_dot_cloud_dot_spanner__v1_dot_proto_dot_transaction__pb2 +import google.protobuf.empty_pb2 as google_dot_protobuf_dot_empty__pb2 + + +class SpannerStub(object): + """Cloud Spanner API + + The Cloud Spanner API can be used to manage sessions and execute + transactions on data stored in Cloud Spanner databases. + """ + + def __init__(self, channel): + """Constructor. + + Args: + channel: A grpc.Channel. + """ + self.CreateSession = channel.unary_unary( + '/google.spanner.v1.Spanner/CreateSession', + request_serializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.CreateSessionRequest.SerializeToString, + response_deserializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.Session.FromString, + ) + self.GetSession = channel.unary_unary( + '/google.spanner.v1.Spanner/GetSession', + request_serializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.GetSessionRequest.SerializeToString, + response_deserializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.Session.FromString, + ) + self.DeleteSession = channel.unary_unary( + '/google.spanner.v1.Spanner/DeleteSession', + request_serializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.DeleteSessionRequest.SerializeToString, + response_deserializer=google_dot_protobuf_dot_empty__pb2.Empty.FromString, + ) + self.ExecuteSql = channel.unary_unary( + '/google.spanner.v1.Spanner/ExecuteSql', + request_serializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.ExecuteSqlRequest.SerializeToString, + response_deserializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_result__set__pb2.ResultSet.FromString, + ) + self.ExecuteStreamingSql = channel.unary_stream( + '/google.spanner.v1.Spanner/ExecuteStreamingSql', + request_serializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.ExecuteSqlRequest.SerializeToString, + response_deserializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_result__set__pb2.PartialResultSet.FromString, + ) + self.Read = channel.unary_unary( + '/google.spanner.v1.Spanner/Read', + request_serializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.ReadRequest.SerializeToString, + response_deserializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_result__set__pb2.ResultSet.FromString, + ) + self.StreamingRead = channel.unary_stream( + '/google.spanner.v1.Spanner/StreamingRead', + request_serializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.ReadRequest.SerializeToString, + response_deserializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_result__set__pb2.PartialResultSet.FromString, + ) + self.BeginTransaction = channel.unary_unary( + '/google.spanner.v1.Spanner/BeginTransaction', + request_serializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.BeginTransactionRequest.SerializeToString, + response_deserializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_transaction__pb2.Transaction.FromString, + ) + self.Commit = channel.unary_unary( + '/google.spanner.v1.Spanner/Commit', + request_serializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.CommitRequest.SerializeToString, + response_deserializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.CommitResponse.FromString, + ) + self.Rollback = channel.unary_unary( + '/google.spanner.v1.Spanner/Rollback', + request_serializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.RollbackRequest.SerializeToString, + response_deserializer=google_dot_protobuf_dot_empty__pb2.Empty.FromString, + ) + + +class SpannerServicer(object): + """Cloud Spanner API + + The Cloud Spanner API can be used to manage sessions and execute + transactions on data stored in Cloud Spanner databases. + """ + + def CreateSession(self, request, context): + """Creates a new session. A session can be used to perform + transactions that read and/or modify data in a Cloud Spanner database. + Sessions are meant to be reused for many consecutive + transactions. + + Sessions can only execute one transaction at a time. To execute + multiple concurrent read-write/write-only transactions, create + multiple sessions. Note that standalone reads and queries use a + transaction internally, and count toward the one transaction + limit. + + Cloud Spanner limits the number of sessions that can exist at any given + time; thus, it is a good idea to delete idle and/or unneeded sessions. + Aside from explicit deletes, Cloud Spanner can delete sessions for which no + operations are sent for more than an hour. If a session is deleted, + requests to it return `NOT_FOUND`. + + Idle sessions can be kept alive by sending a trivial SQL query + periodically, e.g., `"SELECT 1"`. + """ + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + def GetSession(self, request, context): + """Gets a session. Returns `NOT_FOUND` if the session does not exist. + This is mainly useful for determining whether a session is still + alive. + """ + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + def DeleteSession(self, request, context): + """Ends a session, releasing server resources associated with it. + """ + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + def ExecuteSql(self, request, context): + """Executes an SQL query, returning all rows in a single reply. This + method cannot be used to return a result set larger than 10 MiB; + if the query yields more data than that, the query fails with + a `FAILED_PRECONDITION` error. + + Queries inside read-write transactions might return `ABORTED`. If + this occurs, the application should restart the transaction from + the beginning. See [Transaction][google.spanner.v1.Transaction] for more details. + + Larger result sets can be fetched in streaming fashion by calling + [ExecuteStreamingSql][google.spanner.v1.Spanner.ExecuteStreamingSql] instead. + """ + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + def ExecuteStreamingSql(self, request, context): + """Like [ExecuteSql][google.spanner.v1.Spanner.ExecuteSql], except returns the result + set as a stream. Unlike [ExecuteSql][google.spanner.v1.Spanner.ExecuteSql], there + is no limit on the size of the returned result set. However, no + individual row in the result set can exceed 100 MiB, and no + column value can exceed 10 MiB. + """ + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + def Read(self, request, context): + """Reads rows from the database using key lookups and scans, as a + simple key/value style alternative to + [ExecuteSql][google.spanner.v1.Spanner.ExecuteSql]. This method cannot be used to + return a result set larger than 10 MiB; if the read matches more + data than that, the read fails with a `FAILED_PRECONDITION` + error. + + Reads inside read-write transactions might return `ABORTED`. If + this occurs, the application should restart the transaction from + the beginning. See [Transaction][google.spanner.v1.Transaction] for more details. + + Larger result sets can be yielded in streaming fashion by calling + [StreamingRead][google.spanner.v1.Spanner.StreamingRead] instead. + """ + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + def StreamingRead(self, request, context): + """Like [Read][google.spanner.v1.Spanner.Read], except returns the result set as a + stream. Unlike [Read][google.spanner.v1.Spanner.Read], there is no limit on the + size of the returned result set. However, no individual row in + the result set can exceed 100 MiB, and no column value can exceed + 10 MiB. + """ + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + def BeginTransaction(self, request, context): + """Begins a new transaction. This step can often be skipped: + [Read][google.spanner.v1.Spanner.Read], [ExecuteSql][google.spanner.v1.Spanner.ExecuteSql] and + [Commit][google.spanner.v1.Spanner.Commit] can begin a new transaction as a + side-effect. + """ + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + def Commit(self, request, context): + """Commits a transaction. The request includes the mutations to be + applied to rows in the database. + + `Commit` might return an `ABORTED` error. This can occur at any time; + commonly, the cause is conflicts with concurrent + transactions. However, it can also happen for a variety of other + reasons. If `Commit` returns `ABORTED`, the caller should re-attempt + the transaction from the beginning, re-using the same session. + """ + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + def Rollback(self, request, context): + """Rolls back a transaction, releasing any locks it holds. It is a good + idea to call this for any transaction that includes one or more + [Read][google.spanner.v1.Spanner.Read] or [ExecuteSql][google.spanner.v1.Spanner.ExecuteSql] requests and + ultimately decides not to commit. + + `Rollback` returns `OK` if it successfully aborts the transaction, the + transaction was already aborted, or the transaction is not + found. `Rollback` never returns `ABORTED`. + """ + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + +def add_SpannerServicer_to_server(servicer, server): + rpc_method_handlers = { + 'CreateSession': grpc.unary_unary_rpc_method_handler( + servicer.CreateSession, + request_deserializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.CreateSessionRequest.FromString, + response_serializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.Session.SerializeToString, + ), + 'GetSession': grpc.unary_unary_rpc_method_handler( + servicer.GetSession, + request_deserializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.GetSessionRequest.FromString, + response_serializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.Session.SerializeToString, + ), + 'DeleteSession': grpc.unary_unary_rpc_method_handler( + servicer.DeleteSession, + request_deserializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.DeleteSessionRequest.FromString, + response_serializer=google_dot_protobuf_dot_empty__pb2.Empty.SerializeToString, + ), + 'ExecuteSql': grpc.unary_unary_rpc_method_handler( + servicer.ExecuteSql, + request_deserializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.ExecuteSqlRequest.FromString, + response_serializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_result__set__pb2.ResultSet.SerializeToString, + ), + 'ExecuteStreamingSql': grpc.unary_stream_rpc_method_handler( + servicer.ExecuteStreamingSql, + request_deserializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.ExecuteSqlRequest.FromString, + response_serializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_result__set__pb2.PartialResultSet.SerializeToString, + ), + 'Read': grpc.unary_unary_rpc_method_handler( + servicer.Read, + request_deserializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.ReadRequest.FromString, + response_serializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_result__set__pb2.ResultSet.SerializeToString, + ), + 'StreamingRead': grpc.unary_stream_rpc_method_handler( + servicer.StreamingRead, + request_deserializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.ReadRequest.FromString, + response_serializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_result__set__pb2.PartialResultSet.SerializeToString, + ), + 'BeginTransaction': grpc.unary_unary_rpc_method_handler( + servicer.BeginTransaction, + request_deserializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.BeginTransactionRequest.FromString, + response_serializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_transaction__pb2.Transaction.SerializeToString, + ), + 'Commit': grpc.unary_unary_rpc_method_handler( + servicer.Commit, + request_deserializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.CommitRequest.FromString, + response_serializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.CommitResponse.SerializeToString, + ), + 'Rollback': grpc.unary_unary_rpc_method_handler( + servicer.Rollback, + request_deserializer=google_dot_cloud_dot_spanner__v1_dot_proto_dot_spanner__pb2.RollbackRequest.FromString, + response_serializer=google_dot_protobuf_dot_empty__pb2.Empty.SerializeToString, + ), + } + generic_handler = grpc.method_handlers_generic_handler( + 'google.spanner.v1.Spanner', rpc_method_handlers) + server.add_generic_rpc_handlers((generic_handler,)) diff --git a/spanner/google/cloud/spanner_v1/proto/transaction_pb2.py b/spanner/google/cloud/spanner_v1/proto/transaction_pb2.py new file mode 100644 index 000000000000..e82c4e5b5e59 --- /dev/null +++ b/spanner/google/cloud/spanner_v1/proto/transaction_pb2.py @@ -0,0 +1,460 @@ +# Generated by the protocol buffer compiler. DO NOT EDIT! +# source: google/cloud/spanner_v1/proto/transaction.proto + +import sys +_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) +from google.protobuf import descriptor as _descriptor +from google.protobuf import message as _message +from google.protobuf import reflection as _reflection +from google.protobuf import symbol_database as _symbol_database +from google.protobuf import descriptor_pb2 +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + + +from google.api import annotations_pb2 as google_dot_api_dot_annotations__pb2 +from google.protobuf import duration_pb2 as google_dot_protobuf_dot_duration__pb2 +from google.protobuf import timestamp_pb2 as google_dot_protobuf_dot_timestamp__pb2 + + +DESCRIPTOR = _descriptor.FileDescriptor( + name='google/cloud/spanner_v1/proto/transaction.proto', + package='google.spanner.v1', + syntax='proto3', + serialized_pb=_b('\n/google/cloud/spanner_v1/proto/transaction.proto\x12\x11google.spanner.v1\x1a\x1cgoogle/api/annotations.proto\x1a\x1egoogle/protobuf/duration.proto\x1a\x1fgoogle/protobuf/timestamp.proto\"\xe0\x03\n\x12TransactionOptions\x12\x45\n\nread_write\x18\x01 \x01(\x0b\x32/.google.spanner.v1.TransactionOptions.ReadWriteH\x00\x12\x43\n\tread_only\x18\x02 \x01(\x0b\x32..google.spanner.v1.TransactionOptions.ReadOnlyH\x00\x1a\x0b\n\tReadWrite\x1a\xa8\x02\n\x08ReadOnly\x12\x10\n\x06strong\x18\x01 \x01(\x08H\x00\x12\x38\n\x12min_read_timestamp\x18\x02 \x01(\x0b\x32\x1a.google.protobuf.TimestampH\x00\x12\x32\n\rmax_staleness\x18\x03 \x01(\x0b\x32\x19.google.protobuf.DurationH\x00\x12\x34\n\x0eread_timestamp\x18\x04 \x01(\x0b\x32\x1a.google.protobuf.TimestampH\x00\x12\x34\n\x0f\x65xact_staleness\x18\x05 \x01(\x0b\x32\x19.google.protobuf.DurationH\x00\x12\x1d\n\x15return_read_timestamp\x18\x06 \x01(\x08\x42\x11\n\x0ftimestamp_boundB\x06\n\x04mode\"M\n\x0bTransaction\x12\n\n\x02id\x18\x01 \x01(\x0c\x12\x32\n\x0eread_timestamp\x18\x02 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\"\xa4\x01\n\x13TransactionSelector\x12;\n\nsingle_use\x18\x01 \x01(\x0b\x32%.google.spanner.v1.TransactionOptionsH\x00\x12\x0c\n\x02id\x18\x02 \x01(\x0cH\x00\x12\x36\n\x05\x62\x65gin\x18\x03 \x01(\x0b\x32%.google.spanner.v1.TransactionOptionsH\x00\x42\n\n\x08selectorB\x7f\n\x15\x63om.google.spanner.v1B\x10TransactionProtoP\x01Z8google.golang.org/genproto/googleapis/spanner/v1;spanner\xaa\x02\x17Google.Cloud.Spanner.V1b\x06proto3') + , + dependencies=[google_dot_api_dot_annotations__pb2.DESCRIPTOR,google_dot_protobuf_dot_duration__pb2.DESCRIPTOR,google_dot_protobuf_dot_timestamp__pb2.DESCRIPTOR,]) +_sym_db.RegisterFileDescriptor(DESCRIPTOR) + + + + +_TRANSACTIONOPTIONS_READWRITE = _descriptor.Descriptor( + name='ReadWrite', + full_name='google.spanner.v1.TransactionOptions.ReadWrite', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto3', + extension_ranges=[], + oneofs=[ + ], + serialized_start=328, + serialized_end=339, +) + +_TRANSACTIONOPTIONS_READONLY = _descriptor.Descriptor( + name='ReadOnly', + full_name='google.spanner.v1.TransactionOptions.ReadOnly', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='strong', full_name='google.spanner.v1.TransactionOptions.ReadOnly.strong', index=0, + number=1, type=8, cpp_type=7, label=1, + has_default_value=False, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='min_read_timestamp', full_name='google.spanner.v1.TransactionOptions.ReadOnly.min_read_timestamp', index=1, + number=2, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='max_staleness', full_name='google.spanner.v1.TransactionOptions.ReadOnly.max_staleness', index=2, + number=3, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='read_timestamp', full_name='google.spanner.v1.TransactionOptions.ReadOnly.read_timestamp', index=3, + number=4, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='exact_staleness', full_name='google.spanner.v1.TransactionOptions.ReadOnly.exact_staleness', index=4, + number=5, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='return_read_timestamp', full_name='google.spanner.v1.TransactionOptions.ReadOnly.return_read_timestamp', index=5, + number=6, type=8, cpp_type=7, label=1, + has_default_value=False, default_value=False, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto3', + extension_ranges=[], + oneofs=[ + _descriptor.OneofDescriptor( + name='timestamp_bound', full_name='google.spanner.v1.TransactionOptions.ReadOnly.timestamp_bound', + index=0, containing_type=None, fields=[]), + ], + serialized_start=342, + serialized_end=638, +) + +_TRANSACTIONOPTIONS = _descriptor.Descriptor( + name='TransactionOptions', + full_name='google.spanner.v1.TransactionOptions', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='read_write', full_name='google.spanner.v1.TransactionOptions.read_write', index=0, + number=1, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='read_only', full_name='google.spanner.v1.TransactionOptions.read_only', index=1, + number=2, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[_TRANSACTIONOPTIONS_READWRITE, _TRANSACTIONOPTIONS_READONLY, ], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto3', + extension_ranges=[], + oneofs=[ + _descriptor.OneofDescriptor( + name='mode', full_name='google.spanner.v1.TransactionOptions.mode', + index=0, containing_type=None, fields=[]), + ], + serialized_start=166, + serialized_end=646, +) + + +_TRANSACTION = _descriptor.Descriptor( + name='Transaction', + full_name='google.spanner.v1.Transaction', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='id', full_name='google.spanner.v1.Transaction.id', index=0, + number=1, type=12, cpp_type=9, label=1, + has_default_value=False, default_value=_b(""), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='read_timestamp', full_name='google.spanner.v1.Transaction.read_timestamp', index=1, + number=2, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto3', + extension_ranges=[], + oneofs=[ + ], + serialized_start=648, + serialized_end=725, +) + + +_TRANSACTIONSELECTOR = _descriptor.Descriptor( + name='TransactionSelector', + full_name='google.spanner.v1.TransactionSelector', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='single_use', full_name='google.spanner.v1.TransactionSelector.single_use', index=0, + number=1, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='id', full_name='google.spanner.v1.TransactionSelector.id', index=1, + number=2, type=12, cpp_type=9, label=1, + has_default_value=False, default_value=_b(""), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='begin', full_name='google.spanner.v1.TransactionSelector.begin', index=2, + number=3, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto3', + extension_ranges=[], + oneofs=[ + _descriptor.OneofDescriptor( + name='selector', full_name='google.spanner.v1.TransactionSelector.selector', + index=0, containing_type=None, fields=[]), + ], + serialized_start=728, + serialized_end=892, +) + +_TRANSACTIONOPTIONS_READWRITE.containing_type = _TRANSACTIONOPTIONS +_TRANSACTIONOPTIONS_READONLY.fields_by_name['min_read_timestamp'].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP +_TRANSACTIONOPTIONS_READONLY.fields_by_name['max_staleness'].message_type = google_dot_protobuf_dot_duration__pb2._DURATION +_TRANSACTIONOPTIONS_READONLY.fields_by_name['read_timestamp'].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP +_TRANSACTIONOPTIONS_READONLY.fields_by_name['exact_staleness'].message_type = google_dot_protobuf_dot_duration__pb2._DURATION +_TRANSACTIONOPTIONS_READONLY.containing_type = _TRANSACTIONOPTIONS +_TRANSACTIONOPTIONS_READONLY.oneofs_by_name['timestamp_bound'].fields.append( + _TRANSACTIONOPTIONS_READONLY.fields_by_name['strong']) +_TRANSACTIONOPTIONS_READONLY.fields_by_name['strong'].containing_oneof = _TRANSACTIONOPTIONS_READONLY.oneofs_by_name['timestamp_bound'] +_TRANSACTIONOPTIONS_READONLY.oneofs_by_name['timestamp_bound'].fields.append( + _TRANSACTIONOPTIONS_READONLY.fields_by_name['min_read_timestamp']) +_TRANSACTIONOPTIONS_READONLY.fields_by_name['min_read_timestamp'].containing_oneof = _TRANSACTIONOPTIONS_READONLY.oneofs_by_name['timestamp_bound'] +_TRANSACTIONOPTIONS_READONLY.oneofs_by_name['timestamp_bound'].fields.append( + _TRANSACTIONOPTIONS_READONLY.fields_by_name['max_staleness']) +_TRANSACTIONOPTIONS_READONLY.fields_by_name['max_staleness'].containing_oneof = _TRANSACTIONOPTIONS_READONLY.oneofs_by_name['timestamp_bound'] +_TRANSACTIONOPTIONS_READONLY.oneofs_by_name['timestamp_bound'].fields.append( + _TRANSACTIONOPTIONS_READONLY.fields_by_name['read_timestamp']) +_TRANSACTIONOPTIONS_READONLY.fields_by_name['read_timestamp'].containing_oneof = _TRANSACTIONOPTIONS_READONLY.oneofs_by_name['timestamp_bound'] +_TRANSACTIONOPTIONS_READONLY.oneofs_by_name['timestamp_bound'].fields.append( + _TRANSACTIONOPTIONS_READONLY.fields_by_name['exact_staleness']) +_TRANSACTIONOPTIONS_READONLY.fields_by_name['exact_staleness'].containing_oneof = _TRANSACTIONOPTIONS_READONLY.oneofs_by_name['timestamp_bound'] +_TRANSACTIONOPTIONS.fields_by_name['read_write'].message_type = _TRANSACTIONOPTIONS_READWRITE +_TRANSACTIONOPTIONS.fields_by_name['read_only'].message_type = _TRANSACTIONOPTIONS_READONLY +_TRANSACTIONOPTIONS.oneofs_by_name['mode'].fields.append( + _TRANSACTIONOPTIONS.fields_by_name['read_write']) +_TRANSACTIONOPTIONS.fields_by_name['read_write'].containing_oneof = _TRANSACTIONOPTIONS.oneofs_by_name['mode'] +_TRANSACTIONOPTIONS.oneofs_by_name['mode'].fields.append( + _TRANSACTIONOPTIONS.fields_by_name['read_only']) +_TRANSACTIONOPTIONS.fields_by_name['read_only'].containing_oneof = _TRANSACTIONOPTIONS.oneofs_by_name['mode'] +_TRANSACTION.fields_by_name['read_timestamp'].message_type = google_dot_protobuf_dot_timestamp__pb2._TIMESTAMP +_TRANSACTIONSELECTOR.fields_by_name['single_use'].message_type = _TRANSACTIONOPTIONS +_TRANSACTIONSELECTOR.fields_by_name['begin'].message_type = _TRANSACTIONOPTIONS +_TRANSACTIONSELECTOR.oneofs_by_name['selector'].fields.append( + _TRANSACTIONSELECTOR.fields_by_name['single_use']) +_TRANSACTIONSELECTOR.fields_by_name['single_use'].containing_oneof = _TRANSACTIONSELECTOR.oneofs_by_name['selector'] +_TRANSACTIONSELECTOR.oneofs_by_name['selector'].fields.append( + _TRANSACTIONSELECTOR.fields_by_name['id']) +_TRANSACTIONSELECTOR.fields_by_name['id'].containing_oneof = _TRANSACTIONSELECTOR.oneofs_by_name['selector'] +_TRANSACTIONSELECTOR.oneofs_by_name['selector'].fields.append( + _TRANSACTIONSELECTOR.fields_by_name['begin']) +_TRANSACTIONSELECTOR.fields_by_name['begin'].containing_oneof = _TRANSACTIONSELECTOR.oneofs_by_name['selector'] +DESCRIPTOR.message_types_by_name['TransactionOptions'] = _TRANSACTIONOPTIONS +DESCRIPTOR.message_types_by_name['Transaction'] = _TRANSACTION +DESCRIPTOR.message_types_by_name['TransactionSelector'] = _TRANSACTIONSELECTOR + +TransactionOptions = _reflection.GeneratedProtocolMessageType('TransactionOptions', (_message.Message,), dict( + + ReadWrite = _reflection.GeneratedProtocolMessageType('ReadWrite', (_message.Message,), dict( + DESCRIPTOR = _TRANSACTIONOPTIONS_READWRITE, + __module__ = 'google.cloud.spanner_v1.proto.transaction_pb2' + , + __doc__ = """Options for read-write transactions. + """, + # @@protoc_insertion_point(class_scope:google.spanner.v1.TransactionOptions.ReadWrite) + )) + , + + ReadOnly = _reflection.GeneratedProtocolMessageType('ReadOnly', (_message.Message,), dict( + DESCRIPTOR = _TRANSACTIONOPTIONS_READONLY, + __module__ = 'google.cloud.spanner_v1.proto.transaction_pb2' + , + __doc__ = """Options for read-only transactions. + """, + # @@protoc_insertion_point(class_scope:google.spanner.v1.TransactionOptions.ReadOnly) + )) + , + DESCRIPTOR = _TRANSACTIONOPTIONS, + __module__ = 'google.cloud.spanner_v1.proto.transaction_pb2' + , + __doc__ = """See :ref:`spanner-txn` for more information on these. + + Attributes: + timestamp_bound: + How to choose the timestamp for the read-only transaction. + strong: + Read at a timestamp where all previously committed + transactions are visible. + min_read_timestamp: + Executes all reads at a timestamp >= ``min_read_timestamp``. + This is useful for requesting fresher data than some previous + read, or data that is fresh enough to observe the effects of + some previously committed transaction whose timestamp is + known. Note that this option can only be used in single-use + transactions. + max_staleness: + Read data at a timestamp >= ``NOW - max_staleness`` seconds. + Guarantees that all writes that have committed more than the + specified number of seconds ago are visible. Because Cloud + Spanner chooses the exact timestamp, this mode works even if + the client's local clock is substantially skewed from Cloud + Spanner commit timestamps. Useful for reading the freshest + data available at a nearby replica, while bounding the + possible staleness if the local replica has fallen behind. + Note that this option can only be used in single-use + transactions. + read_timestamp: + Executes all reads at the given timestamp. Unlike other modes, + reads at a specific timestamp are repeatable; the same read at + the same timestamp always returns the same data. If the + timestamp is in the future, the read will block until the + specified timestamp, modulo the read's deadline. Useful for + large scale consistent reads such as mapreduces, or for + coordinating many reads against a consistent snapshot of the + data. + exact_staleness: + Executes all reads at a timestamp that is ``exact_staleness`` + old. The timestamp is chosen soon after the read is started. + Guarantees that all writes that have committed more than the + specified number of seconds ago are visible. Because Cloud + Spanner chooses the exact timestamp, this mode works even if + the client's local clock is substantially skewed from Cloud + Spanner commit timestamps. Useful for reading at nearby + replicas without the distributed timestamp negotiation + overhead of ``max_staleness``. + return_read_timestamp: + If true, the Cloud Spanner-selected read timestamp is included + in the [Transaction][google.spanner.v1.Transaction] message + that describes the transaction. + mode: + Required. The type of transaction. + read_write: + Transaction may write. Authorization to begin a read-write + transaction requires + ``spanner.databases.beginOrRollbackReadWriteTransaction`` + permission on the ``session`` resource. + read_only: + Transaction will not write. Authorization to begin a read- + only transaction requires + ``spanner.databases.beginReadOnlyTransaction`` permission on + the ``session`` resource. + """, + # @@protoc_insertion_point(class_scope:google.spanner.v1.TransactionOptions) + )) +_sym_db.RegisterMessage(TransactionOptions) +_sym_db.RegisterMessage(TransactionOptions.ReadWrite) +_sym_db.RegisterMessage(TransactionOptions.ReadOnly) + +Transaction = _reflection.GeneratedProtocolMessageType('Transaction', (_message.Message,), dict( + DESCRIPTOR = _TRANSACTION, + __module__ = 'google.cloud.spanner_v1.proto.transaction_pb2' + , + __doc__ = """A transaction. + + + Attributes: + id: + ``id`` may be used to identify the transaction in subsequent + [Read][google.spanner.v1.Spanner.Read], + [ExecuteSql][google.spanner.v1.Spanner.ExecuteSql], + [Commit][google.spanner.v1.Spanner.Commit], or + [Rollback][google.spanner.v1.Spanner.Rollback] calls. Single- + use read-only transactions do not have IDs, because single-use + transactions do not support multiple requests. + read_timestamp: + For snapshot read-only transactions, the read timestamp chosen + for the transaction. Not returned by default: see [Transaction + Options.ReadOnly.return\_read\_timestamp][google.spanner.v1.Tr + ansactionOptions.ReadOnly.return\_read\_timestamp]. + """, + # @@protoc_insertion_point(class_scope:google.spanner.v1.Transaction) + )) +_sym_db.RegisterMessage(Transaction) + +TransactionSelector = _reflection.GeneratedProtocolMessageType('TransactionSelector', (_message.Message,), dict( + DESCRIPTOR = _TRANSACTIONSELECTOR, + __module__ = 'google.cloud.spanner_v1.proto.transaction_pb2' + , + __doc__ = """This message is used to select the transaction in which a + [Read][google.spanner.v1.Spanner.Read] or + [ExecuteSql][google.spanner.v1.Spanner.ExecuteSql] call runs. + + See [TransactionOptions][google.spanner.v1.TransactionOptions] for more + information about transactions. + + + Attributes: + selector: + If no fields are set, the default is a single use transaction + with strong concurrency. + single_use: + Execute the read or SQL query in a temporary transaction. This + is the most efficient way to execute a transaction that + consists of a single SQL query. + id: + Execute the read or SQL query in a previously-started + transaction. + begin: + Begin a new transaction and execute this read or SQL query in + it. The transaction ID of the new transaction is returned in [ + ResultSetMetadata.transaction][google.spanner.v1.ResultSetMeta + data.transaction], which is a + [Transaction][google.spanner.v1.Transaction]. + """, + # @@protoc_insertion_point(class_scope:google.spanner.v1.TransactionSelector) + )) +_sym_db.RegisterMessage(TransactionSelector) + + +DESCRIPTOR.has_options = True +DESCRIPTOR._options = _descriptor._ParseOptions(descriptor_pb2.FileOptions(), _b('\n\025com.google.spanner.v1B\020TransactionProtoP\001Z8google.golang.org/genproto/googleapis/spanner/v1;spanner\252\002\027Google.Cloud.Spanner.V1')) +try: + # THESE ELEMENTS WILL BE DEPRECATED. + # Please use the generated *_pb2_grpc.py files instead. + import grpc + from grpc.beta import implementations as beta_implementations + from grpc.beta import interfaces as beta_interfaces + from grpc.framework.common import cardinality + from grpc.framework.interfaces.face import utilities as face_utilities +except ImportError: + pass +# @@protoc_insertion_point(module_scope) diff --git a/spanner/google/cloud/spanner_v1/proto/transaction_pb2_grpc.py b/spanner/google/cloud/spanner_v1/proto/transaction_pb2_grpc.py new file mode 100644 index 000000000000..a89435267cb2 --- /dev/null +++ b/spanner/google/cloud/spanner_v1/proto/transaction_pb2_grpc.py @@ -0,0 +1,3 @@ +# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! +import grpc + diff --git a/spanner/google/cloud/spanner_v1/proto/type_pb2.py b/spanner/google/cloud/spanner_v1/proto/type_pb2.py new file mode 100644 index 000000000000..8c2bd21f1f4e --- /dev/null +++ b/spanner/google/cloud/spanner_v1/proto/type_pb2.py @@ -0,0 +1,301 @@ +# Generated by the protocol buffer compiler. DO NOT EDIT! +# source: google/cloud/spanner_v1/proto/type.proto + +import sys +_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) +from google.protobuf.internal import enum_type_wrapper +from google.protobuf import descriptor as _descriptor +from google.protobuf import message as _message +from google.protobuf import reflection as _reflection +from google.protobuf import symbol_database as _symbol_database +from google.protobuf import descriptor_pb2 +# @@protoc_insertion_point(imports) + +_sym_db = _symbol_database.Default() + + +from google.api import annotations_pb2 as google_dot_api_dot_annotations__pb2 + + +DESCRIPTOR = _descriptor.FileDescriptor( + name='google/cloud/spanner_v1/proto/type.proto', + package='google.spanner.v1', + syntax='proto3', + serialized_pb=_b('\n(google/cloud/spanner_v1/proto/type.proto\x12\x11google.spanner.v1\x1a\x1cgoogle/api/annotations.proto\"\x9a\x01\n\x04Type\x12)\n\x04\x63ode\x18\x01 \x01(\x0e\x32\x1b.google.spanner.v1.TypeCode\x12\x33\n\x12\x61rray_element_type\x18\x02 \x01(\x0b\x32\x17.google.spanner.v1.Type\x12\x32\n\x0bstruct_type\x18\x03 \x01(\x0b\x32\x1d.google.spanner.v1.StructType\"\x7f\n\nStructType\x12\x33\n\x06\x66ields\x18\x01 \x03(\x0b\x32#.google.spanner.v1.StructType.Field\x1a<\n\x05\x46ield\x12\x0c\n\x04name\x18\x01 \x01(\t\x12%\n\x04type\x18\x02 \x01(\x0b\x32\x17.google.spanner.v1.Type*\x8e\x01\n\x08TypeCode\x12\x19\n\x15TYPE_CODE_UNSPECIFIED\x10\x00\x12\x08\n\x04\x42OOL\x10\x01\x12\t\n\x05INT64\x10\x02\x12\x0b\n\x07\x46LOAT64\x10\x03\x12\r\n\tTIMESTAMP\x10\x04\x12\x08\n\x04\x44\x41TE\x10\x05\x12\n\n\x06STRING\x10\x06\x12\t\n\x05\x42YTES\x10\x07\x12\t\n\x05\x41RRAY\x10\x08\x12\n\n\x06STRUCT\x10\tBx\n\x15\x63om.google.spanner.v1B\tTypeProtoP\x01Z8google.golang.org/genproto/googleapis/spanner/v1;spanner\xaa\x02\x17Google.Cloud.Spanner.V1b\x06proto3') + , + dependencies=[google_dot_api_dot_annotations__pb2.DESCRIPTOR,]) +_sym_db.RegisterFileDescriptor(DESCRIPTOR) + +_TYPECODE = _descriptor.EnumDescriptor( + name='TypeCode', + full_name='google.spanner.v1.TypeCode', + filename=None, + file=DESCRIPTOR, + values=[ + _descriptor.EnumValueDescriptor( + name='TYPE_CODE_UNSPECIFIED', index=0, number=0, + options=None, + type=None), + _descriptor.EnumValueDescriptor( + name='BOOL', index=1, number=1, + options=None, + type=None), + _descriptor.EnumValueDescriptor( + name='INT64', index=2, number=2, + options=None, + type=None), + _descriptor.EnumValueDescriptor( + name='FLOAT64', index=3, number=3, + options=None, + type=None), + _descriptor.EnumValueDescriptor( + name='TIMESTAMP', index=4, number=4, + options=None, + type=None), + _descriptor.EnumValueDescriptor( + name='DATE', index=5, number=5, + options=None, + type=None), + _descriptor.EnumValueDescriptor( + name='STRING', index=6, number=6, + options=None, + type=None), + _descriptor.EnumValueDescriptor( + name='BYTES', index=7, number=7, + options=None, + type=None), + _descriptor.EnumValueDescriptor( + name='ARRAY', index=8, number=8, + options=None, + type=None), + _descriptor.EnumValueDescriptor( + name='STRUCT', index=9, number=9, + options=None, + type=None), + ], + containing_type=None, + options=None, + serialized_start=380, + serialized_end=522, +) +_sym_db.RegisterEnumDescriptor(_TYPECODE) + +TypeCode = enum_type_wrapper.EnumTypeWrapper(_TYPECODE) +TYPE_CODE_UNSPECIFIED = 0 +BOOL = 1 +INT64 = 2 +FLOAT64 = 3 +TIMESTAMP = 4 +DATE = 5 +STRING = 6 +BYTES = 7 +ARRAY = 8 +STRUCT = 9 + + + +_TYPE = _descriptor.Descriptor( + name='Type', + full_name='google.spanner.v1.Type', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='code', full_name='google.spanner.v1.Type.code', index=0, + number=1, type=14, cpp_type=8, label=1, + has_default_value=False, default_value=0, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='array_element_type', full_name='google.spanner.v1.Type.array_element_type', index=1, + number=2, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='struct_type', full_name='google.spanner.v1.Type.struct_type', index=2, + number=3, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto3', + extension_ranges=[], + oneofs=[ + ], + serialized_start=94, + serialized_end=248, +) + + +_STRUCTTYPE_FIELD = _descriptor.Descriptor( + name='Field', + full_name='google.spanner.v1.StructType.Field', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='name', full_name='google.spanner.v1.StructType.Field.name', index=0, + number=1, type=9, cpp_type=9, label=1, + has_default_value=False, default_value=_b("").decode('utf-8'), + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + _descriptor.FieldDescriptor( + name='type', full_name='google.spanner.v1.StructType.Field.type', index=1, + number=2, type=11, cpp_type=10, label=1, + has_default_value=False, default_value=None, + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto3', + extension_ranges=[], + oneofs=[ + ], + serialized_start=317, + serialized_end=377, +) + +_STRUCTTYPE = _descriptor.Descriptor( + name='StructType', + full_name='google.spanner.v1.StructType', + filename=None, + file=DESCRIPTOR, + containing_type=None, + fields=[ + _descriptor.FieldDescriptor( + name='fields', full_name='google.spanner.v1.StructType.fields', index=0, + number=1, type=11, cpp_type=10, label=3, + has_default_value=False, default_value=[], + message_type=None, enum_type=None, containing_type=None, + is_extension=False, extension_scope=None, + options=None), + ], + extensions=[ + ], + nested_types=[_STRUCTTYPE_FIELD, ], + enum_types=[ + ], + options=None, + is_extendable=False, + syntax='proto3', + extension_ranges=[], + oneofs=[ + ], + serialized_start=250, + serialized_end=377, +) + +_TYPE.fields_by_name['code'].enum_type = _TYPECODE +_TYPE.fields_by_name['array_element_type'].message_type = _TYPE +_TYPE.fields_by_name['struct_type'].message_type = _STRUCTTYPE +_STRUCTTYPE_FIELD.fields_by_name['type'].message_type = _TYPE +_STRUCTTYPE_FIELD.containing_type = _STRUCTTYPE +_STRUCTTYPE.fields_by_name['fields'].message_type = _STRUCTTYPE_FIELD +DESCRIPTOR.message_types_by_name['Type'] = _TYPE +DESCRIPTOR.message_types_by_name['StructType'] = _STRUCTTYPE +DESCRIPTOR.enum_types_by_name['TypeCode'] = _TYPECODE + +Type = _reflection.GeneratedProtocolMessageType('Type', (_message.Message,), dict( + DESCRIPTOR = _TYPE, + __module__ = 'google.cloud.spanner_v1.proto.type_pb2' + , + __doc__ = """``Type`` indicates the type of a Cloud Spanner value, as might be stored + in a table cell or returned from an SQL query. + + + Attributes: + code: + Required. The [TypeCode][google.spanner.v1.TypeCode] for this + type. + array_element_type: + If [code][google.spanner.v1.Type.code] == + [ARRAY][google.spanner.v1.TypeCode.ARRAY], then + ``array_element_type`` is the type of the array elements. + struct_type: + If [code][google.spanner.v1.Type.code] == + [STRUCT][google.spanner.v1.TypeCode.STRUCT], then + ``struct_type`` provides type information for the struct's + fields. + """, + # @@protoc_insertion_point(class_scope:google.spanner.v1.Type) + )) +_sym_db.RegisterMessage(Type) + +StructType = _reflection.GeneratedProtocolMessageType('StructType', (_message.Message,), dict( + + Field = _reflection.GeneratedProtocolMessageType('Field', (_message.Message,), dict( + DESCRIPTOR = _STRUCTTYPE_FIELD, + __module__ = 'google.cloud.spanner_v1.proto.type_pb2' + , + __doc__ = """Message representing a single field of a struct. + """, + # @@protoc_insertion_point(class_scope:google.spanner.v1.StructType.Field) + )) + , + DESCRIPTOR = _STRUCTTYPE, + __module__ = 'google.cloud.spanner_v1.proto.type_pb2' + , + __doc__ = """``StructType`` defines the fields of a + [STRUCT][google.spanner.v1.TypeCode.STRUCT] type. + + + Attributes: + name: + The name of the field. For reads, this is the column name. For + SQL queries, it is the column alias (e.g., ``"Word"`` in the + query ``"SELECT 'hello' AS Word"``), or the column name (e.g., + ``"ColName"`` in the query ``"SELECT ColName FROM Table"``). + Some columns might have an empty name (e.g., !"SELECT + UPPER(ColName)"\`). Note that a query result can contain + multiple fields with the same name. + type: + The type of the field. + fields: + The list of fields that make up this struct. Order is + significant, because values of this struct type are + represented as lists, where the order of field values matches + the order of fields in the + [StructType][google.spanner.v1.StructType]. In turn, the order + of fields matches the order of columns in a read request, or + the order of fields in the ``SELECT`` clause of a query. + """, + # @@protoc_insertion_point(class_scope:google.spanner.v1.StructType) + )) +_sym_db.RegisterMessage(StructType) +_sym_db.RegisterMessage(StructType.Field) + + +DESCRIPTOR.has_options = True +DESCRIPTOR._options = _descriptor._ParseOptions(descriptor_pb2.FileOptions(), _b('\n\025com.google.spanner.v1B\tTypeProtoP\001Z8google.golang.org/genproto/googleapis/spanner/v1;spanner\252\002\027Google.Cloud.Spanner.V1')) +try: + # THESE ELEMENTS WILL BE DEPRECATED. + # Please use the generated *_pb2_grpc.py files instead. + import grpc + from grpc.beta import implementations as beta_implementations + from grpc.beta import interfaces as beta_interfaces + from grpc.framework.common import cardinality + from grpc.framework.interfaces.face import utilities as face_utilities +except ImportError: + pass +# @@protoc_insertion_point(module_scope) diff --git a/spanner/google/cloud/spanner_v1/proto/type_pb2_grpc.py b/spanner/google/cloud/spanner_v1/proto/type_pb2_grpc.py new file mode 100644 index 000000000000..a89435267cb2 --- /dev/null +++ b/spanner/google/cloud/spanner_v1/proto/type_pb2_grpc.py @@ -0,0 +1,3 @@ +# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! +import grpc + diff --git a/spanner/google/cloud/spanner/session.py b/spanner/google/cloud/spanner_v1/session.py similarity index 93% rename from spanner/google/cloud/spanner/session.py rename to spanner/google/cloud/spanner_v1/session.py index 94fd0f092366..103fb4aafae5 100644 --- a/spanner/google/cloud/spanner/session.py +++ b/spanner/google/cloud/spanner_v1/session.py @@ -25,10 +25,10 @@ # pylint: disable=ungrouped-imports from google.cloud.exceptions import NotFound from google.cloud.exceptions import GrpcRendezvous -from google.cloud.spanner._helpers import _options_with_prefix -from google.cloud.spanner.batch import Batch -from google.cloud.spanner.snapshot import Snapshot -from google.cloud.spanner.transaction import Transaction +from google.cloud.spanner_v1._helpers import _options_with_prefix +from google.cloud.spanner_v1.batch import Batch +from google.cloud.spanner_v1.snapshot import Snapshot +from google.cloud.spanner_v1.transaction import Transaction # pylint: enable=ungrouped-imports @@ -46,7 +46,7 @@ class Session(object): * Use :meth:`exists` to check for the existence of the session * :meth:`drop` the session - :type database: :class:`~google.cloud.spanner.database.Database` + :type database: :class:`~google.cloud.spanner_v1.database.Database` :param database: The database to which the session is bound. """ @@ -154,9 +154,9 @@ def snapshot(self, **kw): :type kw: dict :param kw: Passed through to - :class:`~google.cloud.spanner.snapshot.Snapshot` ctor. + :class:`~google.cloud.spanner_v1.snapshot.Snapshot` ctor. - :rtype: :class:`~google.cloud.spanner.snapshot.Snapshot` + :rtype: :class:`~google.cloud.spanner_v1.snapshot.Snapshot` :returns: a snapshot bound to this session :raises ValueError: if the session has not yet been created. """ @@ -174,7 +174,7 @@ def read(self, table, columns, keyset, index='', limit=0): :type columns: list of str :param columns: names of columns to be retrieved - :type keyset: :class:`~google.cloud.spanner.keyset.KeySet` + :type keyset: :class:`~google.cloud.spanner_v1.keyset.KeySet` :param keyset: keys / ranges identifying rows to be retrieved :type index: str @@ -184,7 +184,7 @@ def read(self, table, columns, keyset, index='', limit=0): :type limit: int :param limit: (Optional) maxiumn number of rows to return - :rtype: :class:`~google.cloud.spanner.streamed.StreamedResultSet` + :rtype: :class:`~google.cloud.spanner_v1.streamed.StreamedResultSet` :returns: a result set instance which can be used to consume rows. """ return self.snapshot().read(table, columns, keyset, index, limit) @@ -210,7 +210,7 @@ def execute_sql(self, sql, params=None, param_types=None, query_mode=None): :param query_mode: Mode governing return of results / query plan. See https://cloud.google.com/spanner/reference/rpc/google.spanner.v1#google.spanner.v1.ExecuteSqlRequest.QueryMode1 - :rtype: :class:`~google.cloud.spanner.streamed.StreamedResultSet` + :rtype: :class:`~google.cloud.spanner_v1.streamed.StreamedResultSet` :returns: a result set instance which can be used to consume rows. """ return self.snapshot().execute_sql( @@ -219,7 +219,7 @@ def execute_sql(self, sql, params=None, param_types=None, query_mode=None): def batch(self): """Factory to create a batch for this session. - :rtype: :class:`~google.cloud.spanner.batch.Batch` + :rtype: :class:`~google.cloud.spanner_v1.batch.Batch` :returns: a batch bound to this session :raises ValueError: if the session has not yet been created. """ @@ -231,7 +231,7 @@ def batch(self): def transaction(self): """Create a transaction to perform a set of reads with shared staleness. - :rtype: :class:`~google.cloud.spanner.transaction.Transaction` + :rtype: :class:`~google.cloud.spanner_v1.transaction.Transaction` :returns: a transaction bound to this session :raises ValueError: if the session has not yet been created. """ diff --git a/spanner/google/cloud/spanner/snapshot.py b/spanner/google/cloud/spanner_v1/snapshot.py similarity index 93% rename from spanner/google/cloud/spanner/snapshot.py rename to spanner/google/cloud/spanner_v1/snapshot.py index 7c5ff449448c..8f2a8ca8d9d4 100644 --- a/spanner/google/cloud/spanner/snapshot.py +++ b/spanner/google/cloud/spanner_v1/snapshot.py @@ -17,16 +17,16 @@ import functools from google.protobuf.struct_pb2 import Struct -from google.cloud.proto.spanner.v1.transaction_pb2 import TransactionOptions -from google.cloud.proto.spanner.v1.transaction_pb2 import TransactionSelector +from google.cloud.spanner_v1.proto.transaction_pb2 import TransactionOptions +from google.cloud.spanner_v1.proto.transaction_pb2 import TransactionSelector from google.api.core.exceptions import ServiceUnavailable from google.cloud._helpers import _datetime_to_pb_timestamp from google.cloud._helpers import _timedelta_to_duration_pb -from google.cloud.spanner._helpers import _make_value_pb -from google.cloud.spanner._helpers import _options_with_prefix -from google.cloud.spanner._helpers import _SessionWrapper -from google.cloud.spanner.streamed import StreamedResultSet +from google.cloud.spanner_v1._helpers import _make_value_pb +from google.cloud.spanner_v1._helpers import _options_with_prefix +from google.cloud.spanner_v1._helpers import _SessionWrapper +from google.cloud.spanner_v1.streamed import StreamedResultSet def _restart_on_unavailable(restart): @@ -64,7 +64,7 @@ class _SnapshotBase(_SessionWrapper): Allows reuse of API request methods with different transaction selector. - :type session: :class:`~google.cloud.spanner.session.Session` + :type session: :class:`~google.cloud.spanner_v1.session.Session` :param session: the session used to perform the commit """ _multi_use = False @@ -91,7 +91,7 @@ def read(self, table, columns, keyset, index='', limit=0): :type columns: list of str :param columns: names of columns to be retrieved - :type keyset: :class:`~google.cloud.spanner.keyset.KeySet` + :type keyset: :class:`~google.cloud.spanner_v1.keyset.KeySet` :param keyset: keys / ranges identifying rows to be retrieved :type index: str @@ -101,7 +101,7 @@ def read(self, table, columns, keyset, index='', limit=0): :type limit: int :param limit: (Optional) maxiumn number of rows to return - :rtype: :class:`~google.cloud.spanner.streamed.StreamedResultSet` + :rtype: :class:`~google.cloud.spanner_v1.streamed.StreamedResultSet` :returns: a result set instance which can be used to consume rows. :raises ValueError: for reuse of single-use snapshots, or if a transaction ID is @@ -149,11 +149,11 @@ def execute_sql(self, sql, params=None, param_types=None, query_mode=None): required if parameters are passed. :type query_mode: - :class:`google.cloud.proto.spanner.v1.ExecuteSqlRequest.QueryMode` + :class:`google.cloud.spanner_v1.proto.ExecuteSqlRequest.QueryMode` :param query_mode: Mode governing return of results / query plan. See https://cloud.google.com/spanner/reference/rpc/google.spanner.v1#google.spanner.v1.ExecuteSqlRequest.QueryMode1 - :rtype: :class:`~google.cloud.spanner.streamed.StreamedResultSet` + :rtype: :class:`~google.cloud.spanner_v1.streamed.StreamedResultSet` :returns: a result set instance which can be used to consume rows. :raises ValueError: for reuse of single-use snapshots, or if a transaction ID is @@ -204,7 +204,7 @@ class Snapshot(_SnapshotBase): If no options are passed, reads will use the ``strong`` model, reading at a timestamp where all previously committed transactions are visible. - :type session: :class:`~google.cloud.spanner.session.Session` + :type session: :class:`~google.cloud.spanner_v1.session.Session` :param session: the session used to perform the commit. :type read_timestamp: :class:`datetime.datetime` diff --git a/spanner/google/cloud/spanner/streamed.py b/spanner/google/cloud/spanner_v1/streamed.py similarity index 95% rename from spanner/google/cloud/spanner/streamed.py rename to spanner/google/cloud/spanner_v1/streamed.py index 67503f2c0d7f..4e989e29cb72 100644 --- a/spanner/google/cloud/spanner/streamed.py +++ b/spanner/google/cloud/spanner_v1/streamed.py @@ -17,11 +17,11 @@ from google.protobuf.struct_pb2 import ListValue from google.protobuf.struct_pb2 import Value from google.cloud import exceptions -from google.cloud.proto.spanner.v1 import type_pb2 +from google.cloud.spanner_v1.proto import type_pb2 import six # pylint: disable=ungrouped-imports -from google.cloud.spanner._helpers import _parse_value_pb +from google.cloud.spanner_v1._helpers import _parse_value_pb # pylint: enable=ungrouped-imports @@ -31,10 +31,10 @@ class StreamedResultSet(object): :type response_iterator: :param response_iterator: Iterator yielding - :class:`google.cloud.proto.spanner.v1.result_set_pb2.PartialResultSet` + :class:`google.cloud.spanner_v1.proto.result_set_pb2.PartialResultSet` instances. - :type source: :class:`~google.cloud.spanner.snapshot.Snapshot` + :type source: :class:`~google.cloud.spanner_v1.snapshot.Snapshot` :param source: Snapshot from which the result set was fetched. """ def __init__(self, response_iterator, source=None): @@ -60,7 +60,7 @@ def rows(self): def fields(self): """Field descriptors for result set columns. - :rtype: list of :class:`~google.cloud.proto.spanner.v1.type_pb2.Field` + :rtype: list of :class:`~google.cloud.spanner_v1.proto.type_pb2.Field` :returns: list of fields describing column names / types. """ return self._metadata.row_type.fields @@ -79,7 +79,7 @@ def stats(self): """Result set statistics :rtype: - :class:`~google.cloud.proto.spanner.v1.result_set_pb2.ResultSetStats` + :class:`~google.cloud.spanner_v1.proto.result_set_pb2.ResultSetStats` :returns: structure describing status about the response """ return self._stats @@ -211,7 +211,7 @@ class Unmergeable(ValueError): :type rhs: :class:`google.protobuf.struct_pb2.Value` :param rhs: remaining value to be merged - :type type_: :class:`google.cloud.proto.spanner.v1.type_pb2.Type` + :type type_: :class:`google.cloud.spanner_v1.proto.type_pb2.Type` :param type_: field type of values being merged """ def __init__(self, lhs, rhs, type_): diff --git a/spanner/google/cloud/spanner/transaction.py b/spanner/google/cloud/spanner_v1/transaction.py similarity index 92% rename from spanner/google/cloud/spanner/transaction.py rename to spanner/google/cloud/spanner_v1/transaction.py index 7ac4251dea7d..1f260293f2ef 100644 --- a/spanner/google/cloud/spanner/transaction.py +++ b/spanner/google/cloud/spanner_v1/transaction.py @@ -14,19 +14,19 @@ """Spanner read-write transaction support.""" -from google.cloud.proto.spanner.v1.transaction_pb2 import TransactionSelector -from google.cloud.proto.spanner.v1.transaction_pb2 import TransactionOptions +from google.cloud.spanner_v1.proto.transaction_pb2 import TransactionSelector +from google.cloud.spanner_v1.proto.transaction_pb2 import TransactionOptions from google.cloud._helpers import _pb_timestamp_to_datetime -from google.cloud.spanner._helpers import _options_with_prefix -from google.cloud.spanner.snapshot import _SnapshotBase -from google.cloud.spanner.batch import _BatchBase +from google.cloud.spanner_v1._helpers import _options_with_prefix +from google.cloud.spanner_v1.snapshot import _SnapshotBase +from google.cloud.spanner_v1.batch import _BatchBase class Transaction(_SnapshotBase, _BatchBase): """Implement read-write transaction semantics for a session. - :type session: :class:`~google.cloud.spanner.session.Session` + :type session: :class:`~google.cloud.spanner_v1.session.Session` :param session: the session used to perform the commit :raises ValueError: if session has an existing transaction diff --git a/spanner/google/cloud/spanner_v1/types.py b/spanner/google/cloud/spanner_v1/types.py new file mode 100644 index 000000000000..6bc36fc7ce50 --- /dev/null +++ b/spanner/google/cloud/spanner_v1/types.py @@ -0,0 +1,56 @@ +# Copyright 2017, Google Inc. All rights reserved. +# +# 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 +# +# http://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. + +from __future__ import absolute_import +import sys + +from google.gax.utils.messages import get_messages + +from google.api import auth_pb2 +from google.api import http_pb2 +from google.cloud.spanner_v1.proto import keys_pb2 +from google.cloud.spanner_v1.proto import mutation_pb2 +from google.cloud.spanner_v1.proto import query_plan_pb2 +from google.cloud.spanner_v1.proto import result_set_pb2 +from google.cloud.spanner_v1.proto import spanner_pb2 +from google.cloud.spanner_v1.proto import transaction_pb2 +from google.cloud.spanner_v1.proto import type_pb2 +from google.protobuf import descriptor_pb2 +from google.protobuf import duration_pb2 +from google.protobuf import empty_pb2 +from google.protobuf import struct_pb2 +from google.protobuf import timestamp_pb2 + +names = [] +for module in ( + auth_pb2, + http_pb2, + keys_pb2, + mutation_pb2, + query_plan_pb2, + result_set_pb2, + spanner_pb2, + transaction_pb2, + type_pb2, + descriptor_pb2, + duration_pb2, + empty_pb2, + struct_pb2, + timestamp_pb2, ): + for name, message in get_messages(module).items(): + message.__module__ = 'google.cloud.spanner_v1.types' + setattr(sys.modules[__name__], name, message) + names.append(name) + +__all__ = tuple(sorted(names)) diff --git a/spanner/setup.py b/spanner/setup.py index 1ece643bd6fe..091cf05d8741 100644 --- a/spanner/setup.py +++ b/spanner/setup.py @@ -35,7 +35,7 @@ 'include_package_data': True, 'zip_safe': False, 'classifiers': [ - 'Development Status :: 3 - Alpha', + 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: Apache Software License', 'Operating System :: OS Independent', @@ -51,17 +51,17 @@ REQUIREMENTS = [ - 'google-cloud-core >= 0.27.0, < 0.28dev', 'google-auth >= 1.1.0', - 'grpcio >= 1.2.0, < 2.0dev', - 'gapic-google-cloud-spanner-v1 >= 0.15.0, < 0.16dev', - 'gapic-google-cloud-spanner-admin-database-v1 >= 0.15.0, < 0.16dev', - 'gapic-google-cloud-spanner-admin-instance-v1 >= 0.15.0, < 0.16dev', + 'google-cloud-core >= 0.27.0, < 0.28dev', + 'google-gax>=0.15.15, <0.16dev', + 'googleapis-common-protos[grpc]>=1.5.2, <2.0dev', + 'grpc-google-iam-v1>=0.11.4, <0.12dev', + 'requests>=2.18.4, <3.0dev', ] setup( name='google-cloud-spanner', - version='0.27.0', + version='0.28.0', description='Python Client for Cloud Spanner', long_description=README, namespace_packages=[ diff --git a/spanner/tests/system/test_system.py b/spanner/tests/system/test_system.py index 64177765cb2d..26ee0ee34aac 100644 --- a/spanner/tests/system/test_system.py +++ b/spanner/tests/system/test_system.py @@ -21,23 +21,23 @@ import time import unittest -from google.cloud.proto.spanner.v1.type_pb2 import ARRAY -from google.cloud.proto.spanner.v1.type_pb2 import BOOL -from google.cloud.proto.spanner.v1.type_pb2 import BYTES -from google.cloud.proto.spanner.v1.type_pb2 import DATE -from google.cloud.proto.spanner.v1.type_pb2 import FLOAT64 -from google.cloud.proto.spanner.v1.type_pb2 import INT64 -from google.cloud.proto.spanner.v1.type_pb2 import STRING -from google.cloud.proto.spanner.v1.type_pb2 import TIMESTAMP -from google.cloud.proto.spanner.v1.type_pb2 import Type +from google.cloud.spanner_v1.proto.type_pb2 import ARRAY +from google.cloud.spanner_v1.proto.type_pb2 import BOOL +from google.cloud.spanner_v1.proto.type_pb2 import BYTES +from google.cloud.spanner_v1.proto.type_pb2 import DATE +from google.cloud.spanner_v1.proto.type_pb2 import FLOAT64 +from google.cloud.spanner_v1.proto.type_pb2 import INT64 +from google.cloud.spanner_v1.proto.type_pb2 import STRING +from google.cloud.spanner_v1.proto.type_pb2 import TIMESTAMP +from google.cloud.spanner_v1.proto.type_pb2 import Type from google.cloud._helpers import UTC from google.cloud.exceptions import GrpcRendezvous -from google.cloud.spanner._helpers import TimestampWithNanoseconds -from google.cloud.spanner.client import Client -from google.cloud.spanner.keyset import KeyRange -from google.cloud.spanner.keyset import KeySet -from google.cloud.spanner.pool import BurstyPool +from google.cloud.spanner_v1._helpers import TimestampWithNanoseconds +from google.cloud.spanner import Client +from google.cloud.spanner import KeyRange +from google.cloud.spanner import KeySet +from google.cloud.spanner import BurstyPool from test_utils.retry import RetryErrors from test_utils.retry import RetryInstanceState diff --git a/spanner/tests/unit/gapic/v1/test_database_admin_client_v1.py b/spanner/tests/unit/gapic/v1/test_database_admin_client_v1.py new file mode 100644 index 000000000000..1f527dbca940 --- /dev/null +++ b/spanner/tests/unit/gapic/v1/test_database_admin_client_v1.py @@ -0,0 +1,506 @@ +# Copyright 2017, Google Inc. All rights reserved. +# +# 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 +# +# http://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. +"""Unit tests.""" + +import mock +import unittest + +from google.gax import errors +from google.rpc import status_pb2 + +from google.cloud import spanner_admin_database_v1 +from google.cloud.spanner_admin_database_v1.proto import spanner_database_admin_pb2 +from google.iam.v1 import iam_policy_pb2 +from google.iam.v1 import policy_pb2 +from google.longrunning import operations_pb2 +from google.protobuf import empty_pb2 + + +class CustomException(Exception): + pass + + +class TestDatabaseAdminClient(unittest.TestCase): + @mock.patch('google.gax.config.create_stub', spec=True) + def test_list_databases(self, mock_create_stub): + # Mock gRPC layer + grpc_stub = mock.Mock() + mock_create_stub.return_value = grpc_stub + + client = spanner_admin_database_v1.DatabaseAdminClient() + + # Mock request + parent = client.instance_path('[PROJECT]', '[INSTANCE]') + + # Mock response + next_page_token = '' + databases_element = {} + databases = [databases_element] + expected_response = { + 'next_page_token': next_page_token, + 'databases': databases + } + expected_response = spanner_database_admin_pb2.ListDatabasesResponse( + **expected_response) + grpc_stub.ListDatabases.return_value = expected_response + + paged_list_response = client.list_databases(parent) + resources = list(paged_list_response) + self.assertEqual(1, len(resources)) + self.assertEqual(expected_response.databases[0], resources[0]) + + grpc_stub.ListDatabases.assert_called_once() + args, kwargs = grpc_stub.ListDatabases.call_args + self.assertEqual(len(args), 2) + self.assertEqual(len(kwargs), 1) + self.assertIn('metadata', kwargs) + actual_request = args[0] + + expected_request = spanner_database_admin_pb2.ListDatabasesRequest( + parent=parent) + self.assertEqual(expected_request, actual_request) + + @mock.patch('google.gax.config.API_ERRORS', (CustomException, )) + @mock.patch('google.gax.config.create_stub', spec=True) + def test_list_databases_exception(self, mock_create_stub): + # Mock gRPC layer + grpc_stub = mock.Mock() + mock_create_stub.return_value = grpc_stub + + client = spanner_admin_database_v1.DatabaseAdminClient() + + # Mock request + parent = client.instance_path('[PROJECT]', '[INSTANCE]') + + # Mock exception response + grpc_stub.ListDatabases.side_effect = CustomException() + + paged_list_response = client.list_databases(parent) + self.assertRaises(errors.GaxError, list, paged_list_response) + + @mock.patch('google.gax.config.create_stub', spec=True) + def test_create_database(self, mock_create_stub): + # Mock gRPC layer + grpc_stub = mock.Mock() + mock_create_stub.return_value = grpc_stub + + client = spanner_admin_database_v1.DatabaseAdminClient() + + # Mock request + parent = client.instance_path('[PROJECT]', '[INSTANCE]') + create_statement = 'createStatement552974828' + + # Mock response + name = 'name3373707' + expected_response = {'name': name} + expected_response = spanner_database_admin_pb2.Database( + **expected_response) + operation = operations_pb2.Operation( + name='operations/test_create_database', done=True) + operation.response.Pack(expected_response) + grpc_stub.CreateDatabase.return_value = operation + + response = client.create_database(parent, create_statement) + self.assertEqual(expected_response, response.result()) + + grpc_stub.CreateDatabase.assert_called_once() + args, kwargs = grpc_stub.CreateDatabase.call_args + self.assertEqual(len(args), 2) + self.assertEqual(len(kwargs), 1) + self.assertIn('metadata', kwargs) + actual_request = args[0] + + expected_request = spanner_database_admin_pb2.CreateDatabaseRequest( + parent=parent, create_statement=create_statement) + self.assertEqual(expected_request, actual_request) + + @mock.patch('google.gax.config.create_stub', spec=True) + def test_create_database_exception(self, mock_create_stub): + # Mock gRPC layer + grpc_stub = mock.Mock() + mock_create_stub.return_value = grpc_stub + + client = spanner_admin_database_v1.DatabaseAdminClient() + + # Mock request + parent = client.instance_path('[PROJECT]', '[INSTANCE]') + create_statement = 'createStatement552974828' + + # Mock exception response + error = status_pb2.Status() + operation = operations_pb2.Operation( + name='operations/test_create_database_exception', done=True) + operation.error.CopyFrom(error) + grpc_stub.CreateDatabase.return_value = operation + + response = client.create_database(parent, create_statement) + self.assertEqual(error, response.exception()) + + @mock.patch('google.gax.config.create_stub', spec=True) + def test_get_database(self, mock_create_stub): + # Mock gRPC layer + grpc_stub = mock.Mock() + mock_create_stub.return_value = grpc_stub + + client = spanner_admin_database_v1.DatabaseAdminClient() + + # Mock request + name = client.database_path('[PROJECT]', '[INSTANCE]', '[DATABASE]') + + # Mock response + name_2 = 'name2-1052831874' + expected_response = {'name': name_2} + expected_response = spanner_database_admin_pb2.Database( + **expected_response) + grpc_stub.GetDatabase.return_value = expected_response + + response = client.get_database(name) + self.assertEqual(expected_response, response) + + grpc_stub.GetDatabase.assert_called_once() + args, kwargs = grpc_stub.GetDatabase.call_args + self.assertEqual(len(args), 2) + self.assertEqual(len(kwargs), 1) + self.assertIn('metadata', kwargs) + actual_request = args[0] + + expected_request = spanner_database_admin_pb2.GetDatabaseRequest( + name=name) + self.assertEqual(expected_request, actual_request) + + @mock.patch('google.gax.config.API_ERRORS', (CustomException, )) + @mock.patch('google.gax.config.create_stub', spec=True) + def test_get_database_exception(self, mock_create_stub): + # Mock gRPC layer + grpc_stub = mock.Mock() + mock_create_stub.return_value = grpc_stub + + client = spanner_admin_database_v1.DatabaseAdminClient() + + # Mock request + name = client.database_path('[PROJECT]', '[INSTANCE]', '[DATABASE]') + + # Mock exception response + grpc_stub.GetDatabase.side_effect = CustomException() + + self.assertRaises(errors.GaxError, client.get_database, name) + + @mock.patch('google.gax.config.create_stub', spec=True) + def test_update_database_ddl(self, mock_create_stub): + # Mock gRPC layer + grpc_stub = mock.Mock() + mock_create_stub.return_value = grpc_stub + + client = spanner_admin_database_v1.DatabaseAdminClient() + + # Mock request + database = client.database_path('[PROJECT]', '[INSTANCE]', + '[DATABASE]') + statements = [] + + # Mock response + expected_response = {} + expected_response = empty_pb2.Empty(**expected_response) + operation = operations_pb2.Operation( + name='operations/test_update_database_ddl', done=True) + operation.response.Pack(expected_response) + grpc_stub.UpdateDatabaseDdl.return_value = operation + + response = client.update_database_ddl(database, statements) + self.assertEqual(expected_response, response.result()) + + grpc_stub.UpdateDatabaseDdl.assert_called_once() + args, kwargs = grpc_stub.UpdateDatabaseDdl.call_args + self.assertEqual(len(args), 2) + self.assertEqual(len(kwargs), 1) + self.assertIn('metadata', kwargs) + actual_request = args[0] + + expected_request = spanner_database_admin_pb2.UpdateDatabaseDdlRequest( + database=database, statements=statements) + self.assertEqual(expected_request, actual_request) + + @mock.patch('google.gax.config.create_stub', spec=True) + def test_update_database_ddl_exception(self, mock_create_stub): + # Mock gRPC layer + grpc_stub = mock.Mock() + mock_create_stub.return_value = grpc_stub + + client = spanner_admin_database_v1.DatabaseAdminClient() + + # Mock request + database = client.database_path('[PROJECT]', '[INSTANCE]', + '[DATABASE]') + statements = [] + + # Mock exception response + error = status_pb2.Status() + operation = operations_pb2.Operation( + name='operations/test_update_database_ddl_exception', done=True) + operation.error.CopyFrom(error) + grpc_stub.UpdateDatabaseDdl.return_value = operation + + response = client.update_database_ddl(database, statements) + self.assertEqual(error, response.exception()) + + @mock.patch('google.gax.config.create_stub', spec=True) + def test_drop_database(self, mock_create_stub): + # Mock gRPC layer + grpc_stub = mock.Mock() + mock_create_stub.return_value = grpc_stub + + client = spanner_admin_database_v1.DatabaseAdminClient() + + # Mock request + database = client.database_path('[PROJECT]', '[INSTANCE]', + '[DATABASE]') + + client.drop_database(database) + + grpc_stub.DropDatabase.assert_called_once() + args, kwargs = grpc_stub.DropDatabase.call_args + self.assertEqual(len(args), 2) + self.assertEqual(len(kwargs), 1) + self.assertIn('metadata', kwargs) + actual_request = args[0] + + expected_request = spanner_database_admin_pb2.DropDatabaseRequest( + database=database) + self.assertEqual(expected_request, actual_request) + + @mock.patch('google.gax.config.API_ERRORS', (CustomException, )) + @mock.patch('google.gax.config.create_stub', spec=True) + def test_drop_database_exception(self, mock_create_stub): + # Mock gRPC layer + grpc_stub = mock.Mock() + mock_create_stub.return_value = grpc_stub + + client = spanner_admin_database_v1.DatabaseAdminClient() + + # Mock request + database = client.database_path('[PROJECT]', '[INSTANCE]', + '[DATABASE]') + + # Mock exception response + grpc_stub.DropDatabase.side_effect = CustomException() + + self.assertRaises(errors.GaxError, client.drop_database, database) + + @mock.patch('google.gax.config.create_stub', spec=True) + def test_get_database_ddl(self, mock_create_stub): + # Mock gRPC layer + grpc_stub = mock.Mock() + mock_create_stub.return_value = grpc_stub + + client = spanner_admin_database_v1.DatabaseAdminClient() + + # Mock request + database = client.database_path('[PROJECT]', '[INSTANCE]', + '[DATABASE]') + + # Mock response + expected_response = {} + expected_response = spanner_database_admin_pb2.GetDatabaseDdlResponse( + **expected_response) + grpc_stub.GetDatabaseDdl.return_value = expected_response + + response = client.get_database_ddl(database) + self.assertEqual(expected_response, response) + + grpc_stub.GetDatabaseDdl.assert_called_once() + args, kwargs = grpc_stub.GetDatabaseDdl.call_args + self.assertEqual(len(args), 2) + self.assertEqual(len(kwargs), 1) + self.assertIn('metadata', kwargs) + actual_request = args[0] + + expected_request = spanner_database_admin_pb2.GetDatabaseDdlRequest( + database=database) + self.assertEqual(expected_request, actual_request) + + @mock.patch('google.gax.config.API_ERRORS', (CustomException, )) + @mock.patch('google.gax.config.create_stub', spec=True) + def test_get_database_ddl_exception(self, mock_create_stub): + # Mock gRPC layer + grpc_stub = mock.Mock() + mock_create_stub.return_value = grpc_stub + + client = spanner_admin_database_v1.DatabaseAdminClient() + + # Mock request + database = client.database_path('[PROJECT]', '[INSTANCE]', + '[DATABASE]') + + # Mock exception response + grpc_stub.GetDatabaseDdl.side_effect = CustomException() + + self.assertRaises(errors.GaxError, client.get_database_ddl, database) + + @mock.patch('google.gax.config.create_stub', spec=True) + def test_set_iam_policy(self, mock_create_stub): + # Mock gRPC layer + grpc_stub = mock.Mock() + mock_create_stub.return_value = grpc_stub + + client = spanner_admin_database_v1.DatabaseAdminClient() + + # Mock request + resource = client.database_path('[PROJECT]', '[INSTANCE]', + '[DATABASE]') + policy = {} + + # Mock response + version = 351608024 + etag = b'21' + expected_response = {'version': version, 'etag': etag} + expected_response = policy_pb2.Policy(**expected_response) + grpc_stub.SetIamPolicy.return_value = expected_response + + response = client.set_iam_policy(resource, policy) + self.assertEqual(expected_response, response) + + grpc_stub.SetIamPolicy.assert_called_once() + args, kwargs = grpc_stub.SetIamPolicy.call_args + self.assertEqual(len(args), 2) + self.assertEqual(len(kwargs), 1) + self.assertIn('metadata', kwargs) + actual_request = args[0] + + expected_request = iam_policy_pb2.SetIamPolicyRequest( + resource=resource, policy=policy) + self.assertEqual(expected_request, actual_request) + + @mock.patch('google.gax.config.API_ERRORS', (CustomException, )) + @mock.patch('google.gax.config.create_stub', spec=True) + def test_set_iam_policy_exception(self, mock_create_stub): + # Mock gRPC layer + grpc_stub = mock.Mock() + mock_create_stub.return_value = grpc_stub + + client = spanner_admin_database_v1.DatabaseAdminClient() + + # Mock request + resource = client.database_path('[PROJECT]', '[INSTANCE]', + '[DATABASE]') + policy = {} + + # Mock exception response + grpc_stub.SetIamPolicy.side_effect = CustomException() + + self.assertRaises(errors.GaxError, client.set_iam_policy, resource, + policy) + + @mock.patch('google.gax.config.create_stub', spec=True) + def test_get_iam_policy(self, mock_create_stub): + # Mock gRPC layer + grpc_stub = mock.Mock() + mock_create_stub.return_value = grpc_stub + + client = spanner_admin_database_v1.DatabaseAdminClient() + + # Mock request + resource = client.database_path('[PROJECT]', '[INSTANCE]', + '[DATABASE]') + + # Mock response + version = 351608024 + etag = b'21' + expected_response = {'version': version, 'etag': etag} + expected_response = policy_pb2.Policy(**expected_response) + grpc_stub.GetIamPolicy.return_value = expected_response + + response = client.get_iam_policy(resource) + self.assertEqual(expected_response, response) + + grpc_stub.GetIamPolicy.assert_called_once() + args, kwargs = grpc_stub.GetIamPolicy.call_args + self.assertEqual(len(args), 2) + self.assertEqual(len(kwargs), 1) + self.assertIn('metadata', kwargs) + actual_request = args[0] + + expected_request = iam_policy_pb2.GetIamPolicyRequest( + resource=resource) + self.assertEqual(expected_request, actual_request) + + @mock.patch('google.gax.config.API_ERRORS', (CustomException, )) + @mock.patch('google.gax.config.create_stub', spec=True) + def test_get_iam_policy_exception(self, mock_create_stub): + # Mock gRPC layer + grpc_stub = mock.Mock() + mock_create_stub.return_value = grpc_stub + + client = spanner_admin_database_v1.DatabaseAdminClient() + + # Mock request + resource = client.database_path('[PROJECT]', '[INSTANCE]', + '[DATABASE]') + + # Mock exception response + grpc_stub.GetIamPolicy.side_effect = CustomException() + + self.assertRaises(errors.GaxError, client.get_iam_policy, resource) + + @mock.patch('google.gax.config.create_stub', spec=True) + def test_test_iam_permissions(self, mock_create_stub): + # Mock gRPC layer + grpc_stub = mock.Mock() + mock_create_stub.return_value = grpc_stub + + client = spanner_admin_database_v1.DatabaseAdminClient() + + # Mock request + resource = client.database_path('[PROJECT]', '[INSTANCE]', + '[DATABASE]') + permissions = [] + + # Mock response + expected_response = {} + expected_response = iam_policy_pb2.TestIamPermissionsResponse( + **expected_response) + grpc_stub.TestIamPermissions.return_value = expected_response + + response = client.test_iam_permissions(resource, permissions) + self.assertEqual(expected_response, response) + + grpc_stub.TestIamPermissions.assert_called_once() + args, kwargs = grpc_stub.TestIamPermissions.call_args + self.assertEqual(len(args), 2) + self.assertEqual(len(kwargs), 1) + self.assertIn('metadata', kwargs) + actual_request = args[0] + + expected_request = iam_policy_pb2.TestIamPermissionsRequest( + resource=resource, permissions=permissions) + self.assertEqual(expected_request, actual_request) + + @mock.patch('google.gax.config.API_ERRORS', (CustomException, )) + @mock.patch('google.gax.config.create_stub', spec=True) + def test_test_iam_permissions_exception(self, mock_create_stub): + # Mock gRPC layer + grpc_stub = mock.Mock() + mock_create_stub.return_value = grpc_stub + + client = spanner_admin_database_v1.DatabaseAdminClient() + + # Mock request + resource = client.database_path('[PROJECT]', '[INSTANCE]', + '[DATABASE]') + permissions = [] + + # Mock exception response + grpc_stub.TestIamPermissions.side_effect = CustomException() + + self.assertRaises(errors.GaxError, client.test_iam_permissions, + resource, permissions) diff --git a/spanner/tests/unit/gapic/v1/test_instance_admin_client_v1.py b/spanner/tests/unit/gapic/v1/test_instance_admin_client_v1.py new file mode 100644 index 000000000000..03dadf9e9786 --- /dev/null +++ b/spanner/tests/unit/gapic/v1/test_instance_admin_client_v1.py @@ -0,0 +1,582 @@ +# Copyright 2017, Google Inc. All rights reserved. +# +# 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 +# +# http://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. +"""Unit tests.""" + +import mock +import unittest + +from google.gax import errors +from google.rpc import status_pb2 + +from google.cloud import spanner_admin_instance_v1 +from google.cloud.spanner_admin_instance_v1.proto import spanner_instance_admin_pb2 +from google.iam.v1 import iam_policy_pb2 +from google.iam.v1 import policy_pb2 +from google.longrunning import operations_pb2 +from google.protobuf import empty_pb2 +from google.protobuf import field_mask_pb2 + + +class CustomException(Exception): + pass + + +class TestInstanceAdminClient(unittest.TestCase): + @mock.patch('google.gax.config.create_stub', spec=True) + def test_list_instance_configs(self, mock_create_stub): + # Mock gRPC layer + grpc_stub = mock.Mock() + mock_create_stub.return_value = grpc_stub + + client = spanner_admin_instance_v1.InstanceAdminClient() + + # Mock request + parent = client.project_path('[PROJECT]') + + # Mock response + next_page_token = '' + instance_configs_element = {} + instance_configs = [instance_configs_element] + expected_response = { + 'next_page_token': next_page_token, + 'instance_configs': instance_configs + } + expected_response = spanner_instance_admin_pb2.ListInstanceConfigsResponse( + **expected_response) + grpc_stub.ListInstanceConfigs.return_value = expected_response + + paged_list_response = client.list_instance_configs(parent) + resources = list(paged_list_response) + self.assertEqual(1, len(resources)) + self.assertEqual(expected_response.instance_configs[0], resources[0]) + + grpc_stub.ListInstanceConfigs.assert_called_once() + args, kwargs = grpc_stub.ListInstanceConfigs.call_args + self.assertEqual(len(args), 2) + self.assertEqual(len(kwargs), 1) + self.assertIn('metadata', kwargs) + actual_request = args[0] + + expected_request = spanner_instance_admin_pb2.ListInstanceConfigsRequest( + parent=parent) + self.assertEqual(expected_request, actual_request) + + @mock.patch('google.gax.config.API_ERRORS', (CustomException, )) + @mock.patch('google.gax.config.create_stub', spec=True) + def test_list_instance_configs_exception(self, mock_create_stub): + # Mock gRPC layer + grpc_stub = mock.Mock() + mock_create_stub.return_value = grpc_stub + + client = spanner_admin_instance_v1.InstanceAdminClient() + + # Mock request + parent = client.project_path('[PROJECT]') + + # Mock exception response + grpc_stub.ListInstanceConfigs.side_effect = CustomException() + + paged_list_response = client.list_instance_configs(parent) + self.assertRaises(errors.GaxError, list, paged_list_response) + + @mock.patch('google.gax.config.create_stub', spec=True) + def test_get_instance_config(self, mock_create_stub): + # Mock gRPC layer + grpc_stub = mock.Mock() + mock_create_stub.return_value = grpc_stub + + client = spanner_admin_instance_v1.InstanceAdminClient() + + # Mock request + name = client.instance_config_path('[PROJECT]', '[INSTANCE_CONFIG]') + + # Mock response + name_2 = 'name2-1052831874' + display_name = 'displayName1615086568' + expected_response = {'name': name_2, 'display_name': display_name} + expected_response = spanner_instance_admin_pb2.InstanceConfig( + **expected_response) + grpc_stub.GetInstanceConfig.return_value = expected_response + + response = client.get_instance_config(name) + self.assertEqual(expected_response, response) + + grpc_stub.GetInstanceConfig.assert_called_once() + args, kwargs = grpc_stub.GetInstanceConfig.call_args + self.assertEqual(len(args), 2) + self.assertEqual(len(kwargs), 1) + self.assertIn('metadata', kwargs) + actual_request = args[0] + + expected_request = spanner_instance_admin_pb2.GetInstanceConfigRequest( + name=name) + self.assertEqual(expected_request, actual_request) + + @mock.patch('google.gax.config.API_ERRORS', (CustomException, )) + @mock.patch('google.gax.config.create_stub', spec=True) + def test_get_instance_config_exception(self, mock_create_stub): + # Mock gRPC layer + grpc_stub = mock.Mock() + mock_create_stub.return_value = grpc_stub + + client = spanner_admin_instance_v1.InstanceAdminClient() + + # Mock request + name = client.instance_config_path('[PROJECT]', '[INSTANCE_CONFIG]') + + # Mock exception response + grpc_stub.GetInstanceConfig.side_effect = CustomException() + + self.assertRaises(errors.GaxError, client.get_instance_config, name) + + @mock.patch('google.gax.config.create_stub', spec=True) + def test_list_instances(self, mock_create_stub): + # Mock gRPC layer + grpc_stub = mock.Mock() + mock_create_stub.return_value = grpc_stub + + client = spanner_admin_instance_v1.InstanceAdminClient() + + # Mock request + parent = client.project_path('[PROJECT]') + + # Mock response + next_page_token = '' + instances_element = {} + instances = [instances_element] + expected_response = { + 'next_page_token': next_page_token, + 'instances': instances + } + expected_response = spanner_instance_admin_pb2.ListInstancesResponse( + **expected_response) + grpc_stub.ListInstances.return_value = expected_response + + paged_list_response = client.list_instances(parent) + resources = list(paged_list_response) + self.assertEqual(1, len(resources)) + self.assertEqual(expected_response.instances[0], resources[0]) + + grpc_stub.ListInstances.assert_called_once() + args, kwargs = grpc_stub.ListInstances.call_args + self.assertEqual(len(args), 2) + self.assertEqual(len(kwargs), 1) + self.assertIn('metadata', kwargs) + actual_request = args[0] + + expected_request = spanner_instance_admin_pb2.ListInstancesRequest( + parent=parent) + self.assertEqual(expected_request, actual_request) + + @mock.patch('google.gax.config.API_ERRORS', (CustomException, )) + @mock.patch('google.gax.config.create_stub', spec=True) + def test_list_instances_exception(self, mock_create_stub): + # Mock gRPC layer + grpc_stub = mock.Mock() + mock_create_stub.return_value = grpc_stub + + client = spanner_admin_instance_v1.InstanceAdminClient() + + # Mock request + parent = client.project_path('[PROJECT]') + + # Mock exception response + grpc_stub.ListInstances.side_effect = CustomException() + + paged_list_response = client.list_instances(parent) + self.assertRaises(errors.GaxError, list, paged_list_response) + + @mock.patch('google.gax.config.create_stub', spec=True) + def test_get_instance(self, mock_create_stub): + # Mock gRPC layer + grpc_stub = mock.Mock() + mock_create_stub.return_value = grpc_stub + + client = spanner_admin_instance_v1.InstanceAdminClient() + + # Mock request + name = client.instance_path('[PROJECT]', '[INSTANCE]') + + # Mock response + name_2 = 'name2-1052831874' + config = 'config-1354792126' + display_name = 'displayName1615086568' + node_count = 1539922066 + expected_response = { + 'name': name_2, + 'config': config, + 'display_name': display_name, + 'node_count': node_count + } + expected_response = spanner_instance_admin_pb2.Instance( + **expected_response) + grpc_stub.GetInstance.return_value = expected_response + + response = client.get_instance(name) + self.assertEqual(expected_response, response) + + grpc_stub.GetInstance.assert_called_once() + args, kwargs = grpc_stub.GetInstance.call_args + self.assertEqual(len(args), 2) + self.assertEqual(len(kwargs), 1) + self.assertIn('metadata', kwargs) + actual_request = args[0] + + expected_request = spanner_instance_admin_pb2.GetInstanceRequest( + name=name) + self.assertEqual(expected_request, actual_request) + + @mock.patch('google.gax.config.API_ERRORS', (CustomException, )) + @mock.patch('google.gax.config.create_stub', spec=True) + def test_get_instance_exception(self, mock_create_stub): + # Mock gRPC layer + grpc_stub = mock.Mock() + mock_create_stub.return_value = grpc_stub + + client = spanner_admin_instance_v1.InstanceAdminClient() + + # Mock request + name = client.instance_path('[PROJECT]', '[INSTANCE]') + + # Mock exception response + grpc_stub.GetInstance.side_effect = CustomException() + + self.assertRaises(errors.GaxError, client.get_instance, name) + + @mock.patch('google.gax.config.create_stub', spec=True) + def test_create_instance(self, mock_create_stub): + # Mock gRPC layer + grpc_stub = mock.Mock() + mock_create_stub.return_value = grpc_stub + + client = spanner_admin_instance_v1.InstanceAdminClient() + + # Mock request + parent = client.project_path('[PROJECT]') + instance_id = 'instanceId-2101995259' + instance = {} + + # Mock response + name = 'name3373707' + config = 'config-1354792126' + display_name = 'displayName1615086568' + node_count = 1539922066 + expected_response = { + 'name': name, + 'config': config, + 'display_name': display_name, + 'node_count': node_count + } + expected_response = spanner_instance_admin_pb2.Instance( + **expected_response) + operation = operations_pb2.Operation( + name='operations/test_create_instance', done=True) + operation.response.Pack(expected_response) + grpc_stub.CreateInstance.return_value = operation + + response = client.create_instance(parent, instance_id, instance) + self.assertEqual(expected_response, response.result()) + + grpc_stub.CreateInstance.assert_called_once() + args, kwargs = grpc_stub.CreateInstance.call_args + self.assertEqual(len(args), 2) + self.assertEqual(len(kwargs), 1) + self.assertIn('metadata', kwargs) + actual_request = args[0] + + expected_request = spanner_instance_admin_pb2.CreateInstanceRequest( + parent=parent, instance_id=instance_id, instance=instance) + self.assertEqual(expected_request, actual_request) + + @mock.patch('google.gax.config.create_stub', spec=True) + def test_create_instance_exception(self, mock_create_stub): + # Mock gRPC layer + grpc_stub = mock.Mock() + mock_create_stub.return_value = grpc_stub + + client = spanner_admin_instance_v1.InstanceAdminClient() + + # Mock request + parent = client.project_path('[PROJECT]') + instance_id = 'instanceId-2101995259' + instance = {} + + # Mock exception response + error = status_pb2.Status() + operation = operations_pb2.Operation( + name='operations/test_create_instance_exception', done=True) + operation.error.CopyFrom(error) + grpc_stub.CreateInstance.return_value = operation + + response = client.create_instance(parent, instance_id, instance) + self.assertEqual(error, response.exception()) + + @mock.patch('google.gax.config.create_stub', spec=True) + def test_update_instance(self, mock_create_stub): + # Mock gRPC layer + grpc_stub = mock.Mock() + mock_create_stub.return_value = grpc_stub + + client = spanner_admin_instance_v1.InstanceAdminClient() + + # Mock request + instance = {} + field_mask = {} + + # Mock response + name = 'name3373707' + config = 'config-1354792126' + display_name = 'displayName1615086568' + node_count = 1539922066 + expected_response = { + 'name': name, + 'config': config, + 'display_name': display_name, + 'node_count': node_count + } + expected_response = spanner_instance_admin_pb2.Instance( + **expected_response) + operation = operations_pb2.Operation( + name='operations/test_update_instance', done=True) + operation.response.Pack(expected_response) + grpc_stub.UpdateInstance.return_value = operation + + response = client.update_instance(instance, field_mask) + self.assertEqual(expected_response, response.result()) + + grpc_stub.UpdateInstance.assert_called_once() + args, kwargs = grpc_stub.UpdateInstance.call_args + self.assertEqual(len(args), 2) + self.assertEqual(len(kwargs), 1) + self.assertIn('metadata', kwargs) + actual_request = args[0] + + expected_request = spanner_instance_admin_pb2.UpdateInstanceRequest( + instance=instance, field_mask=field_mask) + self.assertEqual(expected_request, actual_request) + + @mock.patch('google.gax.config.create_stub', spec=True) + def test_update_instance_exception(self, mock_create_stub): + # Mock gRPC layer + grpc_stub = mock.Mock() + mock_create_stub.return_value = grpc_stub + + client = spanner_admin_instance_v1.InstanceAdminClient() + + # Mock request + instance = {} + field_mask = {} + + # Mock exception response + error = status_pb2.Status() + operation = operations_pb2.Operation( + name='operations/test_update_instance_exception', done=True) + operation.error.CopyFrom(error) + grpc_stub.UpdateInstance.return_value = operation + + response = client.update_instance(instance, field_mask) + self.assertEqual(error, response.exception()) + + @mock.patch('google.gax.config.create_stub', spec=True) + def test_delete_instance(self, mock_create_stub): + # Mock gRPC layer + grpc_stub = mock.Mock() + mock_create_stub.return_value = grpc_stub + + client = spanner_admin_instance_v1.InstanceAdminClient() + + # Mock request + name = client.instance_path('[PROJECT]', '[INSTANCE]') + + client.delete_instance(name) + + grpc_stub.DeleteInstance.assert_called_once() + args, kwargs = grpc_stub.DeleteInstance.call_args + self.assertEqual(len(args), 2) + self.assertEqual(len(kwargs), 1) + self.assertIn('metadata', kwargs) + actual_request = args[0] + + expected_request = spanner_instance_admin_pb2.DeleteInstanceRequest( + name=name) + self.assertEqual(expected_request, actual_request) + + @mock.patch('google.gax.config.API_ERRORS', (CustomException, )) + @mock.patch('google.gax.config.create_stub', spec=True) + def test_delete_instance_exception(self, mock_create_stub): + # Mock gRPC layer + grpc_stub = mock.Mock() + mock_create_stub.return_value = grpc_stub + + client = spanner_admin_instance_v1.InstanceAdminClient() + + # Mock request + name = client.instance_path('[PROJECT]', '[INSTANCE]') + + # Mock exception response + grpc_stub.DeleteInstance.side_effect = CustomException() + + self.assertRaises(errors.GaxError, client.delete_instance, name) + + @mock.patch('google.gax.config.create_stub', spec=True) + def test_set_iam_policy(self, mock_create_stub): + # Mock gRPC layer + grpc_stub = mock.Mock() + mock_create_stub.return_value = grpc_stub + + client = spanner_admin_instance_v1.InstanceAdminClient() + + # Mock request + resource = client.instance_path('[PROJECT]', '[INSTANCE]') + policy = {} + + # Mock response + version = 351608024 + etag = b'21' + expected_response = {'version': version, 'etag': etag} + expected_response = policy_pb2.Policy(**expected_response) + grpc_stub.SetIamPolicy.return_value = expected_response + + response = client.set_iam_policy(resource, policy) + self.assertEqual(expected_response, response) + + grpc_stub.SetIamPolicy.assert_called_once() + args, kwargs = grpc_stub.SetIamPolicy.call_args + self.assertEqual(len(args), 2) + self.assertEqual(len(kwargs), 1) + self.assertIn('metadata', kwargs) + actual_request = args[0] + + expected_request = iam_policy_pb2.SetIamPolicyRequest( + resource=resource, policy=policy) + self.assertEqual(expected_request, actual_request) + + @mock.patch('google.gax.config.API_ERRORS', (CustomException, )) + @mock.patch('google.gax.config.create_stub', spec=True) + def test_set_iam_policy_exception(self, mock_create_stub): + # Mock gRPC layer + grpc_stub = mock.Mock() + mock_create_stub.return_value = grpc_stub + + client = spanner_admin_instance_v1.InstanceAdminClient() + + # Mock request + resource = client.instance_path('[PROJECT]', '[INSTANCE]') + policy = {} + + # Mock exception response + grpc_stub.SetIamPolicy.side_effect = CustomException() + + self.assertRaises(errors.GaxError, client.set_iam_policy, resource, + policy) + + @mock.patch('google.gax.config.create_stub', spec=True) + def test_get_iam_policy(self, mock_create_stub): + # Mock gRPC layer + grpc_stub = mock.Mock() + mock_create_stub.return_value = grpc_stub + + client = spanner_admin_instance_v1.InstanceAdminClient() + + # Mock request + resource = client.instance_path('[PROJECT]', '[INSTANCE]') + + # Mock response + version = 351608024 + etag = b'21' + expected_response = {'version': version, 'etag': etag} + expected_response = policy_pb2.Policy(**expected_response) + grpc_stub.GetIamPolicy.return_value = expected_response + + response = client.get_iam_policy(resource) + self.assertEqual(expected_response, response) + + grpc_stub.GetIamPolicy.assert_called_once() + args, kwargs = grpc_stub.GetIamPolicy.call_args + self.assertEqual(len(args), 2) + self.assertEqual(len(kwargs), 1) + self.assertIn('metadata', kwargs) + actual_request = args[0] + + expected_request = iam_policy_pb2.GetIamPolicyRequest( + resource=resource) + self.assertEqual(expected_request, actual_request) + + @mock.patch('google.gax.config.API_ERRORS', (CustomException, )) + @mock.patch('google.gax.config.create_stub', spec=True) + def test_get_iam_policy_exception(self, mock_create_stub): + # Mock gRPC layer + grpc_stub = mock.Mock() + mock_create_stub.return_value = grpc_stub + + client = spanner_admin_instance_v1.InstanceAdminClient() + + # Mock request + resource = client.instance_path('[PROJECT]', '[INSTANCE]') + + # Mock exception response + grpc_stub.GetIamPolicy.side_effect = CustomException() + + self.assertRaises(errors.GaxError, client.get_iam_policy, resource) + + @mock.patch('google.gax.config.create_stub', spec=True) + def test_test_iam_permissions(self, mock_create_stub): + # Mock gRPC layer + grpc_stub = mock.Mock() + mock_create_stub.return_value = grpc_stub + + client = spanner_admin_instance_v1.InstanceAdminClient() + + # Mock request + resource = client.instance_path('[PROJECT]', '[INSTANCE]') + permissions = [] + + # Mock response + expected_response = {} + expected_response = iam_policy_pb2.TestIamPermissionsResponse( + **expected_response) + grpc_stub.TestIamPermissions.return_value = expected_response + + response = client.test_iam_permissions(resource, permissions) + self.assertEqual(expected_response, response) + + grpc_stub.TestIamPermissions.assert_called_once() + args, kwargs = grpc_stub.TestIamPermissions.call_args + self.assertEqual(len(args), 2) + self.assertEqual(len(kwargs), 1) + self.assertIn('metadata', kwargs) + actual_request = args[0] + + expected_request = iam_policy_pb2.TestIamPermissionsRequest( + resource=resource, permissions=permissions) + self.assertEqual(expected_request, actual_request) + + @mock.patch('google.gax.config.API_ERRORS', (CustomException, )) + @mock.patch('google.gax.config.create_stub', spec=True) + def test_test_iam_permissions_exception(self, mock_create_stub): + # Mock gRPC layer + grpc_stub = mock.Mock() + mock_create_stub.return_value = grpc_stub + + client = spanner_admin_instance_v1.InstanceAdminClient() + + # Mock request + resource = client.instance_path('[PROJECT]', '[INSTANCE]') + permissions = [] + + # Mock exception response + grpc_stub.TestIamPermissions.side_effect = CustomException() + + self.assertRaises(errors.GaxError, client.test_iam_permissions, + resource, permissions) diff --git a/spanner/tests/unit/gapic/v1/test_spanner_client_v1.py b/spanner/tests/unit/gapic/v1/test_spanner_client_v1.py new file mode 100644 index 000000000000..5d012ce0fe55 --- /dev/null +++ b/spanner/tests/unit/gapic/v1/test_spanner_client_v1.py @@ -0,0 +1,559 @@ +# Copyright 2017, Google Inc. All rights reserved. +# +# 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 +# +# http://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. +"""Unit tests.""" + +import mock +import unittest + +from google.gax import errors + +# ----------------------------------------------------------------------------- +# Manual change to the GAPIC unit tests because we do not export +# the `SpannerClient` at the usual location because there is a thick wrapper +# around it. +from google.cloud.spanner_v1.gapic import spanner_client as spanner_v1 +# ----------------------------------------------------------------------------- + +from google.cloud.spanner_v1.proto import keys_pb2 +from google.cloud.spanner_v1.proto import result_set_pb2 +from google.cloud.spanner_v1.proto import spanner_pb2 +from google.cloud.spanner_v1.proto import transaction_pb2 +from google.protobuf import empty_pb2 + + +class CustomException(Exception): + pass + + +class TestSpannerClient(unittest.TestCase): + @mock.patch('google.gax.config.create_stub', spec=True) + def test_create_session(self, mock_create_stub): + # Mock gRPC layer + grpc_stub = mock.Mock() + mock_create_stub.return_value = grpc_stub + + client = spanner_v1.SpannerClient() + + # Mock request + database = client.database_path('[PROJECT]', '[INSTANCE]', + '[DATABASE]') + + # Mock response + name = 'name3373707' + expected_response = {'name': name} + expected_response = spanner_pb2.Session(**expected_response) + grpc_stub.CreateSession.return_value = expected_response + + response = client.create_session(database) + self.assertEqual(expected_response, response) + + grpc_stub.CreateSession.assert_called_once() + args, kwargs = grpc_stub.CreateSession.call_args + self.assertEqual(len(args), 2) + self.assertEqual(len(kwargs), 1) + self.assertIn('metadata', kwargs) + actual_request = args[0] + + expected_request = spanner_pb2.CreateSessionRequest(database=database) + self.assertEqual(expected_request, actual_request) + + @mock.patch('google.gax.config.API_ERRORS', (CustomException, )) + @mock.patch('google.gax.config.create_stub', spec=True) + def test_create_session_exception(self, mock_create_stub): + # Mock gRPC layer + grpc_stub = mock.Mock() + mock_create_stub.return_value = grpc_stub + + client = spanner_v1.SpannerClient() + + # Mock request + database = client.database_path('[PROJECT]', '[INSTANCE]', + '[DATABASE]') + + # Mock exception response + grpc_stub.CreateSession.side_effect = CustomException() + + self.assertRaises(errors.GaxError, client.create_session, database) + + @mock.patch('google.gax.config.create_stub', spec=True) + def test_get_session(self, mock_create_stub): + # Mock gRPC layer + grpc_stub = mock.Mock() + mock_create_stub.return_value = grpc_stub + + client = spanner_v1.SpannerClient() + + # Mock request + name = client.session_path('[PROJECT]', '[INSTANCE]', '[DATABASE]', + '[SESSION]') + + # Mock response + name_2 = 'name2-1052831874' + expected_response = {'name': name_2} + expected_response = spanner_pb2.Session(**expected_response) + grpc_stub.GetSession.return_value = expected_response + + response = client.get_session(name) + self.assertEqual(expected_response, response) + + grpc_stub.GetSession.assert_called_once() + args, kwargs = grpc_stub.GetSession.call_args + self.assertEqual(len(args), 2) + self.assertEqual(len(kwargs), 1) + self.assertIn('metadata', kwargs) + actual_request = args[0] + + expected_request = spanner_pb2.GetSessionRequest(name=name) + self.assertEqual(expected_request, actual_request) + + @mock.patch('google.gax.config.API_ERRORS', (CustomException, )) + @mock.patch('google.gax.config.create_stub', spec=True) + def test_get_session_exception(self, mock_create_stub): + # Mock gRPC layer + grpc_stub = mock.Mock() + mock_create_stub.return_value = grpc_stub + + client = spanner_v1.SpannerClient() + + # Mock request + name = client.session_path('[PROJECT]', '[INSTANCE]', '[DATABASE]', + '[SESSION]') + + # Mock exception response + grpc_stub.GetSession.side_effect = CustomException() + + self.assertRaises(errors.GaxError, client.get_session, name) + + @mock.patch('google.gax.config.create_stub', spec=True) + def test_delete_session(self, mock_create_stub): + # Mock gRPC layer + grpc_stub = mock.Mock() + mock_create_stub.return_value = grpc_stub + + client = spanner_v1.SpannerClient() + + # Mock request + name = client.session_path('[PROJECT]', '[INSTANCE]', '[DATABASE]', + '[SESSION]') + + client.delete_session(name) + + grpc_stub.DeleteSession.assert_called_once() + args, kwargs = grpc_stub.DeleteSession.call_args + self.assertEqual(len(args), 2) + self.assertEqual(len(kwargs), 1) + self.assertIn('metadata', kwargs) + actual_request = args[0] + + expected_request = spanner_pb2.DeleteSessionRequest(name=name) + self.assertEqual(expected_request, actual_request) + + @mock.patch('google.gax.config.API_ERRORS', (CustomException, )) + @mock.patch('google.gax.config.create_stub', spec=True) + def test_delete_session_exception(self, mock_create_stub): + # Mock gRPC layer + grpc_stub = mock.Mock() + mock_create_stub.return_value = grpc_stub + + client = spanner_v1.SpannerClient() + + # Mock request + name = client.session_path('[PROJECT]', '[INSTANCE]', '[DATABASE]', + '[SESSION]') + + # Mock exception response + grpc_stub.DeleteSession.side_effect = CustomException() + + self.assertRaises(errors.GaxError, client.delete_session, name) + + @mock.patch('google.gax.config.create_stub', spec=True) + def test_execute_sql(self, mock_create_stub): + # Mock gRPC layer + grpc_stub = mock.Mock() + mock_create_stub.return_value = grpc_stub + + client = spanner_v1.SpannerClient() + + # Mock request + session = client.session_path('[PROJECT]', '[INSTANCE]', '[DATABASE]', + '[SESSION]') + sql = 'sql114126' + + # Mock response + expected_response = {} + expected_response = result_set_pb2.ResultSet(**expected_response) + grpc_stub.ExecuteSql.return_value = expected_response + + response = client.execute_sql(session, sql) + self.assertEqual(expected_response, response) + + grpc_stub.ExecuteSql.assert_called_once() + args, kwargs = grpc_stub.ExecuteSql.call_args + self.assertEqual(len(args), 2) + self.assertEqual(len(kwargs), 1) + self.assertIn('metadata', kwargs) + actual_request = args[0] + + expected_request = spanner_pb2.ExecuteSqlRequest( + session=session, sql=sql) + self.assertEqual(expected_request, actual_request) + + @mock.patch('google.gax.config.API_ERRORS', (CustomException, )) + @mock.patch('google.gax.config.create_stub', spec=True) + def test_execute_sql_exception(self, mock_create_stub): + # Mock gRPC layer + grpc_stub = mock.Mock() + mock_create_stub.return_value = grpc_stub + + client = spanner_v1.SpannerClient() + + # Mock request + session = client.session_path('[PROJECT]', '[INSTANCE]', '[DATABASE]', + '[SESSION]') + sql = 'sql114126' + + # Mock exception response + grpc_stub.ExecuteSql.side_effect = CustomException() + + self.assertRaises(errors.GaxError, client.execute_sql, session, sql) + + @mock.patch('google.gax.config.create_stub', spec=True) + def test_execute_streaming_sql(self, mock_create_stub): + # Mock gRPC layer + grpc_stub = mock.Mock() + mock_create_stub.return_value = grpc_stub + + client = spanner_v1.SpannerClient() + + # Mock request + session = client.session_path('[PROJECT]', '[INSTANCE]', '[DATABASE]', + '[SESSION]') + sql = 'sql114126' + + # Mock response + chunked_value = True + resume_token = b'103' + expected_response = { + 'chunked_value': chunked_value, + 'resume_token': resume_token + } + expected_response = result_set_pb2.PartialResultSet( + **expected_response) + grpc_stub.ExecuteStreamingSql.return_value = iter([expected_response]) + + response = client.execute_streaming_sql(session, sql) + resources = list(response) + self.assertEqual(1, len(resources)) + self.assertEqual(expected_response, resources[0]) + + grpc_stub.ExecuteStreamingSql.assert_called_once() + args, kwargs = grpc_stub.ExecuteStreamingSql.call_args + self.assertEqual(len(args), 2) + self.assertEqual(len(kwargs), 1) + self.assertIn('metadata', kwargs) + actual_request = args[0] + + expected_request = spanner_pb2.ExecuteSqlRequest( + session=session, sql=sql) + self.assertEqual(expected_request, actual_request) + + @mock.patch('google.gax.config.API_ERRORS', (CustomException, )) + @mock.patch('google.gax.config.create_stub', spec=True) + def test_execute_streaming_sql_exception(self, mock_create_stub): + # Mock gRPC layer + grpc_stub = mock.Mock() + mock_create_stub.return_value = grpc_stub + + client = spanner_v1.SpannerClient() + + # Mock request + session = client.session_path('[PROJECT]', '[INSTANCE]', '[DATABASE]', + '[SESSION]') + sql = 'sql114126' + + # Mock exception response + grpc_stub.ExecuteStreamingSql.side_effect = CustomException() + + self.assertRaises(errors.GaxError, client.execute_streaming_sql, + session, sql) + + @mock.patch('google.gax.config.create_stub', spec=True) + def test_read(self, mock_create_stub): + # Mock gRPC layer + grpc_stub = mock.Mock() + mock_create_stub.return_value = grpc_stub + + client = spanner_v1.SpannerClient() + + # Mock request + session = client.session_path('[PROJECT]', '[INSTANCE]', '[DATABASE]', + '[SESSION]') + table = 'table110115790' + columns = [] + key_set = {} + + # Mock response + expected_response = {} + expected_response = result_set_pb2.ResultSet(**expected_response) + grpc_stub.Read.return_value = expected_response + + response = client.read(session, table, columns, key_set) + self.assertEqual(expected_response, response) + + grpc_stub.Read.assert_called_once() + args, kwargs = grpc_stub.Read.call_args + self.assertEqual(len(args), 2) + self.assertEqual(len(kwargs), 1) + self.assertIn('metadata', kwargs) + actual_request = args[0] + + expected_request = spanner_pb2.ReadRequest( + session=session, table=table, columns=columns, key_set=key_set) + self.assertEqual(expected_request, actual_request) + + @mock.patch('google.gax.config.API_ERRORS', (CustomException, )) + @mock.patch('google.gax.config.create_stub', spec=True) + def test_read_exception(self, mock_create_stub): + # Mock gRPC layer + grpc_stub = mock.Mock() + mock_create_stub.return_value = grpc_stub + + client = spanner_v1.SpannerClient() + + # Mock request + session = client.session_path('[PROJECT]', '[INSTANCE]', '[DATABASE]', + '[SESSION]') + table = 'table110115790' + columns = [] + key_set = {} + + # Mock exception response + grpc_stub.Read.side_effect = CustomException() + + self.assertRaises(errors.GaxError, client.read, session, table, + columns, key_set) + + @mock.patch('google.gax.config.create_stub', spec=True) + def test_streaming_read(self, mock_create_stub): + # Mock gRPC layer + grpc_stub = mock.Mock() + mock_create_stub.return_value = grpc_stub + + client = spanner_v1.SpannerClient() + + # Mock request + session = client.session_path('[PROJECT]', '[INSTANCE]', '[DATABASE]', + '[SESSION]') + table = 'table110115790' + columns = [] + key_set = {} + + # Mock response + chunked_value = True + resume_token = b'103' + expected_response = { + 'chunked_value': chunked_value, + 'resume_token': resume_token + } + expected_response = result_set_pb2.PartialResultSet( + **expected_response) + grpc_stub.StreamingRead.return_value = iter([expected_response]) + + response = client.streaming_read(session, table, columns, key_set) + resources = list(response) + self.assertEqual(1, len(resources)) + self.assertEqual(expected_response, resources[0]) + + grpc_stub.StreamingRead.assert_called_once() + args, kwargs = grpc_stub.StreamingRead.call_args + self.assertEqual(len(args), 2) + self.assertEqual(len(kwargs), 1) + self.assertIn('metadata', kwargs) + actual_request = args[0] + + expected_request = spanner_pb2.ReadRequest( + session=session, table=table, columns=columns, key_set=key_set) + self.assertEqual(expected_request, actual_request) + + @mock.patch('google.gax.config.API_ERRORS', (CustomException, )) + @mock.patch('google.gax.config.create_stub', spec=True) + def test_streaming_read_exception(self, mock_create_stub): + # Mock gRPC layer + grpc_stub = mock.Mock() + mock_create_stub.return_value = grpc_stub + + client = spanner_v1.SpannerClient() + + # Mock request + session = client.session_path('[PROJECT]', '[INSTANCE]', '[DATABASE]', + '[SESSION]') + table = 'table110115790' + columns = [] + key_set = {} + + # Mock exception response + grpc_stub.StreamingRead.side_effect = CustomException() + + self.assertRaises(errors.GaxError, client.streaming_read, session, + table, columns, key_set) + + @mock.patch('google.gax.config.create_stub', spec=True) + def test_begin_transaction(self, mock_create_stub): + # Mock gRPC layer + grpc_stub = mock.Mock() + mock_create_stub.return_value = grpc_stub + + client = spanner_v1.SpannerClient() + + # Mock request + session = client.session_path('[PROJECT]', '[INSTANCE]', '[DATABASE]', + '[SESSION]') + options_ = {} + + # Mock response + id_ = b'27' + expected_response = {'id': id_} + expected_response = transaction_pb2.Transaction(**expected_response) + grpc_stub.BeginTransaction.return_value = expected_response + + response = client.begin_transaction(session, options_) + self.assertEqual(expected_response, response) + + grpc_stub.BeginTransaction.assert_called_once() + args, kwargs = grpc_stub.BeginTransaction.call_args + self.assertEqual(len(args), 2) + self.assertEqual(len(kwargs), 1) + self.assertIn('metadata', kwargs) + actual_request = args[0] + + expected_request = spanner_pb2.BeginTransactionRequest( + session=session, options=options_) + self.assertEqual(expected_request, actual_request) + + @mock.patch('google.gax.config.API_ERRORS', (CustomException, )) + @mock.patch('google.gax.config.create_stub', spec=True) + def test_begin_transaction_exception(self, mock_create_stub): + # Mock gRPC layer + grpc_stub = mock.Mock() + mock_create_stub.return_value = grpc_stub + + client = spanner_v1.SpannerClient() + + # Mock request + session = client.session_path('[PROJECT]', '[INSTANCE]', '[DATABASE]', + '[SESSION]') + options_ = {} + + # Mock exception response + grpc_stub.BeginTransaction.side_effect = CustomException() + + self.assertRaises(errors.GaxError, client.begin_transaction, session, + options_) + + @mock.patch('google.gax.config.create_stub', spec=True) + def test_commit(self, mock_create_stub): + # Mock gRPC layer + grpc_stub = mock.Mock() + mock_create_stub.return_value = grpc_stub + + client = spanner_v1.SpannerClient() + + # Mock request + session = client.session_path('[PROJECT]', '[INSTANCE]', '[DATABASE]', + '[SESSION]') + mutations = [] + + # Mock response + expected_response = {} + expected_response = spanner_pb2.CommitResponse(**expected_response) + grpc_stub.Commit.return_value = expected_response + + response = client.commit(session, mutations) + self.assertEqual(expected_response, response) + + grpc_stub.Commit.assert_called_once() + args, kwargs = grpc_stub.Commit.call_args + self.assertEqual(len(args), 2) + self.assertEqual(len(kwargs), 1) + self.assertIn('metadata', kwargs) + actual_request = args[0] + + expected_request = spanner_pb2.CommitRequest( + session=session, mutations=mutations) + self.assertEqual(expected_request, actual_request) + + @mock.patch('google.gax.config.API_ERRORS', (CustomException, )) + @mock.patch('google.gax.config.create_stub', spec=True) + def test_commit_exception(self, mock_create_stub): + # Mock gRPC layer + grpc_stub = mock.Mock() + mock_create_stub.return_value = grpc_stub + + client = spanner_v1.SpannerClient() + + # Mock request + session = client.session_path('[PROJECT]', '[INSTANCE]', '[DATABASE]', + '[SESSION]') + mutations = [] + + # Mock exception response + grpc_stub.Commit.side_effect = CustomException() + + self.assertRaises(errors.GaxError, client.commit, session, mutations) + + @mock.patch('google.gax.config.create_stub', spec=True) + def test_rollback(self, mock_create_stub): + # Mock gRPC layer + grpc_stub = mock.Mock() + mock_create_stub.return_value = grpc_stub + + client = spanner_v1.SpannerClient() + + # Mock request + session = client.session_path('[PROJECT]', '[INSTANCE]', '[DATABASE]', + '[SESSION]') + transaction_id = b'28' + + client.rollback(session, transaction_id) + + grpc_stub.Rollback.assert_called_once() + args, kwargs = grpc_stub.Rollback.call_args + self.assertEqual(len(args), 2) + self.assertEqual(len(kwargs), 1) + self.assertIn('metadata', kwargs) + actual_request = args[0] + + expected_request = spanner_pb2.RollbackRequest( + session=session, transaction_id=transaction_id) + self.assertEqual(expected_request, actual_request) + + @mock.patch('google.gax.config.API_ERRORS', (CustomException, )) + @mock.patch('google.gax.config.create_stub', spec=True) + def test_rollback_exception(self, mock_create_stub): + # Mock gRPC layer + grpc_stub = mock.Mock() + mock_create_stub.return_value = grpc_stub + + client = spanner_v1.SpannerClient() + + # Mock request + session = client.session_path('[PROJECT]', '[INSTANCE]', '[DATABASE]', + '[SESSION]') + transaction_id = b'28' + + # Mock exception response + grpc_stub.Rollback.side_effect = CustomException() + + self.assertRaises(errors.GaxError, client.rollback, session, + transaction_id) diff --git a/spanner/tests/unit/test__helpers.py b/spanner/tests/unit/test__helpers.py index beb5ed7b6bac..421852163241 100644 --- a/spanner/tests/unit/test__helpers.py +++ b/spanner/tests/unit/test__helpers.py @@ -19,7 +19,7 @@ class TestTimestampWithNanoseconds(unittest.TestCase): def _get_target_class(self): - from google.cloud.spanner._helpers import TimestampWithNanoseconds + from google.cloud.spanner_v1._helpers import TimestampWithNanoseconds return TimestampWithNanoseconds @@ -114,7 +114,7 @@ def test_from_rfc3339_w_full_precision(self): class Test_make_value_pb(unittest.TestCase): def _callFUT(self, *args, **kw): - from google.cloud.spanner._helpers import _make_value_pb + from google.cloud.spanner_v1._helpers import _make_value_pb return _make_value_pb(*args, **kw) @@ -211,7 +211,7 @@ def test_w_date(self): def test_w_timestamp_w_nanos(self): from google.protobuf.struct_pb2 import Value from google.cloud._helpers import UTC - from google.cloud.spanner._helpers import TimestampWithNanoseconds + from google.cloud.spanner_v1._helpers import TimestampWithNanoseconds when = TimestampWithNanoseconds( 2016, 12, 20, 21, 13, 47, nanosecond=123456789, tzinfo=UTC) @@ -237,7 +237,7 @@ def test_w_unknown_type(self): class Test_make_list_value_pb(unittest.TestCase): def _callFUT(self, *args, **kw): - from google.cloud.spanner._helpers import _make_list_value_pb + from google.cloud.spanner_v1._helpers import _make_list_value_pb return _make_list_value_pb(*args, **kw) @@ -272,7 +272,7 @@ def test_w_multiple_values(self): class Test_make_list_value_pbs(unittest.TestCase): def _callFUT(self, *args, **kw): - from google.cloud.spanner._helpers import _make_list_value_pbs + from google.cloud.spanner_v1._helpers import _make_list_value_pbs return _make_list_value_pbs(*args, **kw) @@ -307,13 +307,13 @@ def test_w_multiple_values(self): class Test_parse_value_pb(unittest.TestCase): def _callFUT(self, *args, **kw): - from google.cloud.spanner._helpers import _parse_value_pb + from google.cloud.spanner_v1._helpers import _parse_value_pb return _parse_value_pb(*args, **kw) def test_w_null(self): from google.protobuf.struct_pb2 import Value, NULL_VALUE - from google.cloud.proto.spanner.v1.type_pb2 import Type, STRING + from google.cloud.spanner_v1.proto.type_pb2 import Type, STRING field_type = Type(code=STRING) value_pb = Value(null_value=NULL_VALUE) @@ -322,7 +322,7 @@ def test_w_null(self): def test_w_string(self): from google.protobuf.struct_pb2 import Value - from google.cloud.proto.spanner.v1.type_pb2 import Type, STRING + from google.cloud.spanner_v1.proto.type_pb2 import Type, STRING VALUE = u'Value' field_type = Type(code=STRING) @@ -332,7 +332,7 @@ def test_w_string(self): def test_w_bytes(self): from google.protobuf.struct_pb2 import Value - from google.cloud.proto.spanner.v1.type_pb2 import Type, BYTES + from google.cloud.spanner_v1.proto.type_pb2 import Type, BYTES VALUE = b'Value' field_type = Type(code=BYTES) @@ -342,7 +342,7 @@ def test_w_bytes(self): def test_w_bool(self): from google.protobuf.struct_pb2 import Value - from google.cloud.proto.spanner.v1.type_pb2 import Type, BOOL + from google.cloud.spanner_v1.proto.type_pb2 import Type, BOOL VALUE = True field_type = Type(code=BOOL) @@ -352,7 +352,7 @@ def test_w_bool(self): def test_w_int(self): from google.protobuf.struct_pb2 import Value - from google.cloud.proto.spanner.v1.type_pb2 import Type, INT64 + from google.cloud.spanner_v1.proto.type_pb2 import Type, INT64 VALUE = 12345 field_type = Type(code=INT64) @@ -362,7 +362,7 @@ def test_w_int(self): def test_w_float(self): from google.protobuf.struct_pb2 import Value - from google.cloud.proto.spanner.v1.type_pb2 import Type, FLOAT64 + from google.cloud.spanner_v1.proto.type_pb2 import Type, FLOAT64 VALUE = 3.14159 field_type = Type(code=FLOAT64) @@ -373,7 +373,7 @@ def test_w_float(self): def test_w_date(self): import datetime from google.protobuf.struct_pb2 import Value - from google.cloud.proto.spanner.v1.type_pb2 import Type, DATE + from google.cloud.spanner_v1.proto.type_pb2 import Type, DATE VALUE = datetime.date.today() field_type = Type(code=DATE) @@ -383,9 +383,9 @@ def test_w_date(self): def test_w_timestamp_wo_nanos(self): from google.protobuf.struct_pb2 import Value - from google.cloud.proto.spanner.v1.type_pb2 import Type, TIMESTAMP + from google.cloud.spanner_v1.proto.type_pb2 import Type, TIMESTAMP from google.cloud._helpers import UTC, _datetime_to_rfc3339 - from google.cloud.spanner._helpers import TimestampWithNanoseconds + from google.cloud.spanner_v1._helpers import TimestampWithNanoseconds VALUE = TimestampWithNanoseconds( 2016, 12, 20, 21, 13, 47, microsecond=123456, tzinfo=UTC) @@ -398,9 +398,9 @@ def test_w_timestamp_wo_nanos(self): def test_w_timestamp_w_nanos(self): from google.protobuf.struct_pb2 import Value - from google.cloud.proto.spanner.v1.type_pb2 import Type, TIMESTAMP + from google.cloud.spanner_v1.proto.type_pb2 import Type, TIMESTAMP from google.cloud._helpers import UTC, _datetime_to_rfc3339 - from google.cloud.spanner._helpers import TimestampWithNanoseconds + from google.cloud.spanner_v1._helpers import TimestampWithNanoseconds VALUE = TimestampWithNanoseconds( 2016, 12, 20, 21, 13, 47, nanosecond=123456789, tzinfo=UTC) @@ -413,7 +413,7 @@ def test_w_timestamp_w_nanos(self): def test_w_array_empty(self): from google.protobuf.struct_pb2 import Value - from google.cloud.proto.spanner.v1.type_pb2 import Type, ARRAY, INT64 + from google.cloud.spanner_v1.proto.type_pb2 import Type, ARRAY, INT64 field_type = Type(code=ARRAY, array_element_type=Type(code=INT64)) value_pb = Value() @@ -422,7 +422,7 @@ def test_w_array_empty(self): def test_w_array_non_empty(self): from google.protobuf.struct_pb2 import Value, ListValue - from google.cloud.proto.spanner.v1.type_pb2 import Type, ARRAY, INT64 + from google.cloud.spanner_v1.proto.type_pb2 import Type, ARRAY, INT64 field_type = Type(code=ARRAY, array_element_type=Type(code=INT64)) VALUES = [32, 19, 5] @@ -434,10 +434,10 @@ def test_w_array_non_empty(self): def test_w_struct(self): from google.protobuf.struct_pb2 import Value - from google.cloud.proto.spanner.v1.type_pb2 import Type, StructType - from google.cloud.proto.spanner.v1.type_pb2 import ( + from google.cloud.spanner_v1.proto.type_pb2 import Type, StructType + from google.cloud.spanner_v1.proto.type_pb2 import ( STRUCT, STRING, INT64) - from google.cloud.spanner._helpers import _make_list_value_pb + from google.cloud.spanner_v1._helpers import _make_list_value_pb VALUES = [u'phred', 32] struct_type_pb = StructType(fields=[ @@ -451,8 +451,8 @@ def test_w_struct(self): def test_w_unknown_type(self): from google.protobuf.struct_pb2 import Value - from google.cloud.proto.spanner.v1.type_pb2 import Type - from google.cloud.proto.spanner.v1.type_pb2 import ( + from google.cloud.spanner_v1.proto.type_pb2 import Type + from google.cloud.spanner_v1.proto.type_pb2 import ( TYPE_CODE_UNSPECIFIED) field_type = Type(code=TYPE_CODE_UNSPECIFIED) @@ -465,13 +465,13 @@ def test_w_unknown_type(self): class Test_parse_list_value_pbs(unittest.TestCase): def _callFUT(self, *args, **kw): - from google.cloud.spanner._helpers import _parse_list_value_pbs + from google.cloud.spanner_v1._helpers import _parse_list_value_pbs return _parse_list_value_pbs(*args, **kw) def test_empty(self): - from google.cloud.proto.spanner.v1.type_pb2 import Type, StructType - from google.cloud.proto.spanner.v1.type_pb2 import STRING, INT64 + from google.cloud.spanner_v1.proto.type_pb2 import Type, StructType + from google.cloud.spanner_v1.proto.type_pb2 import STRING, INT64 struct_type_pb = StructType(fields=[ StructType.Field(name='name', type=Type(code=STRING)), @@ -481,9 +481,9 @@ def test_empty(self): self.assertEqual(self._callFUT(rows=[], row_type=struct_type_pb), []) def test_non_empty(self): - from google.cloud.proto.spanner.v1.type_pb2 import Type, StructType - from google.cloud.proto.spanner.v1.type_pb2 import STRING, INT64 - from google.cloud.spanner._helpers import _make_list_value_pbs + from google.cloud.spanner_v1.proto.type_pb2 import Type, StructType + from google.cloud.spanner_v1.proto.type_pb2 import STRING, INT64 + from google.cloud.spanner_v1._helpers import _make_list_value_pbs VALUES = [ [u'phred', 32], @@ -502,7 +502,7 @@ def test_non_empty(self): class Test_SessionWrapper(unittest.TestCase): def _getTargetClass(self): - from google.cloud.spanner._helpers import _SessionWrapper + from google.cloud.spanner_v1._helpers import _SessionWrapper return _SessionWrapper @@ -518,7 +518,7 @@ def test_ctor(self): class Test_options_with_prefix(unittest.TestCase): def _call_fut(self, *args, **kw): - from google.cloud.spanner._helpers import _options_with_prefix + from google.cloud.spanner_v1._helpers import _options_with_prefix return _options_with_prefix(*args, **kw) diff --git a/spanner/tests/unit/test_batch.py b/spanner/tests/unit/test_batch.py index cf65fdd7e4f5..a6f2e7346e17 100644 --- a/spanner/tests/unit/test_batch.py +++ b/spanner/tests/unit/test_batch.py @@ -43,7 +43,7 @@ def _make_one(self, *args, **kwargs): class Test_BatchBase(_BaseTest): def _getTargetClass(self): - from google.cloud.spanner.batch import _BatchBase + from google.cloud.spanner_v1.batch import _BatchBase return _BatchBase @@ -75,7 +75,7 @@ def test__check_state_virtual(self): base._check_state() def test_insert(self): - from google.cloud.proto.spanner.v1.mutation_pb2 import Mutation + from google.cloud.spanner_v1.proto.mutation_pb2 import Mutation session = _Session() base = self._make_one(session) @@ -92,7 +92,7 @@ def test_insert(self): self._compare_values(write.values, VALUES) def test_update(self): - from google.cloud.proto.spanner.v1.mutation_pb2 import Mutation + from google.cloud.spanner_v1.proto.mutation_pb2 import Mutation session = _Session() base = self._make_one(session) @@ -109,7 +109,7 @@ def test_update(self): self._compare_values(write.values, VALUES) def test_insert_or_update(self): - from google.cloud.proto.spanner.v1.mutation_pb2 import Mutation + from google.cloud.spanner_v1.proto.mutation_pb2 import Mutation session = _Session() base = self._make_one(session) @@ -126,7 +126,7 @@ def test_insert_or_update(self): self._compare_values(write.values, VALUES) def test_replace(self): - from google.cloud.proto.spanner.v1.mutation_pb2 import Mutation + from google.cloud.spanner_v1.proto.mutation_pb2 import Mutation session = _Session() base = self._make_one(session) @@ -143,8 +143,8 @@ def test_replace(self): self._compare_values(write.values, VALUES) def test_delete(self): - from google.cloud.proto.spanner.v1.mutation_pb2 import Mutation - from google.cloud.spanner.keyset import KeySet + from google.cloud.spanner_v1.proto.mutation_pb2 import Mutation + from google.cloud.spanner_v1.keyset import KeySet keys = [[0], [1], [2]] keyset = KeySet(keys=keys) @@ -170,7 +170,7 @@ def test_delete(self): class TestBatch(_BaseTest): def _getTargetClass(self): - from google.cloud.spanner.batch import Batch + from google.cloud.spanner_v1.batch import Batch return Batch @@ -180,7 +180,7 @@ def test_ctor(self): self.assertIs(batch._session, session) def test_commit_already_committed(self): - from google.cloud.spanner.keyset import KeySet + from google.cloud.spanner_v1.keyset import KeySet keys = [[0], [1], [2]] keyset = KeySet(keys=keys) @@ -195,11 +195,11 @@ def test_commit_already_committed(self): def test_commit_grpc_error(self): from google.gax.errors import GaxError - from google.cloud.proto.spanner.v1.transaction_pb2 import ( + from google.cloud.spanner_v1.proto.transaction_pb2 import ( TransactionOptions) - from google.cloud.proto.spanner.v1.mutation_pb2 import ( + from google.cloud.spanner_v1.proto.mutation_pb2 import ( Mutation as MutationPB) - from google.cloud.spanner.keyset import KeySet + from google.cloud.spanner_v1.keyset import KeySet keys = [[0], [1], [2]] keyset = KeySet(keys=keys) @@ -234,8 +234,8 @@ def test_commit_grpc_error(self): def test_commit_ok(self): import datetime - from google.cloud.proto.spanner.v1.spanner_pb2 import CommitResponse - from google.cloud.proto.spanner.v1.transaction_pb2 import ( + from google.cloud.spanner_v1.proto.spanner_pb2 import CommitResponse + from google.cloud.spanner_v1.proto.transaction_pb2 import ( TransactionOptions) from google.cloud._helpers import UTC from google.cloud._helpers import _datetime_to_pb_timestamp @@ -282,8 +282,8 @@ def test_context_mgr_already_committed(self): def test_context_mgr_success(self): import datetime - from google.cloud.proto.spanner.v1.spanner_pb2 import CommitResponse - from google.cloud.proto.spanner.v1.transaction_pb2 import ( + from google.cloud.spanner_v1.proto.spanner_pb2 import CommitResponse + from google.cloud.spanner_v1.proto.transaction_pb2 import ( TransactionOptions) from google.cloud._helpers import UTC from google.cloud._helpers import _datetime_to_pb_timestamp @@ -312,7 +312,7 @@ def test_context_mgr_success(self): def test_context_mgr_failure(self): import datetime - from google.cloud.proto.spanner.v1.spanner_pb2 import CommitResponse + from google.cloud.spanner_v1.proto.spanner_pb2 import CommitResponse from google.cloud._helpers import UTC from google.cloud._helpers import _datetime_to_pb_timestamp diff --git a/spanner/tests/unit/test_client.py b/spanner/tests/unit/test_client.py index 5fd79ab86ebb..1020985657e1 100644 --- a/spanner/tests/unit/test_client.py +++ b/spanner/tests/unit/test_client.py @@ -42,9 +42,9 @@ class TestClient(unittest.TestCase): USER_AGENT = 'you-sir-age-int' def _get_target_class(self): - from google.cloud.spanner.client import Client + from google.cloud import spanner - return Client + return spanner.Client def _make_one(self, *args, **kwargs): return self._get_target_class()(*args, **kwargs) @@ -52,7 +52,7 @@ def _make_one(self, *args, **kwargs): def _constructor_test_helper(self, expected_scopes, creds, user_agent=None, expected_creds=None): - from google.cloud.spanner import client as MUT + from google.cloud.spanner_v1 import client as MUT user_agent = user_agent or MUT.DEFAULT_USER_AGENT client = self._make_one(project=self.PROJECT, credentials=creds, @@ -69,7 +69,7 @@ def _constructor_test_helper(self, expected_scopes, creds, self.assertEqual(client.user_agent, user_agent) def test_constructor_default_scopes(self): - from google.cloud.spanner import client as MUT + from google.cloud.spanner_v1 import client as MUT expected_scopes = ( MUT.SPANNER_ADMIN_SCOPE, @@ -78,7 +78,7 @@ def test_constructor_default_scopes(self): self._constructor_test_helper(expected_scopes, creds) def test_constructor_custom_user_agent_and_timeout(self): - from google.cloud.spanner import client as MUT + from google.cloud.spanner_v1 import client as MUT CUSTOM_USER_AGENT = 'custom-application' expected_scopes = ( @@ -106,9 +106,9 @@ def test_constructor_credentials_wo_create_scoped(self): self._constructor_test_helper(expected_scopes, creds) def test_admin_api_lib_name(self): - from google.cloud.spanner import __version__ - from google.cloud.gapic.spanner_admin_database import v1 as db - from google.cloud.gapic.spanner_admin_instance import v1 as inst + from google.cloud.spanner_v1 import __version__ + from google.cloud.spanner_admin_database_v1 import gapic as db + from google.cloud.spanner_admin_instance_v1 import gapic as inst # Get the actual admin client classes. DatabaseAdminClient = db.database_admin_client.DatabaseAdminClient @@ -145,16 +145,15 @@ def test_admin_api_lib_name(self): __version__) def test_instance_admin_api(self): - from google.cloud.spanner import __version__ - from google.cloud.spanner.client import SPANNER_ADMIN_SCOPE + from google.cloud.spanner_v1 import __version__ + from google.cloud.spanner_v1.client import SPANNER_ADMIN_SCOPE credentials = _make_credentials() client = self._make_one(project=self.PROJECT, credentials=credentials) expected_scopes = (SPANNER_ADMIN_SCOPE,) - patch = mock.patch('google.cloud.spanner.client.InstanceAdminClient') - - with patch as instance_admin_client: + inst_module = 'google.cloud.spanner_v1.client.InstanceAdminClient' + with mock.patch(inst_module) as instance_admin_client: api = client.instance_admin_api self.assertIs(api, instance_admin_client.return_value) @@ -171,16 +170,15 @@ def test_instance_admin_api(self): credentials.with_scopes.assert_called_once_with(expected_scopes) def test_database_admin_api(self): - from google.cloud.spanner import __version__ - from google.cloud.spanner.client import SPANNER_ADMIN_SCOPE + from google.cloud.spanner_v1 import __version__ + from google.cloud.spanner_v1.client import SPANNER_ADMIN_SCOPE credentials = _make_credentials() client = self._make_one(project=self.PROJECT, credentials=credentials) expected_scopes = (SPANNER_ADMIN_SCOPE,) - patch = mock.patch('google.cloud.spanner.client.DatabaseAdminClient') - - with patch as database_admin_client: + db_module = 'google.cloud.spanner_v1.client.DatabaseAdminClient' + with mock.patch(db_module) as database_admin_client: api = client.database_admin_api self.assertIs(api, database_admin_client.return_value) @@ -225,7 +223,7 @@ def test_project_name_property(self): def test_list_instance_configs_wo_paging(self): from google.cloud._testing import _GAXPageIterator from google.gax import INITIAL_PAGE - from google.cloud.spanner.client import InstanceConfig + from google.cloud.spanner_v1.client import InstanceConfig credentials = _make_credentials() client = self._make_one(project=self.PROJECT, credentials=credentials) @@ -255,7 +253,7 @@ def test_list_instance_configs_wo_paging(self): def test_list_instance_configs_w_paging(self): from google.cloud._testing import _GAXPageIterator - from google.cloud.spanner.client import InstanceConfig + from google.cloud.spanner_v1.client import InstanceConfig SIZE = 15 TOKEN_RETURNED = 'TOKEN_RETURNED' @@ -290,8 +288,8 @@ def test_list_instance_configs_w_paging(self): [('google-cloud-resource-prefix', client.project_name)]) def test_instance_factory_defaults(self): - from google.cloud.spanner.instance import DEFAULT_NODE_COUNT - from google.cloud.spanner.instance import Instance + from google.cloud.spanner_v1.instance import DEFAULT_NODE_COUNT + from google.cloud.spanner_v1.instance import Instance credentials = _make_credentials() client = self._make_one(project=self.PROJECT, credentials=credentials) @@ -306,7 +304,7 @@ def test_instance_factory_defaults(self): self.assertIs(instance._client, client) def test_instance_factory_explicit(self): - from google.cloud.spanner.instance import Instance + from google.cloud.spanner_v1.instance import Instance credentials = _make_credentials() client = self._make_one(project=self.PROJECT, credentials=credentials) @@ -325,7 +323,7 @@ def test_instance_factory_explicit(self): def test_list_instances_wo_paging(self): from google.cloud._testing import _GAXPageIterator from google.gax import INITIAL_PAGE - from google.cloud.spanner.instance import Instance + from google.cloud.spanner_v1.instance import Instance credentials = _make_credentials() client = self._make_one(project=self.PROJECT, credentials=credentials) @@ -360,7 +358,7 @@ def test_list_instances_wo_paging(self): def test_list_instances_w_paging(self): from google.cloud._testing import _GAXPageIterator - from google.cloud.spanner.instance import Instance + from google.cloud.spanner_v1.instance import Instance SIZE = 15 TOKEN_RETURNED = 'TOKEN_RETURNED' diff --git a/spanner/tests/unit/test_database.py b/spanner/tests/unit/test_database.py index 851fec4a2175..49e9b4a4c36e 100644 --- a/spanner/tests/unit/test_database.py +++ b/spanner/tests/unit/test_database.py @@ -19,7 +19,7 @@ from google.cloud._testing import _GAXBaseAPI -from google.cloud.spanner import __version__ +from google.cloud.spanner_v1 import __version__ def _make_credentials(): # pragma: NO COVER @@ -51,12 +51,12 @@ def _make_one(self, *args, **kwargs): class TestDatabase(_BaseTest): def _getTargetClass(self): - from google.cloud.spanner.database import Database + from google.cloud.spanner_v1.database import Database return Database def test_ctor_defaults(self): - from google.cloud.spanner.pool import BurstyPool + from google.cloud.spanner_v1.pool import BurstyPool instance = _Instance(self.INSTANCE_NAME) @@ -106,7 +106,7 @@ def test_ctor_w_ddl_statements_ok(self): self.assertEqual(list(database.ddl_statements), DDL_STATEMENTS) def test_from_pb_bad_database_name(self): - from google.cloud.proto.spanner.admin.database.v1 import ( + from google.cloud.spanner_admin_database_v1.proto import ( spanner_database_admin_pb2 as admin_v1_pb2) database_name = 'INCORRECT_FORMAT' @@ -117,7 +117,7 @@ def test_from_pb_bad_database_name(self): klass.from_pb(database_pb, None) def test_from_pb_project_mistmatch(self): - from google.cloud.proto.spanner.admin.database.v1 import ( + from google.cloud.spanner_admin_database_v1.proto import ( spanner_database_admin_pb2 as admin_v1_pb2) ALT_PROJECT = 'ALT_PROJECT' @@ -130,7 +130,7 @@ def test_from_pb_project_mistmatch(self): klass.from_pb(database_pb, instance) def test_from_pb_instance_mistmatch(self): - from google.cloud.proto.spanner.admin.database.v1 import ( + from google.cloud.spanner_admin_database_v1.proto import ( spanner_database_admin_pb2 as admin_v1_pb2) ALT_INSTANCE = '/projects/%s/instances/ALT-INSTANCE' % ( @@ -144,7 +144,7 @@ def test_from_pb_instance_mistmatch(self): klass.from_pb(database_pb, instance) def test_from_pb_success_w_explicit_pool(self): - from google.cloud.proto.spanner.admin.database.v1 import ( + from google.cloud.spanner_admin_database_v1.proto import ( spanner_database_admin_pb2 as admin_v1_pb2) client = _Client() @@ -161,9 +161,9 @@ def test_from_pb_success_w_explicit_pool(self): self.assertIs(database._pool, pool) def test_from_pb_success_w_hyphen_w_default_pool(self): - from google.cloud.proto.spanner.admin.database.v1 import ( + from google.cloud.spanner_admin_database_v1.proto import ( spanner_database_admin_pb2 as admin_v1_pb2) - from google.cloud.spanner.pool import BurstyPool + from google.cloud.spanner_v1.pool import BurstyPool DATABASE_ID_HYPHEN = 'database-id' DATABASE_NAME_HYPHEN = ( @@ -196,7 +196,7 @@ def test_spanner_api_property_w_scopeless_creds(self): pool = _Pool() database = self._make_one(self.DATABASE_ID, instance, pool=pool) - patch = mock.patch('google.cloud.spanner.database.SpannerClient') + patch = mock.patch('google.cloud.spanner_v1.database.SpannerClient') with patch as spanner_client: api = database.spanner_api @@ -214,7 +214,7 @@ def test_spanner_api_property_w_scopeless_creds(self): def test_spanner_api_w_scoped_creds(self): import google.auth.credentials - from google.cloud.spanner.database import SPANNER_DATA_SCOPE + from google.cloud.spanner_v1.database import SPANNER_DATA_SCOPE class _CredentialsWithScopes( google.auth.credentials.Scoped): @@ -236,7 +236,7 @@ def with_scopes(self, scopes): pool = _Pool() database = self._make_one(self.DATABASE_ID, instance, pool=pool) - patch = mock.patch('google.cloud.spanner.database.SpannerClient') + patch = mock.patch('google.cloud.spanner_v1.database.SpannerClient') with patch as spanner_client: api = database.spanner_api @@ -411,7 +411,7 @@ def test_exists_not_found(self): [('google-cloud-resource-prefix', database.name)]) def test_exists_success(self): - from google.cloud.proto.spanner.admin.database.v1 import ( + from google.cloud.spanner_admin_database_v1.proto import ( spanner_database_admin_pb2 as admin_v1_pb2) from tests._fixtures import DDL_STATEMENTS @@ -468,7 +468,7 @@ def test_reload_not_found(self): [('google-cloud-resource-prefix', database.name)]) def test_reload_success(self): - from google.cloud.proto.spanner.admin.database.v1 import ( + from google.cloud.spanner_admin_database_v1.proto import ( spanner_database_admin_pb2 as admin_v1_pb2) from tests._fixtures import DDL_STATEMENTS @@ -608,7 +608,7 @@ def test_drop_success(self): [('google-cloud-resource-prefix', database.name)]) def test_session_factory(self): - from google.cloud.spanner.session import Session + from google.cloud.spanner_v1.session import Session client = _Client() instance = _Instance(self.INSTANCE_NAME, client=client) @@ -622,7 +622,7 @@ def test_session_factory(self): self.assertIs(session._database, database) def test_snapshot_defaults(self): - from google.cloud.spanner.database import SnapshotCheckout + from google.cloud.spanner_v1.database import SnapshotCheckout client = _Client() instance = _Instance(self.INSTANCE_NAME, client=client) @@ -639,7 +639,7 @@ def test_snapshot_defaults(self): def test_snapshot_w_read_timestamp_and_multi_use(self): import datetime from google.cloud._helpers import UTC - from google.cloud.spanner.database import SnapshotCheckout + from google.cloud.spanner_v1.database import SnapshotCheckout now = datetime.datetime.utcnow().replace(tzinfo=UTC) client = _Client() @@ -657,7 +657,7 @@ def test_snapshot_w_read_timestamp_and_multi_use(self): checkout._kw, {'read_timestamp': now, 'multi_use': True}) def test_batch(self): - from google.cloud.spanner.database import BatchCheckout + from google.cloud.spanner_v1.database import BatchCheckout client = _Client() instance = _Instance(self.INSTANCE_NAME, client=client) @@ -739,7 +739,7 @@ def nested_unit_of_work(): class TestBatchCheckout(_BaseTest): def _getTargetClass(self): - from google.cloud.spanner.database import BatchCheckout + from google.cloud.spanner_v1.database import BatchCheckout return BatchCheckout @@ -750,12 +750,12 @@ def test_ctor(self): def test_context_mgr_success(self): import datetime - from google.cloud.proto.spanner.v1.spanner_pb2 import CommitResponse - from google.cloud.proto.spanner.v1.transaction_pb2 import ( + from google.cloud.spanner_v1.proto.spanner_pb2 import CommitResponse + from google.cloud.spanner_v1.proto.transaction_pb2 import ( TransactionOptions) from google.cloud._helpers import UTC from google.cloud._helpers import _datetime_to_pb_timestamp - from google.cloud.spanner.batch import Batch + from google.cloud.spanner_v1.batch import Batch now = datetime.datetime.utcnow().replace(tzinfo=UTC) now_pb = _datetime_to_pb_timestamp(now) @@ -785,7 +785,7 @@ def test_context_mgr_success(self): [('google-cloud-resource-prefix', database.name)]) def test_context_mgr_failure(self): - from google.cloud.spanner.batch import Batch + from google.cloud.spanner_v1.batch import Batch database = _Database(self.DATABASE_NAME) pool = database._pool = _Pool() @@ -810,12 +810,12 @@ class Testing(Exception): class TestSnapshotCheckout(_BaseTest): def _getTargetClass(self): - from google.cloud.spanner.database import SnapshotCheckout + from google.cloud.spanner_v1.database import SnapshotCheckout return SnapshotCheckout def test_ctor_defaults(self): - from google.cloud.spanner.snapshot import Snapshot + from google.cloud.spanner_v1.snapshot import Snapshot database = _Database(self.DATABASE_NAME) session = _Session(database) @@ -838,7 +838,7 @@ def test_ctor_defaults(self): def test_ctor_w_read_timestamp_and_multi_use(self): import datetime from google.cloud._helpers import UTC - from google.cloud.spanner.snapshot import Snapshot + from google.cloud.spanner_v1.snapshot import Snapshot now = datetime.datetime.utcnow().replace(tzinfo=UTC) database = _Database(self.DATABASE_NAME) @@ -861,7 +861,7 @@ def test_ctor_w_read_timestamp_and_multi_use(self): self.assertIs(pool._session, session) def test_context_mgr_failure(self): - from google.cloud.spanner.snapshot import Snapshot + from google.cloud.spanner_v1.snapshot import Snapshot database = _Database(self.DATABASE_NAME) pool = database._pool = _Pool() diff --git a/spanner/tests/unit/test_instance.py b/spanner/tests/unit/test_instance.py index ca8edacf3b81..57c535969177 100644 --- a/spanner/tests/unit/test_instance.py +++ b/spanner/tests/unit/test_instance.py @@ -37,7 +37,7 @@ class TestInstance(unittest.TestCase): DATABASE_NAME = '%s/databases/%s' % (INSTANCE_NAME, DATABASE_ID) def _getTargetClass(self): - from google.cloud.spanner.instance import Instance + from google.cloud.spanner_v1.instance import Instance return Instance @@ -45,7 +45,7 @@ def _make_one(self, *args, **kwargs): return self._getTargetClass()(*args, **kwargs) def test_constructor_defaults(self): - from google.cloud.spanner.instance import DEFAULT_NODE_COUNT + from google.cloud.spanner_v1.instance import DEFAULT_NODE_COUNT client = object() instance = self._make_one(self.INSTANCE_ID, client) @@ -85,7 +85,7 @@ def test_copy(self): self.assertEqual(instance, new_instance) def test__update_from_pb_success(self): - from google.cloud.proto.spanner.admin.instance.v1 import ( + from google.cloud.spanner_admin_instance_v1.proto import ( spanner_instance_admin_pb2 as admin_v1_pb2) display_name = 'display_name' @@ -99,7 +99,7 @@ def test__update_from_pb_success(self): self.assertEqual(instance.display_name, display_name) def test__update_from_pb_no_display_name(self): - from google.cloud.proto.spanner.admin.instance.v1 import ( + from google.cloud.spanner_admin_instance_v1.proto import ( spanner_instance_admin_pb2 as admin_v1_pb2) instance_pb = admin_v1_pb2.Instance() @@ -110,7 +110,7 @@ def test__update_from_pb_no_display_name(self): self.assertEqual(instance.display_name, None) def test_from_pb_bad_instance_name(self): - from google.cloud.proto.spanner.admin.instance.v1 import ( + from google.cloud.spanner_admin_instance_v1.proto import ( spanner_instance_admin_pb2 as admin_v1_pb2) instance_name = 'INCORRECT_FORMAT' @@ -121,7 +121,7 @@ def test_from_pb_bad_instance_name(self): klass.from_pb(instance_pb, None) def test_from_pb_project_mistmatch(self): - from google.cloud.proto.spanner.admin.instance.v1 import ( + from google.cloud.spanner_admin_instance_v1.proto import ( spanner_instance_admin_pb2 as admin_v1_pb2) ALT_PROJECT = 'ALT_PROJECT' @@ -136,7 +136,7 @@ def test_from_pb_project_mistmatch(self): klass.from_pb(instance_pb, client) def test_from_pb_success(self): - from google.cloud.proto.spanner.admin.instance.v1 import ( + from google.cloud.spanner_admin_instance_v1.proto import ( spanner_instance_admin_pb2 as admin_v1_pb2) client = _Client(project=self.PROJECT) @@ -283,7 +283,7 @@ def test_exists_instance_not_found(self): [('google-cloud-resource-prefix', instance.name)]) def test_exists_success(self): - from google.cloud.proto.spanner.admin.instance.v1 import ( + from google.cloud.spanner_admin_instance_v1.proto import ( spanner_instance_admin_pb2 as admin_v1_pb2) client = _Client(self.PROJECT) @@ -338,7 +338,7 @@ def test_reload_instance_not_found(self): [('google-cloud-resource-prefix', instance.name)]) def test_reload_success(self): - from google.cloud.proto.spanner.admin.instance.v1 import ( + from google.cloud.spanner_admin_instance_v1.proto import ( spanner_instance_admin_pb2 as admin_v1_pb2) client = _Client(self.PROJECT) @@ -365,7 +365,7 @@ def test_reload_success(self): def test_update_grpc_error(self): from google.gax.errors import GaxError - from google.cloud.spanner.instance import DEFAULT_NODE_COUNT + from google.cloud.spanner_v1.instance import DEFAULT_NODE_COUNT client = _Client(self.PROJECT) api = client.instance_admin_api = _FauxInstanceAdminAPI( @@ -388,7 +388,7 @@ def test_update_grpc_error(self): def test_update_not_found(self): from google.cloud.exceptions import NotFound - from google.cloud.spanner.instance import DEFAULT_NODE_COUNT + from google.cloud.spanner_v1.instance import DEFAULT_NODE_COUNT client = _Client(self.PROJECT) api = client.instance_admin_api = _FauxInstanceAdminAPI( @@ -481,8 +481,8 @@ def test_delete_success(self): [('google-cloud-resource-prefix', instance.name)]) def test_database_factory_defaults(self): - from google.cloud.spanner.database import Database - from google.cloud.spanner.pool import BurstyPool + from google.cloud.spanner_v1.database import Database + from google.cloud.spanner_v1.pool import BurstyPool client = _Client(self.PROJECT) instance = self._make_one(self.INSTANCE_ID, client, self.CONFIG_NAME) @@ -499,7 +499,7 @@ def test_database_factory_defaults(self): self.assertIs(pool._database, database) def test_database_factory_explicit(self): - from google.cloud.spanner.database import Database + from google.cloud.spanner_v1.database import Database from tests._fixtures import DDL_STATEMENTS client = _Client(self.PROJECT) @@ -520,7 +520,7 @@ def test_database_factory_explicit(self): def test_list_databases_wo_paging(self): from google.cloud._testing import _GAXPageIterator from google.gax import INITIAL_PAGE - from google.cloud.spanner.database import Database + from google.cloud.spanner_v1.database import Database NEXT_TOKEN = 'TOKEN' database_pb = _DatabasePB(name=self.DATABASE_NAME) @@ -549,7 +549,7 @@ def test_list_databases_wo_paging(self): def test_list_databases_w_paging(self): from google.cloud._testing import _GAXPageIterator - from google.cloud.spanner.database import Database + from google.cloud.spanner_v1.database import Database SIZE = 15 TOKEN = 'TOKEN' diff --git a/spanner/tests/unit/test_keyset.py b/spanner/tests/unit/test_keyset.py index 6ee0670c5828..800c0cf2cdd2 100644 --- a/spanner/tests/unit/test_keyset.py +++ b/spanner/tests/unit/test_keyset.py @@ -19,7 +19,7 @@ class TestKeyRange(unittest.TestCase): def _getTargetClass(self): - from google.cloud.spanner.keyset import KeyRange + from google.cloud.spanner_v1.keyset import KeyRange return KeyRange @@ -93,7 +93,7 @@ def test_ctor_w_start_closed_and_end_open(self): self.assertEqual(krange.end_closed, None) def test_to_pb_w_start_closed_and_end_open(self): - from google.cloud.proto.spanner.v1.keys_pb2 import KeyRange + from google.cloud.spanner_v1.proto.keys_pb2 import KeyRange KEY_1 = [u'key_1'] KEY_2 = [u'key_2'] @@ -107,7 +107,7 @@ def test_to_pb_w_start_closed_and_end_open(self): self.assertEqual(krange_pb.end_open.values[0].string_value, KEY_2[0]) def test_to_pb_w_start_open_and_end_closed(self): - from google.cloud.proto.spanner.v1.keys_pb2 import KeyRange + from google.cloud.spanner_v1.proto.keys_pb2 import KeyRange KEY_1 = [u'key_1'] KEY_2 = [u'key_2'] @@ -123,7 +123,7 @@ def test_to_pb_w_start_open_and_end_closed(self): class TestKeySet(unittest.TestCase): def _getTargetClass(self): - from google.cloud.spanner.keyset import KeySet + from google.cloud.spanner_v1.keyset import KeySet return KeySet @@ -147,7 +147,7 @@ def test_ctor_w_keys(self): self.assertEqual(keyset.ranges, []) def test_ctor_w_ranges(self): - from google.cloud.spanner.keyset import KeyRange + from google.cloud.spanner_v1.keyset import KeyRange range_1 = KeyRange(start_closed=[u'key1'], end_open=[u'key3']) range_2 = KeyRange(start_open=[u'key5'], end_closed=[u'key6']) @@ -164,7 +164,7 @@ def test_ctor_w_all_and_keys(self): self._make_one(all_=True, keys=[['key1'], ['key2']]) def test_ctor_w_all_and_ranges(self): - from google.cloud.spanner.keyset import KeyRange + from google.cloud.spanner_v1.keyset import KeyRange range_1 = KeyRange(start_closed=[u'key1'], end_open=[u'key3']) range_2 = KeyRange(start_open=[u'key5'], end_closed=[u'key6']) @@ -173,7 +173,7 @@ def test_ctor_w_all_and_ranges(self): self._make_one(all_=True, ranges=[range_1, range_2]) def test_to_pb_w_all(self): - from google.cloud.proto.spanner.v1.keys_pb2 import KeySet + from google.cloud.spanner_v1.proto.keys_pb2 import KeySet keyset = self._make_one(all_=True) @@ -185,7 +185,7 @@ def test_to_pb_w_all(self): self.assertEqual(len(result.ranges), 0) def test_to_pb_w_only_keys(self): - from google.cloud.proto.spanner.v1.keys_pb2 import KeySet + from google.cloud.spanner_v1.proto.keys_pb2 import KeySet KEYS = [[u'key1'], [u'key2']] keyset = self._make_one(keys=KEYS) @@ -203,8 +203,8 @@ def test_to_pb_w_only_keys(self): self.assertEqual(len(result.ranges), 0) def test_to_pb_w_only_ranges(self): - from google.cloud.proto.spanner.v1.keys_pb2 import KeySet - from google.cloud.spanner.keyset import KeyRange + from google.cloud.spanner_v1.proto.keys_pb2 import KeySet + from google.cloud.spanner_v1.keyset import KeyRange KEY_1 = u'KEY_1' KEY_2 = u'KEY_2' diff --git a/spanner/tests/unit/test_types.py b/spanner/tests/unit/test_param_types.py similarity index 59% rename from spanner/tests/unit/test_types.py rename to spanner/tests/unit/test_param_types.py index 4f30779c757f..bb1f02247416 100644 --- a/spanner/tests/unit/test_types.py +++ b/spanner/tests/unit/test_param_types.py @@ -19,15 +19,15 @@ class Test_ArrayParamType(unittest.TestCase): def test_it(self): - from google.cloud.proto.spanner.v1 import type_pb2 - from google.cloud.spanner.types import ArrayParamType - from google.cloud.spanner.types import INT64_PARAM_TYPE + from google.cloud.spanner_v1.proto import type_pb2 + from google.cloud.spanner_v1 import param_types expected = type_pb2.Type( code=type_pb2.ARRAY, - array_element_type=type_pb2.Type(code=type_pb2.INT64)) + array_element_type=type_pb2.Type(code=type_pb2.INT64), + ) - found = ArrayParamType(INT64_PARAM_TYPE) + found = param_types.Array(param_types.INT64) self.assertEqual(found, expected) @@ -35,27 +35,27 @@ def test_it(self): class Test_Struct(unittest.TestCase): def test_it(self): - from google.cloud.proto.spanner.v1 import type_pb2 - from google.cloud.spanner.types import INT64_PARAM_TYPE - from google.cloud.spanner.types import STRING_PARAM_TYPE - from google.cloud.spanner.types import StructParamType - from google.cloud.spanner.types import StructField + from google.cloud.spanner_v1.proto import type_pb2 + from google.cloud.spanner_v1 import param_types struct_type = type_pb2.StructType(fields=[ type_pb2.StructType.Field( name='name', - type=type_pb2.Type(code=type_pb2.STRING)), + type=type_pb2.Type(code=type_pb2.STRING), + ), type_pb2.StructType.Field( name='count', - type=type_pb2.Type(code=type_pb2.INT64)), + type=type_pb2.Type(code=type_pb2.INT64), + ), ]) expected = type_pb2.Type( code=type_pb2.STRUCT, - struct_type=struct_type) + struct_type=struct_type, + ) - found = StructParamType([ - StructField('name', STRING_PARAM_TYPE), - StructField('count', INT64_PARAM_TYPE), + found = param_types.Struct([ + param_types.StructField('name', param_types.STRING), + param_types.StructField('count', param_types.INT64), ]) self.assertEqual(found, expected) diff --git a/spanner/tests/unit/test_pool.py b/spanner/tests/unit/test_pool.py index e4124dcf6b99..9334a5495493 100644 --- a/spanner/tests/unit/test_pool.py +++ b/spanner/tests/unit/test_pool.py @@ -20,7 +20,7 @@ class TestAbstractSessionPool(unittest.TestCase): def _getTargetClass(self): - from google.cloud.spanner.pool import AbstractSessionPool + from google.cloud.spanner_v1.pool import AbstractSessionPool return AbstractSessionPool @@ -54,7 +54,7 @@ def test_clear_abstract(self): pool.clear() def test_session_wo_kwargs(self): - from google.cloud.spanner.pool import SessionCheckout + from google.cloud.spanner_v1.pool import SessionCheckout pool = self._make_one() checkout = pool.session() @@ -64,7 +64,7 @@ def test_session_wo_kwargs(self): self.assertEqual(checkout._kwargs, {}) def test_session_w_kwargs(self): - from google.cloud.spanner.pool import SessionCheckout + from google.cloud.spanner_v1.pool import SessionCheckout pool = self._make_one() checkout = pool.session(foo='bar') @@ -77,7 +77,7 @@ def test_session_w_kwargs(self): class TestFixedSizePool(unittest.TestCase): def _getTargetClass(self): - from google.cloud.spanner.pool import FixedSizePool + from google.cloud.spanner_v1.pool import FixedSizePool return FixedSizePool @@ -210,7 +210,7 @@ def test_clear(self): class TestBurstyPool(unittest.TestCase): def _getTargetClass(self): - from google.cloud.spanner.pool import BurstyPool + from google.cloud.spanner_v1.pool import BurstyPool return BurstyPool @@ -326,7 +326,7 @@ def test_clear(self): class TestPingingPool(unittest.TestCase): def _getTargetClass(self): - from google.cloud.spanner.pool import PingingPool + from google.cloud.spanner_v1.pool import PingingPool return PingingPool @@ -382,7 +382,7 @@ def test_get_hit_no_ping(self): def test_get_hit_w_ping(self): import datetime from google.cloud._testing import _Monkey - from google.cloud.spanner import pool as MUT + from google.cloud.spanner_v1 import pool as MUT pool = self._make_one(size=4) database = _Database('name') @@ -404,7 +404,7 @@ def test_get_hit_w_ping(self): def test_get_hit_w_ping_expired(self): import datetime from google.cloud._testing import _Monkey - from google.cloud.spanner import pool as MUT + from google.cloud.spanner_v1 import pool as MUT pool = self._make_one(size=4) database = _Database('name') @@ -464,7 +464,7 @@ def test_put_full(self): def test_put_non_full(self): import datetime from google.cloud._testing import _Monkey - from google.cloud.spanner import pool as MUT + from google.cloud.spanner_v1 import pool as MUT pool = self._make_one(size=1) queue = pool._sessions = _Queue() @@ -515,7 +515,7 @@ def test_ping_oldest_fresh(self): def test_ping_oldest_stale_but_exists(self): import datetime from google.cloud._testing import _Monkey - from google.cloud.spanner import pool as MUT + from google.cloud.spanner_v1 import pool as MUT pool = self._make_one(size=1) database = _Database('name') @@ -532,7 +532,7 @@ def test_ping_oldest_stale_but_exists(self): def test_ping_oldest_stale_and_not_exists(self): import datetime from google.cloud._testing import _Monkey - from google.cloud.spanner import pool as MUT + from google.cloud.spanner_v1 import pool as MUT pool = self._make_one(size=1) database = _Database('name') @@ -552,7 +552,7 @@ def test_ping_oldest_stale_and_not_exists(self): class TestTransactionPingingPool(unittest.TestCase): def _getTargetClass(self): - from google.cloud.spanner.pool import TransactionPingingPool + from google.cloud.spanner_v1.pool import TransactionPingingPool return TransactionPingingPool @@ -601,7 +601,7 @@ def test_bind(self): def test_bind_w_timestamp_race(self): import datetime from google.cloud._testing import _Monkey - from google.cloud.spanner import pool as MUT + from google.cloud.spanner_v1 import pool as MUT NOW = datetime.datetime.utcnow() pool = self._make_one() database = _Database('name') @@ -715,7 +715,7 @@ def test_begin_pending_transactions_non_empty(self): class TestSessionCheckout(unittest.TestCase): def _getTargetClass(self): - from google.cloud.spanner.pool import SessionCheckout + from google.cloud.spanner_v1.pool import SessionCheckout return SessionCheckout diff --git a/spanner/tests/unit/test_session.py b/spanner/tests/unit/test_session.py index a045e94d35de..51fe7c03783f 100644 --- a/spanner/tests/unit/test_session.py +++ b/spanner/tests/unit/test_session.py @@ -29,7 +29,7 @@ class TestSession(unittest.TestCase): SESSION_NAME = DATABASE_NAME + '/sessions/' + SESSION_ID def _getTargetClass(self): - from google.cloud.spanner.session import Session + from google.cloud.spanner_v1.session import Session return Session @@ -214,7 +214,7 @@ def test_snapshot_not_created(self): session.snapshot() def test_snapshot_created(self): - from google.cloud.spanner.snapshot import Snapshot + from google.cloud.spanner_v1.snapshot import Snapshot database = _Database(self.DATABASE_NAME) session = self._make_one(database) @@ -228,7 +228,7 @@ def test_snapshot_created(self): self.assertFalse(snapshot._multi_use) def test_snapshot_created_w_multi_use(self): - from google.cloud.spanner.snapshot import Snapshot + from google.cloud.spanner_v1.snapshot import Snapshot database = _Database(self.DATABASE_NAME) session = self._make_one(database) @@ -242,7 +242,7 @@ def test_snapshot_created_w_multi_use(self): self.assertTrue(snapshot._multi_use) def test_read_not_created(self): - from google.cloud.spanner.keyset import KeySet + from google.cloud.spanner_v1.keyset import KeySet TABLE_NAME = 'citizens' COLUMNS = ['email', 'first_name', 'last_name', 'age'] @@ -255,9 +255,9 @@ def test_read_not_created(self): session.read(TABLE_NAME, COLUMNS, KEYSET) def test_read(self): - from google.cloud.spanner import session as MUT + from google.cloud.spanner_v1 import session as MUT from google.cloud._testing import _Monkey - from google.cloud.spanner.keyset import KeySet + from google.cloud.spanner_v1.keyset import KeySet TABLE_NAME = 'citizens' COLUMNS = ['email', 'first_name', 'last_name', 'age'] @@ -308,7 +308,7 @@ def test_execute_sql_not_created(self): session.execute_sql(SQL) def test_execute_sql_defaults(self): - from google.cloud.spanner import session as MUT + from google.cloud.spanner_v1 import session as MUT from google.cloud._testing import _Monkey SQL = 'SELECT first_name, age FROM citizens' @@ -353,7 +353,7 @@ def test_batch_not_created(self): session.batch() def test_batch_created(self): - from google.cloud.spanner.batch import Batch + from google.cloud.spanner_v1.batch import Batch database = _Database(self.DATABASE_NAME) session = self._make_one(database) @@ -372,7 +372,7 @@ def test_transaction_not_created(self): session.transaction() def test_transaction_created(self): - from google.cloud.spanner.transaction import Transaction + from google.cloud.spanner_v1.transaction import Transaction database = _Database(self.DATABASE_NAME) session = self._make_one(database) @@ -397,7 +397,7 @@ def test_transaction_w_existing_txn(self): def test_retry_transaction_w_commit_error_txn_already_begun(self): from google.gax.errors import GaxError - from google.cloud.spanner.transaction import Transaction + from google.cloud.spanner_v1.transaction import Transaction TABLE_NAME = 'citizens' COLUMNS = ['email', 'first_name', 'last_name', 'age'] @@ -432,9 +432,9 @@ def unit_of_work(txn, *args, **kw): self.assertEqual(kw, {}) def test_run_in_transaction_callback_raises_abort(self): - from google.cloud.proto.spanner.v1.transaction_pb2 import ( + from google.cloud.spanner_v1.proto.transaction_pb2 import ( Transaction as TransactionPB) - from google.cloud.spanner.transaction import Transaction + from google.cloud.spanner_v1.transaction import Transaction TABLE_NAME = 'citizens' COLUMNS = ['email', 'first_name', 'last_name', 'age'] @@ -476,12 +476,12 @@ def unit_of_work(txn, *args, **kw): def test_run_in_transaction_w_args_w_kwargs_wo_abort(self): import datetime - from google.cloud.proto.spanner.v1.spanner_pb2 import CommitResponse - from google.cloud.proto.spanner.v1.transaction_pb2 import ( + from google.cloud.spanner_v1.proto.spanner_pb2 import CommitResponse + from google.cloud.spanner_v1.proto.transaction_pb2 import ( Transaction as TransactionPB) from google.cloud._helpers import UTC from google.cloud._helpers import _datetime_to_pb_timestamp - from google.cloud.spanner.transaction import Transaction + from google.cloud.spanner_v1.transaction import Transaction TABLE_NAME = 'citizens' COLUMNS = ['email', 'first_name', 'last_name', 'age'] @@ -523,12 +523,12 @@ def unit_of_work(txn, *args, **kw): def test_run_in_transaction_w_abort_no_retry_metadata(self): import datetime - from google.cloud.proto.spanner.v1.spanner_pb2 import CommitResponse - from google.cloud.proto.spanner.v1.transaction_pb2 import ( + from google.cloud.spanner_v1.proto.spanner_pb2 import CommitResponse + from google.cloud.spanner_v1.proto.transaction_pb2 import ( Transaction as TransactionPB) from google.cloud._helpers import UTC from google.cloud._helpers import _datetime_to_pb_timestamp - from google.cloud.spanner.transaction import Transaction + from google.cloud.spanner_v1.transaction import Transaction TABLE_NAME = 'citizens' COLUMNS = ['email', 'first_name', 'last_name', 'age'] @@ -570,13 +570,13 @@ def unit_of_work(txn, *args, **kw): def test_run_in_transaction_w_abort_w_retry_metadata(self): import datetime - from google.cloud.proto.spanner.v1.spanner_pb2 import CommitResponse - from google.cloud.proto.spanner.v1.transaction_pb2 import ( + from google.cloud.spanner_v1.proto.spanner_pb2 import CommitResponse + from google.cloud.spanner_v1.proto.transaction_pb2 import ( Transaction as TransactionPB) from google.cloud._helpers import UTC from google.cloud._helpers import _datetime_to_pb_timestamp - from google.cloud.spanner.transaction import Transaction - from google.cloud.spanner import session as MUT + from google.cloud.spanner_v1.transaction import Transaction + from google.cloud.spanner_v1 import session as MUT from google.cloud._testing import _Monkey TABLE_NAME = 'citizens' @@ -631,13 +631,13 @@ def test_run_in_transaction_w_callback_raises_abort_wo_metadata(self): import datetime from google.gax.errors import GaxError from grpc import StatusCode - from google.cloud.proto.spanner.v1.spanner_pb2 import CommitResponse - from google.cloud.proto.spanner.v1.transaction_pb2 import ( + from google.cloud.spanner_v1.proto.spanner_pb2 import CommitResponse + from google.cloud.spanner_v1.proto.transaction_pb2 import ( Transaction as TransactionPB) from google.cloud._helpers import UTC from google.cloud._helpers import _datetime_to_pb_timestamp - from google.cloud.spanner.transaction import Transaction - from google.cloud.spanner import session as MUT + from google.cloud.spanner_v1.transaction import Transaction + from google.cloud.spanner_v1 import session as MUT from google.cloud._testing import _Monkey TABLE_NAME = 'citizens' @@ -697,13 +697,13 @@ def test_run_in_transaction_w_abort_w_retry_metadata_deadline(self): from google.gax.errors import GaxError from google.gax.grpc import exc_to_code from grpc import StatusCode - from google.cloud.proto.spanner.v1.spanner_pb2 import CommitResponse - from google.cloud.proto.spanner.v1.transaction_pb2 import ( + from google.cloud.spanner_v1.proto.spanner_pb2 import CommitResponse + from google.cloud.spanner_v1.proto.transaction_pb2 import ( Transaction as TransactionPB) from google.cloud._helpers import UTC from google.cloud._helpers import _datetime_to_pb_timestamp - from google.cloud.spanner.transaction import Transaction - from google.cloud.spanner import session as MUT + from google.cloud.spanner_v1.transaction import Transaction + from google.cloud.spanner_v1 import session as MUT from google.cloud._testing import _Monkey TABLE_NAME = 'citizens' @@ -754,14 +754,14 @@ def unit_of_work(txn, *args, **kw): self.assertEqual(kw, {'some_arg': 'def'}) def test_run_in_transaction_w_timeout(self): - from google.cloud.spanner import session as MUT + from google.cloud.spanner_v1 import session as MUT from google.cloud._testing import _Monkey from google.gax.errors import GaxError from google.gax.grpc import exc_to_code - from google.cloud.proto.spanner.v1.transaction_pb2 import ( + from google.cloud.spanner_v1.proto.transaction_pb2 import ( Transaction as TransactionPB) from grpc import StatusCode - from google.cloud.spanner.transaction import Transaction + from google.cloud.spanner_v1.transaction import Transaction TABLE_NAME = 'citizens' COLUMNS = ['email', 'first_name', 'last_name', 'age'] diff --git a/spanner/tests/unit/test_snapshot.py b/spanner/tests/unit/test_snapshot.py index a9b03a397910..6403a3e0f228 100644 --- a/spanner/tests/unit/test_snapshot.py +++ b/spanner/tests/unit/test_snapshot.py @@ -36,7 +36,7 @@ class Test_restart_on_unavailable(unittest.TestCase): def _call_fut(self, restart): - from google.cloud.spanner.snapshot import _restart_on_unavailable + from google.cloud.spanner_v1.snapshot import _restart_on_unavailable return _restart_on_unavailable(restart) @@ -123,7 +123,7 @@ class Test_SnapshotBase(unittest.TestCase): SESSION_NAME = DATABASE_NAME + '/sessions/' + SESSION_ID def _getTargetClass(self): - from google.cloud.spanner.snapshot import _SnapshotBase + from google.cloud.spanner_v1.snapshot import _SnapshotBase return _SnapshotBase @@ -138,7 +138,7 @@ class _Derived(self._getTargetClass()): _multi_use = False def _make_txn_selector(self): - from google.cloud.proto.spanner.v1.transaction_pb2 import ( + from google.cloud.spanner_v1.proto.transaction_pb2 import ( TransactionOptions, TransactionSelector) if self._transaction_id: @@ -163,10 +163,10 @@ def test__make_txn_selector_virtual(self): base._make_txn_selector() def test_read_grpc_error(self): - from google.cloud.proto.spanner.v1.transaction_pb2 import ( + from google.cloud.spanner_v1.proto.transaction_pb2 import ( TransactionSelector) from google.gax.errors import GaxError - from google.cloud.spanner.keyset import KeySet + from google.cloud.spanner_v1.keyset import KeySet KEYSET = KeySet(all_=True) database = _Database() @@ -195,14 +195,14 @@ def test_read_grpc_error(self): def _read_helper(self, multi_use, first=True, count=0): from google.protobuf.struct_pb2 import Struct - from google.cloud.proto.spanner.v1.result_set_pb2 import ( + from google.cloud.spanner_v1.proto.result_set_pb2 import ( PartialResultSet, ResultSetMetadata, ResultSetStats) - from google.cloud.proto.spanner.v1.transaction_pb2 import ( + from google.cloud.spanner_v1.proto.transaction_pb2 import ( TransactionSelector) - from google.cloud.proto.spanner.v1.type_pb2 import Type, StructType - from google.cloud.proto.spanner.v1.type_pb2 import STRING, INT64 - from google.cloud.spanner.keyset import KeySet - from google.cloud.spanner._helpers import _make_value_pb + from google.cloud.spanner_v1.proto.type_pb2 import Type, StructType + from google.cloud.spanner_v1.proto.type_pb2 import STRING, INT64 + from google.cloud.spanner_v1.keyset import KeySet + from google.cloud.spanner_v1._helpers import _make_value_pb TXN_ID = b'DEADBEEF' VALUES = [ @@ -300,7 +300,7 @@ def test_read_w_multi_use_w_first_w_count_gt_0(self): self._read_helper(multi_use=True, first=True, count=1) def test_execute_sql_grpc_error(self): - from google.cloud.proto.spanner.v1.transaction_pb2 import ( + from google.cloud.spanner_v1.proto.transaction_pb2 import ( TransactionSelector) from google.gax.errors import GaxError @@ -337,13 +337,13 @@ def test_execute_sql_w_params_wo_param_types(self): def _execute_sql_helper(self, multi_use, first=True, count=0): from google.protobuf.struct_pb2 import Struct - from google.cloud.proto.spanner.v1.result_set_pb2 import ( + from google.cloud.spanner_v1.proto.result_set_pb2 import ( PartialResultSet, ResultSetMetadata, ResultSetStats) - from google.cloud.proto.spanner.v1.transaction_pb2 import ( + from google.cloud.spanner_v1.proto.transaction_pb2 import ( TransactionSelector) - from google.cloud.proto.spanner.v1.type_pb2 import Type, StructType - from google.cloud.proto.spanner.v1.type_pb2 import STRING, INT64 - from google.cloud.spanner._helpers import _make_value_pb + from google.cloud.spanner_v1.proto.type_pb2 import Type, StructType + from google.cloud.spanner_v1.proto.type_pb2 import STRING, INT64 + from google.cloud.spanner_v1._helpers import _make_value_pb TXN_ID = b'DEADBEEF' VALUES = [ @@ -453,7 +453,7 @@ class TestSnapshot(unittest.TestCase): TRANSACTION_ID = b'DEADBEEF' def _getTargetClass(self): - from google.cloud.spanner.snapshot import Snapshot + from google.cloud.spanner_v1.snapshot import Snapshot return Snapshot def _make_one(self, *args, **kwargs): @@ -720,7 +720,7 @@ def test_begin_w_gax_error(self): [('google-cloud-resource-prefix', database.name)]) def test_begin_ok_exact_staleness(self): - from google.cloud.proto.spanner.v1.transaction_pb2 import ( + from google.cloud.spanner_v1.proto.transaction_pb2 import ( Transaction as TransactionPB) transaction_pb = TransactionPB(id=self.TRANSACTION_ID) @@ -746,7 +746,7 @@ def test_begin_ok_exact_staleness(self): [('google-cloud-resource-prefix', database.name)]) def test_begin_ok_exact_strong(self): - from google.cloud.proto.spanner.v1.transaction_pb2 import ( + from google.cloud.spanner_v1.proto.transaction_pb2 import ( Transaction as TransactionPB) transaction_pb = TransactionPB(id=self.TRANSACTION_ID) diff --git a/spanner/tests/unit/test_streamed.py b/spanner/tests/unit/test_streamed.py index c02c80466db7..4ab5dbc18d48 100644 --- a/spanner/tests/unit/test_streamed.py +++ b/spanner/tests/unit/test_streamed.py @@ -21,7 +21,7 @@ class TestStreamedResultSet(unittest.TestCase): def _getTargetClass(self): - from google.cloud.spanner.streamed import StreamedResultSet + from google.cloud.spanner_v1.streamed import StreamedResultSet return StreamedResultSet @@ -55,15 +55,15 @@ def test_fields_unset(self): @staticmethod def _make_scalar_field(name, type_): - from google.cloud.proto.spanner.v1.type_pb2 import StructType - from google.cloud.proto.spanner.v1.type_pb2 import Type + from google.cloud.spanner_v1.proto.type_pb2 import StructType + from google.cloud.spanner_v1.proto.type_pb2 import Type return StructType.Field(name=name, type=Type(code=type_)) @staticmethod def _make_array_field(name, element_type_code=None, element_type=None): - from google.cloud.proto.spanner.v1.type_pb2 import StructType - from google.cloud.proto.spanner.v1.type_pb2 import Type + from google.cloud.spanner_v1.proto.type_pb2 import StructType + from google.cloud.spanner_v1.proto.type_pb2 import Type if element_type is None: element_type = Type(code=element_type_code) @@ -73,8 +73,8 @@ def _make_array_field(name, element_type_code=None, element_type=None): @staticmethod def _make_struct_type(struct_type_fields): - from google.cloud.proto.spanner.v1.type_pb2 import StructType - from google.cloud.proto.spanner.v1.type_pb2 import Type + from google.cloud.spanner_v1.proto.type_pb2 import StructType + from google.cloud.spanner_v1.proto.type_pb2 import Type fields = [ StructType.Field(name=key, type=Type(code=value)) @@ -85,7 +85,7 @@ def _make_struct_type(struct_type_fields): @staticmethod def _make_value(value): - from google.cloud.spanner._helpers import _make_value_pb + from google.cloud.spanner_v1._helpers import _make_value_pb return _make_value_pb(value) @@ -93,7 +93,7 @@ def _make_value(value): def _make_list_value(values=(), value_pbs=None): from google.protobuf.struct_pb2 import ListValue from google.protobuf.struct_pb2 import Value - from google.cloud.spanner._helpers import _make_list_value_pb + from google.cloud.spanner_v1._helpers import _make_list_value_pb if value_pbs is not None: return Value(list_value=ListValue(values=value_pbs)) @@ -101,7 +101,7 @@ def _make_list_value(values=(), value_pbs=None): @staticmethod def _make_result_set_metadata(fields=(), transaction_id=None): - from google.cloud.proto.spanner.v1.result_set_pb2 import ( + from google.cloud.spanner_v1.proto.result_set_pb2 import ( ResultSetMetadata) metadata = ResultSetMetadata() for field in fields: @@ -112,10 +112,10 @@ def _make_result_set_metadata(fields=(), transaction_id=None): @staticmethod def _make_result_set_stats(query_plan=None, **kw): - from google.cloud.proto.spanner.v1.result_set_pb2 import ( + from google.cloud.spanner_v1.proto.result_set_pb2 import ( ResultSetStats) from google.protobuf.struct_pb2 import Struct - from google.cloud.spanner._helpers import _make_value_pb + from google.cloud.spanner_v1._helpers import _make_value_pb query_stats = Struct(fields={ key: _make_value_pb(value) for key, value in kw.items()}) @@ -127,7 +127,7 @@ def _make_result_set_stats(query_plan=None, **kw): @staticmethod def _make_partial_result_set( values, metadata=None, stats=None, chunked_value=False): - from google.cloud.proto.spanner.v1.result_set_pb2 import ( + from google.cloud.spanner_v1.proto.result_set_pb2 import ( PartialResultSet) return PartialResultSet( values=values, @@ -150,7 +150,7 @@ def test_properties_set(self): self.assertIs(streamed.stats, stats) def test__merge_chunk_bool(self): - from google.cloud.spanner.streamed import Unmergeable + from google.cloud.spanner_v1.streamed import Unmergeable iterator = _MockCancellableIterator() streamed = self._make_one(iterator) @@ -205,7 +205,7 @@ def test__merge_chunk_float64_w_empty(self): self.assertEqual(merged.number_value, 3.14159) def test__merge_chunk_float64_w_float64(self): - from google.cloud.spanner.streamed import Unmergeable + from google.cloud.spanner_v1.streamed import Unmergeable iterator = _MockCancellableIterator() streamed = self._make_one(iterator) @@ -347,8 +347,8 @@ def test__merge_chunk_array_of_string_with_null(self): self.assertIsNone(streamed._pending_chunk) def test__merge_chunk_array_of_array_of_int(self): - from google.cloud.proto.spanner.v1.type_pb2 import StructType - from google.cloud.proto.spanner.v1.type_pb2 import Type + from google.cloud.spanner_v1.proto.type_pb2 import StructType + from google.cloud.spanner_v1.proto.type_pb2 import Type subarray_type = Type( code='ARRAY', array_element_type=Type(code='INT64')) @@ -379,8 +379,8 @@ def test__merge_chunk_array_of_array_of_int(self): self.assertIsNone(streamed._pending_chunk) def test__merge_chunk_array_of_array_of_string(self): - from google.cloud.proto.spanner.v1.type_pb2 import StructType - from google.cloud.proto.spanner.v1.type_pb2 import Type + from google.cloud.spanner_v1.proto.type_pb2 import StructType + from google.cloud.spanner_v1.proto.type_pb2 import Type subarray_type = Type( code='ARRAY', array_element_type=Type(code='STRING')) @@ -910,7 +910,7 @@ class TestStreamedResultSet_JSON_acceptance_tests(unittest.TestCase): _json_tests = None def _getTargetClass(self): - from google.cloud.spanner.streamed import StreamedResultSet + from google.cloud.spanner_v1.streamed import StreamedResultSet return StreamedResultSet @@ -1015,7 +1015,7 @@ def test_multiple_row_chunks_non_chunks_interleaved(self): def _generate_partial_result_sets(prs_text_pbs): from google.protobuf.json_format import Parse - from google.cloud.proto.spanner.v1.result_set_pb2 import PartialResultSet + from google.cloud.spanner_v1.proto.result_set_pb2 import PartialResultSet partial_result_sets = [] @@ -1048,7 +1048,7 @@ def _normalize_float(cell): def _normalize_results(rows_data, fields): """Helper for _parse_streaming_read_acceptance_tests""" - from google.cloud.proto.spanner.v1 import type_pb2 + from google.cloud.spanner_v1.proto import type_pb2 normalized = [] for row_data in rows_data: diff --git a/spanner/tests/unit/test_transaction.py b/spanner/tests/unit/test_transaction.py index 98b25186ff1e..8fe13b3de2c7 100644 --- a/spanner/tests/unit/test_transaction.py +++ b/spanner/tests/unit/test_transaction.py @@ -38,7 +38,7 @@ class TestTransaction(unittest.TestCase): TRANSACTION_ID = b'DEADBEEF' def _getTargetClass(self): - from google.cloud.spanner.transaction import Transaction + from google.cloud.spanner_v1.transaction import Transaction return Transaction @@ -137,7 +137,7 @@ def test_begin_w_gax_error(self): [('google-cloud-resource-prefix', database.name)]) def test_begin_ok(self): - from google.cloud.proto.spanner.v1.transaction_pb2 import ( + from google.cloud.spanner_v1.proto.transaction_pb2 import ( Transaction as TransactionPB) transaction_pb = TransactionPB(id=self.TRANSACTION_ID) @@ -279,8 +279,8 @@ def test_commit_w_gax_error(self): def test_commit_ok(self): import datetime - from google.cloud.proto.spanner.v1.spanner_pb2 import CommitResponse - from google.cloud.spanner.keyset import KeySet + from google.cloud.spanner_v1.proto.spanner_pb2 import CommitResponse + from google.cloud.spanner_v1.keyset import KeySet from google.cloud._helpers import UTC from google.cloud._helpers import _datetime_to_pb_timestamp @@ -311,8 +311,8 @@ def test_commit_ok(self): def test_context_mgr_success(self): import datetime - from google.cloud.proto.spanner.v1.spanner_pb2 import CommitResponse - from google.cloud.proto.spanner.v1.transaction_pb2 import ( + from google.cloud.spanner_v1.proto.spanner_pb2 import CommitResponse + from google.cloud.spanner_v1.proto.transaction_pb2 import ( Transaction as TransactionPB) from google.cloud._helpers import UTC from google.cloud._helpers import _datetime_to_pb_timestamp @@ -344,7 +344,7 @@ def test_context_mgr_success(self): def test_context_mgr_failure(self): from google.protobuf.empty_pb2 import Empty empty_pb = Empty() - from google.cloud.proto.spanner.v1.transaction_pb2 import ( + from google.cloud.spanner_v1.proto.transaction_pb2 import ( Transaction as TransactionPB) transaction_pb = TransactionPB(id=self.TRANSACTION_ID)