Error executing sql pragma synchronous normal

Пытаюсь синхронизировать Windows версию с Anroid версией. После нажатия кнопки "Синхронизировать" выполняется бэкап и тут-же появляется окно с текстом ошибки:"Error executing SQL "PRAGMA SYNCHRONOUS=NORMAL;" : file is encrypted or is not a database."Как быть?

Ошибка при синхронизации

enjoyyourself

Старейшина
Сообщения: 116
Зарегистрирован: 05 авг 2010, 22:26

Ошибка при синхронизации

Пытаюсь синхронизировать Windows версию с Anroid версией. После нажатия кнопки «Синхронизировать» выполняется бэкап и тут-же появляется окно с текстом ошибки:
«Error executing SQL «PRAGMA SYNCHRONOUS=NORMAL;» : file is encrypted or is not a database.»
Как быть?


Аватара пользователя

Keepsoft

Администратор
Сообщения: 3648
Зарегистрирован: 20 мар 2008, 18:03
Контактная информация:

Re: Ошибка при синхронизации

Сообщение Keepsoft » 27 май 2021, 00:15

enjoyyourself писал(а):Пытаюсь синхронизировать Windows версию с Anroid версией. После нажатия кнопки «Синхронизировать» выполняется бэкап и тут-же появляется окно с текстом ошибки:
«Error executing SQL «PRAGMA SYNCHRONOUS=NORMAL;» : file is encrypted or is not a database.»
Как быть?

Обновите, пожалуйста, обе версии Домашней бухгалтерии и перезапустите свой смартфон.

С уважением, Keepsoft.



Аватара пользователя

Keepsoft

Администратор
Сообщения: 3648
Зарегистрирован: 20 мар 2008, 18:03
Контактная информация:

Re: Ошибка при синхронизации

Сообщение Keepsoft » 31 май 2021, 13:57

enjoyyourself писал(а):К сожалению обновить не могу. Без обновления проблему не решить?

Скорее всего нет, не решить.

С уважением, Keepsoft.


enjoyyourself

Старейшина
Сообщения: 116
Зарегистрирован: 05 авг 2010, 22:26

Re: Ошибка при синхронизации

Сообщение enjoyyourself » 02 июн 2021, 14:56

Решил с помощью установки галки на «Сбросить истроию синхронизации …».
Ну вы хоть попытались..



Вернуться в «Общие вопросы»

Кто сейчас на конференции

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

Время прочтения
9 мин

Просмотры 189K

Первая часть — вводная.
Вторая часть — быстрый старт.

Третья часть — тонкости и особенности.

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

Поскольку, опять-таки, информации очень много, то формат статьи будет такой: небольшая вводная в интересную тему и ссылка на родной сайт, где подробности. Сайт, увы, на английском.

Использование SQLite в многопоточных приложениях

SQLite может быть собран в однопоточном варианте (параметр компиляции SQLITE_THREADSAFE = 0).

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

Проверить, есть ли многопоточность можно через вызов sqlite3_threadsafe(): если вернула 0, то это однопоточный SQLite.

По умолчанию, SQLite собран с поддержкой потоков (sqlite3.dll).

Есть два способа использования многопоточного SQLite: serialized и multi-thread.

Serialized (надо указать флаг SQLITE_OPEN_FULLMUTEX при открытии соединения). В этом режиме потоки могут как угодно дергать вызовы SQLite, никаких ограничений. Но все вызовы блокируют друг друга и обрабатываются строго последовательно.

Multi-thread (SQLITE_OPEN_NOMUTEX). В этом режиме нельзя использовать одно и то же соединение одновременно из нескольких потоков (но допускается одновременное использование разных соединений разными потоками). Обычно используется именно этот режим.

Узнать больше

Формат данных

База данных SQLite может хранить (текстовые) данные в UTF-8 или UTF-16.

Набор вызовов API состоит из вызовов, которые получают UTF-8 (sqlite3_XXX) и вызовов, которые получают UTF-16 (sqlite3_XXX16).

Если тип данных интерфейса и соединения не совпадает, то выполняется конвертация «на лету».

Всегда используйте UTF-8.

Поддержка UNICODE

По умолчанию — нету поддержки. Надо создать свой collation (способ сравнения) через sqlite3_create_collation .
И определить свои встроенные функции like(), upper(), lower() через www.sqlite.org/c3ref/create_function.html.

Есть такой проект «International Components for Unicode», ICU.

И некоторые собирают SQLite DLL уже с ним.

Как использовать ICU в SQLite.

Наткнулся на статью на хабре.

Типы данных и сравнение значений

Как уже говорилось, SQLIte позволяет записать в любой столбец любое значение.

Значение внутри БД может принадлежать к одному из следующих типов хранения (storage class):
NULL,
INTEGER (занимает 1,2,3,4,6 или 8 байт),
REAL (число с плавающей точкой, 8 байт в формате IEEE),
TEXT (строка в формате данных базы, обычно UTF-8),
BLOB (двоичные данные, хранятся «как есть»).

Порядок сортировки значений разных типов:
NULL меньше всего (включая другой NULL);
INTEGER и REAL меньше любого TEXT и BLOB, между собой сравниваются арифметически;
TEXT меньше любого BLOB, между собой сравниваются на базе своих collation;
BLOB-ы сравниваются между собой через memcmp().

SQLite выполняет неявные преобразования типов «на лету» в нескольких местах:
— при занесении значения в столбец (тип столбца задает рекомендацию по преобразованию);
— при сравнении значений между собой.

Столбец может иметь следующие

рекомендации приведения типа

: TEXT, NUMERIC, INTEGER, REAL, NONE.

Значения BLOB и NULL всегда заносятся в любой столбец «как есть».

В столбец TEXT значения TEXT заносятся «как есть», значения INTEGER и REAL становятся строками.
В столбец NUMERIC, INTEGER числа записываются «как есть», а строки становятся числами, если _могут_ (то есть допустимо обратное преобразование «без потерь»).
Для столбца REAL правила похожи на INTEGER(NUMERIC); отличие в том, что все числа представлены в формате с плавающей запятой.
В столбец NONE значения заносятся «как есть» (этот тип используется по умолчанию, если не задан другой).

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

При сравнении числа со строкой, если строка может быть преобразована в число «без потерь», она становится числом.

Узнать больше

Отмечу здесь, что в SQLite в уникальном индексе может быть сколько угодно NULL значений (с этим согласен Oracle и не согласен MS SQL).

База данных в памяти

Если в вызове sqlite3_open() передать имя файла как «:memory:», то SQLite создаст соединение к новой (чистой) БД

в памяти

.

Это соединение абсолютно неотличимо от соединения к БД в файле по логике использования: доступен тот же набор SQL команд.

Увы, не существует возможности открыть два соединения к одной и той же БД в памяти.

UPD: Уже, оказывается, можно открыть два соединения к одной БД в памяти.

rc = sqlite3_open("file:memdb1?mode=memory&cache=shared", &db);
ATTACH DATABASE 'file:memdb1?mode=memory&cache=shared' AS aux1;

Узнать больше.

Присоединение одновременно к нескольким БД

Чтобы открыть соединение к БД используется вызов sqlite3_open().

В любой момент времени мы можем к открытому соединению

присоединить

еще до 10 баз данных через SQL команду ATTACH DATABASE.

sqlite3_open('foo.sqlite3', &db); // откроем соединение к БД в файле "foo.sqlite3"

sqlite3_exec(&db, "ATTACH 'bar.sqlite3' AS bar", ... ); // присоединим "bar.sqlite3"

Теперь все таблицы БД в файле db1.sqlite3 стали прозрачно доступны в нашем соединении.

Для разрешения конфликтов имен следует использовать имя присоединения (основная база называется «main»):

SELECT * FROM main.my_table UNION SELECT * FROM bar.my_table

Ничего не мешает присоединить к БД новую базу в памяти и использовать ее для кэширования и пр.

sqlite3_open('foo.sqlite3', &db); // откроем соединение к БД в файле "foo.sqlite3"

sqlite3_exec(&db, "ATTACH ':memory:' AS mem", ... ); // присоединим новую БД в памяти

Узнать больше

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

Временная база данных

Передайте пустую строку вместо имени файла в sqlite3_open() и будет создана временная БД в файле на диске. Причем, после закрытия соединения к БД, она будет удалена с диска.

Тонкие настройки БД через команду PRAGMA

SQL команда PRAGMA служит для задания всевозможных настроек у соединения или у самой БД:

  PRAGMA name; // запросить текущее значение параметра name

  PRAGMA name = value; // задать параметр name значением value

Настройку соединения (очевидно) следует проводить сразу после открытия и до его использования.

Полное описание всех параметров находится здесь.

Остановлюсь на важнейших вещах.

PRAGMA page_size = bytes; // размер страницы БД; страница БД - это единица обмена между диском и кэшом, разумно сделать равным размеру кластера диска (у меня 4096)

PRAGMA cache_size = -kibibytes; // задать размер кэша соединения в килобайтах, по умолчанию он равен 2000 страниц БД

PRAGMA encoding = "UTF-8";  // тип данных БД, всегда используйте UTF-8

PRAGMA foreign_keys = 1; // включить поддержку foreign keys, по умолчанию - ОТКЛЮЧЕНА

PRAGMA journal_mode = DELETE | TRUNCATE | PERSIST | MEMORY | WAL | OFF;  // задать тип журнала, см. далее

PRAGMA synchronous = 0 | OFF | 1 | NORMAL | 2 | FULL; // тип синхронизации транзакции, см. далее
Журнал и фиксация транзакций

Вот и подошли к теме, овладение которой сразу переводит вас на третий уровень магистра SQLite.

SQLite тщательно блюдет целостность данных в БД (ACID), реализуя механизм изменения данных через транзакции.

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

Если вы не используете транзакции явно (BEGIN; …; COMMIT;), то

всегда создается неявная транзакция

. Она стартует перед выполнением команды и коммитится сразу после.

Отсюда, кстати, и жалобы на «медленность» SQLite. SQLite может вставлять и до 50 тыс записей в секунду, но

фиксировать транзакций

он не может больше, чем ~ 50 в секунду.

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

При настройках по умолчанию SQLite гарантирует целостность БД даже при отключении питания в процессе работы.

Достигается подобное изумительное поведение ведением журнала (специального файла) и хитроумным механизмом синхронизации изменений на диске.

Кратенько обновление данных в БД работает так:

— до любой модификации БД SQLite сохраняет изменяемые страницы из БД в отдельном файле (журнале), то есть просто копирует их туда;
— убедившись, что копия страниц создана, SQLite начинает менять БД;
— убедившись, что все изменения в БД «дошли до диска» и БД стала целостной, SQLite стирает журнал.

Подробно атомарность механизма транзакций описана тут.

Если SQLite открывает соединение к БД и видит, что журнал уже есть, он соображает, что БД находится в незавершенном состоянии и автоматически откатывает последнюю транзакцию.

То есть механизм восстановления БД после сбоев, фактически, встроен в SQLite и работает незаметно для пользователя.

По умолчанию журнал ведется в режиме DELETE .

PRAGMA journal_mode = DELETE

Это означает, что файл журнала удаляется после завершения транзакции. Сам факт наличия файла с журналом в этом режиме означает для SQLite, что транзакция не была завершена, база нуждается в восстановлении. Файл журнала имеет имя файла БД, к которому добавлено «-journal».

В режиме TRUNCATE файл журнала обрезается до нуля (на некоторых системах это работает быстрее, чем удаление файла).

В режиме PERSIST начало файла журнала забивается нулями (при этом его размер не меняется и он может занимать кучу места).

В режиме MEMORY файл журнала ведется в памяти и это работает быстро, но не гарантирует восстановление базы при сбоях (копии данных-то нету на диске).

А можно и совсем отключить журнал (PRAGMA journal_mode = OFF). В этой ситуации перестает работать откат транзакций (команда ROLLBACK) и база, скорее всего, испортится, если программа будет завершена аварийно.

Для базы данных в памяти режим журнала может быть только либо MEMORY, либо OFF.

Вернемся немного назад. Как же SQLite «убеждается», что база всегда будет целостной?

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

Допустим, SQLite завершил запись в БД и хочет стереть файл журнала, чтобы отметить факт фиксации транзакции.

А вдруг файл сотрется раньше, чем обновится БД?

Если в этот промежуток времени отключится питание, то журнала уже не будет, а БД еще не будет целостной — потеря данных!

Короче говоря, хитроумный механизм фиксации изменений должен полагаться на некоторые гарантии со стороны дисковой системы и ОС.

PRAGMA synchronous задает степень «паранойи» SQLite на это счет.

Режим OFF (или 0) означает: SQLite считает, что данные фиксированы на диске сразу после того как он передал их ОС (то есть сразу после вызова соот-го API ОС).

Это означает, что целостность гарантирована при

аварии приложения

(поскольку ОС продолжает работать), но не при

аварии ОС

или отключении питания.

Режим синхронизации NORMAL (или 1) гарантирует целостность при авариях ОС и почти при всех отключениях питания. Существует ненулевой шанс, что при потере питания в самый неподходящий момент база испортится. Это некий средний, компромисный режим по производительности и надежности.

Режим FULL гарантирует целостность всегда и везде и при любых авариях. Но работает, разумеется, медленнее, поскольку в определенных местах делаются паузы ожидания. И это режим по умолчанию.

Итак, осталась неохваченной только тема журнала типа WAL.

Режим журнала WAL

По умолчанию, режим журнала БД всегда «возвращается» в DELETE. Допустим, мы открыли соединение к БД и установили режим PERSIST. Изменили данные, закрыли соединение.

На диске остался файл журнала (начало которого забито нулями).

Открываем соединение к БД снова. Если не задать режим журнала в этом соединении, он опять будет работать в DELETE. Как только мы обновим данные, механизм фиксации транзакций сотрет файл журнала.

Режим журнала WAL работает иначе — он «постоянный». Как только мы перевели базу в режим WAL, она останется в этом режиме, пока ей явно не поменяют режим журнала на другой.

Итак, зачем он нужен?

Изначально SQLite проектировалась как встроенная БД. Архитектура разделения одновременного доступа к данным была устроена примитивно: одновременно несколько соединений могут читать БД, а вот записывать в данный момент времени может только одно соединение. Это, как минимум, означает, что пишущее соединение ждет «освобождения» БД от читающих. При попытке записать в «занятую» БД приложение получает ошибку SQLITE_BUSY (не путать с SQLITE_LOCKED!). Достигается этот механизм разделения доступа через API блокировки файлов (которые плохо работают на сетевых дисках, поэтому там не рекомендуется использовать SQLite; узнать больше )

В режиме WAL (Write-Ahead Logging) «читатели» БД и «писатели» в БД уже не мешают друг другу, то есть допускается модификация данных при одновременном чтении. Короче говоря, это шаг в сторону больших и серьезных СУБД, в которых все так и есть. Утверждается также, что SQLite в WAL работает быстрее.

Но есть и недостатки:
— требуется некоторые дополнительные ништяки от ОС (unix и Windows имеют эти ништяки);
— БД занимает несколько файлов (файлы «XXX-wal» и «XXX-shm»);
— плохо работает на больших транзакциях (условно, если транзакция больше 50 Мбайт);
— нельзя открыть такую БД в режиме «только чтение»;
— возникает дополнительная операция checkpoint.

Фактически, в режиме WAL данные БД разделяются между БД и файлом журнала. Операция checkpoint переносит данные в БД. По умолчанию, это делается автоматически, если журнал занял 1000 страниц БД.
То есть, идут быстрые COMMIT-ы и вдруг какой-то COMMIT задумался и начал делать checkpoint. Если такое поведение нежелательно, можно делать checkpoint вручную (когда все спокойно), можно это делать и в отдельном процессе.

Пределы

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

По умолчанию, BLOB или строкое значение могут занимать 1 Гбайт и это же ограничение размера одной записи (можно поднять до 2^31 — 1, параметр SQLITE_MAX_LENGTH).

Количество столбцов: 2000 (можно поднять до 32767, SQLITE_MAX_COLUMN).

Размер SQL оператора: 1 МБайт (1073741824 байт, SQLITE_MAX_SQL_LENGTH).

Одновременный join: 64 таблицы.

Присоединить баз к соединению: 10 (до 62, SQLITE_MAX_ATTACHED)

Максимальное количество страниц в БД: 1073741823 (до 2147483646, SQLITE_MAX_PAGE_COUNT).

Если задать размер страницы 65636 байт, то максимальный размер БД будет примерно 14 Терабайт.

Максимальное число записей в таблице: 2^64 — 1, но на практике, конечно, ограничение размера вступит раньше.

Узнать больше sqlite.org/limits.html

UDP: Ссылки по оптимизации SQLite: 1 2 android-1 android-2

Продолжение следует

 
Добежал
 
(2008-10-10 14:49)
[0]

Судя по всему, SQLite неправильно работает с русскими символами в путях к файлу БД (или, наверное, будет точнее сказать, что работает неверно с НЕ английскими символами).

Есть такой класс:

//------------------------------------------------------------------------------
// TSQLiteDatabase
//------------------------------------------------------------------------------

constructor TSQLiteDatabase.Create(const FileName: string);
var
 Msg: pchar;
 iResult: integer;
begin
 inherited Create;

 self.fInTrans := False;

 Msg := nil;
 try
   iResult := SQLite3_Open(PChar(FileName), FHandle);

   if iResult <> SQLITE_OK then
     if Assigned(Handle) then
     begin
       Msg := Sqlite3_ErrMsg(Handle);
       raise ESqliteException.CreateFmt("Failed to open database "%s" : %s",
         [FileName, Msg]);
     end
     else
       raise ESqliteException.CreateFmt("Failed to open database "%s" : unknown error",
         [FileName]);

   //set a few configs
   self.ExecSQL("PRAGMA SYNCHRONOUS=NORMAL;");
//    self.ExecSQL("PRAGMA full_column_names = 1;");
   self.ExecSQL("PRAGMA temp_store = MEMORY;");

 finally
   if Assigned(Msg) then
     SQLite3_Free(Msg);
 end;

end;

Экспорт:

function SQLite3_Open(dbname: PChar; var db: TSqliteDB): integer; cdecl; external "sqlite3.dll" name "sqlite3_open";

Глюк очень интересный. Если, например, сделать так:

TSQLiteDatabase.Create("c:фигняtest.db");

То он не выдает ошибку, а создает файл test.db прямо в «c:» !
Ощущение, что он как-будто «не учитывает» директории с русскими символами.

Кто встречался, что делать?!

P.S. «sqlite3.dll» — почему то в свойствах версия не указана, но качал с оф. сайта не более месяца назад.


 
tesseract ©
 
(2008-10-10 14:53)
[1]


> То он не выдает ошибку, а создает файл test.db прямо в «c:
> » !

Там строка unicode. Читаем мануал.


 
Добежал
 
(2008-10-10 15:03)
[2]

Блин, точно… Нафига так заголовочный файл составлен:

function SQLite3_Open(dbname: PChar; var db: TSqliteDB): integer; cdecl; external "sqlite3.dll" name "sqlite3_open";

гады…

Я б$% ошибку два часа искал! У меня так оказалось, что в директории были русские символы, поэтому он создавал в директории выше. А доступ в директорию выше была запрещена! В результате я вроде как указываю правильный путь (сто пятьдесят раз проверял), а он говорит что не может создать базу… Блин, блин, ненавижу ;)


 
jack128_
 
(2008-10-10 15:36)
[3]


> Нафига так заголовочный файл составлен:

а как он по твоему должен быть составлен???


 
tesseract ©
 
(2008-10-10 15:36)
[4]


> Нафига так заголовочный файл составлен:

Прально он составлен. Для Сей, multibyte там вроде ипользуеться, а не совсем unicode. Да и гемора с выяснением размеров строки вроде поменьше.  Delphi вроде сама догадываеться когда какая строка используеться, но не всегда.


 
jack128_
 
(2008-10-10 15:38)
[5]


> Для Сей, multibyte там вроде ипользуеться, а не совсем unicode

UTF-8 в этой функции используется.
в прочем есть версия функции и для utf-16


 
Добежал
 
(2008-10-10 16:19)
[6]


> а как он по твоему должен быть составлен???

Жень, по-моему, очевидно:

function SQLite3_Open(dbname: PUTF8String; var db: TSqliteDB): integer; cdecl; external «sqlite3.dll» name «sqlite3_open»;


> Прально он составлен

хм… наверное, я тупой. Но все таки под PChar обычно понимают указатель на ANSI-символ / строчки.
Хотя, конечно, вы сейчас начнете доказывать обратное…


 
jack128_
 
(2008-10-10 16:42)
[7]


> Жень, по-моему, очевидно:


int sqlite3_open(
 const char *filename,
 sqlite3 **ppDb        
);

Ты действительно думаешь, что дельфиское PUTF8String — эквивалентно сишному cosnt char *

???  Слава богу, что ты не занимаешся переводом сишных хедеров….


 
Добежал
 
(2008-10-10 16:56)
[8]


> Ты действительно думаешь, что дельфиское PUTF8String — эквивалентно
> сишному cosnt char *

я действительно думаю, что библиотека sqlite3 принимает в качестве параметра указатель на UTF8 набор символов.
В си такого типа видимо нету.

В дельфи есть, это PUTF8String. То есть, описание на си + комментарий справа — получается вот.

Это мое мнение, если я не прав — поясните ошибку. Только не в стиле «ты дурак и слава богу что не ты что-то делаешь».


 
jack128_
 
(2008-10-10 17:24)
[9]

 UTF8String = type string;
 PUTF8String = ^UTF8String;

то есть PUTF8String — указатель на строку. ПРичем не просто на строку, а на _длинную_ строку,  которая сама по себе является указателем на символы.

char * — это указатель на символ


 
Добежал
 
(2008-10-10 17:39)
[10]

Черт, точно.

Действительно, должно быть что-то типа:

UTFChar = type char;
PUTFString = ^UTFChar;

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

Но это не отменяет того, что функцию:


> constructor TSQLiteDatabase.Create(const FileName: string);

надо было писать как:

constructor TSQLiteDatabase.Create(const FileName: UTF8String);


 
Игорь Шевченко ©
 
(2008-10-10 17:43)
[11]

Вообще-то символ в UTF-8 — это char, так что в заголовке все правильно написано


 
Anatoly Podgoretsky ©
 
(2008-10-10 19:08)
[12]

> Игорь Шевченко  (10.10.2008 17:43:11)  [11]

Не согласен, для порядку надо TUTF8String, это же как TCaption/TDate/TTime — нужно для двух целей — первое подчеркнуть что это особый тип, а второе — это то что можно сделать отдельный редактор свойства для диспетчера объектов.


 
Добежал
 
(2008-10-10 21:03)
[13]


> Вообще-то символ в UTF-8 — это char

а указатели в 32-ух битной windows все 32-ух битные. Но зачем то ведь придумали типизированные указатели.


> так что в заголовке все правильно написано

в заголовке да. Неправильно здесь:

constructor TSQLiteDatabase.Create(const FileName: string);

Надо:

constructor TSQLiteDatabase.Create(const FileName: UTF8String);


 
jack128_
 
(2008-10-10 21:13)
[14]


> Надо:
>
> constructor TSQLiteDatabase.Create(const FileName: UTF8String);
>

да нет, сигнатуру нуно поменять на WideString, а в реализацию добавить UTF8Encode


—————————————————————————————————

Оператор PRAGMA — это расширение SQL для данных SQLITE, и это уникальная функция, которая в основном используется для изменения базы данных SQLITE или операций внутреннего запроса данных. Он использует ту же форму, что и SELECT, INSERT и другие операторы для выполнения запросов, но есть несколько важных отличий:
1. Некоторые предложения PRAGMA могут быть удалены, а новые предложения PRAGMA могут быть добавлены в новых версиях. Следовательно, обратная совместимость не может быть гарантирована.
2. Неизвестная команда PRAGMA не выводит сообщение об ошибке, она просто игнорируется.
3. Некоторые PRAGMA работают только на этапе компиляции SQL, но не на этапе выполнения. Это означает, что если вы используете эти API-интерфейсы на языке C, sqlite3_prepare (), sqlite3_step (), sqlite3_finalize (), команда pragma может выполняться только в вызове prepare (), а не в последних двух API. Или прагма может быть запущена при выполнении sqlite3_step (). На каком этапе он выполняется, зависит от самой прагмы и версии выпуска SQLite.
4. Команда pragma уникальна для sqlite, и в принципе невозможно поддерживать совместимость с другими базами данных.

Формат синтаксиса команды PRAGMA следующий:

Он может не принимать никаких параметров или только один параметр. Этот параметр может быть обозначен знаком равенства или заключен в круглые скобки. Оба имеют одинаковый эффект. Во многих случаях значение параметра является логическим, значение (1, да, истина или включено) или (0, нет, ложь, выключено)
Параметры ключевого слова могут быть заключены в кавычки, например, «да» [FALSE]. Некоторые команды прагмы используют символьные строки в качестве параметров, причем «0» и «нет» имеют одинаковое значение. При запросе значения параметра во многих случаях значение возвращается вместо ключевого слова.

Перед именем прагмы вы можете выбрать имя базы данных. Имя базы данных — это имя базы данных, которая будет «присоединена» (связана) или «основная», «временная», чтобы указать основную базу данных и временную базу данных. Если необязательное имя базы данных опущено, по умолчанию будет использоваться «основная» база данных. В некоторых командах прагмы имя базы данных не имеет смысла и просто игнорируется.

Давайте посмотрим на некоторые полезные команды прагмы в sqlite:
auto_vacuum
automatic_index
cache_size
case_sensitive_like
checkpoint_fullfsync
collation_list
compile_options
count_changes¹
database_list
default_cache_size¹
empty_result_callbacks¹
encoding
foreign_key_list
foreign_keys
freelist_count
full_column_names¹
fullfsync
ignore_check_constraints
incremental_vacuum
index_info
index_list
integrity_check
journal_mode
journal_size_limit
legacy_file_format
locking_mode
max_page_count
page_count
page_size
parser_trace²
quick_check
read_uncommitted
recursive_triggers
reverse_unordered_selects
schema_version
secure_delete
short_column_names¹
synchronous
table_info
temp_store
temp_store_directory¹
user_version
vdbe_listing²
vdbe_trace²
wal_autocheckpoint
wal_checkpoint
writable_schema
Некоторые из них, отмеченные цифрой 1 в правом верхнем углу, кажутся устаревшими. Те, которые отмечены цифрой 2, используются только для отладки и полезны только тогда, когда sqlite собран под предварительно скомпилированным макросом SQLITE_DEBUG.

Давайте посмотрим на конкретное использование этих команд:
1. PRAGMA auto_vacuum;
PRAGMA auto_vacuum = 0 или NONE | 1 или FULL | 2 или INCREMENTAL;
Здесь 0 и NONE имеют одинаковое значение.
Значение по умолчанию — 0, что означает, что автоматическая очистка отключена. Если макрос SQLITE_DEFAULT_AUTOVACUUM не определен во время компиляции. При удалении данных размер базы данных не изменится. Бесполезные страницы файлов базы данных будут добавлены в список фрилансеров для дальнейшего использования. В это время используйте команду VACUUM, чтобы перестроить всю базу данных, чтобы освободить ненужное дисковое пространство.
Если значение равно 1, все страницы списка фрилансеров будут перемещены в конец файла, а файл будет обрезаться каждый раз при отправке транзакции. Обратите внимание, что автоматическая очистка только обрезает страницу списка фрилансеров из файла и не выполняет такие операции, как фрагментация, то есть не так тщательно, как команда VACUUM. Фактически, автоматический пылесос сделает больше фрагментов.
Только когда база данных хранит некоторую дополнительную информацию, она позволяет каждой странице базы данных отслеживать ссылающиеся на нее страницы, и автоматическая очистка полезна. Его необходимо включить без создания каких-либо таблиц. После того, как таблица была создана, автоматический вакуум нельзя включить или отключить.
Когда значение равно 2, это означает инкрементный вакуум, что означает, что это не автоматический вакуум каждый раз, когда отправляется транзакция, и для запуска автоматического вакуума необходимо вызывать независимый оператор incremental_vacuum.
База данных может переключаться между 1 и 2 режимами вакуума. Но вы не можете переключиться с нулевого на полный или инкрементный. Чтобы переключиться, либо база данных представляет собой совершенно новую базу данных (без каких-либо таблиц), либо после запуска команды вакуума отдельно. Чтобы изменить автоматический режим вакуумирования, сначала выполните оператор auto_vacuum, чтобы установить новый режим, а затем вызовите VACUUM для реорганизации базы данных.
Оператор auto_vacuum без параметров возвращает текущее значение режима auto_vacuum.

2. PRAGMA automatic_index;
   PRAGMA automatic_index = boolean;
Запросить, установить или сбросить функцию автоматического индексирования. Значение по умолчанию — истина (1).

3. PRAGMA cache_size;
   PRAGMA cache_size = <number of pages>;
Запросить или изменить максимальное количество страниц базы данных, которое может быть размещено в открытой памяти базы данных. Значение по умолчанию — 2000. Этот параметр изменяет размер кэша только в текущем сеансе. При повторном открытии базы данных будет восстановлено значение по умолчанию. Вы можете использовать default_cache_size, чтобы установить размер кеша во всех сессиях

4. PRAGMA case_sensitive_like=boolean;
По умолчанию регистр символов ascii игнорируется. ‘a’ LIKE’A ‘будет истинным. Когда case_sensitive_like отключено, будет использоваться подобное поведение по умолчанию. Когда он включен, он будет чувствителен к регистру.

5. PRAGMA checkpoint_fullfsync
   PRAGMA checkpoint_fullfsync=boolean;
Запросите или установите значение флага fullfsync. Если это значение установлено, метод синхронизации F_FULLFSYNC будет вызываться во время работы контрольной точки.Значение по умолчанию выключено. Только операционная система Mac OS-X поддерживает F_FULLFSYNC. Кроме того, если установлено значение fullfsync, метод синхронизации F_FULLFSYNC будет использоваться во всех операциях синхронизации, а флаг checkpoint_fullfsync совершенно не имеет значения.

6. PRAGMA collation_list;
Возвращает все последовательности сортировки, определенные текущим подключением к базе данных.

7. PRAGMA compile_options;
Это хвалят, возвращайте все предварительно скомпилированные макросы, используемые при компиляции SQLITE. Конечно, префиксы, начинающиеся с «SQLITE_», будут игнорироваться. Фактически, он возвращается путем вызова метода sqlite3_compileoption_get ().

8. PRAGMA count_changes;
   PRAGMA count_changes=boolean;
Эта команда отключена. Она предназначена для обеспечения обратной совместимости. Если это значение не задано, операторы INSERT, UPDATE, DELETE не будут возвращать много строк измененных данных.
Фактически, sqlite3_changes () может получить количество измененных строк.

9. PRAGMA database_list;
Вернуть список баз данных, связанных с текущим подключением к базе данных.

10. PRAGMA default_cache_size;
    PRAGMA default_cache_size = Number-of-pages;
Установите размер кеша по умолчанию в единицах страниц. К сожалению, от этого заказа тоже будет отказано.

11. PRAGMA empty_result_callbacks;
    PRAGMA empty_result_callbacks = boolean;
Только для обратной совместимости. Если значение флага сброшено, функция обратного вызова, предоставляемая sqlite3_exec () (возвращающая 0 или более строк данных), не будет запущена.

12. PRAGMA encoding;
    PRAGMA encoding = «UTF-8»; 
    PRAGMA encoding = «UTF-16»; 
    PRAGMA encoding = «UTF-16le»; 
    PRAGMA encoding = «UTF-16be»;
Значение по умолчанию — utf-8. Если вы используете команду attach, вам потребуется использовать ту же кодировку набора символов, что и в основной базе данных.Если новая кодировка базы данных отличается от основной, произойдет сбой.

13. PRAGMA foreign_key_list(table-name);
Вернуться к списку внешних ключей

14. PRAGMA foreign_keys;
    PRAGMA foreign_keys = boolean;
Параметры запроса или снятие ограничений для внешних ключей. Ограничения по внешним ключам действительны, только если BEGIN или SAVEPOINT не находится в состоянии PENDING.
Изменение этого параметра повлияет на выполнение всех подготовленных операторов SQL.
Начиная с версии 3.6.19, обязательный лимит FK по умолчанию отключен. Другими словами, зависимости внешнего ключа не являются принудительными.

15. PRAGMA freelist_count;
Вернуть количество неиспользуемых страниц в файле базы данных

16. PRAGMA full_column_names;
    PRAGMA full_column_names = boolean;
    deprecated. 
1. Если есть предложение AS, в имени столбца будет использоваться псевдоним после AS
2. Если результатом является обычное выражение, а не имя столбца исходной таблицы, используется текст выражения.
3. Если переключатель short_column_names включен, имя столбца исходной таблицы будет использоваться без префикса имени таблицы.
4. Если оба переключателя установлены в положение ВЫКЛ., Применяется второе правило.
5. Столбец результатов представляет собой комбинацию активных исходных столбцов таблицы: TABLE.COLUMN

17. PRAGMA fullfsync;
    PRAGMA fullfsync = boolean;
Значение по умолчанию — ВЫКЛ, и только ОС MAC поддерживает F_FULLFSYNC.

18. PRAGMA ignore_check_constraints = boolean;
Независимо от того, применять ли ограничения проверки, значение по умолчанию отключено

19. PRAGMA incremental_vacuum(N);
N страниц удаляются из списка фрилансеров. Используется для установки этого параметра. Каждый раз обрезайте одинаковое количество страниц. Эта команда должна быть действительна в режиме auto_vacuum = incremental. Если количество страниц в списке фрилансеров меньше N, или N меньше 1, или N полностью игнорируется, то весь список фрилансеров будет очищен.

20. PRAGMA index_info(index-name);
Получите информацию об указанном индексе.

21. PRAGMA index_list(table-name);
Получить связанную информацию об индексе, связанном с целевой таблицей

22. PRAGMA integrity_check; 
    PRAGMA integrity_check(integer);
Выполните проверку полноты всей библиотеки и проверьте записи с нарушением порядка, отсутствующие страницы и поврежденные индексы.

23. 
PRAGMA journal_mode; 
PRAGMA database.journal_mode; 
PRAGMA journal_mode = DELETE | TRUNCATE | PERSIST | MEMORY | WAL | OFF 
PRAGMA database.journal_mode = DELETE | TRUNCATE | PERSIST | MEMORY | WAL | OFF
Используется для установки journal_mode базы данных. DELETE — поведение по умолчанию. В этом режиме каждый раз, когда транзакция завершается, файл журнала будет удаляться, что приведет к фиксации транзакции.
Режим TRUNCATE путем усечения журнала отката до 0 вместо его удаления. В большинстве случаев это быстрее, чем режим DELETE (поскольку нет необходимости удалять файлы)
В режиме PERSIST журнал отката не удаляется в конце каждой транзакции, а в заголовке журнала заполняется только 0. Это предотвратит откат других подключений к базе данных. Этот режим является оптимизацией для некоторых платформ, особенно когда удаление или усечение файла обходится дороже, чем перезапись первого блока файла.
В режиме MEMORY в ОЗУ сохраняется только журнал отката, который сохраняет дисковые операции ввода-вывода, но это приводит к потере стабильности и целостности. Если он выйдет из строя в середине, база данных может быть повреждена.
Режим WAL, то есть журнал упреждающей записи, заменяет журнал отката. Этот режим является постоянным и связан с несколькими данными, и он остается действующим после повторного открытия базы данных. Этот режим действует только после версии 3.7.0.
(После экспериментов выяснилось, что он генерирует два файла: .shm и .wal)
Режим OFF, поэтому транзакции не поддерживаются. Взаимодействие с другими людьми
Также обратите внимание, что для базы данных памяти есть только два режима: MEMORY или OFF. И, если в настоящее время есть активные транзакции, нельзя изменять режим транзакции.

24. PRAGMA journal_size_limit
    PRAGMA journal_size_limit = N ;
Если вы используете «монопольный режим» (PRAGMA lock_mode = exclusive) или (PRAGMA journal_mode = persist) при подключении, файл журнала по-прежнему будет находиться в файловой системе после подтверждения транзакции. Это может повысить эффективность, но также приведет к потере места. Большая транзакция (например, VACUUM) будет занимать много места на диске.
Этот параметр ограничивает размер файла журнала. Значение по умолчанию -1.

25. PRAGMA legacy_file_format; 
    PRAGMA legacy_file_format = boolean;
Если установлено значение ON, будет использоваться формат файла 3.0.0; если он выключен, будет использоваться последний формат файла, что может привести к тому, что старая версия sqlite не сможет открыть файл.
Когда база данных sqlite3 нового формата файла открывается в первый раз, значение отключено, но значение по умолчанию будет включено.

26. PRAGMA locking_mode; 
    PRAGMA locking_mode = NORMAL | EXCLUSIVE
Значение по умолчанию — НОРМАЛЬНОЕ.Соединение с базой данных снимает блокировку файла в конце каждой транзакции чтения или записи. Если он находится в ЭКСКЛЮЗИВНОМ режиме, соединение никогда не снимает блокировку файла. В этом режиме, когда операция чтения выполняется в первый раз, общая блокировка будет получена и сохранена, а эксклюзивная блокировка будет получена и удержана для первой записи.
Освободите монопольную блокировку.Только когда соединение с базой данных будет закрыто или режим блокировки будет изменен обратно на НОРМАЛЬНЫЙ, доступ к файлу базы данных будет снова (чтение или запись). Просто установить для него значение NORMAL недостаточно, эксклюзивная блокировка будет снята только при следующем посещении.
Есть три причины для установки режима блокировки EXCLUSIVE.
1. Приложению необходимо запретить другим процессам доступ к файлам базы данных.
2. Уменьшается количество системных вызовов файловой системы, что приводит к небольшому снижению производительности.
3. Режим журнала WAL можно использовать в ЭКСКЛЮЗИВНОМ режиме без использования общей памяти.
Если указано имя базы данных, действует только целевая база данных. Такие как:
PRAGMA main.locking_mode = EXCLUSIVE; Если имя базы данных не указано, оно вступит в силу для всех открытых баз данных. Временные базы данных или базы данных памяти всегда используют эксклюзивный режим блокировки.
Когда вы входите в режим журнала WAL в первый раз, режим блокировки использует эксклюзивный. После этого режим блокировки не может быть изменен, пока вы не выйдете из режима журнала WAL. Если вы используете НОРМАЛЬНЫЙ в начале режима блокировки, в первый раз вы входите в WAL, режим блокировки будет заблокирован, режим можно изменить, и нет необходимости выходить из режима WAL.

27. PRAGMA max_page_count; 
    PRAGMA max_page_count = N;
Запросить или установить максимальное количество страниц файлов базы данных

28. PRAGMA page_count;
Вернуть количество страниц файла базы данных

29. PRAGMA page_size; 
    PRAGMA page_size = bytes;
Запросите или установите размер страницы файла базы данных, который должен быть степенью 2 и находиться в диапазоне от 512 до 65536.
При создании базы данных будет указан размер по умолчанию. Команда page_size сразу изменит размер страницы (если база данных пуста, то есть без создания каких-либо таблиц). Если новый размер указан, он находится между запуском команды VACUUM и база данных не находится в режиме журнала WAL, то команда VACUUM настроит размер страницы на новый размер (в настоящее время не должно быть ограничений на создание таблиц. )
Значение по умолчанию для SQLITE_DEFAULT_PAGE_SIZE — 1024, а максимальный размер страницы по умолчанию — 8192. В Windows иногда размер страницы по умолчанию может быть больше 1024, в зависимости от GetDiskFreeSpace () для получения реального установленного размера сектора.

30. PRAGMA parser_trace = boolean;
При использовании в DEBUG.

31. PRAGMA quick_check; 
    PRAGMA quick_check(integer)
Аналогичен Integrity_check, но не проверяет соответствие содержимого индекса содержимому таблицы.

32. PRAGMA read_uncommitted; 
    PRAGMA read_uncommitted = boolean;
Прочитать незафиксированный переключатель. Уровень изоляции транзакции по умолчанию: сериализуемый. Любой процесс или поток может установить уровень изоляции незафиксированного чтения, но SERIALIZABLE по-прежнему используется, за исключением тех соединений, которые совместно используют кеш режима страницы и таблицы.

33. PRAGMA recursive_triggers; 
    PRAGMA recursive_triggers = boolean;
Повлияет на выполнение всех операторов. До версии 3.6.18 этот переключатель не поддерживался. Значение по умолчанию выключено.

34. PRAGMA reverse_unordered_selects; 
PRAGMA reverse_unordered_selects = boolean;
Когда этот переключатель включен, оператор select без order by будет выводить результаты в обратном порядке.

35. PRAGMA schema_version; 
PRAGMA schema_version = integer ; 
PRAGMA user_version; 
PRAGMA user_version = integer ;
Схема и пользовательская версия — это 32-битные целые числа (в представлении с прямым порядком байтов) в 40 и 60 байтах заголовка файла базы данных.
Версия схемы поддерживается внутри SQLite. При изменении схемы значение будет увеличено. Явное изменение этого значения очень опасно.
Пользовательская версия может использоваться приложениями.

36. PRAGMA secure_delete; 
PRAGMA database.secure_delete; 
PRAGMA secure_delete = boolean 
PRAGMA database.secure_delete = boolean
Если установлено значение ON, удаленное содержимое будет перезаписано 0. Значение по умолчанию определяется макросом SQLITE_SECURE_DELETE. Это ВЫКЛ.

37. PRAGMA short_column_names; 
PRAGMA short_column_names = boolean;
deprecated.

38. PRAGMA synchronous; 
PRAGMA synchronous = 0 | OFF | 1 | NORMAL | 2 | FULL;
Запросите и установите значение флага синхронизации. Значение по умолчанию — ПОЛНЫЙ.

39. PRAGMA table_info(table-name);
Вернуть основную информацию таблицы

40. PRAGMA temp_store; 
PRAGMA temp_store = 0 | DEFAULT | 1 | FILE | 2 | MEMORY;
Запросите или установите значение параметра temp_store.
SQLITE_TEMP_STORE PRAGMA temp_store Storage used forTEMP tables
0 any file
1 0 file
1 1 file
1 2 memory
2 0 memory
2 1 file
2 2 memory
3 any memory

40. PRAGMA temp_store_directory; 
    PRAGMA temp_store_directory = ‘directory-name’;
Установите или измените расположение каталога temp_store. Не рекомендуется.

41. PRAGMA vdbe_listing = boolean;
Используется для DEBUG

42. PRAGMA vdbe_trace = boolean;
Используется для DEBUG

43. PRAGMA wal_autocheckpoint;
PRAGMA wal_autocheckpoint=N;
Установите интервал между автоматическими контрольными точками WAL (в страницах), значение по умолчанию — 1000.

44. PRAGMA database.wal_checkpoint;
PRAGMA database.wal_checkpoint(PASSIVE);
PRAGMA database.wal_checkpoint(FULL);
PRAGMA database.wal_checkpoint(RESTART);

45. PRAGMA writable_schema = boolean;
Если установлено значение ON, таблица SQLITE_MASTER может выполнять операции CUD. Это опасно!

(finished!!!)

SQLite

Small. Fast. Reliable.
Choose any three.

The PRAGMA statement is an SQL extension specific to SQLite and used to
modify the operation of the SQLite library or to query the SQLite library for
internal (non-table) data. The PRAGMA statement is issued using the same
interface as other SQLite commands (e.g. SELECT, INSERT) but is
different in the following important respects:

  • The pragma command is specific to SQLite and is
    not compatible with any other SQL database engine.
  • Specific pragma statements may be removed and others added in future
    releases of SQLite. There is no guarantee of backwards compatibility.
  • No error messages are generated if an unknown pragma is issued.
    Unknown pragmas are simply ignored. This means if there is a typo in
    a pragma statement the library does not inform the user of the fact.
  • Some pragmas take effect during the SQL compilation stage, not the
    execution stage. This means if using the C-language sqlite3_prepare(),
    sqlite3_step(), sqlite3_finalize() API (or similar in a wrapper
    interface), the pragma may run during the sqlite3_prepare() call,
    not during the sqlite3_step() call as normal SQL statements do.
    Or the pragma might run during sqlite3_step() just like normal
    SQL statements. Whether or not the pragma runs during sqlite3_prepare()
    or sqlite3_step() depends on the pragma and on the specific release
    of SQLite.
  • The EXPLAIN and EXPLAIN QUERY PLAN prefixes to SQL statements
    only affect the behavior of the statement during sqlite3_step().
    That means that PRAGMA statements that take effect during
    sqlite3_prepare() will behave the same way regardless of whether or
    not they are prefaced by «EXPLAIN».

The C-language API for SQLite provides the SQLITE_FCNTL_PRAGMA
file control which gives VFS implementations the
opportunity to add new PRAGMA statements or to override the meaning of
built-in PRAGMA statements.


PRAGMA command syntax

pragma-stmt:

PRAGMA

schema-name

.

pragma-name

(

pragma-value

)

=

pragma-value

pragma-value:

A pragma can take either zero or one argument. The argument is may be either
in parentheses or it may be separated from the pragma name by an equal sign.
The two syntaxes yield identical results.
In many pragmas, the argument is a boolean. The boolean can be one of:

1 yes true on
0 no false off

Keyword arguments can optionally appear in quotes.
(Example: ‘yes’ [FALSE].) Some pragmas
takes a string literal as their argument. When pragma takes a keyword
argument, it will usually also take a numeric equivalent as well.
For example, «0» and «no» mean the same thing, as does «1» and «yes».
When querying the value of a setting, many pragmas return the number
rather than the keyword.

A pragma may have an optional schema-name
before the pragma name.
The schema-name is the name of an ATTACH-ed database
or «main» or «temp» for the main and the TEMP databases. If the optional
schema name is omitted, «main» is assumed. In some pragmas, the schema
name is meaningless and is simply ignored. In the documentation below,
pragmas for which the schema name is meaningful are shown with a
«schema.» prefix.


PRAGMA functions

PRAGMAs that return results and that have no side-effects can be
accessed from ordinary SELECT statements as table-valued functions.
For each participating PRAGMA, the corresponding table-valued function
has the same name as the PRAGMA with a 7-character «pragma_» prefix.
The PRAGMA argument and schema, if any, are passed as arguments to the
table-valued function, with the schema as an optional, last argument.

For example, information about the columns in an index can be
read using the index_info pragma as follows:

PRAGMA index_info('idx52');

Or, the same content can be read using:

SELECT * FROM pragma_index_info('idx52');

The advantage of the table-valued function format is that the query
can return just a subset of the PRAGMA columns, can include a WHERE clause,
can use aggregate functions, and the table-valued function can be just
one of several data sources in a join.
For example, to get a list of all indexed columns in a schema, one
could query:

SELECT DISTINCT m.name || '.' || ii.name AS 'indexed-columns'
  FROM sqlite_schema AS m,
       pragma_index_list(m.name) AS il,
       pragma_index_info(il.name) AS ii
 WHERE m.type='table'
 ORDER BY 1;

Additional notes:

  • Table-valued functions exist only for built-in PRAGMAs, not for PRAGMAs
    defined using the SQLITE_FCNTL_PRAGMA file control.

  • Table-valued functions exist only for PRAGMAs that return results and
    that have no side-effects.

  • This feature could be used to implement
    information schema
    by first creating a separate schema using

    ATTACH ':memory:' AS 'information_schema';
    

    Then creating
    VIEWs in that schema that implement the official information schema
    tables using table-valued PRAGMA functions.

  • The table-valued functions for PRAGMA feature was added
    in SQLite version 3.16.0 (2017-01-02). Prior versions of SQLite
    cannot use this feature.


List Of PRAGMAs

  • analysis_limit
  • application_id
  • auto_vacuum
  • automatic_index
  • busy_timeout
  • cache_size
  • cache_spill
  • case_sensitive_like
  • cell_size_check
  • checkpoint_fullfsync
  • collation_list
  • compile_options
  • count_changes¹
  • data_store_directory¹
  • data_version
  • database_list
  • default_cache_size¹
  • defer_foreign_keys
  • empty_result_callbacks¹
  • encoding
  • foreign_key_check
  • foreign_key_list
  • foreign_keys
  • freelist_count
  • full_column_names¹
  • fullfsync
  • function_list
  • hard_heap_limit
  • ignore_check_constraints
  • incremental_vacuum
  • index_info
  • index_list
  • index_xinfo
  • integrity_check
  • journal_mode
  • journal_size_limit
  • legacy_alter_table
  • legacy_file_format
  • locking_mode
  • max_page_count
  • mmap_size
  • module_list
  • optimize
  • page_count
  • page_size
  • parser_trace²
  • pragma_list
  • query_only
  • quick_check
  • read_uncommitted
  • recursive_triggers
  • reverse_unordered_selects
  • schema_version³
  • secure_delete
  • short_column_names¹
  • shrink_memory
  • soft_heap_limit
  • stats³
  • synchronous
  • table_info
  • table_list
  • table_xinfo
  • temp_store
  • temp_store_directory¹
  • threads
  • trusted_schema
  • user_version
  • vdbe_addoptrace²
  • vdbe_debug²
  • vdbe_listing²
  • vdbe_trace²
  • wal_autocheckpoint
  • wal_checkpoint
  • writable_schema³

Notes:

  1. Pragmas whose names are struck through
    are deprecated. Do not use them. They exist
    for historical compatibility.
  2. These pragmas are only available in builds using non-standard
    compile-time options.
  3. These pragmas are used for testing SQLite and are not recommended
    for use in application programs.

PRAGMA analysis_limit;

PRAGMA analysis_limit =
N;

Query or change a limit on the approximate ANALYZE setting.
This is the approximate number of
rows examined in each index by the ANALYZE command.
If the argument N is omitted, then the analysis limit
is unchanged.
If the limit is zero, then the analysis limit is disabled and
the ANALYZE command will examine all rows of each index.
If N is greater than zero, then the analysis limit is set to N
and subsequent ANALYZE commands will stop analyzing
each index after it has examined approximately N rows.
If N is a negative number or something other than an integer value,
then the pragma behaves as if the N argument was omitted.
In all cases, the value returned is the new analysis limit used
for subsequent ANALYZE commands.

This pragma can be used to help the ANALYZE command run faster
on large databases. The results of analysis are not as good
when only part of each index is examined, but the results are
usually good enough. Setting N to 100 or 1000 allows the
ANALYZE command to run very quickly, even on multi-gigabyte
database files. This pragma is particularly useful in combination
with PRAGMA optimize.

This pragma was added in SQLite version 3.32.0 (2020-05-22).
The current implementation only uses the lower 31 bits of the
N value — higher order bits are silently ignored. Future versions
of SQLite might begin using higher order bits.


PRAGMA schema.application_id;

PRAGMA
schema.application_id = integer ;

The application_id PRAGMA is used to query or set the 32-bit
signed big-endian «Application ID» integer located at offset
68 into the database header. Applications that use SQLite as their
application file-format should set the Application ID integer to
a unique integer so that utilities such as
file(1) can determine the specific
file type rather than just reporting «SQLite3 Database». A list of
assigned application IDs can be seen by consulting the
magic.txt file in the SQLite source repository.

See also the user_version pragma.


PRAGMA schema.auto_vacuum;
PRAGMA
schema.auto_vacuum =
0 | NONE | 1 | FULL | 2 | INCREMENTAL;

Query or set the auto-vacuum status in the database.

The default setting for auto-vacuum is 0 or «none»,
unless the SQLITE_DEFAULT_AUTOVACUUM compile-time option is used.
The «none» setting means that auto-vacuum is disabled.
When auto-vacuum is disabled and data is deleted data from a database,
the database file remains the same size. Unused database file
pages are added to a «freelist» and reused for subsequent inserts. So
no database file space is lost. However, the database file does not
shrink. In this mode the VACUUM
command can be used to rebuild the entire database file and
thus reclaim unused disk space.

When the auto-vacuum mode is 1 or «full», the freelist pages are
moved to the end of the database file and the database file is truncated
to remove the freelist pages at every transaction commit.
Note, however, that auto-vacuum only truncates the freelist pages
from the file. Auto-vacuum does not defragment the database nor
repack individual database pages the way that the
VACUUM command does. In fact, because
it moves pages around within the file, auto-vacuum can actually
make fragmentation worse.

Auto-vacuuming is only possible if the database stores some
additional information that allows each database page to be
traced backwards to its referrer. Therefore, auto-vacuuming must
be turned on before any tables are created. It is not possible
to enable or disable auto-vacuum after a table has been created.

When the value of auto-vacuum is 2 or «incremental» then the additional
information needed to do auto-vacuuming is stored in the database file
but auto-vacuuming does not occur automatically at each commit as it
does with auto_vacuum=full. In incremental mode, the separate
incremental_vacuum pragma must
be invoked to cause the auto-vacuum to occur.

The database connection can be changed between full and incremental
autovacuum mode at any time. However, changing from
«none» to «full» or «incremental» can only occur when the database
is new (no tables
have yet been created) or by running the VACUUM command. To
change auto-vacuum modes, first use the auto_vacuum pragma to set
the new desired mode, then invoke the VACUUM command to
reorganize the entire database file. To change from «full» or
«incremental» back to «none» always requires running VACUUM even
on an empty database.

When the auto_vacuum pragma is invoked with no arguments, it
returns the current auto_vacuum mode.


PRAGMA automatic_index;

PRAGMA automatic_index =
boolean;

Query, set, or clear the automatic indexing capability.

Automatic indexing is enabled by default as of
version 3.7.17 (2013-05-20),
but this might change in future releases of SQLite.


PRAGMA busy_timeout;

PRAGMA busy_timeout =
milliseconds;

Query or change the setting of the
busy timeout.
This pragma is an alternative to the sqlite3_busy_timeout() C-language
interface which is made available as a pragma for use with language
bindings that do not provide direct access to sqlite3_busy_timeout().

Each database connection can only have a single
busy handler. This PRAGMA sets the busy handler
for the process, possibly overwriting any previously set busy handler.


PRAGMA schema.cache_size;

PRAGMA
schema.cache_size = pages;

PRAGMA
schema.cache_size = —kibibytes;

Query or change the suggested maximum number of database disk pages
that SQLite will hold in memory at once per open database file. Whether
or not this suggestion is honored is at the discretion of the
Application Defined Page Cache.
The default page cache that is built into SQLite honors the request,
however alternative application-defined page cache implementations
may choose to interpret the suggested cache size in different ways
or to ignore it all together.
The default suggested cache size is -2000, which means the cache size
is limited to 2048000 bytes of memory.
The default suggested cache size can be altered using the
SQLITE_DEFAULT_CACHE_SIZE compile-time options.
The TEMP database has a default suggested cache size of 0 pages.

If the argument N is positive then the suggested cache size is set
to N. If the argument N is negative, then the
number of cache pages is adjusted to be a number of pages that would
use approximately abs(N*1024) bytes of memory based on the current
page size. SQLite remembers the number of pages in the page cache,
not the amount of memory used. So if you set the cache size using
a negative number and subsequently change the page size (using the
PRAGMA page_size command) then the maximum amount of cache
memory will go up or down in proportion to the change in page size.

Backwards compatibility note:
The behavior of cache_size with a negative N
was different prior to version 3.7.10 (2012-01-16). In
earlier versions, the number of pages in the cache was set
to the absolute value of N.

When you change the cache size using the cache_size pragma, the
change only endures for the current session. The cache size reverts
to the default value when the database is closed and reopened.

The default page cache implemention does not allocate
the full amount of cache memory all at once. Cache memory
is allocated in smaller chunks on an as-needed basis. The page_cache
setting is a (suggested) upper bound on the amount of memory that the
cache can use, not the amount of memory it will use all of the time.
This is the behavior of the default page cache implementation, but an
application defined page cache is free
to behave differently if it wants.


PRAGMA cache_spill;

PRAGMA cache_spill=
boolean;

PRAGMA
schema.cache_spill=N;

The cache_spill pragma enables or disables the ability of the pager
to spill dirty cache pages to the database file in the middle of a
transaction. Cache_spill is enabled by default and most applications
should leave it that way as cache spilling is usually advantageous.
However, a cache spill has the side-effect of acquiring an
EXCLUSIVE lock on the database file. Hence, some applications that
have large long-running transactions may want to disable cache spilling
in order to prevent the application from acquiring an exclusive lock
on the database until the moment that the transaction COMMITs.

The «PRAGMA cache_spill=N» form of this pragma sets a minimum
cache size threshold required for spilling to occur. The number of pages
in cache must exceed both the cache_spill threshold and the maximum cache
size set by the PRAGMA cache_size statement in order for spilling to
occur.

The «PRAGMA cache_spill=boolean» form of this pragma applies
across all databases attached to the database connection. But the
«PRAGMA cache_spill=N» form of this statement only applies to
the «main» schema or whatever other schema is specified as part of the
statement.


PRAGMA case_sensitive_like = boolean;

The default behavior of the LIKE operator is to ignore case
for ASCII characters. Hence, by default ‘a’ LIKE ‘A’ is
true. The case_sensitive_like pragma installs a new application-defined
LIKE function that is either case sensitive or insensitive depending
on the value of the case_sensitive_like pragma.
When case_sensitive_like is disabled, the default LIKE behavior is
expressed. When case_sensitive_like is enabled, case becomes
significant. So, for example,
‘a’ LIKE ‘A’ is false but ‘a’ LIKE ‘a’ is still true.

This pragma uses sqlite3_create_function() to overload the
LIKE and GLOB functions, which may override previous implementations
of LIKE and GLOB registered by the application. This pragma
only changes the behavior of the SQL LIKE operator. It does not
change the behavior of the sqlite3_strlike() C-language interface,
which is always case insensitive.


PRAGMA cell_size_check

PRAGMA cell_size_check =
boolean;

The cell_size_check pragma enables or disables additional sanity
checking on database b-tree pages as they are initially read from disk.
With cell size checking enabled, database corruption is detected earlier
and is less likely to «spread». However, there is a small performance
hit for doing the extra checks and so cell size checking is turned off
by default.


PRAGMA checkpoint_fullfsync

PRAGMA checkpoint_fullfsync =
boolean;

Query or change the fullfsync flag for checkpoint operations.
If this flag is set, then the F_FULLFSYNC syncing method is used
during checkpoint operations on systems that support F_FULLFSYNC.
The default value of the checkpoint_fullfsync flag
is off. Only Mac OS-X supports F_FULLFSYNC.

If the fullfsync flag is set, then the F_FULLFSYNC syncing
method is used for all sync operations and the checkpoint_fullfsync
setting is irrelevant.


PRAGMA collation_list;

Return a list of the collating sequences defined for the current
database connection.


PRAGMA compile_options;

This pragma returns the names of compile-time options used when
building SQLite, one option per row. The «SQLITE_» prefix is omitted
from the returned option names. See also the
sqlite3_compileoption_get() C/C++ interface and the
sqlite_compileoption_get() SQL functions.


PRAGMA count_changes;

PRAGMA count_changes =
boolean;

Query or change the count-changes flag. Normally, when the
count-changes flag is not set, INSERT, UPDATE and DELETE statements
return no data. When count-changes is set, each of these commands
returns a single row of data consisting of one integer value — the
number of rows inserted, modified or deleted by the command. The
returned change count does not include any insertions, modifications
or deletions performed by triggers, any changes made automatically
by foreign key actions, or updates caused by an upsert.

Another way to get the row change counts is to use the
sqlite3_changes() or sqlite3_total_changes() interfaces.
There is a subtle different, though. When an INSERT, UPDATE, or
DELETE is run against a view using an INSTEAD OF trigger,
the count_changes pragma reports the number of rows in the view
that fired the trigger, whereas sqlite3_changes() and
sqlite3_total_changes() do not.

This pragma is deprecated and exists
for backwards compatibility only. New applications
should avoid using this pragma. Older applications should discontinue
use of this pragma at the earliest opportunity. This pragma may be omitted
from the build when SQLite is compiled using SQLITE_OMIT_DEPRECATED.


PRAGMA data_store_directory;

PRAGMA data_store_directory = ‘
directory-name‘;

Query or change the value of the sqlite3_data_directory global
variable, which windows operating-system interface backends use to
determine where to store database files specified using a relative
pathname.

Changing the data_store_directory setting is not threadsafe.
Never change the data_store_directory setting if another thread
within the application is running any SQLite interface at the same time.
Doing so results in undefined behavior. Changing the data_store_directory
setting writes to the sqlite3_data_directory global
variable and that global variable is not protected by a mutex.

This facility is provided for WinRT which does not have an OS
mechanism for reading or changing the current working directory.
The use of this pragma in any other context is discouraged and may
be disallowed in future releases.

This pragma is deprecated and exists
for backwards compatibility only. New applications
should avoid using this pragma. Older applications should discontinue
use of this pragma at the earliest opportunity. This pragma may be omitted
from the build when SQLite is compiled using SQLITE_OMIT_DEPRECATED.


PRAGMA schema.data_version;

The «PRAGMA data_version» command provides an indication that the
database file has been modified.
Interactive programs that hold database content in memory or that
display database content on-screen can use the PRAGMA data_version
command to determine if they need to flush and reload their memory
or update the screen display.

The integer values returned by two
invocations of «PRAGMA data_version» from the same connection
will be different if changes were committed to the database
by any other connection in the interim.
The «PRAGMA data_version» value is unchanged for commits made
on the same database connection.
The behavior of «PRAGMA data_version» is the same for all database
connections, including database connections in separate processes
and shared cache database connections.

The «PRAGMA data_version» value is a local property of each
database connection and so values returned by two concurrent invocations
of «PRAGMA data_version» on separate database connections are
often different even though the underlying database is identical.
It is only meaningful to compare the «PRAGMA data_version» values
returned by the same database connection at two different points in
time.


PRAGMA database_list;

This pragma works like a query to return one row for each database
attached to the current database connection.
The second column is «main» for the main database file, «temp»
for the database file used to store TEMP objects, or the name of the
ATTACHed database for other database files.
The third column is the name of the database file itself, or an empty
string if the database is not associated with a file.


PRAGMA schema.default_cache_size;

PRAGMA
schema.default_cache_size
=
Number-of-pages;

This pragma queries or sets the suggested maximum number of pages
of disk cache that will be allocated per open database file.
The difference between this pragma and cache_size is that the
value set here persists across database connections.
The value of the default cache size is stored in the 4-byte
big-endian integer located at offset 48 in the header of the
database file.

This pragma is deprecated and exists
for backwards compatibility only. New applications
should avoid using this pragma. Older applications should discontinue
use of this pragma at the earliest opportunity. This pragma may be omitted
from the build when SQLite is compiled using SQLITE_OMIT_DEPRECATED.


PRAGMA defer_foreign_keys

PRAGMA defer_foreign_keys =
boolean;

When the defer_foreign_keys PRAGMA is on,
enforcement of all foreign key constraints is delayed until the
outermost transaction is committed. The defer_foreign_keys pragma
defaults to OFF so that foreign key constraints are only deferred if
they are created as «DEFERRABLE INITIALLY DEFERRED». The
defer_foreign_keys pragma is automatically switched off at each
COMMIT or ROLLBACK. Hence, the defer_foreign_keys pragma must be
separately enabled for each transaction. This pragma is
only meaningful if foreign key constraints are enabled, of course.

The sqlite3_db_status(db,SQLITE_DBSTATUS_DEFERRED_FKS,…)
C-language interface can be used during a transaction to determine
if there are deferred and unresolved foreign key constraints.


PRAGMA empty_result_callbacks;

PRAGMA empty_result_callbacks =
boolean;

Query or change the empty-result-callbacks flag.

The empty-result-callbacks flag affects the sqlite3_exec() API only.
Normally, when the empty-result-callbacks flag is cleared, the
callback function supplied to the sqlite3_exec() is not invoked
for commands that return zero rows of data. When empty-result-callbacks
is set in this situation, the callback function is invoked exactly once,
with the third parameter set to 0 (NULL). This is to enable programs
that use the sqlite3_exec() API to retrieve column-names even when
a query returns no data.

This pragma is deprecated and exists
for backwards compatibility only. New applications
should avoid using this pragma. Older applications should discontinue
use of this pragma at the earliest opportunity. This pragma may be omitted
from the build when SQLite is compiled using SQLITE_OMIT_DEPRECATED.


PRAGMA encoding;

PRAGMA encoding = ‘UTF-8’;

PRAGMA encoding = ‘UTF-16’;

PRAGMA encoding = ‘UTF-16le’;

PRAGMA encoding = ‘UTF-16be’;

In first form, if the main database has already been
created, then this pragma returns the text encoding used by the
main database, one of ‘UTF-8’, ‘UTF-16le’ (little-endian UTF-16
encoding) or ‘UTF-16be’ (big-endian UTF-16 encoding). If the main
database has not already been created, then the value returned is the
text encoding that will be used to create the main database, if
it is created by this session.

The second through fifth forms of this pragma
set the encoding that the main database will be created with if
it is created by this session. The string ‘UTF-16’ is interpreted
as «UTF-16 encoding using native machine byte-ordering». It is not
possible to change the text encoding of a database after it has been
created and any attempt to do so will be silently ignored.

If no encoding is first set with this pragma,
then the encoding with which the main database will be created
defaults to one determined by the
API used to open the connection.

Once an encoding has been set for a database, it cannot be changed.

Databases created by the ATTACH command always use the same encoding
as the main database. An attempt to ATTACH a database with a different
text encoding from the «main» database will fail.


PRAGMA schema.foreign_key_check;

PRAGMA
schema.foreign_key_check(table-name);

The foreign_key_check pragma checks the database, or the table
called «table-name«, for
foreign key constraints that are violated. The foreign_key_check
pragma returns one row output for each foreign key violation.
There are four columns in each result row.
The first column is the name of the table that contains the REFERENCES
clause. The second column is the rowid of the row that
contains the invalid REFERENCES clause, or NULL if the child table is a
WITHOUT ROWID table. The third column is the name
of the table that is referred to. The fourth column is the index of
the specific foreign key constraint that failed. The fourth column
in the output of the foreign_key_check pragma is the same integer as
the first column in the output of the foreign_key_list pragma.
When a «table-name» is specified, the only foreign key constraints
checked are those created by REFERENCES clauses in the
CREATE TABLE statement for table-name.


PRAGMA foreign_key_list(table-name);

This pragma returns one row for each foreign key constraint
created by a REFERENCES clause in the CREATE TABLE statement of
table «table-name«.


PRAGMA foreign_keys;

PRAGMA foreign_keys =
boolean;

Query, set, or clear the enforcement of foreign key constraints.

This pragma is a no-op within a transaction; foreign key constraint
enforcement may only be enabled or disabled when there is no pending
BEGIN or SAVEPOINT.

Changing the foreign_keys setting affects the execution of
all statements prepared
using the database connection, including those prepared before the
setting was changed. Any existing statements prepared using the legacy
sqlite3_prepare() interface may fail with an SQLITE_SCHEMA error
after the foreign_keys setting is changed.

As of SQLite version 3.6.19, the default setting for foreign
key enforcement is OFF. However, that might change in a future
release of SQLite. The default setting for foreign key enforcement
can be specified at compile-time using the SQLITE_DEFAULT_FOREIGN_KEYS
preprocessor macro. To minimize future problems, applications should
set the foreign key enforcement flag as required by the application
and not depend on the default setting.


PRAGMA schema.freelist_count;

Return the number of unused pages in the database file.


PRAGMA full_column_names;

PRAGMA full_column_names =
boolean;

Query or change the full_column_names flag. This flag together
with the short_column_names flag determine
the way SQLite assigns names to result columns of SELECT statements.
Result columns are named by applying the following rules in order:

  1. If there is an AS clause on the result, then the name of
    the column is the right-hand side of the AS clause.

  2. If the result is a general expression, not a just the name of
    a source table column,
    then the name of the result is a copy of the expression text.

  3. If the short_column_names pragma is ON, then the name of the
    result is the name of the source table column without the
    source table name prefix: COLUMN.

  4. If both pragmas short_column_names and full_column_names
    are OFF then case (2) applies.

  5. The name of the result column is a combination of the source table
    and source column name: TABLE.COLUMN

This pragma is deprecated and exists
for backwards compatibility only. New applications
should avoid using this pragma. Older applications should discontinue
use of this pragma at the earliest opportunity. This pragma may be omitted
from the build when SQLite is compiled using SQLITE_OMIT_DEPRECATED.


PRAGMA fullfsync

PRAGMA fullfsync =
boolean;

Query or change the fullfsync flag. This flag
determines whether or not the F_FULLFSYNC syncing method is used
on systems that support it. The default value of the fullfsync flag
is off. Only Mac OS X supports F_FULLFSYNC.

See also checkpoint_fullfsync.


PRAGMA function_list;

This pragma returns a list of SQL functions
known to the database connection. Each row of the result
describes a single calling signature for a single SQL function.
Some SQL functions will have multiple rows in the result set
if they can (for example) be invoked with a varying number of
arguments or can accept text in various encodings.


PRAGMA hard_heap_limit
PRAGMA hard_heap_limit=
N

This pragma invokes the sqlite3_hard_heap_limit64() interface with
the argument N, if N is specified and N is a positive integer that
is less than the current hard heap limit.
The hard_heap_limit pragma always returns the same integer
that would be returned by the sqlite3_hard_heap_limit64(-1) C-language
function. That is to say, it always returns the value of the hard
heap limit that is set after any changes imposed by this PRAGMA.

This pragma can only lower the heap limit, never raise it.
The C-language interface sqlite3_hard_heap_limit64() must be used
to raise the heap limit.

See also the soft_heap_limit pragma.


PRAGMA ignore_check_constraints = boolean;

This pragma enables or disables the enforcement of CHECK constraints.
The default setting is off, meaning that CHECK constraints are
enforced by default.


PRAGMA schema.incremental_vacuum(N);
PRAGMA
schema.incremental_vacuum;

The incremental_vacuum pragma causes up to N pages to
be removed from the freelist. The database file is truncated by
the same amount. The incremental_vacuum pragma has no effect if
the database is not in
auto_vacuum=incremental mode
or if there are no pages on the freelist. If there are fewer than
N pages on the freelist, or if N is less than 1, or
if the «(N)» argument is omitted, then the entire
freelist is cleared.


PRAGMA schema.index_info(index-name);

This pragma returns one row for each key column in the named index.
A key column is a column that is actually named in the CREATE INDEX
index statement or UNIQUE constraint or PRIMARY KEY constraint that
created the index. Index entries also usually contain auxiliary
columns that point back to the table row being indexed. The auxiliary
index-columns are not shown by the index_info pragma, but they are
listed by the index_xinfo pragma.

Output columns from the index_info pragma are as follows:

  1. The rank of the column within the index. (0 means left-most.)
  2. The rank of the column within the table being indexed.
    A value of -1 means rowid and a value of -2 means that an
    expression is being used.
  3. The name of the column being indexed. This columns is NULL
    if the column is the rowid or an expression.

If there is no index named index-name but there is a
WITHOUT ROWID table with that name, then (as of
SQLite version 3.30.0 on 2019-10-04) this pragma returns the
PRIMARY KEY columns of the WITHOUT ROWID table as they are used
in the records of the underlying b-tree, which is to say with
duplicate columns removed.


PRAGMA schema.index_list(table-name);

This pragma returns one row for each index associated with the
given table.

Output columns from the index_list pragma are as follows:

  1. A sequence number assigned to each index for internal tracking
    purposes.
  2. The name of the index.
  3. «1» if the index is UNIQUE and «0» if not.
  4. «c» if the index was created by a CREATE INDEX statement,
    «u» if the index was created by a UNIQUE constraint, or
    «pk» if the index was created by a PRIMARY KEY constraint.
  5. «1» if the index is a partial index and «0» if not.

PRAGMA schema.index_xinfo(index-name);

This pragma returns information about every column in an index.
Unlike this index_info pragma, this pragma returns information about
every column in the index, not just the key columns.
(A key column is a column that is actually named in the CREATE INDEX
index statement or UNIQUE constraint or PRIMARY KEY constraint that
created the index. Auxiliary columns are additional columns needed to
locate the table entry that corresponds to each index entry.)

Output columns from the index_xinfo pragma are as follows:

  1. The rank of the column within the index. (0 means left-most.
    Key columns come before auxiliary columns.)
  2. The rank of the column within the table being indexed, or -1 if
    the index-column is the rowid of the table being indexed and -2
    if the index is on an expression.
  3. The name of the column being indexed, or NULL if the index-column
    is the rowid of the table being indexed or an
    expression.
  4. 1 if the index-column is sorted in reverse (DESC) order by the
    index and 0 otherwise.
  5. The name for the collating sequence
    used to compare values in the index-column.
  6. 1 if the index-column is a key column and 0 if the index-column
    is an auxiliary column.

If there is no index named index-name but there is a
WITHOUT ROWID table with that name, then (as of
SQLite version 3.30.0 on 2019-10-04) this pragma returns the
columns of the WITHOUT ROWID table as they are used
in the records of the underlying b-tree, which is to say with
de-duplicated PRIMARY KEY columns first followed by data columns.


PRAGMA schema.integrity_check;

PRAGMA
schema.integrity_check(N)

PRAGMA
schema.integrity_check(TABLENAME)

This pragma does a low-level formatting and consistency check
of the database. The integrity_check pragma look for:

  • Table or index entries that are out of sequence
  • Misformatted records
  • Missing pages
  • Missing or surplus index entries
  • UNIQUE, CHECK, and NOT NULL constraint errors
  • Integrity of the freelist
  • Sections of the database that are used more than once, or not at all

If the integrity_check pragma finds problems, strings are returned
(as multiple rows with a single column per row) which describe
the problems. Pragma integrity_check will return at most N
errors before the analysis quits, with N defaulting
to 100. If pragma integrity_check finds no errors, a
single row with the value ‘ok’ is returned.

The usual case is that the entire database file is checked. However,
if the argument is TABLENAME, then checking is only performed for the
the table named and its associated indexes.
This is called a «partial integrity check». Because only a subset of the
database is checked, errors such as unused sections of the file or duplication
use of the same section of the file by two or more tables cannot be detected.
The freelist is only verified on a
partial integrity check if TABLENAME is sqlite_schema or one of its
aliases. Support for partial integrity checks was added with
version 3.33.0 (2020-08-14).

PRAGMA integrity_check does not find
FOREIGN KEY errors.
Use the PRAGMA foreign_key_check command to find errors in
FOREIGN KEY constraints.

See also the PRAGMA quick_check command which does most of the
checking of PRAGMA integrity_check but runs much faster.


PRAGMA schema.journal_mode;

PRAGMA
schema.journal_mode
= DELETE | TRUNCATE | PERSIST | MEMORY | WAL | OFF

This pragma queries or sets the journal mode for databases
associated with the current database connection.

The first form of this pragma queries the current journaling
mode for database. When database is omitted, the
«main» database is queried.

The second form changes the journaling mode for «database»
or for all attached databases if «database» is omitted.
The new journal mode is returned. If the journal mode
could not be changed, the original journal mode is returned.

The DELETE journaling mode is the normal behavior. In the DELETE
mode, the rollback journal is deleted at the conclusion of each
transaction. Indeed, the delete operation is the action that causes
the transaction to commit.
(See the document titled
Atomic Commit In SQLite for additional detail.)

The TRUNCATE journaling mode commits transactions by truncating
the rollback journal to zero-length instead of deleting it. On many
systems, truncating a file is much faster than deleting the file since
the containing directory does not need to be changed.

The PERSIST journaling mode prevents the rollback journal from
being deleted at the end of each transaction. Instead, the header
of the journal is overwritten with zeros. This will prevent other
database connections from rolling the journal back. The PERSIST
journaling mode is useful as an optimization on platforms where
deleting or truncating a file is much more expensive than overwriting
the first block of a file with zeros. See also:
PRAGMA journal_size_limit and SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT.

The MEMORY journaling mode stores the rollback journal in
volatile RAM. This saves disk I/O but at the expense of database
safety and integrity. If the application using SQLite crashes in
the middle of a transaction when the MEMORY journaling mode is set,
then the database file will very likely
go corrupt.

The WAL journaling mode uses a write-ahead log instead of a
rollback journal to implement transactions. The WAL journaling mode
is persistent; after being set it stays in effect
across multiple database connections and after closing and
reopening the database. A database in WAL journaling mode
can only be accessed by SQLite version 3.7.0 (2010-07-21)
or later.

The OFF journaling mode disables the rollback journal completely.
No rollback journal is ever created and hence there is never a rollback
journal to delete. The OFF journaling mode disables the atomic
commit and rollback capabilities of SQLite. The ROLLBACK command
no longer works; it behaves in an undefined way. Applications must
avoid using the ROLLBACK command when the journal mode is OFF.
If the application crashes
in the middle of a transaction when the OFF journaling mode is
set, then the database file will very likely
go corrupt. Without a journal, there is no way for
a statement to unwind partially completed operations following
a constraint error. This might also leave the database in a corrupted
state. For example, if a duplicate entry causes a
CREATE UNIQUE INDEX statement to fail half-way through,
it will leave behind a partially created, and hence corrupt, index.
Because OFF journaling
mode allows the database file to be corrupted using ordinary SQL,
it is disabled when SQLITE_DBCONFIG_DEFENSIVE is enabled.

Note that the journal_mode for an in-memory database
is either MEMORY or OFF and can not be changed to a different value.
An attempt to change the journal_mode of an in-memory database to
any setting other than MEMORY or OFF is ignored. Note also that
the journal_mode cannot be changed while a transaction is active.



PRAGMA
schema.journal_size_limit
PRAGMA
schema.journal_size_limit = N ;

If a database connection is operating in
exclusive locking mode or in
persistent journal mode
(PRAGMA journal_mode=persist) then
after committing a transaction the rollback journal file may remain in
the file-system. This increases performance for subsequent transactions
since overwriting an existing file is faster than append to a file,
but it also consumes
file-system space. After a large transaction (e.g. a VACUUM),
the rollback journal file may consume a very large amount of space.

Similarly, in WAL mode, the write-ahead log file is not truncated
following a checkpoint. Instead, SQLite reuses the existing file
for subsequent WAL entries since overwriting is faster than appending.

The journal_size_limit pragma may be used to limit the size of
rollback-journal and WAL files left
in the file-system after transactions or checkpoints.
Each time a transaction is committed or a WAL file resets, SQLite
compares the size of the rollback journal file or WAL file left in
the file-system to the size limit
set by this pragma and if the journal or WAL file is larger
it is truncated to the limit.

The second form of the pragma listed above is used to set a new limit
in bytes for the specified database. A negative number implies no limit.
To always truncate rollback journals and WAL files to their minimum size,
set the journal_size_limit to zero.
Both the first and second forms of the pragma listed above return a single
result row containing a single integer column — the value of the journal
size limit in bytes. The default journal size limit is -1 (no limit). The
SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT preprocessor macro can be used to change
the default journal size limit at compile-time.

This pragma only operates on the single database specified prior
to the pragma name (or on the «main» database if no database is specified.)
There is no way to change the journal size limit on all attached databases
using a single PRAGMA statement. The size limit must be set separately for
each attached database.


PRAGMA legacy_alter_table;

PRAGMA legacy_alter_table = boolean

This pragma sets or queries the value of the legacy_alter_table
flag. When this flag is on, the ALTER TABLE RENAME
command (for changing the name of a table) works as it did
in SQLite 3.24.0 (2018-06-04) and earlier. More specifically,
when this flag is on
the ALTER TABLE RENAME command only rewrites the initial occurrence
of the table name in its CREATE TABLE statement and in any associated
CREATE INDEX and CREATE TRIGGER statements. Other references to the
table are unmodified, including:

  • References to the table within the bodies of triggers and views.
  • References to the table within CHECK constraints in the original
    CREATE TABLE statement.
  • References to the table within the WHERE clauses of partial indexes.

The default setting for this pragma is OFF, which means that all
references to the table anywhere in the schema are converted to the new name.

This pragma is provided as a work-around for older programs that
contain code that expect the incomplete behavior
of ALTER TABLE RENAME found in older versions of SQLite.
New applications should leave this flag turned off.

For compatibility with older virtual table implementations,
this flag is turned on temporarily while the sqlite3_module.xRename
method is being run. The value of this flag is restored after the
sqlite3_module.xRename method finishes.

The legacy alter table behavior can also be toggled on and off
using the SQLITE_DBCONFIG_LEGACY_ALTER_TABLE option to the
sqlite3_db_config() interface.

The legacy alter table behavior is a per-connection setting. Turning
this features on or off affects all attached database files within the
database connection.
The setting does not persist. Changing this setting in one connection
does not affect any other connections.


PRAGMA legacy_file_format;

This pragma no longer functions. It has become a no-op.
The capabilities formerly provided by PRAGMA legacy_file_format
are now available using the SQLITE_DBCONFIG_LEGACY_FILE_FORMAT
option to the sqlite3_db_config() C-language interface.


PRAGMA schema.locking_mode;

PRAGMA
schema.locking_mode
= NORMAL | EXCLUSIVE

This pragma sets or queries the database connection locking-mode.
The locking-mode is either NORMAL or EXCLUSIVE.

In NORMAL locking-mode (the default unless overridden at compile-time
using SQLITE_DEFAULT_LOCKING_MODE), a database connection
unlocks the database file at the conclusion of each read or
write transaction. When the locking-mode is set to EXCLUSIVE, the
database connection never releases file-locks. The first time the
database is read in EXCLUSIVE mode, a shared lock is obtained and
held. The first time the database is written, an exclusive lock is
obtained and held.

Database locks obtained by a connection in EXCLUSIVE mode may be
released either by closing the database connection, or by setting the
locking-mode back to NORMAL using this pragma and then accessing the
database file (for read or write). Simply setting the locking-mode to
NORMAL is not enough — locks are not released until the next time
the database file is accessed.

There are three reasons to set the locking-mode to EXCLUSIVE.

  1. The application wants to prevent other processes from
    accessing the database file.
  2. The number of system calls for filesystem operations is reduced,
    possibly resulting in a small performance increase.
  3. WAL databases can be accessed in EXCLUSIVE mode without the
    use of shared memory.
    (Additional information)

When the locking_mode pragma specifies a particular database,
for example:

PRAGMA main.locking_mode=EXCLUSIVE;

then the locking mode applies only to the named database. If no
database name qualifier precedes the «locking_mode» keyword then
the locking mode is applied to all databases, including any new
databases added by subsequent ATTACH commands.

The «temp» database (in which TEMP tables and indices are stored)
and in-memory databases
always uses exclusive locking mode. The locking mode of temp and
in-memory databases cannot
be changed. All other databases use the normal locking mode by default
and are affected by this pragma.

If the locking mode is EXCLUSIVE when first entering
WAL journal mode, then the locking mode cannot be changed to
NORMAL until after exiting WAL journal mode.
If the locking mode is NORMAL when first entering WAL
journal mode, then the locking mode can be changed between NORMAL and
EXCLUSIVE and back again at any time and without needing to exit
WAL journal mode.


PRAGMA schema.max_page_count;

PRAGMA
schema.max_page_count = N;

Query or set the maximum number of pages in the database file.
Both forms of the pragma return the maximum page count. The second
form attempts to modify the maximum page count. The maximum page
count cannot be reduced below the current database size.


PRAGMA schema.mmap_size;

PRAGMA
schema.mmap_size=N

Query or change the maximum number of bytes that are set
aside for memory-mapped I/O on a single database. The first form
(without an argument) queries the current limit. The second
form (with a numeric argument) sets the limit for the specified
database, or for all databases if the optional database name is
omitted. In the second form, if the database name is omitted, the
limit that is set becomes the default limit for all databases that
are added to the database connection by subsequent ATTACH
statements.

The argument N is the maximum number of bytes of the database file
that will be accessed using memory-mapped I/O. If N is zero then
memory mapped I/O is disabled. If N is negative, then the limit
reverts to the default value determined by the most recent
sqlite3_config(SQLITE_CONFIG_MMAP_SIZE), or to the compile
time default determined by SQLITE_DEFAULT_MMAP_SIZE if not
start-time limit has been set.

The PRAGMA mmap_size statement will never increase the amount
of address space used for memory-mapped I/O above the
hard limit set by the SQLITE_MAX_MMAP_SIZE compile-time option,
nor the hard limit set at startup-time by the second argument to
sqlite3_config(SQLITE_CONFIG_MMAP_SIZE)

The size of the memory-mapped I/O region cannot be changed while
the memory-mapped I/O region is in active use, to avoid unmapping
memory out from under running SQL statements. For this reason,
the mmap_size pragma may be a no-op if the prior mmap_size is non-zero
and there are other SQL statements running concurrently on the same
database connection.


PRAGMA module_list;

This pragma returns a list of
virtual table modules registered with the database connection.


PRAGMA optimize;

PRAGMA optimize(
MASK);

PRAGMA
schema.optimize;

PRAGMA
schema.optimize(MASK);

Attempt to optimize the database. All schemas are optimized in the
first two forms, and only the specified schema is optimized in the latter
two.

To achieve the best long-term query performance without the need to
do a detailed engineering analysis of the application schema and SQL,
it is recommended that applications run «PRAGMA optimize» (with no arguments)
just before closing each database connection. Long-running applications
might also benefit from setting a timer to run «PRAGMA optimize» every
few hours.

This pragma is usually a no-op or nearly so and is very fast.
However if SQLite feels
that performing database optimizations (such as running ANALYZE
or creating new indexes) will improve the performance of future queries, then
some database I/O may be done. Applications that want to limit the amount
of work performed can set a timer that will invoke
sqlite3_interrupt() if the pragma goes on for too long.
Or, since SQLite 3.32.0, the application can use
PRAGMA analysis_limit=N for some small
value of N (a few hundred or a few thousand) to limit the depth
of analyze.

The details of optimizations performed by this pragma are expected
to change and improve over time. Applications should anticipate that
this pragma will perform new optimizations in future releases.

The optional MASK argument is a bitmask of optimizations to perform:

  1. Debugging mode. Do not actually perform any optimizations
    but instead return one line of text for each optimization
    that would have been done. Off by default.

  2. Run ANALYZE on tables that might benefit. On by default.
    See below for additional information.

  3. (Not yet implemented)
    Record usage and performance
    information from the current session in the
    database file so that it will be available to «optimize»
    pragmas run by future database connections.

  4. (Not yet implemented)
    Create indexes that might have been helpful to recent queries.

The default MASK is and always shall be 0xfffe. The 0xfffe mask means
perform all of the optimizations listed above except Debug Mode. If new
optimizations are added in the future that should be off by default, those
new optimizations will be given a mask of 0x10000 or larger.

To see all optimizations that would have been done without actually
doing them, run «PRAGMA optimize(-1)». To use only the ANALYZE
optimization, run «PRAGMA optimize(0x02)».

Determination Of When To Run Analyze

In the current implementation, a table is analyzed if and only if
all of the following are true:

  • MASK bit 0x02 is set.

  • The query planner used sqlite_stat1-style statistics for one or
    more indexes of the table at some point during the lifetime of
    the current connection.

  • One or more indexes of the table are currently unanalyzed or
    the number of rows in the table has increased by 25 times or more
    since the last time ANALYZE was run.

The rules for when tables are analyzed are likely to change in
future releases.


PRAGMA schema.page_count;

Return the total number of pages in the database file.


PRAGMA schema.page_size;

PRAGMA
schema.page_size = bytes;

Query or set the page size of the database. The page
size must be a power of two between 512 and 65536 inclusive.

When a new database is created, SQLite assigns a page size to
the database based on platform and filesystem. For many years,
the default page size was almost always 1024 bytes, but beginning
with SQLite version 3.12.0 (2016-03-29),
the default page size increased to 4096.
The default page size is recommended for most applications.

Specifying a new page size does not change the page size
immediately. Instead, the new page size is remembered and is used
to set the page size when the database is first created, if it does
not already exist when the page_size pragma is issued, or at the
next VACUUM command that is run on the same database connection
while not in WAL mode.

The SQLITE_DEFAULT_PAGE_SIZE compile-time option can be used
to change the default page size assigned to new databases.


PRAGMA parser_trace = boolean;

If SQLite has been compiled with the SQLITE_DEBUG compile-time
option, then the parser_trace pragma can be used to turn on tracing
for the SQL parser used internally by SQLite.
This feature is used for debugging SQLite itself.

This pragma is intended for use when debugging SQLite itself. It
is only available when the SQLITE_DEBUG compile-time option
is used.


PRAGMA pragma_list;

This pragma returns a list of PRAGMA commands
known to the database connection.


PRAGMA query_only;

PRAGMA query_only =
boolean;

The query_only pragma prevents data changes on database files when
enabled. When this pragma is enabled, any attempt to CREATE, DELETE,
DROP, INSERT, or UPDATE will result in an SQLITE_READONLY error.
However, the database is not truly read-only. You can still run
a checkpoint or a COMMIT and the return value of the
sqlite3_db_readonly() routine is not affected.


PRAGMA schema.quick_check;

PRAGMA
schema.quick_check(N)

PRAGMA schema.quick_check(TABLENAME)

The pragma is like integrity_check except that it does not verify
UNIQUE constraints and does not verify
that index content matches table content. By skipping UNIQUE
and index consistency checks, quick_check is able to run faster.
PRAGMA quick_check runs in O(N) time whereas PRAGMA integrity_check
requires O(NlogN) time where N is the total number of rows in the
database. Otherwise the two pragmas are the same.


PRAGMA read_uncommitted;

PRAGMA read_uncommitted =
boolean;

Query, set, or clear READ UNCOMMITTED isolation. The default isolation
level for SQLite is SERIALIZABLE. Any process or thread can select
READ UNCOMMITTED isolation, but SERIALIZABLE will still be used except
between connections that share a common page and schema cache.
Cache sharing is enabled using the sqlite3_enable_shared_cache() API.
Cache sharing is disabled by default.

See SQLite Shared-Cache Mode for additional information.


PRAGMA recursive_triggers;

PRAGMA recursive_triggers =
boolean;

Query, set, or clear the recursive trigger capability.

Changing the recursive_triggers setting affects the execution of
all statements prepared
using the database connection, including those prepared before the
setting was changed. Any existing statements prepared using the legacy
sqlite3_prepare() interface may fail with an SQLITE_SCHEMA error
after the recursive_triggers setting is changed.

Prior to SQLite version 3.6.18 (2009-09-11),
recursive triggers were not supported.
The behavior of SQLite was always as if this pragma was
set to OFF. Support for recursive triggers was added in version 3.6.18
but was initially turned OFF by default, for compatibility. Recursive
triggers may be turned on by default in future versions of SQLite.

The depth of recursion for triggers has a hard upper limit set by
the SQLITE_MAX_TRIGGER_DEPTH compile-time option and a run-time
limit set by sqlite3_limit(db,SQLITE_LIMIT_TRIGGER_DEPTH,…).


PRAGMA reverse_unordered_selects;

PRAGMA reverse_unordered_selects =
boolean;

When enabled, this PRAGMA causes many SELECT statements without
an ORDER BY clause to emit their results in the reverse order from what
they normally would. This can help debug applications that are
making invalid assumptions about the result order.
The reverse_unordered_selects pragma works for most SELECT statements,
however the query planner may sometimes choose an algorithm that is
not easily reversed, in which case the output will appear in the same
order regardless of the reverse_unordered_selects setting.

SQLite makes no
guarantees about the order of results if a SELECT omits the ORDER BY
clause. Even so, the order of results does not change from one
run to the next, and so many applications mistakenly come to depend
on the arbitrary output order whatever that order happens to be. However,
sometimes new versions of SQLite will contain optimizer enhancements
that will cause the output order of queries without ORDER BY clauses
to shift. When that happens, applications that depend on a certain
output order might malfunction. By running the application multiple
times with this pragma both disabled and enabled, cases where the
application makes faulty assumptions about output order can be
identified and fixed early, reducing problems
that might be caused by linking against a different version of SQLite.


PRAGMA schema.schema_version;

PRAGMA
schema.schema_version = integer ;

The schema_version pragma will get or set
the value of the schema-version integer at offset 40 in the
database header.

SQLite automatically increments the schema-version whenever the
schema changes. As each SQL statement runs, the schema version is
checked to ensure that the schema has not changed since the SQL
statement was prepared.
Subverting this mechanism by using «PRAGMA schema_version=N»
to change the value of the schema_version
may cause SQL statement to run using an obsolete schema,
which can lead to incorrect answers and/or
database corruption.
It is always safe to read the schema_version, but changing the
schema_version can cause problems. For this reason, attempts
to change the value of schema_version are a silent no-op when
defensive mode is enabled for a
database connection.


Warning:
Misuse of this pragma can result in database corruption.

For the purposes of this pragma, the VACUUM command is considered
a schema change, since VACUUM will usually alter the «rootpage»
values for entries in the sqlite_schema table.

See also the application_id pragma and user_version pragma.


PRAGMA schema.secure_delete;

PRAGMA
schema.secure_delete = boolean|FAST

Query or change the secure-delete setting. When secure_delete is
on, SQLite overwrites deleted content with zeros. The default
setting for secure_delete is determined by the SQLITE_SECURE_DELETE
compile-time option and is normally off. The off setting for
secure_delete improves performance by reducing the number of CPU cycles
and the amount of disk I/O. Applications that wish to avoid leaving
forensic traces after content is deleted or updated should enable the
secure_delete pragma prior to performing the delete or update, or else
run VACUUM after the delete or update.

The «fast» setting for secure_delete (added circa 2017-08-01)
is an intermediate setting in between «on» and «off».
When secure_delete is set to «fast»,
SQLite will overwrite deleted content with zeros only if doing so
does not increase the amount of I/O. In other words, the «fast»
setting uses more CPU cycles but does not use more I/O.
This has the effect of purging all old content from b-tree pages,
but leaving forensic traces on freelist pages.

When there are attached databases and no database
is specified in the pragma, all databases have their secure-delete
setting altered.
The secure-delete setting for newly attached databases is the setting
of the main database at the time the ATTACH command is evaluated.

When multiple database connections share the same cache, changing
the secure-delete flag on one database connection changes it for them
all.


PRAGMA short_column_names;

PRAGMA short_column_names =
boolean;

Query or change the short-column-names flag. This flag affects
the way SQLite names columns of data returned by SELECT statements.
See the full_column_names pragma for full details.

This pragma is deprecated and exists
for backwards compatibility only. New applications
should avoid using this pragma. Older applications should discontinue
use of this pragma at the earliest opportunity. This pragma may be omitted
from the build when SQLite is compiled using SQLITE_OMIT_DEPRECATED.


PRAGMA shrink_memory

This pragma causes the database connection on which it is invoked
to free up as much memory as it can, by calling
sqlite3_db_release_memory().


PRAGMA soft_heap_limit
PRAGMA soft_heap_limit=
N

This pragma invokes the sqlite3_soft_heap_limit64() interface with
the argument N, if N is specified and is a non-negative integer.
The soft_heap_limit pragma always returns the same integer
that would be returned by the sqlite3_soft_heap_limit64(-1) C-language
function.

See also the hard_heap_limit pragma.


PRAGMA stats;

This pragma returns auxiliary information about tables and
indices. The returned information is used during testing to help
verify that the query planner is operating correctly. The format
and meaning of this pragma will likely change from one release
to the next. Because of its volatility, the behavior and output
format of this pragma are deliberately undocumented.

The intended use of this pragma is only for testing and validation of
SQLite. This pragma is subject to change without notice and is not
recommended for use by application programs.


PRAGMA schema.synchronous;

PRAGMA
schema.synchronous =
0 | OFF | 1 | NORMAL | 2 | FULL | 3 | EXTRA;

Query or change the setting of the «synchronous» flag.
The first (query) form will return the synchronous setting as an
integer. The second form changes the synchronous setting.
The meanings of the various synchronous settings are as follows:

EXTRA (3)
EXTRA synchronous is like FULL with the addition that the directory
containing a rollback journal is synced after that journal is unlinked
to commit a transaction in DELETE mode. EXTRA provides additional
durability if the commit is followed closely by a power loss.
FULL (2)
When synchronous is FULL (2), the SQLite database engine will
use the xSync method of the VFS to ensure that all content is safely
written to the disk surface prior to continuing.
This ensures that an operating system crash or power failure will
not corrupt the database.
FULL synchronous is very safe, but it is also slower. FULL is the
most commonly used synchronous setting when not in WAL mode.
NORMAL (1)
When synchronous is NORMAL (1), the SQLite database
engine will still sync at the most critical moments, but less often
than in FULL mode. There is a very small (though non-zero) chance that
a power failure at just the wrong time could corrupt the database in
journal_mode=DELETE on an older filesystem.
WAL mode is safe from corruption with synchronous=NORMAL, and probably
DELETE mode is safe too on modern filesystems. WAL mode is always consistent
with synchronous=NORMAL, but WAL mode does lose durability. A transaction
committed in WAL mode with synchronous=NORMAL might roll back following
a power loss or system crash. Transactions are durable across application
crashes regardless of the synchronous setting or journal mode.
The synchronous=NORMAL setting is a good choice for most applications
running in WAL mode.
OFF (0)
With synchronous OFF (0), SQLite continues without syncing
as soon as it has handed data off to the operating system.
If the application running SQLite crashes, the data will be safe, but
the database might become corrupted if the operating system
crashes or the computer loses power before that data has been written
to the disk surface. On the other hand, commits can be orders of
magnitude faster with synchronous OFF.

In WAL mode when synchronous is NORMAL (1), the WAL file is
synchronized before each checkpoint and the database file is
synchronized after each completed checkpoint and the WAL file
header is synchronized when a WAL file begins to be reused after
a checkpoint, but no sync operations occur during most transactions.
With synchronous=FULL in WAL mode, an additional
sync operation of the WAL file happens after each transaction commit.
The extra WAL sync following each transaction helps ensure that
transactions are durable across a power loss. Transactions are
consistent with or without the extra syncs provided by
synchronous=FULL.
If durability is not a concern, then synchronous=NORMAL is normally
all one needs in WAL mode.

The TEMP schema always has synchronous=OFF since the content of
of TEMP is ephemeral and is not expected to survive a power outage.
Attempts to change the synchronous setting for TEMP are
silently ignored.

See also the fullfsync and checkpoint_fullfsync pragmas.


PRAGMA schema.table_info(table-name);

This pragma returns one row for each normal column
in the named table.
Columns in the result set include: «name» (its name); «type»
(data type if given, else »); «notnull» (whether or not the column
can be NULL); «dflt_value» (the default value for the column);
and «pk» (either zero for columns that are not part of the primary key,
or the 1-based index of the column within the primary key).

The «cid» column should not be taken to mean more than
«rank within the current result set».

The table named in the table_info pragma can also be a view.

This pragma does not show information about generated columns or
hidden columns. Use PRAGMA table_xinfo to get a more complete list
of columns that includes generated and hidden columns.


PRAGMA table_list;

PRAGMA
schema.table_list;

PRAGMA table_list(
table-name);

This pragma returns information about the tables and views in the schema,
one table per row of output. The table_list pragma first appeared
in SQLite version 3.37.0 (2021-11-27). As of its initial release
the columns returned by the table_list pragma include those listed below.
Future versions of SQLite will probably add additional columns of
output.

  1. schema: the schema in which the table or view appears
    (for example «main» or «temp»).
  2. name: the name of the table or view.
  3. type: the type of object — one of «table», «view»,
    «shadow» (for shadow tables), or «virtual» for
    virtual tables.
  4. ncol: the number of columns in the table, including
    generated columns and hidden columns.
  5. wr: 1 if the table is a WITHOUT ROWID table or 0 if is not.
  6. strict: 1 if the table is a STRICT table or 0 if it is not.
  7. Additional columns will likely be added in future releases.

The default behavior is to show all tables in all schemas. If the
schema. name appears before the pragma, then only tables in that
one schema are shown. If a table-name argument is supplied, then
only information about that one table is returned.


PRAGMA schema.table_xinfo(table-name);

This pragma returns one row for each column in the named table,
including generated columns and hidden columns.
The output has the same columns as for PRAGMA table_info plus
a column, «hidden», whose value signifies a normal column (0),
a dynamic or stored generated column (2 or 3),
or a hidden column in a virtual table (1). The rows for which
this field is non-zero are those omitted for PRAGMA table_info.


PRAGMA temp_store;

PRAGMA temp_store =

0 | DEFAULT | 1 | FILE | 2 | MEMORY;

Query or change the setting of the «temp_store» parameter.
When temp_store is DEFAULT (0), the compile-time C preprocessor macro
SQLITE_TEMP_STORE is used to determine where temporary tables and indices
are stored. When
temp_store is MEMORY (2) temporary tables and indices are kept
as if they were in pure in-memory databases.
When temp_store is FILE (1) temporary tables and indices are stored
in a file. The temp_store_directory pragma can be used to specify
the directory containing temporary files when
FILE is specified. When the temp_store setting is changed,
all existing temporary tables, indices, triggers, and views are
immediately deleted.

It is possible for the library compile-time C preprocessor symbol
SQLITE_TEMP_STORE to override this pragma setting.
The following table summarizes
the interaction of the SQLITE_TEMP_STORE preprocessor macro and the
temp_store pragma:

SQLITE_TEMP_STORE PRAGMA
temp_store
Storage used for
TEMP tables and indices
0 any file
1 0 file
1 1 file
1 2 memory
2 0 memory
2 1 file
2 2 memory
3 any memory

PRAGMA temp_store_directory;

PRAGMA temp_store_directory = ‘
directory-name‘;

Query or change the value of the sqlite3_temp_directory global
variable, which many operating-system interface backends use to
determine where to store temporary tables and indices.

When the temp_store_directory setting is changed, all existing temporary
tables, indices, triggers, and viewers in the database connection that
issued the pragma are immediately deleted. In
practice, temp_store_directory should be set immediately after the first
database connection for a process is opened. If the temp_store_directory
is changed for one database connection while other database connections
are open in the same process, then the behavior is undefined and
probably undesirable.

Changing the temp_store_directory setting is not threadsafe.
Never change the temp_store_directory setting if another thread
within the application is running any SQLite interface at the same time.
Doing so results in undefined behavior. Changing the temp_store_directory
setting writes to the sqlite3_temp_directory global
variable and that global variable is not protected by a mutex.

The value directory-name should be enclosed in single quotes.
To revert the directory to the default, set the directory-name to
an empty string, e.g., PRAGMA temp_store_directory = ». An
error is raised if directory-name is not found or is not
writable.

The default directory for temporary files depends on the OS. Some
OS interfaces may choose to ignore this variable and place temporary
files in some other directory different from the directory specified
here. In that sense, this pragma is only advisory.

This pragma is deprecated and exists
for backwards compatibility only. New applications
should avoid using this pragma. Older applications should discontinue
use of this pragma at the earliest opportunity. This pragma may be omitted
from the build when SQLite is compiled using SQLITE_OMIT_DEPRECATED.


PRAGMA threads;

PRAGMA threads =
N;

Query or change the value of the
sqlite3_limit(db,SQLITE_LIMIT_WORKER_THREADS,…) limit for
the current database connection. This limit sets an upper bound
on the number of auxiliary threads that a prepared statement is
allowed to launch to assist with a query. The default limit is 0
unless it is changed using the SQLITE_DEFAULT_WORKER_THREADS
compile-time option. When the limit is zero, that means no
auxiliary threads will be launched.

This pragma is a thin wrapper around the
sqlite3_limit(db,SQLITE_LIMIT_WORKER_THREADS,…) interface.


PRAGMA trusted_schema;

PRAGMA trusted_schema =
boolean;

The trusted_schema setting is a per-connection boolean that
determines whether or not SQL functions and virtual tables that
have not been security audited are allowed to be run by views,
triggers, or in expressions of the schema such as CHECK constraints,
DEFAULT clauses, generated columns, expression indexes, and/or
partial indexes. This setting can also be controlled using
the sqlite3_db_config(db,SQLITE_DBCONFIG_TRUSTED_SCHEMA,…)
C-language interface.

In order to maintain backwards compatibility, this setting is
ON by default. There are advantages to turning it off, and most
applications will be unaffected if it is turned off. For that reason,
all applications are encouraged to switch this setting off on every
database connection as soon as that connection is opened.

The -DSQLITE_TRUSTED_SCHEMA=0 compile-time option will cause
this setting to default to OFF.


PRAGMA schema.user_version;

PRAGMA
schema.user_version = integer ;

The user_version pragma will get or set
the value of the user-version integer at offset 60 in the
database header. The user-version is an integer that is
available to applications to use however they want. SQLite
makes no use of the user-version itself.

See also the application_id pragma and schema_version pragma.


PRAGMA vdbe_addoptrace = boolean;

If SQLite has been compiled with the SQLITE_DEBUG compile-time
option, then the vdbe_addoptrace pragma can be used to cause a complete
VDBE opcodes to be displayed as they are created during code generation.
This feature is used for debugging SQLite itself. See the
VDBE documentation for more
information.

This pragma is intended for use when debugging SQLite itself. It
is only available when the SQLITE_DEBUG compile-time option
is used.


PRAGMA vdbe_debug = boolean;

If SQLite has been compiled with the SQLITE_DEBUG compile-time
option, then the vdbe_debug pragma is a shorthand for three other
debug-only pragmas: vdbe_addoptrace, vdbe_listing, and vdbe_trace.
This feature is used for debugging SQLite itself. See the
VDBE documentation for more
information.

This pragma is intended for use when debugging SQLite itself. It
is only available when the SQLITE_DEBUG compile-time option
is used.


PRAGMA vdbe_listing = boolean;

If SQLite has been compiled with the SQLITE_DEBUG compile-time
option, then the vdbe_listing pragma can be used to cause a complete
listing of the virtual machine opcodes to appear on standard output
as each statement is evaluated.
With listing is on, the entire content of a program is printed
just prior to beginning execution. The statement
executes normally after the listing is printed.
This feature is used for debugging SQLite itself. See the
VDBE documentation for more
information.

This pragma is intended for use when debugging SQLite itself. It
is only available when the SQLITE_DEBUG compile-time option
is used.


PRAGMA vdbe_trace = boolean;

If SQLite has been compiled with the SQLITE_DEBUG compile-time
option, then the vdbe_trace pragma can be used to cause virtual machine
opcodes to be printed on standard output as they are evaluated.
This feature is used for debugging SQLite. See the
VDBE documentation for more
information.

This pragma is intended for use when debugging SQLite itself. It
is only available when the SQLITE_DEBUG compile-time option
is used.


PRAGMA wal_autocheckpoint;
PRAGMA wal_autocheckpoint=
N;

This pragma queries or sets the write-ahead log
auto-checkpoint interval.
When the write-ahead log is enabled (via the
journal_mode pragma) a checkpoint will be run automatically whenever
the write-ahead log equals or exceeds N pages in length.
Setting the auto-checkpoint size to zero or a negative value
turns auto-checkpointing off.

This pragma is a wrapper around the
sqlite3_wal_autocheckpoint() C interface.
All automatic checkpoints are PASSIVE.

Autocheckpointing is enabled by default with an interval
of 1000 or SQLITE_DEFAULT_WAL_AUTOCHECKPOINT.


PRAGMA schema.wal_checkpoint;
PRAGMA schema.wal_checkpoint(PASSIVE);
PRAGMA schema.wal_checkpoint(FULL);
PRAGMA schema.wal_checkpoint(RESTART);
PRAGMA schema.wal_checkpoint(TRUNCATE);

If the write-ahead log is enabled (via the journal_mode pragma),
this pragma causes a checkpoint operation to run on database
database, or on all attached databases if database
is omitted. If write-ahead log mode is disabled, this pragma is a
harmless no-op.

Invoking this
pragma without an argument is equivalent to calling the
sqlite3_wal_checkpoint() C interface.

Invoking this pragma with an argument is equivalent to calling the
sqlite3_wal_checkpoint_v2() C interface with a
3rd parameter
corresponding to the argument:

PASSIVE
Checkpoint as many frames as possible without waiting for any database
readers or writers to finish. Sync the db file if all frames in the log
are checkpointed. This mode is the same as calling the
sqlite3_wal_checkpoint() C interface. The
busy-handler callback is never invoked in
this mode.

FULL
This mode blocks
(invokes the busy-handler callback)
until there is no
database writer and all readers are reading from the most recent database
snapshot. It then checkpoints all frames in the log file and syncs the
database file. FULL blocks concurrent writers while it is
running, but readers can proceed.

RESTART
This mode works the same way as FULL with the addition that after
checkpointing the log file it blocks (calls the
busy-handler callback)
until all readers are finished with the log file. This ensures
that the next client to write to the database file restarts the log file
from the beginning. RESTART blocks concurrent writers while it is
running, but allowed readers to proceed.

TRUNCATE
This mode works the same way as RESTART with the
addition that the WAL file is truncated to zero bytes upon successful
completion.

The wal_checkpoint pragma returns a single row with three
integer columns. The first column is usually 0 but will be
1 if a RESTART or FULL or TRUNCATE checkpoint was blocked from completing,
for example because another thread or process was actively
using the database. In other words, the first column is 0 if the
equivalent call to sqlite3_wal_checkpoint_v2() would have returned
SQLITE_OK or 1 if the equivalent call would have returned SQLITE_BUSY.
The second column is the number of modified pages that have been
written to the write-ahead log file.
The third column is the number of pages in the write-ahead log file
that have been successfully moved back into the database file at
the conclusion of the checkpoint.
The second and third column are -1 if there is no
write-ahead log, for example if this pragma is invoked on a database
connection that is not in WAL mode.


PRAGMA writable_schema = boolean;
PRAGMA writable_schema = RESET

When this pragma is on, and the SQLITE_DBCONFIG_DEFENSIVE flag
is off, then the sqlite_schema table
can be changed using ordinary UPDATE, INSERT, and DELETE
statements. If the argument is «RESET» then schema writing is
disabled (as with «PRAGMA writable_schema=OFF») and, in addition, the
schema is reloaded. Warning:
misuse of this pragma can easily result in
a corrupt database file.


This page last modified on 2022-12-25 13:08:46 UTC

Понравилась статья? Поделить с друзьями:
  • 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