I am receiving this error when trying to add/remove database users on my Plesk Obsedian server.
Unfortunately, the release version of MariaDB I’m using, 10.4.x, is not officially supported by them even though I installed the update via their instructions.
No matter.
Can someone provide a simple step by step to fix the problem?
I am not a database wizard, but I can dabble a bit in command line, and I’m terrific at copying and pasting.
Thanks.
Gene Steinberg
Answer
This request occured 7 months ago, but the answer still may be usefull for anybody encountering the same issue.
I personnaly had the same message when I tried to create a view that relied on other views that did not exist in the schema or which definer user was not recognised by Mariadb. The solution is quite obvious:
1) Ensure that the definer user exists in your database. Create him if needed and do not forget to flush privileges.
2) Create or alter the dependances views with the correct definer user.
3) Create or alter the view for which the message occured with the correct definer user.
Sorry for Gene. I hope he found a solution by himself.
-
↑ The Community ↑
Comments
Content reproduced on this site is the property of its respective owners,
and this content is not reviewed in advance by MariaDB. The views, information and opinions
expressed by this content do not necessarily represent those of MariaDB or any other party.
Содержание
- MySQL:The user specified as a definer does not exist (error 1449)-Solutions
- Solution: 1
- Solution: 2
- Solution: 3
- MySQL:The user specified as a definer does not exist (error 1449)-Solutions
- Solution: 1
- Solution: 2
- Solution: 3
- Restoring MySQL dump ERROR 1449
- 2 Answers 2
- Ошибка MySQL 1449: пользователь, указанный как определитель, не существует
- 34 ответа
- 1. Измените DEFINER
- Как изменить определитель для представлений
- Как изменить определитель для хранимых процедур
- 2. Создайте отсутствующего пользователя
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: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.
Источник
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,
- fire up your trusted text editor (I trust vim for stuffs like this, VS Code crawls like no progress opening GB size files)
- search for Current Database: mysql comment / marker.
- select the text from that point up to the next Current Database: comment/marker.
- Cut it, put it before the first Current Database comment/marker.
Afterwards, I saved the modified dump, and now the dump restores without error.
Источник
Ошибка MySQL 1449: пользователь, указанный как определитель, не существует
Когда я запускаю следующий запрос, я получаю сообщение об ошибке:
Сообщение об ошибке:
Почему я получаю эту ошибку? Как это исправить?
34 ответа
Это обычно происходит при экспорте представлений/триггеров/процедур из одной базы данных или сервера в другой, поскольку пользователь, создавший этот объект, больше не существует.
У вас есть два варианта:
1. Измените DEFINER
Это, возможно, проще всего сделать при первоначальном импорте объектов базы данных, удалив любые операторы DEFINER из дампа.
Изменение определителя позже является более сложным:
Как изменить определитель для представлений
Запустите этот SQL для генерации необходимых операторов ALTER
Скопируйте и запустите инструкции ALTER
Как изменить определитель для хранимых процедур
Будьте осторожны, потому что это изменит все определители для всех баз данных.
2. Создайте отсутствующего пользователя
Если вы обнаружили следующую ошибку при использовании базы данных MySQL:
Тогда вы можете решить это, используя следующее:
Это работало как шарм — вам нужно только изменить someuser на имя пропавшего пользователя. На локальном сервере-разработчике обычно можно использовать root .
Также рассмотрите вопрос о том, действительно ли вам нужно предоставить разрешения пользователя ALL или они могут сделать меньше.
Пользователь, который изначально создал представление или процедуру SQL, был удален. Если вы воссоздаете этого пользователя, он должен устранить вашу ошибку.
Если пользователь существует, то:
Создайте удаляемого пользователя следующим образом:
Я получил ту же ошибку после обновления mysql.
Ошибка была исправлена после этой команды:
mysql_upgrade должен выполняться каждый раз при обновлении MySQL. Он проверяет все таблицы во всех базах данных на предмет несовместимости с текущей версией MySQL Server. Если найденная таблица имеет возможную несовместимость, она проверяется. Если обнаружены какие-либо проблемы, таблица будет восстановлена. mysql_upgrade также обновляет системные таблицы, чтобы вы могли использовать новые привилегии или возможности, которые могли быть добавлены.
Решение — это всего лишь однострочный запрос, как показано ниже:
Замените ROOT своим именем пользователя mysql. Замените PASSWORD своим паролем mysql.
Выполните следующие действия:
- Перейдите в PHPMyAdmin
- Выберите свою базу данных
- Выберите таблицу
- В верхнем меню Нажмите «Триггеры»
- Нажмите «Изменить», чтобы изменить триггер
- Измените определитель с [user @localhost] на root @localhost
Надеюсь, что это поможет
Для будущих googlers: у меня есть аналогичное сообщение, пытающееся обновить таблицу в базе данных, которая не содержит представлений. После некоторого копания оказалось, что я импортировал триггеры на эту таблицу, и это были вещи, определенные несуществующим пользователем. Сбрасывание триггеров решило проблему.
Исправлено, выполнив следующие комментарии.
если вы получаете some_other вместо web2vi , тогда вы должны соответствующим образом изменить имя.
быстро исправить работу и выгрузить файл:
Пользователь ‘web2vi’ не существует на вашем сервере mysql.
Если этот пользователь существует, проверьте, на каких серверах он может получить доступ, хотя я бы подумал, что это будет другая ошибка (например, у вас может быть web2vi @localhost, но вы получаете доступ к db как web2vi @% (во что угодно )
Попробуйте установить процедуру как SECURITY INVOKER
Mysql default устанавливает безопасность процедур как «DEFINER» (CREATOR OF).. вы должны установить защиту для «invoker».
У меня была такая же проблема с пользователем root, и он работал у меня, когда я заменил
Итак, если пользователю ‘web2vi’ разрешено подключаться из ‘localhost’, вы можете попробовать:
Я подключен удаленно к базе данных.
У меня была такая же ошибка, когда я пытался выбрать из представления.
Однако проблема заключается в том, что это представление, выбранное из другого представления, которое было восстановлено из резервной копии с другого сервера.
и на самом деле, ДА, пользователь был недействителен, но не был очевиден с первого взгляда.
В моем случае таблица имела триггер с пользователем DEFINER, которого не было.
Вы можете попробовать следующее:
Ваше мнение, «view_quotes», возможно, было скопировано из другой базы данных, где «web2vi» является допустимым пользователем в базе данных, где «web2vi» не является допустимым пользователем.
Либо добавьте пользователя «web2vi» в базу данных, либо измените представление (обычно удаление части DEFINER = ‘web2vi’ @’%’ и выполнение script сделает трюк)
Это произошло со мной после того, как я импортировал дамп в Windows 10 с MySQL Workbench 6.3 Community, а «root @% не существует». Хотя пользователь существовал. Сначала я попытался прокомментировать DEFINER, но это не сработало. Затем я заменил строку «root @%» на «root @localhost» и повторно импортировал дамп. Это сделало трюк для меня.
Почему я получаю эту ошибку? Как это исправить?
Я потратил час до того, как нашел решение для такой проблемы. Но в моем случае я запустил это:
Если вы действительно хотите найти проблему, просто запустите следующие команды:
. и после каждого из них найдите поле «определитель».
В моем случае это был бородатый старый триггер, который кто-то из разработчиков забыл удалить.
когда mysql.proc пуст, но система всегда замечает «[email protected]%» для имени таблицы, нет, вы просто root в командной строке mysql и введите:
Если это хранимая процедура, вы можете сделать:
Но это не рекомендуется.
Для меня лучшим решением является создание определителя:
Один или несколько видов, созданных/зарегистрированных другим пользователем. Вам нужно будет проверить владельца представления и:
- Восстановить пользователя; как говорят другие ответы. или
- Создайте представления, созданные пользователем ‘web2vi’ , используя ALTER VIEW
У меня была эта проблема.
Я пытался перенести представления из BD1 в BD2, используя SQLYog. SQLYog воссоздал представления в другой базе данных (DB2), но он сохранил пользователя BD1 (они разные). Позже я понял, что представления, которые я использовал в моем запросе, имели ту же ошибку, что и вы, даже когда я не создавал никакого представления.
Надеюсь на эту помощь.
Проблема понятна — MySQL не может найти пользователя, заданного в качестве определителя.
Я столкнулся с этой проблемой после синхронизации модели базы данных с сервера разработки, применения ее к localhost, внесения изменений в модель и последующего повторного использования ее на localhost. По-видимому, было определено представление (я изменил), и поэтому я не смог обновить локальную версию.
Как исправить (легко) :
Примечание: он включает удаление, поэтому он отлично подходит для представлений, но убедитесь, что у вас есть резервная копия данных, если вы попробуете это в таблицах.
- Войдите в базу данных как пользователь root (или все, что имеет достаточную мощность для внесения изменений).
- Удалить представление, таблицу или все, с чем вы столкнулись.
- Синхронизируйте свою новую модель — она не будет жаловаться на то, чего не существует сейчас. Вы можете удалить часть SQL SECURITY DEFINER из определения элемента, с которым у вас были проблемы.
P.S. Это не является ни правильным, ни лучшим решением. Я просто разместил его как возможное (и очень простое) решение.
У меня была одна и та же проблема минут назад, я столкнулся с этой проблемой после того, как удалил неиспользуемого пользователя из таблицы mysql.user, но вместо этого изменил его вид, вот удобная команда, которая делает ее очень простой:
Смешайте это с командной строкой mysql (предполагая * nix, не знакомый с окнами):
Примечание: команда генерирует и добавляет SELECT CONCAT в файл, делая mysql -uuser -ppass databasename сбой, если вы не удалите его.
Источник
Когда я запускаю следующий запрос, я получаю сообщение об ошибке:
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 `tbl_supplier_list` `a`
LEFT JOIN `view_quotes` `b`
ON (`b`.`quote_id` = `a`.`quote_id`)
LIMIT 0, 30
Сообщение об ошибке:
#1449 - The user specified as a definer ('web2vi'@'%') does not exist
Почему я получаю эту ошибку? Как это исправить?
Ответ 1
Это обычно происходит при экспорте представлений/триггеров/процедур из одной базы данных или сервера в другой, поскольку пользователь, создавший этот объект, больше не существует.
У вас есть два варианта:
1. Измените DEFINER
Это, возможно, проще всего сделать при первоначальном импорте объектов базы данных, удалив любые операторы DEFINER из дампа.
Изменение определителя позже является более сложным:
Как изменить определитель для представлений
-
Запустите этот SQL для генерации необходимых операторов ALTER
SELECT CONCAT("ALTER DEFINER=`youruser`@`host` VIEW ", table_name, " AS ", view_definition, ";") FROM information_schema.views WHERE table_schema='your-database-name'; -
Скопируйте и запустите инструкции ALTER
Как изменить определитель для хранимых процедур
Пример:
UPDATE `mysql`.`proc` p SET definer = '[email protected]%' WHERE definer='[email protected]%'
Будьте осторожны, потому что это изменит все определители для всех баз данных.
2. Создайте отсутствующего пользователя
Если вы обнаружили следующую ошибку при использовании базы данных MySQL:
The user specified as a definer ('someuser'@'%') does not exist`Тогда вы можете решить это, используя следующее:
GRANT ALL ON *.* TO 'someuser'@'%' IDENTIFIED BY 'complex-password'; FLUSH PRIVILEGES;
Из http://www.lynnnayko.com/2010/07/mysql-user-specified-as-definer-root.html
Это работало как шарм — вам нужно только изменить someuser на имя пропавшего пользователя. На локальном сервере-разработчике обычно можно использовать root.
Также рассмотрите вопрос о том, действительно ли вам нужно предоставить разрешения пользователя ALL или они могут сделать меньше.
Ответ 2
Пользователь, который изначально создал представление или процедуру SQL, был удален. Если вы воссоздаете этого пользователя, он должен устранить вашу ошибку.
Ответ 3
Я получил ту же ошибку после обновления mysql.
Ошибка была исправлена после этой команды:
mysql_upgrade -u root
mysql_upgrade должен выполняться каждый раз при обновлении MySQL. Он проверяет все таблицы во всех базах данных на предмет несовместимости с текущей версией MySQL Server. Если найденная таблица имеет возможную несовместимость, она проверяется. Если обнаружены какие-либо проблемы, таблица будет восстановлена. mysql_upgrade также обновляет системные таблицы, чтобы вы могли использовать новые привилегии или возможности, которые могли быть добавлены.
Ответ 4
Если пользователь существует, то:
mysql> flush privileges;
Ответ 5
Создайте удаляемого пользователя следующим образом:
mysql> create user 'web2vi';
или
mysql> create user 'web2vi'@'%';
Ответ 6
Выполните следующие действия:
- Перейдите в PHPMyAdmin
- Выберите свою базу данных
- Выберите таблицу
- В верхнем меню Нажмите «Триггеры»
- Нажмите «Изменить», чтобы изменить триггер
- Измените определитель с [user @localhost] на root @localhost
Надеюсь, что это поможет
Ответ 7
Решение — это всего лишь однострочный запрос, как показано ниже:
grant all on *.* to 'ROOT'@'%' identified by 'PASSWORD' with grant option;
Замените ROOT своим именем пользователя mysql.
Замените PASSWORD своим паролем mysql.
Ответ 8
Для будущих googlers: у меня есть аналогичное сообщение, пытающееся обновить таблицу в базе данных, которая не содержит представлений. После некоторого копания оказалось, что я импортировал триггеры на эту таблицу, и это были вещи, определенные несуществующим пользователем. Сбрасывание триггеров решило проблему.
Ответ 9
Исправлено, выполнив следующие комментарии.
grant all on *.* to 'web2vi'@'%' identified by 'root' with grant option;
FLUSH PRIVILEGES;
если вы получаете some_other вместо web2vi, тогда вы должны соответствующим образом изменить имя.
Ответ 10
быстро исправить работу и выгрузить файл:
mysqldump --single-transaction -u root -p xyz_live_db > xyz_live_db_bkup110116.sql
Ответ 11
Пользователь ‘web2vi’ не существует на вашем сервере mysql.
См. http://dev.mysql.com/doc/refman/5.1/en/error-messages-server.html#error_er_no_such_user
Если этот пользователь существует, проверьте, на каких серверах он может получить доступ, хотя я бы подумал, что это будет другая ошибка (например, у вас может быть web2vi @localhost, но вы получаете доступ к db как web2vi @% (во что угодно )
Ответ 12
У меня была такая же проблема с пользователем root, и он работал у меня, когда я заменил
[email protected]%
по
[email protected]
Итак, если пользователю ‘web2vi’ разрешено подключаться из ‘localhost’, вы можете попробовать:
[email protected]
Я подключен удаленно к базе данных.
Ответ 13
grant all on *.* to 'username'@'%' identified by 'password' with grant option;
Пример:
grant all on *.* to 'web2vi'@'%' identified by 'password' with grant option;
Ответ 14
Это случилось со мной после перемещения БД с одного сервера на другой. Первоначально определитель использовал localhost и пользователя. На новом сервере у нас нет этого пользователя, и хост также был изменен. Я сделал резервную копию этой конкретной таблицы и вручную удалил все триггеры из phpmyadmin. После этого он работал нормально для меня.
Ответ 15
Мои 5 центов.
У меня была такая же ошибка, когда я пытался выбрать из представления.
Однако проблема заключается в том, что это представление, выбранное из другого представления, которое было восстановлено из резервной копии с другого сервера.
и на самом деле, ДА, пользователь был недействителен, но не был очевиден с первого взгляда.
Ответ 16
Попробуйте установить процедуру как
SECURITY INVOKER
Mysql default устанавливает безопасность процедур как «DEFINER» (CREATOR OF).. вы должны установить защиту для «invoker».
Ответ 17
У меня была одна и та же проблема минут назад, я столкнулся с этой проблемой после того, как удалил неиспользуемого пользователя из таблицы mysql.user, но вместо этого изменил его вид, вот удобная команда, которая делает ее очень простой:
SELECT CONCAT("ALTER DEFINER=`youruser`@`host` VIEW ",
table_name," AS ", view_definition,";") FROM
information_schema.views WHERE table_schema='databasename'
Смешайте это с командной строкой mysql (предполагая * nix, не знакомый с окнами):
> echo above_query | mysql -uuser -p > alterView.sql
> mysql -uuser -ppass databasename < alterView.sql
Примечание: команда генерирует и добавляет SELECT CONCAT в файл, делая mysql -uuser -ppass databasename < alterView.sql сбой, если вы не удалите его.
Источник: https://dba.stackexchange.com/questions/4129/modify-definer-on-many-views
Ответ 18
Ваше мнение, «view_quotes», возможно, было скопировано из другой базы данных, где «web2vi» является допустимым пользователем в базе данных, где «web2vi» не является допустимым пользователем.
Либо добавьте пользователя «web2vi» в базу данных, либо измените представление (обычно удаление части DEFINER = ‘web2vi’ @’%’ и выполнение script сделает трюк)
Ответ 19
В моем случае таблица имела триггер с пользователем DEFINER, которого не было.
Ответ 20
Проблема понятна — MySQL не может найти пользователя, заданного в качестве определителя.
Я столкнулся с этой проблемой после синхронизации модели базы данных с сервера разработки, применения ее к localhost, внесения изменений в модель и последующего повторного использования ее на localhost. По-видимому, было определено представление (я изменил), и поэтому я не смог обновить локальную версию.
Как исправить (легко) :
Примечание: он включает удаление, поэтому он отлично подходит для представлений, но убедитесь, что у вас есть резервная копия данных, если вы попробуете это в таблицах.
- Войдите в базу данных как пользователь root (или все, что имеет достаточную мощность для внесения изменений).
- Удалить представление, таблицу или все, с чем вы столкнулись.
- Синхронизируйте свою новую модель — она не будет жаловаться на то, чего не существует сейчас. Вы можете удалить часть SQL SECURITY DEFINER из определения элемента, с которым у вас были проблемы.
P.S. Это не является ни правильным, ни лучшим решением. Я просто разместил его как возможное (и очень простое) решение.
Ответ 21
Вы можете попробовать следующее:
$ mysql -u root -p
> grant all privileges on *.* to `root`@`%` identified by 'password';
> flush privileges;
Ответ 22
Почему я получаю эту ошибку? Как это исправить?
Я потратил час до того, как нашел решение для такой проблемы. Но в моем случае я запустил это:
mysql> UPDATE `users` SET `somefield` = 1 WHERE `user_id` = 2;
ERROR 1449 (HY000): The user specified as a definer ('root'@'%') does not exist
Если вы действительно хотите найти проблему, просто запустите следующие команды:
SHOW PROCEDURE STATUS;
SHOW FUNCTION STATUS;
SHOW TRIGGERS;
SHOW FULL TABLES IN database_name WHERE TABLE_TYPE LIKE 'VIEW';
… и после каждого из них найдите поле «определитель».
В моем случае это был бородатый старый триггер, который кто-то из разработчиков забыл удалить.
Ответ 23
От ссылка MySQL CREATE VIEW:
В предложениях DEFINER и SQL SECURITY указан контекст безопасности, который будет использоваться при проверке прав доступа во время вызова представления.
Этот пользователь должен существовать и всегда лучше использовать «localhost» в качестве имени хоста. Поэтому я думаю, что если вы проверите, что пользователь существует и измените его на «localhost» при создании представления, у вас не будет этой ошибки.
Ответ 24
Перейдите в раздел подпрограммы редактирования, а внизу измените тип безопасности с Definer на Invoker.
Ответ 25
Один или несколько видов, созданных/зарегистрированных другим пользователем. Вам нужно будет проверить владельца представления и:
- Восстановить пользователя; как говорят другие ответы.
или - Создайте представления, созданные пользователем
'web2vi', используя ALTER VIEW
У меня была эта проблема.
Я пытался перенести представления из BD1 в BD2, используя SQLYog. SQLYog воссоздал представления в другой базе данных (DB2), но он сохранил пользователя BD1 (они разные). Позже я понял, что представления, которые я использовал в моем запросе, имели ту же ошибку, что и вы, даже когда я не создавал никакого представления.
Надеюсь на эту помощь.
Ответ 26
Если это хранимая процедура, вы можете сделать:
UPDATE `mysql`.`proc` SET definer = 'YournewDefiner' WHERE definer='OldDefinerShownBefore'
Но это не рекомендуется.
Для меня лучшим решением является создание определителя:
create user 'myuser' identified by 'mypass';
grant all on `mytable`.* to 'myuser' identified by 'mypass';
Ответ 27
когда mysql.proc пуст, но система всегда замечает «[email protected]%» для имени таблицы, нет, вы просто root в командной строке mysql и введите:
CHECK TABLE `database`.`table_name` QUICK FAST MEDIUM CHANGED;
flush privileges;
над
Ответ 28
Это произошло со мной после того, как я импортировал дамп в Windows 10 с MySQL Workbench 6.3 Community, а «root @% не существует». Хотя пользователь существовал.
Сначала я попытался прокомментировать DEFINER, но это не сработало.
Затем я заменил строку «root @%» на «root @localhost» и повторно импортировал дамп. Это сделало трюк для меня.
Ответ 29
Пользователь базы данных также, похоже, чувствителен к регистру, поэтому, когда у меня был пользователь root @@%, у меня не было пользователя ROOT ‘@’%. Я изменил пользователя на верхний регистр с помощью инструментария, и проблема была решена!
Ответ 30
в моем случае у меня был триггер в этой таблице, что я не мог обновлять данные, получая ту же ошибку.
Ошибка MySQL 1449: пользователь, указанный как определитель, не существует
решение заключалось в том, чтобы удалить триггеры в этой таблице и снова создать их снова, это устранило проблему, поскольку триггер был сделан с другим пользователем с другого сервера, а имя пользователя изменилось на новом сервере после изменения компании-хостинга. что мои 2 цента
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.
mysql> grant all on test.* to 'spuser'@'localhost' identified by 'sppass'; Query OK, 0 rows affected (0.04 sec)mysql> flush privileges; Query OK, 0 rows affected (0.04 sec)### Doc: If you modify the grant tables indirectly using account-management statements such as GRANT, REVOKE, SET PASSWORD, or RENAME USER, the server notices these changes and loads the grant tables into memory again immediately. mysql> DROP PROCEDURE IF EXISTS myproc; Query OK, 0 rows affected, 1 warning (0.00 sec) mysql> DELIMITER $$ mysql> CREATE DEFINER='spuser'@'localhost' PROCEDURE myproc() -> BEGIN -> select count(*) from test.a; -> END $$ Query OK, 0 rows affected (0.00 sec) mysql> DELIMITER ; mysql> select current_user(); +----------------+ | current_user() | +----------------+ | root@localhost | +----------------+ 1 row in set (0.00 sec) mysql> call test.myproc(); +----------+ | count(*) | +----------+ | 6 | +----------+ 1 row in set (0.00 sec) Query OK, 0 rows affected (0.00 sec)
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.
mysql> drop user 'spuser'@'localhost'; Query OK, 0 rows affected (0.00 sec)mysql> flush privileges; Query OK, 0 rows affected (0.00 sec)mysql> call test.myproc(); ERROR 1449 (HY000): The user specified as a definer ('spuser'@'localhost') does not exist
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
mysql> grant all privileges on test.* to 'spuser'@'localhost' identified by 'sppass'; Query OK, 0 rows affected (0.01 sec)mysql> flush privileges; Query OK, 0 rows affected (0.00 sec)mysql> call test.myproc(); +----------+ | count(*) | +----------+ | 6 | +----------+ 1 row in set (0.00 sec) Query OK, 0 rows affected (0.00 sec)
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
mysql> DROP PROCEDURE IF EXISTS myproc;
Query OK, 0 rows affected (0.00 sec)
mysql> DELIMITER $$
mysql> CREATE DEFINER='spuser'@'localhost' PROCEDURE myproc()
-> SQL SECURITY INVOKER
-> BEGIN
-> select count(*) from test.a;
-> END $$
Query OK, 0 rows affected (0.00 sec)
mysql> DELIMITER ;
mysql> drop user 'spuser'@'localhost';
Query OK, 0 rows affected (0.00 sec)
mysql> flush privileges;
Query OK, 0 rows affected (0.01 sec)
mysql> call test.myproc();
+----------+
| count(*) |
+----------+
| 6 |
+----------+
1 row in set (0.00 sec)
Query OK, 0 rows affected (0.00 sec)
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
mysql> DROP PROCEDURE IF EXISTS myproc;
Query OK, 0 rows affected, 1 warning (0.00 sec)
mysql> DELIMITER $$
mysql> CREATE DEFINER='spuser'@'localhost' PROCEDURE myproc()
-> BEGIN
-> select count(*) from test.a;
-> END $$
Query OK, 0 rows affected (0.00 sec)
mysql> DELIMITER ;
mysql> select * from mysql.proc where name='myproc';
+------+------+-----------+---------------+----------+-----------------+------------------+---------------+------------+---------+------------------------------------------+------------------+---------------------+---------------------+----------+---------+----------------------+----------------------+-------------------+------------------------------------------+
| db | name | type | specific_name | language | sql_data_access | is_deterministic | security_type | param_list | returns | body | definer | created | modified | sql_mode | comment | character_set_client | collation_connection | db_collation | body_utf8 |
+------+------+-----------+---------------+----------+-----------------+------------------+---------------+------------+---------+------------------------------------------+------------------+---------------------+---------------------+----------+---------+----------------------+----------------------+-------------------+------------------------------------------+
| test | myproc | PROCEDURE | myproc | SQL | CONTAINS_SQL | NO | DEFINER | | | BEGIN
select count(*) from test.a;
END | spuser@localhost | 2015-03-20 23:57:53 | 2015-03-20 23:57:53 | | | utf8 | utf8_general_ci | latin1_swedish_ci | BEGIN
select count(*) from test.a;
END |
+------+------+-----------+---------------+----------+-----------------+------------------+---------------+------------+---------+------------------------------------------+------------------+---------------------+---------------------+----------+---------+----------------------+----------------------+-------------------+------------------------------------------+
1 row in set (0.00 sec)
mysql> drop user 'spuser'@'localhost';
Query OK, 0 rows affected (0.00 sec)
mysql> flush privileges;
Query OK, 0 rows affected (0.00 sec)
mysql> call test.myproc();
ERROR 1449 (HY000): The user specified as a definer ('spuser'@'localhost') does not exist
mysql> update mysql.proc set definer='root@localhost' where name='test';
Query OK, 1 row affected (0.00 sec)
Rows matched: 1 Changed: 1 Warnings: 0
mysql> select * from routines where routine_name='myproc';
+---------------+-----------------+----------------+--------------+--------------+-----------+--------------------------+------------------------+-------------------+---------------+--------------------+----------------+----------------+--------------+------------------------------------------+---------------+-------------------+-----------------+------------------+-----------------+----------+---------------+---------------------+---------------------+----------+-----------------+----------------+----------------------+----------------------+--------------------+
| SPECIFIC_NAME | ROUTINE_CATALOG | ROUTINE_SCHEMA | ROUTINE_NAME | ROUTINE_TYPE | DATA_TYPE | CHARACTER_MAXIMUM_LENGTH | CHARACTER_OCTET_LENGTH | NUMERIC_PRECISION | NUMERIC_SCALE | CHARACTER_SET_NAME | COLLATION_NAME | DTD_IDENTIFIER | ROUTINE_BODY | ROUTINE_DEFINITION | EXTERNAL_NAME | EXTERNAL_LANGUAGE | PARAMETER_STYLE | IS_DETERMINISTIC | SQL_DATA_ACCESS | SQL_PATH | SECURITY_TYPE | CREATED | LAST_ALTERED | SQL_MODE | ROUTINE_COMMENT | DEFINER | CHARACTER_SET_CLIENT | COLLATION_CONNECTION | DATABASE_COLLATION |
+---------------+-----------------+----------------+--------------+--------------+-----------+--------------------------+------------------------+-------------------+---------------+--------------------+----------------+----------------+--------------+------------------------------------------+---------------+-------------------+-----------------+------------------+-----------------+----------+---------------+---------------------+---------------------+----------+-----------------+----------------+----------------------+----------------------+--------------------+
| myproc | def | test | myproc | PROCEDURE | | NULL | NULL | NULL | NULL | NULL | NULL | NULL | SQL | BEGIN
select count(*) from test.a;
END | NULL | NULL | SQL | NO | CONTAINS SQL | NULL | DEFINER | 2015-03-20 23:58:51 | 2015-03-20 23:57:53 | | | root@localhost | utf8 | utf8_general_ci | latin1_swedish_ci |
+---------------+-----------------+----------------+--------------+--------------+-----------+--------------------------+------------------------+-------------------+---------------+--------------------+----------------+----------------+--------------+------------------------------------------+---------------+-------------------+-----------------+------------------+-----------------+----------+---------------+---------------------+---------------------+----------+-----------------+----------------+----------------------+----------------------+--------------------+
1 row in set (0.02 sec)
mysql> exit
Bye
root@ubuntu:~# mysql -uroot -pkedar
Welcome to the MySQL monitor. Commands end with ; or g.
Your MySQL connection id is 5
Server version: 5.5.30-log MySQL Community Server (GPL)
Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help;' or 'h' for help. Type 'c' to clear the current input statement.
mysql> use test
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A
Database changed
mysql> call test.myproc();
+----------+
| count(*) |
+----------+
| 6 |
+----------+
1 row in set (0.00 sec)
Query OK, 0 rows affected (0.00 sec)
mysql>
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! 🙂
Let me know.
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.
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.”
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 thatDEFINER: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…
- The recommendation to alter procedures on MySQL 8.X is to drop them and recreate them with the changes needed.
- Option 1: Running from
mysqlcommand line:-
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 ; Make the substitutions of
<NEWusername>and<NEWhostname>as described above intofix_conf_definer.sql-
Apply the SQL using
mysql:mysql -u <MYSQL_USER_NAME> <NewConfluenceDatabaseName> -p < fix_conf_definer.sql
-
- Option 2: Running from a GUI SQL query tool:
-
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; -
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; Make the substitutions of
<NEWusername>and<NEWhostname>as described above- 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…
-
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 - Open up the
triggers.sqlin a text editor and manually search and replace all the old definer settings to new definer settings.-
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 ...
-
- 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
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
*Use the Comments section for questions
Daily & Exclusive Content
Question : I’m trying to execute a CREATE VIEW statement on a MariaDB 10.5 database. The top part of statement is included here:
CREATE OR REPLACE ALGORITHM = UNDEFINED VIEW `MY_VIEW` AS
select col1,col2,isnumeric(col3) = 0
FROM myTable
The isnumeric function referenced in the statement is a custom function and am including the definition and CREATE statement here.
CREATE DEFINER=`MY_USR’@’%` FUNCTION `isnumeric`(val varchar(1024)) RETURNS tinyint(1)
DETERMINISTIC
return val regexp ‘^(-|\+)?([0-9]+\.[0-9]*|[0-9]*\.[0-9]+|[0-9]+)$’
but getting this error message:
ERROR 1449 (HY000): The user specified as a definer (‘MY_USR’@’%’) does not exist
As added information — I’ve been able to execute CREATE TABLE statements & other other DDL statememts with the same logon — so privileges don’t appear to be an issue. I created all the objects and also executing the statements as root. How can I fix this issue?
Answer: Based on the details presented — the CREATE FUNCTION is using the DEFINER=`MY_USR’@’%`. A few things to mention about using the DEFINER . From the MariaDB documentation — «Each function has an account associated as the definer. By default, the definer is the account that created the function.»
Based on this definition because the FUNCTION CREATE uses the MY_USER@% user and then the login user uses the xff@localhost user, causing MariaDB to think that the current user does not have permission to access the function.
If you rebuild the function without the DEFINER=`MY_USR’@’%` part , and then rerun the statement — it should work.
Read more on MariaDB commands & troubleshooting
MariaDB is number function
Quick access to MariaDB Cheatsheet
Author: Rambler (http://www.dba-ninja.com)
Share:


