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
esc := '['
38
reset := $(esc)'0m'
39
emph := $(esc)'7m '
40
endEmph := ' '$(reset)
41

    
42
# User interaction
43

    
44
confirm = $(if $(shell read -p $(emph)"$(1)"$(endEmph)$$'$(if\
45
$(2),\n$(2))\nContinue? (y/n) ' REPLY; test "$$REPLY" = y && echo t),,\
46
$(error Aborting))
47

    
48
# Commands
49
MKDIR = mkdir -p
50
mkdir = $(MKDIR) $(@D)
51
CP = cp -p
52
diff = diff --unified=2
53
diffIgnoreSpace = $(diff) --ignore-space-change
54
diffVerbose = $(if $(verbose),diff --side-by-side --left-column\
55
--width=$(termCols),$(diff))
56

    
57
# BIEN commands
58
sortFilenames = $(shell $(bin)/sort_filenames $(1))
59
selfMap = $(bin)/cols 0 0
60
psqlAsBien := $(bin)/psql_script_vegbien
61
psqlNoSearchPath := env no_search_path=1 $(psqlAsBien)
62
# Usage: ($(inDatasrc); cat $(file))|$(psqlCmd)
63
inDatasrc := echo 'SET search_path TO "$(datasrc)";'
64

    
65
# SVN
66
addDir = $(if $(wildcard $(1)/),svn add --depth=empty $(1),svn mkdir $(1))
67
setSvnIgnore = svn propset svn:ignore $(2) $(1)
68
define addDirWithIgnore
69
$(addDir)
70
$(setSvnIgnore)
71
endef
72

    
73
##### Environment
74

    
75
export PATH := $(bin):$(PATH)
76

    
77
##### General targets
78

    
79
all: _always maps ;
80

    
81
clean: _always
82
	$(RM) $(all)
83

    
84
remake: _always clean
85
	+$(selfMake)
86
# re-run make so that cache of existing files is reset
87

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

    
94
%/: % _always ;
95

    
96
%: %.make
97
	$(make_script)
98
.PRECIOUS: % # save partial outputs of aborted src make scripts
99

    
100
##### Tables discovery
101

    
102
sortFile := import_order.txt
103
noImportFile := _no_import
104

    
105
dontImport = $(wildcard $(1)/$(noImportFile))$(if\
106
$(import_source),,$(filter Source,$(1)))
107

    
108
tables := $(if $(wildcard $(sortFile)),$(shell cat $(sortFile)))
109
    # $(shell) replaces "\n" with " "
110
allSubdirs := $(call wildcard/,*/)
111
allTables := $(call sortFilenames,$(filter-out _% verify logs,$(allSubdirs:%/=%)))
112
joinedTables := $(filter-out $(tables),$(allTables))
113
allTables := $(strip $(joinedTables) $(tables))# move joined tables to beginning
114
ifeq ($(tables),)# none specified in sort file
115
tables := $(allTables)
116
endif
117
importTables := $(foreach table,$(tables),$(if\
118
$(call dontImport,$(table)),,$(table)))
119

    
120
##### SVN
121

    
122
svnFilesGlob:= */{,$(noImportFile),{,.}{map,*terms,VegBIEN}.csv{,.*},*header.*,*.sql,test.xml.ref}
123
svnFilesGlob := {map.csv,*{schema,~}*.sql,{,*/}*.make,$(svnFilesGlob)}
124
_svnFilesGlob := {_MySQL/{,*schema*.sql,*.make},_src/*.{url,pdf}}
125
svnFiles = $(filter-out _% logs/%,$(call wildcard/,$(svnFilesGlob)))\
126
$(call wildcard/,$(_svnFilesGlob))
127

    
128
add: _always Source/add Source/map.csv $(allTables:%=%/add)
129
	$(call setSvnIgnore,.,'*')
130
	$(call addDirWithIgnore,logs,$$'*.log.sql\n*.trace')
131
	$(call addDirWithIgnore,verify,$$'*.out\n*.csv\n*.xls')
132
	$(call addFile,import_order.txt)
133
	$(if $(wildcard _MySQL/),$(call addDirWithIgnore,_MySQL,'*'))
134
	$(if $(wildcard _src/),$(call addDirWithIgnore,_src,'*'))
135
	$(call add*,$(svnFiles))
136

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

    
142
##### Existing maps discovery
143

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

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

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

    
152
srcDict := map.csv
153

    
154
vocab := $(mappings)/VegCore.csv
155
coreMap := $(mappings)/VegCore-VegBIEN.csv
156
dict := $(mappings)/Veg+-VegCore.csv
157

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

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

    
164
##### Sources
165

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

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

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

    
183
##### Input data retrieval
184

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

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

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

    
201
##### Staging tables installation
202

    
203
srcTable := %.src
204

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

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

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

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

    
220
reinstall: _always uninstall install ;
221

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

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

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

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

    
235
logInstall = $(if $(log),$(if $(quiet),$(2)$(1)$(installLog) 2>&1,2>&1|tee $(3)\
236
$(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" $(psqlNoSearchPath) \
244
--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
(prefix=; . $(bin)/vegbien_dest; unset schemas; env schema=$(datasrc) table=$*\
249
$(bin)/csv2db) $(logInstall*Add))
250

    
251
define exportHeader
252
$(cleanup)
253
echo 'SELECT * FROM "$(datasrc)"."$*" LIMIT 0;'|$(psqlNoSearchPath) \
254
--no-align --field-separator=, --pset=footer=off >$*/header.csv
255
endef
256

    
257
# For staging tables which are derived by joining together other staging tables.
258
%/install %/header.csv: %/create.sql _always
259
	($(inDatasrc); echo 'CREATE TABLE "$*" AS'; cat $<; echo ';')|"time" \
260
$(psqlNoSearchPath) --echo-all --set=schema='"$(datasrc)"' --set=table='"$*"' \
261
$(logInstall*)
262
	$(exportHeader)
263
.PRECIOUS: %/header.csv
264

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

    
278
%/uninstall: _always
279
	echo 'DROP TABLE IF EXISTS "$(datasrc)"."$*" CASCADE;'|$(psqlNoSearchPath)
280

    
281
%/reinstall: _always %/uninstall %/install ;
282

    
283
cleanup: _always $(tables:%=%/cleanup) ;
284

    
285
# WARNING: This removes any index comments, due to a PostgreSQL bug.
286
# This occurs because ALTER TABLE recreates the index but not its comment.
287
%/cleanup: _always
288
	$(cleanup)
289

    
290
##### Maps building
291

    
292
# WARNING: You CANNOT make a subdir using `make inputs/<datasrc>/<subdir>/`.
293
# You must instead make the entire datasource dir: `make inputs/<datasrc>/`
294

    
295
# Maps to (try to) build are added to this
296
maps :=
297

    
298
srcRoot = $(mappings)/root.sh
299
mkSrcMap = $(catSrcs)|(. $(srcRoot); env datasrc=$(datasrc) $(bin)/src_map >$@)
300

    
301
define translate
302
$(bin)/in_place $< $(bin)/canon 1 $(1)
303
$(bin)/in_place $< $(bin)/translate 1 $(1)
304
endef
305
translate? = $(if $(wildcard $(1)),$(translate))
306

    
307
$(srcDict):# empty target in case it doesn't exist
308

    
309
# Via maps cleanup
310
ifneq ($(filter %/.map.csv.last_cleanup,$(MAKECMDGOALS)),)
311
%/.map.csv.last_cleanup: %/map.csv $(vocab) $(dict) $(coreMap) $(srcDict)
312
	$(call translate?,$(srcDict))
313
	$(bin)/in_place $< $(bin)/canon 1 $(vocab)
314
	$(call translate?,$(dict))
315
	touch $@
316
	+$(selfMake) $(<:%/map.csv=%/unmapped_terms.csv)
317
	+$(selfMake) $(<:%/map.csv=%/new_terms.csv)
318
.PRECIOUS: %/.map.csv.last_cleanup
319
else
320
%/map.csv: _always
321
	$(if $(wildcard $@),,$(if $(nonXml),$(mkSrcMap)))
322
	+$(selfMake) $(@:%/map.csv=%/.map.csv.last_cleanup)
323
.PRECIOUS: %/map.csv
324
endif
325

    
326
%/VegBIEN.csv: %/map.csv $(coreMap)
327
	<$< $(bin)/cat_cols 1 2|$(bin)/join $(coreMap)|$(bin)/sort_map >$@
328
maps += $(autogenMaps)
329

    
330
maps: $(maps) _always ;
331

    
332
all += $(maps)
333

    
334
##### Maps validation
335

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

    
339
%/unmapped_terms.csv: %/map.csv $(coreMap)
340
	tail -n +2 $<|$(bin)/cols 1|$(bin)/filter_out_ci 0 $(coreMap) >$@
341
	$(bin)/autoremove $@
342

    
343
%/new_terms.csv: %/map.csv $(vocab) $(dict) %/unmapped_terms.csv
344
	$(newTerms)
345
	$(bin)/autoremove $@
346
newTerms = tail -n +2 $<|$(bin)/filter_out_ci 0 $(vocab)|$(bin)/filter_out_ci 0\
347
$(dict) $(if $(wildcard $(word 4,$+)),|$(bin)/filter_out_ci 0 $(word 4,$+))\
348
|grep -vE '^"?:' >$@; exit 0# because grep exits nonzero if no match
349

    
350
termsSubdirs := $(importTables)
351

    
352
include $(root)/lib/mappings.Makefile
353

    
354
##### External dependencies
355

    
356
$(root)/%: _always
357
	+$(subMake)
358
.PRECIOUS: $(root)/% # let ext. dir's Makefile decide whether to delete on error
359

    
360
##### Mapping
361

    
362
+maps = $(filter %/map.csv %/VegBIEN.csv $(mappings)/%,$(+_))
363
map2db = env in_database=vegbien in_schema=$(datasrc) in_table=$*\
364
out_database=vegbien $(root)/map $(+maps)
365

    
366
##### Import to VegBIEN
367

    
368
profileTest = $(if $(profile),$(if $(test),1))
369
profileOnly = -env profile_to=/dev/fd/3 $(map2db) 3>&1 1>&2|\
370
$(bin)/profile_stats /dev/fd/0
371

    
372
log_ = $*/logs/$(if $(n),n=$(n).,)$(version).log.sql
373
trace = $(log_:.log.sql=.trace)
374
import = -$(if $(profileTest),$(profileOnly),(set -x; "time" env commit=1\
375
$(if $(profile),profile_to=$(trace)) $(map2db)) $(if $(log),\
376
$(if $(n),,&>$(log_)))$(if $(log),$(if $(n), 2>&1|tee -a $(log_))))
377
# don't abort on import errors, which often relate to invalid input data
378

    
379
import: $(importTables:%=%/import) _always ;
380

    
381
%/import: %/VegBIEN.csv _always
382
	$(import)
383
# default:
384
%/import: _always ;
385

    
386
##### Log files from import
387

    
388
logs := $(wildcard */logs/*.log.sql */logs/*.trace)
389

    
390
rm_logs: _always
391
	$(RM) $(logs)
392

    
393
##### Verification of import
394

    
395
verifyTables := $(patsubst verify/%.ref,%,$(wildcard verify/*.ref))
396

    
397
verify: $(verifyTables:%=%/verify) _always ;
398

    
399
%/verify: verify/%.ref verify/%.out _always
400
	-$(diffVerbose) $(+_)
401
# don't abort on verification errors, which are expected during development
402
# default:
403
%/verify: verify/%.out _always
404
	$(if $(shell test -e $< && echo t),cat $<)
405
# don't run if verify/%.out's default do-nothing action was used
406
# can't use $(wildcard) because it won't recheck file after verify/%.out is run
407

    
408
psqlExport := "time" $(psqlNoSearchPath) --no-align --field-separator=$$'\t'\
409
--pset=footer=off --pset=null=NULL
410
# Note that using $(inDatasrc) will not work with datasources whose tables are
411
# the same name as VegBIEN tables (likely only VegBank), because the datasource
412
# is first in the search_path.
413
verify = $(if $(reverify),($(inDatasrc); cat $<)|$(psqlExport)\
414
--set=datasource="'$(datasrc)'" >$@)
415

    
416
verify/%.out: $(mappings)/verify.%.sql _always
417
	$(verify)
418
.PRECIOUS: verify/%.out # save partial output in case of error to help debugging
419
# default:
420
verify/%.out: _always ;
421

    
422
all += $(wildcard verify/*.out)
423

    
424
%.ref: %.ref.sql
425
	($(inDatasrc); cat $<)|$(psqlExport) >$@
426
.PRECIOUS: %.ref # there must always be a .ref for the make rules to work
427

    
428
##### Editing import
429

    
430
rotate: _always
431
	echo "UPDATE source SET shortname = shortname||'.$(version)'\
432
WHERE shortname = '$(datasrc)';"|$(psqlAsBien)
433

    
434
rm: _always
435
	echo "DELETE FROM source WHERE shortname = '$(datasrc)';"|$(psqlAsBien)
436

    
437
##### Testing
438

    
439
testRefOutput = $(subst .by_col,,$(1))
440
testRef = $(testRefOutput).ref
441
hasOwnRef = $(filter $@,$(call testRefOutput,$@))
442
# filter returns non-empty if they are equal
443

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

    
466
tests :=
467

    
468
# Requires staging tables. To create them, run `make inputs/<datasrc>/install`.
469
# Non-flat-file inputs fall back to mimicking a successful test
470
%/test.xml: %/VegBIEN.csv _always
471
	$(if $(nonXml),$(call runTest,by_col=))
472
tests += %/test.xml
473

    
474
%/test.by_col.xml: %/VegBIEN.csv _always
475
	$(if $(nonXml),$(call runTest,by_col=1))
476

    
477
# Only run column-based tests if column-based mode enabled, because these tests
478
# are much slower than the row-based tests for small numbers of rows
479
ifneq ($(by_col),)
480
tests += %/test.by_col.xml
481
endif
482

    
483
testOutputs := $(foreach test,$(tests),$(importTables:%=$(test)))
484

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

    
487
test: _always $(testOutputs) ;
488

    
489
all += $(wildcard %/test*.xml)
490

    
491
# Accepts a test output: make <test_output_path>-ok
492
%-ok: _always
493
	mv $* $(call testRef,$*)
494

    
495
accept-all: _always
496
	+yes|$(selfMake) test
497

    
498
##### Documentation
499

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

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