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
	(echo 'SET search_path TO "$(datasrc)";'; echo 'CREATE TABLE "$*" AS';\
181
cat $<; echo ';'; \
182
echo 'ALTER TABLE "$*" ADD COLUMN row_num serial NOT NULL PRIMARY KEY;'; \
183
echo 'VACUUM ANALYZE "$*";')|$(psqlAsBien) --echo-all
184
	(prefix=; . $(bin)/vegbien_dest; env schema=$(datasrc) table=$* \
185
errors_table_only=1 $(bin)/csv2db)
186
	echo 'SELECT * FROM "$(datasrc)"."$*" LIMIT 0;'|$(psqlAsBien) \
187
--no-align --field-separator=, --pset=footer=off >$*/header.csv
188

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

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

    
200
##### Maps building
201

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

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

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

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

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

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

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

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

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

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

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

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

    
262
all += $(maps)
263

    
264
##### Maps validation
265

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

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

    
272
##### External dependencies
273

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

    
278
##### Mapping
279

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

    
287
##### Import to VegBIEN
288

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

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

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

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

    
307
##### Log files from import
308

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

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

    
314
##### Verification of import
315

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

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

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

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

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

    
338
%.ref: %.ref.sql
339
	(echo 'SET search_path TO "$(datasrc)";'; cat $<)|$(psqlExport) >$@
340

    
341
##### Editing import
342

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

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

    
351
##### Testing
352

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

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

    
380
tests :=
381

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

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

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

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

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

    
402
test: _always $(testOutputs) ;
403

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

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

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

    
413
##### Documentation
414

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

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