    def sync_groups(self, group_names):
        """Synchronize groups with database"""

        current_groups = {g.name for g in self.orm_user.groups}
        new_groups = set(group_names)
        if current_groups == new_groups:
            # no change, nothing to do
            return

        # log group changes
        added_groups = new_groups.difference(current_groups)
        removed_groups = current_groups.difference(group_names)
        if added_groups:
            self.log.info(f"Adding user {self.name} to group(s): {added_groups}")
        if removed_groups:
            self.log.info(f"Removing user {self.name} from group(s): {removed_groups}")

        if group_names:
            groups = (
                self.db.query(orm.Group).filter(orm.Group.name.in_(new_groups)).all()
            )
            existing_groups = {g.name for g in groups}
            for group_name in added_groups:
                if group_name not in existing_groups:
                    # create groups that don't exist yet
                    self.log.info(
                        f"Creating new group {group_name} for user {self.name}"
                    )
                    group = orm.Group(name=group_name)
                    self.db.add(group)
                    groups.append(group)
            self.orm_user.groups = groups
        else:
            self.orm_user.groups = []
        self.db.commit()
Synchronize groups with database
jupyterhub/user.py