models: Make ID generation for custom SQL more reliable and faster