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
continue ?=
10
debug ?=
11
full_import ?=
12
import_source ?= 1
13
is_view ?=
14
log ?= $(if $(test),,1)
15
noclobber ?=
16
profile ?=
17
quiet ?=
18
reverify ?= 1
19
schema_only ?=
20
use_staged ?= $(by_col)
21

    
22
export null_strs# don't initialize, so that it will use the default
23

    
24
# Makefile
25
exts ?= csv tsv tab txt dat dmp
26
test_n ?= 2
27

    
28
##### Vars/functions
29

    
30
# Paths
31
datasrc := $(patsubst .%,%,$(notdir $(realpath .)))
32
bin := $(root)/bin
33
mappings := $(root)/mappings
34

    
35
# Make
36
SHELL := /bin/bash
37
selfMake = $(MAKE) --makefile=../input.Makefile
38
subMake = $(MAKE) "$(@:$(root)/%=%)" --directory=$(root)
39
+_ = $(+:_%=)
40
# used to filter the output of embedded $(shell make ...) invocations
41
filter_make := grep -vF -e lib -e ".Makefile'."
42
addBeforeExt = $(basename $(2))$(1)$(suffix $(2))
43

    
44
# Terminal
45
termCols := $(shell tput cols)
46

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

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

    
63
# SVN
64
setSvnIgnore = svn propset svn:ignore $(2) $(1)
65
define addDirWithIgnore
66
$(addDir)
67
$(setSvnIgnore)
68
endef
69

    
70
##### Environment
71

    
72
export PATH := $(bin):$(PATH)
73

    
74
##### General targets
75

    
76
all: _always maps ;
77

    
78
clean: _always
79
	$(RM) $(all)
80

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

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

    
91
%/: %/map.csv _always ;
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 $(noImportFile))$(wildcard $(1)/$(noImportFile))$(if\
105
$(import_source),,$(filter Source,$(1)))
106

    
107
ifeq ($(sort_file_updated),)# keep $(sortFile) up-to-date
108
$(shell sort_file_updated=1 $(selfMake) $(sortFile)|$(filter_make) >&2)
109
export sort_file_updated=1
110
endif
111

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

    
128
list_tables: _always # use `make -s` to avoid echoing commands
129
	@for table in $(tables); do echo "$$table"; done
130

    
131
$(sortFile): _always
132
	$(if $(filter-out $(sort_file_tables),$(tables)),$(selfMake) -s list_tables >$@)
133
# add any missing tables to $(sortFile)
134

    
135
##### SVN
136

    
137
svnFilesGlob:= */{,{,.}{data,map,VegBIEN}.csv{,.*},*header.*,*.sql,test.xml.ref}
138
svnFilesGlob := {map.csv,*{grants,validations,~}*.sql,{,*/}{*.{log,make},*terms.csv},$(svnFilesGlob)}
139
_svnFilesGlob := {_MySQL/{,*.make},{,*/}{$(noImportFile),*{run,Makefile},*.{md5,url},*README.TXT}}
140
svnFiles = $(filter-out _% logs/% %.data.sql,$(call wildcard/,$(svnFilesGlob)))\
141
$(call wildcard/,$(_svnFilesGlob))
142

    
143
add: _always $(if $(call dontImport,.),,add!) ;
144

    
145
# To update all inputs with these settings: make inputs/add
146
add!: _always Source/add $(allTables:%=%/add)
147
	$(call setSvnIgnore,.,'*')
148
	$(call addDirWithIgnore,logs,$$'*.gz\n*.log.sql\n*.trace')
149
	$(call addDirWithIgnore,verify,$$'*.csv\n*.log\n*.out\n*.tsv\n*.txt\n*.xls\n*.xlsx')
150
	$(call addFile,import_order.txt)
151
	$(if $(wildcard _MySQL/),$(call addDirWithIgnore,_MySQL,'*'))
152
	$(if $(wildcard _src/),$(call addDirWithIgnore,_src,'*'))
153
	$(if $(wildcard _archive/),$(call addDirWithIgnore,_archive,'*'))
154
	# invoke externally to clear $$(wildcard) cache before expanding $$(svnFiles)
155
	$(selfMake) add_files
156

    
157
add_files: _always
158
	$(call add*,$(svnFiles))
159

    
160
# Adds a new table subdir
161
%/add: _always
162
	$(call addDirWithIgnore,$*,'*')
163
	$(call addDirWithIgnore,$*/logs,$$'*.gz\n*.log.sql\n*.trace')
164

    
165
##### Existing maps discovery
166

    
167
anyMap := %/map.csv %/VegBIEN.csv %/unmapped_terms.csv %/new_terms.csv
168

    
169
exts := $(call ci,$(exts))
170
extsFilter := $(addprefix %.,$(exts))
171
dataOnly = $(filter $(extsFilter),$(1))
172

    
173
anyTest = $*/test.%
174
srcsOnly = $(filter-out $(anyMap) $(anyTest) %/logs,$(call dataOnly,$(1)))
175

    
176
srcDict := map.csv
177

    
178
vocab := $(mappings)/VegCore.vocab.csv
179
thesaurus := $(mappings)/VegCore.thesaurus.csv
180
coreMap := $(mappings)/VegCore-VegBIEN.csv
181

    
182
viaMaps := $(tables:%=%/map.csv)
183

    
184
autogenMaps := $(subst map.,VegBIEN.,$(viaMaps))
185
directMaps := $(autogenMaps) $(filter-out $(autogenMaps),\
186
$(wildcard */VegBIEN.csv))
187

    
188
##### Sources
189

    
190
srcs = $(call sortFilenames,$(call srcsOnly,$(wildcard $*/*)))
191
nonHeaderSrcs = $(filter-out %/header.csv %/header.txt,$(srcs))
192
isRef = $(if $(nonHeaderSrcs),,1)
193
    # empty subdir, so references an already-installed staging table
194
catSrcs = $(bin)/cat_csv $(nonHeaderSrcs)
195
withCatSrcs = $(catSrcs:$(bin)/%=$(bin)/with_%) --
196

    
197
%/list_srcs: _always # use `make -s` to avoid echoing commands
198
	echo $(nonHeaderSrcs)
199

    
200
# Run with `make -s` to avoid echoing make commands
201
cat: $(importTables:%=%/cat) _always ;
202

    
203
%/cat: _always
204
	$(catSrcs)
205

    
206
##### Input data retrieval
207

    
208
# Must come before `%.sql: _MySQL/%.sql` to override it
209
%.sql: %.sql.make
210
	$(make_script)
211

    
212
# The export must be created with:
213
# `--compatible=postgresql --add-locks=false --set-charset --no-create-info`
214
# Must come before `%.sql: _MySQL/%.sql` to override it
215
%.data.sql: _MySQL/%.data.sql
216
	$(if $(wildcard $@),,$(bin)/my2pg.data <$< >$@)
217

    
218
# The export must be created with:
219
# `--compatible=postgresql --add-locks=false --set-charset`
220
# Add `--no-data` to create a schema-only export.
221
%.sql: _MySQL/%.sql
222
	$(if $(wildcard $@),,$(bin)/my2pg <$< >$@)
223

    
224
##### Staging tables installation
225

    
226
srcTable := %.src
227

    
228
dbExportsWildcard = $(sort $(patsubst _MySQL/%.make,%,$(wildcard\
229
$(1) _MySQL/$(1).make)))
230

    
231
dbExports := $(call dbExportsWildcard,*schema*.sql)# schemas first
232
ifeq ($(schema_only),) # add rest of .sql files
233
dbExports += $(filter-out $(dbExports),$(call dbExportsWildcard,*.sql))
234
endif
235
dbExports := $(filter-out grants.sql,$(dbExports))
236
dbExports := $(strip $(dbExports))# += adds extra whitespace
237
allInstalls := $(if $(dbExports),sql) $(allTables)
238

    
239
datasrc_schema_exists = $(shell schema=$(datasrc)\
240
$(root)/lib/runscripts/local.run pg_schema_exists && echo t)
241

    
242
install: _always
243
	$(if $(wildcard ./run),./run install,$(if $(wildcard table.run),$(if\
244
$(datasrc_schema_exists),,+$(selfMake) install_oldstyle)))
245
	+$(selfMake) validate/install
246
# table.run: only run this for datasource dirs
247

    
248
install_oldstyle: _always schema $(allInstalls:%=%/install) ;
249

    
250
uninstall: _always confirm_rm_schema rm_schema ;
251
# rm_schema will also drop all staging tables
252

    
253
reinstall: _always uninstall install ;
254

    
255
confirm_rm_schema: _always
256
	$(if $(filter TNRS,$(datasrc)),$(call confirm,WARNING: This will delete the\
257
TNRS cache!,To save it: make backups/TNRS.backup-remake))
258

    
259
schema: _always
260
	-echo 'CREATE SCHEMA "$(datasrc)";'|$(psqlNoSearchPath)
261
# ignore errors if schema exists
262

    
263
rm_schema: _always
264
	echo 'DROP SCHEMA IF EXISTS "$(datasrc)" CASCADE;'|$(psqlNoSearchPath)
265

    
266
installLog := logs/install.log.sql
267

    
268
log_dir = $(1)logs
269
has_log_dir = $(call and,$(wildcard $(log_dir)),$(call not,$(noclobber)))
270
logInstall = $(if $(has_log_dir),$(if $(quiet),$(2)$(1)$(installLog)\
271
2>&1,2>&1|tee $(3) $(1)$(installLog)))
272
logInstallRoot = $(call logInstall,,>)
273
logInstall* = $(call logInstall,$*/,>)
274
logInstall*Add = $(call logInstall,$*/,>>,-a)# append to log
275

    
276
# Must come before %/install to override it
277
sql/install: $(dbExports)
278
	set -o pipefail; ($(inDatasrc); $(if $(wildcard schema.sql),cat schema.sql;)\
279
cat $(filter-out schema.sql grants.sql,$+)|pg_dump_limit $(if $(wildcard\
280
grants.sql),; cat grants.sql))|"time" env no_search_path=1 \
281
$(bin)/psql_$(if $(debug),verbose,script)_vegbien --set=schema='"$(datasrc)"' \
282
$(logInstallRoot)
283

    
284
# $debug option runs the *.sql import verbosely, to display which statements are
285
# being run. this should only be used for SQL files that use COPY FROM to import
286
# data, to avoid echoing pages of insert statements.
287
cleanup = set -o pipefail; \
288
$(if $(wildcard $*/cleanup.sql),($(inDatasrc); cat $*/cleanup.sql)\
289
|"time" $(psqlNoSearchPath) --echo-all --set=table='"$*"' $(logInstall*Add),\
290
(export schema=$(datasrc) table=$*; . $(bin)/vegbien_dest; unset schemas; \
291
$(bin)/csv2db) $(logInstall*Add))
292

    
293
%/header.csv:
294
	set -o pipefail; \
295
echo 'COPY (SELECT * FROM "$(datasrc)"."$*" LIMIT 0) TO STDOUT CSV HEADER;'|\
296
env no_search_path=1 $(bin)/psql_script_vegbien >$*/header.csv
297

    
298
exportHeader = $(selfMake) "$*/header.csv"
299

    
300
# Don't try to edit a view. Must come before %/install to override it.
301
%_view/install: _always ;
302

    
303
%.sql/run: _always
304
	$(if $(wildcard $(@D)),($(inDatasrc); cat $(@D))|(cd '$(*D)';\
305
"time" env no_search_path=1 ../$(bin)/psql_verbose_vegbien \
306
--set=table='"$(*D)"' --set=table_str=\''"$(*D)"'\'))
307

    
308
%/postprocess.sql: $(thesaurus) _always
309
	$(if $(wildcard $*/run),$(bin)/in_place $@ env text=1 $(bin)/repl $<)
310

    
311
%/postprocess: _always
312
	$(if\
313
$(wildcard $*/run),$*/run postprocess,$(selfMake) "$*/postprocess.sql/run")
314

    
315
%/map_table: _always
316
	$(if $(wildcard $*/run),$*/run map_table)
317

    
318
# For staging tables which are derived by joining together other staging tables.
319
%/install: %/create.sql _always
320
	set -o pipefail; \
321
($(inDatasrc); echo 'CREATE TABLE "$*" AS'; cat $<; echo ';')|"time" \
322
$(psqlNoSearchPath) --echo-all --set=schema='"$(datasrc)"' --set=table='"$*"' \
323
$(logInstall*)
324
	$(exportHeader)
325
	$(selfMake) "$*/postprocess"
326
	$(cleanup)
327

    
328
%/install: _always
329
	$(import_install_)
330
	$(exportHeader)
331
	$(selfMake) "$*/postprocess"
332
	$(cleanup)
333
define import_install_
334
set -o pipefail; (. $(bin)/vegbien_dest; unset schemas; "time" $(nice)\
335
env schema=$(datasrc) table=$* $(bin)/csv2db $(catSrcs) $(logInstall*))
336
$(if $(filter $(srcTable),$*),($(inDatasrc);\
337
echo 'ALTER TABLE "$(datasrc)"."$*" RENAME row_num TO "$*.row_num";')|"time"\
338
$(psqlNoSearchPath) --echo-all --set=table='"$*"' $(logInstall*Add))
339
endef
340
# table-scope src table's row_num col to allow joining it with other tables
341

    
342
%/uninstall: _always
343
	echo 'DROP $(if\
344
$(is_view),VIEW,TABLE) IF EXISTS "$(datasrc)"."$*" CASCADE;'|$(psqlNoSearchPath)
345

    
346
%/reinstall: _always %/uninstall %/install ;
347

    
348
postprocess: _always $(allTables:%=%/postprocess) ;
349

    
350
cleanup: _always $(tables:%=%/cleanup) ;
351

    
352
# WARNING: This removes any index comments, due to a PostgreSQL bug.
353
# This occurs because ALTER TABLE recreates the index but not its comment.
354
%/cleanup: _always
355
	$(cleanup)
356

    
357
##### Maps building
358

    
359
# Maps to (try to) build are added to this
360
maps :=
361

    
362
srcRoot = $(mappings)/root.sh
363
mkSrcMap = (. $(srcRoot); env datasrc=$(datasrc) $(bin)/src_map <$*/header.csv\
364
>$@)
365

    
366
translate = $(if $(wildcard $(1)),$(bin)/in_place $< $(bin)/translate_ci 1 $(1))
367

    
368
$(srcDict):# empty target in case it doesn't exist
369

    
370
# Via maps cleanup
371
ifneq ($(filter %/.map.csv.last_cleanup,$(MAKECMDGOALS)),)
372
%/.map.csv.last_cleanup: %/map.csv $(vocab) $(thesaurus) $(coreMap) $(srcDict)
373
	$(call translate,$(srcDict))
374
	$(bin)/in_place $< $(bin)/canon 1 $(vocab)
375
	$(call translate,$(thesaurus))
376
	$(bin)/in_place $< $(bin)/fix_line_endings
377
	touch $@
378
	+$(selfMake) $(<:%/map.csv=%/unmapped_terms.csv)
379
	+$(selfMake) $(<:%/map.csv=%/new_terms.csv)
380
.PRECIOUS: %/.map.csv.last_cleanup
381
else
382
%/map.csv: _always
383
	$(if $(wildcard $@),,$(mk_map_csv))
384
	+$(selfMake) $(@:%/map.csv=%/.map.csv.last_cleanup)
385
define mk_map_csv
386
+$(selfMake) "$*/header.csv"
387
$(mkSrcMap)
388
endef
389
endif
390

    
391
%/VegBIEN.csv: %/map.csv $(coreMap)
392
	$(if $(wildcard $*/run),-ln -s "../$(coreMap)" "$@"\
393
,<$< $(bin)/cat_cols 1 2|$(bin)/join $(coreMap)|$(bin)/sort_map >$@)
394
# ignore errors if symlink exists
395
maps += $(autogenMaps)
396

    
397
maps: $(maps) _always ;
398

    
399
all += $(maps)
400

    
401
##### Maps validation
402

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

    
406
%/unmapped_terms.csv: %/map.csv $(coreMap)
407
	tail -n +2 $<|$(bin)/cols 1|$(bin)/filter_out_ci 0 $(coreMap) >$@
408
	$(bin)/autoremove $@
409

    
410
%/new_terms.csv: %/map.csv $(vocab) $(thesaurus) %/unmapped_terms.csv
411
	$(newTerms)
412
	$(bin)/autoremove $@
413
newTerms = tail -n +2 $<|$(bin)/filter_out_ci 0 $(vocab)|$(bin)/filter_out_ci 0\
414
$(thesaurus) $(if $(wildcard $(word 4,$+)),|$(bin)/filter_out_ci 0 $(word 4,$+))\
415
|grep -vE -e '^"?:' -e 'UNUSED' >$@; exit 0 # grep exits nonzero if no match
416

    
417
termsSubdirs := $(tables)
418

    
419
include $(root)/lib/mappings.Makefile
420

    
421
##### External dependencies
422

    
423
$(root)/%: _always
424
	+$(subMake)
425
.PRECIOUS: $(root)/% # let ext. dir's Makefile decide whether to delete on error
426

    
427
##### Mapping
428

    
429
+maps = $(filter %/map.csv %/VegBIEN.csv $(mappings)/%,$(+_))
430
map2db = env in_database=vegbien in_schema=$(datasrc) in_table=$*\
431
out_database=vegbien source=$(datasrc).new $(root)/map $(+maps)
432

    
433
##### Import to VegBIEN
434

    
435
import_temp: $(importTables:%=%/import) _always ;
436

    
437
import: _always import_temp publish validate ; # removes temp suffix when done
438

    
439
rm: _always
440
	echo "SELECT datasource_rm('$(datasrc)');"|"time" $(psqlAsBien)
441

    
442
reimport: _always import ; # import replaces the previous import
443

    
444
profileTest = $(if $(profile),$(if $(test),1))
445
profileOnly = -env profile_to=/dev/fd/3 $(map2db) 3>&1 1>&2|\
446
$(bin)/profile_stats /dev/fd/0
447

    
448
log_ = $*/logs/$(if $(n),n=$(n).,)$(version).log.sql
449

    
450
# Displays the import log file path
451
# Run with `make -s` to avoid echoing make commands
452
%/log_file: _always
453
	echo $$(pwd)/$(log_)
454

    
455
trace = $(log_:.log.sql=.trace)
456
restart_row = $(shell set -x; grep -F Partition: $(log_)|tail -1|$(sed)\
457
's/^.* rows ([[:digit:]]+)-.*$$/\1/')
458
import = $(if $(profileTest),$(profileOnly),(set -x; date; "time" env commit=1\
459
$(if $(profile),profile_to=$(trace)) $(if $(continue),start=$(restart_row))\
460
$(map2db))$(if $(log), >>$(log_) 2>&1))
461

    
462
import? = $(if $(call and,$(full_import),$(call dontImport,.)),,$(import))
463

    
464
%/import_temp: %/VegBIEN.csv _always
465
	$(if $(full_import),-)$(import?)
466
# don't abort on import errors, which often relate to invalid input data
467
# default:
468
%/import_temp: _always ;
469

    
470
%/import: %/import_temp _always ;
471

    
472
#### Taxonomic scrubbing
473

    
474
scrub: _always
475
	$(selfMake) $(root)/scrub & echo $$!
476
# using & (background process) also ignores TNRS errors, so that TNRS bugs do
477
# not prevent the remaining tables from being imported even if TNRS can't be run
478

    
479
# Removes TNRS taxondeterminations
480
unscrub: _always
481
	echo "SELECT delete_scrubbed_taxondeterminations('$(datasrc)');"|\
482
"time" env no_query_results=1 $(psqlAsBien)
483

    
484
rescrub: _always unscrub scrub ;
485

    
486
import_scrub: _always import scrub ;
487

    
488
reimport_scrub: _always reimport scrub ;
489

    
490
%/import_scrub: _always %/import scrub ;
491

    
492
##### Log files from import
493

    
494
logs := $(wildcard */logs/*.log.sql */logs/*.trace)
495

    
496
rm_logs: _always
497
	$(RM) $(logs)
498

    
499
##### Verification of import
500

    
501
### new-style aggregating validations (also work w/ old-style import)
502

    
503
# must be in input.Makefile instead of table.run because some datasources that
504
# we validate still use old-style import
505

    
506
# validations.sql must be in a subdir so it won't get run by sql/install
507
validate/install: _always verify/validations.sql/run ;
508

    
509
validate: _always
510
	echo "SELECT remake_diff_tables('$(datasrc)');"\
511
|$(psqlAsBien)$(if $(log), >>.$(log_) 2>&1)
512

    
513
### old-style aggregating validations (not related to old-style import)
514

    
515
verifyTables := $(patsubst verify/%.ref,%,$(wildcard verify/*.ref))
516

    
517
verify: $(verifyTables:%=%/verify) _always ;
518

    
519
%/verify: verify/%.ref verify/%.out _always
520
	-$(diffVerbose) $(+_)
521
# don't abort on verification errors, which are expected during development
522
# default:
523
%/verify: verify/%.out _always
524
	$(if $(shell test -e $< && echo t),cat $<)
525
# don't run if verify/%.out's default do-nothing action was used
526
# can't use $(wildcard) because it won't recheck file after verify/%.out is run
527

    
528
psqlExport := "time" $(psqlNoSearchPath) --no-align --field-separator=$$'\t'\
529
--pset=footer=off --pset=null=NULL
530
# Note that using $(inDatasrc) will not work with datasources whose tables are
531
# the same name as VegBIEN tables (likely only VegBank), because the datasource
532
# is first in the search_path.
533
verify = $(if $(reverify),($(inDatasrc); cat $<)|$(psqlExport)\
534
--set=datasource="'$(datasrc)'" >$@)
535

    
536
verify/%.out: verify/%.out.sql _always
537
	$(verify)
538
.PRECIOUS: verify/%.out # save partial output in case of error to help debugging
539
# default:
540
verify/%.out: _always ;
541

    
542
all += $(wildcard verify/*.out)
543

    
544
%.ref: %.ref.sql
545
	($(inDatasrc); cat $<)|$(psqlExport) >$@
546
.PRECIOUS: %.ref # there must always be a .ref for the make rules to work
547

    
548
##### Editing import
549

    
550
rename/%: _always
551
	echo "UPDATE source SET shortname = '$*' WHERE shortname = '$(datasrc)';"\
552
|$(psqlAsBien)
553

    
554
%/publish: _always # usage: make inputs/src/src.version/publish
555
	echo "SELECT datasource_publish('$*');"|$(psqlAsBien)
556

    
557
publish: _always $(datasrc).new/publish ; # usage: make inputs/src/publish
558

    
559
##### Testing
560

    
561
testRefOutput = $(subst .by_col,,$(1))
562
testRef = $(testRefOutput).ref
563
hasOwnRef = $(filter $@,$(call testRefOutput,$@))
564
# filter returns non-empty if they are equal
565

    
566
# `rm $@`: Remove outputs of successful tests to reduce clutter
567
# `$(foreach use_staged...)`: Run with use_staged=1
568
define runTest
569
@echo "Testing $(abspath $@)..."
570
>$@ env test=1 n=$(test_n) $(1) $(foreach use_staged,1,$(map2db))
571
$(if $(hasOwnRef),,-)@(set -x; $(diffIgnoreSpace) $(call testRef,$@) $@) 2>&1\
572
&& rm $@ || { e=$$?; $(if $(wildcard $(call testRef,$@)),,cat $@;)\
573
$(if $(hasOwnRef),\
574
{\
575
read -p $(emph)'Accept new test output? (y/n)'$(endEmph) REPLY;\
576
if test "$$REPLY" = y; then\
577
(set -x; $(MAKE) $@-ok --directory=$(realpath .) --makefile=../input.Makefile);\
578
exit 0;\
579
fi;\
580
};,\
581
echo $(emph)"Note: The preceding failed test is compared to another test's\
582
output"$(endEmph);\
583
echo $(emph)"When it fails, this always indicates a bug"$(endEmph);\
584
)\
585
exit $$e;}
586
endef
587

    
588
tests :=
589

    
590
%/test: %/test.xml $(if $(by_col),%/test.by_col.xml) _always ;
591

    
592
# Requires staging tables. To create them, run `make inputs/<datasrc>/install`.
593
# Non-flat-file inputs fall back to mimicking a successful test
594
%/test.xml: %/VegBIEN.csv _always
595
	$(call runTest,by_col=)
596
tests += %/test.xml
597

    
598
%/test.by_col.xml: %/VegBIEN.csv _always
599
	$(call runTest,by_col=1)
600

    
601
# Only run column-based tests if column-based mode enabled, because these tests
602
# are much slower than the row-based tests for small numbers of rows
603
ifneq ($(by_col),)
604
tests += %/test.by_col.xml
605
endif
606

    
607
testOutputs := $(foreach test,$(tests),$(tables:%=$(test)))
608

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

    
611
test: _always $(testOutputs) ;
612

    
613
all += $(wildcard %/test*.xml)
614

    
615
# Accepts a test output: make <test_output_path>-ok
616
%-ok: _always
617
	mv $* $(call testRef,$*)
618

    
619
accept-all: _always
620
	+yes|$(selfMake) test
621

    
622
##### Documentation
623

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

    
627
%/logs/steps.by_col.log.sql: _always
628
	+$(steps)
(10-10/13)