Fix defect calculating nextId and inserting in empty database