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
public_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 txt 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_script_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},_src/*.{url,pdf}}
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 Source/map.csv $(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
extsFilter := $(addprefix %.,$(exts))
140
dataOnly = $(filter $(extsFilter),$(1))
141

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

    
145
srcDict := map.csv
146

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

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

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

    
157
##### Sources
158

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

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

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

    
176
##### Input data retrieval
177

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

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

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

    
194
##### Staging tables installation
195

    
196
srcTable := %.src
197

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

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

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

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

    
213
reinstall: _always uninstall install ;
214

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

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

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

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

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

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

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

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

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

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

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

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

    
277
%/reinstall: _always %/uninstall %/install ;
278

    
279
cleanup: _always $(tables:%=%/cleanup) ;
280

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

    
286
##### Maps building
287

    
288
# Maps to (try to) build are added to this
289
maps :=
290

    
291
srcRoot = $(mappings)/root.sh
292
mkSrcMap = $(catSrcs)|(. $(srcRoot); env datasrc=$(datasrc) $(bin)/src_map >$@)
293

    
294
define translate
295
$(bin)/in_place $< $(bin)/canon 1 $(1)
296
$(bin)/in_place $< $(bin)/translate 1 $(1)
297
endef
298
translate? = $(if $(wildcard $(1)),$(translate))
299

    
300
$(srcDict):# empty target in case it doesn't exist
301

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

    
319
%/VegBIEN.csv: %/map.csv $(coreMap)
320
	<$< $(bin)/cat_cols 1 2|$(bin)/join $(coreMap)|$(bin)/sort_map >$@
321
maps += $(autogenMaps)
322

    
323
maps: $(maps) _always ;
324

    
325
all += $(maps)
326

    
327
##### Maps validation
328

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

    
332
%/unmapped_terms.csv: %/map.csv $(coreMap)
333
	tail -n +2 $<|$(bin)/cols 1|$(bin)/filter_out_ci 0 $(coreMap) >$@
334
	$(bin)/autoremove $@
335

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

    
343
termsSubdirs := $(importTables)
344

    
345
include $(root)/lib/mappings.Makefile
346

    
347
##### External dependencies
348

    
349
$(root)/%: _always
350
	+$(subMake)
351
.PRECIOUS: $(root)/% # let ext. dir's Makefile decide whether to delete on error
352

    
353
##### Mapping
354

    
355
+maps = $(filter %/map.csv %/VegBIEN.csv $(mappings)/%,$(+_))
356
map2db = env in_database=vegbien in_schema=$(datasrc) in_table=$*\
357
out_database=vegbien $(root)/map $(+maps)
358

    
359
##### Import to VegBIEN
360

    
361
profileTest = $(if $(profile),$(if $(test),1))
362
profileOnly = -env profile_to=/dev/fd/3 $(map2db) 3>&1 1>&2|\
363
$(bin)/profile_stats /dev/fd/0
364

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

    
372
import? = $(if $(call and,$(public_import),$(call dontImport,.)),,$(import))
373

    
374
import: $(importTables:%=%/import) _always ;
375

    
376
%/import: %/VegBIEN.csv _always
377
	$(import?)
378
# default:
379
%/import: _always ;
380

    
381
##### Log files from import
382

    
383
logs := $(wildcard */logs/*.log.sql */logs/*.trace)
384

    
385
rm_logs: _always
386
	$(RM) $(logs)
387

    
388
##### Verification of import
389

    
390
verifyTables := $(patsubst verify/%.ref,%,$(wildcard verify/*.ref))
391

    
392
verify: $(verifyTables:%=%/verify) _always ;
393

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

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

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

    
417
all += $(wildcard verify/*.out)
418

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

    
423
##### Editing import
424

    
425
rename/%: _always
426
	echo "UPDATE source SET shortname = '$*' WHERE shortname = '$(datasrc)';"\
427
|$(psqlAsBien)
428

    
429
rm: _always
430
	echo "DELETE FROM source WHERE shortname = '$(datasrc)';"\
431
|"time" $(psqlAsBien)
432

    
433
##### Testing
434

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

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

    
462
tests :=
463

    
464
%/test: %/test.xml _always ;
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)