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\n*.zip')
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 *data*.sql)
232
	# schema/data in order, and before clean_up.sql, etc
233
ifeq ($(schema_only),) # add rest of .sql files
234
dbExports += $(filter-out $(dbExports),$(call dbExportsWildcard,*.sql))
235
endif
236
dbExports := $(filter-out grants.sql,$(dbExports))
237
dbExports := $(strip $(dbExports))# += adds extra whitespace
238
allInstalls := $(if $(dbExports),sql) $(allTables)
239

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

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

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

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

    
254
reinstall: _always uninstall install ;
255

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
358
##### Maps building
359

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

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

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

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

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

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

    
398
maps: $(maps) _always ;
399

    
400
all += $(maps)
401

    
402
##### Maps validation
403

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

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

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

    
418
termsSubdirs := $(tables)
419

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

    
422
##### External dependencies
423

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

    
428
##### Mapping
429

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

    
434
##### Import to VegBIEN
435

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

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

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

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

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

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

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

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

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

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

    
471
%/import: %/import_temp _always ;
472

    
473
#### Taxonomic scrubbing
474

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

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

    
485
rescrub: _always unscrub scrub ;
486

    
487
import_scrub: _always import scrub ;
488

    
489
reimport_scrub: _always reimport scrub ;
490

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

    
493
##### Log files from import
494

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

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

    
500
##### Verification of import
501

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

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

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

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

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

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

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

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

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

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

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

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

    
549
##### Editing import
550

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

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

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

    
560
##### Testing
561

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

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

    
589
tests :=
590

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

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

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

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

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

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

    
612
test: _always $(testOutputs) ;
613

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

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

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

    
623
##### Documentation
624

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

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