All files / owid-grapher/db/model Variable.ts

20% Statements 47/235
100% Branches 1/1
0% Functions 0/4
20% Lines 47/235

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 3131x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x           1x 1x                                                                                                                                                                                                             1x 1x                                                                                                                                                                   1x 1x                                                                                                                                                            
import * as lodash from "lodash"
import { Writable } from "stream"
import * as db from "../db"
import {
    OwidChartDimensionInterface,
    OwidVariableDisplayConfigInterface,
} from "../../clientUtils/OwidVariableDisplayConfigInterface"
import { OwidVariablesAndEntityKey } from "../../clientUtils/OwidVariable"
import { arrToCsvRow, omitNullableValues } from "../../clientUtils/Util"
import {
    DataValueQueryArgs,
    DataValueResult,
    OwidVariableId,
} from "../../clientUtils/owidTypes"
import { OwidSource } from "../../clientUtils/OwidSource"
 
export namespace Variable {
    export interface Row {
        id: number
        name: string
        code: string | null
        unit: string
        shortUnit: string | null
        description: string | null
        createdAt: Date
        updatedAt: Date
        datasetId: number
        sourceId: number
        display: OwidVariableDisplayConfigInterface
        coverage?: string
        timespan?: string
        columnOrder?: number
    }
 
    export type UnparsedRow = Row & { display: string }
 
    export type Field = keyof Row
 
    export const table = "variables"
 
    export function rows(plainRows: UnparsedRow[]): Row[] {
        for (const row of plainRows) {
            row.display = row.display ? JSON.parse(row.display) : undefined
        }
        return plainRows
    }
}
 
export async function getVariableData(variableIds: number[]): Promise<any> {
    variableIds = lodash.uniq(variableIds)
    const data: OwidVariablesAndEntityKey = { variables: {}, entityKey: {} }

    type VariableQueryRow = Readonly<
        Variable.UnparsedRow & {
            display: string
            datasetName: string
            nonRedistributable: number
            sourceName: string
            sourceDescription: string
        }
    >

    const variableQuery: Promise<VariableQueryRow[]> = db.queryMysql(
        `
        SELECT
            variables.*,
            datasets.name AS datasetName,
            datasets.nonRedistributable AS nonRedistributable,
            sources.name AS sourceName,
            sources.description AS sourceDescription
        FROM variables
        JOIN datasets ON variables.datasetId = datasets.id
        JOIN sources ON variables.sourceId = sources.id
        WHERE variables.id IN (?)
        `,
        [variableIds]
    )

    const dataQuery = db.queryMysql(
        `
        SELECT
            value,
            year,
            variableId,
            entities.id AS entityId,
            entities.name AS entityName,
            entities.code AS entityCode
        FROM data_values
        LEFT JOIN entities ON data_values.entityId = entities.id
        WHERE data_values.variableId IN (?)
        ORDER BY
            variableId ASC,
            year ASC
        `,
        [variableIds]
    )

    const variables = await variableQuery

    for (const row of variables) {
        const {
            sourceId,
            sourceName,
            sourceDescription,
            nonRedistributable,
            display: displayJson,
            ...variable
        } = row
        const display = JSON.parse(displayJson)
        const partialSource: OwidSource = JSON.parse(sourceDescription)
        data.variables[variable.id] = {
            ...omitNullableValues(variable),
            nonRedistributable: Boolean(nonRedistributable),
            display,
            source: {
                id: sourceId,
                name: sourceName,
                dataPublishedBy: partialSource.dataPublishedBy || "",
                dataPublisherSource: partialSource.dataPublisherSource || "",
                link: partialSource.link || "",
                retrievedDate: partialSource.retrievedDate || "",
                additionalInfo: partialSource.additionalInfo || "",
            },
            years: [],
            entities: [],
            values: [],
        }
    }

    const results = await dataQuery

    for (const row of results) {
        const variable = data.variables[row.variableId]
        variable.years.push(row.year)
        variable.entities.push(row.entityId)

        const asNumber = parseFloat(row.value)
        if (!isNaN(asNumber)) variable.values.push(asNumber)
        else variable.values.push(row.value)

        if (data.entityKey[row.entityId] === undefined) {
            data.entityKey[row.entityId] = {
                name: row.entityName,
                code: row.entityCode,
            }
        }
    }

    return data
}
 
// TODO use this in Dataset.writeCSV() maybe?
export async function writeVariableCSV(
    variableIds: number[],
    stream: Writable
): Promise<void> {
    const variableQuery: Promise<{ id: number; name: string }[]> =
        db.queryMysql(
            `
            SELECT id, name
            FROM variables
            WHERE id IN (?)
            `,
            [variableIds]
        )

    const dataQuery: Promise<
        {
            variableId: number
            entity: string
            year: number
            value: string
        }[]
    > = db.queryMysql(
        `
        SELECT
            data_values.variableId AS variableId,
            entities.name AS entity,
            data_values.year AS year,
            data_values.value AS value
        FROM
            data_values
            JOIN entities ON entities.id = data_values.entityId
            JOIN variables ON variables.id = data_values.variableId
        WHERE
            data_values.variableId IN (?)
        ORDER BY
            data_values.entityId ASC,
            data_values.year ASC
        `,
        [variableIds]
    )

    let variables = await variableQuery
    const variablesById = lodash.keyBy(variables, "id")

    // Throw an error if not all variables exist
    if (variables.length !== variableIds.length) {
        const fetchedVariableIds = variables.map((v) => v.id)
        const missingVariables = lodash.difference(
            variableIds,
            fetchedVariableIds
        )
        throw Error(`Variable IDs do not exist: ${missingVariables.join(", ")}`)
    }

    variables = variableIds.map((variableId) => variablesById[variableId])

    const columns = ["Entity", "Year"].concat(variables.map((v) => v.name))
    stream.write(arrToCsvRow(columns))

    const variableColumnIndex: { [id: number]: number } = {}
    for (const variable of variables) {
        variableColumnIndex[variable.id] = columns.indexOf(variable.name)
    }

    const data = await dataQuery

    let row: unknown[] = []
    for (const datum of data) {
        if (datum.entity !== row[0] || datum.year !== row[1]) {
            // New row
            if (row.length) {
                stream.write(arrToCsvRow(row))
            }
            row = [datum.entity, datum.year]
            for (const variable of variables) {
                row.push("")
            }
        }
        row[variableColumnIndex[datum.variableId]] = datum.value
    }
}
 
export const getDataValue = async ({
    variableId,
    entityId,
    year,
}: DataValueQueryArgs): Promise<DataValueResult | undefined> => {
    if (!variableId || !entityId) return
 
    const queryStart = `
        SELECT
            value,
            year,
            variables.unit AS unit,
            entities.name AS entityName
        FROM data_values
        JOIN entities on entities.id = data_values.entityId
        JOIN variables on variables.id = data_values.variableId
        WHERE entities.id = ?
        AND variables.id = ?`
 
    const queryStartVariables = [entityId, variableId]
 
    let row
 
    if (year) {
        row = await db.mysqlFirst(
            `${queryStart}
            AND data_values.year = ?`,
            [...queryStartVariables, year]
        )
    } else {
        row = await db.mysqlFirst(
            `${queryStart}
            ORDER BY data_values.year DESC
            LIMIT 1`,
            queryStartVariables
        )
    }
 
    if (!row) return
 
    return {
        value: Number(row.value),
        year: Number(row.year),
        unit: row.unit,
        entityName: row.entityName,
    }
}
 
export const getOwidChartDimensionConfigForVariable = async (
    variableId: OwidVariableId,
    chartId: number
): Promise<OwidChartDimensionInterface | undefined> => {
    const row = await db.mysqlFirst(
        `
        SELECT config->"$.dimensions" AS dimensions
        FROM charts
        WHERE id = ?
        `,
        [chartId]
    )
    if (!row.dimensions) return
    const dimensions = JSON.parse(row.dimensions)
    return dimensions.find(
        (dimension: OwidChartDimensionInterface) =>
            dimension.variableId === variableId
    )
}
 
export const getOwidVariableDisplayConfig = async (
    variableId: OwidVariableId
): Promise<OwidVariableDisplayConfigInterface | undefined> => {
    const row = await db.mysqlFirst(
        `SELECT display FROM variables WHERE id = ?`,
        [variableId]
    )
    if (!row.display) return
    return JSON.parse(row.display)
}