env.py 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. import os
  2. from logging.config import fileConfig
  3. from alembic import context
  4. from sqlalchemy import engine_from_config, pool, text
  5. # this is the Alembic Config object, which provides
  6. # access to the values within the .ini file in use.
  7. config = context.config
  8. # Interpret the config file for Python logging.
  9. # This line sets up loggers basically.
  10. if config.config_file_name is not None:
  11. fileConfig(config.config_file_name)
  12. # add your model's MetaData object here
  13. # for 'autogenerate' support
  14. # from myapp import mymodel
  15. # target_metadata = mymodel.Base.metadata
  16. target_metadata = None
  17. def get_schema_name():
  18. """Get the schema name from environment or config."""
  19. return os.environ.get("R2R_PROJECT_NAME", "r2r_default")
  20. def include_object(object, name, type_, reflected, compare_to):
  21. """Filter objects based on schema."""
  22. # Include only objects in our schema
  23. if hasattr(object, "schema"):
  24. return object.schema == get_schema_name()
  25. return True
  26. def run_migrations_offline() -> None:
  27. """Run migrations in 'offline' mode."""
  28. url = config.get_main_option("sqlalchemy.url")
  29. schema_name = get_schema_name()
  30. context.configure(
  31. url=url,
  32. target_metadata=target_metadata,
  33. literal_binds=True,
  34. dialect_opts={"paramstyle": "named"},
  35. include_schemas=True,
  36. include_object=include_object,
  37. version_table_schema=schema_name,
  38. version_table=f"{schema_name}_alembic_version",
  39. )
  40. with context.begin_transaction():
  41. # Ensure schema exists
  42. context.execute(text(f"CREATE SCHEMA IF NOT EXISTS {schema_name}"))
  43. context.run_migrations()
  44. def run_migrations_online() -> None:
  45. """Run migrations in 'online' mode."""
  46. schema_name = get_schema_name()
  47. connectable = engine_from_config(
  48. config.get_section(config.config_ini_section, {}),
  49. prefix="sqlalchemy.",
  50. poolclass=pool.NullPool,
  51. )
  52. with connectable.connect() as connection:
  53. # Ensure schema exists
  54. connection.execute(text(f"CREATE SCHEMA IF NOT EXISTS {schema_name}"))
  55. connection.commit()
  56. context.configure(
  57. connection=connection,
  58. target_metadata=target_metadata,
  59. include_schemas=True,
  60. include_object=include_object,
  61. version_table_schema=schema_name,
  62. version_table=f"{schema_name}_alembic_version",
  63. )
  64. with context.begin_transaction():
  65. context.run_migrations()
  66. if context.is_offline_mode():
  67. run_migrations_offline()
  68. else:
  69. run_migrations_online()