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
log ?= $(if $(test),,1)
10
profile ?=
11
quiet ?=
12
reverify ?= 1
13
use_staged ?= $(by_col)
14

    
15
# Makefile
16
exts ?= csv tsv txt xml
17
test_n ?= 2
18

    
19
##### Vars/functions
20

    
21
# Paths
22
datasrc := $(notdir $(realpath .))
23
bin := $(root)/bin
24
mappings := $(root)/mappings
25

    
26
# Make
27
SHELL := /bin/bash
28
selfMake = $(MAKE) --makefile=../input.Makefile
29
subMake = $(MAKE) $(@:$(root)/%=%) --directory=$(root)
30
+_ = $(+:_%=)
31
addBeforeExt = $(basename $(2))$(1)$(suffix $(2))
32

    
33
# OS
34
os := $(shell uname)
35
forOs = $(patsubst %,%-$(filter Linux Darwin,$(os)),$(1))
36

    
37
# Formatting
38
SED = sed -$(if $(filter Darwin,$(os)),E,r)
39

    
40
# System
41
date = $(shell date +"%Y-%m-%d-%H-%M-%S")
42

    
43
# Terminal
44
termCols := $(shell tput cols)
45
esc := '['
46
reset := $(esc)'0m'
47
emph := $(esc)'7m '
48
endEmph := ' '$(reset)
49

    
50
# Commands
51
MKDIR = mkdir -p
52
mkdir = $(MKDIR) $(@D)
53
CP = cp -p
54
diff = diff --unified=2
55
diffIgnoreSpace = $(diff) --ignore-space-change
56
diffVerbose = $(if $(verbose),diff --side-by-side --left-column\
57
--width=$(termCols),$(diff))
58

    
59
# BIEN commands
60
sortFilenames = $(shell $(bin)/sort_filenames $(1))
61
selfMap = $(bin)/cols 0 0
62
psqlOpts := --set ON_ERROR_STOP=1 --quiet
63
psqlAsBien := $(bin)/psql_vegbien $(psqlOpts)
64
# Usage: ($(inDatasrc); cat $(file))|$(psqlCmd)
65
inDatasrc = echo 'SET search_path TO "$(datasrc)";'
66

    
67
# SVN
68
addDir = $(if $(wildcard $(1)/),svn add --depth=empty $(1),svn mkdir $(1))
69
setSvnIgnore = svn propset svn:ignore $(2) $(1)
70
define addDirWithIgnore
71
$(addDir)
72
$(setSvnIgnore)
73
endef
74

    
75
##### General targets
76

    
77
all: _always maps ;
78

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

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

    
86
make_script = ./$< >$@
87

    
88
%/: % _always ;
89

    
90
# Must come before `%: %.make` to override it
91
%: %.make
92
	(set -x; "time" $(make_script)) 2>>$<.log
93
.PRECIOUS: % # save partial outputs of aborted src make scripts
94

    
95
##### SVN
96

    
97
add: _always
98
	$(call setSvnIgnore,.,'*')
99
	$(call addDirWithIgnore,verify,'*.out')
100
	$(call addFile,import_order.txt)
101

    
102
# Adds a new table subdir
103
%/add: _always
104
	$(call addDirWithIgnore,$*,'*')
105
	$(call addDirWithIgnore,$*/logs,$$'*.log.sql\n*.trace')
106

    
107
##### Existing maps discovery
108

    
109
sortFile := import_order.txt
110

    
111
tables := $(if $(wildcard $(sortFile)),$(shell cat $(sortFile)))
112
    # $(shell) replaces "\n" with " "
113
allSubdirs := $(call wildcard/,*/)
114
allTables := $(call sortFilenames,$(filter-out _% verify,$(allSubdirs:%/=%)))
115
joinedTables := $(filter-out $(tables),$(allTables))
116
allTables := $(joinedTables) $(tables)# move joined tables to beginning
117
ifeq ($(tables),)# none specified in sort file
118
tables := $(allTables)
119
endif
120

    
121
srcMaps := $(wildcard */src.csv)
122

    
123
srcMap := %/src.csv
124
viaMap := %/map.csv
125
fullViaMap := %/map.full.csv
126
directMap := %/VegBIEN.csv
127
anyMap := $(srcMap) $(viaMap) $(fullViaMap) $(directMap)
128

    
129
extsFilter := $(addprefix %.,$(exts))
130
dataOnly = $(filter $(extsFilter),$(1))
131

    
132
anyTest = $*/test.%
133
srcsOnly = $(filter-out $(anyMap) $(anyTest) %/logs,$(call dataOnly,$(1)))
134

    
135
via := Veg+
136

    
137
coreMap := $(mappings)/$(via)-VegBIEN.csv
138
coreSelfMap := $(mappings)/$(via).self.csv
139

    
140
viaMaps := $(wildcard $(tables:%=%/map.csv))
141
viaMaps += $(filter-out $(viaMaps),$(srcMaps:%/src.csv=%/map.csv))
142
viaMaps += $(filter-out $(viaMaps) $(fullViaMap),$(wildcard */map.csv))
143

    
144
autogenMaps := $(subst map.,VegBIEN.,$(viaMaps))
145
directMaps := $(autogenMaps) $(filter-out $(autogenMaps),\
146
$(wildcard */VegBIEN.csv))
147

    
148
##### Sources
149

    
150
srcs = $(call sortFilenames,$(call srcsOnly,$(wildcard $*/*)))
151
isCsv = $(if $(srcs),$(if $(filter %.xml,$(srcs)),,1))
152
    # true if $(srcs) non-empty and contains no *.xml
153
catSrcs = $(bin)/cat$(if $(isCsv),_csv) $(srcs)
154
withCatSrcs = $(catSrcs:$(bin)/%=$(bin)/with_%) --
155

    
156
# Usage: `make {--silent|-s} inputs/<datasrc>/cat` (don't echo make commands)
157
cat: $(tables:%=%/cat) _always ;
158

    
159
%/cat: _always
160
	$(catSrcs)
161

    
162
##### Staging tables installation
163

    
164
install: _always schema $(allTables:%=%/install) ;
165

    
166
uninstall: _always rm_schema ;
167
# rm_schema will also drop all staging tables
168

    
169
reinstall: _always uninstall install ;
170

    
171
schema: _always
172
	-echo 'CREATE SCHEMA "$(datasrc)";'|$(psqlAsBien)
173
# ignore errors if schema exists
174

    
175
rm_schema: _always
176
	echo 'DROP SCHEMA IF EXISTS "$(datasrc)" CASCADE;'|$(psqlAsBien)
177

    
178
# For staging tables which are derived by joining together other staging tables.
179
%/install %/header.csv: %/create.sql _always
180
	($(inDatasrc); echo 'CREATE TABLE "$*" AS'; cat $<; echo ';'; \
181
echo 'ALTER TABLE "$*" ADD COLUMN row_num serial NOT NULL PRIMARY KEY;'; \
182
echo 'VACUUM ANALYZE "$*";')|$(psqlAsBien) --echo-all
183
	(prefix=; . $(bin)/vegbien_dest; env schema=$(datasrc) table=$* \
184
errors_table_only=1 $(bin)/csv2db)
185
	echo 'SELECT * FROM "$(datasrc)"."$*" LIMIT 0;'|$(psqlAsBien) \
186
--no-align --field-separator=, --pset=footer=off >$*/header.csv
187

    
188
# The joined tables must be suffixed with ".src" to prevent the creation of a
189
# row_num column, which collides during joins.
190
isJoinedTable = $(filter %.src,$*)
191
hasRowNum = $(if $(isJoinedTable),,1)
192

    
193
%/install: _always
194
	$(if $(isCsv),$(import_install_))
195
import_install_ = (prefix=; . $(bin)/vegbien_dest; "time" nice -n +5\
196
env schema=$(datasrc) table=$* has_row_num=$(hasRowNum) $(bin)/csv2db\
197
$(catSrcs) $(if $(log),$(if $(quiet),&>,2>&1|tee )$*/logs/install.log.sql))
198

    
199
##### Maps building
200

    
201
# WARNING: You CANNOT make a subdir using `make inputs/<datasrc>/<subdir>/`.
202
# You must instead make the entire datasource dir: `make inputs/<datasrc>/`
203

    
204
# Maps to (try to) build are added to one of these
205
maps :=
206
createOnlyMaps :=
207

    
208
srcRoot = $(mappings)/root.sh
209
mkSrcMap = $(catSrcs)|(. $(srcRoot); env datasrc=$(datasrc) $(bin)/src_map >$@)
210

    
211
# Src maps cleanup
212
ifneq ($(filter %/.src.csv.last_cleanup,$(MAKECMDGOALS)),)
213
%/.src.csv.last_cleanup: %/src.csv
214
	$(bin)/in_place $< $(bin)/cols +
215
	touch $@
216
else
217
# Autogen src maps with known table names
218
%/src.csv: _always
219
	$(if $(wildcard $@),,$(if $(isCsv),$(mkSrcMap)))
220
	+$(if $(isCsv),$(selfMake) $(@:%/src.csv=%/.src.csv.last_cleanup))
221
# only build if doesn't exist
222
# only build if CSV srcs exist for that table name
223
endif
224

    
225
createOnlyMaps += $(tables:%=%/src.csv)
226

    
227
# Must come before $(root)/% to override it
228
$(coreSelfMap): _always
229
	-+$(subMake)
230
# ignore errors if $(coreSelfMap) does not exist
231

    
232
# Via maps cleanup
233
ifneq ($(filter %/.map.csv.last_cleanup,$(MAKECMDGOALS)),)
234
%/.map.csv.last_cleanup: %/map.csv $(coreMap)
235
	$(bin)/in_place $< env ignore=1 $(bin)/subtract $(word 2,$+) 0 1 2
236
	touch $@
237
# Include comment column so commented mappings are never removed
238
else
239
%/map.csv: %/src.csv _always
240
	$(if $(wildcard $@),,$(if $(wildcard $<),$(CP) $< $@))
241
	+$(selfMake) $(@:%/map.csv=%/.map.csv.last_cleanup)
242
endif
243

    
244
srcMap* = $*/src.csv
245
joinSrcMap = $(if $(hasSrc),$(bin)/in_place $@ $(bin)/intersect $(srcMap*) 0)
246
hasSrc = $(shell test -s $(word 3,$+) && echo t)
247

    
248
makeFullCsv = env ignore=1 $(bin)/union <$(wordlist 1,2,$+)|$(bin)/sort_map >$@
249

    
250
%/map.full.csv: %/map.csv $(coreSelfMap)
251
	$(makeFullCsv)
252
	$(joinSrcMap)
253
maps += $(patsubst %/map.csv,%/map.full.csv,$(viaMaps))
254

    
255
%/VegBIEN.csv: %/map.full.csv $(coreMap)
256
	$(bin)/join <$+|$(bin)/sort_map >$@
257
maps += $(autogenMaps)
258

    
259
maps: $(createOnlyMaps) $(maps) _always ;
260

    
261
all += $(maps)
262

    
263
##### Maps validation
264

    
265
missingMappingsCmd = +$(selfMake) remake 2>&1\
266
|$(SED) -n 's/^.*No $(*2Space) mapping for (.*)$$/\1/p'|$(SED) 's/\/_.*//'\
267
$(if $(filter non-empty_join,$*),|$(bin)/ucase_first 0)|sort|uniq
268

    
269
include $(root)/lib/mappings.Makefile
270

    
271
##### External dependencies
272

    
273
$(root)/%: _always
274
	+$(subMake)
275
.PRECIOUS: $(root)/% # let ext. dir's Makefile decide whether to delete on error
276

    
277
##### Mapping
278

    
279
+maps = $(filter %/map.csv %/VegBIEN.csv $(mappings)/%,$(+_))
280
map = $(if $(srcs),$(withCatSrcs) $(root)/map $(+maps),\
281
$(shell echo Warning: No input file $*/*.{$(exts)} >&2)false)
282
# need false to run some command, when prefixed by `env ...` below
283
map2db = $(if $(use_staged),env in_database=vegbien in_schema=$(datasrc)\
284
in_table=$*) env out_database=vegbien $(map)
285

    
286
##### Import to VegBIEN
287

    
288
profileTest = $(if $(profile),$(if $(test),1))
289
profileOnly = -env profile_to=/dev/fd/3 $(map2db) 3>&1 1>&2|\
290
$(bin)/profile_stats /dev/fd/0
291

    
292
log_ = $*/logs/$(if $(n),n=$(n).,)$(date).log.sql
293
trace = $(log_:.log.sql=.trace)
294
import = -$(if $(profileTest),$(profileOnly),(set -x; "time" env commit=1\
295
$(if $(profile),profile_to=$(trace)) $(map2db)) $(if $(log),\
296
$(if $(n),,&>$(log_)))$(if $(log),$(if $(n), 2>&1|tee -a $(log_))))
297
# don't abort on import errors, which often relate to invalid input data
298

    
299
import: $(tables:%=%/import) _always ;
300

    
301
%/import: %/VegBIEN.csv _always
302
	$(import)
303
# default:
304
%/import: _always ;
305

    
306
##### Log files from import
307

    
308
logs := $(wildcard */logs/*.log.sql */logs/*.trace)
309

    
310
rm_logs: _always
311
	$(RM) $(logs)
312

    
313
##### Verification of import
314

    
315
verify: $(tables:%=%/verify) _always ;
316

    
317
%/verify: verify/%.ref verify/%.out _always
318
	-$(diffVerbose) $(+_)
319
# don't abort on verification errors, which are expected during development
320
# default:
321
%/verify: verify/%.out _always
322
	$(if $(shell test -e $< && echo t),cat $<)
323
# don't run if verify/%.out's default do-nothing action was used
324
# can't use $(wildcard) because it won't recheck file after verify/%.out is run
325

    
326
psqlExport := "time" $(psqlAsBien) --no-align --field-separator=$$'\t'\
327
--pset=footer=off --pset=null=NULL
328
verify = $(if $(reverify),$(psqlExport) --set=datasource="'$(datasrc)'" <$< >$@)
329

    
330
verify/%.out: $(mappings)/verify.%.sql _always
331
	$(verify)
332
# default:
333
verify/%.out: _always ;
334

    
335
all += $(wildcard verify/*.out)
336

    
337
%.ref: %.ref.sql
338
	($(inDatasrc); cat $<)|$(psqlExport) >$@
339

    
340
##### Editing import
341

    
342
rotate: _always
343
	echo "UPDATE party SET organizationname = organizationname||'.$(date)'\
344
WHERE organizationname = '$(datasrc)';"|$(psqlAsBien)
345

    
346
rm: _always
347
	echo "DELETE FROM party WHERE organizationname = '$(datasrc)';"|\
348
$(psqlAsBien)
349

    
350
##### Testing
351

    
352
testRefOutput = $(subst .by_col,,$(1))
353
testRef = $(testRefOutput).ref
354
hasOwnRef = $(filter $@,$(call testRefOutput,$@))
355
# filter returns non-empty if they are equal
356

    
357
# `rm $@`: Remove outputs of successful tests to reduce clutter
358
# `$(foreach use_staged...)`: Run with use_staged=1
359
define runTest
360
@echo "Testing $(abspath $@)..."
361
>$@ env test=1 n=$(test_n) $(1) $(foreach use_staged,1,$(map2db))
362
@(set -x; $(diffIgnoreSpace) $(call testRef,$@) $@) 2>&1 && rm $@ || { e=$$?;\
363
$(if $(wildcard $(call testRef,$@)),,cat $@;)\
364
$(if $(hasOwnRef),\
365
{\
366
read -p $(emph)'Accept new test output? (y/n)'$(endEmph) REPLY;\
367
if test "$$REPLY" = y; then\
368
(set -x; $(MAKE) $@-ok --directory=$(realpath .) --makefile=../input.Makefile);\
369
exit 0;\
370
fi;\
371
};,\
372
echo $(emph)"Note: The preceding failed test is compared to another test's\
373
output"$(endEmph);\
374
echo $(emph)"When it fails, this always indicates a bug"$(endEmph);\
375
)\
376
exit $$e;}
377
endef
378

    
379
tests :=
380

    
381
# Requires staging tables. To create them, run `make inputs/<datasrc>/install`.
382
# Non-flat-file inputs fall back to mimicking a successful test
383
%/test.xml: %/VegBIEN.csv _always
384
	$(if $(isCsv),$(call runTest,by_col=))
385
tests += %/test.xml
386

    
387
%/test.by_col.xml: %/VegBIEN.csv _always
388
	-$(if $(isCsv),$(call runTest,by_col=1))
389
# Don't abort tester if only by-column test fails
390

    
391
# Only run column-based tests if column-based mode enabled, because these tests
392
# are much slower than the row-based tests for small numbers of rows
393
ifneq ($(by_col),)
394
tests += %/test.by_col.xml
395
endif
396

    
397
testOutputs := $(foreach test,$(tests),$(tables:%=$(test)))
398

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

    
401
test: _always $(testOutputs) ;
402

    
403
all += $(wildcard %/test*.xml)
404

    
405
# Accepts a test output: make <test_output_path>-ok
406
%-ok: _always
407
	mv $* $(call testRef,$*)
408

    
409
accept-all: _always
410
	+yes|$(selfMake) test
411

    
412
##### Documentation
413

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

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