Search code examples
google-apps-scriptauto-incrementgoogle-app-maker

How to make auto-increment field in app maker from 5000


I have a table of products, and order_ID column that need to start from 5000

I have tried this:

if (record.Order_ID) {
  record.Order_ID = record.Order_ID + 1;
}
else {
  record.Order_ID = 5000;
}

Solution

  • In case you need to implement it with Drive Tables:

    // onCreate model's event handler 
    // it receives about-to-create record as parameter
    var ID_START_FROM = 5000;
    
    var lock = LockService.getScriptLock();
    // we need to lock our script, to prevent IDs inconsistency
    // wait 3 seconds for script lock
    lock.waitLock(3000);
    
    // Run query to get latest ID
    var query = app.models.Product.newQuery();
    query.sorting.Id._descending();
    query.limit = 1;
    
    var records = query.run();
    var next_id = records.length > 0 ? records[0].Id + 1 : ID_START_FROM;
    
    record.Id = next_id;
    // ...do other stuff
    
    lock.releaseLock();
    

    In case you are using Cloud SQL as data backend, you can easily alter your table:

    ALTER TABLE Product AUTO_INCREMENT = 5000;