-
Notifications
You must be signed in to change notification settings - Fork 44
/
snippets.py
260 lines (201 loc) · 8.55 KB
/
snippets.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
# Copyright 2022 Google, Inc.
# 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.
import argparse
from datetime import datetime, timedelta, timezone
from pprint import pprint
import time
from google.cloud import datastore # noqa: I100
def _preamble():
# [START datastore_size_coloration_query]
from google.cloud import datastore
# For help authenticating your client, visit
# https://cloud.google.com/docs/authentication/getting-started
client = datastore.Client()
# [END datastore_size_coloration_query]
assert client is not None
def in_query(client):
# [START datastore_in_query]
query = client.query(kind="Task")
query.add_filter("tag", "IN", ["learn", "study"])
# [END datastore_in_query]
return list(query.fetch())
def not_equals_query(client):
# [START datastore_not_equals_query]
query = client.query(kind="Task")
query.add_filter("category", "!=", "work")
# [END datastore_not_equals_query]
return list(query.fetch())
def not_in_query(client):
# [START datastore_not_in_query]
query = client.query(kind="Task")
query.add_filter("category", "NOT_IN", ["work", "chores", "school"])
# [END datastore_not_in_query]
return list(query.fetch())
def query_with_readtime(client):
# [START datastore_stale_read]
# Create a read time of 15 seconds in the past
read_time = datetime.now(timezone.utc) - timedelta(seconds=15)
# Fetch an entity with read_time
task_key = client.key("Task", "sampletask")
entity = client.get(task_key, read_time=read_time)
# Query Task entities with read_time
query = client.query(kind="Task")
tasks = query.fetch(read_time=read_time, limit=10)
# [END datastore_stale_read]
results = list(tasks)
results.append(entity)
return results
def count_query_in_transaction(client):
# [START datastore_count_in_transaction]
task1 = datastore.Entity(client.key("Task", "task1"))
task2 = datastore.Entity(client.key("Task", "task2"))
task1["owner"] = "john"
task2["owner"] = "john"
tasks = [task1, task2]
client.put_multi(tasks)
with client.transaction() as transaction:
tasks_of_john = client.query(kind="Task")
tasks_of_john.add_filter("owner", "=", "john")
total_tasks_query = client.aggregation_query(tasks_of_john)
query_result = total_tasks_query.count(alias="tasks_count").fetch()
for task_result in query_result:
tasks_count = task_result[0]
if tasks_count.value < 2:
task3 = datastore.Entity(client.key("Task", "task3"))
task3["owner"] = "john"
transaction.put(task3)
tasks.append(task3)
else:
print(f"Found existing {tasks_count.value} tasks, rolling back")
client.entities_to_delete.extend(tasks)
raise Exception("User 'John' cannot have more than 2 tasks")
# [END datastore_count_in_transaction]
def count_query_on_kind(client):
# [START datastore_count_on_kind]
task1 = datastore.Entity(client.key("Task", "task1"))
task2 = datastore.Entity(client.key("Task", "task2"))
tasks = [task1, task2]
client.put_multi(tasks)
all_tasks_query = client.query(kind="Task")
all_tasks_count_query = client.aggregation_query(all_tasks_query).count()
query_result = all_tasks_count_query.fetch()
for aggregation_results in query_result:
for aggregation in aggregation_results:
print(f"Total tasks (accessible from default alias) is {aggregation.value}")
# [END datastore_count_on_kind]
return tasks
def count_query_with_limit(client):
# [START datastore_count_with_limit]
task1 = datastore.Entity(client.key("Task", "task1"))
task2 = datastore.Entity(client.key("Task", "task2"))
task3 = datastore.Entity(client.key("Task", "task3"))
tasks = [task1, task2, task3]
client.put_multi(tasks)
all_tasks_query = client.query(kind="Task")
all_tasks_count_query = client.aggregation_query(all_tasks_query).count()
query_result = all_tasks_count_query.fetch(limit=2)
for aggregation_results in query_result:
for aggregation in aggregation_results:
print(f"We have at least {aggregation.value} tasks")
# [END datastore_count_with_limit]
return tasks
def count_query_property_filter(client):
# [START datastore_count_with_property_filter]
task1 = datastore.Entity(client.key("Task", "task1"))
task2 = datastore.Entity(client.key("Task", "task2"))
task3 = datastore.Entity(client.key("Task", "task3"))
task1["done"] = True
task2["done"] = False
task3["done"] = True
tasks = [task1, task2, task3]
client.put_multi(tasks)
completed_tasks = client.query(kind="Task").add_filter("done", "=", True)
remaining_tasks = client.query(kind="Task").add_filter("done", "=", False)
completed_tasks_query = client.aggregation_query(query=completed_tasks).count(
alias="total_completed_count"
)
remaining_tasks_query = client.aggregation_query(query=remaining_tasks).count(
alias="total_remaining_count"
)
completed_query_result = completed_tasks_query.fetch()
for aggregation_results in completed_query_result:
for aggregation_result in aggregation_results:
if aggregation_result.alias == "total_completed_count":
print(f"Total completed tasks count is {aggregation_result.value}")
remaining_query_result = remaining_tasks_query.fetch()
for aggregation_results in remaining_query_result:
for aggregation_result in aggregation_results:
if aggregation_result.alias == "total_remaining_count":
print(f"Total remaining tasks count is {aggregation_result.value}")
# [END datastore_count_with_property_filter]
return tasks
def count_query_with_stale_read(client):
tasks = [task for task in client.query(kind="Task").fetch()]
client.delete_multi(tasks) # ensure the database is empty before starting
# [START datastore_count_query_with_stale_read]
task1 = datastore.Entity(client.key("Task", "task1"))
task2 = datastore.Entity(client.key("Task", "task2"))
# Saving two tasks
task1["done"] = True
task2["done"] = False
client.put_multi([task1, task2])
time.sleep(10)
past_timestamp = datetime.now(
timezone.utc
) # we have two tasks in database at this time.
time.sleep(10)
# Saving third task
task3 = datastore.Entity(client.key("Task", "task3"))
task3["done"] = False
client.put(task3)
all_tasks = client.query(kind="Task")
all_tasks_count = client.aggregation_query(
query=all_tasks,
).count(alias="all_tasks_count")
# Executing aggregation query
query_result = all_tasks_count.fetch()
for aggregation_results in query_result:
for aggregation_result in aggregation_results:
print(f"Latest tasks count is {aggregation_result.value}")
# Executing aggregation query with past timestamp
tasks_in_past = client.aggregation_query(query=all_tasks).count(
alias="tasks_in_past"
)
tasks_in_the_past_query_result = tasks_in_past.fetch(read_time=past_timestamp)
for aggregation_results in tasks_in_the_past_query_result:
for aggregation_result in aggregation_results:
print(f"Stale tasks count is {aggregation_result.value}")
# [END datastore_count_query_with_stale_read]
return [task1, task2, task3]
def main(project_id):
client = datastore.Client(project_id)
for name, function in globals().items():
if name in (
"main",
"_preamble",
"defaultdict",
"datetime",
"timezone",
"timedelta",
) or not callable(function):
continue
print(name)
pprint(function(client))
print("\n-----------------\n")
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description="Demonstrates datastore API operations."
)
parser.add_argument("project_id", help="Your cloud project ID.")
args = parser.parse_args()
main(args.project_id)