Add Containerfle

This commit is contained in:
2025-09-29 20:06:07 +08:00
parent fa37916440
commit e354caa03f
12 changed files with 1617 additions and 112 deletions
+112
View File
@@ -0,0 +1,112 @@
# A generic, single database configuration.
[alembic]
# path to migration scripts
script_location = migrations
# template used to generate migration file names; The default value is %%(rev)s_%%(slug)s
# Uncomment the line below if you want the files to be prepended with date and time
# file_template = %%(year)d_%%(month).2d_%%(day).2d_%%(hour).2d%%(minute).2d-%%(rev)s_%%(slug)s
# sys.path path, will be prepended to sys.path if present.
# defaults to the current working directory.
prepend_sys_path = .
# timezone to use when rendering the date within the migration file
# as well as the filename.
# If specified, requires the python-dateutil library that can be
# installed by adding `alembic[tz]` to the pip requirements
# string value is passed to dateutil.tz.gettz()
# leave blank for localtime
# timezone =
# max length of characters to apply to the
# "slug" field
# truncate_slug_length = 40
# set to 'true' to run the environment during
# the 'revision' command, regardless of autogenerate
# revision_environment = false
# set to 'true' to allow .pyc and .pyo files without
# a source .py file to be detected as revisions in the
# versions/ directory
# sourceless = false
# version number format
version_num_format = %04d
# version path separator; As mentioned above, this is the character used to split
# version_locations. The default within new alembic.ini files is "os", which uses
# os.pathsep. If this key is omitted entirely, it falls back to the legacy
# behavior of splitting on spaces and/or commas.
# Valid values for version_path_separator are:
#
# version_path_separator = :
# version_path_separator = ;
# version_path_separator = space
version_path_separator = os
# set to 'true' to search source files recursively
# in each "version_locations" directory
# new in Alembic version 1.10
# recursive_version_locations = false
# the output encoding used when revision files
# are written from script.py.mako
# output_encoding = utf-8
sqlalchemy.url = sqlite:///hockey_results.db
[post_write_hooks]
# post_write_hooks defines scripts or Python functions that are run
# on newly generated revision scripts. See the documentation for further
# detail and examples
# format using "black" - use the console_scripts runner, against the "black" entrypoint
# hooks = black
# black.type = console_scripts
# black.entrypoint = black
# black.options = -l 79 REVISION_SCRIPT_FILENAME
# lint with attempts to fix using "ruff" - use the exec runner, execute a binary
# hooks = ruff
# ruff.type = exec
# ruff.executable = %(here)s/.venv/bin/ruff
# ruff.options = --fix REVISION_SCRIPT_FILENAME
# Logging configuration
[loggers]
keys = root,sqlalchemy,alembic
[handlers]
keys = console
[formatters]
keys = generic
[logger_root]
level = WARN
handlers = console
qualname =
[logger_sqlalchemy]
level = WARN
handlers =
qualname = sqlalchemy.engine
[logger_alembic]
level = INFO
handlers =
qualname = alembic
[handler_console]
class = StreamHandler
args = (sys.stderr,)
level = NOTSET
formatter = generic
[formatter_generic]
format = %(levelname)-5.5s [%(name)s] %(message)s
datefmt = %H:%M:%S
+292
View File
@@ -0,0 +1,292 @@
# encoding=utf-8
"""
Database configuration and models for multi-database support using SQLAlchemy.
Supports PostgreSQL, MariaDB/MySQL, and SQLite.
"""
import os
from sqlalchemy import create_engine, Column, Integer, String, Date, DateTime, Text, SmallInteger, ForeignKey, Boolean, Float
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, relationship
from sqlalchemy.dialects.mysql import LONGTEXT
from sqlalchemy.dialects.postgresql import JSON
from datetime import datetime
# Base class for all models
Base = declarative_base()
class DatabaseConfig:
"""Database configuration class for multiple database support."""
def __init__(self):
self.database_url = self._get_database_url()
self.engine = create_engine(self.database_url, echo=False)
self.SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=self.engine)
def _get_database_url(self):
"""Get database URL from environment variables or configuration."""
db_type = os.getenv('DATABASE_TYPE', 'sqlite').lower()
if db_type == 'postgresql':
return self._get_postgresql_url()
elif db_type in ['mysql', 'mariadb']:
return self._get_mysql_url()
elif db_type == 'sqlite':
return self._get_sqlite_url()
else:
raise ValueError(f"Unsupported database type: {db_type}")
def _get_postgresql_url(self):
"""Get PostgreSQL connection URL."""
host = os.getenv('POSTGRES_HOST', 'localhost')
port = os.getenv('POSTGRES_PORT', '5432')
database = os.getenv('POSTGRES_DATABASE', 'hockey_results')
username = os.getenv('POSTGRES_USER', 'postgres')
password = os.getenv('POSTGRES_PASSWORD', '')
return f"postgresql://{username}:{password}@{host}:{port}/{database}"
def _get_mysql_url(self):
"""Get MySQL/MariaDB connection URL."""
host = os.getenv('MYSQL_HOST', 'localhost')
port = os.getenv('MYSQL_PORT', '3306')
database = os.getenv('MYSQL_DATABASE', 'hockey_results')
username = os.getenv('MYSQL_USER', 'root')
password = os.getenv('MYSQL_PASSWORD', '')
charset = os.getenv('MYSQL_CHARSET', 'utf8mb4')
return f"mysql+pymysql://{username}:{password}@{host}:{port}/{database}?charset={charset}"
def _get_sqlite_url(self):
"""Get SQLite connection URL."""
database_path = os.getenv('SQLITE_DATABASE_PATH', 'hockey_results.db')
return f"sqlite:///{database_path}"
def get_session(self):
"""Get database session."""
return self.SessionLocal()
def create_tables(self):
"""Create all database tables."""
Base.metadata.create_all(bind=self.engine)
# Global database configuration instance
db_config = DatabaseConfig()
# Database Models
class Player(Base):
"""Player model."""
__tablename__ = 'players'
player_number = Column(Integer, primary_key=True)
player_forenames = Column(String(50))
player_surname = Column(String(30))
player_nickname = Column(String(30))
player_chinese_name = Column(String(10))
player_email = Column(String(255))
player_dob = Column(Date)
player_hkid = Column(String(20))
player_tel_number = Column(String(30))
player_team = Column(String(6))
player_picture_url = Column(String(255))
created_at = Column(DateTime, default=datetime.utcnow)
updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
class Club(Base):
"""Club model."""
__tablename__ = 'clubs'
id = Column(Integer, primary_key=True)
hockey_club = Column(String(100), unique=True, nullable=False)
logo_url = Column(String(255))
created_at = Column(DateTime, default=datetime.utcnow)
class Team(Base):
"""Team model."""
__tablename__ = 'teams'
id = Column(Integer, primary_key=True)
club = Column(String(100), ForeignKey('clubs.hockey_club'))
team = Column(String(10))
display_name = Column(String(100))
league = Column(String(50))
created_at = Column(DateTime, default=datetime.utcnow)
class MatchSquad(Base):
"""Match squad model."""
__tablename__ = 'match_squad'
id = Column(Integer, primary_key=True)
player_number = Column(Integer, ForeignKey('players.player_number'))
player_forenames = Column(String(50))
player_surname = Column(String(30))
player_nickname = Column(String(30))
match_date = Column(Date)
created_at = Column(DateTime, default=datetime.utcnow)
class HockeyFixture(Base):
"""Hockey fixture model."""
__tablename__ = 'hockey_fixtures'
fixture_number = Column(Integer, primary_key=True)
date = Column(Date)
time = Column(String(10))
home_team = Column(String(100))
away_team = Column(String(100))
venue = Column(String(255))
home_score = Column(Integer)
away_score = Column(Integer)
umpire1 = Column(String(100))
umpire2 = Column(String(100))
match_official = Column(String(100))
division = Column(String(50))
created_at = Column(DateTime, default=datetime.utcnow)
class AdminSettings(Base):
"""Admin settings model."""
__tablename__ = 'admin_settings'
id = Column(Integer, primary_key=True)
userid = Column(String(50), default='admin')
next_fixture = Column(Integer)
next_club = Column(String(100))
next_team = Column(String(100))
next_date = Column(Date)
curr_motm = Column(Integer, ForeignKey('players.player_number'))
curr_dotd = Column(Integer, ForeignKey('players.player_number'))
oppo_logo = Column(String(255))
hkfc_logo = Column(String(255))
motm_url_suffix = Column(String(50))
prev_fixture = Column(Integer)
created_at = Column(DateTime, default=datetime.utcnow)
updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
class MotmVote(Base):
"""MOTM/DotD voting model."""
__tablename__ = 'motm_votes'
id = Column(Integer, primary_key=True)
player_number = Column(Integer, ForeignKey('players.player_number'))
player_name = Column(String(100))
motm_total = Column(Integer, default=0)
dotd_total = Column(Integer, default=0)
goals_total = Column(Integer, default=0)
assists_total = Column(Integer, default=0)
fixture_number = Column(Integer)
motm_votes = Column(Integer, default=0)
dotd_votes = Column(Integer, default=0)
goals = Column(Integer, default=0)
assists = Column(Integer, default=0)
created_at = Column(DateTime, default=datetime.utcnow)
updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
class MatchComment(Base):
"""Match comments model."""
__tablename__ = 'match_comments'
id = Column(Integer, primary_key=True)
match_date = Column(Date)
opposition = Column(String(100))
comment = Column(Text)
created_at = Column(DateTime, default=datetime.utcnow)
class HockeyUser(Base):
"""User authentication model."""
__tablename__ = 'hockey_users'
id = Column(Integer, primary_key=True)
username = Column(String(50), unique=True, nullable=False)
email = Column(String(255), unique=True, nullable=False)
password = Column(String(255), nullable=False)
created_at = Column(DateTime, default=datetime.utcnow)
last_login = Column(DateTime)
# Database utility functions
def get_db_session():
"""Get database session."""
return db_config.get_session()
def execute_sql(sql_command, params=None):
"""Execute SQL command with parameters."""
session = get_db_session()
try:
if params:
result = session.execute(sql_command, params)
else:
result = session.execute(sql_command)
session.commit()
return result
except Exception as e:
session.rollback()
print(f"SQL Error: {e}")
raise
finally:
session.close()
def fetch_all(sql_command, params=None):
"""Fetch all results from SQL query."""
session = get_db_session()
try:
if params:
result = session.execute(sql_command, params)
else:
result = session.execute(sql_command)
return result.fetchall()
except Exception as e:
print(f"SQL Error: {e}")
return []
finally:
session.close()
def fetch_one(sql_command, params=None):
"""Fetch one result from SQL query."""
session = get_db_session()
try:
if params:
result = session.execute(sql_command, params)
else:
result = session.execute(sql_command)
return result.fetchone()
except Exception as e:
print(f"SQL Error: {e}")
return None
finally:
session.close()
# Legacy compatibility functions
def sql_write(sql_cmd):
"""Legacy compatibility function for sql_write."""
try:
execute_sql(sql_cmd)
return True
except Exception as e:
print(f"Write Error: {e}")
return False
def sql_write_static(sql_cmd):
"""Legacy compatibility function for sql_write_static."""
return sql_write(sql_cmd)
def sql_read(sql_cmd):
"""Legacy compatibility function for sql_read."""
try:
result = fetch_all(sql_cmd)
# Convert to list of dictionaries for compatibility
return [dict(row) for row in result] if result else []
except Exception as e:
print(f"Read Error: {e}")
return []
def sql_read_static(sql_cmd):
"""Legacy compatibility function for sql_read_static."""
return sql_read(sql_cmd)
# Initialize database tables
def init_database():
"""Initialize database tables."""
try:
db_config.create_tables()
print("Database tables created successfully")
except Exception as e:
print(f"Database initialization error: {e}")
raise
+104 -109
View File
@@ -1,121 +1,116 @@
# encoding=utf-8
import pymysql
"""
Database configuration module with SQLAlchemy support.
This module provides backward compatibility with the old PyMySQL-based functions
while using SQLAlchemy for database operations.
"""
import os
import json
# These environment variables are configured in app.yaml.
CLOUDSQL_CONNECTION_NAME = "hk-hockey:asia-east2:hk-hockey-sql"
LOCAL_DB_SERVER = "mariadb.db.svc.cluster.local"
CLOUDSQL_USER = "root"
CLOUDSQL_WRITE_USER = "hockeyWrite"
CLOUDSQL_READ_USER = "hockeyRead"
CLOUDSQL_PASSWORD = "P8P1YopMlwg8TxhE"
CLOUDSQL_WRITE_PASSWORD = "1URYcxXXlQ6xOWgj"
CLOUDSQL_READ_PASSWORD = "o4GWrbbkBKy3oR6u"
CLOUDSQL_DATABASE = "20209_hockeyResults"
LOCAL_DATABASE = "hockeyResults2021"
CLOUDSQL_DATABASE_STATIC = "hockeyResults"
CLOUDSQL_CHARSET = "utf8"
import warnings
from database import (
db_config,
sql_write,
sql_write_static,
sql_read,
sql_read_static,
get_db_session,
execute_sql,
fetch_all,
fetch_one,
init_database
)
# Legacy constants for backward compatibility
CLOUDSQL_CONNECTION_NAME = os.getenv('CLOUDSQL_CONNECTION_NAME', "hk-hockey:asia-east2:hk-hockey-sql")
LOCAL_DB_SERVER = os.getenv('LOCAL_DB_SERVER', "mariadb.db.svc.cluster.local")
CLOUDSQL_USER = os.getenv('CLOUDSQL_USER', "root")
CLOUDSQL_WRITE_USER = os.getenv('CLOUDSQL_WRITE_USER', "hockeyWrite")
CLOUDSQL_READ_USER = os.getenv('CLOUDSQL_READ_USER', "hockeyRead")
CLOUDSQL_PASSWORD = os.getenv('CLOUDSQL_PASSWORD', "P8P1YopMlwg8TxhE")
CLOUDSQL_WRITE_PASSWORD = os.getenv('CLOUDSQL_WRITE_PASSWORD', "1URYcxXXlQ6xOWgj")
CLOUDSQL_READ_PASSWORD = os.getenv('CLOUDSQL_READ_PASSWORD', "o4GWrbbkBKy3oR6u")
CLOUDSQL_DATABASE = os.getenv('CLOUDSQL_DATABASE', "20209_hockeyResults")
LOCAL_DATABASE = os.getenv('LOCAL_DATABASE', "hockeyResults2021")
CLOUDSQL_DATABASE_STATIC = os.getenv('CLOUDSQL_DATABASE_STATIC', "hockeyResults")
CLOUDSQL_CHARSET = os.getenv('CLOUDSQL_CHARSET', "utf8")
# Legacy functions for backward compatibility
def write_cloudsql():
# When deployed to App Engine, the `SERVER_SOFTWARE` environment variable
# will be set to 'Google App Engine/version'.
if os.getenv('SERVER_SOFTWARE', '').startswith('Google App Engine/'):
# Connect using the unix socket located at
# /cloudsql/cloudsql-connection-name.
cloudsql_unix_socket = os.path.join('/cloudsql', CLOUDSQL_CONNECTION_NAME)
db = pymysql.connect(unix_socket=cloudsql_unix_socket, user=CLOUDSQL_WRITE_USER, passwd=CLOUDSQL_WRITE_PASSWORD, db=CLOUDSQL_DATABASE, charset=CLOUDSQL_CHARSET)
else:
db = pymysql.connect(host=LOCAL_DB_SERVER, user=CLOUDSQL_WRITE_USER, passwd=CLOUDSQL_WRITE_PASSWORD, db=LOCAL_DATABASE, charset=CLOUDSQL_CHARSET)
return db
"""
Legacy function - now uses SQLAlchemy.
Returns a session object for compatibility.
"""
warnings.warn(
"write_cloudsql() is deprecated. Use get_db_session() instead.",
DeprecationWarning,
stacklevel=2
)
return get_db_session()
def write_cloudsql_static():
# When deployed to App Engine, the `SERVER_SOFTWARE` environment variable
# will be set to 'Google App Engine/version'.
if os.getenv('SERVER_SOFTWARE', '').startswith('Google App Engine/'):
# Connect using the unix socket located at
# /cloudsql/cloudsql-connection-name.
cloudsql_unix_socket = os.path.join('/cloudsql', CLOUDSQL_CONNECTION_NAME)
db = pymysql.connect(unix_socket=cloudsql_unix_socket, user=CLOUDSQL_WRITE_USER, passwd=CLOUDSQL_WRITE_PASSWORD, db=CLOUDSQL_DATABASE_STATIC, charset=CLOUDSQL_CHARSET)
else:
db = pymysql.connect(host=LOCAL_DB_SERVER, user=CLOUDSQL_WRITE_USER, passwd=CLOUDSQL_WRITE_PASSWORD, db=CLOUDSQL_DATABASE_STATIC, charset=CLOUDSQL_CHARSET)
return db
"""
Legacy function - now uses SQLAlchemy.
Returns a session object for compatibility.
"""
warnings.warn(
"write_cloudsql_static() is deprecated. Use get_db_session() instead.",
DeprecationWarning,
stacklevel=2
)
return get_db_session()
def read_cloudsql():
# When deployed to App Engine, the `SERVER_SOFTWARE` environment variable
# will be set to 'Google App Engine/version'.
if os.getenv('SERVER_SOFTWARE', '').startswith('Google App Engine/'):
# Connect using the unix socket located at
# /cloudsql/cloudsql-connection-name.
cloudsql_unix_socket = os.path.join('/cloudsql', CLOUDSQL_CONNECTION_NAME)
db = pymysql.connect(unix_socket=cloudsql_unix_socket, user=CLOUDSQL_READ_USER, passwd=CLOUDSQL_READ_PASSWORD, db=CLOUDSQL_DATABASE, charset=CLOUDSQL_CHARSET)
else:
db = pymysql.connect(host=LOCAL_DB_SERVER, user=CLOUDSQL_READ_USER, passwd=CLOUDSQL_READ_PASSWORD, db=LOCAL_DATABASE, charset=CLOUDSQL_CHARSET)
return db
"""
Legacy function - now uses SQLAlchemy.
Returns a session object for compatibility.
"""
warnings.warn(
"read_cloudsql() is deprecated. Use get_db_session() instead.",
DeprecationWarning,
stacklevel=2
)
return get_db_session()
def read_cloudsql_static():
# When deployed to App Engine, the `SERVER_SOFTWARE` environment variable
# will be set to 'Google App Engine/version'.
if os.getenv('SERVER_SOFTWARE', '').startswith('Google App Engine/'):
# Connect using the unix socket located at
# /cloudsql/cloudsql-connection-name.
cloudsql_unix_socket = os.path.join('/cloudsql', CLOUDSQL_CONNECTION_NAME)
db = pymysql.connect(unix_socket=cloudsql_unix_socket, user=CLOUDSQL_READ_USER, passwd=CLOUDSQL_READ_PASSWORD, db=CLOUDSQL_DATABASE_STATIC, charset=CLOUDSQL_CHARSET)
else:
db = pymysql.connect(host=LOCAL_DB_SERVER, user=CLOUDSQL_READ_USER, passwd=CLOUDSQL_READ_PASSWORD, db=CLOUDSQL_DATABASE_STATIC, charset=CLOUDSQL_CHARSET)
return db
"""
Legacy function - now uses SQLAlchemy.
Returns a session object for compatibility.
"""
warnings.warn(
"read_cloudsql_static() is deprecated. Use get_db_session() instead.",
DeprecationWarning,
stacklevel=2
)
return get_db_session()
def sql_write(sql_cmd):
try:
db = write_cloudsql()
cursor = db.cursor(pymysql.cursors.DictCursor)
cursor.execute(sql_cmd)
db.commit()
except Exception as e:
print(e)
finally:
cursor.close()
db.close()
return db
def sql_write_static(sql_cmd):
try:
db = write_cloudsql_static()
cursor = db.cursor(pymysql.cursors.DictCursor)
cursor.execute(sql_cmd)
db.commit()
except Exception as e:
print(e)
finally:
cursor.close()
db.close()
return db
def sql_read(sql_cmd):
try:
db = read_cloudsql()
cursor = db.cursor(pymysql.cursors.DictCursor)
cursor.execute(sql_cmd)
rows = cursor.fetchall()
except Exception as e:
print(e)
rows = ''
finally:
cursor.close()
db.close()
return rows
def sql_read_static(sql_cmd):
try:
db = read_cloudsql_static()
cursor = db.cursor(pymysql.cursors.DictCursor)
cursor.execute(sql_cmd)
rows = cursor.fetchall()
except Exception as e:
print(e)
rows = ''
finally:
cursor.close()
db.close()
return rows
# These functions now use SQLAlchemy but maintain the same interface
__all__ = [
'sql_write',
'sql_write_static',
'sql_read',
'sql_read_static',
'get_db_session',
'execute_sql',
'fetch_all',
'fetch_one',
'init_database',
'db_config',
# Legacy constants
'CLOUDSQL_CONNECTION_NAME',
'LOCAL_DB_SERVER',
'CLOUDSQL_USER',
'CLOUDSQL_WRITE_USER',
'CLOUDSQL_READ_USER',
'CLOUDSQL_PASSWORD',
'CLOUDSQL_WRITE_PASSWORD',
'CLOUDSQL_READ_PASSWORD',
'CLOUDSQL_DATABASE',
'LOCAL_DATABASE',
'CLOUDSQL_DATABASE_STATIC',
'CLOUDSQL_CHARSET',
# Legacy functions
'write_cloudsql',
'write_cloudsql_static',
'read_cloudsql',
'read_cloudsql_static'
]
+13 -2
View File
@@ -1,7 +1,6 @@
Flask>=2.0.0,<3.0.0
Werkzeug>=2.0.0
email-validator
flask-mysql
flask_login
Flask-BasicAuth
Flask-Bootstrap
@@ -9,4 +8,16 @@ flask_wtf
wtforms>=3.0.0
wtforms_components
MarkupSafe>=2.0.0
pymysql
# SQLAlchemy and database drivers
SQLAlchemy>=2.0.0
Flask-SQLAlchemy>=3.0.0
alembic>=1.12.0
# Database drivers
pymysql>=1.1.0
psycopg2-binary>=2.9.0
PyMySQL>=1.1.0
# Legacy support (can be removed after migration)
flask-mysql