Mysqldump got error 1449 the user specified as a definer

Restoring MySQL dump ERROR 1449 I took hot backup (dump) from my Master MySQL DB with below command mysqldump -uroot -p —skip-lock-tables —single-transaction —flush-logs —hex-blob —master-data=2 -A > Master Version: MySQL-server-5.5.41-1.el6.x86_64 At the time of restoration on slave we are getting this error, have I done something wrong. ]$ mysql -u root -p user_table_dump.sql […]

Содержание

  1. Restoring MySQL dump ERROR 1449
  2. 2 Answers 2
  3. A SysAdmin’s NoteBook
  4. Subscribe to Blog via Email
  5. Recent Posts
  6. Recent Comments
  7. Archives
  8. mysqldump: Got error: 1449: The user specified as a definer (‘user’@’%’) does not exist when using LOCK TABLES
  9. MySQL:The user specified as a definer does not exist (error 1449)-Solutions
  10. Solution: 1
  11. Solution: 2
  12. Solution: 3
  13. Ошибка MySQL 1449: пользователь, указанный как определитель, не существует
  14. ОТВЕТЫ
  15. Ответ 1
  16. 1. Измените DEFINER
  17. Как изменить определитель для представлений
  18. Как изменить определитель для хранимых процедур
  19. 2. Создайте отсутствующего пользователя
  20. Ответ 2
  21. Ответ 3
  22. Ответ 4
  23. Ответ 5
  24. Ответ 6
  25. Ответ 7
  26. Ответ 8
  27. Ответ 9
  28. Ответ 10
  29. Ответ 11
  30. Ответ 12
  31. Ответ 13
  32. Ответ 14
  33. Ответ 15
  34. Ответ 16
  35. Ответ 17
  36. Ответ 18
  37. Ответ 19
  38. Ответ 20
  39. Ответ 21
  40. Ответ 22
  41. Ответ 23
  42. Ответ 24
  43. Ответ 25
  44. Ответ 26
  45. Ответ 27
  46. Ответ 28
  47. Ответ 29
  48. Ответ 30

Restoring MySQL dump ERROR 1449

I took hot backup (dump) from my Master MySQL DB with below command

mysqldump -uroot -p —skip-lock-tables —single-transaction —flush-logs —hex-blob —master-data=2 -A >

Master Version: MySQL-server-5.5.41-1.el6.x86_64

At the time of restoration on slave we are getting this error, have I done something wrong.

]$ mysql -u root -p user_table_dump.sql

2 Answers 2

I tried to solve this in many ways but, didn’t find any workaround. then I tried to redo the whole thing again with the below steps.

I took a backup of mysql user from Master Host,

mysqldump -u root -p mysql user > user_table_dump.sql

and restored mysql user on slave,

Apparently this is an old question, but still came up top in Google search. I was facing this exact same issue before, and the looks like previous answer by Mongrel works. However, when I reinstalled my computer, I have made a dump using mysqldump —all-databases , and this error 1449 inadvertently came up, and extracting mysql database only from the formatted drive is almost certainly impossible.

So, I finally came up with a «manual» solution by editing the .sql dump: Move the restore statements of mysql database up top. Now on very long dumps (GBs size) this is error prone. So,

  1. fire up your trusted text editor (I trust vim for stuffs like this, VS Code crawls like no progress opening GB size files)
  2. search for Current Database: mysql comment / marker.
  3. select the text from that point up to the next Current Database: comment/marker.
  4. Cut it, put it before the first Current Database comment/marker.

Afterwards, I saved the modified dump, and now the dump restores without error.

Источник

A SysAdmin’s NoteBook

Subscribe to Blog via Email

Recent Posts

  • Captain Kill on Got permission denied while trying to connect to the Docker daemon socket at unix:///var/run/docker.sock: Get http://%2Fvar%2Frun%2Fdocker.sock/v1.39/containers/nginx/json: dial unix /var/run/docker.sock: connect: permission denied
  • Charles Lindsey on X-Ham-Report in Cpanel
  • Securing Solr Admin Console on Install solr with jetty in Ubuntu
  • Securing Solr Admin Console on Installing Jetty in Ubuntu 14.04
  • Install solr with jetty in Ubuntu on Installing Jetty in Ubuntu 14.04

Archives

mysqldump: Got error: 1449: The user specified as a definer (‘user’@’%’) does not exist when using LOCK TABLES

I came across this error while taking the database dump of a database. The database was originally created in another server and transferred to my server after long. When I tried to take a database dump as a part of my backup script, I came across this error.

mysqldump: Got error: 1449: The user specified as a definer (‘edulanche’@’%’) does not exist when using LOCK TABLES

Basically this error is caused by a definer which was created in the previous server but is not present in the new server. The easiest way to get past this error is to go to the original dump file and search for ‘definer’ in it.

/*!50013 DEFINER=`user`@`%` SQL SECURITY DEFINER */

If found, modify it to reflect the root user or database user in your new server.

/*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */

I also removed the database which was already restored and recreated it, just to be sure everything starts afresh.

Источник

MySQL:The user specified as a definer does not exist (error 1449)-Solutions

The self-explanatory error that led this post is:
MySQL error 1449: The user specified as a definer does not exist.
I wrote about DEFINER & INVOKER SQL SECURITY in MySQL long back in early 2012 which covers the explanation of how they work WRT stored routines in MySQL!

Here I’ll try to extend it little more with examples for the error and provide 3 solutions.

We will create a simple procedure to return count from table ‘a’ of database ‘test’ and a specific user as a DEFINER.

Alright the procedure call above worked fine as expected.
Now let’s create a trouble! Let’s drop a user and try to see what do we get here.

Hmmm… This is the error I wanted to point & explain. I encourage you to refer the DEFINER & INVOKER in SQL SECURITY explained in my previous article and ofcourse MySQL documentation is a bible.

Well so as the error says it is expecting a user which is not present. So the easy way out here is to create the dropped user, reload privileges and make a call.

Solution: 1

Though we might not want to get into troubles at first! So how can we avoid from getting in to this situation?

The answer is using “SQL SECURITY” defined as “INVOKER”. SQL SECURITY here defines that the procedure will run under the INVOKER’s privileges. (Default is DEFINER)
Specifying INVOKER we are free from the dependency of DEFINER user.

Let’s test as follows:
– Create procedure with SQL SECURITY specified as INVOKER.
– Drop definer user
– call the procedure and…

Solution: 2

Hmmm so this look good! No error & stored procedure works well…even if we lost the user who created the procedure!
But there is an obvious understanding that the SQL SECURITY INVOKER clause may behave differently depending on privileges of the user who calls it.

Alright, finally I’ll add one more way to resolve the error: “MySQL error 1449: The user specified as a definer does not exist”
The stored procedure or say MySQL routines are stored in mysql.proc table which also reflects in information_schema.ROUTINES table.
One can directly update the mysql.proc table’s DEFINER column to replace deleted user with existing user. Let’s do that.

Solution: 3

Conclusion: The error “Definer does not exist” can be resolved by atleast 3 ways:
– Create the DEFINER (user).
– Change the DEFINER by updating mysql.proc.
– Bring in the INVOKER (with caution).

Well as such we updated DEFINER column in mysql.proc table to avoid user creation.
Do you see a possibility of 4th solution to update security_type column of mysql.proc to INVOKER? See if that works! 🙂

References:
1. http://dev.mysql.com/doc/refman/5.0/en/stored-programs-security.html
2. http://kedar.nitty-witty.com/blog/access-control-in-mysql-stored-routines-by-example-definer-invoker-sql-security

Update:
Why “flush tables” commands are “strikethrough-ed” –> because they’re not required & they better stay to convey the same message of what Jaime wrote to pass-on.

Источник

Ошибка MySQL 1449: пользователь, указанный как определитель, не существует

Когда я запускаю следующий запрос, я получаю сообщение об ошибке:

Сообщение об ошибке:

Почему я получаю эту ошибку? Как это исправить?

ОТВЕТЫ

Ответ 1

Это обычно происходит при экспорте представлений/триггеров/процедур из одной базы данных или сервера в другой, поскольку пользователь, создавший этот объект, больше не существует.

У вас есть два варианта:

1. Измените DEFINER

Это, возможно, проще всего сделать при первоначальном импорте объектов базы данных, удалив любые операторы DEFINER из дампа.

Изменение определителя позже является более сложным:

Как изменить определитель для представлений

Запустите этот SQL для генерации необходимых операторов ALTER

Скопируйте и запустите инструкции ALTER

Как изменить определитель для хранимых процедур

Будьте осторожны, потому что это изменит все определители для всех баз данных.

2. Создайте отсутствующего пользователя

Если вы обнаружили следующую ошибку при использовании базы данных MySQL:

Тогда вы можете решить это, используя следующее:

Это работало как шарм — вам нужно только изменить someuser на имя пропавшего пользователя. На локальном сервере-разработчике обычно можно использовать root .

Также рассмотрите вопрос о том, действительно ли вам нужно предоставить разрешения пользователя ALL или они могут сделать меньше.

Ответ 2

Пользователь, который изначально создал представление или процедуру SQL, был удален. Если вы воссоздаете этого пользователя, он должен устранить вашу ошибку.

Ответ 3

Я получил ту же ошибку после обновления mysql.

Ошибка была исправлена после этой команды:

mysql_upgrade должен выполняться каждый раз при обновлении MySQL. Он проверяет все таблицы во всех базах данных на предмет несовместимости с текущей версией MySQL Server. Если найденная таблица имеет возможную несовместимость, она проверяется. Если обнаружены какие-либо проблемы, таблица будет восстановлена. mysql_upgrade также обновляет системные таблицы, чтобы вы могли использовать новые привилегии или возможности, которые могли быть добавлены.

Ответ 4

Если пользователь существует, то:

Ответ 5

Создайте удаляемого пользователя следующим образом:

Ответ 6

Выполните следующие действия:

  • Перейдите в PHPMyAdmin
  • Выберите свою базу данных
  • Выберите таблицу
  • В верхнем меню Нажмите «Триггеры»
  • Нажмите «Изменить», чтобы изменить триггер
  • Измените определитель с [user @localhost] на root @localhost

Надеюсь, что это поможет

Ответ 7

Решение — это всего лишь однострочный запрос, как показано ниже:

Замените ROOT своим именем пользователя mysql. Замените PASSWORD своим паролем mysql.

Ответ 8

Для будущих googlers: у меня есть аналогичное сообщение, пытающееся обновить таблицу в базе данных, которая не содержит представлений. После некоторого копания оказалось, что я импортировал триггеры на эту таблицу, и это были вещи, определенные несуществующим пользователем. Сбрасывание триггеров решило проблему.

Ответ 9

Исправлено, выполнив следующие комментарии.

если вы получаете some_other вместо web2vi , тогда вы должны соответствующим образом изменить имя.

Ответ 10

быстро исправить работу и выгрузить файл:

Ответ 11

Пользователь ‘web2vi’ не существует на вашем сервере mysql.

Если этот пользователь существует, проверьте, на каких серверах он может получить доступ, хотя я бы подумал, что это будет другая ошибка (например, у вас может быть web2vi @localhost, но вы получаете доступ к db как web2vi @% (во что угодно )

Ответ 12

У меня была такая же проблема с пользователем root, и он работал у меня, когда я заменил

Итак, если пользователю ‘web2vi’ разрешено подключаться из ‘localhost’, вы можете попробовать:

Я подключен удаленно к базе данных.

Ответ 13

Ответ 14

Это случилось со мной после перемещения БД с одного сервера на другой. Первоначально определитель использовал localhost и пользователя. На новом сервере у нас нет этого пользователя, и хост также был изменен. Я сделал резервную копию этой конкретной таблицы и вручную удалил все триггеры из phpmyadmin. После этого он работал нормально для меня.

Ответ 15

У меня была такая же ошибка, когда я пытался выбрать из представления.

Однако проблема заключается в том, что это представление, выбранное из другого представления, которое было восстановлено из резервной копии с другого сервера.

и на самом деле, ДА, пользователь был недействителен, но не был очевиден с первого взгляда.

Ответ 16

Попробуйте установить процедуру как SECURITY INVOKER

Mysql default устанавливает безопасность процедур как «DEFINER» (CREATOR OF).. вы должны установить защиту для «invoker».

Ответ 17

У меня была одна и та же проблема минут назад, я столкнулся с этой проблемой после того, как удалил неиспользуемого пользователя из таблицы mysql.user, но вместо этого изменил его вид, вот удобная команда, которая делает ее очень простой:

Смешайте это с командной строкой mysql (предполагая * nix, не знакомый с окнами):

Примечание: команда генерирует и добавляет SELECT CONCAT в файл, делая mysql -uuser -ppass databasename сбой, если вы не удалите его.

Ответ 18

Ваше мнение, «view_quotes», возможно, было скопировано из другой базы данных, где «web2vi» является допустимым пользователем в базе данных, где «web2vi» не является допустимым пользователем.
Либо добавьте пользователя «web2vi» в базу данных, либо измените представление (обычно удаление части DEFINER = ‘web2vi’ @’%’ и выполнение script сделает трюк)

Ответ 19

В моем случае таблица имела триггер с пользователем DEFINER, которого не было.

Ответ 20

Проблема понятна — MySQL не может найти пользователя, заданного в качестве определителя.

Я столкнулся с этой проблемой после синхронизации модели базы данных с сервера разработки, применения ее к localhost, внесения изменений в модель и последующего повторного использования ее на localhost. По-видимому, было определено представление (я изменил), и поэтому я не смог обновить локальную версию.

Как исправить (легко) :

Примечание: он включает удаление, поэтому он отлично подходит для представлений, но убедитесь, что у вас есть резервная копия данных, если вы попробуете это в таблицах.

  • Войдите в базу данных как пользователь root (или все, что имеет достаточную мощность для внесения изменений).
  • Удалить представление, таблицу или все, с чем вы столкнулись.
  • Синхронизируйте свою новую модель — она ​​не будет жаловаться на то, чего не существует сейчас. Вы можете удалить часть SQL SECURITY DEFINER из определения элемента, с которым у вас были проблемы.

P.S. Это не является ни правильным, ни лучшим решением. Я просто разместил его как возможное (и очень простое) решение.

Ответ 21

Вы можете попробовать следующее:

Ответ 22

Почему я получаю эту ошибку? Как это исправить?

Я потратил час до того, как нашел решение для такой проблемы. Но в моем случае я запустил это:

Если вы действительно хотите найти проблему, просто запустите следующие команды:

. и после каждого из них найдите поле «определитель».

В моем случае это был бородатый старый триггер, который кто-то из разработчиков забыл удалить.

Ответ 23

В предложениях DEFINER и SQL SECURITY указан контекст безопасности, который будет использоваться при проверке прав доступа во время вызова представления.

Этот пользователь должен существовать и всегда лучше использовать «localhost» в качестве имени хоста. Поэтому я думаю, что если вы проверите, что пользователь существует и измените его на «localhost» при создании представления, у вас не будет этой ошибки.

Ответ 24

Перейдите в раздел подпрограммы редактирования, а внизу измените тип безопасности с Definer на Invoker.

Ответ 25

Один или несколько видов, созданных/зарегистрированных другим пользователем. Вам нужно будет проверить владельца представления и:

  • Восстановить пользователя; как говорят другие ответы. или
  • Создайте представления, созданные пользователем ‘web2vi’ , используя ALTER VIEW

У меня была эта проблема.

Я пытался перенести представления из BD1 в BD2, используя SQLYog. SQLYog воссоздал представления в другой базе данных (DB2), но он сохранил пользователя BD1 (они разные). Позже я понял, что представления, которые я использовал в моем запросе, имели ту же ошибку, что и вы, даже когда я не создавал никакого представления.

Надеюсь на эту помощь.

Ответ 26

Если это хранимая процедура, вы можете сделать:

Но это не рекомендуется.

Для меня лучшим решением является создание определителя:

Ответ 27

когда mysql.proc пуст, но система всегда замечает «[email protected]%» для имени таблицы, нет, вы просто root в командной строке mysql и введите:

Ответ 28

Это произошло со мной после того, как я импортировал дамп в Windows 10 с MySQL Workbench 6.3 Community, а «root @% не существует». Хотя пользователь существовал. Сначала я попытался прокомментировать DEFINER, но это не сработало. Затем я заменил строку «root @%» на «root @localhost» и повторно импортировал дамп. Это сделало трюк для меня.

Ответ 29

Пользователь базы данных также, похоже, чувствителен к регистру, поэтому, когда у меня был пользователь root @@%, у меня не было пользователя ROOT ‘@’%. Я изменил пользователя на верхний регистр с помощью инструментария, и проблема была решена!

Ответ 30

в моем случае у меня был триггер в этой таблице, что я не мог обновлять данные, получая ту же ошибку.

Ошибка MySQL 1449: пользователь, указанный как определитель, не существует

решение заключалось в том, чтобы удалить триггеры в этой таблице и снова создать их снова, это устранило проблему, поскольку триггер был сделан с другим пользователем с другого сервера, а имя пользователя изменилось на новом сервере после изменения компании-хостинга. что мои 2 цента

Источник

Error Description:

When we run the following query, we get an error:

SELECT
  `a`.`sl_id`                     AS `sl_id`,
  `a`.`quote_id`                  AS `quote_id`,
  `a`.`sl_date`                   AS `sl_date`,
  `a`.`sl_type`                   AS `sl_type`,
  `a`.`sl_status`                 AS `sl_status`,
  `b`.`client_id`                 AS `client_id`,
  `b`.`business`                  AS `business`,
  `b`.`affaire_type`              AS `affaire_type`,
  `b`.`quotation_date`            AS `quotation_date`,
  `b`.`total_sale_price_with_tax` AS `total_sale_price_with_tax`,
  `b`.`STATUS`                    AS `status`,
  `b`.`customer_name`             AS `customer_name`
FROM `wikitechy_list` `a`
  LEFT JOIN `view_quotes` `b`
    ON (`b`.`quote_id` = `a`.`quote_id`)
LIMIT 0, 30
click below button to copy the code. By — mysql tutorial — team
  • The error message is:
#1449 - The user specified as a definer ('web2vi'@'%') does not exist
click below button to copy the code. By — mysql tutorial — team

Solution 1:

Change the DEFINER

  • This is possibly easiest to do when initially importing your database objects, by removing any DEFINER statements from the dump.
  • Changing the definer later is a more little tricky:

How to change the definer for views

  • Run this SQL to generate the necessary ALTER statements
	SELECT CONCAT("ALTER DEFINER=`youruser`@`host` VIEW ", 
	table_name, " AS ", view_definition, ";") 
	FROM information_schema.views 
WHERE table_schema='your-database-name';
click below button to copy the code. By — mysql tutorial — team
  • Copy and run the ALTER statements

Solution 2:

Create the missing user

  • If you’ve found following error while using MySQL database:
The user specified as a definer ('someuser'@'%') does not exist`
click below button to copy the code. By — mysql tutorial — team
  • Then you can solve it by using following :
GRANT ALL ON *.* TO 'someuser'@'%' IDENTIFIED BY 'complex-password';
FLUSH PRIVILEGES;
click below button to copy the code. By — mysql tutorial — team

Solution 3:

  • The user who originally created the SQL view or procedure has been deleted. If you recreate that user, it should address your error.

Solution 4:

  • If the user exists, then:
mysql> flush privileges;
click below button to copy the code. By — mysql tutorial — team

 

Problem

After moving a MySQL database between MySQL servers we observe the following error on atlassian-confluence.log files when trying to edit pages:

caused by: org.springframework.jdbc.UncategorizedSQLException: Hibernate operation: could not execute statement; uncategorized SQLException; SQL state [HY000]; error code [1449]; The user specified as a definer ('username'@'hostname') does not exist; nested exception is java.sql.SQLException: The user specified as a definer ('username'@'hostname') does not exist
at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:89)
caused by: java.sql.SQLException: The user specified as a definer ('username'@'hostname') does not exist
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:129)

Diagnosis

Environment

  • This issue affects Confluence with MySQL version 5.7 and 8.0.

Cause

“The DEFINER clause specifies the MySQL account to be used when checking access privileges at routine execution time for routines that have the SQL SECURITY DEFINER characteristic.”

  • (info) Reference: https://dev.mysql.com/doc/refman/8.0/en/create-procedure.html

When a procedure is exported into a Dump File, it is exported having username and hostname defined in its DDL. The combination of username and hostname is the DEFINER that has permissions to run that procedure.

Error will happen if that dump is imported into a Database without the combination of username and hostname with privileges granted on the new database.

Resolution

There are few possible solutions, it will all depend on your environment and which MySQL version you are running.

Always back up your data before performing any modifications to the database. If possible, test any alter, insert, update, or delete SQL commands on a staging server first.

The following SQL statements should be run whilst Confluence is shutdown.

Solution 1

  • Create the missing user/account and grant permission for ‘username’@’hostname’
    Even if you are not planning to use that user for Confluence to connect to MySQL, that user will be used by MySQL to run the Procedures with that DEFINER:

    CREATE USER IF NOT EXISTS <username> IDENTIFIED BY '<password>';
    GRANT ALL PRIVILEGES ON <ConfluenceDatabase>.* TO '<username>'@'<hostname>';

Solution 2

  • Alter MySQL Dump File before import
    As mentioned above, procedures were exported from previous MySQL with DEFINER set for ‘<username>’@'<hostname>’.
    After export the Dump File, you should modify dump file, looking for previous username/hostname combination on Create Procedure statements and replace with new username and hostname. And finally import Dump File on new MySQL server.

Solution 3

3.1. Fix up the Stored Procedures Definers:

For MySQL 5.x…

-- 1. Substitute <NEWusername> with the new SQL user
-- 2. Substitute <NEWhostname> with the new Confluence host
-- 3. Substitute <username> with the old SQL user
-- 4. Substitute <hostname> with the old Confluence host
-- 5. Substitute <ConfluenceDatabase> with the new Confluence database name
UPDATE `mysql`.`proc` p SET definer = '<NEWusername>@<NEWhostname>' WHERE definer='<username>@<hostname>' and db = '<ConfluenceDatabase>';

For MySQL 8.x…

  1. The recommendation to alter procedures on MySQL 8.X is to drop them and recreate them with the changes needed.
  2. Option 1: Running from mysql command line:
    1. Save this DDL to a file called fix_conf_definer.sql:

      -- 1. Drop the existing Stored Procedures
      drop procedure if exists content_perm_set_procedure_for_denormalised_permissions;
      drop procedure if exists content_permission_procedure_for_denormalised_permissions;
      drop procedure if exists content_procedure_for_denormalised_permissions;
      drop procedure if exists space_permission_procedure_for_denormalised_permissions;
      drop procedure if exists space_procedure_for_denormalised_permissions;
      
      DELIMITER //
      
      -- 2. Substitute <NEWusername> with the new SQL user
      -- 3. Substitute <NEWhostname> with the new Confluence host
      -- 4. Run each of these blocks (one at a time) as one SQL statement
      create
          definer = <NEWusername>@`<NEWhostname>` procedure `content_perm_set_procedure_for_denormalised_permissions`(OUT isServiceDisabled tinyint(1))
      BEGIN
          SET isServiceDisabled = TRUE;
      END//
      
      create
          definer = <NEWusername>@`<NEWhostname>` procedure content_permission_procedure_for_denormalised_permissions(OUT isServiceDisabled tinyint(1))
      BEGIN
          SET isServiceDisabled = TRUE;
      END//
      
      create
          definer = <NEWusername>@`<NEWhostname>` procedure content_procedure_for_denormalised_permissions(OUT isServiceDisabled tinyint(1))
      BEGIN
          SET isServiceDisabled = TRUE;
      END//
      
      create
          definer = <NEWusername>@`<NEWhostname>` procedure space_permission_procedure_for_denormalised_permissions(OUT isServiceDisabled tinyint(1))
      BEGIN
          SET isServiceDisabled = TRUE;
      END//
      
      create
          definer = <NEWusername>@`<NEWhostname>` procedure space_procedure_for_denormalised_permissions(OUT isServiceDisabled tinyint(1))
      BEGIN
          SET isServiceDisabled = TRUE;
      END//
      DELIMITER ;
    2. (warning) Make the substitutions of <NEWusername>  and <NEWhostname>  as described above into fix_conf_definer.sql 
    3. Apply the SQL using mysql :

      mysql -u <MYSQL_USER_NAME> <NewConfluenceDatabaseName> -p < fix_conf_definer.sql 
  3. Option 2: Running from a GUI SQL query tool:
    1. Copy and paste this DDL to your SQL GUI query window and run on your new Confluence database:

      -- 1. Drop the existing Stored Procedures
      drop procedure if exists content_perm_set_procedure_for_denormalised_permissions;
      drop procedure if exists content_permission_procedure_for_denormalised_permissions;
      drop procedure if exists content_procedure_for_denormalised_permissions;
      drop procedure if exists space_permission_procedure_for_denormalised_permissions;
      drop procedure if exists space_procedure_for_denormalised_permissions;
    2. Copy and paste this DDL to your SQL GUI query window (do not run this yet!):

      -- 2. Substitute <NEWusername> with the new SQL user
      -- 3. Substitute <NEWhostname> with the new Confluence host
      -- 4. Run each of these blocks (one at a time) as one SQL statement
      create
          definer = <NEWusername>@`<NEWhostname>` procedure `content_perm_set_procedure_for_denormalised_permissions`(OUT isServiceDisabled tinyint(1))
      BEGIN
          SET isServiceDisabled = TRUE;
      END;
      
      create
          definer = <NEWusername>@`<NEWhostname>` procedure content_permission_procedure_for_denormalised_permissions(OUT isServiceDisabled tinyint(1))
      BEGIN
          SET isServiceDisabled = TRUE;
      END;
      
      create
          definer = <NEWusername>@`<NEWhostname>` procedure content_procedure_for_denormalised_permissions(OUT isServiceDisabled tinyint(1))
      BEGIN
          SET isServiceDisabled = TRUE;
      END;
      
      create
          definer = <NEWusername>@`<NEWhostname>` procedure space_permission_procedure_for_denormalised_permissions(OUT isServiceDisabled tinyint(1))
      BEGIN
          SET isServiceDisabled = TRUE;
      END;
      
      create
          definer = <NEWusername>@`<NEWhostname>` procedure space_procedure_for_denormalised_permissions(OUT isServiceDisabled tinyint(1))
      BEGIN
          SET isServiceDisabled = TRUE;
      END;
    3. (warning) Make the substitutions of <NEWusername>  and <NEWhostname>  as described above
    4. Run each «block» one at a time as a single SQL statement until all SQL blocks have been run successfully. Here is an example using DbVisualizer:

3.2. Fix up the Triggers Definers:

For MySQL 5.x and MySQL 8.x…

  1. Dump out the triggers:

    mysqldump -u <USER_NAME> -p --triggers --add-drop-trigger --no-create-info --no-data --no-create-db --skip-opt <ConfluenceDatabase> > triggers.sql
  2. Open up the triggers.sql  in a text editor and manually search and replace all the old definer settings to new definer settings.
    1. E.g. Search and replace all `confold`@`10.0.0.111`  with `confnew`@`10.0.0.122` 

      From (old):

      ...
      /*!50003 CREATE*/ /*!50017 DEFINER=`confold`@`10.0.0.111`*/ /*!50003 TRIGGER denormalised_content_trigger_on_insert
      ...

      To (new)

      ...
      /*!50003 CREATE*/ /*!50017 DEFINER=`confnew`@`10.0.0.122`*/ /*!50003 TRIGGER denormalised_content_trigger_on_insert
      ...
  3. Reapply the updated triggers
    mysql -u <USER_NAME> -p <ConfluenceDatabase> < triggers.sql

Solution 4

  • Migrate Database
    You can use the Documentation used to Migrate databases. This can be used to move Databases from one server to another, even if you are using same database on both server, like MySQL: Migrating to Another Database

Понравилась статья? Поделить с друзьями:
  • Mysqldump got error 1044 access denied for user
  • Mysqldump error 2013 lost connection to mysql server during query when dumping table
  • Mysqlcheck got error 2013 lost connection to mysql server during query when executing check table
  • Mysqlcheck got error 1049 unknown database
  • Mysqladmin connect to server at localhost failed error access denied for user root localhost