DEV Community

whimsyy
whimsyy

Posted on

clean database with github action

My Workflow

This workflow delete session entry older than 30 min and workflow runs every 10 minutes.
github Repo

Submission Category:

Wacky Wildcards

Yaml File or Link to Code

Workflow:

name: Clean DB

on:
  schedule:
    # runs every 10 min
    - cron: '*/10 * * * *'

jobs:
  build:
    runs-on: ubuntu-latest
    steps:

      - name: checkout repo content
        uses: actions/checkout@v2 # checkout the repository content to github runner

      - name: setup python
        uses: actions/setup-python@v2
        with:
          python-version: '3.7.7' # install the python version needed

      - name: Install dependencies
        run: |
          python -m pip install --upgrade pip
          pip install -r requirements.txt

      - name: execute py script # run main.py to get the latest data
        env:
          DbUser: ${{ secrets.DBUSER }}
          DbPass: ${{ secrets.DBPASS }}
          DbHost: ${{ secrets.DBHOST }}
          DB: ${{ secrets.DB }}
        run: python main.py
Enter fullscreen mode Exit fullscreen mode

main.py :

from connection import conn,cur
import mysql.connector

try:
    query = "DELETE FROM sessions WHERE TIMESTAMPDIFF(MINUTE,time,CURRENT_TIMESTAMP()) > 30"

    cur.execute(query)
    conn.commit()
    print("cleaned")
except mysql.connector.Error as    e:
    print("db error")
    print(e)
Enter fullscreen mode Exit fullscreen mode

connection.py :

import os
import mysql.connector

conn = mysql.connector.connect(user=os.environ["DbUser"], 
                                  password= os.environ["DbPass"],
                                  host=os.environ["DbHost"],
                                  database=os.environ["DB"])

cur = conn.cursor()
Enter fullscreen mode Exit fullscreen mode

Additional Resources / Info

I am using this action in mysql databse action

Latest comments (0)