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
ifeq ($(tables),)# none specified in sort file
106
tables := $(allTables)
107
endif
108
importTables := $(foreach table,$(tables),$(if\
109
$(call dontImport,$(table)),,$(table)))
110

    
111
##### SVN
112

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

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

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

    
135
##### Existing maps discovery
136

    
137
anyMap := %/map.csv %/VegBIEN.csv %/unmapped_terms.csv %/new_terms.csv
138

    
139
exts := $(call ci,$(exts))
140
extsFilter := $(addprefix %.,$(exts))
141
dataOnly = $(filter $(extsFilter),$(1))
142

    
143
anyTest = $*/test.%
144
srcsOnly = $(filter-out $(anyMap) $(anyTest) %/logs,$(call dataOnly,$(1)))
145

    
146
srcDict := map.csv
147

    
148
vocab := $(mappings)/VegCore.vocab.csv
149
thesaurus := $(mappings)/VegCore.thesaurus.csv
150
coreMap := $(mappings)/VegCore-VegBIEN.csv
151

    
152
viaMaps := $(importTables:%=%/map.csv)
153

    
154
autogenMaps := $(subst map.,VegBIEN.,$(viaMaps))
155
directMaps := $(autogenMaps) $(filter-out $(autogenMaps),\
156
$(wildcard */VegBIEN.csv))
157

    
158
##### Sources
159

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

    
171
# Run with `make -s` to avoid echoing make commands
172
cat: $(importTables:%=%/cat) _always ;
173

    
174
%/cat: _always
175
	$(catSrcs)
176

    
177
##### Input data retrieval
178

    
179
# Must come before `%.sql: _MySQL/%.sql` to override it
180
%.sql: %.sql.make
181
	$(make_script)
182

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

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

    
195
##### Staging tables installation
196

    
197
srcTable := %.src
198

    
199
dbExportsWildcard = $(sort $(patsubst _MySQL/%.make,%,$(wildcard\
200
$(1) _MySQL/$(1).make)))
201

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

    
209
install: _always schema $(allInstalls:%=%/install) ;
210

    
211
uninstall: _always confirm_rm_schema rm_schema ;
212
# rm_schema will also drop all staging tables
213

    
214
reinstall: _always uninstall install ;
215

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

    
220
schema: _always
221
	-echo 'CREATE SCHEMA "$(datasrc)";'|$(psqlNoSearchPath)
222
# ignore errors if schema exists
223

    
224
rm_schema: _always
225
	echo 'DROP SCHEMA IF EXISTS "$(datasrc)" CASCADE;'|$(psqlNoSearchPath)
226

    
227
installLog := logs/install.log.sql
228

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

    
235
# Must come before %/install to override it
236
sql/install: $(dbExports)
237
	($(inDatasrc); cat $+|pg_dump_limit)|"time" $(bin)/psql_script_vegbien \
238
--set=schema='"$(datasrc)"' $(logInstallRoot)
239

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

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

    
249
exportHeader = $(selfMake) $*/header.csv
250

    
251
# Don't try to edit a view. Must come before %/install to override it.
252
%_view/install: _always ;
253

    
254
%.sql/run: _always
255
	$(if $(wildcard $(@D)),($(inDatasrc); cat $(@D))|(cd '$(*D)';\
256
"time" env no_search_path=1 ../$(bin)/psql_verbose_vegbien \
257
--set=table='"$(*D)"' --set=table_str=\''"$(*D)"'\'))
258

    
259
%/postprocess: _always %/postprocess.sql/run
260
	$(if $(wildcard $*/import),$*/import)
261

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

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

    
286
%/uninstall: _always
287
	echo 'DROP TABLE IF EXISTS "$(datasrc)"."$*" CASCADE;'|$(psqlNoSearchPath)
288

    
289
%/reinstall: _always %/uninstall %/install ;
290

    
291
postprocess: _always $(allTables:%=%/postprocess) ;
292

    
293
cleanup: _always $(tables:%=%/cleanup) ;
294

    
295
# WARNING: This removes any index comments, due to a PostgreSQL bug.
296
# This occurs because ALTER TABLE recreates the index but not its comment.
297
%/cleanup: _always
298
	$(cleanup)
299

    
300
##### Maps building
301

    
302
# Maps to (try to) build are added to this
303
maps :=
304

    
305
srcRoot = $(mappings)/root.sh
306
mkSrcMap = (. $(srcRoot); env datasrc=$(datasrc) $(bin)/src_map <$*/header.csv\
307
>$@)
308

    
309
translate = $(if $(wildcard $(1)),$(bin)/in_place $< $(bin)/translate_ci 1 $(1))
310

    
311
$(srcDict):# empty target in case it doesn't exist
312

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

    
335
%/VegBIEN.csv: %/map.csv $(coreMap)
336
	<$< $(bin)/cat_cols 1 2|$(bin)/join $(coreMap)|$(bin)/sort_map >$@
337
maps += $(autogenMaps)
338

    
339
maps: $(maps) _always ;
340

    
341
all += $(maps)
342

    
343
##### Maps validation
344

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

    
348
%/unmapped_terms.csv: %/map.csv $(coreMap)
349
	tail -n +2 $<|$(bin)/cols 1|$(bin)/filter_out_ci 0 $(coreMap) >$@
350
	$(bin)/autoremove $@
351

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

    
359
termsSubdirs := $(importTables)
360

    
361
include $(root)/lib/mappings.Makefile
362

    
363
##### External dependencies
364

    
365
$(root)/%: _always
366
	+$(subMake)
367
.PRECIOUS: $(root)/% # let ext. dir's Makefile decide whether to delete on error
368

    
369
##### Mapping
370

    
371
+maps = $(filter %/map.csv %/VegBIEN.csv $(mappings)/%,$(+_))
372
map2db = env in_database=vegbien in_schema=$(datasrc) in_table=$*\
373
out_database=vegbien $(root)/map $(+maps)
374

    
375
##### Import to VegBIEN
376

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

    
379
rm: _always
380
	echo "DELETE FROM source WHERE shortname = '$(datasrc)';"\
381
|"time" $(psqlAsBien)
382

    
383
reimport: _always rm import ;
384

    
385
profileTest = $(if $(profile),$(if $(test),1))
386
profileOnly = -env profile_to=/dev/fd/3 $(map2db) 3>&1 1>&2|\
387
$(bin)/profile_stats /dev/fd/0
388

    
389
log_ = $*/logs/$(if $(n),n=$(n).,)$(version).log.sql
390

    
391
# Displays the import log file path
392
# Run with `make -s` to avoid echoing make commands
393
%/log_file: _always
394
	echo $$(pwd)/$(log_)
395

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

    
401
import? = $(if $(call and,$(full_import),$(call dontImport,.)),,$(import))
402

    
403
%/import: %/VegBIEN.csv _always
404
	$(import?)
405
# default:
406
%/import: _always ;
407

    
408
#### Taxonomic scrubbing
409

    
410
scrub: _always
411
	$(selfMake) $(root)/scrub & echo $$!
412

    
413
# Removes TNRS taxondeterminations
414
unscrub: _always
415
	echo "SELECT delete_scrubbed_taxondeterminations('$(datasrc)');"|\
416
"time" env no_query_results=1 $(psqlAsBien)
417

    
418
rescrub: _always unscrub scrub ;
419

    
420
import_scrub: _always import scrub ;
421

    
422
reimport_scrub: _always reimport scrub ;
423

    
424
##### Log files from import
425

    
426
logs := $(wildcard */logs/*.log.sql */logs/*.trace)
427

    
428
rm_logs: _always
429
	$(RM) $(logs)
430

    
431
##### Verification of import
432

    
433
verifyTables := $(patsubst verify/%.ref,%,$(wildcard verify/*.ref))
434

    
435
verify: $(verifyTables:%=%/verify) _always ;
436

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

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

    
454
verify/%.out: $(mappings)/verify.%.sql _always
455
	$(verify)
456
.PRECIOUS: verify/%.out # save partial output in case of error to help debugging
457
# default:
458
verify/%.out: _always ;
459

    
460
all += $(wildcard verify/*.out)
461

    
462
%.ref: %.ref.sql
463
	($(inDatasrc); cat $<)|$(psqlExport) >$@
464
.PRECIOUS: %.ref # there must always be a .ref for the make rules to work
465

    
466
##### Editing import
467

    
468
rename/%: _always
469
	echo "UPDATE source SET shortname = '$*' WHERE shortname = '$(datasrc)';"\
470
|$(psqlAsBien)
471

    
472
##### Testing
473

    
474
testRefOutput = $(subst .by_col,,$(1))
475
testRef = $(testRefOutput).ref
476
hasOwnRef = $(filter $@,$(call testRefOutput,$@))
477
# filter returns non-empty if they are equal
478

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

    
501
tests :=
502

    
503
%/test: %/test.xml _always ;
504

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

    
511
%/test.by_col.xml: %/VegBIEN.csv _always
512
	$(if $(nonXml),$(call runTest,by_col=1))
513

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

    
520
testOutputs := $(foreach test,$(tests),$(importTables:%=$(test)))
521

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

    
524
test: _always $(testOutputs) ;
525

    
526
all += $(wildcard %/test*.xml)
527

    
528
# Accepts a test output: make <test_output_path>-ok
529
%-ok: _always
530
	mv $* $(call testRef,$*)
531

    
532
accept-all: _always
533
	+yes|$(selfMake) test
534

    
535
##### Documentation
536

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

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