2 # Cookbook Name:: mysql
3 # Provider:: 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 # http://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.
22 def load_current_resource
23 @mysql = Chef::MySQL.new
25 @current_resource = Chef::Resource::MysqlDatabase.new(new_resource.name)
26 @current_resource.database(new_resource.database)
27 if (mysql_database = @mysql.databases[@current_resource.database])
28 @current_resource.permissions(mysql_database[:permissions])
34 unless @mysql.databases.include?(new_resource.database)
35 converge_by("create #{new_resource}") do
36 Chef::Log.info("Creating #{new_resource}")
37 @mysql.execute(:command => "CREATE DATABASE `#{new_resource.database}`")
41 new_permissions = Hash[new_resource.permissions.collect do |user, privileges|
42 [@mysql.canonicalise_user(user), privileges]
45 @current_resource.permissions.each_key do |user|
46 next if new_permissions[user]
48 converge_by("revoke all for #{user} on #{new_resource}") do
49 Chef::Log.info("Revoking all for #{user} on #{new_resource}")
50 @mysql.execute(:command => "REVOKE ALL ON `#{new_resource.database}`.* FROM #{user}")
54 new_permissions.each do |user, new_privileges|
55 current_privileges = @current_resource.permissions[user] || {}
56 new_privileges = Array(new_privileges)
58 if new_privileges.include?(:all)
59 new_privileges |= (Chef::MySQL::DATABASE_PRIVILEGES - [:grant])
62 Chef::MySQL::DATABASE_PRIVILEGES.each do |privilege|
63 if new_privileges.include?(privilege)
64 unless current_privileges.include?(privilege)
65 converge_by("grant #{privilege} for #{user} on mysql database #{new_resource}") do
66 Chef::Log.info("Granting #{privilege} for #{user} on mysql database #{new_resource}")
67 @mysql.execute(:command => "GRANT #{@mysql.privilege_name(privilege)} ON `#{new_resource.database}`.* TO #{user}")
70 elsif current_privileges.include?(privilege)
71 converge_by("revoke #{privilege} for #{user} on #{new_resource}") do
72 Chef::Log.info("Revoking #{privilege} for #{user} on #{new_resource}")
73 @mysql.execute(:command => "REVOKE #{@mysql.privilege_name(privilege)} ON `#{new_resource.database}`.* FROM #{user}")
81 if @mysql.databases.include?(new_resource.database)
82 converge_by("drop #{new_resource}") do
83 Chef::Log.info("Dropping #{new_resource}")
84 @mysql.execute(:command => "DROP DATABASE `#{new_resource.database}`")