Error executing sql commit database is locked asterisk

Модератор: april22

Модератор: april22

Error executing SQL (COMMIT): database is locked

Всем доброго времени,

Проблема такая, в астере постоянно появляется запись:

Код: выделить все
WARNING[23148]: db.c:288 db_execute_sql: Error executing SQL (COMMIT): database is locked

Чисто теоретически я понимаю что такая проблема возможна из-за доступа к базе. Например если одновременные подключения происходят.
Базу использую для записи звонков. Звонки записываются без каких-либо проблем, а предупреждение вылетает. Причем с произвольной переодичностью.

Кто-то сталкивался с такой проблемой? Подскажите как быть или скажите где читать, буду благодарен.

natrox
 
Сообщений: 37
Зарегистрирован: 20 янв 2014, 04:58
Откуда: Иркутская область, г. Усть-Илимск
  • ICQ

Re: Error executing SQL (COMMIT): database is locked

Сообщение Glukinho » 15 окт 2015, 12:16

Что за база и как подключена? Например, если используете приложение MYSQL, есть смысл переключиться на ODBC.

Glukinho
 
Сообщений: 616
Зарегистрирован: 07 янв 2011, 21:05

Re: Error executing SQL (COMMIT): database is locked

Сообщение Glukinho » 20 окт 2015, 13:47

Собственно, сам на днях с этим столкнулся.
Дело было в правах на /var/lib/asterisk/astdb.sqlite3, это внутренняя БД астериска, а вовсе не MySQL или какая-то внешняя база.

Glukinho
 
Сообщений: 616
Зарегистрирован: 07 янв 2011, 21:05


Вернуться в Вопросы новичков

Кто сейчас на форуме

Сейчас этот форум просматривают: нет зарегистрированных пользователей и гости: 7

Содержание

  1. Asterisk Db.C Error Executing Sql Database Is Locked
  2. Asterisk Forums • View topic — asterisk database locked
  3. Db_execute_sql: Error executing SQL (COMMIT): database is .
  4. Asterisk Forums • View topic — Asterisk database locked?
  5. AstDB database is locked error Telium
  6. Database locked? — General Help — FreePBX Community Forums
  7. Asterisk CLI And Database Problem
  8. How to Fix SQLite Error Database is Locked — Error Code 5
  9. Couldn’t execute statment: SQL logic error or missing .
  10. asterisk/res_odbc.c at master · asterisk/asterisk · GitHub
  11. Asterisk Db.C Error Executing Sql Database Is Locked Fixes & Solutions
  12. История изменений [назад]
  13. Asterix проблемы со звонками и звуком
  14. Asterix проблемы со звонками и звуком
  15. История изменений [назад]
  16. Asterix проблемы со звонками и звуком
  17. Asterix проблемы со звонками и звуком
  18. Как разблокировать базу данных SQLite?

Asterisk Db.C Error Executing Sql Database Is Locked

We have collected for you the most relevant information on Asterisk Db.C Error Executing Sql Database Is Locked, as well as possible solutions to this problem. Take a look at the links provided and find the solution that works. Other people have encountered Asterisk Db.C Error Executing Sql Database Is Locked before you, so use the ready-made solutions.

Asterisk Forums • View topic — asterisk database locked

    http://forums.asterisk.org/viewtopic.php?t=90930
    Jul 24, 2014 · You have problems with Asterisk accessing your database. There is no simple answer for this. You will have to debug this by yourself. I would start with Asterisk …

Db_execute_sql: Error executing SQL (COMMIT): database is .

    https://community.freepbx.org/t/db-execute-sql-error-executing-sql-commit-database-is-locked/44779
    Hi, I got this error: [2017-10-13 08:22:01] WARNING[1334]: db.c:288 db_execute_sql: Error executing SQL (COMMIT): database is locked [2017-10-13 08:22:02] WARNING .

Asterisk Forums • View topic — Asterisk database locked?

    http://forums.asterisk.org/viewtopic.php?t=96424
    Return to Asterisk Support Jump to: Select a forum —————— General Announcements Asterisk Biz & Jobs Asterisk Asterisk Support Asterisk General AsteriskNOW AsteriskNOW Support AsteriskNOW General Switchvox SMB and SOHO Switchvox Developers Switchvox Free Edition Digium Software Fax For Asterisk Skype For Asterisk Digium Phone API

AstDB database is locked error Telium

    https://telium.io/en/topic/astdb-database-is-locked-error/
    Jun 28, 2019 · The error you are seeing in the Asterisk CLI is due to an app not properly handling concurrent use of the AstDB (SQLite 3 database). When synchronizing the AstDB HAAst will briefly lock the database (with a SQL lock), at which point apps should queue their commands until the lock …
    https://community.freepbx.org/t/database-locked/32480
    rasterisk -x “database show” will “dump” it’s content. ( redirect that into a text file also JIC.) If restarting asterisk doesn’t fix it and you have no other process using it (which is unlikely apart from occasionally FreePBX reloads), I would probably rename that file while asterisk is stopped, It should be rebuilt on an asterisk .

Asterisk CLI And Database Problem

    https://asteriskfaqs.org/2015/12/22/asterisk-users/asterisk-cli-and-database-problem.html
    Dec 22, 2015 · “asterisk -rv”) as a user with insufficient permissions. I would double check: (1) What user/groups own the various Asterisk directories (specified in your asterisk.conf) (2) What user/group you are running the safe_asterisk script under (3) What user/group you are running as when you attempt to connect to Asterisk

How to Fix SQLite Error Database is Locked — Error Code 5

    https://www.arysontechnologies.com/blog/fix-sqlite-error-database-locked/
    To fix “SQLite database is locked error code 5” the best solution is to create a backup of the database, which will have no locks on it. After that, replace the database with its backup copy. Follow the following script to do the same where.x.Sqlite is the Sqlite database file: $Sqlite3.x.Sqlite

Couldn’t execute statment: SQL logic error or missing .

    https://forum.issabel.org/d/1523-couldn-t-execute-statment-sql-logic-error-or-missing-database
    Hola buenas tardes, Asterisk 11.25.0 CentOS Linux release 7.3.1611 (Core) 4.4.91-1.el7.elrepo.x86_64 #1 SMP Sun Oct 8 08:54:00 EDT 2017 x86_64 x86_64 x86_64 GNU/Linux

asterisk/res_odbc.c at master · asterisk/asterisk · GitHub

    https://github.com/asterisk/asterisk/blob/master/res/res_odbc.c
    * the SQL text is removed from the connection in all cases, so only if it becomes the * new longest executing query do we steal the SQL text. In other cases what will happen * is that the SQL text will be freed if the connection is released back to the class or * if a new query is done on the connection. */ ast_free (obj-> parent-> sql_text);

Asterisk Db.C Error Executing Sql Database Is Locked Fixes & Solutions

We are confident that the above descriptions of Asterisk Db.C Error Executing Sql Database Is Locked and how to fix it will be useful to you. If you have another solution to Asterisk Db.C Error Executing Sql Database Is Locked or some notes on the existing ways to solve it, then please drop us an email.

Источник

История изменений [назад]

Asterix проблемы со звонками и звуком

Есть сервер на Asterisk 12.8.1. Тестирую его с sipml5 и с x-lite 4.8.0

Если звонить с одного клиента sipml5 на другой, то звонок проходит и нет звука нет ни с одной стороны.

Звонки с x-lite не проходят вообще: если звоню с x-lite на sipml5, то пишет «failed to establish call», если с sipml5 на x-lite, то моментально вешается трубка(лог звонка ниже).

В чем может быть проблема?

1

Asterix проблемы со звонками и звуком

Есть сервер на Asterisk 12.8.1. Тестирую его с sipml5 и с x-lite 4.8.0

Если звонить с одного клиента sipml5 на другой, то звонок проходит и нет звука нет ни с одной стороны.

Звонки с x-lite не проходят вообще: если звоню с x-lite на sipml5, то пишет «failed to establish call», если с sipml5 на x-lite, то моментально вешается трубка(лог звонка ниже).

В чем может быть проблема?

Проект компании «АТС Дизайн»
Asterisk ® и Digium ® являются зарегистрированными торговыми марками компании Digium, Inc., США.
IP АТС Asterisk распространяется под лицензией GNU GPL.

Источник

История изменений [назад]

2

Asterix проблемы со звонками и звуком

Есть сервер на Asterisk 12.8.1. Тестирую его с sipml5 и с x-lite 4.8.0

Если звонить с одного клиента sipml5 на другой, то звонок проходит и нет звука нет ни с одной стороны.

Звонки с x-lite не проходят вообще: если звоню с x-lite на sipml5, то пишет «failed to establish call», если с sipml5 на x-lite, то моментально вешается трубка(лог звонка ниже).

В чем может быть проблема?

1

Asterix проблемы со звонками и звуком

Есть сервер на Asterisk 12.8.1. Тестирую его с sipml5 и с x-lite 4.8.0

Если звонить с одного клиента sipml5 на другой, то звонок проходит и нет звука нет ни с одной стороны.

Звонки с x-lite не проходят вообще: если звоню с x-lite на sipml5, то пишет «failed to establish call», если с sipml5 на x-lite, то моментально вешается трубка(лог звонка ниже).

В чем может быть проблема?

Проект компании «АТС Дизайн»
Asterisk ® и Digium ® являются зарегистрированными торговыми марками компании Digium, Inc., США.
IP АТС Asterisk распространяется под лицензией GNU GPL.

Источник

Как разблокировать базу данных SQLite?

Как разблокировать базу данных, чтобы это работало?

В Windows вы можете попробовать эту программу http://www.nirsoft.net/utils/opened_files_view.html, чтобы узнать, как процесс обрабатывает файл БД. Попробуйте закрыть эту программу для разблокировки базы данных

В Linux и macOS вы можете сделать что-то подобное, например, если ваш заблокированный файл — development.db:

Эта команда покажет, какой процесс блокирует файл:

Просто убей процесс .

. И ваша база данных будет разблокирована.

Я вызвал блокировку базы данных sqlite из-за сбоя приложения во время записи. Вот как я это исправил:

Страница DatabaseIsLocked, указанная ниже, больше не доступна. Страница Блокировка и параллелизм файлов описывает изменения, связанные с блокировкой файлов, представленные в версии 3, и может быть полезна для будущих читателей. https://www.sqlite.org/lockingv3.html

Страница SQLite wiki DatabaseIsLocked предлагает хорошее объяснение этого сообщения об ошибке. Отчасти утверждается, что источник разногласий является внутренним (для процесса, выдающего ошибку).

Эта страница не объясняет, как SQLite решает, что что-то в вашем процессе имеет блокировку, и какие условия могут привести к ложному срабатыванию.

Удаление файла -journal звучит как ужасная идея. Он позволяет sqlite откатывать базу данных до согласованного состояния после сбоя. Если вы удалите его, когда база данных находится в несогласованном состоянии, то у вас останется поврежденная база данных. Ссылаясь на страницу с сайта sqlite :

Если происходит сбой или сбой питания, и на диске остается горячий журнал, важно, чтобы исходный файл базы данных и горячий журнал оставались на диске с их исходными именами, пока файл базы данных не будет открыт другим процессом SQLite и откатан , [. ]

Мы подозреваем, что обычный режим сбоя для восстановления SQLite происходит следующим образом: происходит сбой питания. После восстановления питания доброжелательный пользователь или системный администратор начинает осматривать диск на предмет повреждений. Они видят файл своей базы данных с именем «Important.data». Возможно, этот файл им знаком. Но после сбоя есть еще и горячий журнал под названием «важное.данные-журнал». Затем пользователь удаляет горячий журнал, думая, что он помогает очистить систему. Мы не знаем никакого способа предотвратить это, кроме обучения пользователей.

Предполагается, что откат произойдет автоматически при следующем открытии базы данных, но произойдет сбой, если процесс не сможет заблокировать базу данных. Как уже говорили другие, одна из возможных причин этого заключается в том, что в настоящее время этот процесс открыт. Другая возможность — устаревшая блокировка NFS, если база данных находится на томе NFS. В этом случае обходным путем является замена файла базы данных новой копией, которая не заблокирована на сервере NFS (mv database.db original.db; cp original.db database.db). Обратите внимание, что в FAQ по sqlite рекомендуется соблюдать осторожность при одновременном доступе к базам данных на томах NFS из-за ошибочных реализаций блокировки файлов NFS.

Я не могу объяснить, почему удаление файла -journal позволило бы вам заблокировать базу данных, которую вы не могли раньше. Это воспроизводимо?

Кстати, наличие файла -journal не обязательно означает, что произошел сбой или есть изменения, которые необходимо откатить. Sqlite имеет несколько разных режимов ведения журнала, а в режимах PERSIST или TRUNCATE он всегда оставляет файл -journal на своем месте и изменяет его содержимое, чтобы указать, существуют ли частичные транзакции для отката.

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

  1. Скопируйте файл базы данных в другое место.
  2. Замените базу данных на скопированную базу данных. Это разыменует все процессы, которые обращались к вашему файлу базы данных.

Если у процесса есть блокировка на базе данных SQLite и происходит сбой, она остается заблокированной навсегда. Это проблема. Дело не в том, что какой-то другой процесс имеет блокировку.

файлы базы данных SQLite — это просто файлы, поэтому первым шагом было бы убедиться, что они не только для чтения. Другая вещь, которую нужно сделать, — убедиться, что у вас нет какой-либо программы просмотра БД SQLite с графическим интерфейсом при открытой БД. Вы можете открыть базу данных в другой оболочке, или ваш код может открыть базу данных. Обычно это можно увидеть, если в другом потоке или приложении, таком как SQLite Database Browser, БД открыта для записи.

У меня была эта проблема только сейчас, с использованием базы данных SQLite на удаленном сервере, хранящейся в монтировании NFS. SQLite не удалось получить блокировку после того, как сеанс удаленной оболочки, который я использовал, потерпел крах, когда база данных была открыта.

Предложенные выше рецепты восстановления не сработали (включая идею сначала переместить, а затем скопировать базу данных обратно). Но после копирования в систему, отличную от NFS, база данных стала пригодной для использования, и данные, похоже, не были потеряны.

Моя блокировка была вызвана сбоем системы, а не зависанием. Чтобы решить эту проблему, я просто переименовал файл, а затем скопировал его обратно в исходное имя и местоположение.

Использование оболочки Linux, которая была бы .

Я добавил » Pooling=true » в строку подключения, и это сработало.

Я нашел документацию о различных состояниях блокировки в SQLite очень полезной. Майкл, если вы можете выполнять чтение, но не можете выполнять запись в базу данных, это означает, что процесс получил зарезервированную блокировку в вашей базе данных, но еще не выполнил запись. Если вы используете SQLite3, есть новая блокировка, называемая PENDING, в которой больше не разрешено подключать больше процессов, но существующие соединения могут выполнять чтение, поэтому, если это проблема, вы должны рассмотреть ее.

Эта ошибка может быть выдана, если файл находится в удаленной папке, например в общей папке. Я изменил базу данных на локальный каталог, и он работал отлично.

У меня есть такая проблема в приложении, что доступ к SQLite из 2-х подключений — одно только для чтения, а второе для записи и чтения. Похоже, что соединение только для чтения заблокировало запись со второго соединения. Наконец, оказывается, что необходимо завершить или, по крайней мере, сбросить подготовленные операторы НЕМЕДЛЕННО после использования. До тех пор, пока готовый оператор не будет открыт, он вызвал, что база данных была заблокирована для записи.

НЕ ЗАБЫВАЙТЕ ЗВОНИТЬ:

Некоторые функции, такие как INDEX’ing, могут занимать очень много времени и блокировать всю базу данных во время работы. В таких случаях он может даже не использовать файл журнала!

Поэтому лучший / единственный способ проверить, заблокирована ли ваша база данных, потому что процесс АКТИВНО записывает в нее (и, таким образом, вы должны оставить его в покое, пока он не завершит свою работу), — это md5 (или md5sum в некоторых системах) файл дважды , Если вы получаете другую контрольную сумму, база данных пишется, и вы действительно ДЕЙСТВИТЕЛЬНО не хотите уничтожать этот процесс, потому что вы можете легко получить поврежденную таблицу / базу данных, если вы это сделаете.

Я еще раз повторю, потому что это важно — решение НЕ в том, чтобы найти программу блокировки и убить ее, а в том, чтобы найти, есть ли в базе данных блокировка записи по уважительной причине, и пойти дальше. Иногда правильное решение — просто перерыв на кофе.

Единственный способ создать эту заблокированную, но не записываемую ситуацию — это если ваша программа выполняется BEGIN EXCLUSIVE , потому что она хотела внести какие-то изменения в таблицу или что-то еще, то по какой-либо причине никогда не отправляет END потом, и процесс никогда не завершается . Все три выполняемых условия крайне маловероятны в любом правильно написанном коде, и, таким образом, в 99 случаях из 100, когда кто-то хочет уничтожить -9 свой процесс блокировки, процесс блокировки фактически блокирует вашу базу данных по уважительной причине. Программисты обычно не добавляют BEGIN EXCLUSIVE условие, если в этом нет особой необходимости, поскольку оно предотвращает параллелизм и увеличивает количество жалоб пользователей. Сам SQLite добавляет его только тогда, когда это действительно необходимо (например, при индексации).

Наконец, статус «заблокирован» не существует ВНУТРИ файла, как указано в нескольких ответах, — он находится в ядре операционной системы. Запущенный процесс BEGIN EXCLUSIVE запросил у ОС блокировку файла. Даже если ваш эксклюзивный процесс потерпел крах, ваша ОС сможет выяснить, должна ли она поддерживать блокировку файла или нет !! Невозможно получить базу данных, которая заблокирована, но ни один процесс не блокирует ее активно !! Когда дело доходит до выяснения, какой процесс блокирует файл, обычно лучше использовать lsof, а не fuser (это хорошая демонстрация того, почему: /unix/94316/fuser-vs-lsof- проверять используемые файлы ). Кроме того, если у вас есть DTrace (OSX), вы можете использовать iosnoop для файла.

Источник

Adblock
detector

2

Db_execute_sql: Error Executing SQL (COMMIT): Database Is Locked

Home » Asterisk Users » Db_execute_sql: Error Executing SQL (COMMIT): Database Is Locked

December 23, 2020


Asterisk Users

No Comments

In: /var/lib/asterisk
-rw-r–r– 1 asterisk asterisk 12288 Dec 23 10:52 astdb.sqlite3

ast_db_put: Couldn’t execute statement: SQL logic error ast_db_put: Couldn’t execute statement: attempt to write a readonly database db_execute_sql: Error executing SQL (COMMIT): database is locked

The astdb.sqlite3 was root:root but I change it to asterisk:asterisk and I still getting these error messages

In windows you can try this program http://www.nirsoft.net/utils/opened_files_view.html to find out the process is handling db file. Try closed that program for unlock database

In Linux and macOS you can do something similar, for example, if your locked file is development.db:

$ fuser development.db

This command will show what process is locking the file:

> development.db: 5430

Just kill the process…

kill -9 5430

…And your database will be unlocked.

guruz's user avatar

guruz

1,58413 silver badges21 bronze badges

answered Aug 13, 2010 at 22:37

noneno's user avatar

nonenononeno

3,2441 gold badge15 silver badges5 bronze badges

8

The SQLite wiki DatabaseIsLocked page offers an explanation of this error message. It states, in part, that the source of contention is internal (to the process emitting the error). What this page doesn’t explain is how SQLite decides that something in your process holds a lock and what conditions could lead to a false positive.

This error code occurs when you try to do two incompatible things with a database at the same time from the same database connection.


Changes related to file locking introduced in v3 and may be useful for future readers and can be found here: File Locking And Concurrency In SQLite Version 3

Ярослав Рахматуллин's user avatar

answered Oct 20, 2008 at 14:24

converter42's user avatar

converter42converter42

7,3312 gold badges28 silver badges24 bronze badges

2

If you want to remove a «database is locked» error then follow these steps:

  1. Copy your database file to some other location.
  2. Replace the database with the copied database. This will dereference all processes which were accessing your database file.

animuson's user avatar

animuson

53.2k28 gold badges142 silver badges147 bronze badges

answered Mar 7, 2013 at 12:28

vinayak jadi's user avatar

2

Deleting the -journal file sounds like a terrible idea. It’s there to allow sqlite to roll back the database to a consistent state after a crash. If you delete it while the database is in an inconsistent state, then you’re left with a corrupted database. Citing a page from the sqlite site:

If a crash or power loss does occur and a hot journal is left on the disk, it is essential that the original database file and the hot journal remain on disk with their original names until the database file is opened by another SQLite process and rolled back. […]

We suspect that a common failure mode for SQLite recovery happens like this: A power failure occurs. After power is restored, a well-meaning user or system administrator begins looking around on the disk for damage. They see their database file named «important.data». This file is perhaps familiar to them. But after the crash, there is also a hot journal named «important.data-journal». The user then deletes the hot journal, thinking that they are helping to cleanup the system. We know of no way to prevent this other than user education.

The rollback is supposed to happen automatically the next time the database is opened, but it will fail if the process can’t lock the database. As others have said, one possible reason for this is that another process currently has it open. Another possibility is a stale NFS lock, if the database is on an NFS volume. In that case, a workaround is to replace the database file with a fresh copy that isn’t locked on the NFS server (mv database.db original.db; cp original.db database.db). Note that the sqlite FAQ recommends caution regarding concurrent access to databases on NFS volumes, because of buggy implementations of NFS file locking.

I can’t explain why deleting a -journal file would let you lock a database that you couldn’t before. Is that reproducible?

By the way, the presence of a -journal file doesn’t necessarily mean that there was a crash or that there are changes to be rolled back. Sqlite has a few different journal modes, and in PERSIST or TRUNCATE modes it leaves the -journal file in place always, and changes the contents to indicate whether or not there are partial transactions to roll back.

Community's user avatar

answered Jun 22, 2009 at 14:25

Aaron's user avatar

AaronAaron

6085 silver badges8 bronze badges

0

the SQLite db files are just files, so the first step would be to make sure it isn’t read-only. The other thing to do is to make sure that you don’t have some sort of GUI SQLite DB viewer with the DB open. You could have the DB open in another shell, or your code may have the DB open. Typically you would see this if a different thread, or application such as SQLite Database Browser has the DB open for writing.

answered Sep 29, 2008 at 22:39

Heat Miser's user avatar

Heat MiserHeat Miser

19.4k7 gold badges34 silver badges38 bronze badges

2

My lock was caused by the system crashing and not by a hanging process. To resolve this, I simply renamed the file then copied it back to its original name and location.

Using a Linux shell that would be:

mv mydata.db temp.db
cp temp.db mydata.db

TarHalda's user avatar

TarHalda

9531 gold badge7 silver badges25 bronze badges

answered Aug 4, 2009 at 11:02

Ben L's user avatar

Ben LBen L

6,4708 gold badges39 silver badges34 bronze badges

0

If a process has a lock on an SQLite DB and crashes, the DB stays locked permanently. That’s the problem. It’s not that some other process has a lock.

answered Jan 29, 2009 at 22:58

2

I had this problem just now, using an SQLite database on a remote server, stored on an NFS mount. SQLite was unable to obtain a lock after the remote shell session I used had crashed while the database was open.

The recipes for recovery suggested above did not work for me (including the idea to first move and then copy the database back). But after copying it to a non-NFS system, the database became usable and not data appears to have been lost.

answered Jun 16, 2011 at 3:19

jogojapan's user avatar

jogojapanjogojapan

67.5k11 gold badges97 silver badges131 bronze badges

Some functions, like INDEX’ing, can take a very long time — and it locks the whole database while it runs. In instances like that, it might not even use the journal file!

So the best/only way to check if your database is locked because a process is ACTIVELY writing to it (and thus you should leave it the hell alone until its completed its operation) is to md5 (or md5sum on some systems) the file twice.
If you get a different checksum, the database is being written, and you really really REALLY don’t want to kill -9 that process because you can easily end up with a corrupt table/database if you do.

I’ll reiterate, because it’s important — the solution is NOT to find the locking program and kill it — it’s to find if the database has a write lock for a good reason, and go from there. Sometimes the correct solution is just a coffee break.

The only way to create this locked-but-not-being-written-to situation is if your program runs BEGIN EXCLUSIVE, because it wanted to do some table alterations or something, then for whatever reason never sends an END afterwards, and the process never terminates. All three conditions being met is highly unlikely in any properly-written code, and as such 99 times out of 100 when someone wants to kill -9 their locking process, the locking process is actually locking your database for a good reason. Programmers don’t typically add the BEGIN EXCLUSIVE condition unless they really need to, because it prevents concurrency and increases user complaints. SQLite itself only adds it when it really needs to (like when indexing).

Finally, the ‘locked’ status does not exist INSIDE the file as several answers have stated — it resides in the Operating System’s kernel. The process which ran BEGIN EXCLUSIVE has requested from the OS a lock be placed on the file. Even if your exclusive process has crashed, your OS will be able to figure out if it should maintain the file lock or not!! It is not possible to end up with a database which is locked but no process is actively locking it!!
When it comes to seeing which process is locking the file, it’s typically better to use lsof rather than fuser (this is a good demonstration of why: https://unix.stackexchange.com/questions/94316/fuser-vs-lsof-to-check-files-in-use). Alternatively if you have DTrace (OSX) you can use iosnoop on the file.

Community's user avatar

answered Feb 19, 2015 at 16:05

J.J's user avatar

J.JJ.J

3,3491 gold badge27 silver badges35 bronze badges

I added «Pooling=true» to connection string and it worked.

shA.t's user avatar

shA.t

16.4k5 gold badges53 silver badges111 bronze badges

answered Mar 8, 2016 at 9:49

user1900210's user avatar

0

This error can be thrown if the file is in a remote folder, like a shared folder. I changed the database to a local directory and it worked perfectly.

answered Sep 12, 2012 at 20:29

Zequez's user avatar

ZequezZequez

3,3492 gold badges30 silver badges42 bronze badges

0

I found the documentation of the various states of locking in SQLite to be very helpful. Michael, if you can perform reads but can’t perform writes to the database, that means that a process has gotten a RESERVED lock on your database but hasn’t executed the write yet. If you’re using SQLite3, there’s a new lock called PENDING where no more processes are allowed to connect but existing connections can sill perform reads, so if this is the issue you should look at that instead.

answered Nov 14, 2008 at 18:44

Kyle Cronin's user avatar

Kyle CroninKyle Cronin

76.9k42 gold badges148 silver badges163 bronze badges

I have such problem within the app, which access to SQLite from 2 connections — one was read-only and second for writing and reading. It looks like that read-only connection blocked writing from second connection. Finally, it is turns out that it is required to finalize or, at least, reset prepared statements IMMEDIATELY after use. Until prepared statement is opened, it caused to database was blocked for writing.

DON’T FORGET CALL:

sqlite_reset(xxx);

or

sqlite_finalize(xxx);

answered Feb 17, 2012 at 18:39

Mike Keskinov's user avatar

Mike KeskinovMike Keskinov

11.5k6 gold badges60 silver badges86 bronze badges

I just had something similar happen to me — my web application was able to read from the database, but could not perform any inserts or updates. A reboot of Apache solved the issue at least temporarily.

It’d be nice, however, to be able to track down the root cause.

answered Nov 14, 2008 at 18:37

Michael Cox's user avatar

Michael CoxMichael Cox

1,28113 silver badges15 bronze badges

0

lsof command on my Linux environment helped me to figure it out that a process was hanging keeping the file open.
Killed the process and problem was solved.

answered Sep 16, 2011 at 20:29

PinkSheep's user avatar

PinkSheepPinkSheep

4152 gold badges4 silver badges12 bronze badges

This link solve the problem. : When Sqlite gives : Database locked error
It solved my problem may be useful to you.

And you can use begin transaction and end transaction to not make database locked in future.

Community's user avatar

answered May 16, 2013 at 5:50

shreeji's user avatar

0

Should be a database’s internal problem…
For me it has been manifested after trying to browse database with «SQLite manager»…
So, if you can’t find another process connect to database and you just can’t fix it,
just try this radical solution:

  1. Provide to export your tables (You can use «SQLite manager» on Firefox)
  2. If the migration alter your database scheme delete the last failed migration
  3. Rename your «database.sqlite» file
  4. Execute «rake db:migrate» to make a new working database
  5. Provide to give the right permissions to database for table’s importing
  6. Import your backed up tables
  7. Write the new migration
  8. Execute it with «rake db:migrate«

shA.t's user avatar

shA.t

16.4k5 gold badges53 silver badges111 bronze badges

answered Apr 3, 2011 at 11:49

Davide Ganz's user avatar

0

In my experience, this error is caused by: You opened multiple connections.

e.g.:

  1. 1 or more sqlitebrowser (GUI)
  2. 1 or more electron thread
  3. rails thread

I am nore sure about the details of SQLITE3 how to handle the multiple thread/request, but when I close the sqlitebrowser and electron thread, then rails is running well and won’t block any more.

answered Apr 18, 2021 at 9:19

Siwei's user avatar

SiweiSiwei

18.6k5 gold badges71 silver badges93 bronze badges

I ran into this same problem on Mac OS X 10.5.7 running Python scripts from a terminal session. Even though I had stopped the scripts and the terminal window was sitting at the command prompt, it would give this error the next time it ran. The solution was to close the terminal window and then open it up again. Doesn’t make sense to me, but it worked.

answered Jun 12, 2009 at 20:20

Shawn Swaner's user avatar

Shawn SwanerShawn Swaner

10.4k1 gold badge21 silver badges14 bronze badges

I just had the same error.
After 5 minets google-ing I found that I didun’t closed one shell witch were using the db.
Just close it and try again ;)

answered Dec 15, 2011 at 9:11

MightyPixel's user avatar

I had the same problem. Apparently the rollback function seems to overwrite the db file with the journal which is the same as the db file but without the most recent change. I’ve implemented this in my code below and it’s been working fine since then, whereas before my code would just get stuck in the loop as the database stayed locked.

Hope this helps

my python code

##############
#### Defs ####
##############
def conn_exec( connection , cursor , cmd_str ):
    done        = False
    try_count   = 0.0
    while not done:
        try:
            cursor.execute( cmd_str )
            done = True
        except sqlite.IntegrityError:
            # Ignore this error because it means the item already exists in the database
            done = True
        except Exception, error:
            if try_count%60.0 == 0.0:       # print error every minute
                print "t" , "Error executing command" , cmd_str
                print "Message:" , error

            if try_count%120.0 == 0.0:      # if waited for 2 miutes, roll back
                print "Forcing Unlock"
                connection.rollback()

            time.sleep(0.05)    
            try_count += 0.05


def conn_comit( connection ):
    done        = False
    try_count   = 0.0
    while not done:
        try:
            connection.commit()
            done = True
        except sqlite.IntegrityError:
            # Ignore this error because it means the item already exists in the database
            done = True
        except Exception, error:
            if try_count%60.0 == 0.0:       # print error every minute
                print "t" , "Error executing command" , cmd_str
                print "Message:" , error

            if try_count%120.0 == 0.0:      # if waited for 2 miutes, roll back
                print "Forcing Unlock"
                connection.rollback()

            time.sleep(0.05)    
            try_count += 0.05       




##################
#### Run Code ####
##################
connection = sqlite.connect( db_path )
cursor = connection.cursor()
# Create tables if database does not exist
conn_exec( connection , cursor , '''CREATE TABLE IF NOT EXISTS fix (path TEXT PRIMARY KEY);''')
conn_exec( connection , cursor , '''CREATE TABLE IF NOT EXISTS tx (path TEXT PRIMARY KEY);''')
conn_exec( connection , cursor , '''CREATE TABLE IF NOT EXISTS completed (fix DATE, tx DATE);''')
conn_comit( connection )

answered Feb 17, 2012 at 11:56

Jay's user avatar

JayJay

3,2596 gold badges37 silver badges52 bronze badges

One common reason for getting this exception is when you are trying to do a write operation while still holding resources for a read operation. For example, if you SELECT from a table, and then try to UPDATE something you’ve selected without closing your ResultSet first.

answered Oct 24, 2012 at 17:33

Martin's user avatar

MartinMartin

7,5519 gold badges48 silver badges82 bronze badges

I was having «database is locked» errors in a multi-threaded application as well, which appears to be the SQLITE_BUSY result code, and I solved it with setting sqlite3_busy_timeout to something suitably long like 30000.

(On a side-note, how odd that on a 7 year old question nobody found this out already! SQLite really is a peculiar and amazing project…)

answered Mar 2, 2016 at 22:38

Stijn Sanders's user avatar

Stijn SandersStijn Sanders

35.6k11 gold badges44 silver badges67 bronze badges

1

Before going down the reboot option, it is worthwhile to see if you can find the user of the sqlite database.

On Linux, one can employ fuser to this end:

$ fuser database.db

$ fuser database.db-journal

In my case I got the following response:

philip    3556  4700  0 10:24 pts/3    00:00:01 /usr/bin/python manage.py shell

Which showed that I had another Python program with pid 3556 (manage.py) using the database.

Serge Stroobandt's user avatar

answered Jun 21, 2010 at 10:45

Philip Clarke's user avatar

An old question, with a lot of answers, here’s the steps I’ve recently followed reading the answers above, but in my case the problem was due to cifs resource sharing. This case is not reported previously, so hope it helps someone.

  • Check no connections are left open in your java code.
  • Check no other processes are using your SQLite db file with lsof.
  • Check the user owner of your running jvm process has r/w permissions over the file.
  • Try to force the lock mode on the connection opening with

    final SQLiteConfig config = new SQLiteConfig();
    
    config.setReadOnly(false);
    
    config.setLockingMode(LockingMode.NORMAL);
    
    connection = DriverManager.getConnection(url, config.toProperties());
    

If your using your SQLite db file over a NFS shared folder, check this point of the SQLite faq, and review your mounting configuration options to make sure your avoiding locks, as described here:

//myserver /mymount cifs username=*****,password=*****,iocharset=utf8,sec=ntlm,file,nolock,file_mode=0700,dir_mode=0700,uid=0500,gid=0500 0 0

shA.t's user avatar

shA.t

16.4k5 gold badges53 silver badges111 bronze badges

answered Apr 20, 2016 at 10:31

kothvandir's user avatar

kothvandirkothvandir

2,0712 gold badges19 silver badges33 bronze badges

I got this error in a scenario a little different from the ones describe here.

The SQLite database rested on a NFS filesystem shared by 3 servers. On 2 of the servers I was able do run queries on the database successfully, on the third one thought I was getting the «database is locked» message.

The thing with this 3rd machine was that it had no space left on /var. Everytime I tried to run a query in ANY SQLite database located in this filesystem I got the «database is locked» message and also this error over the logs:

Aug 8 10:33:38 server01 kernel: lockd: cannot monitor 172.22.84.87

And this one also:

Aug 8 10:33:38 server01 rpc.statd[7430]: Failed to insert: writing /var/lib/nfs/statd/sm/other.server.name.com: No space left on device
Aug 8 10:33:38 server01 rpc.statd[7430]: STAT_FAIL to server01 for SM_MON of 172.22.84.87

After the space situation was handled everything got back to normal.

shA.t's user avatar

shA.t

16.4k5 gold badges53 silver badges111 bronze badges

answered Aug 9, 2016 at 3:21

ederribeiro's user avatar

ederribeiroederribeiro

3881 gold badge3 silver badges15 bronze badges

If you’re trying to unlock the Chrome database to view it with SQLite, then just shut down Chrome.

Windows

%userprofile%Local SettingsApplication DataGoogleChromeUser DataDefaultWeb Data

or

%userprofile%Local SettingsApplication DataGoogleChromeUser DataDefaultChrome Web Data

Mac

~/Library/Application Support/Google/Chrome/Default/Web Data

answered Feb 25, 2018 at 20:51

Bob Stein's user avatar

Bob SteinBob Stein

15.5k10 gold badges82 silver badges98 bronze badges

From your previous comments you said a -journal file was present.

This could mean that you have opened and (EXCLUSIVE?) transaction and have not yet committed the data. Did your program or some other process leave the -journal behind??

Restarting the sqlite process will look at the journal file and clean up any uncommitted actions and remove the -journal file.

answered Dec 29, 2008 at 1:44

daivd camerondaivd cameron

As Seun Osewa has said, sometimes a zombie process will sit in the terminal with a lock aquired, even if you don’t think it possible. Your script runs, crashes, and you go back to the prompt, but there’s a zombie process spawned somewhere by a library call, and that process has the lock.

Closing the terminal you were in (on OSX) might work. Rebooting will work. You could look for «python» processes (for example) that are not doing anything, and kill them.

answered Jan 7, 2010 at 5:51

wisty's user avatar

wistywisty

6,9371 gold badge30 silver badges29 bronze badges

Asterix проблемы со звонками и звуком

Есть сервер на Asterisk 12.8.1. Тестирую его с sipml5 и с x-lite 4.8.0

Если звонить с одного клиента sipml5 на другой, то звонок проходит и нет звука нет ни с одной стороны.

       == Using SIP VIDEO CoS mark 6
  == Using SIP RTP CoS mark 5
    -- Executing [102@from-internal:1] NoOp("SIP/103-00000236", "webrtc test call") in new stack
    -- Executing [102@from-internal:2] Dial("SIP/103-00000236", "SIP/102") in new stack
  == Using SIP VIDEO CoS mark 6
  == Using SIP RTP CoS mark 5
    -- Called SIP/102
    -- SIP/102-00000237 is ringing
    -- SIP/102-00000237 answered SIP/103-00000236
    -- Channel SIP/103-00000236 joined 'simple_bridge' basic-bridge <06cd696a-ecb1-4027-b27b-072e2ae675ae>
    -- Channel SIP/102-00000237 joined 'simple_bridge' basic-bridge <06cd696a-ecb1-4027-b27b-072e2ae675ae>

Звонки с x-lite не проходят вообще: если звоню с x-lite на sipml5, то пишет «failed to establish call», если с sipml5 на x-lite, то моментально вешается трубка(лог звонка ниже).

== Using SIP VIDEO CoS mark 6
      == Using SIP RTP CoS mark 5
        -- Executing [101@from-internal:1] NoOp("SIP/102-00000231", "webrtc test call") in new stack
        -- Executing [101@from-internal:2] Dial("SIP/102-00000231", "SIP/101") in new stack
      == Using SIP VIDEO CoS mark 6
      == Using SIP RTP CoS mark 5
        -- Called SIP/101
        -- SIP/101-00000232 is ringing
    [Apr 22 13:29:41] WARNING[19547]: db.c:288 db_execute_sql: Error executing SQL (COMMIT): database is locked
    [Apr 22 13:29:49] NOTICE[19573]: chan_sip.c:28033 handle_request_register: Registration from '"2401" <sip:2401@80.243.15.29:5060>' failed for '91.236.75.139:5077' - Wrong password
      == Everyone is busy/congested at this time (1:0/0/1)
        -- Executing [101@from-internal:3] Hangup("SIP/102-00000231", "") in new stack

В чем может быть проблема?

Asterix Asterisk проблемы со звонками и звуком

Есть сервер на Asterisk 12.8.1. Тестирую его с sipml5 и с x-lite 4.8.0

Если звонить с одного клиента sipml5 на другой, то звонок проходит и нет звука нет ни с одной стороны.

       == Using SIP VIDEO CoS mark 6
  == Using SIP RTP CoS mark 5
    -- Executing [102@from-internal:1] NoOp("SIP/103-00000236", "webrtc test call") in new stack
    -- Executing [102@from-internal:2] Dial("SIP/103-00000236", "SIP/102") in new stack
  == Using SIP VIDEO CoS mark 6
  == Using SIP RTP CoS mark 5
    -- Called SIP/102
    -- SIP/102-00000237 is ringing
    -- SIP/102-00000237 answered SIP/103-00000236
    -- Channel SIP/103-00000236 joined 'simple_bridge' basic-bridge <06cd696a-ecb1-4027-b27b-072e2ae675ae>
    -- Channel SIP/102-00000237 joined 'simple_bridge' basic-bridge <06cd696a-ecb1-4027-b27b-072e2ae675ae>

Звонки с x-lite не проходят вообще: если звоню с x-lite на sipml5, то пишет «failed to establish call», если с sipml5 на x-lite, то моментально вешается трубка(лог звонка ниже).

== Using SIP VIDEO CoS mark 6
      == Using SIP RTP CoS mark 5
        -- Executing [101@from-internal:1] NoOp("SIP/102-00000231", "webrtc test call") in new stack
        -- Executing [101@from-internal:2] Dial("SIP/102-00000231", "SIP/101") in new stack
      == Using SIP VIDEO CoS mark 6
      == Using SIP RTP CoS mark 5
        -- Called SIP/101
        -- SIP/101-00000232 is ringing
    [Apr 22 13:29:41] WARNING[19547]: db.c:288 db_execute_sql: Error executing SQL (COMMIT): database is locked
    [Apr 22 13:29:49] NOTICE[19573]: chan_sip.c:28033 handle_request_register: Registration from '"2401" <sip:2401@80.243.15.29:5060>' failed for '91.236.75.139:5077' - Wrong password
      == Everyone is busy/congested at this time (1:0/0/1)
        -- Executing [101@from-internal:3] Hangup("SIP/102-00000231", "") in new stack

В чем может быть проблема?

Понравилась статья? Поделить с друзьями:
  • Error executing program error code 2
  • Error executing maven unable to load cache item
  • Error executing image transfer script error copying
  • Error executing gpgv to check release signature
  • Error executing file запрошенная операция требует повышения windows 7