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
%/: %/map.csv _always ;
95

    
96
%/: % _always ;
97

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

    
102
##### Tables discovery
103

    
104
sortFile := import_order.txt
105
noImportFile := _no_import
106

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

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

    
122
##### SVN
123

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

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

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

    
145
##### Existing maps discovery
146

    
147
anyMap := %/map.csv %/VegBIEN.csv %/unmapped_terms.csv %/new_terms.csv
148

    
149
extsFilter := $(addprefix %.,$(exts))
150
dataOnly = $(filter $(extsFilter),$(1))
151

    
152
anyTest = $*/test.%
153
srcsOnly = $(filter-out $(anyMap) $(anyTest) %/logs,$(call dataOnly,$(1)))
154

    
155
srcDict := map.csv
156

    
157
vocab := $(mappings)/VegCore.csv
158
coreMap := $(mappings)/VegCore-VegBIEN.csv
159
dict := $(mappings)/Veg+-VegCore.csv
160

    
161
viaMaps := $(importTables:%=%/map.csv)
162

    
163
autogenMaps := $(subst map.,VegBIEN.,$(viaMaps))
164
directMaps := $(autogenMaps) $(filter-out $(autogenMaps),\
165
$(wildcard */VegBIEN.csv))
166

    
167
##### Sources
168

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

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

    
183
%/cat: _always
184
	$(catSrcs)
185

    
186
##### Input data retrieval
187

    
188
# Must come before `%.sql: _MySQL/%.sql` to override it
189
%.sql: %.sql.make
190
	$(make_script)
191

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

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

    
204
##### Staging tables installation
205

    
206
srcTable := %.src
207

    
208
dbExportsWildcard = $(sort $(patsubst _MySQL/%.make,%,$(wildcard\
209
$(1) _MySQL/$(1).make)))
210

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

    
218
install: _always schema $(allInstalls:%=%/install) ;
219

    
220
uninstall: _always confirm_rm_schema rm_schema ;
221
# rm_schema will also drop all staging tables
222

    
223
reinstall: _always uninstall install ;
224

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

    
229
schema: _always
230
	-echo 'CREATE SCHEMA "$(datasrc)";'|$(psqlNoSearchPath)
231
# ignore errors if schema exists
232

    
233
rm_schema: _always
234
	echo 'DROP SCHEMA IF EXISTS "$(datasrc)" CASCADE;'|$(psqlNoSearchPath)
235

    
236
installLog := logs/install.log.sql
237

    
238
logInstall = $(if $(log),$(if $(quiet),$(2)$(1)$(installLog) 2>&1,2>&1|tee $(3)\
239
$(1)$(installLog)))
240
logInstallRoot = $(call logInstall,,>)
241
logInstall* = $(call logInstall,$*/,>)
242
logInstall*Add = $(call logInstall,$*/,>>,-a)# append to log
243

    
244
# Must come before %/install to override it
245
sql/install: $(dbExports)
246
	($(inDatasrc); cat $+|pg_dump_limit)|"time" $(psqlNoSearchPath) \
247
--set=schema='"$(datasrc)"' $(logInstallRoot)
248

    
249
cleanup = $(if $(wildcard $*/cleanup.sql),($(inDatasrc); cat $*/cleanup.sql)\
250
|"time" $(psqlNoSearchPath) --echo-all --set=table='"$*"' $(logInstall*Add),\
251
(prefix=; . $(bin)/vegbien_dest; unset schemas; env schema=$(datasrc) table=$*\
252
$(bin)/csv2db) $(logInstall*Add))
253

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

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

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

    
281
%/uninstall: _always
282
	echo 'DROP TABLE IF EXISTS "$(datasrc)"."$*" CASCADE;'|$(psqlNoSearchPath)
283

    
284
%/reinstall: _always %/uninstall %/install ;
285

    
286
cleanup: _always $(tables:%=%/cleanup) ;
287

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

    
293
##### Maps building
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
%/test: %/test.xml _always ;
469

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

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

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

    
485
testOutputs := $(foreach test,$(tests),$(importTables:%=$(test)))
486

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

    
489
test: _always $(testOutputs) ;
490

    
491
all += $(wildcard %/test*.xml)
492

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

    
497
accept-all: _always
498
	+yes|$(selfMake) test
499

    
500
##### Documentation
501

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

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