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

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

    
20
##### Vars/functions
21

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

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

    
34
# Terminal
35
termCols := $(shell tput cols)
36
esc := '['
37
reset := $(esc)'0m'
38
emph := $(esc)'7m '
39
endEmph := ' '$(reset)
40

    
41
# User interaction
42

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

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

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

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

    
72
##### Environment
73

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

    
76
##### General targets
77

    
78
all: _always maps ;
79

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

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

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

    
93
%/: % _always ;
94

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

    
99
##### Tables discovery
100

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

    
104
dontImport = $(wildcard $(1)/$(noImportFile))
105

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

    
118
##### SVN
119

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

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

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

    
140
##### Existing maps discovery
141

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

    
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.csv
153
coreMap := $(mappings)/VegCore-VegBIEN.csv
154
dict := $(mappings)/Veg+-VegCore.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) $(srcs)
173
withCatSrcs = $(catSrcs:$(bin)/%=$(bin)/with_%) --
174

    
175
# Usage: `make {--silent|-s} inputs/<datasrc>/cat` (don't echo 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) $(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
logInstall = $(if $(log),$(if $(quiet),$(2)$(1)$(installLog) 2>&1,2>&1|tee $(3)\
234
$(1)$(installLog)))
235
logInstallRoot = $(call logInstall,,>)
236
logInstall* = $(call logInstall,$*/,>)
237
logInstall*Add = $(call logInstall,$*/,>>,-a)# append to log
238

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

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

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

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

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

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

    
279
%/reinstall: _always %/uninstall %/install ;
280

    
281
cleanup: _always $(tables:%=%/cleanup) ;
282

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

    
288
##### Maps building
289

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

    
293
# Maps to (try to) build are added to this
294
maps :=
295

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

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

    
305
$(srcDict):# empty target in case it doesn't exist
306

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

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

    
328
maps: $(maps) _always ;
329

    
330
all += $(maps)
331

    
332
##### Maps validation
333

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

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

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

    
348
termsSubdirs := $(importTables)
349

    
350
include $(root)/lib/mappings.Makefile
351

    
352
##### External dependencies
353

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

    
358
##### Mapping
359

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

    
364
##### Import to VegBIEN
365

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

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

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

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

    
384
##### Log files from import
385

    
386
logs := $(wildcard */logs/*.log.sql */logs/*.trace)
387

    
388
rm_logs: _always
389
	$(RM) $(logs)
390

    
391
##### Verification of import
392

    
393
verifyTables := $(patsubst verify/%.ref,%,$(wildcard verify/*.ref))
394

    
395
verify: $(verifyTables:%=%/verify) _always ;
396

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

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

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

    
420
all += $(wildcard verify/*.out)
421

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

    
426
##### Editing import
427

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

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

    
435
##### Testing
436

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

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

    
464
tests :=
465

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

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

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

    
481
testOutputs := $(foreach test,$(tests),$(importTables:%=$(test)))
482

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

    
485
test: _always $(testOutputs) ;
486

    
487
all += $(wildcard %/test*.xml)
488

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

    
493
accept-all: _always
494
	+yes|$(selfMake) test
495

    
496
##### Documentation
497

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

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