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

    
17
# Makefile
18
exts ?= csv tsv txt dmp xml
19
test_n ?= 2
20

    
21
##### Vars/functions
22

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

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

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

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

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

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

    
61
##### Environment
62

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

    
65
##### General targets
66

    
67
all: _always maps ;
68

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

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

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

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

    
84
%/: % _always ;
85

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

    
90
##### Tables discovery
91

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

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

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

    
110
##### SVN
111

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

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

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

    
134
##### Existing maps discovery
135

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

    
138
extsFilter := $(addprefix %.,$(exts))
139
dataOnly = $(filter $(extsFilter),$(1))
140

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

    
144
srcDict := map.csv
145

    
146
vocab := $(mappings)/VegCore.csv
147
coreMap := $(mappings)/VegCore-VegBIEN.csv
148
dict := $(mappings)/Veg+-VegCore.csv
149

    
150
viaMaps := $(importTables:%=%/map.csv)
151

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

    
156
##### Sources
157

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

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

    
172
%/cat: _always
173
	$(catSrcs)
174

    
175
##### Input data retrieval
176

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

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

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

    
193
##### Staging tables installation
194

    
195
srcTable := %.src
196

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

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

    
207
install: _always schema $(allInstalls:%=%/install) ;
208

    
209
uninstall: _always confirm_rm_schema rm_schema ;
210
# rm_schema will also drop all staging tables
211

    
212
reinstall: _always uninstall install ;
213

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

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

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

    
225
installLog := logs/install.log.sql
226

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

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

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

    
243
define exportHeader
244
$(cleanup)
245
echo 'SELECT * FROM "$(datasrc)"."$*" LIMIT 0;'|$(psqlNoSearchPath) \
246
--no-align --field-separator=, --pset=footer=off >$*/header.csv
247
endef
248

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

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

    
270
%/uninstall: _always
271
	echo 'DROP TABLE IF EXISTS "$(datasrc)"."$*" CASCADE;'|$(psqlNoSearchPath)
272

    
273
%/reinstall: _always %/uninstall %/install ;
274

    
275
cleanup: _always $(tables:%=%/cleanup) ;
276

    
277
# WARNING: This removes any index comments, due to a PostgreSQL bug.
278
# This occurs because ALTER TABLE recreates the index but not its comment.
279
%/cleanup: _always
280
	$(cleanup)
281

    
282
##### Maps building
283

    
284
# Maps to (try to) build are added to this
285
maps :=
286

    
287
srcRoot = $(mappings)/root.sh
288
mkSrcMap = $(catSrcs)|(. $(srcRoot); env datasrc=$(datasrc) $(bin)/src_map >$@)
289

    
290
define translate
291
$(bin)/in_place $< $(bin)/canon 1 $(1)
292
$(bin)/in_place $< $(bin)/translate 1 $(1)
293
endef
294
translate? = $(if $(wildcard $(1)),$(translate))
295

    
296
$(srcDict):# empty target in case it doesn't exist
297

    
298
# Via maps cleanup
299
ifneq ($(filter %/.map.csv.last_cleanup,$(MAKECMDGOALS)),)
300
%/.map.csv.last_cleanup: %/map.csv $(vocab) $(dict) $(coreMap) $(srcDict)
301
	$(call translate?,$(srcDict))
302
	$(bin)/in_place $< $(bin)/canon 1 $(vocab)
303
	$(call translate?,$(dict))
304
	touch $@
305
	+$(selfMake) $(<:%/map.csv=%/unmapped_terms.csv)
306
	+$(selfMake) $(<:%/map.csv=%/new_terms.csv)
307
.PRECIOUS: %/.map.csv.last_cleanup
308
else
309
%/map.csv: _always
310
	$(if $(wildcard $@),,$(if $(nonXml),$(mkSrcMap)))
311
	+$(selfMake) $(@:%/map.csv=%/.map.csv.last_cleanup)
312
.PRECIOUS: %/map.csv
313
endif
314

    
315
%/VegBIEN.csv: %/map.csv $(coreMap)
316
	<$< $(bin)/cat_cols 1 2|$(bin)/join $(coreMap)|$(bin)/sort_map >$@
317
maps += $(autogenMaps)
318

    
319
maps: $(maps) _always ;
320

    
321
all += $(maps)
322

    
323
##### Maps validation
324

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

    
328
%/unmapped_terms.csv: %/map.csv $(coreMap)
329
	tail -n +2 $<|$(bin)/cols 1|$(bin)/filter_out_ci 0 $(coreMap) >$@
330
	$(bin)/autoremove $@
331

    
332
%/new_terms.csv: %/map.csv $(vocab) $(dict) %/unmapped_terms.csv
333
	$(newTerms)
334
	$(bin)/autoremove $@
335
newTerms = tail -n +2 $<|$(bin)/filter_out_ci 0 $(vocab)|$(bin)/filter_out_ci 0\
336
$(dict) $(if $(wildcard $(word 4,$+)),|$(bin)/filter_out_ci 0 $(word 4,$+))\
337
|grep -vE '^"?:' >$@; exit 0# because grep exits nonzero if no match
338

    
339
termsSubdirs := $(importTables)
340

    
341
include $(root)/lib/mappings.Makefile
342

    
343
##### External dependencies
344

    
345
$(root)/%: _always
346
	+$(subMake)
347
.PRECIOUS: $(root)/% # let ext. dir's Makefile decide whether to delete on error
348

    
349
##### Mapping
350

    
351
+maps = $(filter %/map.csv %/VegBIEN.csv $(mappings)/%,$(+_))
352
map2db = env in_database=vegbien in_schema=$(datasrc) in_table=$*\
353
out_database=vegbien $(root)/map $(+maps)
354

    
355
##### Import to VegBIEN
356

    
357
profileTest = $(if $(profile),$(if $(test),1))
358
profileOnly = -env profile_to=/dev/fd/3 $(map2db) 3>&1 1>&2|\
359
$(bin)/profile_stats /dev/fd/0
360

    
361
log_ = $*/logs/$(if $(n),n=$(n).,)$(version).log.sql
362
trace = $(log_:.log.sql=.trace)
363
import = -$(if $(profileTest),$(profileOnly),(set -x; "time" env commit=1\
364
$(if $(profile),profile_to=$(trace)) $(map2db)) $(if $(log),\
365
$(if $(n),,&>$(log_)))$(if $(log),$(if $(n), 2>&1|tee -a $(log_))))
366
# don't abort on import errors, which often relate to invalid input data
367

    
368
import: $(importTables:%=%/import) _always ;
369

    
370
%/import: %/VegBIEN.csv _always
371
	$(import)
372
# default:
373
%/import: _always ;
374

    
375
##### Log files from import
376

    
377
logs := $(wildcard */logs/*.log.sql */logs/*.trace)
378

    
379
rm_logs: _always
380
	$(RM) $(logs)
381

    
382
##### Verification of import
383

    
384
verifyTables := $(patsubst verify/%.ref,%,$(wildcard verify/*.ref))
385

    
386
verify: $(verifyTables:%=%/verify) _always ;
387

    
388
%/verify: verify/%.ref verify/%.out _always
389
	-$(diffVerbose) $(+_)
390
# don't abort on verification errors, which are expected during development
391
# default:
392
%/verify: verify/%.out _always
393
	$(if $(shell test -e $< && echo t),cat $<)
394
# don't run if verify/%.out's default do-nothing action was used
395
# can't use $(wildcard) because it won't recheck file after verify/%.out is run
396

    
397
psqlExport := "time" $(psqlNoSearchPath) --no-align --field-separator=$$'\t'\
398
--pset=footer=off --pset=null=NULL
399
# Note that using $(inDatasrc) will not work with datasources whose tables are
400
# the same name as VegBIEN tables (likely only VegBank), because the datasource
401
# is first in the search_path.
402
verify = $(if $(reverify),($(inDatasrc); cat $<)|$(psqlExport)\
403
--set=datasource="'$(datasrc)'" >$@)
404

    
405
verify/%.out: $(mappings)/verify.%.sql _always
406
	$(verify)
407
.PRECIOUS: verify/%.out # save partial output in case of error to help debugging
408
# default:
409
verify/%.out: _always ;
410

    
411
all += $(wildcard verify/*.out)
412

    
413
%.ref: %.ref.sql
414
	($(inDatasrc); cat $<)|$(psqlExport) >$@
415
.PRECIOUS: %.ref # there must always be a .ref for the make rules to work
416

    
417
##### Editing import
418

    
419
rotate: _always
420
	echo "UPDATE source SET shortname = shortname||'.$(version)'\
421
WHERE shortname = '$(datasrc)';"|$(psqlAsBien)
422

    
423
rm: _always
424
	echo "DELETE FROM source WHERE shortname = '$(datasrc)';"|$(psqlAsBien)
425

    
426
##### Testing
427

    
428
testRefOutput = $(subst .by_col,,$(1))
429
testRef = $(testRefOutput).ref
430
hasOwnRef = $(filter $@,$(call testRefOutput,$@))
431
# filter returns non-empty if they are equal
432

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

    
455
tests :=
456

    
457
%/test: %/test.xml _always ;
458

    
459
# Requires staging tables. To create them, run `make inputs/<datasrc>/install`.
460
# Non-flat-file inputs fall back to mimicking a successful test
461
%/test.xml: %/VegBIEN.csv _always
462
	$(if $(nonXml),$(call runTest,by_col=))
463
tests += %/test.xml
464

    
465
%/test.by_col.xml: %/VegBIEN.csv _always
466
	$(if $(nonXml),$(call runTest,by_col=1))
467

    
468
# Only run column-based tests if column-based mode enabled, because these tests
469
# are much slower than the row-based tests for small numbers of rows
470
ifneq ($(by_col),)
471
tests += %/test.by_col.xml
472
endif
473

    
474
testOutputs := $(foreach test,$(tests),$(importTables:%=$(test)))
475

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

    
478
test: _always $(testOutputs) ;
479

    
480
all += $(wildcard %/test*.xml)
481

    
482
# Accepts a test output: make <test_output_path>-ok
483
%-ok: _always
484
	mv $* $(call testRef,$*)
485

    
486
accept-all: _always
487
	+yes|$(selfMake) test
488

    
489
##### Documentation
490

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

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