{"record":{"id":"c996bbce97a5d58f","repo":"invoke-ai/InvokeAI","slug":"failed-to-create-user-e","errorCode":null,"errorMessage":"Failed to create user: {e}","messagePattern":"Failed to create user: (.+?)","errorType":"exception","errorClass":"ValueError","httpStatus":400,"severity":"error","filePath":"invokeai/app/services/users/users_default.py","lineNumber":117,"sourceCode":"                # before the INSERT below commits. In-process callers are additionally\n                # serialized by the database's shared RLock; the explicit lock also covers a\n                # second process (invoke-useradd --admin) writing during the setup window.\n                cursor.execute(\"BEGIN IMMEDIATE\")\n                # Same predicate as has_admin(), read on the cursor that performs the write.\n                cursor.execute(\"SELECT COUNT(*) FROM users WHERE is_admin = TRUE AND is_active = TRUE\")\n                row = cursor.fetchone()\n                if row and row[0] > 0:\n                    raise ValueError(\"Admin user already exists\")\n            try:\n                cursor.execute(\n                    \"\"\"\n                    INSERT INTO users (user_id, email, display_name, password_hash, is_admin)\n                    VALUES (?, ?, ?, ?, ?)\n                    \"\"\",\n                    (user_id, user_data.email, user_data.display_name, password_hash, user_data.is_admin),\n                )\n            except sqlite3.IntegrityError as e:\n                raise ValueError(f\"Failed to create user: {e}\") from e\n\n        user = self.get(user_id)\n        if user is None:\n            raise RuntimeError(\"Failed to retrieve created user\")\n        return user\n\n    def get(self, user_id: str) -> UserDTO | None:\n        \"\"\"Get user by ID.\"\"\"\n        with self._db.transaction() as cursor:\n            cursor.execute(\n                f\"\"\"\n                SELECT {_USER_DTO_COLUMNS}\n                FROM users\n                WHERE user_id = ?\n                \"\"\",\n                (user_id,),\n            )\n            row = cursor.fetchone()","sourceCodeStart":99,"sourceCodeEnd":135,"githubUrl":"https://github.com/invoke-ai/InvokeAI/blob/0b6a024f2ff6a86bfb953dcdb9cc504ef7397a06/invokeai/app/services/users/users_default.py#L99-L135","documentation":"UserService._create wraps sqlite3.IntegrityError raised by the INSERT into the users table as a ValueError. This means the new user row violated a database constraint - almost always the UNIQUE constraint on email (or user_id), or a NOT NULL constraint. The original sqlite message is preserved in the exception text and __cause__.","triggerScenarios":"Calling UserService.create(...) or create_admin(...) with a UserCreateRequest whose email (or generated user_id) already exists in the users table, or with a field that violates a NOT NULL constraint on the users table.","commonSituations":"Re-running an initialization/bootstrap script that registers a default admin; a race where two workers insert the same email; case-variant duplicate emails ('Admin@x.com' vs 'admin@x.com') colliding with a case-insensitive unique index; an email column added later with UNIQUE that existing data now violates.","solutions":["Check whether the email already exists (self.get_by_email or SELECT) before calling create, or treat ValueError as 'already exists'.","Read the wrapped sqlite3 message (e.__cause__) to see which constraint failed (users.email UNIQUE vs NOT NULL).","Use a different email/user_id for the new account, or update the existing user instead of creating a new one.","Wrap the create call in a try/except sqlite3.IntegrityError at the call site if duplicates are expected and should be idempotent."],"exampleFix":"// before\nuser = users.create(UserCreateRequest(email='admin@example.com', ...))\n// after\ntry:\n    user = users.create(UserCreateRequest(email='admin@example.com', ...))\nexcept ValueError as e:\n    user = users.get_by_email('admin@example.com')  # already registered","handlingStrategy":"validation","validationCode":"if users.get_by_email(req.email) is not None:\n    raise ValueError(f'Email {req.email} already registered')","typeGuard":null,"tryCatchPattern":"try:\n    user = users.create(req)\nexcept ValueError as e:\n    if 'UNIQUE' in str(e):\n        user = users.get_by_email(req.email)\n    else:\n        raise","preventionTips":["Check for an existing email before creating; treat duplicates as updates, not inserts","Make bootstrap scripts idempotent (create only if get_by_email returns None)","Catch and inspect the wrapped sqlite3.IntegrityError (__cause__) to identify the failing constraint","Normalize emails (lowercase, trim) before insert to avoid case-variant duplicates"],"tags":["sqlite","unique-constraint","valueerror","user-creation"],"backgroundTag":"unique-constraint-violation","analyzedSha":"0b6a024f2ff6a86bfb953dcdb9cc504ef7397a06","analyzedAt":"2026-08-29T04:46:49.967Z","schemaVersion":2},"datasetVersion":"2026-08-29T07:17:48.351Z"}