2 # Cookbook Name:: mysql
3 # Resource:: mysql_database
5 # Copyright 2013, OpenStreetMap Foundation
7 # Licensed under the Apache License, Version 2.0 (the "License");
8 # you may not use this file except in compliance with the License.
9 # You may obtain a copy of the License at
11 # https://www.apache.org/licenses/LICENSE-2.0
13 # Unless required by applicable law or agreed to in writing, software
14 # distributed under the License is distributed on an "AS IS" BASIS,
15 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 # See the License for the specific language governing permissions and
17 # limitations under the License.
20 default_action :create
22 property :database, :kind_of => String, :name_attribute => true
23 property :permissions, :kind_of => Hash, :default => {}
26 unless mysql_databases.include?(new_resource.database)
27 converge_by("create #{new_resource}") do
28 Chef::Log.info("Creating #{new_resource}")
29 mysql_execute(:command => "CREATE DATABASE `#{new_resource.database}`")
33 current_permissions = mysql_databases[new_resource.database]&.dig(:permissions) || {}
35 new_permissions = Hash[new_resource.permissions.collect do |user, privileges|
36 [mysql_canonicalise_user(user), privileges]
39 current_permissions.each_key do |user|
40 next if new_permissions[user]
42 converge_by("revoke all for #{user} on #{new_resource}") do
43 Chef::Log.info("Revoking all for #{user} on #{new_resource}")
44 mysql_execute(:command => "REVOKE ALL ON `#{new_resource.database}`.* FROM #{user}")
48 new_permissions.each do |user, new_privileges|
49 current_privileges = current_permissions[user] || {}
50 new_privileges = Array(new_privileges)
52 if new_privileges.include?(:all)
53 new_privileges |= (OpenStreetMap::MySQL::DATABASE_PRIVILEGES - [:grant])
56 OpenStreetMap::MySQL::DATABASE_PRIVILEGES.each do |privilege|
57 if new_privileges.include?(privilege)
58 unless current_privileges.include?(privilege)
59 converge_by("grant #{privilege} for #{user} on mysql database #{new_resource}") do
60 Chef::Log.info("Granting #{privilege} for #{user} on mysql database #{new_resource}")
61 mysql_execute(:command => "GRANT #{mysql_privilege_name(privilege)} ON `#{new_resource.database}`.* TO #{user}")
64 elsif current_privileges.include?(privilege)
65 converge_by("revoke #{privilege} for #{user} on #{new_resource}") do
66 Chef::Log.info("Revoking #{privilege} for #{user} on #{new_resource}")
67 mysql_execute(:command => "REVOKE #{mysql_privilege_name(privilege)} ON `#{new_resource.database}`.* FROM #{user}")
75 if mysql_databases.include?(new_resource.database)
76 converge_by("drop #{new_resource}") do
77 Chef::Log.info("Dropping #{new_resource}")
78 mysql_execute(:command => "DROP DATABASE `#{new_resource.database}`")
84 include OpenStreetMap::MySQL