add dwh_tugas_akhir_daily dag (edoxid + informatika -> postgres dwh)
Daily ETL into the PostgreSQL DWH (Coolify "Data Warehouse IF"):
- raw: full-refresh copy of eDOXID submissions/verificators/users and
informatika mahasiswa/lulusan/dosen, without sensitive columns
- staging: normalize NIM/NIP, cast score/ipk/sks, fix known bad values
('2020/2010' academic year, Excel-corrupted lulusan.ipk)
- mart: dim_mahasiswa, dim_dosen, dim_tahap_ta, fact_ujian_ta,
fact_penugasan_dosen, mhs_progres_ta (risk flags), etl_log
for angkatan >= DWH_MIN_ANGKATAN (default 2019)
New env on airflow-scheduler: DWH_HOST, DWH_PASSWORD (+ optional
DWH_PORT, DWH_DATABASE, DWH_USERNAME, DWH_MIN_ANGKATAN).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
a357e0622e
commit
8ebedecdc3
@@ -0,0 +1,208 @@
|
||||
"""ETL tugas akhir ke DWH PostgreSQL: eDOXID + DB dashboard (informatika) -> raw -> staging -> mart.
|
||||
|
||||
Raw disalin utuh (full refresh) tapi TANPA kolom sensitif: password, token,
|
||||
email, no. HP, NIK, alamat, nama orang tua, catatan dosen, dsb. Filter angkatan
|
||||
(DWH_MIN_ANGKATAN) baru diterapkan di mart.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from datetime import date, datetime
|
||||
|
||||
from psycopg2.extras import execute_values
|
||||
|
||||
from scripts.dwh_config import connect_dwh, connect_edoxid, connect_informatika, get_min_angkatan
|
||||
from scripts.dwh_edoxid_sql import MART_SQL, STAGING_SQL
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Ambang flag risiko di mart.mhs_progres_ta
|
||||
RISK_PARAMS = {
|
||||
"risk_semester_belum_proposal": 9, # belum seminar proposal di semester >= 9
|
||||
"risk_bulan_setelah_proposal": 12, # > 12 bulan setelah seminar proposal, belum sidang hasil
|
||||
"risk_bulan_setelah_hasil": 6, # > 6 bulan setelah sidang hasil, belum sidang akhir
|
||||
"risk_semester_batas": 13, # batas masa studi S1 = 14 semester
|
||||
}
|
||||
|
||||
# (tabel raw, [(kolom, tipe postgres)], query sumber). Urutan kolom = urutan SELECT.
|
||||
EDOXID_TABLES = [
|
||||
(
|
||||
"edoxid_submissions",
|
||||
[
|
||||
("id", "bigint"), ("title", "text"), ("status", "text"), ("schedule", "timestamp"),
|
||||
("schedule_request", "timestamp"), ("room", "text"), ("grade", "text"), ("score", "text"),
|
||||
("grade_status", "text"), ("result_status", "text"), ("student_id", "bigint"),
|
||||
("type_id", "int"), ("skill_group_id", "int"), ("format_id", "int"),
|
||||
("academic_year", "text"), ("semester", "text"), ("ipk_now", "text"),
|
||||
("amount_sks_now", "text"), ("spota_submission_id", "bigint"),
|
||||
("is_ready_to_be_processed", "smallint"), ("ready_at", "timestamp"),
|
||||
("verificator_id_who_submit_result", "bigint"), ("updated_submit_result_at", "timestamp"),
|
||||
("bypass_pengajuan_kaprodi", "smallint"), ("created_at", "timestamp"), ("updated_at", "timestamp"),
|
||||
],
|
||||
"""
|
||||
SELECT id, title, status, schedule, schedule_request, room, grade, score, grade_status,
|
||||
result_status, student_id, type_id, skill_group_id, format_id, academic_year,
|
||||
semester, ipk_now, amount_sks_now, spota_submission_id, is_ready_to_be_processed,
|
||||
ready_at, verificator_id_who_submit_result, updated_submit_result_at,
|
||||
bypass_pengajuan_kaprodi, created_at, updated_at
|
||||
FROM submissions
|
||||
""",
|
||||
),
|
||||
(
|
||||
"edoxid_verificators",
|
||||
[
|
||||
("id", "bigint"), ("type", "text"), ("status", "text"), ("final_status", "text"),
|
||||
("user_id", "bigint"), ("submission_id", "bigint"), ("is_read_by_dosen", "smallint"),
|
||||
("created_at", "timestamp"), ("updated_at", "timestamp"),
|
||||
],
|
||||
"""
|
||||
SELECT id, type, status, final_status, user_id, submission_id, is_read_by_dosen,
|
||||
created_at, updated_at
|
||||
FROM verificators
|
||||
""",
|
||||
),
|
||||
(
|
||||
"edoxid_users",
|
||||
[
|
||||
("id", "bigint"), ("unique_id", "text"), ("name", "text"), ("role", "text"),
|
||||
("position", "text"), ("status", "text"), ("created_at", "timestamp"),
|
||||
],
|
||||
"SELECT id, unique_id, name, role, position, status, created_at FROM users",
|
||||
),
|
||||
]
|
||||
|
||||
INFORMATIKA_TABLES = [
|
||||
(
|
||||
"informatika_mahasiswa",
|
||||
[
|
||||
("nim", "text"), ("nama", "text"), ("angkatan", "int"), ("jk", "text"), ("agama", "text"),
|
||||
("tanggal_lahir", "text"), ("kabupaten", "text"), ("provinsi", "text"),
|
||||
("asal_instansi", "text"), ("jenis_pendaftaran", "text"), ("pekerjaan_ayah", "text"),
|
||||
("penghasilan_ayah", "text"), ("pekerjaan_ibu", "text"), ("penghasilan_ibu", "text"),
|
||||
("penerima_beasiswa", "text"), ("berkebutuhan_khusus", "text"),
|
||||
],
|
||||
"""
|
||||
SELECT nim, nama, angkatan, jk, agama, tanggal_lahir, kabupaten, provinsi, asal_instansi,
|
||||
jenis_pendaftaran, pekerjaan_ayah, penghasilan_ayah, pekerjaan_ibu, penghasilan_ibu,
|
||||
penerima_beasiswa, berkebutuhan_khusus
|
||||
FROM mahasiswa
|
||||
""",
|
||||
),
|
||||
(
|
||||
"informatika_lulusan",
|
||||
[("periode", "text"), ("nim", "text"), ("ipk", "text")],
|
||||
"SELECT periode, nim, ipk FROM lulusan",
|
||||
),
|
||||
(
|
||||
"informatika_dosen",
|
||||
[
|
||||
("id_dosen", "int"), ("nip", "text"), ("nidn", "text"), ("nama", "text"), ("jk", "text"),
|
||||
("gelar", "text"), ("fungsional", "text"), ("bidang", "text"),
|
||||
],
|
||||
"SELECT id_dosen, nip, nidn, nama, jk, gelar, fungsional, bidang FROM dosen",
|
||||
),
|
||||
]
|
||||
|
||||
MART_TABLES = ["dim_tahap_ta", "dim_dosen", "dim_mahasiswa", "fact_ujian_ta", "fact_penugasan_dosen", "mhs_progres_ta"]
|
||||
|
||||
|
||||
def _clean_value(value, pg_type: str):
|
||||
# MySQL zero-date ('0000-00-00') dikembalikan pymysql sebagai string -> NULL
|
||||
if pg_type == "timestamp":
|
||||
return value if isinstance(value, (datetime, date)) else None
|
||||
if isinstance(value, str):
|
||||
return value.replace("\x00", "")
|
||||
return value
|
||||
|
||||
|
||||
def _ensure_log_table(dwh_cur) -> None:
|
||||
dwh_cur.execute(
|
||||
"""
|
||||
CREATE TABLE IF NOT EXISTS mart.etl_log (
|
||||
id bigserial PRIMARY KEY,
|
||||
skema text NOT NULL,
|
||||
tabel text NOT NULL,
|
||||
jumlah_baris bigint NOT NULL,
|
||||
selesai_at timestamptz NOT NULL DEFAULT now()
|
||||
)
|
||||
"""
|
||||
)
|
||||
|
||||
|
||||
def _log_counts(dwh_cur, schema: str, tables: list) -> dict:
|
||||
counts = {}
|
||||
for table in tables:
|
||||
dwh_cur.execute(f"SELECT count(*) FROM {schema}.{table}")
|
||||
counts[table] = dwh_cur.fetchone()[0]
|
||||
dwh_cur.execute(
|
||||
"INSERT INTO mart.etl_log (skema, tabel, jumlah_baris) VALUES (%s, %s, %s)",
|
||||
(schema, table, counts[table]),
|
||||
)
|
||||
return counts
|
||||
|
||||
|
||||
def _load_raw(source_connect, tables: list) -> dict:
|
||||
"""Salin tiap tabel sumber ke raw.<tabel> (DROP + CREATE + INSERT) dalam satu transaksi."""
|
||||
source = source_connect()
|
||||
try:
|
||||
extracted = []
|
||||
with source.cursor() as cur:
|
||||
for name, columns, query in tables:
|
||||
cur.execute(query)
|
||||
types = [t for _, t in columns]
|
||||
rows = [tuple(_clean_value(v, t) for v, t in zip(row, types)) for row in cur.fetchall()]
|
||||
extracted.append((name, columns, rows))
|
||||
finally:
|
||||
source.close()
|
||||
|
||||
dwh = connect_dwh()
|
||||
try:
|
||||
with dwh, dwh.cursor() as cur:
|
||||
_ensure_log_table(cur)
|
||||
for name, columns, rows in extracted:
|
||||
ddl = ", ".join(f"{col} {typ}" for col, typ in columns)
|
||||
cur.execute(f"DROP TABLE IF EXISTS raw.{name}")
|
||||
cur.execute(f"CREATE TABLE raw.{name} ({ddl}, _loaded_at timestamptz NOT NULL DEFAULT now())")
|
||||
if rows:
|
||||
col_list = ", ".join(col for col, _ in columns)
|
||||
execute_values(cur, f"INSERT INTO raw.{name} ({col_list}) VALUES %s", rows, page_size=1000)
|
||||
counts = _log_counts(cur, "raw", [name for name, _, _ in extracted])
|
||||
finally:
|
||||
dwh.close()
|
||||
|
||||
logger.info("Raw selesai: %s", counts)
|
||||
return counts
|
||||
|
||||
|
||||
def run_load_raw_edoxid() -> dict:
|
||||
return _load_raw(connect_edoxid, EDOXID_TABLES)
|
||||
|
||||
|
||||
def run_load_raw_informatika() -> dict:
|
||||
return _load_raw(connect_informatika, INFORMATIKA_TABLES)
|
||||
|
||||
|
||||
def run_build_staging() -> dict:
|
||||
dwh = connect_dwh()
|
||||
try:
|
||||
with dwh, dwh.cursor() as cur:
|
||||
cur.execute(STAGING_SQL)
|
||||
counts = _log_counts(cur, "staging", ["ta_submission", "ta_penugasan", "mahasiswa", "lulusan", "dosen"])
|
||||
finally:
|
||||
dwh.close()
|
||||
logger.info("Staging selesai: %s", counts)
|
||||
return counts
|
||||
|
||||
|
||||
def run_build_mart() -> dict:
|
||||
params = dict(RISK_PARAMS, min_angkatan=get_min_angkatan())
|
||||
dwh = connect_dwh()
|
||||
try:
|
||||
with dwh, dwh.cursor() as cur:
|
||||
cur.execute(MART_SQL, params)
|
||||
counts = _log_counts(cur, "mart", MART_TABLES)
|
||||
finally:
|
||||
dwh.close()
|
||||
logger.info("Mart selesai (angkatan >= %s): %s", params["min_angkatan"], counts)
|
||||
return counts
|
||||
Reference in New Issue
Block a user