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
psqlAsBien := $(bin)/psql_script_vegbien
60
psqlNoSearchPath := env no_search_path=1 $(psqlAsBien)
61
# Usage: ($(inDatasrc); cat $(file))|$(psqlCmd)
62
inDatasrc := echo 'SET search_path TO "$(datasrc)";'
63

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

    
72
##### Environment
73

    
74
export PATH := $(bin):$(PATH)
75

    
76
##### General targets
77

    
78
all: _always maps ;
79

    
80
clean: _always
81
	$(RM) $(all)
82

    
83
remake: _always clean
84
	+$(selfMake)
85
# re-run make so that cache of existing files is reset
86

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

    
93
%/: % _always ;
94

    
95
%: %.make
96
	$(make_script)
97
.PRECIOUS: % # save partial outputs of aborted src make scripts
98

    
99
##### SVN
100

    
101
noImportFile := _no_import
102

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

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

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

    
123
##### Existing maps discovery
124

    
125
sortFile := import_order.txt
126

    
127
dontImport = $(wildcard $(1)/$(noImportFile))
128

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

    
141
anyMap := %/map.csv %/VegBIEN.csv %/unmapped_terms.csv %/new_terms.csv
142

    
143
extsFilter := $(addprefix %.,$(exts))
144
dataOnly = $(filter $(extsFilter),$(1))
145

    
146
anyTest = $*/test.%
147
srcsOnly = $(filter-out $(anyMap) $(anyTest) %/logs,$(call dataOnly,$(1)))
148

    
149
srcDict := map.csv
150

    
151
vocab := $(mappings)/VegCore.csv
152
coreMap := $(mappings)/VegCore-VegBIEN.csv
153
dict := $(mappings)/Veg+-VegCore.csv
154

    
155
viaMaps := $(importTables:%=%/map.csv)
156

    
157
autogenMaps := $(subst map.,VegBIEN.,$(viaMaps))
158
directMaps := $(autogenMaps) $(filter-out $(autogenMaps),\
159
$(wildcard */VegBIEN.csv))
160

    
161
##### Sources
162

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

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

    
177
%/cat: _always
178
	$(catSrcs)
179

    
180
##### Input data retrieval
181

    
182
# Must come before `%.sql: _MySQL/%.sql` to override it
183
%.sql: %.sql.make
184
	$(make_script)
185

    
186
# The export must be created with:
187
# `--compatible=postgresql --add-locks=false --set-charset --no-create-info`
188
# Must come before `%.sql: _MySQL/%.sql` to override it
189
%.data.sql: _MySQL/%.data.sql
190
	$(if $(wildcard $@),,$(bin)/my2pg.data <$< >$@)
191

    
192
# The export must be created with:
193
# `--compatible=postgresql --add-locks=false --set-charset`
194
# Add `--no-data` to create a schema-only export.
195
%.sql: _MySQL/%.sql
196
	$(if $(wildcard $@),,$(bin)/my2pg <$< >$@)
197

    
198
##### Staging tables installation
199

    
200
srcTable := %.src
201

    
202
dbExportsWildcard = $(sort $(patsubst _MySQL/%.make,%,$(wildcard\
203
$(1) _MySQL/$(1).make)))
204

    
205
dbExports := $(call dbExportsWildcard,*schema*.sql)# schemas first
206
ifeq ($(schema_only),) # add rest of .sql files
207
dbExports += $(filter-out $(dbExports),$(call dbExportsWildcard,*.sql))
208
endif
209
dbExports := $(strip $(dbExports))# += adds extra whitespace
210
allInstalls := $(if $(dbExports),sql) $(allTables)
211

    
212
install: _always schema $(allInstalls:%=%/install) ;
213

    
214
uninstall: _always confirm_rm_schema rm_schema ;
215
# rm_schema will also drop all staging tables
216

    
217
reinstall: _always uninstall install ;
218

    
219
confirm_rm_schema: _always
220
	$(if $(filter TNRS,$(datasrc)),$(call confirm,WARNING: This will delete the\
221
TNRS cache!,To save it: make backups/TNRS.backup-remake))
222

    
223
schema: _always
224
	-echo 'CREATE SCHEMA "$(datasrc)";'|$(psqlNoSearchPath)
225
# ignore errors if schema exists
226

    
227
rm_schema: _always
228
	echo 'DROP SCHEMA IF EXISTS "$(datasrc)" CASCADE;'|$(psqlNoSearchPath)
229

    
230
installLog := logs/install.log.sql
231

    
232
logInstall = $(if $(log),$(if $(quiet),$(2)$(1)$(installLog) 2>&1,2>&1|tee $(3)\
233
$(1)$(installLog)))
234
logInstallRoot = $(call logInstall,,>)
235
logInstall* = $(call logInstall,$*/,>)
236
logInstall*Add = $(call logInstall,$*/,>>,-a)# append to log
237

    
238
# Must come before %/install to override it
239
sql/install: $(dbExports)
240
	($(inDatasrc); cat $+|pg_dump_limit)|"time" $(psqlNoSearchPath) \
241
--set=schema='"$(datasrc)"' $(logInstallRoot)
242

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

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

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

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

    
275
%/uninstall: _always
276
	echo 'DROP TABLE IF EXISTS "$(datasrc)"."$*" CASCADE;'|$(psqlNoSearchPath)
277

    
278
%/reinstall: _always %/uninstall %/install ;
279

    
280
cleanup: _always $(tables:%=%/cleanup) ;
281

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

    
287
##### Maps building
288

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

    
292
# Maps to (try to) build are added to this
293
maps :=
294

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

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

    
304
$(srcDict):# empty target in case it doesn't exist
305

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

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

    
327
maps: $(maps) _always ;
328

    
329
all += $(maps)
330

    
331
##### Maps validation
332

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

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

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

    
347
termsSubdirs := $(importTables)
348

    
349
include $(root)/lib/mappings.Makefile
350

    
351
##### External dependencies
352

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

    
357
##### Mapping
358

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

    
363
##### Import to VegBIEN
364

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

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

    
376
import: $(importTables:%=%/import) _always ;
377

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

    
383
##### Log files from import
384

    
385
logs := $(wildcard */logs/*.log.sql */logs/*.trace)
386

    
387
rm_logs: _always
388
	$(RM) $(logs)
389

    
390
##### Verification of import
391

    
392
verifyTables := $(patsubst verify/%.ref,%,$(wildcard verify/*.ref))
393

    
394
verify: $(verifyTables:%=%/verify) _always ;
395

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

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

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

    
419
all += $(wildcard verify/*.out)
420

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

    
425
##### Editing import
426

    
427
rotate: _always
428
	echo "UPDATE source SET shortname = shortname||'.$(version)'\
429
WHERE shortname = '$(datasrc)';"|$(psqlAsBien)
430

    
431
rm: _always
432
	echo "DELETE FROM source WHERE shortname = '$(datasrc)';"|$(psqlAsBien)
433

    
434
##### Testing
435

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

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

    
463
tests :=
464

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

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

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

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

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

    
484
test: _always $(testOutputs) ;
485

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

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

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

    
495
##### Documentation
496

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

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