Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Erro no exercício 04 da aula 04 quando o banco já contem dados #279

Open
taconi opened this issue Jan 13, 2025 · 2 comments · May be fixed by #280
Open

Erro no exercício 04 da aula 04 quando o banco já contem dados #279

taconi opened this issue Jan 13, 2025 · 2 comments · May be fixed by #280

Comments

@taconi
Copy link
Contributor

taconi commented Jan 13, 2025

Como reproduzir

Clonando o repositório e instalando as dependências:

git clone https://github.com/taconi/fast-db-erro.git
cd fast-db-erro/
poetry install

Atualizando o banco para a última migração:

poetry run alembic upgrade head

Mensagem de Erro

sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) Cannot add a column with non-constant default
[SQL: ALTER TABLE users ADD COLUMN updated_at DATETIME DEFAULT (CURRENT_TIMESTAMP) NOT NULL]
(Background on this error at: https://sqlalche.me/e/20/e3q8)
Mensagem completa do erro
INFO  [alembic.runtime.migration] Context impl SQLiteImpl.
INFO  [alembic.runtime.migration] Will assume non-transactional DDL.
INFO  [alembic.runtime.migration] Running upgrade a968fed2afb0 -> 5a90a52babb7, exercicio 02 aula 04
Traceback (most recent call last):
  File "/tmp/fast_zero/.venv/lib/python3.13/site-packages/sqlalchemy/engine/base.py", line 1964, in _exec_single_context
    self.dialect.do_execute(
    ~~~~~~~~~~~~~~~~~~~~~~~^
        cursor, str_statement, effective_parameters, context
        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    )
    ^
  File "/tmp/fast_zero/.venv/lib/python3.13/site-packages/sqlalchemy/engine/default.py", line 942, in do_execute
    cursor.execute(statement, parameters)
    ~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^
sqlite3.OperationalError: Cannot add a column with non-constant default

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/tmp/fast_zero/.venv/bin/alembic", line 8, in <module>
    sys.exit(main())
             ~~~~^^
  File "/tmp/fast_zero/.venv/lib/python3.13/site-packages/alembic/config.py", line 636, in main
    CommandLine(prog=prog).main(argv=argv)
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^
  File "/tmp/fast_zero/.venv/lib/python3.13/site-packages/alembic/config.py", line 626, in main
    self.run_cmd(cfg, options)
    ~~~~~~~~~~~~^^^^^^^^^^^^^^
  File "/tmp/fast_zero/.venv/lib/python3.13/site-packages/alembic/config.py", line 603, in run_cmd
    fn(
    ~~^
        config,
        ^^^^^^^
        *[getattr(options, k, None) for k in positional],
        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
        **{k: getattr(options, k, None) for k in kwarg},
        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    )
    ^
  File "/tmp/fast_zero/.venv/lib/python3.13/site-packages/alembic/command.py", line 406, in upgrade
    script.run_env()
    ~~~~~~~~~~~~~~^^
  File "/tmp/fast_zero/.venv/lib/python3.13/site-packages/alembic/script/base.py", line 586, in run_env
    util.load_python_file(self.dir, "env.py")
    ~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^
  File "/tmp/fast_zero/.venv/lib/python3.13/site-packages/alembic/util/pyfiles.py", line 95, in load_python_file
    module = load_module_py(module_id, path)
  File "/tmp/fast_zero/.venv/lib/python3.13/site-packages/alembic/util/pyfiles.py", line 113, in load_module_py
    spec.loader.exec_module(module)  # type: ignore
    ~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^
  File "<frozen importlib._bootstrap_external>", line 1026, in exec_module
  File "<frozen importlib._bootstrap>", line 488, in _call_with_frames_removed
  File "/tmp/fast_zero/migrations/env.py", line 88, in <module>
    run_migrations_online()
    ~~~~~~~~~~~~~~~~~~~~~^^
  File "/tmp/fast_zero/migrations/env.py", line 82, in run_migrations_online
    context.run_migrations()
    ~~~~~~~~~~~~~~~~~~~~~~^^
  File "<string>", line 8, in run_migrations
  File "/tmp/fast_zero/.venv/lib/python3.13/site-packages/alembic/runtime/environment.py", line 946, in run_migrations
    self.get_context().run_migrations(**kw)
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^
  File "/tmp/fast_zero/.venv/lib/python3.13/site-packages/alembic/runtime/migration.py", line 623, in run_migrations
    step.migration_fn(**kw)
    ~~~~~~~~~~~~~~~~~^^^^^^
  File "/tmp/fast_zero/migrations/versions/5a90a52babb7_exercicio_02_aula_04.py", line 23, in upgrade
    op.add_column('users', sa.Column('updated_at', sa.DateTime(), server_default=sa.text('(CURRENT_TIMESTAMP)'), nullable=False))
    ~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "<string>", line 8, in add_column
  File "<string>", line 3, in add_column
  File "/tmp/fast_zero/.venv/lib/python3.13/site-packages/alembic/operations/ops.py", line 2156, in add_column
    return operations.invoke(op)
           ~~~~~~~~~~~~~~~~~^^^^
  File "/tmp/fast_zero/.venv/lib/python3.13/site-packages/alembic/operations/base.py", line 442, in invoke
    return fn(self, operation)
  File "/tmp/fast_zero/.venv/lib/python3.13/site-packages/alembic/operations/toimpl.py", line 183, in add_column
    operations.impl.add_column(table_name, column, schema=schema, **kw)
    ~~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/tmp/fast_zero/.venv/lib/python3.13/site-packages/alembic/ddl/impl.py", line 374, in add_column
    self._exec(base.AddColumn(table_name, column, schema=schema))
    ~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/tmp/fast_zero/.venv/lib/python3.13/site-packages/alembic/ddl/impl.py", line 247, in _exec
    return conn.execute(construct, params)
           ~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^
  File "/tmp/fast_zero/.venv/lib/python3.13/site-packages/sqlalchemy/engine/base.py", line 1416, in execute
    return meth(
        self,
        distilled_parameters,
        execution_options or NO_OPTIONS,
    )
  File "/tmp/fast_zero/.venv/lib/python3.13/site-packages/sqlalchemy/sql/ddl.py", line 180, in _execute_on_connection
    return connection._execute_ddl(
           ~~~~~~~~~~~~~~~~~~~~~~~^
        self, distilled_params, execution_options
        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    )
    ^
  File "/tmp/fast_zero/.venv/lib/python3.13/site-packages/sqlalchemy/engine/base.py", line 1527, in _execute_ddl
    ret = self._execute_context(
        dialect,
    ...<4 lines>...
        compiled,
    )
  File "/tmp/fast_zero/.venv/lib/python3.13/site-packages/sqlalchemy/engine/base.py", line 1843, in _execute_context
    return self._exec_single_context(
           ~~~~~~~~~~~~~~~~~~~~~~~~~^
        dialect, context, statement, parameters
        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    )
    ^
  File "/tmp/fast_zero/.venv/lib/python3.13/site-packages/sqlalchemy/engine/base.py", line 1983, in _exec_single_context
    self._handle_dbapi_exception(
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~^
        e, str_statement, effective_parameters, cursor, context
        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    )
    ^
  File "/tmp/fast_zero/.venv/lib/python3.13/site-packages/sqlalchemy/engine/base.py", line 2352, in _handle_dbapi_exception
    raise sqlalchemy_exception.with_traceback(exc_info[2]) from e
  File "/tmp/fast_zero/.venv/lib/python3.13/site-packages/sqlalchemy/engine/base.py", line 1964, in _exec_single_context
    self.dialect.do_execute(
    ~~~~~~~~~~~~~~~~~~~~~~~^
        cursor, str_statement, effective_parameters, context
        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    )
    ^
  File "/tmp/fast_zero/.venv/lib/python3.13/site-packages/sqlalchemy/engine/default.py", line 942, in do_execute
    cursor.execute(statement, parameters)
    ~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^
sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) Cannot add a column with non-constant default
[SQL: ALTER TABLE users ADD COLUMN updated_at DATETIME DEFAULT (CURRENT_TIMESTAMP) NOT NULL]
(Background on this error at: https://sqlalche.me/e/20/e3q8)
@taconi
Copy link
Contributor Author

taconi commented Jan 15, 2025

Erro não acontece no postgres, os registros antigos recebem a coluna updated_at com a data atual, no caso, a data em que a migração foi aplicada

@taconi
Copy link
Contributor Author

taconi commented Jan 15, 2025

Cara, ta vendo aqui e o material da aula 4 aponta para a live sobre migrações.
Nela é dependido uns 8 minutos sobre esse mesmo problema e sua solução (operações em batch).

https://youtu.be/yQtqkq9UkDA?t=5313 (minutagem 1:28:33)

Como a live é um material auxilixar de estudos creio que isso não sejá necessáriamente um erro.
Mas, acho que a solução do exercício poderia contemplar este cenário também.

@taconi taconi linked a pull request Jan 15, 2025 that will close this issue
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant