Re: permission error using libByName

132 views
Skip to first unread message

Bill Crews

unread,
May 26, 2025, 5:01:09 PM5/26/25
to Doris Reilly, mementodatabase
Separate from the permissions of a library is allowing the script access to the library. This is done in the script editor. It likely has a Shield icon to press. 


On Mon, May 26, 2025, 14:37 Doris Reilly <doris....@gmail.com> wrote:
I am trying to create a script to automate linking records between two libraries for data that was imported from Access.  

I am using as a starting point the script example from the convo https://groups.google.com/u/1/g/mementodatabase/c/bBhGHnSQz_Y

I created a Library Action script on a library named "Home Inventory Attachments".  From that script I need to filter the related library "Home Inventory Main" to find corresponding records.

When I run the script, I get the error "PermissionError Can't access to Home Inventory Main".  I can't get to first base without resolving this error.  I can't seem to get around it, even if I grant public permission to the libraries.

I am new to JavaScript and scripting in Memento, so pardon my ignorance.  I have only a barebones script so far, just to make sure I can read the data.  Here is what I have so far:  Any help is appreciated.

******************************************

let arr = selectedEntries();
let ent = libByName('Home Inventory Main').entries();

let find = '';
let filter = [];

let i = arr.length;
message ('Number of selected entries: ' + i);

while (i--) {
  find = arr[i].field('AttachmentID');
  message(find);
}



--
You received this message because you are subscribed to the Google Groups "mementodatabase" group.
To unsubscribe from this group and stop receiving emails from it, send an email to mementodataba...@googlegroups.com.
To view this discussion visit https://groups.google.com/d/msgid/mementodatabase/5e8dd5fe-2064-401b-8205-8e2cc4ce4c94n%40googlegroups.com.

Doris Reilly

unread,
May 26, 2025, 5:14:51 PM5/26/25
to Bill Crews, mementodatabase
Thanks, Bill...I figured that out about 30 seconds after I hit send.  I deleted the post, but somehow you saw it.  Thanks for the reply.

Can I ask a follow up question?

I am trying to replicate the logic from the conversation https://groups.google.com/u/1/g/mementodatabase/c/bBhGHnSQz_Y

I am new to JavaScript filters, but what I can gather is they are very efficient alternatives to functions.

What I don't understand in the code provided by Mmm in the linked conversation is what a and b represent in the line:
filter = ent.filter((a,b) => a.field('unique number drink') === find);

Are they variables for the arrays for records for Pubs and Drinks? If so, where in the code are the arrays passed to the filter?

Thanks for your patience -- I am trying to hack my way through this with little experience in JavaScript.

Below is the complete code from the conversation:

let arr = selectedEntries();
let ent = libByName('Drinks Consumed').entries();
let find = '';
let filter = [];
let i = arr.length;
while (i--) {
find = arr[i].field('unique number pub');
if (find.length > 0 && !arr[i].field('connected')) {
filter = ent.filter((a,b) => a.field('unique number drink') === find);
if (filter.length > 0) {
filter.sort((a,b) => (a.title).localeCompare(b.title));
arr[i].set('drinks', filter);
arr[i].set('connected', true);
}
}
}
message('Done');


Bill Crews

unread,
May 26, 2025, 7:44:07 PM5/26/25
to Doris Reilly, mementodatabase
Doris, I'm sorry, but I no longer keep up to date with new features, such the Entry object's filter() method. The wiki is obsolete now and there's no documentation of filter() under the Entry object in there, and that's not the only undocumented thing. So I can't look it up to answer your question, either. 

Since you replied to the forum, Mmm or others who are keeping up with things will surely answer you. 

Mmm

unread,
May 27, 2025, 4:06:20 AM5/27/25
to mementodatabase
Не ломайте себе голову.
Аргумент "b" в стрелочной функции лишний (опечатка, невнимательность), но не влияющий на результат и не вызывающие ошибку.

Должно было быть:

filter = ent.filter(a => a.field('unique number drink') === find);

Вместо "a" можете использовать любое другое обозначение (название).

filter = ent.filter(element => element.field('unique number drink') === find);

Получить массив подходящих записей можно так:

let filter = [];
for (let item of ent) {
    if (item.field('unique number drink') === find) {
        filter.push(item);
    }
}

Оба скрипта дадут одинаковый результат.

Более подробно о методе filter() можно почитать, например, здесь:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

вторник, 27 мая 2025 г. в 02:44:07 UTC+3, bill....@gmail.com:

Doris Reilly

unread,
May 27, 2025, 1:05:55 PM5/27/25
to mementodatabase
Thanks, Mmm!  That makes it more clear.  The snippet of code is a crash course in JS!

I now understand the filter and also the arrow function.  But I have a couple of questions about the last part of the snippet in the conversation https://groups.google.com/u/0/g/mementodatabase/c/bBhGHnSQz_Y

1.  Can you explain what this line does?  

filter.sort((a,b) => (a.title).localeCompare(b.title));

I think filter.sort is sorting the filter array. Not sure what the a.title is? Are you comparing two elements in two different arrays? Is this line even necessary?

2. This line of code seems to be the critical action that actually links the records in the two libraries, correct?

arr[i].set('drinks', filter);

Can you explain what the term 'drinks' represents? Is this the link field in my library? What should I put in there for this code to work with my libraries?

3. I know there are hidden internal unique identifiers in the library that do the joins to link the libraries, because I can see them when I execute a sql query like this:

  SELECT id as guid, "Item Name", "Attachment Filename" FROM "Home Inventory Attachments <= 400"
  
  Which gives me the result below.  The one record with data in the Item Name was linked manually.  Because I want to understand what the code is doing, is the arr[i]].set. updating the link field column ('Item Name' in my library)?
  
QueryResult.jpg

Thanks in advance for your assistance -- I am so close to getting my database from Access imported and useable.  I just need to get the script to link records in my data working.

Doris

Mmm

unread,
May 27, 2025, 3:25:28 PM5/27/25
to mementodatabase
На пальцах...

1. После фильтра массива записей получился новый массив записей, удовлетворяющих условию.
Новый массив имеет имя "filter" (назовите, как хотите), не нужно путать с методом filter().
Массив сортируется по имени записи entry().title, которое является "строкой":

filter.sort((a,b) => (a.title).localeCompare(b.title));//где "a" и "b" две последовательные записи массива, сортировка по возрастанию

filter.sort((a,b) => (b.title).localeCompare(a.title));//сортировка по убыванию

Более подробно про localeCompare():
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/localeCompare

Более подробно про сортировку:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

2. Я уже не помню суть вопроса автора, но по скрипту понимаю, что поле 'drinks' является записями библиотеки 'Drinks Consumed'.
Что нужно в Вашей библиотеке, я не знаю.
Для этого следует показать библиотеки и пояснить задачу, которую стараетесь решить.

3. Про запрос SQL ничего сказать не могу. Какая задача - получить id записей и два поля из записи???? Без условий??? Смысл???


>>> SELECT id as guid, "Item Name", "Attachment Filename" FROM "Home Inventory Attachments <= 400"

Из библиотеки Вы получаете три столбца:
- SELECT - отбор данных,
- id as guid - id записи с новым именем столбца "guid",
- "Item Name", "Attachment Filename" - столбцы полей "Item Name", "Attachment Filename" со своими именами,
- после FROM идет имя библиотеки "Home Inventory Attachments <= 400",
- WHERE - условие в запросе отсутствует (Вы просто получаете id записи и два столбца для всех записей библиотеки).

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

Большая просьба - скриншоты прикреплять как файл, а не как изображение. 

вторник, 27 мая 2025 г. в 20:05:55 UTC+3, doris....@gmail.com:

Doris Reilly

unread,
May 27, 2025, 5:06:56 PM5/27/25
to mementodatabase
Thanks again for the quick reply, Mmm.  I believe I have solved it!

The example code I was following was from a scenario that was a many-to-many relationship.  Mine is a simple on-to-many, where Main is the "one" and Attachments is the "many.  Once I realized that, I modified the array set method to write to the correct library, and all is well!

The reason I was showing the results of the SQL query was because of a fundamental misunderstanding on my part.  I thought the contents of link field was a unique GUID string, but it is actually the objectID of related record.  So I just needed to write the objectID for the Main library record to the link field in the related Attachments library.  And like magic, it all works beautifully!

I do not add a sort, since I don't care what order they are saved/processed in.

For the benefit of anyone else cracking a similar nut, here is my code that now works.  Any suggestions to make it is welcome!

Doris

PS  Sorry about attaching the image...I will do better in the future ; )

************************

let main = selectedEntries();
let att = libByName('Home Inventory Attachments <= 400').entries();

let find = '';
let attfilter = [];
let mainfilter = [];

let i = main.length;  // number of selected entries in Main library

while (i--) {
  find = main[i].field('ItemID');  // get ItemID for first selected record in Main

  if (find > 0 && !main[i].field('Linked')) {   // check if the record has been linked

    attfilter = att.filter(a => a.field('ItemID') === find);  // get the related Attachments records
   
    let j = attfilter.length;

    while (j--) {
      attfilter[j].set('Item Name',main[i]);
      main[i].set('Linked',true);    
    }
  }  
}

Bill Crews

unread,
May 27, 2025, 6:29:23 PM5/27/25
to Doris Reilly, mementodatabase
Update on my remarks about the state of the wiki...

These new methods & functions are all in beta, I'm told. Vasily tells me that, when they go into production he will document them. Here's also planning on moving the wiki. I'm not sure what effect that'll have on us. 

Reply all
Reply to author
Forward
0 new messages