add events table
This commit is contained in:
61
migrations/add_events_table.py
Normal file
61
migrations/add_events_table.py
Normal file
@@ -0,0 +1,61 @@
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
# Add the parent directory to Python path so we can import from root
|
||||
sys.path.append(str(Path(__file__).parent.parent))
|
||||
|
||||
from flask import Flask
|
||||
from flask_sqlalchemy import SQLAlchemy
|
||||
from extensions import db
|
||||
from sqlalchemy import text
|
||||
|
||||
def upgrade():
|
||||
# Create events table
|
||||
with db.engine.connect() as conn:
|
||||
conn.execute(text('''
|
||||
CREATE TABLE IF NOT EXISTS events (
|
||||
id SERIAL PRIMARY KEY,
|
||||
event_type VARCHAR(50) NOT NULL,
|
||||
user_id INTEGER NOT NULL REFERENCES "user" (id),
|
||||
timestamp TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
details JSONB,
|
||||
ip_address VARCHAR(45),
|
||||
user_agent VARCHAR(255)
|
||||
);
|
||||
|
||||
-- Create index on event_type for faster filtering
|
||||
CREATE INDEX IF NOT EXISTS idx_events_event_type ON events(event_type);
|
||||
|
||||
-- Create index on timestamp for faster date-based queries
|
||||
CREATE INDEX IF NOT EXISTS idx_events_timestamp ON events(timestamp);
|
||||
|
||||
-- Create index on user_id for faster user-based queries
|
||||
CREATE INDEX IF NOT EXISTS idx_events_user_id ON events(user_id);
|
||||
'''))
|
||||
conn.commit()
|
||||
|
||||
def downgrade():
|
||||
# Drop events table and its indexes
|
||||
with db.engine.connect() as conn:
|
||||
conn.execute(text('''
|
||||
DROP INDEX IF EXISTS idx_events_event_type;
|
||||
DROP INDEX IF EXISTS idx_events_timestamp;
|
||||
DROP INDEX IF EXISTS idx_events_user_id;
|
||||
DROP TABLE IF EXISTS events;
|
||||
'''))
|
||||
conn.commit()
|
||||
|
||||
if __name__ == '__main__':
|
||||
app = Flask(__name__)
|
||||
|
||||
# Use the same database configuration as in app.py
|
||||
app.config['SQLALCHEMY_DATABASE_URI'] = os.getenv('DATABASE_URL', 'postgresql://postgres:1253@localhost:5432/docupulse')
|
||||
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
|
||||
|
||||
print("Connecting to database...")
|
||||
|
||||
db.init_app(app)
|
||||
|
||||
with app.app_context():
|
||||
upgrade()
|
||||
Reference in New Issue
Block a user