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
##### SVN
116

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

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

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

    
139
##### Existing maps discovery
140

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

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

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

    
150
srcDict := map.csv
151

    
152
vocab := $(mappings)/VegCore.vocab.csv
153
thesaurus := $(mappings)/VegCore.thesaurus.csv
154
coreMap := $(mappings)/VegCore-VegBIEN.csv
155

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

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

    
162
##### Sources
163

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

    
175
# Run with `make -s` to avoid echoing make commands
176
cat: $(importTables:%=%/cat) _always ;
177

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

    
181
##### Input data retrieval
182

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

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

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

    
199
##### Staging tables installation
200

    
201
srcTable := %.src
202

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

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

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

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

    
218
reinstall: _always uninstall install ;
219

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

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

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

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

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

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

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

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

    
255
exportHeader = $(selfMake) $*/header.csv
256

    
257
# Don't try to edit a view. Must come before %/install to override it.
258
%_view/install: _always ;
259

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

    
265
%/postprocess: _always
266
	$(if $(wildcard $*/run),,$(selfMake) $*/postprocess.sql/run)
267
	$(if $(wildcard $*/import),$*/import)
268

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

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

    
296
%/uninstall: _always
297
	echo 'DROP TABLE IF EXISTS "$(datasrc)"."$*" CASCADE;'|$(psqlNoSearchPath)
298

    
299
%/reinstall: _always %/uninstall %/install ;
300

    
301
postprocess: _always $(allTables:%=%/postprocess) ;
302

    
303
cleanup: _always $(tables:%=%/cleanup) ;
304

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

    
310
##### Maps building
311

    
312
# Maps to (try to) build are added to this
313
maps :=
314

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

    
319
translate = $(if $(wildcard $(1)),$(bin)/in_place $< $(bin)/translate_ci 1 $(1))
320

    
321
$(srcDict):# empty target in case it doesn't exist
322

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

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

    
350
maps: $(maps) _always ;
351

    
352
all += $(maps)
353

    
354
##### Maps validation
355

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

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

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

    
370
termsSubdirs := $(importTables)
371

    
372
include $(root)/lib/mappings.Makefile
373

    
374
##### External dependencies
375

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

    
380
##### Mapping
381

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

    
386
##### Import to VegBIEN
387

    
388
import: $(importTables:%=%/import) _always ;
389

    
390
rm: _always
391
	echo "DELETE FROM source WHERE shortname = '$(datasrc)';"\
392
|"time" $(psqlAsBien)
393

    
394
reimport: _always rm import ;
395

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

    
400
log_ = $*/logs/$(if $(n),n=$(n).,)$(version).log.sql
401

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

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

    
412
import? = $(if $(call and,$(full_import),$(call dontImport,.)),,$(import))
413

    
414
%/import: %/VegBIEN.csv _always
415
	$(import?)
416
# default:
417
%/import: _always ;
418

    
419
#### Taxonomic scrubbing
420

    
421
scrub: _always
422
	$(selfMake) $(root)/scrub & echo $$!
423

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

    
429
rescrub: _always unscrub scrub ;
430

    
431
import_scrub: _always import scrub ;
432

    
433
reimport_scrub: _always reimport scrub ;
434

    
435
##### Log files from import
436

    
437
logs := $(wildcard */logs/*.log.sql */logs/*.trace)
438

    
439
rm_logs: _always
440
	$(RM) $(logs)
441

    
442
##### Verification of import
443

    
444
verifyTables := $(patsubst verify/%.ref,%,$(wildcard verify/*.ref))
445

    
446
verify: $(verifyTables:%=%/verify) _always ;
447

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

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

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

    
471
all += $(wildcard verify/*.out)
472

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

    
477
##### Editing import
478

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

    
483
##### Testing
484

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

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

    
512
tests :=
513

    
514
%/test: %/test.xml _always ;
515

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

    
522
%/test.by_col.xml: %/VegBIEN.csv _always
523
	$(if $(nonXml),$(call runTest,by_col=1))
524

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

    
531
testOutputs := $(foreach test,$(tests),$(importTables:%=$(test)))
532

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

    
535
test: _always $(testOutputs) ;
536

    
537
all += $(wildcard %/test*.xml)
538

    
539
# Accepts a test output: make <test_output_path>-ok
540
%-ok: _always
541
	mv $* $(call testRef,$*)
542

    
543
accept-all: _always
544
	+yes|$(selfMake) test
545

    
546
##### Documentation
547

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

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