|
| 1 | +package com.target.data_validator.validator |
| 2 | + |
| 3 | +import com.target.data_validator.{ValidatorCheckEvent, ValidatorError, VarSubstitution} |
| 4 | +import io.circe._ |
| 5 | +import io.circe.generic.semiauto._ |
| 6 | +import org.apache.spark.sql.{DataFrame, Row} |
| 7 | +import org.apache.spark.sql.catalyst.analysis.UnresolvedAttribute |
| 8 | +import org.apache.spark.sql.catalyst.expressions.aggregate.Sum |
| 9 | +import org.apache.spark.sql.types._ |
| 10 | + |
| 11 | +case class ColumnSumCheck( |
| 12 | + column: String, |
| 13 | + minValue: Option[Json] = None, |
| 14 | + maxValue: Option[Json] = None, |
| 15 | + inclusive: Option[Json] = None |
| 16 | +) extends ColumnBased(column, Sum(UnresolvedAttribute(column)).toAggregateExpression()) { |
| 17 | + |
| 18 | + private val minOrMax: Either[String, Unit] = if (minValue.isEmpty && maxValue.isEmpty) { |
| 19 | + Left("'minValue' or 'maxValue' or both must be defined") |
| 20 | + } else { |
| 21 | + Right() |
| 22 | + } |
| 23 | + |
| 24 | + private val lowerBound: Either[String, Double] = minValue match { |
| 25 | + case Some(json) => |
| 26 | + if (json.isNumber) { Right(json.asNumber.get.toDouble) } |
| 27 | + else { Left(s"'minValue' defined but type is not a Number, is: ${json.name}") } |
| 28 | + case None => Right(Double.MinValue) |
| 29 | + } |
| 30 | + |
| 31 | + private val upperBound: Either[String, Double] = maxValue match { |
| 32 | + case Some(json) => |
| 33 | + if (json.isNumber) { Right(json.asNumber.get.toDouble) } |
| 34 | + else { Left(s"'maxValue' defined but type is not a Number, is: ${json.name}") } |
| 35 | + case None => Right(Double.MaxValue) |
| 36 | + } |
| 37 | + |
| 38 | + private val minLessThanMax: Either[String, Unit] = (lowerBound, upperBound) match { |
| 39 | + case (Right(lower), Right(upper)) if lower >= upper => |
| 40 | + Left(s"'minValue': $lower must be less than 'maxValue': $upper") |
| 41 | + case _ => Right() |
| 42 | + } |
| 43 | + |
| 44 | + private val inclusiveBounds: Either[String, Boolean] = inclusive match { |
| 45 | + case Some(json) => |
| 46 | + if (json.isBoolean) { Right(json.asBoolean.get) } |
| 47 | + else { Left(s"'inclusive' defined but type is not Boolean, is: ${json.name}") } |
| 48 | + case None => Right(false) |
| 49 | + } |
| 50 | + |
| 51 | + override def name: String = "columnSumCheck" |
| 52 | + |
| 53 | + override def quickCheck(r: Row, count: Long, idx: Int): Boolean = { |
| 54 | + |
| 55 | + def evaluate(sum: Double): Boolean = { |
| 56 | + if (inclusiveBounds.right.get) { sum > upperBound.right.get || sum < lowerBound.right.get} |
| 57 | + else { sum >= upperBound.right.get || sum <= lowerBound.right.get} |
| 58 | + } |
| 59 | + |
| 60 | + failed = r.schema(idx).dataType match { |
| 61 | + case ShortType => evaluate(r.getShort(idx)) |
| 62 | + case IntegerType => evaluate(r.getInt(idx)) |
| 63 | + case LongType => evaluate(r.getLong(idx)) |
| 64 | + case FloatType => evaluate(r.getFloat(idx)) |
| 65 | + case DoubleType => evaluate(r.getDouble(idx)) |
| 66 | + case ut => throw new Exception(s"Unsupported type for $name found in schema: $ut") |
| 67 | + } |
| 68 | + |
| 69 | + val bounds = minValue.getOrElse("") :: maxValue.getOrElse("") :: Nil |
| 70 | + val prettyBounds = if (inclusiveBounds.right.get) { |
| 71 | + r.get(idx) + " in " + bounds.mkString("[", " , ", "]") |
| 72 | + } else { |
| 73 | + r.get(idx) + " in " + bounds.mkString("(", " , ", ")") |
| 74 | + } |
| 75 | + val errorValue = if (failed) 1 else 0 |
| 76 | + addEvent(ValidatorCheckEvent(failed, s"$name on '$column': $prettyBounds", count, errorValue)) |
| 77 | + failed |
| 78 | + } |
| 79 | + |
| 80 | + override def substituteVariables(dict: VarSubstitution): ValidatorBase = { |
| 81 | + val ret = copy( |
| 82 | + column = getVarSub(column, "column", dict), |
| 83 | + minValue = minValue.map(getVarSubJson(_, "minValue", dict)), |
| 84 | + maxValue = maxValue.map(getVarSubJson(_, "maxValue", dict)), |
| 85 | + inclusive = inclusive.map(getVarSubJson(_, "inclusive", dict)) |
| 86 | + ) |
| 87 | + this.getEvents.foreach(ret.addEvent) |
| 88 | + ret |
| 89 | + } |
| 90 | + |
| 91 | + override def configCheck(df: DataFrame): Boolean = { |
| 92 | + logger.debug(s"Full check config: ${this.toString}") |
| 93 | + Seq( |
| 94 | + minOrMax, |
| 95 | + lowerBound, |
| 96 | + upperBound, |
| 97 | + minLessThanMax, |
| 98 | + inclusiveBounds |
| 99 | + ).foreach { |
| 100 | + case Left(msg) => |
| 101 | + logger.error(msg) |
| 102 | + addEvent(ValidatorError(msg)) |
| 103 | + case _ => |
| 104 | + } |
| 105 | + |
| 106 | + findColumnInDataFrame(df, column) match { |
| 107 | + case Some(ft) if ft.dataType.isInstanceOf[NumericType] => |
| 108 | + case Some(ft) => |
| 109 | + val msg = s"Column: $column found, but not of numericType type: ${ft.dataType}" |
| 110 | + logger.error(msg) |
| 111 | + addEvent(ValidatorError(msg)) |
| 112 | + case None => |
| 113 | + val msg = s"Column: $column not found in schema" |
| 114 | + logger.error(msg) |
| 115 | + addEvent(ValidatorError(msg)) |
| 116 | + } |
| 117 | + failed |
| 118 | + } |
| 119 | + |
| 120 | + override def toJson: Json = { |
| 121 | + val additionalFieldsForReport = Json.fromFields(Set( |
| 122 | + "type" -> Json.fromString("columnSumCheck"), |
| 123 | + "failed" -> Json.fromBoolean(failed) |
| 124 | + )) |
| 125 | + |
| 126 | + val base = ColumnSumCheck.encoder(this) |
| 127 | + base.deepMerge(additionalFieldsForReport) |
| 128 | + } |
| 129 | +} |
| 130 | + |
| 131 | +object ColumnSumCheck { |
| 132 | + val encoder: Encoder[ColumnSumCheck] = deriveEncoder[ColumnSumCheck] |
| 133 | + val decoder: Decoder[ColumnSumCheck] = deriveDecoder[ColumnSumCheck] |
| 134 | + def fromJson(c: HCursor): Either[DecodingFailure, ValidatorBase] = decoder.apply(c) |
| 135 | +} |
0 commit comments