-
-
Notifications
You must be signed in to change notification settings - Fork 250
Expand file tree
/
Copy pathdb.ts
More file actions
1294 lines (1194 loc) · 39.4 KB
/
db.ts
File metadata and controls
1294 lines (1194 loc) · 39.4 KB
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
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import * as _ from "lodash-es"
import knex, { Knex } from "knex"
import {
GRAPHER_DB_HOST,
GRAPHER_DB_USER,
GRAPHER_DB_PASS,
GRAPHER_DB_NAME,
GRAPHER_DB_PORT,
BAKED_BASE_URL,
} from "../settings/serverSettings.js"
import { IS_ARCHIVE } from "../settings/clientSettings.js"
import { PROD_URL } from "../site/SiteConstants.js"
import { registerExitHandler } from "./cleanup.js"
import { createTagGraph, Url } from "@ourworldindata/utils"
import {
ImageMetadata,
MinimalDataInsightInterface,
OwidGdocType,
DBRawPostGdocWithTags,
parsePostsGdocsWithTagsRow,
DBEnrichedPostGdocWithTags,
parsePostsGdocsRow,
TagGraphRootName,
FlatTagGraph,
FlatTagGraphNode,
MinimalTagWithIsTopic,
DbPlainPostGdocLink,
ContentGraphLinkType,
OwidGdoc,
DbPlainTag,
TagGraphNode,
MinimalExplorerInfo,
DbEnrichedImage,
DbEnrichedImageWithUserId,
DbEnrichedImageWithPageviews,
MinimalTag,
BreadcrumbItem,
PostsGdocsTableName,
OwidGdocBaseInterface,
TagGraphRoot,
FeaturedMetricByParentTagNameDictionary,
ChartConfigsTableName,
FeaturedMetricsTableName,
TagsTableName,
TagGraphTableName,
ExplorersTableName,
MultiDimDataPagesTableName,
OwidGdocMinimalPostInterface,
DbRawPostGdoc,
} from "@ourworldindata/types"
import { gdocFromJSON } from "./model/Gdoc/GdocFactory.js"
import { getCanonicalUrl } from "@ourworldindata/components"
import { rawGdocToMinimalPost } from "./model/Gdoc/GdocBase.js"
/**
* TEMPORARY: Transaction-scoped caching helper for baking performance
*
* Caches the result of an async function on the knex transaction object.
* Cache is automatically cleared when the transaction ends, making it safe
* for both long-running baking transactions and short web app requests.
*
* @param knex - The knex transaction object
* @param cacheKey - Unique key for this cached function
* @param fn - The async function to cache
* @returns The cached or computed result
*
* @example
* export async function getDods(knex: KnexReadonlyTransaction) {
* return cachedInTransaction(knex, 'dods', async () => {
* return knexRaw(knex, `SELECT * FROM dods`)
* })
* }
*/
export async function cachedInTransaction<T>(
knex: KnexReadonlyTransaction,
cacheKey: string,
fn: () => Promise<T>
): Promise<T> {
const cache = ((knex as any).__queryCache =
(knex as any).__queryCache || {})
if (cache[cacheKey] !== undefined) {
return cache[cacheKey]
}
const result = await fn()
cache[cacheKey] = result
return result
}
// Return the first match from a mysql query
export const closeTypeOrmAndKnexConnections = async (): Promise<void> => {
if (_knexInstance) {
await _knexInstance.destroy()
_knexInstance = undefined
}
}
let _knexInstance: Knex | undefined = undefined
export function setKnexInstance(knexInstance: Knex<any, any[]>): void {
_knexInstance = knexInstance
}
const getNewKnexInstance = (): Knex<any, any[]> => {
return knex({
client: "mysql2",
connection: {
host: GRAPHER_DB_HOST,
user: GRAPHER_DB_USER,
password: GRAPHER_DB_PASS,
database: GRAPHER_DB_NAME,
port: GRAPHER_DB_PORT,
charset: "utf8mb4",
typeCast: (field: any, next: any) => {
if (field.type === "TINY" && field.length === 1) {
return field.string() === "1" // 1 = true, 0 = false
}
return next()
},
// The mysql2 driver will return JSON objects by default, which is nice, but we have many code paths that
// expect JSON strings, so we instead tell it to return JSON strings.
//@ts-expect-error This is an option in mysql2 v3.10+, but it's not yet reflected in the knex types
jsonStrings: true,
},
})
}
export const knexInstance = (): Knex<any, any[]> => {
if (_knexInstance) return _knexInstance
_knexInstance = getNewKnexInstance()
registerExitHandler(async () => {
if (_knexInstance) await _knexInstance.destroy()
})
return _knexInstance
}
declare const __read_capability: unique symbol
declare const __write_capability: unique symbol
export type KnexReadonlyTransaction = Knex.Transaction<any, any[]> & {
readonly [__read_capability]: "read"
}
export type KnexReadWriteTransaction = Knex.Transaction<any, any[]> & {
readonly [__read_capability]: "read"
readonly [__write_capability]: "write"
}
export enum TransactionCloseMode {
Close,
KeepOpen,
}
async function knexTransaction<T, KT>(
transactionFn: (trx: KT) => Promise<T>,
closeConnection: TransactionCloseMode,
readonly: boolean,
knex: Knex<any, any[]>
): Promise<T> {
try {
const options = readonly ? { readOnly: true } : {}
const result = await knex.transaction(
async (trx) => transactionFn(trx as KT),
options
)
return result
} finally {
if (closeConnection === TransactionCloseMode.Close) {
await knex.destroy()
if (knex === _knexInstance) _knexInstance = undefined
}
}
}
export async function knexReadonlyTransaction<T>(
transactionFn: (trx: KnexReadonlyTransaction) => Promise<T>,
closeConnection: TransactionCloseMode = TransactionCloseMode.KeepOpen,
knex: Knex<any, any[]> = knexInstance()
): Promise<T> {
return knexTransaction(transactionFn, closeConnection, true, knex)
}
export async function knexReadWriteTransaction<T>(
transactionFn: (trx: KnexReadWriteTransaction) => Promise<T>,
closeConnection: TransactionCloseMode = TransactionCloseMode.KeepOpen,
knex: Knex<any, any[]> = knexInstance()
): Promise<T> {
return knexTransaction(transactionFn, closeConnection, false, knex)
}
export const knexRaw = async <TRow = unknown>(
knex: Knex<any, any[]>,
str: string,
params?: any[] | Record<string, any>
): Promise<TRow[]> => {
try {
const rawReturnConstruct = await knex.raw(str, params ?? [])
return rawReturnConstruct[0]
} catch (e) {
console.error("Exception when executing SQL statement!", {
sql: str,
params,
error: e,
})
throw e
}
}
export const knexRawFirst = async <TRow = unknown>(
knex: KnexReadonlyTransaction,
str: string,
params?: any[] | Record<string, any>
): Promise<TRow | undefined> => {
const results = await knexRaw<TRow>(knex, str, params)
if (results.length === 0) return undefined
return results[0]
}
export const knexRawInsert = async (
knex: KnexReadWriteTransaction,
str: string,
params?: any[]
): Promise<{ insertId: number }> => (await knex.raw(str, params ?? []))[0]
export const getExplorerTags = async (
knex: KnexReadonlyTransaction
): Promise<{ slug: string; tags: Pick<DbPlainTag, "name" | "id">[] }[]> => {
return knexRaw<{ slug: string; tags: string }>(
knex,
`-- sql
SELECT
ext.explorerSlug as slug,
CASE
WHEN COUNT(t.id) = 0 THEN JSON_ARRAY()
ELSE JSON_ARRAYAGG(JSON_OBJECT('name', t.name, 'id', t.id))
END AS tags
FROM
explorer_tags ext
LEFT JOIN tags t ON
ext.tagId = t.id
GROUP BY
ext.explorerSlug`
).then((rows) =>
rows.map((row) => ({
slug: row.slug,
tags: JSON.parse(row.tags) as Pick<DbPlainTag, "name" | "id">[],
}))
)
}
export const getPublishedExplorersBySlug = async (
knex: KnexReadonlyTransaction,
includeUnlisted: boolean = true
): Promise<Record<string, MinimalExplorerInfo>> => {
return cachedInTransaction(
knex,
includeUnlisted
? "publishedExplorersBySlug"
: "unlistedPublishedExplorersBySlug",
async () => {
const tags = await getExplorerTags(knex)
const tagsBySlug = _.keyBy(tags, "slug")
return knexRaw(
knex,
`-- sql
SELECT
e.slug,
e.config->>"$.explorerTitle" as title,
e.config->>"$.explorerSubtitle" as subtitle,
e.createdAt,
e.updatedAt
FROM
explorers e
WHERE
e.isPublished = TRUE`
).then((rows) => {
let processed = rows.map((row: any) => {
const tagsForExplorer = tagsBySlug[row.slug]
return {
slug: row.slug,
title: row.title,
subtitle: row.subtitle === "null" ? "" : row.subtitle,
tags: tagsForExplorer
? tagsForExplorer.tags.map((tag) => tag.name)
: [],
createdAt: row.createdAt,
updatedAt: row.updatedAt,
}
})
if (!includeUnlisted) {
processed = processed.filter(
(row) => !row.tags.includes("Unlisted")
)
}
return _.keyBy(processed, "slug")
})
}
)
}
export const getPublishedDataInsights = (
knex: KnexReadonlyTransaction,
limit = Number.MAX_SAFE_INTEGER // default to no limit
): Promise<MinimalDataInsightInterface[]> => {
return knexRaw(
knex,
`-- sql
SELECT
content->>'$.title' AS title,
authors,
publishedAt,
updatedAt,
slug,
ROW_NUMBER() OVER (ORDER BY publishedAt DESC) - 1 AS \`index\`
FROM posts_gdocs
WHERE type = '${OwidGdocType.DataInsight}'
AND published = TRUE
AND publishedAt <= NOW()
ORDER BY publishedAt DESC
LIMIT ?`,
[limit]
).then((results) =>
results.map((record: any) => ({
...record,
index: Number(record.index),
authors: JSON.parse(record.authors),
}))
) as Promise<MinimalDataInsightInterface[]>
}
export async function checkIfSlugCollides(
knex: KnexReadonlyTransaction,
gdoc: OwidGdocBaseInterface
): Promise<boolean> {
const existingGdoc = await knex(PostsGdocsTableName)
.where({
slug: gdoc.slug,
published: true,
})
.whereNot({
id: gdoc.id,
})
.first()
.then((row) => (row ? parsePostsGdocsRow(row) : undefined))
if (!existingGdoc) return false
const existingCanonicalUrl = getCanonicalUrl("", existingGdoc)
const incomingCanonicalUrl = getCanonicalUrl("", gdoc)
return existingCanonicalUrl === incomingCanonicalUrl
}
export const getPublishedDataInsightCount = (
knex: KnexReadonlyTransaction,
topicSlug?: string
): Promise<number> => {
let query
if (topicSlug) {
query = knexRawFirst<{ count: number }>(
knex,
`
SELECT COUNT(DISTINCT(posts_gdocs.id)) AS count
FROM posts_gdocs
JOIN posts_gdocs_x_tags as pgt ON posts_gdocs.id = pgt.gdocId
JOIN tags ON pgt.tagId = tags.id
WHERE type = '${OwidGdocType.DataInsight}'
AND published = TRUE
AND publishedAt <= NOW()
AND tags.slug = ?`,
[topicSlug]
)
} else {
query = knexRawFirst<{ count: number }>(
knex,
`
SELECT COUNT(*) AS count
FROM posts_gdocs
WHERE type = '${OwidGdocType.DataInsight}'
AND published = TRUE
AND publishedAt <= NOW()`
)
}
return query.then((res) => res?.count ?? 0)
}
export const getTotalNumberOfCharts = (
knex: KnexReadonlyTransaction
): Promise<number> => {
return knexRawFirst<{ count: number }>(
knex,
`-- sql
SELECT COUNT(*) AS count
FROM charts c
JOIN chart_configs cc ON c.configId = cc.id
WHERE cc.full ->> "$.isPublished" = "true"
`
).then((res) => res?.count ?? 0)
}
export const getTotalNumberOfInUseGrapherTags = (
knex: KnexReadonlyTransaction
): Promise<number> => {
return knexRawFirst<{ count: number }>(
knex,
`
SELECT COUNT(DISTINCT(tagId)) AS count
FROM chart_tags
WHERE chartId IN (
SELECT id
FROM charts
WHERE publishedAt IS NOT NULL)`
).then((res) => res?.count ?? 0)
}
/**
* For usage with GdocFactory.load, until we refactor Gdocs to be entirely Knex-based.
*/
export const getHomepageId = (
knex: KnexReadonlyTransaction
): Promise<string | undefined> => {
return knexRawFirst<{ id: string }>(
knex,
`-- sql
SELECT
posts_gdocs.id
FROM
posts_gdocs
WHERE
type = '${OwidGdocType.Homepage}'
AND published = TRUE`
).then((result) => result?.id)
}
export const getHomepageAnnouncements = (
knex: KnexReadonlyTransaction
): Promise<OwidGdocMinimalPostInterface[]> => {
return knexRaw<DbRawPostGdoc>(
knex,
`-- sql
SELECT
pg.*
FROM ${PostsGdocsTableName} pg
WHERE pg.published = TRUE
AND pg.publishedAt <= NOW()
AND pg.type = '${OwidGdocType.Announcement}'
AND pg.publicationContext = 'listed'
ORDER BY pg.publishedAt DESC
LIMIT 3
`
).then((rows) => rows.map(rawGdocToMinimalPost))
}
export async function checkIsImageInDB(
trx: KnexReadonlyTransaction,
filename: string
): Promise<boolean> {
const image = await trx("images").where("filename", filename).first()
return !!image
}
export const getImageMetadataByFilenames = async (
knex: KnexReadonlyTransaction,
filenames: string[]
): Promise<Record<string, ImageMetadata & { id: number }>> => {
if (filenames.length === 0) return {}
const rows = await knexRaw<ImageMetadata & { id: number }>(
knex,
`-- sql
SELECT
id,
filename,
defaultAlt,
updatedAt,
originalWidth,
originalHeight,
cloudflareId
FROM
images
WHERE filename IN (?)
AND replacedBy IS NULL`,
[filenames]
)
return _.keyBy(rows, "filename")
}
export const getPublishedGdocsWithTags = async (
knex: KnexReadonlyTransaction,
// The traditional "post" types - doesn't include data insights, author pages, the homepage, etc.
gdocTypes: OwidGdocType[] = [
OwidGdocType.Article,
OwidGdocType.LinearTopicPage,
OwidGdocType.TopicPage,
OwidGdocType.AboutPage,
OwidGdocType.Announcement,
],
options: { excludeDeprecated?: boolean } = {}
): Promise<DBEnrichedPostGdocWithTags[]> => {
const { excludeDeprecated = false } = options
const query = `-- sql
SELECT
g.manualBreadcrumbs,
g.content,
g.createdAt,
g.id,
g.markdown,
g.publicationContext,
g.published,
g.publishedAt,
g.revisionId,
g.slug,
g.updatedAt,
if( COUNT(t.id) = 0, JSON_ARRAY(), JSON_ARRAYAGG(
JSON_OBJECT(
'id', t.id,
'name', t.name,
'slug', t.slug
))) AS tags
FROM
posts_gdocs g
LEFT JOIN posts_gdocs_x_tags gxt ON
g.id = gxt.gdocId
LEFT JOIN tags t ON
gxt.tagId = t.id
WHERE
g.published = 1
AND g.type IN (:gdocTypes)
AND g.publishedAt <= NOW()
${
excludeDeprecated
? `AND (g.content ->> '$."deprecation-notice"' IS NULL)`
: ""
}
GROUP BY g.id
ORDER BY g.publishedAt DESC`
return knexRaw<DBRawPostGdocWithTags>(knex, query, {
gdocTypes,
}).then((rows) => rows.map(parsePostsGdocsWithTagsRow))
}
export const getNonGrapherExplorerViewCount = (
knex: KnexReadonlyTransaction
): Promise<number> => {
return knexRawFirst<{ count: number }>(
knex,
`-- sql
SELECT
COUNT(*) as count
FROM
explorers,
json_table(config, "$.blocks[*]"
COLUMNS (
type TEXT PATH "$.type",
NESTED PATH "$.block[*]"
COLUMNS (grapherId INT PATH "$.grapherId")
)
) t1
WHERE
isPublished = 1
AND type = "graphers"
AND grapherId IS NULL`
).then((res) => res?.count ?? 0)
}
/**
* 1. Fetch all records in tag_graph:
* - isTopic = true when there is a published TP/LTP with the same slug as the tag
* - isSearchable = true when isTopic OR the tag has searchableInAlgolia set
* 2. Group tags by their parentId
* 3. Return the flat tag graph along with a __rootId property so that the UI knows which record is the root node
*/
export async function getFlatTagGraph(knex: KnexReadonlyTransaction): Promise<
FlatTagGraph & {
__rootId: number
}
> {
const tagGraphByParentId = await knexRaw<FlatTagGraphNode>(
knex,
`-- sql
SELECT
tg.parentId,
tg.childId,
tg.weight,
t.slug,
t.name,
p.slug IS NOT NULL AS isTopic,
(p.slug IS NOT NULL OR t.searchableInAlgolia = TRUE) AS isSearchable
FROM
tag_graph tg
LEFT JOIN tags t ON
tg.childId = t.id
LEFT JOIN posts_gdocs p ON
t.slug = p.slug AND p.published = 1 AND p.type IN (:types)
-- order by descending weight, tiebreak by name
ORDER BY tg.weight DESC, t.name ASC`,
{
types: [OwidGdocType.TopicPage, OwidGdocType.LinearTopicPage],
}
).then((rows) => _.groupBy(rows, "parentId"))
const tagGraphRootIdResult = await knexRawFirst<{
id: number
}>(
knex,
`-- sql
SELECT id FROM tags WHERE name = "${TagGraphRootName}"`
)
if (!tagGraphRootIdResult) throw new Error("Tag graph root not found")
return { ...tagGraphByParentId, __rootId: tagGraphRootIdResult.id }
}
// DFS through the tag graph and track all paths from a child to the root
// e.g. { "childTag": [ [parentTag1, parentTag2, childTag], [parentTag3, childTag] ] }
// Use with getUniqueNamesFromTopicHierarchies to collapse all paths to the child into
// a single array of unique parent tag names, including the original tags if they are topics.
export async function getTagHierarchiesByChildName(
trx: KnexReadonlyTransaction,
includeAreasAndTopicsOnly: boolean = false
): Promise<
Record<DbPlainTag["name"], Pick<DbPlainTag, "id" | "name" | "slug">[][]>
> {
const { __rootId, ...flatTagGraph } = await getFlatTagGraph(trx)
const areaAndTopicTagNames = await getAllAreaAndTopicTagNames(trx)
const tagGraph = createTagGraph(flatTagGraph, __rootId)
const tagsById = await trx<DbPlainTag>("tags")
.select("id", "name", "slug")
.then((tags) => _.keyBy(tags, "id"))
const pathsByChildName: Record<
DbPlainTag["name"],
Pick<DbPlainTag, "id" | "name" | "slug">[][]
> = {}
function trackAllPaths(
node: TagGraphNode,
currentPath: Pick<DbPlainTag, "id" | "name" | "slug">[] = []
): void {
const currentTag = tagsById[node.id]
const newPath = [...currentPath, currentTag]
// Don't add paths for root node
if (node.id !== __rootId) {
const nodeName = currentTag.name
if (!pathsByChildName[nodeName]) {
pathsByChildName[nodeName] = []
}
let pathToAdd = newPath.slice(1) // Exclude root
if (includeAreasAndTopicsOnly) {
pathToAdd = pathToAdd.filter((tag) =>
areaAndTopicTagNames.includes(tag.name)
)
}
// Only add non-empty paths
if (pathToAdd.length > 0) {
pathsByChildName[nodeName].push(pathToAdd)
}
}
for (const child of node.children) {
trackAllPaths(child, newPath)
}
}
trackAllPaths(tagGraph)
return pathsByChildName
}
export const getTopicHierarchiesByChildName = (
trx: KnexReadonlyTransaction
): Promise<
Record<DbPlainTag["name"], Pick<DbPlainTag, "id" | "name" | "slug">[][]>
> => getTagHierarchiesByChildName(trx, true)
export function getBestBreadcrumbs(
tags: MinimalTag[],
parentTagArraysByChildName: Record<
string,
Pick<DbPlainTag, "id" | "name" | "slug">[][]
>
): BreadcrumbItem[] {
// For each tag, find the best path according to our criteria
// e.g. { "Nuclear Energy ": ["Energy and Environment", "Energy"], "Air Pollution": ["Energy and Environment"] }
const result = new Map<number, Pick<DbPlainTag, "id" | "name" | "slug">[]>()
for (const tag of tags) {
const paths = parentTagArraysByChildName[tag.name]
if (paths && paths.length > 0) {
// Since getFlatTagGraph already orders by weight DESC and name ASC,
// the first path in the array will be our best path
result.set(tag.id, paths[0])
}
}
// Only keep the topics in the paths, because only topics are clickable as breadcrumbs
const topicsOnly = Array.from(result.values()).reduce(
(acc, path) => {
return [...acc, path.filter((tag) => tag.slug)]
},
[] as Pick<DbPlainTag, "id" | "name" | "slug">[][]
)
// Pick the longest path from result, assuming that the longest path is the best
const longestPath = topicsOnly.reduce((best, path) => {
return path.length > best.length ? path : best
}, [])
const baseUrl = IS_ARCHIVE ? PROD_URL : BAKED_BASE_URL
const breadcrumbs = longestPath.map((tag) => ({
label: tag.name,
href: `${baseUrl}/${tag.slug}`,
}))
return breadcrumbs
}
export async function updateTagGraph(
knex: KnexReadWriteTransaction,
tagGraph: FlatTagGraph
): Promise<void> {
const tagGraphRows: {
parentId: number
childId: number
weight: number
}[] = []
for (const children of Object.values(tagGraph)) {
for (const child of children) {
tagGraphRows.push({
parentId: child.parentId,
childId: child.childId,
weight: child.weight,
})
}
}
const existingTagGraphRows = await knexRaw<{
parentId: number
childId: number
weight: number
}>(
knex,
`-- sql
SELECT parentId, childId, weight FROM tag_graph
`
)
// Remove rows that are not in the new tag graph
// Add rows that are in the new tag graph but not in the existing tag graph
const rowsToDelete = existingTagGraphRows.filter(
(row) =>
!tagGraphRows.some(
(newRow) =>
newRow.parentId === row.parentId &&
newRow.childId === row.childId &&
newRow.weight === row.weight
)
)
const rowsToAdd = tagGraphRows.filter(
(newRow) =>
!existingTagGraphRows.some(
(row) =>
newRow.parentId === row.parentId &&
newRow.childId === row.childId &&
newRow.weight === row.weight
)
)
if (rowsToDelete.length > 0) {
await knexRaw(
knex,
`-- sql
DELETE FROM tag_graph
WHERE parentId IN (?)
AND childId IN (?)
AND weight IN (?)
`,
[
rowsToDelete.map((row) => row.parentId),
rowsToDelete.map((row) => row.childId),
rowsToDelete.map((row) => row.weight),
]
)
}
if (rowsToAdd.length > 0) {
await knexRaw(
knex,
`-- sql
INSERT INTO tag_graph (parentId, childId, weight)
VALUES ?
`,
[rowsToAdd.map((row) => [row.parentId, row.childId, row.weight])]
)
}
}
export function getMinimalTagsWithIsTopic(
knex: KnexReadonlyTransaction
): Promise<MinimalTagWithIsTopic[]> {
return knexRaw<MinimalTagWithIsTopic>(
knex,
`-- sql
SELECT t.id,
t.name,
t.slug,
t.slug IS NOT NULL AND MAX(IF(pg.type IN (:types), TRUE, FALSE)) AS isTopic,
(t.slug IS NOT NULL AND MAX(IF(pg.type IN (:types), TRUE, FALSE))) OR t.searchableInAlgolia AS isSearchable
FROM tags t
LEFT JOIN posts_gdocs_x_tags gt ON t.id = gt.tagId
LEFT JOIN posts_gdocs pg ON gt.gdocId = pg.id
GROUP BY t.id, t.name
ORDER BY t.name ASC
`,
{
types: [
OwidGdocType.TopicPage,
OwidGdocType.LinearTopicPage,
OwidGdocType.Article,
],
}
)
}
export async function getGrapherLinkTargets(
knex: KnexReadonlyTransaction
): Promise<Pick<DbPlainPostGdocLink, "target">[]> {
return knexRaw<Pick<DbPlainPostGdocLink, "target">>(
knex,
`-- sql
SELECT target
FROM posts_gdocs_links
WHERE linkType = '${ContentGraphLinkType.Grapher}'
`
)
}
export async function getStaticVizLinkTargets(
knex: KnexReadonlyTransaction
): Promise<Pick<DbPlainPostGdocLink, "target">[]> {
return knexRaw<Pick<DbPlainPostGdocLink, "target">>(
knex,
`-- sql
SELECT DISTINCT target
FROM posts_gdocs_links
WHERE linkType = '${ContentGraphLinkType.StaticViz}'
`
)
}
/**
* Get the slugs of all datapages that are linked to in KeyIndicator blocks
* Optionally exclude homepage KeyIndicator blocks, because for prefetching (the one current usecase for this function)
* the SiteBaker fetches the indicator metadata separately
*/
export async function getLinkedIndicatorSlugs({
knex,
excludeHomepage = false,
}: {
knex: KnexReadonlyTransaction
excludeHomepage: boolean
}): Promise<Set<string>> {
let rawQuery = `-- sql
SELECT * FROM posts_gdocs WHERE published = TRUE`
if (excludeHomepage) {
rawQuery += ` AND type != '${OwidGdocType.Homepage}'`
}
return knexRaw<OwidGdoc>(knex, rawQuery)
.then((gdocs) => gdocs.map((gdoc) => gdocFromJSON(gdoc)))
.then((gdocs) => gdocs.flatMap((gdoc) => gdoc.linkedKeyIndicatorSlugs))
.then((slugs) => new Set(slugs))
}
export async function selectReplacementChainForImage(
trx: KnexReadonlyTransaction,
id: string
): Promise<DbEnrichedImage[]> {
return knexRaw<DbEnrichedImage>(
trx,
`-- sql
WITH RECURSIVE replacement_chain AS (
SELECT i.*
FROM images i
WHERE id = ?
UNION ALL
SELECT i.*
FROM images i
INNER JOIN replacement_chain rc ON i.replacedBy = rc.id
)
SELECT * FROM replacement_chain
`,
[id]
)
}
export function getCloudflareImages(
trx: KnexReadonlyTransaction,
options?: {
excludeFeaturedImages?: boolean
excludeThumbnails?: boolean
excludeResearchAndWriting?: boolean
}
): Promise<DbEnrichedImageWithPageviews[]> {
const {
excludeFeaturedImages = false,
excludeThumbnails = false,
excludeResearchAndWriting = false,
} = options || {}
let havingClause = ""
const conditions: string[] = []
if (excludeFeaturedImages) {
conditions.push("isFeaturedImage = 0")
conditions.push("isBodyContent = 1")
}
if (excludeThumbnails) {
conditions.push("i.filename NOT LIKE '%thumbnail%'")
}
if (excludeResearchAndWriting) {
conditions.push("isInResearchAndWriting = 0")
}
if (conditions.length > 0) {
havingClause = `HAVING ${conditions.join(" AND ")}`
}
return knexRaw<DbEnrichedImageWithPageviews>(
trx,
`-- sql
SELECT
i.*,
COALESCE(SUM(pv.views_365d), 0) AS views_365d,
MAX(CASE WHEN i.filename = pg.content->>'$."featured-image"' THEN 1 ELSE 0 END) AS isFeaturedImage,
MAX(CASE WHEN
JSON_SEARCH(pg.content, 'one', i.filename, NULL, '$.body') IS NOT NULL
AND (
JSON_SEARCH(pg.content, 'one', i.filename, NULL, '$.body[*].primary[*].value.filename') IS NULL
AND JSON_SEARCH(pg.content, 'one', i.filename, NULL, '$.body[*].secondary[*].value.filename') IS NULL
AND JSON_SEARCH(pg.content, 'one', i.filename, NULL, '$.body[*].rows[*].articles[*].value.filename') IS NULL
AND JSON_SEARCH(pg.content, 'one', i.filename, NULL, '$.body[*].more.articles[*].value.filename') IS NULL
AND JSON_SEARCH(pg.content, 'one', i.filename, NULL, '$.body[*].latest.articles[*].value.filename') IS NULL
)
THEN 1 ELSE 0 END) AS isBodyContent,
MAX(CASE WHEN
JSON_SEARCH(pg.content, 'one', i.filename, NULL, '$.body[*].primary[*].value.filename') IS NOT NULL
OR JSON_SEARCH(pg.content, 'one', i.filename, NULL, '$.body[*].secondary[*].value.filename') IS NOT NULL
OR JSON_SEARCH(pg.content, 'one', i.filename, NULL, '$.body[*].rows[*].articles[*].value.filename') IS NOT NULL
OR JSON_SEARCH(pg.content, 'one', i.filename, NULL, '$.body[*].more.articles[*].value.filename') IS NOT NULL
OR JSON_SEARCH(pg.content, 'one', i.filename, NULL, '$.body[*].latest.articles[*].value.filename') IS NOT NULL
THEN 1 ELSE 0 END) AS isInResearchAndWriting
FROM images i
LEFT JOIN posts_gdocs_x_images pxi ON i.id = pxi.imageId
LEFT JOIN posts_gdocs pg ON pxi.gdocId = pg.id AND pg.published = 1
LEFT JOIN analytics_pageviews pv ON pv.url = CONCAT('https://ourworldindata.org/', pg.slug)
AND pv.day = (SELECT MAX(day) FROM analytics_pageviews)
WHERE i.cloudflareId IS NOT NULL
AND i.replacedBy IS NULL
GROUP BY i.id
${havingClause}`
)
}
export function getCloudflareImage(
trx: KnexReadonlyTransaction,
filename: string
): Promise<DbEnrichedImageWithUserId | undefined> {
return knexRawFirst(
trx,
`-- sql
SELECT *
FROM images
WHERE filename = ?
AND replacedBy IS NULL`,
[filename]
)
}
/**
* Get the title, slug, and googleId of all gdocs that reference each image
*/
export function getImageUsage(trx: KnexReadonlyTransaction): Promise<
Record<
number,
{
title: string
id: string
}[]
>
> {
return knexRaw<{
imageId: number