Project

General

Profile

1
selfDir_uZPPqC := $(dir $(lastword $(MAKEFILE_LIST)))
2
root := $(selfDir_uZPPqC)..
3
include $(root)/lib/common.Makefile
4

    
5

    
6
##### Configuration
7

    
8
# Command line
9
log ?= $(if $(test),,1)
10
profile ?=
11
quiet ?=
12
reverify ?= 1
13
schema_only ?=
14
use_staged ?= $(by_col)
15

    
16
# Makefile
17
exts ?= csv tsv txt dmp xml
18
test_n ?= 2
19

    
20
##### Vars/functions
21

    
22
# Paths
23
datasrc := $(patsubst .%,%,$(notdir $(realpath .)))
24
bin := $(root)/bin
25
mappings := $(root)/mappings
26

    
27
# Make
28
SHELL := /bin/bash
29
selfMake = $(MAKE) --makefile=../input.Makefile
30
subMake = $(MAKE) $(@:$(root)/%=%) --directory=$(root)
31
+_ = $(+:_%=)
32
addBeforeExt = $(basename $(2))$(1)$(suffix $(2))
33

    
34
# Terminal
35
termCols := $(shell tput cols)
36
esc := '['
37
reset := $(esc)'0m'
38
emph := $(esc)'7m '
39
endEmph := ' '$(reset)
40

    
41
# User interaction
42

    
43
confirm = $(if $(shell read -p $(emph)"$(1)"$(endEmph)$$'$(if\
44
$(2),\n$(2))\nContinue? (y/n) ' REPLY; test "$$REPLY" = y && echo t),,\
45
$(error Aborting))
46

    
47
# Commands
48
MKDIR = mkdir -p
49
mkdir = $(MKDIR) $(@D)
50
CP = cp -p
51
diff = diff --unified=2
52
diffIgnoreSpace = $(diff) --ignore-space-change
53
diffVerbose = $(if $(verbose),diff --side-by-side --left-column\
54
--width=$(termCols),$(diff))
55

    
56
# BIEN commands
57
sortFilenames = $(shell $(bin)/sort_filenames $(1))
58
selfMap = $(bin)/cols 0 0
59
psqlOpts := --set ON_ERROR_STOP=1 --quiet
60
psqlAsBien := $(bin)/psql_vegbien $(psqlOpts)
61
searchPath := $(datasrc),$(shell prefix=; . $(bin)/vegbien_dest;\
62
echo "$$schemas")
63
searchPath := "$(subst $(comma),"$(comma)",$(searchPath))"
64
# Usage: ($(inDatasrc); cat $(file))|$(psqlCmd)
65
inDatasrc := echo 'SET search_path TO $(searchPath);'
66

    
67
# SVN
68
addDir = $(if $(wildcard $(1)/),svn add --depth=empty $(1),svn mkdir $(1))
69
setSvnIgnore = svn propset svn:ignore $(2) $(1)
70
define addDirWithIgnore
71
$(addDir)
72
$(setSvnIgnore)
73
endef
74

    
75
##### Environment
76

    
77
export PATH := $(bin):$(PATH)
78

    
79
##### General targets
80

    
81
all: _always maps ;
82

    
83
clean: _always
84
	$(RM) $(all)
85

    
86
remake: _always clean
87
	+$(selfMake)
88
# re-run make so that cache of existing files is reset
89

    
90
# Only remake if doesn't exist. This prevents unintentional remaking when the
91
# make script is newly checked out from svn (which sets the mod time to now) but
92
# the output is synced externally.
93
# Can't remove prereq to do this, because it determines when the rule applies.
94
make_script = $(if $(wildcard $@),,"time" ./$< >$@)
95

    
96
%/: % _always ;
97

    
98
%: %.make
99
	$(make_script)
100
.PRECIOUS: % # save partial outputs of aborted src make scripts
101

    
102
##### SVN
103

    
104
noImportFile := _no_import
105

    
106
svnFilesGlob:= */{,$(noImportFile),{,.}{map,*terms,VegBIEN}.csv{,.*},*header.*,*.sql,test*.xml*}
107
svnFilesGlob := {map.csv,*{schema,~}*.sql,{,*/}*.make,$(svnFilesGlob)}
108
_svnFilesGlob := {_MySQL/{,*schema*.sql,*.make},_src/*.{url,pdf}}
109
svnFiles = $(filter-out _% logs/%,$(call wildcard/,$(svnFilesGlob)))\
110
$(call wildcard/,$(_svnFilesGlob))
111

    
112
add: _always
113
	$(call setSvnIgnore,.,'*')
114
	$(call addDirWithIgnore,logs,$$'*.log.sql\n*.trace')
115
	$(call addDirWithIgnore,verify,'*.out')
116
	$(call addFile,import_order.txt)
117
	$(if $(wildcard _MySQL/),$(call addDirWithIgnore,_MySQL,'*'))
118
	$(if $(wildcard _src/),$(call addDirWithIgnore,_src,'*'))
119
	$(call add*,$(svnFiles))
120

    
121
# Adds a new table subdir
122
%/add: _always
123
	$(call addDirWithIgnore,$*,'*')
124
	$(call addDirWithIgnore,$*/logs,$$'*.log.sql\n*.trace')
125

    
126
##### Existing maps discovery
127

    
128
sortFile := import_order.txt
129

    
130
dontImport = $(wildcard $(1)/$(noImportFile))
131

    
132
tables := $(if $(wildcard $(sortFile)),$(shell cat $(sortFile)))
133
    # $(shell) replaces "\n" with " "
134
allSubdirs := $(call wildcard/,*/)
135
allTables := $(call sortFilenames,$(filter-out _% verify logs,$(allSubdirs:%/=%)))
136
joinedTables := $(filter-out $(tables),$(allTables))
137
allTables := $(joinedTables) $(tables)# move joined tables to beginning
138
ifeq ($(tables),)# none specified in sort file
139
tables := $(allTables)
140
endif
141
importTables := $(foreach table,$(tables),$(if\
142
$(call dontImport,$(table)),,$(table)))
143

    
144
anyMap := %/map.csv %/VegBIEN.csv %/unmapped_terms.csv %/new_terms.csv
145

    
146
extsFilter := $(addprefix %.,$(exts))
147
dataOnly = $(filter $(extsFilter),$(1))
148

    
149
anyTest = $*/test.%
150
srcsOnly = $(filter-out $(anyMap) $(anyTest) %/logs,$(call dataOnly,$(1)))
151

    
152
srcDict := map.csv
153

    
154
vocab := $(mappings)/VegCore.csv
155
coreMap := $(mappings)/VegCore-VegBIEN.csv
156
dict := $(mappings)/Veg+-VegCore.csv
157

    
158
viaMaps := $(importTables:%=%/map.csv)
159

    
160
autogenMaps := $(subst map.,VegBIEN.,$(viaMaps))
161
directMaps := $(autogenMaps) $(filter-out $(autogenMaps),\
162
$(wildcard */VegBIEN.csv))
163

    
164
##### Sources
165

    
166
srcs = $(call sortFilenames,$(call srcsOnly,$(wildcard $*/*)))
167
nonHeaderSrcs = $(filter-out %/header.csv,$(srcs))
168
isRef = $(if $(nonHeaderSrcs),,1)
169
    # empty subdir, so references an already-installed staging table
170
isXml = $(filter %.xml,$(nonHeaderSrcs))
171
nonXml = $(if $(isXml),,1)
172
isCsv = $(if $(nonHeaderSrcs),$(if $(isXml),,1))
173
    # true if $(srcs) non-empty and contains no *.xml
174
catSrcs = $(bin)/cat$(if $(nonXml),_csv) $(srcs)
175
withCatSrcs = $(catSrcs:$(bin)/%=$(bin)/with_%) --
176

    
177
# Usage: `make {--silent|-s} inputs/<datasrc>/cat` (don't echo make commands)
178
cat: $(importTables:%=%/cat) _always ;
179

    
180
%/cat: _always
181
	$(catSrcs)
182

    
183
##### Staging tables installation
184

    
185
srcTable := %.src
186

    
187
dbExports := $(sort $(wildcard *schema*.sql))# schemas first
188
ifeq ($(schema_only),)
189
dbExports += $(sort $(filter-out $(dbExports),$(wildcard *.sql)))# all others
190
endif
191
dbExports := $(strip $(dbExports))# += adds extra whitespace
192
allInstalls := $(if $(dbExports),sql) $(allTables)
193

    
194
install: _always schema $(allInstalls:%=%/install) ;
195

    
196
uninstall: _always confirm_rm_schema rm_schema ;
197
# rm_schema will also drop all staging tables
198

    
199
reinstall: _always uninstall install ;
200

    
201
confirm_rm_schema: _always
202
	$(if $(filter TNRS,$(datasrc)),$(call confirm,WARNING: This will delete the\
203
TNRS cache!,To save it: make backups/TNRS.backup-remake))
204

    
205
schema: _always
206
	-echo 'CREATE SCHEMA "$(datasrc)";'|$(psqlAsBien)
207
# ignore errors if schema exists
208

    
209
rm_schema: _always
210
	echo 'DROP SCHEMA IF EXISTS "$(datasrc)" CASCADE;'|$(psqlAsBien)
211

    
212
installLog := logs/install.log.sql
213

    
214
logInstall = $(if $(log),$(if $(quiet),$(2)$(1)$(installLog) 2>&1,2>&1|tee $(3)\
215
$(1)$(installLog)))
216
logInstallRoot = $(call logInstall,,>)
217
logInstall* = $(call logInstall,$*/,>)
218
logInstall*Add = $(call logInstall,$*/,>>,-a)# append to log
219

    
220
# Must come before %/install to override it
221
sql/install: $(dbExports)
222
	($(inDatasrc); cat $+|pg_dump_limit)|"time" $(psqlAsBien) \
223
--set=schema='"$(datasrc)"' $(logInstallRoot)
224

    
225
# Must come before `%.sql: _MySQL/%.sql` to override it
226
%.sql: %.sql.make
227
	$(make_script)
228

    
229
# The export must be created with:
230
# `--compatible=postgresql --add-locks=false --set-charset --no-create-info`
231
# Must come before `%.sql: _MySQL/%.sql` to override it
232
%.data.sql: _MySQL/%.data.sql
233
	$(if $(wildcard $@),,$(bin)/my2pg.data <$< >$@)
234

    
235
# The export must be created with:
236
# `--compatible=postgresql --add-locks=false --set-charset`
237
# Add `--no-data` to create a schema-only export.
238
%.sql: _MySQL/%.sql
239
	$(if $(wildcard $@),,$(bin)/my2pg <$< >$@)
240

    
241
cleanup = $(if $(wildcard $*/cleanup.sql),($(inDatasrc); cat $*/cleanup.sql)\
242
|"time" $(psqlAsBien) --echo-all --set=table='"$*"' $(logInstall*Add),\
243
(prefix=; . $(bin)/vegbien_dest; env schema=$(datasrc) table=$* $(bin)/csv2db)\
244
$(logInstall*Add))
245

    
246
define exportHeader
247
$(cleanup)
248
echo 'SELECT * FROM "$(datasrc)"."$*" LIMIT 0;'|$(psqlAsBien) \
249
--no-align --field-separator=, --pset=footer=off >$*/header.csv
250
endef
251

    
252
# For staging tables which are derived by joining together other staging tables.
253
%/install %/header.csv: %/create.sql _always
254
	($(inDatasrc); echo 'CREATE TABLE "$*" AS'; cat $<; echo ';')|"time" \
255
$(psqlAsBien) --echo-all --set=schema='"$(datasrc)"' --set=table='"$*"' \
256
$(logInstall*)
257
	$(exportHeader)
258
.PRECIOUS: %/header.csv
259

    
260
%/install: _always
261
	$(if $(isRef),$(exportHeader),$(if $(nonXml),$(import_install_)))
262
	$(if $(wildcard $*/postprocess.sql),($(inDatasrc); cat $*/postprocess.sql;)\
263
|"time" $(psqlAsBien) --echo-all --set=table='"$*"' $(logInstall*Add))
264
define import_install_
265
(prefix=; . $(bin)/vegbien_dest; "time" nice -n +5\
266
env schema=$(datasrc) table=$* $(bin)/csv2db $(catSrcs) $(logInstall*))
267
$(if $(filter $(srcTable),$*),($(inDatasrc);\
268
echo 'ALTER TABLE "$(datasrc)"."$*" RENAME row_num TO "$*.row_num";')|"time"\
269
$(psqlAsBien) --echo-all --set=table='"$*"' $(logInstall*Add))
270
endef
271
# table-scope src table's row_num col to allow joining it with other tables
272

    
273
%/uninstall: _always
274
	echo 'DROP TABLE IF EXISTS "$(datasrc)"."$*" CASCADE;'|$(psqlAsBien)
275

    
276
%/reinstall: _always %/uninstall %/install ;
277

    
278
cleanup: _always $(tables:%=%/cleanup) ;
279

    
280
# WARNING: This removes any index comments, due to a PostgreSQL bug.
281
# This occurs because ALTER TABLE recreates the index but not its comment.
282
%/cleanup: _always
283
	$(cleanup)
284

    
285
##### Maps building
286

    
287
# WARNING: You CANNOT make a subdir using `make inputs/<datasrc>/<subdir>/`.
288
# You must instead make the entire datasource dir: `make inputs/<datasrc>/`
289

    
290
# Maps to (try to) build are added to this
291
maps :=
292

    
293
srcRoot = $(mappings)/root.sh
294
mkSrcMap = $(catSrcs)|(. $(srcRoot); env datasrc=$(datasrc) $(bin)/src_map >$@)
295

    
296
define translate
297
$(bin)/in_place $< $(bin)/canon 1 $(1)
298
$(bin)/in_place $< $(bin)/translate 1 $(1)
299
endef
300
translate? = $(if $(wildcard $(1)),$(translate))
301

    
302
$(srcDict):# empty target in case it doesn't exist
303

    
304
# Via maps cleanup
305
ifneq ($(filter %/.map.csv.last_cleanup,$(MAKECMDGOALS)),)
306
%/.map.csv.last_cleanup: %/map.csv $(vocab) $(dict) $(coreMap) $(srcDict)
307
	$(call translate?,$(srcDict))
308
	$(bin)/in_place $< $(bin)/canon 1 $(vocab)
309
	$(call translate?,$(dict))
310
	touch $@
311
	+$(selfMake) $(<:%/map.csv=%/unmapped_terms.csv)
312
	+$(selfMake) $(<:%/map.csv=%/new_terms.csv)
313
.PRECIOUS: %/.map.csv.last_cleanup
314
else
315
%/map.csv: _always
316
	$(if $(wildcard $@),,$(if $(nonXml),$(mkSrcMap)))
317
	+$(selfMake) $(@:%/map.csv=%/.map.csv.last_cleanup)
318
.PRECIOUS: %/map.csv
319
endif
320

    
321
%/VegBIEN.csv: %/map.csv $(coreMap)
322
	<$< $(bin)/cat_cols 1 2|$(bin)/join $(coreMap)|$(bin)/sort_map >$@
323
maps += $(autogenMaps)
324

    
325
maps: $(maps) _always ;
326

    
327
all += $(maps)
328

    
329
##### Maps validation
330

    
331
# `tail -n +2`: Remove header before running filter_out_ci because filter_out_ci
332
# only removes the header if it matches the vocabulary's header.
333

    
334
%/unmapped_terms.csv: %/map.csv $(coreMap)
335
	tail -n +2 $<|$(bin)/cols 1|$(bin)/filter_out_ci 0 $(coreMap) >$@
336
	$(bin)/autoremove $@
337

    
338
%/new_terms.csv: %/map.csv $(vocab) $(dict) %/unmapped_terms.csv
339
	$(newTerms)
340
	$(bin)/autoremove $@
341
newTerms = tail -n +2 $<|$(bin)/filter_out_ci 0 $(vocab)|$(bin)/filter_out_ci 0\
342
$(dict) $(if $(wildcard $(word 4,$+)),|$(bin)/filter_out_ci 0 $(word 4,$+))\
343
|grep -vE '^"?:' >$@; exit 0# because grep exits nonzero if no match
344

    
345
termsSubdirs := $(importTables)
346

    
347
include $(root)/lib/mappings.Makefile
348

    
349
##### External dependencies
350

    
351
$(root)/%: _always
352
	+$(subMake)
353
.PRECIOUS: $(root)/% # let ext. dir's Makefile decide whether to delete on error
354

    
355
##### Mapping
356

    
357
+maps = $(filter %/map.csv %/VegBIEN.csv $(mappings)/%,$(+_))
358
map2db = env in_database=vegbien in_schema=$(datasrc) in_table=$*\
359
out_database=vegbien $(root)/map $(+maps)
360

    
361
##### Import to VegBIEN
362

    
363
profileTest = $(if $(profile),$(if $(test),1))
364
profileOnly = -env profile_to=/dev/fd/3 $(map2db) 3>&1 1>&2|\
365
$(bin)/profile_stats /dev/fd/0
366

    
367
log_ = $*/logs/$(if $(n),n=$(n).,)$(version).log.sql
368
trace = $(log_:.log.sql=.trace)
369
import = -$(if $(profileTest),$(profileOnly),(set -x; "time" env commit=1\
370
$(if $(profile),profile_to=$(trace)) $(map2db)) $(if $(log),\
371
$(if $(n),,&>$(log_)))$(if $(log),$(if $(n), 2>&1|tee -a $(log_))))
372
# don't abort on import errors, which often relate to invalid input data
373

    
374
import: $(importTables:%=%/import) _always ;
375

    
376
%/import: %/VegBIEN.csv _always
377
	$(import)
378
# default:
379
%/import: _always ;
380

    
381
##### Log files from import
382

    
383
logs := $(wildcard */logs/*.log.sql */logs/*.trace)
384

    
385
rm_logs: _always
386
	$(RM) $(logs)
387

    
388
##### Verification of import
389

    
390
verifyTables := $(patsubst verify/%.ref,%,$(wildcard verify/*.ref))
391

    
392
verify: $(verifyTables:%=%/verify) _always ;
393

    
394
%/verify: verify/%.ref verify/%.out _always
395
	-$(diffVerbose) $(+_)
396
# don't abort on verification errors, which are expected during development
397
# default:
398
%/verify: verify/%.out _always
399
	$(if $(shell test -e $< && echo t),cat $<)
400
# don't run if verify/%.out's default do-nothing action was used
401
# can't use $(wildcard) because it won't recheck file after verify/%.out is run
402

    
403
psqlExport := "time" $(psqlAsBien) --no-align --field-separator=$$'\t'\
404
--pset=footer=off --pset=null=NULL
405
# Note that using $(inDatasrc) will not work with datasources whose tables are
406
# the same name as VegBIEN tables (likely only VegBank), because the datasource
407
# is first in the search_path.
408
verify = $(if $(reverify),($(inDatasrc); cat $<)|$(psqlExport)\
409
--set=datasource="'$(datasrc)'" >$@)
410

    
411
verify/%.out: $(mappings)/verify.%.sql _always
412
	$(verify)
413
.PRECIOUS: verify/%.out # save partial output in case of error to help debugging
414
# default:
415
verify/%.out: _always ;
416

    
417
all += $(wildcard verify/*.out)
418

    
419
%.ref: %.ref.sql
420
	($(inDatasrc); cat $<)|$(psqlExport) >$@
421
.PRECIOUS: %.ref # there must always be a .ref for the make rules to work
422

    
423
##### Editing import
424

    
425
rotate: _always
426
	echo "UPDATE party SET organizationname = organizationname||'.$(version)'\
427
WHERE organizationname = '$(datasrc)';"|$(psqlAsBien)
428

    
429
rm: _always
430
	echo "DELETE FROM party WHERE organizationname = '$(datasrc)';"|\
431
$(psqlAsBien)
432

    
433
##### Testing
434

    
435
testRefOutput = $(subst .by_col,,$(1))
436
testRef = $(testRefOutput).ref
437
hasOwnRef = $(filter $@,$(call testRefOutput,$@))
438
# filter returns non-empty if they are equal
439

    
440
# `rm $@`: Remove outputs of successful tests to reduce clutter
441
# `$(foreach use_staged...)`: Run with use_staged=1
442
define runTest
443
@echo "Testing $(abspath $@)..."
444
>$@ env test=1 n=$(test_n) $(1) $(foreach use_staged,1,$(map2db))
445
@(set -x; $(diffIgnoreSpace) $(call testRef,$@) $@) 2>&1 && rm $@ || { e=$$?;\
446
$(if $(wildcard $(call testRef,$@)),,cat $@;)\
447
$(if $(hasOwnRef),\
448
{\
449
read -p $(emph)'Accept new test output? (y/n)'$(endEmph) REPLY;\
450
if test "$$REPLY" = y; then\
451
(set -x; $(MAKE) $@-ok --directory=$(realpath .) --makefile=../input.Makefile);\
452
exit 0;\
453
fi;\
454
};,\
455
echo $(emph)"Note: The preceding failed test is compared to another test's\
456
output"$(endEmph);\
457
echo $(emph)"When it fails, this always indicates a bug"$(endEmph);\
458
)\
459
exit $$e;}
460
endef
461

    
462
tests :=
463

    
464
# Requires staging tables. To create them, run `make inputs/<datasrc>/install`.
465
# Non-flat-file inputs fall back to mimicking a successful test
466
%/test.xml: %/VegBIEN.csv _always
467
	$(if $(nonXml),$(call runTest,by_col=))
468
tests += %/test.xml
469

    
470
%/test.by_col.xml: %/VegBIEN.csv _always
471
	$(if $(nonXml),$(call runTest,by_col=1))
472

    
473
# Only run column-based tests if column-based mode enabled, because these tests
474
# are much slower than the row-based tests for small numbers of rows
475
ifneq ($(by_col),)
476
tests += %/test.by_col.xml
477
endif
478

    
479
testOutputs := $(foreach test,$(tests),$(importTables:%=$(test)))
480

    
481
.PRECIOUS: $(testOutputs) # save outputs of failed tests so they can be accepted
482

    
483
test: _always $(testOutputs) ;
484

    
485
all += $(wildcard %/test*.xml)
486

    
487
# Accepts a test output: make <test_output_path>-ok
488
%-ok: _always
489
	mv $* $(call testRef,$*)
490

    
491
accept-all: _always
492
	+yes|$(selfMake) test
493

    
494
##### Documentation
495

    
496
steps = $(selfMake) -s $*/import test=1 by_col=1 verbosity=2 n=100\
497
2>&1|$(bin)/debug2redmine >$@
498

    
499
%/logs/steps.by_col.log.sql: _always
500
	+$(steps)
(4-4/4)