SQL object not being reinitialized

166 views
Skip to first unread message

David Gilmore

unread,
Sep 22, 2026, 10:13:21 AMSep 22
to mementodatabase
Reporrting a possible serious issue with the SQL select object (and also to see if anyone else is seeing this).

I have a library that contains a check box ("Mark"), and have a script to scan the library to clear that check box. The way I have been doing that is:

var entries = lib().entries();
for (let e of entries) {
  e.set("Mark", false);
  EntryColor(e);
}

However, this script takes a few seconds to run (library has > 100 entries). In an attempt to speed it up, script was changed to:

var ssql = "SELECT * FROM ToDo WHERE Mark = true";
var entries = sql(ssql).asEntries();
var cnt = entries.length; // (Added for debugging)
message(cnt.toString());
for (let e of entries) {
  e.set("Mark", false);
  EntryColor(e);
}

Much faster. But this changed script only works the first time. The first time it will only return the entries where "Mark" is set. The routine then resets "Mark". Running the script again returns those same records that were returned the first time. Also, the "cnt" count returns say 4 the first time, and again 4 the second time, even though the "cnt" should now be 0.

I believe the SQL object is not being cleared/closed properly after the sql object is run and then done with. The erroneous results will continue even when the Memento app is closed, and restarted. However, a force close of Memento will clear the sql, and the next time the script is run it will work properly.

This is on Android (Samsung GS25 Ultra). I have not tried this on a PC or iOS. I have also reported this directly to Memento.

Er Mo

unread,
Sep 22, 2026, 12:16:29 PMSep 22
to mementodatabase
Hallo
Man kann auch direkt unter Memento suchen / Filtern und so das gleicher Suchergebnis zu erhalten . Die beschriebenen Fehle habe ich da nicht bemerkt.

Hello,
You can also search or filter directly under "Memento" to get the same search result. I didn't notice the errors described when doing that.

Ernst

David Gilmore

unread,
Sep 22, 2026, 12:36:00 PMSep 22
to mementodatabase
Guter Tag, Ernst,

I am doing all of this in script, so filtering or searching using the UI is not applicable.

Mmm

unread,
Sep 22, 2026, 2:06:35 PMSep 22
to mementodatabase
Я не увидел решения ошибки запросов SQL для одноименных библиотек. 
Если есть одноименная библиотека, то все запросы выполняются к библиотеке с наименьшим индексом (созданной ранее). Поэтому Вы не видите выполненные изменения.

Попробуйте добавить:
return true;

Например, в функцию EntryColor(e) или другим способом.
Обычно это помогает. 
Если Вы создадите тестовую библиотеку и предоставите общий доступ с разрешением копирования структуры, то выявление ошибки будет упрощено.

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

В любом случае, я поддерживаю уведомление команды MDB.
Возможно Вы получите похожий ответ. Будем рады его увидеть.

вторник, 22 сентября 2026 г. в 19:36:00 UTC+3, aa6...@gmail.com:

David Gilmore

unread,
Sep 22, 2026, 5:54:16 PMSep 22
to mementodatabase
I appreciate everyone that is trying to find a work around. I already have one, by just using my old method of fetching the records.

I posted this to let anyone that is using a SQL Select statement know that under some cirumstances the returned set of entries do not match what was actually selected. My libraries are somewhat complex, so I made a simple example to demonstrate.

You can reproduce this problem yourself by taking one of your existing libraries, add a checkbox field to it, then enter the script (changing the library name and column name in the script to whatever you are using). Place the script anywhere you want (I made it a "Library Action" myself). Check your new checkbox in a couple of entries, then run the script twice. You probably will see the "count" of returned records be the same between runs, even though the script as written resets that checkbox during the first run.

var ssql = "SELECT * FROM <yourlibraryname> WHERE <yourcolumnname> = true";

var entries = sql(ssql).asEntries();
var cnt = entries.length; // (Added for debugging)
message(cnt.toString());
for (let e of entries) {
  e.set("<yourcolumnname>", false);
}

I have a simple library ready for Vasily should he request it. However, there may be something to a particular library, because when I was preparing a demonstration library from one of my existing libraries, the first one would not fail consistantly, but the second one did (the second had more fields).

David Gilmore

unread,
Sep 22, 2026, 6:14:50 PMSep 22
to mementodatabase
Here is the link to the "DailyTest" database:  https://mementodb.com/s/AUwq2NTJv

You should download it only to your Android phone, as the problem may or may not exist on other platforms.

Mmm

unread,
Sep 23, 2026, 6:35:42 AMSep 23
to mementodatabase
Был неправ, когда привел свой пример. Там другая логика. 

Скопируйте скрипт ShowComp в свою тестовую библиотеку. 
Это визуализация обсуждаемой ошибки.
Первый диалог показывает Ваш подход, второй - мой.

Открытие – закрытие библиотеки не исправляет ошибки.
Открытие – закрытие приложения или сброс кеша библиотеки устраняют ошибку.
Предположу, что не обновляется кеш библиотеки при выполнении скриптов.

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

Мгновенное изменение фильтров после выполнения скриптов работает.

среда, 23 сентября 2026 г. в 01:14:50 UTC+3, aa6...@gmail.com:
show1.jpg
show2.jpg
ShowComp.txt

Mmm

unread,
Sep 23, 2026, 6:56:54 AMSep 23
to mementodatabase
Дополнение:
Не указал, что файл ShowComp.txt содержит код для скрипта действие в библиотеке.

Это ещё раз подтверждает необходимость инструмента импорта–экспорта скриптов.
Голосование:
среда, 23 сентября 2026 г. в 13:35:42 UTC+3, Mmm:

David Gilmore

unread,
Sep 23, 2026, 10:00:36 AMSep 23
to mementodatabase
Thanks Mmm. The simple script I provided (and can be copied/pasted as needed) is valid and does work, when it works. It is simplified from what I am actually using, just to demonstrate the problem.

Like I stated originally, I believe something is not being initialized properly when the SQL is run the second time. "Force Stopping", or "clearing cache" are just some of the different ways to temporarily bypass the problem.

Hopefully Memento will come back with a solution (it was also reported directly to Memento).

Mmm

unread,
Sep 29, 2026, 10:17:11 AMSep 29
to mementodatabase
Исправлено в 5.10.0.

среда, 23 сентября 2026 г. в 17:00:36 UTC+3, aa6...@gmail.com:

David Gilmore

unread,
Sep 29, 2026, 11:13:56 AMSep 29
to mementodatabase
Thanks Mmm. Vasily notified me , and indicated the problem was due to the Boolean (check box) field, and that he will release a fix.

Mmm

unread,
Sep 29, 2026, 1:53:13 PMSep 29
to mementodatabase
Исправление даёт возможность отображать только записи, которые соответствуют условию скрипта или все записи, если условие не выполняется.

Можно считать этот прием "динамическим фильтром".

Пример реализации:
1. Скрипт выполняет действие и отмечает "Complete" true или false по своим условиям.
2. Пресет на основе запроса SQL отображает либо подходящие записи ("Complete" = true) либо все записи, если подходящие отсутствуют.

SELECT * FROM "DailyTest"
WHERE "Complete" = 1 AND removed = 0

UNION ALL

SELECT * FROM "DailyTest"
WHERE "Complete" = 0 AND removed = 0
  AND NOT EXISTS (
    SELECT 1 FROM "DailyTest"
    WHERE "Complete" = 1 AND removed = 0
  )
ORDER BY "Site" ASC;


К сожалению, при ручном изменении поля "динамический фильтр" не работает.

Давид, будет замечательно, если Вы сообщите Василию об этом в существующей переписке.

вторник, 29 сентября 2026 г. в 18:13:56 UTC+3, aa6...@gmail.com:
script.jpg
manual.png

David Gilmore

unread,
Sep 30, 2026, 10:21:48 AMSep 30
to mementodatabase
Its been my experience that Memento's implementation of SQL does not always support complex SQL statements. UPDATE and INSERT type SQL statements are other examples of what does not work.

Vasily mentioned that he does some sort of processing of the SQL statement to handle the differences between Memento's tables and the actual database they are residing in.

You are welcome to communicate directly with Vasily on this. Email sup...@mementodatabase.com


Reply all
Reply to author
Forward
0 new messages