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
	$(if $(wildcard _archive/),$(call addDirWithIgnore,_archive,'*'))
136
	$(call add*,$(svnFiles))
137

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

    
143
##### Existing maps discovery
144

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

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

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

    
153
srcDict := map.csv
154

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

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

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

    
165
##### Sources
166

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

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

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

    
184
##### Input data retrieval
185

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

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

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

    
202
##### Staging tables installation
203

    
204
srcTable := %.src
205

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

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

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

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

    
221
reinstall: _always uninstall install ;
222

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
291
##### Maps building
292

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

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

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

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

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

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

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

    
331
maps: $(maps) _always ;
332

    
333
all += $(maps)
334

    
335
##### Maps validation
336

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

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

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

    
351
termsSubdirs := $(importTables)
352

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

    
355
##### External dependencies
356

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

    
361
##### Mapping
362

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

    
367
##### Import to VegBIEN
368

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

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

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

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

    
387
##### Log files from import
388

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

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

    
394
##### Verification of import
395

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

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

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

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

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

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

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

    
429
##### Editing import
430

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

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

    
438
##### Testing
439

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

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

    
467
tests :=
468

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

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

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

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

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

    
488
test: _always $(testOutputs) ;
489

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

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

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

    
499
##### Documentation
500

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

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