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
profile ?=
13
quiet ?=
14
reverify ?= 1
15
schema_only ?=
16
use_staged ?= $(by_col)
17

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

    
22
##### Vars/functions
23

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

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

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

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

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

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

    
62
##### Environment
63

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

    
66
##### General targets
67

    
68
all: _always maps ;
69

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

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

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

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

    
85
%/: % _always ;
86

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

    
91
##### Tables discovery
92

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

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

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

    
114
##### SVN
115

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

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

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

    
138
##### Existing maps discovery
139

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

    
142
exts := $(call ci,$(exts))
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.vocab.csv
152
thesaurus := $(mappings)/VegCore.thesaurus.csv
153
coreMap := $(mappings)/VegCore-VegBIEN.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) $(nonHeaderSrcs)
172
withCatSrcs = $(catSrcs:$(bin)/%=$(bin)/with_%) --
173

    
174
# Run with `make -s` to avoid echoing 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) $(filter-out Source,$(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
log_dir = $(1)logs
233
has_log_dir = $(wildcard $(log_dir))
234
logInstall = $(if $(has_log_dir),$(if $(quiet),$(2)$(1)$(installLog)\
235
2>&1,2>&1|tee $(3) $(1)$(installLog)))
236
logInstallRoot = $(call logInstall,,>)
237
logInstall* = $(call logInstall,$*/,>)
238
logInstall*Add = $(call logInstall,$*/,>>,-a)# append to log
239

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

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

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

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

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

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

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

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

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

    
291
%/uninstall: _always
292
	echo 'DROP TABLE IF EXISTS "$(datasrc)"."$*" CASCADE;'|$(psqlNoSearchPath)
293

    
294
%/reinstall: _always %/uninstall %/install ;
295

    
296
postprocess: _always $(allTables:%=%/postprocess) ;
297

    
298
cleanup: _always $(tables:%=%/cleanup) ;
299

    
300
# WARNING: This removes any index comments, due to a PostgreSQL bug.
301
# This occurs because ALTER TABLE recreates the index but not its comment.
302
%/cleanup: _always
303
	$(cleanup)
304

    
305
##### Maps building
306

    
307
# Maps to (try to) build are added to this
308
maps :=
309

    
310
srcRoot = $(mappings)/root.sh
311
mkSrcMap = (. $(srcRoot); env datasrc=$(datasrc) $(bin)/src_map <$*/header.csv\
312
>$@)
313

    
314
translate = $(if $(wildcard $(1)),$(bin)/in_place $< $(bin)/translate_ci 1 $(1))
315

    
316
$(srcDict):# empty target in case it doesn't exist
317

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

    
339
%/VegBIEN.csv: %/map.csv $(coreMap)
340
	<$< $(bin)/cat_cols 1 2|$(bin)/join $(coreMap)|$(bin)/sort_map >$@
341
maps += $(autogenMaps)
342

    
343
maps: $(maps) _always ;
344

    
345
all += $(maps)
346

    
347
##### Maps validation
348

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

    
352
%/unmapped_terms.csv: %/map.csv $(coreMap)
353
	tail -n +2 $<|$(bin)/cols 1|$(bin)/filter_out_ci 0 $(coreMap) >$@
354
	$(bin)/autoremove $@
355

    
356
%/new_terms.csv: %/map.csv $(vocab) $(thesaurus) %/unmapped_terms.csv
357
	$(newTerms)
358
	$(bin)/autoremove $@
359
newTerms = tail -n +2 $<|$(bin)/filter_out_ci 0 $(vocab)|$(bin)/filter_out_ci 0\
360
$(thesaurus) $(if $(wildcard $(word 4,$+)),|$(bin)/filter_out_ci 0 $(word 4,$+))\
361
|grep -vE -e '^"?:' -e 'UNUSED' >$@; exit 0 # grep exits nonzero if no match
362

    
363
termsSubdirs := $(importTables)
364

    
365
include $(root)/lib/mappings.Makefile
366

    
367
##### External dependencies
368

    
369
$(root)/%: _always
370
	+$(subMake)
371
.PRECIOUS: $(root)/% # let ext. dir's Makefile decide whether to delete on error
372

    
373
##### Mapping
374

    
375
+maps = $(filter %/map.csv %/VegBIEN.csv $(mappings)/%,$(+_))
376
map2db = env in_database=vegbien in_schema=$(datasrc) in_table=$*\
377
out_database=vegbien $(root)/map $(+maps)
378

    
379
##### Import to VegBIEN
380

    
381
import: $(importTables:%=%/import) _always ;
382

    
383
rm: _always
384
	echo "DELETE FROM source WHERE shortname = '$(datasrc)';"\
385
|"time" $(psqlAsBien)
386

    
387
reimport: _always rm import ;
388

    
389
profileTest = $(if $(profile),$(if $(test),1))
390
profileOnly = -env profile_to=/dev/fd/3 $(map2db) 3>&1 1>&2|\
391
$(bin)/profile_stats /dev/fd/0
392

    
393
log_ = $*/logs/$(if $(n),n=$(n).,)$(version).log.sql
394

    
395
# Displays the import log file path
396
# Run with `make -s` to avoid echoing make commands
397
%/log_file: _always
398
	echo $$(pwd)/$(log_)
399

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

    
405
import? = $(if $(call and,$(full_import),$(call dontImport,.)),,$(import))
406

    
407
%/import: %/VegBIEN.csv _always
408
	$(import?)
409
# default:
410
%/import: _always ;
411

    
412
#### Taxonomic scrubbing
413

    
414
scrub: _always
415
	$(selfMake) $(root)/scrub & echo $$!
416

    
417
# Removes TNRS taxondeterminations
418
unscrub: _always
419
	echo "SELECT delete_scrubbed_taxondeterminations('$(datasrc)');"|\
420
"time" env no_query_results=1 $(psqlAsBien)
421

    
422
rescrub: _always unscrub scrub ;
423

    
424
import_scrub: _always import scrub ;
425

    
426
reimport_scrub: _always reimport scrub ;
427

    
428
##### Log files from import
429

    
430
logs := $(wildcard */logs/*.log.sql */logs/*.trace)
431

    
432
rm_logs: _always
433
	$(RM) $(logs)
434

    
435
##### Verification of import
436

    
437
verifyTables := $(patsubst verify/%.ref,%,$(wildcard verify/*.ref))
438

    
439
verify: $(verifyTables:%=%/verify) _always ;
440

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

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

    
458
verify/%.out: $(mappings)/verify.%.sql _always
459
	$(verify)
460
.PRECIOUS: verify/%.out # save partial output in case of error to help debugging
461
# default:
462
verify/%.out: _always ;
463

    
464
all += $(wildcard verify/*.out)
465

    
466
%.ref: %.ref.sql
467
	($(inDatasrc); cat $<)|$(psqlExport) >$@
468
.PRECIOUS: %.ref # there must always be a .ref for the make rules to work
469

    
470
##### Editing import
471

    
472
rename/%: _always
473
	echo "UPDATE source SET shortname = '$*' WHERE shortname = '$(datasrc)';"\
474
|$(psqlAsBien)
475

    
476
##### Testing
477

    
478
testRefOutput = $(subst .by_col,,$(1))
479
testRef = $(testRefOutput).ref
480
hasOwnRef = $(filter $@,$(call testRefOutput,$@))
481
# filter returns non-empty if they are equal
482

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

    
505
tests :=
506

    
507
%/test: %/test.xml _always ;
508

    
509
# Requires staging tables. To create them, run `make inputs/<datasrc>/install`.
510
# Non-flat-file inputs fall back to mimicking a successful test
511
%/test.xml: %/VegBIEN.csv _always
512
	$(if $(nonXml),$(call runTest,by_col=))
513
tests += %/test.xml
514

    
515
%/test.by_col.xml: %/VegBIEN.csv _always
516
	$(if $(nonXml),$(call runTest,by_col=1))
517

    
518
# Only run column-based tests if column-based mode enabled, because these tests
519
# are much slower than the row-based tests for small numbers of rows
520
ifneq ($(by_col),)
521
tests += %/test.by_col.xml
522
endif
523

    
524
testOutputs := $(foreach test,$(tests),$(importTables:%=$(test)))
525

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

    
528
test: _always $(testOutputs) ;
529

    
530
all += $(wildcard %/test*.xml)
531

    
532
# Accepts a test output: make <test_output_path>-ok
533
%-ok: _always
534
	mv $* $(call testRef,$*)
535

    
536
accept-all: _always
537
	+yes|$(selfMake) test
538

    
539
##### Documentation
540

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

    
544
%/logs/steps.by_col.log.sql: _always
545
	+$(steps)
(5-5/5)