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
full_import ?=
10
import_source ?= 1
11
log ?= $(if $(test),,1)
12
noclobber ?=
13
profile ?=
14
quiet ?=
15
reverify ?= 1
16
schema_only ?=
17
use_staged ?= $(by_col)
18

    
19
# Makefile
20
exts ?= csv tsv tab txt dat dmp xml
21
test_n ?= 2
22

    
23
##### Vars/functions
24

    
25
# Paths
26
datasrc := $(patsubst .%,%,$(notdir $(realpath .)))
27
bin := $(root)/bin
28
mappings := $(root)/mappings
29

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

    
37
# Terminal
38
termCols := $(shell tput cols)
39

    
40
# Commands
41
MKDIR = mkdir -p
42
mkdir = $(MKDIR) $(@D)
43
diff = diff --unified=2
44
diffIgnoreSpace = $(diff) --ignore-space-change
45
diffVerbose = $(if $(verbose),diff --side-by-side --left-column\
46
--width=$(termCols),$(diff))
47

    
48
# BIEN commands
49
sortFilenames = $(shell $(bin)/sort_filenames $(1))
50
selfMap = $(bin)/cols 0 0
51
psqlAsBien := $(bin)/psql_verbose_vegbien
52
psqlNoSearchPath := env no_search_path=1 $(psqlAsBien)
53
# Usage: ($(inDatasrc); cat $(file))|$(psqlCmd)
54
inDatasrc := echo 'SET search_path TO "$(datasrc)";'
55

    
56
# SVN
57
setSvnIgnore = svn propset svn:ignore $(2) $(1)
58
define addDirWithIgnore
59
$(addDir)
60
$(setSvnIgnore)
61
endef
62

    
63
##### Environment
64

    
65
export PATH := $(bin):$(PATH)
66

    
67
##### General targets
68

    
69
all: _always maps ;
70

    
71
clean: _always
72
	$(RM) $(all)
73

    
74
remake: _always clean
75
	+$(selfMake)
76
# re-run make so that cache of existing files is reset
77

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

    
84
%/: %/map.csv _always ;
85

    
86
%/: % _always ;
87

    
88
%: %.make
89
	$(make_script)
90
.PRECIOUS: % # save partial outputs of aborted src make scripts
91

    
92
##### Tables discovery
93

    
94
sortFile := import_order.txt
95
noImportFile := _no_import
96

    
97
dontImport = $(wildcard $(noImportFile))$(wildcard $(1)/$(noImportFile))$(if\
98
$(import_source),,$(filter Source,$(1)))
99

    
100
tables := $(if $(wildcard $(sortFile)),$(shell cat $(sortFile)))
101
    # $(shell) replaces "\n" with " "
102
allSubdirs := $(call wildcard/,*/)
103
allTables := $(call sortFilenames,$(filter-out _% verify logs,$(allSubdirs:%/=%)))
104
joinedTables := $(filter-out $(tables),$(allTables))
105
allTables := $(strip $(joinedTables) $(tables))# move joined tables to beginning
106
has_visible_files = $(call wildcard/,$(1)/*)
107
allTables := $(foreach table,$(allTables),$(if\
108
$(call has_visible_files,$(table)),$(table)))
109
ifeq ($(tables),)# none specified in sort file
110
tables := $(allTables)
111
endif
112
importTables := $(foreach table,$(tables),$(if\
113
$(call dontImport,$(table)),,$(table)))
114

    
115
list_tables: _always # use `make -s` to avoid echoing commands
116
	@for table in $(tables); do echo "$$table"; done
117

    
118
##### SVN
119

    
120
svnFilesGlob:= */{,$(noImportFile),{,.}{map,VegBIEN}.csv{,.*},*header.*,*.sql,test.xml.ref}
121
svnFilesGlob := {map.csv,*{schema,~}*.sql,{,*/}{*.make,*terms.csv},$(svnFilesGlob)}
122
_svnFilesGlob := {_MySQL/{,*schema*.sql,*.make},{,*/}{*{run,Makefile},*.{md5,url,pdf},*README.TXT}}
123
svnFiles = $(filter-out _% logs/% %.data.sql,$(call wildcard/,$(svnFilesGlob)))\
124
$(call wildcard/,$(_svnFilesGlob))
125

    
126
# To update all inputs with these settings: make inputs/add
127
add: _always Source/add $(allTables:%=%/add)
128
	$(call setSvnIgnore,.,'*')
129
	$(call addDirWithIgnore,logs,$$'*.gz\n*.log.sql\n*.trace')
130
	$(call addDirWithIgnore,verify,$$'*.out\n*.csv\n*.xls\n*.xlsx')
131
	$(call addFile,import_order.txt)
132
	$(if $(wildcard _MySQL/),$(call addDirWithIgnore,_MySQL,'*'))
133
	$(if $(wildcard _src/),$(call addDirWithIgnore,_src,'*'))
134
	$(if $(wildcard _archive/),$(call addDirWithIgnore,_archive,'*'))
135
	$(call add*,$(svnFiles))
136

    
137
# Adds a new table subdir
138
%/add: _always
139
	$(call addDirWithIgnore,$*,'*')
140
	$(call addDirWithIgnore,$*/logs,$$'*.gz\n*.log.sql\n*.trace')
141

    
142
##### Existing maps discovery
143

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

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

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

    
153
srcDict := map.csv
154

    
155
vocab := $(mappings)/VegCore.vocab.csv
156
thesaurus := $(mappings)/VegCore.thesaurus.csv
157
coreMap := $(mappings)/VegCore-VegBIEN.csv
158

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

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

    
165
##### Sources
166

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

    
178
# Run with `make -s` to avoid echoing make commands
179
cat: $(importTables:%=%/cat) _always ;
180

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

    
184
##### Input data retrieval
185

    
186
# Must come before `%.sql: _MySQL/%.sql` to override it
187
%.sql: %.sql.make
188
	$(make_script)
189

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

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

    
202
##### Staging tables installation
203

    
204
srcTable := %.src
205

    
206
dbExportsWildcard = $(sort $(patsubst _MySQL/%.make,%,$(wildcard\
207
$(1) _MySQL/$(1).make)))
208

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

    
216
install: _always schema $(allInstalls:%=%/install) ;
217

    
218
uninstall: _always confirm_rm_schema rm_schema ;
219
# rm_schema will also drop all staging tables
220

    
221
reinstall: _always uninstall install ;
222

    
223
confirm_rm_schema: _always
224
	$(if $(filter TNRS,$(datasrc)),$(call confirm,WARNING: This will delete the\
225
TNRS cache!,To save it: make backups/TNRS.backup-remake))
226

    
227
schema: _always
228
	-echo 'CREATE SCHEMA "$(datasrc)";'|$(psqlNoSearchPath)
229
# ignore errors if schema exists
230

    
231
rm_schema: _always
232
	echo 'DROP SCHEMA IF EXISTS "$(datasrc)" CASCADE;'|$(psqlNoSearchPath)
233

    
234
installLog := logs/install.log.sql
235

    
236
log_dir = $(1)logs
237
has_log_dir = $(call and,$(wildcard $(log_dir)),$(call not,$(noclobber)))
238
logInstall = $(if $(has_log_dir),$(if $(quiet),$(2)$(1)$(installLog)\
239
2>&1,2>&1|tee $(3) $(1)$(installLog)))
240
logInstallRoot = $(call logInstall,,>)
241
logInstall* = $(call logInstall,$*/,>)
242
logInstall*Add = $(call logInstall,$*/,>>,-a)# append to log
243

    
244
# Must come before %/install to override it
245
sql/install: $(dbExports)
246
	($(inDatasrc); cat $+|pg_dump_limit)|"time" env no_search_path=1 \
247
$(bin)/psql_script_vegbien --set=schema='"$(datasrc)"' $(logInstallRoot)
248

    
249
cleanup = $(if $(wildcard $*/cleanup.sql),($(inDatasrc); cat $*/cleanup.sql)\
250
|"time" $(psqlNoSearchPath) --echo-all --set=table='"$*"' $(logInstall*Add),\
251
(export schema=$(datasrc) table=$*; . $(bin)/vegbien_dest; unset schemas; \
252
$(bin)/csv2db) $(logInstall*Add))
253

    
254
%/header.csv:
255
	echo 'COPY (SELECT * FROM "$(datasrc)"."$*" LIMIT 0) TO STDOUT CSV HEADER;'|\
256
env no_search_path=1 $(bin)/psql_script_vegbien >$*/header.csv
257

    
258
exportHeader = $(selfMake) $*/header.csv
259

    
260
# Don't try to edit a view. Must come before %/install to override it.
261
%_view/install: _always ;
262

    
263
%.sql/run: _always
264
	$(if $(wildcard $(@D)),($(inDatasrc); cat $(@D))|(cd '$(*D)';\
265
"time" env no_search_path=1 ../$(bin)/psql_verbose_vegbien \
266
--set=table='"$(*D)"' --set=table_str=\''"$(*D)"'\'))
267

    
268
%/postprocess: _always
269
	$(if $(wildcard $*/run),,$(selfMake) $*/postprocess.sql/run)
270
	$(if $(wildcard $*/import),$*/import)
271

    
272
# For staging tables which are derived by joining together other staging tables.
273
%/install %/header.csv: %/create.sql _always
274
	($(inDatasrc); echo 'CREATE TABLE "$*" AS'; cat $<; echo ';')|"time" \
275
$(psqlNoSearchPath) --echo-all --set=schema='"$(datasrc)"' --set=table='"$*"' \
276
$(logInstall*)
277
	$(selfMake) $*/postprocess
278
	$(exportHeader)
279
	$(cleanup)
280
ifneq ($(noclobber),)
281
.PRECIOUS: %/header.csv
282
endif
283

    
284
%/install: _always
285
	$(if $(isCsv),$(import_install_))
286
	$(selfMake) $*/postprocess
287
	-$(exportHeader)
288
	-$(if $(isCsv),,$(cleanup))
289
# ignore errors if table does not exist (non-data dir)
290
define import_install_
291
(. $(bin)/vegbien_dest; unset schemas; "time" nice -n +5\
292
env schema=$(datasrc) table=$* $(bin)/csv2db $(catSrcs) $(logInstall*))
293
$(if $(filter $(srcTable),$*),($(inDatasrc);\
294
echo 'ALTER TABLE "$(datasrc)"."$*" RENAME row_num TO "$*.row_num";')|"time"\
295
$(psqlNoSearchPath) --echo-all --set=table='"$*"' $(logInstall*Add))
296
endef
297
# table-scope src table's row_num col to allow joining it with other tables
298

    
299
%/uninstall: _always
300
	echo 'DROP TABLE IF EXISTS "$(datasrc)"."$*" CASCADE;'|$(psqlNoSearchPath)
301

    
302
%/reinstall: _always %/uninstall %/install ;
303

    
304
postprocess: _always $(allTables:%=%/postprocess) ;
305

    
306
cleanup: _always $(tables:%=%/cleanup) ;
307

    
308
# WARNING: This removes any index comments, due to a PostgreSQL bug.
309
# This occurs because ALTER TABLE recreates the index but not its comment.
310
%/cleanup: _always
311
	$(cleanup)
312

    
313
##### Maps building
314

    
315
# Maps to (try to) build are added to this
316
maps :=
317

    
318
srcRoot = $(mappings)/root.sh
319
mkSrcMap = (. $(srcRoot); env datasrc=$(datasrc) $(bin)/src_map <$*/header.csv\
320
>$@)
321

    
322
translate = $(if $(wildcard $(1)),$(bin)/in_place $< $(bin)/translate_ci 1 $(1))
323

    
324
$(srcDict):# empty target in case it doesn't exist
325

    
326
# Via maps cleanup
327
ifneq ($(filter %/.map.csv.last_cleanup,$(MAKECMDGOALS)),)
328
%/.map.csv.last_cleanup: %/map.csv $(vocab) $(thesaurus) $(coreMap) $(srcDict)
329
	$(call translate,$(srcDict))
330
	$(bin)/in_place $< $(bin)/canon 1 $(vocab)
331
	$(call translate,$(thesaurus))
332
	$(bin)/in_place $< $(bin)/fix_line_endings
333
	touch $@
334
	+$(selfMake) $(<:%/map.csv=%/unmapped_terms.csv)
335
	+$(selfMake) $(<:%/map.csv=%/new_terms.csv)
336
.PRECIOUS: %/.map.csv.last_cleanup
337
else
338
%/map.csv: _always
339
	$(if $(wildcard $@),,$(mk_map_csv))
340
	+$(selfMake) $(@:%/map.csv=%/.map.csv.last_cleanup)
341
define mk_map_csv
342
+$(selfMake) $*/header.csv
343
$(if $(nonXml),$(mkSrcMap))
344
endef
345
endif
346

    
347
%/VegBIEN.csv: %/map.csv $(coreMap)
348
	<$< $(bin)/cat_cols 1 2$(if $(wildcard\
349
$*/run),|$(bin)/cols 1 1 3|(head -1 $<; tail -n +2)\
350
)|$(bin)/join $(coreMap)|$(bin)/sort_map >$@
351
maps += $(autogenMaps)
352

    
353
maps: $(maps) _always ;
354

    
355
all += $(maps)
356

    
357
##### Maps validation
358

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

    
362
%/unmapped_terms.csv: %/map.csv $(coreMap)
363
	tail -n +2 $<|$(bin)/cols 1|$(bin)/filter_out_ci 0 $(coreMap) >$@
364
	$(bin)/autoremove $@
365

    
366
%/new_terms.csv: %/map.csv $(vocab) $(thesaurus) %/unmapped_terms.csv
367
	$(newTerms)
368
	$(bin)/autoremove $@
369
newTerms = tail -n +2 $<|$(bin)/filter_out_ci 0 $(vocab)|$(bin)/filter_out_ci 0\
370
$(thesaurus) $(if $(wildcard $(word 4,$+)),|$(bin)/filter_out_ci 0 $(word 4,$+))\
371
|grep -vE -e '^"?:' -e 'UNUSED' >$@; exit 0 # grep exits nonzero if no match
372

    
373
termsSubdirs := $(importTables)
374

    
375
include $(root)/lib/mappings.Makefile
376

    
377
##### External dependencies
378

    
379
$(root)/%: _always
380
	+$(subMake)
381
.PRECIOUS: $(root)/% # let ext. dir's Makefile decide whether to delete on error
382

    
383
##### Mapping
384

    
385
+maps = $(filter %/map.csv %/VegBIEN.csv $(mappings)/%,$(+_))
386
map2db = env in_database=vegbien in_schema=$(datasrc) in_table=$*\
387
out_database=vegbien $(root)/map $(+maps)
388

    
389
##### Import to VegBIEN
390

    
391
import: $(importTables:%=%/import) _always ;
392

    
393
rm: _always
394
	echo "DELETE FROM source WHERE shortname = '$(datasrc)';"\
395
|"time" $(psqlAsBien)
396

    
397
reimport: _always rm import ;
398

    
399
profileTest = $(if $(profile),$(if $(test),1))
400
profileOnly = -env profile_to=/dev/fd/3 $(map2db) 3>&1 1>&2|\
401
$(bin)/profile_stats /dev/fd/0
402

    
403
log_ = $*/logs/$(if $(n),n=$(n).,)$(version).log.sql
404

    
405
# Displays the import log file path
406
# Run with `make -s` to avoid echoing make commands
407
%/log_file: _always
408
	echo $$(pwd)/$(log_)
409

    
410
trace = $(log_:.log.sql=.trace)
411
import = -$(if $(profileTest),$(profileOnly),(set -x; date; "time" env commit=1\
412
$(if $(profile),profile_to=$(trace)) $(map2db))$(if $(log), >>$(log_) 2>&1))
413
# don't abort on import errors, which often relate to invalid input data
414

    
415
import? = $(if $(call and,$(full_import),$(call dontImport,.)),,$(import))
416

    
417
%/import: %/VegBIEN.csv _always
418
	$(import?)
419
# default:
420
%/import: _always ;
421

    
422
#### Taxonomic scrubbing
423

    
424
scrub: _always
425
	$(selfMake) $(root)/scrub & echo $$!
426

    
427
# Removes TNRS taxondeterminations
428
unscrub: _always
429
	echo "SELECT delete_scrubbed_taxondeterminations('$(datasrc)');"|\
430
"time" env no_query_results=1 $(psqlAsBien)
431

    
432
rescrub: _always unscrub scrub ;
433

    
434
import_scrub: _always import scrub ;
435

    
436
reimport_scrub: _always reimport scrub ;
437

    
438
##### Log files from import
439

    
440
logs := $(wildcard */logs/*.log.sql */logs/*.trace)
441

    
442
rm_logs: _always
443
	$(RM) $(logs)
444

    
445
##### Verification of import
446

    
447
verifyTables := $(patsubst verify/%.ref,%,$(wildcard verify/*.ref))
448

    
449
verify: $(verifyTables:%=%/verify) _always ;
450

    
451
%/verify: verify/%.ref verify/%.out _always
452
	-$(diffVerbose) $(+_)
453
# don't abort on verification errors, which are expected during development
454
# default:
455
%/verify: verify/%.out _always
456
	$(if $(shell test -e $< && echo t),cat $<)
457
# don't run if verify/%.out's default do-nothing action was used
458
# can't use $(wildcard) because it won't recheck file after verify/%.out is run
459

    
460
psqlExport := "time" $(psqlNoSearchPath) --no-align --field-separator=$$'\t'\
461
--pset=footer=off --pset=null=NULL
462
# Note that using $(inDatasrc) will not work with datasources whose tables are
463
# the same name as VegBIEN tables (likely only VegBank), because the datasource
464
# is first in the search_path.
465
verify = $(if $(reverify),($(inDatasrc); cat $<)|$(psqlExport)\
466
--set=datasource="'$(datasrc)'" >$@)
467

    
468
verify/%.out: $(mappings)/verify.%.sql _always
469
	$(verify)
470
.PRECIOUS: verify/%.out # save partial output in case of error to help debugging
471
# default:
472
verify/%.out: _always ;
473

    
474
all += $(wildcard verify/*.out)
475

    
476
%.ref: %.ref.sql
477
	($(inDatasrc); cat $<)|$(psqlExport) >$@
478
.PRECIOUS: %.ref # there must always be a .ref for the make rules to work
479

    
480
##### Editing import
481

    
482
rename/%: _always
483
	echo "UPDATE source SET shortname = '$*' WHERE shortname = '$(datasrc)';"\
484
|$(psqlAsBien)
485

    
486
##### Testing
487

    
488
testRefOutput = $(subst .by_col,,$(1))
489
testRef = $(testRefOutput).ref
490
hasOwnRef = $(filter $@,$(call testRefOutput,$@))
491
# filter returns non-empty if they are equal
492

    
493
# `rm $@`: Remove outputs of successful tests to reduce clutter
494
# `$(foreach use_staged...)`: Run with use_staged=1
495
define runTest
496
@echo "Testing $(abspath $@)..."
497
>$@ env test=1 n=$(test_n) $(1) $(foreach use_staged,1,$(map2db))
498
$(if $(hasOwnRef),,-)@(set -x; $(diffIgnoreSpace) $(call testRef,$@) $@) 2>&1\
499
&& rm $@ || { e=$$?; $(if $(wildcard $(call testRef,$@)),,cat $@;)\
500
$(if $(hasOwnRef),\
501
{\
502
read -p $(emph)'Accept new test output? (y/n)'$(endEmph) REPLY;\
503
if test "$$REPLY" = y; then\
504
(set -x; $(MAKE) $@-ok --directory=$(realpath .) --makefile=../input.Makefile);\
505
exit 0;\
506
fi;\
507
};,\
508
echo $(emph)"Note: The preceding failed test is compared to another test's\
509
output"$(endEmph);\
510
echo $(emph)"When it fails, this always indicates a bug"$(endEmph);\
511
)\
512
exit $$e;}
513
endef
514

    
515
tests :=
516

    
517
%/test: %/test.xml _always ;
518

    
519
# Requires staging tables. To create them, run `make inputs/<datasrc>/install`.
520
# Non-flat-file inputs fall back to mimicking a successful test
521
%/test.xml: %/VegBIEN.csv _always
522
	$(if $(nonXml),$(call runTest,by_col=))
523
tests += %/test.xml
524

    
525
%/test.by_col.xml: %/VegBIEN.csv _always
526
	$(if $(nonXml),$(call runTest,by_col=1))
527

    
528
# Only run column-based tests if column-based mode enabled, because these tests
529
# are much slower than the row-based tests for small numbers of rows
530
ifneq ($(by_col),)
531
tests += %/test.by_col.xml
532
endif
533

    
534
testOutputs := $(foreach test,$(tests),$(importTables:%=$(test)))
535

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

    
538
test: _always $(testOutputs) ;
539

    
540
all += $(wildcard %/test*.xml)
541

    
542
# Accepts a test output: make <test_output_path>-ok
543
%-ok: _always
544
	mv $* $(call testRef,$*)
545

    
546
accept-all: _always
547
	+yes|$(selfMake) test
548

    
549
##### Documentation
550

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

    
554
%/logs/steps.by_col.log.sql: _always
555
	+$(steps)
(9-9/9)