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
# Makefile
23
exts ?= csv tsv tab txt dat dmp
24
test_n ?= 2
25

    
26
##### Vars/functions
27

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

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

    
42
# Terminal
43
termCols := $(shell tput cols)
44

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

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

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

    
68
##### Environment
69

    
70
export PATH := $(bin):$(PATH)
71

    
72
##### General targets
73

    
74
all: _always maps ;
75

    
76
clean: _always
77
	$(RM) $(all)
78

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

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

    
89
%/: %/map.csv _always ;
90

    
91
%/: % _always ;
92

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

    
97
##### Tables discovery
98

    
99
sortFile := import_order.txt
100
noImportFile := _no_import
101

    
102
dontImport = $(wildcard $(noImportFile))$(wildcard $(1)/$(noImportFile))$(if\
103
$(import_source),,$(filter Source,$(1)))
104

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

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

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

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

    
133
##### SVN
134

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

    
141
add: _always $(if $(call dontImport,.),,add!) ;
142

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

    
155
add_files: _always
156
	$(call add*,$(svnFiles))
157

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

    
163
##### Existing maps discovery
164

    
165
anyMap := %/map.csv %/VegBIEN.csv %/unmapped_terms.csv %/new_terms.csv
166

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

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

    
174
srcDict := map.csv
175

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

    
180
viaMaps := $(tables:%=%/map.csv)
181

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

    
186
##### Sources
187

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

    
195
# Run with `make -s` to avoid echoing make commands
196
cat: $(importTables:%=%/cat) _always ;
197

    
198
%/cat: _always
199
	$(catSrcs)
200

    
201
##### Input data retrieval
202

    
203
# Must come before `%.sql: _MySQL/%.sql` to override it
204
%.sql: %.sql.make
205
	$(make_script)
206

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

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

    
219
##### Staging tables installation
220

    
221
srcTable := %.src
222

    
223
dbExportsWildcard = $(sort $(patsubst _MySQL/%.make,%,$(wildcard\
224
$(1) _MySQL/$(1).make)))
225

    
226
dbExports := $(call dbExportsWildcard,*schema*.sql)# schemas first
227
ifeq ($(schema_only),) # add rest of .sql files
228
dbExports += $(filter-out $(dbExports),$(call dbExportsWildcard,*.sql))
229
endif
230
dbExports := $(filter-out grants.sql,$(dbExports))
231
dbExports := $(strip $(dbExports))# += adds extra whitespace
232
allInstalls := $(if $(dbExports),sql) $(allTables)
233

    
234
datasrc_schema_exists = $(shell schema=$(datasrc)\
235
$(root)/lib/runscripts/local.run pg_schema_exists && echo t)
236

    
237
install: _always
238
	$(if $(wildcard ./run),./run install,$(if $(wildcard table.run),$(if\
239
$(datasrc_schema_exists),,+$(selfMake) install_oldstyle)))
240
	+$(selfMake) validate/install
241
# table.run: only run this for datasource dirs
242

    
243
install_oldstyle: _always schema $(allInstalls:%=%/install) ;
244

    
245
uninstall: _always confirm_rm_schema rm_schema ;
246
# rm_schema will also drop all staging tables
247

    
248
reinstall: _always uninstall install ;
249

    
250
confirm_rm_schema: _always
251
	$(if $(filter TNRS,$(datasrc)),$(call confirm,WARNING: This will delete the\
252
TNRS cache!,To save it: make backups/TNRS.backup-remake))
253

    
254
schema: _always
255
	-echo 'CREATE SCHEMA "$(datasrc)";'|$(psqlNoSearchPath)
256
# ignore errors if schema exists
257

    
258
rm_schema: _always
259
	echo 'DROP SCHEMA IF EXISTS "$(datasrc)" CASCADE;'|$(psqlNoSearchPath)
260

    
261
installLog := logs/install.log.sql
262

    
263
log_dir = $(1)logs
264
has_log_dir = $(call and,$(wildcard $(log_dir)),$(call not,$(noclobber)))
265
logInstall = $(if $(has_log_dir),$(if $(quiet),$(2)$(1)$(installLog)\
266
2>&1,2>&1|tee $(3) $(1)$(installLog)))
267
logInstallRoot = $(call logInstall,,>)
268
logInstall* = $(call logInstall,$*/,>)
269
logInstall*Add = $(call logInstall,$*/,>>,-a)# append to log
270

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

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

    
288
%/header.csv:
289
	set -o pipefail; \
290
echo 'COPY (SELECT * FROM "$(datasrc)"."$*" LIMIT 0) TO STDOUT CSV HEADER;'|\
291
env no_search_path=1 $(bin)/psql_script_vegbien >$*/header.csv
292

    
293
exportHeader = $(selfMake) "$*/header.csv"
294

    
295
# Don't try to edit a view. Must come before %/install to override it.
296
%_view/install: _always ;
297

    
298
%.sql/run: _always
299
	$(if $(wildcard $(@D)),($(inDatasrc); cat $(@D))|(cd '$(*D)';\
300
"time" env no_search_path=1 ../$(bin)/psql_verbose_vegbien \
301
--set=table='"$(*D)"' --set=table_str=\''"$(*D)"'\'))
302

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

    
306
%/postprocess: _always
307
	$(if\
308
$(wildcard $*/run),$*/run postprocess,$(selfMake) "$*/postprocess.sql/run")
309

    
310
%/map_table: _always
311
	$(if $(wildcard $*/run),$*/run map_table)
312

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

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

    
337
%/uninstall: _always
338
	echo 'DROP $(if\
339
$(is_view),VIEW,TABLE) IF EXISTS "$(datasrc)"."$*" CASCADE;'|$(psqlNoSearchPath)
340

    
341
%/reinstall: _always %/uninstall %/install ;
342

    
343
postprocess: _always $(allTables:%=%/postprocess) ;
344

    
345
cleanup: _always $(tables:%=%/cleanup) ;
346

    
347
# WARNING: This removes any index comments, due to a PostgreSQL bug.
348
# This occurs because ALTER TABLE recreates the index but not its comment.
349
%/cleanup: _always
350
	$(cleanup)
351

    
352
##### Maps building
353

    
354
# Maps to (try to) build are added to this
355
maps :=
356

    
357
srcRoot = $(mappings)/root.sh
358
mkSrcMap = (. $(srcRoot); env datasrc=$(datasrc) $(bin)/src_map <$*/header.csv\
359
>$@)
360

    
361
translate = $(if $(wildcard $(1)),$(bin)/in_place $< $(bin)/translate_ci 1 $(1))
362

    
363
$(srcDict):# empty target in case it doesn't exist
364

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

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

    
392
maps: $(maps) _always ;
393

    
394
all += $(maps)
395

    
396
##### Maps validation
397

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

    
401
%/unmapped_terms.csv: %/map.csv $(coreMap)
402
	tail -n +2 $<|$(bin)/cols 1|$(bin)/filter_out_ci 0 $(coreMap) >$@
403
	$(bin)/autoremove $@
404

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

    
412
termsSubdirs := $(tables)
413

    
414
include $(root)/lib/mappings.Makefile
415

    
416
##### External dependencies
417

    
418
$(root)/%: _always
419
	+$(subMake)
420
.PRECIOUS: $(root)/% # let ext. dir's Makefile decide whether to delete on error
421

    
422
##### Mapping
423

    
424
+maps = $(filter %/map.csv %/VegBIEN.csv $(mappings)/%,$(+_))
425
map2db = env in_database=vegbien in_schema=$(datasrc) in_table=$*\
426
out_database=vegbien source=$(datasrc).new $(root)/map $(+maps)
427

    
428
##### Import to VegBIEN
429

    
430
import_temp: $(importTables:%=%/import) _always ;
431

    
432
import: _always import_temp publish validate ; # removes temp suffix when done
433

    
434
rm: _always
435
	echo "SELECT datasource_rm('$(datasrc)');"|"time" $(psqlAsBien)
436

    
437
reimport: _always import ; # import replaces the previous import
438

    
439
profileTest = $(if $(profile),$(if $(test),1))
440
profileOnly = -env profile_to=/dev/fd/3 $(map2db) 3>&1 1>&2|\
441
$(bin)/profile_stats /dev/fd/0
442

    
443
log_ = $*/logs/$(if $(n),n=$(n).,)$(version).log.sql
444

    
445
# Displays the import log file path
446
# Run with `make -s` to avoid echoing make commands
447
%/log_file: _always
448
	echo $$(pwd)/$(log_)
449

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

    
457
import? = $(if $(call and,$(full_import),$(call dontImport,.)),,$(import))
458

    
459
%/import_temp: %/VegBIEN.csv _always
460
	$(if $(full_import),-)$(import?)
461
# don't abort on import errors, which often relate to invalid input data
462
# default:
463
%/import_temp: _always ;
464

    
465
%/import: %/import_temp _always ;
466

    
467
#### Taxonomic scrubbing
468

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

    
474
# Removes TNRS taxondeterminations
475
unscrub: _always
476
	echo "SELECT delete_scrubbed_taxondeterminations('$(datasrc)');"|\
477
"time" env no_query_results=1 $(psqlAsBien)
478

    
479
rescrub: _always unscrub scrub ;
480

    
481
import_scrub: _always import scrub ;
482

    
483
reimport_scrub: _always reimport scrub ;
484

    
485
%/import_scrub: _always %/import scrub ;
486

    
487
##### Log files from import
488

    
489
logs := $(wildcard */logs/*.log.sql */logs/*.trace)
490

    
491
rm_logs: _always
492
	$(RM) $(logs)
493

    
494
##### Verification of import
495

    
496
### new-style aggregating validations (also work w/ old-style import)
497

    
498
# must be in input.Makefile instead of table.run because some datasources that
499
# we validate still use old-style import
500

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

    
504
validate: _always
505
	echo "SELECT remake_diff_tables('$(datasrc)');"\
506
|$(psqlAsBien)$(if $(log), >>.$(log_) 2>&1)
507

    
508
### old-style aggregating validations (not related to old-style import)
509

    
510
verifyTables := $(patsubst verify/%.ref,%,$(wildcard verify/*.ref))
511

    
512
verify: $(verifyTables:%=%/verify) _always ;
513

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

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

    
531
verify/%.out: verify/%.out.sql _always
532
	$(verify)
533
.PRECIOUS: verify/%.out # save partial output in case of error to help debugging
534
# default:
535
verify/%.out: _always ;
536

    
537
all += $(wildcard verify/*.out)
538

    
539
%.ref: %.ref.sql
540
	($(inDatasrc); cat $<)|$(psqlExport) >$@
541
.PRECIOUS: %.ref # there must always be a .ref for the make rules to work
542

    
543
##### Editing import
544

    
545
rename/%: _always
546
	echo "UPDATE source SET shortname = '$*' WHERE shortname = '$(datasrc)';"\
547
|$(psqlAsBien)
548

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

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

    
554
##### Testing
555

    
556
testRefOutput = $(subst .by_col,,$(1))
557
testRef = $(testRefOutput).ref
558
hasOwnRef = $(filter $@,$(call testRefOutput,$@))
559
# filter returns non-empty if they are equal
560

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

    
583
tests :=
584

    
585
%/test: %/test.xml $(if $(by_col),%/test.by_col.xml) _always ;
586

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

    
593
%/test.by_col.xml: %/VegBIEN.csv _always
594
	$(call runTest,by_col=1)
595

    
596
# Only run column-based tests if column-based mode enabled, because these tests
597
# are much slower than the row-based tests for small numbers of rows
598
ifneq ($(by_col),)
599
tests += %/test.by_col.xml
600
endif
601

    
602
testOutputs := $(foreach test,$(tests),$(tables:%=$(test)))
603

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

    
606
test: _always $(testOutputs) ;
607

    
608
all += $(wildcard %/test*.xml)
609

    
610
# Accepts a test output: make <test_output_path>-ok
611
%-ok: _always
612
	mv $* $(call testRef,$*)
613

    
614
accept-all: _always
615
	+yes|$(selfMake) test
616

    
617
##### Documentation
618

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

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