Weehooey
Weehooey

Reputation: 1008

How unique is the id in ScriptDb (from getId())?

Obviously, the id is unique within the instance of the script but is the id unique across all scripts for the user? for the domain (for Google Apps)? or is it unique across the universe (i.e. Google)?

If the data is shared across applications, can the id be a unique reference number?

Upvotes: 1

Views: 1030

Answers (3)

AdamL
AdamL

Reputation: 24609

** edited as per OP's answer/megabyte's comments **

It would appear that you can only rely on the ID being unique within the current ScriptDb database. When a database object is stored, the documentation says that it is assigned an "opaque, immutable string value", and that it is a "unique identifier".

It's a good question as to whether that ID is unique across a domain, or across everything (edit - seems we can not rely on either being the case).

Upvotes: 2

Weehooey
Weehooey

Reputation: 1008

Google has confirmed it is only unique to that script:

Apps Script Office Hours Questions

Upvotes: 3

megabyte1024
megabyte1024

Reputation: 8650

The ScriptDB IDs are unique for stored data of a predefined script. The rest is an undefined behavior and it is not very reliable to rely on it. In not critical situation is possible, but I do not suggest, to generate unique IDs basing on

  • Current Time. var now = new Date();
  • Current Application ID. Mainly it exists but not in 100% cases. var id = UiApp.getActiveApplication().getId();
  • Current User ID. var user = Session.getActiveUser().getUserLoginId();
  • A few Random Numbers. Math.random();

To get an ID is necessary to join everything in a string, to compute the string digest and to encode the result using the Base64. But this solution is not truly random value and it is better to ask Google to create an function which generates truly unique UUIDs.

The code is

function getUniqueId() {
  var now = new Date();
  var id = UiApp.getActiveApplication().getId();
  var randStr = '';
  for (var i = 0; i < 10; i++) {
    randStr += Math.random();
  }
  var user = Session.getActiveUser().getUserLoginId();
  var str = '' + now + id + randStr + user;
  var digets = Utilities.computeDigest(Utilities.DigestAlgorithm.SHA_256, str);
  var res = Utilities.base64Encode(digets);
  res = res.substr(0, res.length - 2);
  return res;
}

Upvotes: 2

Related Questions