-
Notifications
You must be signed in to change notification settings - Fork 33
/
Copy pathapplication.rb
86 lines (71 loc) · 2.75 KB
/
application.rb
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
# Copyright 2025 Google LLC
#
# Use of this source code is governed by an MIT-style
# license that can be found in the LICENSE file or at
# https://opensource.org/licenses/MIT.
require "io/console"
require_relative "../config/environment"
require_relative "models/singer"
require_relative "models/album"
class Application
def self.run
# Create a new singer.
singer = create_new_singer
# Create a new album.
album = create_new_album singer
# Verify that the album exists.
find_album singer.singerid, album.albumid
# List all singers, albums and tracks.
list_singers_albums
# Create a new singer using mutations.
# This requires us to set a primary key value manually.
# You can also instruct the Spanner Ruby ActiveRecord provider to that automatically
# by including this in your database configuration:
# use_client_side_id_for_mutations: true
create_new_singer_using_mutations
end
def self.find_album singerid, albumid
album = Album.find [singerid, albumid]
puts "Found album: #{album.title}"
end
def self.list_singers_albums
puts ""
puts "Listing all singers with corresponding albums"
Singer.all.order("last_name, first_name").each do |singer|
puts "#{singer.first_name} #{singer.last_name} has #{singer.albums.count} albums:"
singer.albums.order("title").each do |album|
puts " #{album.title}"
end
end
end
def self.create_new_singer
# Create a new singer. The singerid is generated by an IDENTITY column in the database and returned.
puts ""
singer = Singer.create first_name: "Melissa", last_name: "Garcia"
puts "Created a new singer '#{singer.first_name} #{singer.last_name}' with id #{singer.singerid}"
singer
end
def self.create_new_album singer
# Create a new album.
puts ""
puts "Creating a new album for #{singer.first_name} #{singer.last_name}"
# The albumid is not generated by the database.
album = singer.albums.build albumid: 1, title: "New Title"
album.save!
album
end
def self.create_new_singer_using_mutations
# Create a new singer using mutations. Mutations do not support THEN RETURN clauses,
# so we must specify a value for the primary key before inserting the row.
puts ""
singer = nil
ActiveRecord::Base.transaction isolation: :buffered_mutations do
# Assign the singer a random id value. This value will be included in the insert mutation.
singer = Singer.create id: SecureRandom.uuid.gsub("-", "").hex & 0x7FFFFFFFFFFFFFFF,
first_name: "Melissa", last_name: "Garcia"
end
puts "Inserted a new singer '#{singer.first_name} #{singer.last_name}' using mutations with id #{singer.singerid}"
singer
end
end
Application.run