Skip to content

Commit 4ef793c

Browse files
AlisskaPiec24tAVaksmanIlya Gurovlarkee
authored
feat: autocommit sample (#172)
* feat: autocommit sample * remove unused imports * Remove samples/samples init * No package-relative imports in samples * fix check errors, rename test file * move ResultsChecksum() to test * use connection.Cursor in patch * Apply suggestions from code review Co-authored-by: Chris Kleinknecht <[email protected]> * Update samples/samples/autocommit_test.py Co-authored-by: Chris Kleinknecht <[email protected]> * lint fix Co-authored-by: Chris Kleinknecht <[email protected]> Co-authored-by: Alex <[email protected]> Co-authored-by: Ilya Gurov <[email protected]> Co-authored-by: larkee <[email protected]>
1 parent 9b8d472 commit 4ef793c

File tree

2 files changed

+126
-0
lines changed

2 files changed

+126
-0
lines changed

samples/samples/autocommit.py

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
# Copyright 2020 Google LLC
2+
#
3+
# Use of this source code is governed by a BSD-style
4+
# license that can be found in the LICENSE file or at
5+
# https://developers.google.com/open-source/licenses/bsd
6+
7+
import argparse
8+
9+
from google.cloud.spanner_dbapi import connect
10+
11+
12+
def enable_autocommit_mode(instance_id, database_id):
13+
"""Enables autocommit mode."""
14+
# [START spanner_enable_autocommit_mode]
15+
16+
connection = connect(instance_id, database_id)
17+
connection.autocommit = True
18+
print("Autocommit mode is enabled.")
19+
20+
cursor = connection.cursor()
21+
22+
cursor.execute(
23+
"""CREATE TABLE Singers (
24+
SingerId INT64 NOT NULL,
25+
FirstName STRING(1024),
26+
LastName STRING(1024),
27+
SingerInfo BYTES(MAX)
28+
) PRIMARY KEY (SingerId)"""
29+
)
30+
31+
cursor.execute(
32+
"""INSERT INTO Singers (SingerId, FirstName, LastName) VALUES
33+
(12, 'Melissa', 'Garcia'),
34+
(13, 'Russell', 'Morales'),
35+
(14, 'Jacqueline', 'Long'),
36+
(15, 'Dylan', 'Shaw')"""
37+
)
38+
39+
cursor.execute("""SELECT * FROM Singers WHERE SingerId = 13""")
40+
41+
print("SingerId: {}, AlbumId: {}, AlbumTitle: {}".format(*cursor.fetchone()))
42+
43+
connection.close()
44+
# [END spanner_enable_autocommit_mode]
45+
46+
47+
if __name__ == "__main__":
48+
parser = argparse.ArgumentParser(
49+
description=__doc__,
50+
formatter_class=argparse.RawDescriptionHelpFormatter,
51+
)
52+
parser.add_argument("instance_id", help="Your Cloud Spanner instance ID.")
53+
parser.add_argument(
54+
"--database-id",
55+
help="Your Cloud Spanner database ID.",
56+
default="example_db",
57+
)
58+
subparsers = parser.add_subparsers(dest="command")
59+
subparsers.add_parser("enable_autocommit_mode", help=enable_autocommit_mode.__doc__)
60+
args = parser.parse_args()
61+
if args.command == "enable_autocommit_mode":
62+
enable_autocommit_mode(args.instance_id, args.database_id)
63+
else:
64+
print(f"Command {args.command} did not match expected commands.")

samples/samples/autocommit_test.py

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
# Copyright 2020 Google LLC
2+
#
3+
# Use of this source code is governed by a BSD-style
4+
# license that can be found in the LICENSE file or at
5+
# https://developers.google.com/open-source/licenses/bsd
6+
7+
import uuid
8+
9+
from google.cloud import spanner
10+
from google.cloud.spanner_dbapi import connect
11+
import mock
12+
import pytest
13+
14+
import autocommit
15+
16+
17+
def unique_instance_id():
18+
"""Creates a unique id for the database."""
19+
return f"test-instance-{uuid.uuid4().hex[:10]}"
20+
21+
22+
def unique_database_id():
23+
"""Creates a unique id for the database."""
24+
return f"test-db-{uuid.uuid4().hex[:10]}"
25+
26+
27+
INSTANCE_ID = unique_instance_id()
28+
DATABASE_ID = unique_database_id()
29+
30+
31+
@pytest.fixture(scope="module")
32+
def spanner_instance():
33+
spanner_client = spanner.Client()
34+
config_name = f"{spanner_client.project_name}/instanceConfigs/regional-us-central1"
35+
36+
instance = spanner_client.instance(INSTANCE_ID, config_name)
37+
op = instance.create()
38+
op.result(120) # block until completion
39+
yield instance
40+
instance.delete()
41+
42+
43+
@pytest.fixture(scope="module")
44+
def database(spanner_instance):
45+
"""Creates a temporary database that is removed after testing."""
46+
db = spanner_instance.database(DATABASE_ID)
47+
db.create()
48+
yield db
49+
db.drop()
50+
51+
52+
def test_enable_autocommit_mode(capsys, database):
53+
connection = connect(INSTANCE_ID, DATABASE_ID)
54+
cursor = connection.cursor()
55+
56+
with mock.patch(
57+
"google.cloud.spanner_dbapi.connection.Cursor", return_value=cursor,
58+
):
59+
autocommit.enable_autocommit_mode(INSTANCE_ID, DATABASE_ID)
60+
out, _ = capsys.readouterr()
61+
assert "Autocommit mode is enabled." in out
62+
assert "SingerId: 13, AlbumId: Russell, AlbumTitle: Morales" in out

0 commit comments

Comments
 (0)