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
##### Environment
76

    
77
export PATH := $(bin):$(PATH)
78

    
79
##### General targets
80

    
81
all: _always maps ;
82

    
83
clean: _always
84
	$(RM) $(all)
85

    
86
remake: _always clean
87
	+$(selfMake)
88
# re-run make so that cache of existing files is reset
89

    
90
make_script = ./$< >$@
91

    
92
%/: % _always ;
93

    
94
%: %.make
95
	$(if $(wildcard $@),,"time" $(make_script))
96
# Only remake if doesn't exist. This prevents unintentional remaking when the
97
# make script is newly checked out from svn (which sets the mod time to now) but
98
# the output is synced externally.
99
# Can't remove prereq to do this, because it determines when the rule applies.
100
.PRECIOUS: % # save partial outputs of aborted src make scripts
101

    
102
##### SVN
103

    
104
add: _always
105
	$(call setSvnIgnore,.,'*')
106
	$(call addDirWithIgnore,verify,'*.out')
107
	$(call addFile,import_order.txt)
108

    
109
# Adds a new table subdir
110
%/add: _always
111
	$(call addDirWithIgnore,$*,'*')
112
	$(call addDirWithIgnore,$*/logs,$$'*.log.sql\n*.trace')
113

    
114
##### Existing maps discovery
115

    
116
sortFile := import_order.txt
117

    
118
tables := $(if $(wildcard $(sortFile)),$(shell cat $(sortFile)))
119
    # $(shell) replaces "\n" with " "
120
allSubdirs := $(call wildcard/,*/)
121
allTables := $(call sortFilenames,$(filter-out _% verify,$(allSubdirs:%/=%)))
122
joinedTables := $(filter-out $(tables),$(allTables))
123
allTables := $(joinedTables) $(tables)# move joined tables to beginning
124
ifeq ($(tables),)# none specified in sort file
125
tables := $(allTables)
126
endif
127

    
128
srcMaps := $(wildcard */src.csv)
129

    
130
srcMap := %/src.csv
131
viaMap := %/map.csv
132
fullViaMap := %/map.full.csv
133
directMap := %/VegBIEN.csv
134
anyMap := $(srcMap) $(viaMap) $(fullViaMap) $(directMap)
135

    
136
extsFilter := $(addprefix %.,$(exts))
137
dataOnly = $(filter $(extsFilter),$(1))
138

    
139
anyTest = $*/test.%
140
srcsOnly = $(filter-out $(anyMap) $(anyTest) %/logs,$(call dataOnly,$(1)))
141

    
142
via := Veg+
143

    
144
coreMap := $(mappings)/$(via)-VegBIEN.csv
145
coreSelfMap := $(mappings)/$(via).self.csv
146

    
147
viaMaps := $(wildcard $(tables:%=%/map.csv))
148
viaMaps += $(filter-out $(viaMaps),$(srcMaps:%/src.csv=%/map.csv))
149
viaMaps += $(filter-out $(viaMaps) $(fullViaMap),$(wildcard */map.csv))
150

    
151
autogenMaps := $(subst map.,VegBIEN.,$(viaMaps))
152
directMaps := $(autogenMaps) $(filter-out $(autogenMaps),\
153
$(wildcard */VegBIEN.csv))
154

    
155
##### Sources
156

    
157
srcs = $(call sortFilenames,$(call srcsOnly,$(wildcard $*/*)))
158
isCsv = $(if $(srcs),$(if $(filter %.xml,$(srcs)),,1))
159
    # true if $(srcs) non-empty and contains no *.xml
160
catSrcs = $(bin)/cat$(if $(isCsv),_csv) $(srcs)
161
withCatSrcs = $(catSrcs:$(bin)/%=$(bin)/with_%) --
162

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

    
166
%/cat: _always
167
	$(catSrcs)
168

    
169
##### Staging tables installation
170

    
171
dbExports := $(filter-out %.my.sql,$(wildcard *.sql))
172
allInstalls := $(dbExports) $(allTables)
173

    
174
install: _always schema $(allInstalls:%=%/install) ;
175

    
176
uninstall: _always rm_schema ;
177
# rm_schema will also drop all staging tables
178

    
179
reinstall: _always uninstall install ;
180

    
181
schema: _always
182
	-echo 'CREATE SCHEMA "$(datasrc)";'|$(psqlAsBien)
183
# ignore errors if schema exists
184

    
185
rm_schema: _always
186
	echo 'DROP SCHEMA IF EXISTS "$(datasrc)" CASCADE;'|$(psqlAsBien)
187

    
188
# Must come before %/install to override it
189
%.sql/install: %.sql _always
190
	($(inDatasrc); grep -vF 'SET search_path' $<)|"time" $(psqlAsBien)
191

    
192
# The export must be created with:
193
# `--compatible=postgresql --add-locks=false --set-charset`
194
%.pg.sql: %.my.sql
195
	$(bin)/my2pg <$< >$@
196

    
197
# For staging tables which are derived by joining together other staging tables.
198
%/install %/header.csv: %/create.sql _always
199
	($(inDatasrc); echo 'CREATE TABLE "$*" AS'; cat $<; echo ';'; \
200
echo 'ALTER TABLE "$*" ADD COLUMN row_num serial NOT NULL PRIMARY KEY;'; \
201
echo 'VACUUM ANALYZE "$*";')|$(psqlAsBien) --echo-all
202
	(prefix=; . $(bin)/vegbien_dest; env schema=$(datasrc) table=$* \
203
errors_table_only=1 $(bin)/csv2db)
204
	echo 'SELECT * FROM "$(datasrc)"."$*" LIMIT 0;'|$(psqlAsBien) \
205
--no-align --field-separator=, --pset=footer=off >$*/header.csv
206

    
207
# The joined tables must be suffixed with ".src" to prevent the creation of a
208
# row_num column, which collides during joins.
209
isJoinedTable = $(filter %.src,$*)
210
hasRowNum = $(if $(isJoinedTable),,1)
211

    
212
%/install: _always
213
	$(if $(isCsv),$(import_install_))
214
import_install_ = (prefix=; . $(bin)/vegbien_dest; "time" nice -n +5\
215
env schema=$(datasrc) table=$* has_row_num=$(hasRowNum) $(bin)/csv2db\
216
$(catSrcs) $(if $(log),$(if $(quiet),&>,2>&1|tee )$*/logs/install.log.sql))
217

    
218
##### Maps building
219

    
220
# WARNING: You CANNOT make a subdir using `make inputs/<datasrc>/<subdir>/`.
221
# You must instead make the entire datasource dir: `make inputs/<datasrc>/`
222

    
223
# Maps to (try to) build are added to one of these
224
maps :=
225
createOnlyMaps :=
226

    
227
srcRoot = $(mappings)/root.sh
228
mkSrcMap = $(catSrcs)|(. $(srcRoot); env datasrc=$(datasrc) $(bin)/src_map >$@)
229

    
230
# Src maps cleanup
231
ifneq ($(filter %/.src.csv.last_cleanup,$(MAKECMDGOALS)),)
232
%/.src.csv.last_cleanup: %/src.csv
233
	$(bin)/in_place $< $(bin)/cols +
234
	touch $@
235
else
236
# Autogen src maps with known table names
237
%/src.csv: _always
238
	$(if $(wildcard $@),,$(if $(isCsv),$(mkSrcMap)))
239
	+$(if $(isCsv),$(selfMake) $(@:%/src.csv=%/.src.csv.last_cleanup))
240
# only build if doesn't exist
241
# only build if CSV srcs exist for that table name
242
endif
243

    
244
createOnlyMaps += $(tables:%=%/src.csv)
245

    
246
# Must come before $(root)/% to override it
247
$(coreSelfMap): _always
248
	-+$(subMake)
249
# ignore errors if $(coreSelfMap) does not exist
250

    
251
# Via maps cleanup
252
ifneq ($(filter %/.map.csv.last_cleanup,$(MAKECMDGOALS)),)
253
%/.map.csv.last_cleanup: %/map.csv $(coreMap)
254
	$(bin)/in_place $< env ignore=1 $(bin)/subtract $(word 2,$+) 0 1 2
255
	touch $@
256
# Include comment column so commented mappings are never removed
257
else
258
%/map.csv: %/src.csv _always
259
	$(if $(wildcard $@),,$(if $(wildcard $<),$(CP) $< $@))
260
	+$(selfMake) $(@:%/map.csv=%/.map.csv.last_cleanup)
261
endif
262

    
263
srcMap* = $*/src.csv
264
joinSrcMap = $(if $(hasSrc),$(bin)/in_place $@ $(bin)/intersect $(srcMap*) 0)
265
hasSrc = $(shell test -s $(word 3,$+) && echo t)
266

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

    
269
%/map.full.csv: %/map.csv $(coreSelfMap)
270
	$(makeFullCsv)
271
	$(joinSrcMap)
272
maps += $(patsubst %/map.csv,%/map.full.csv,$(viaMaps))
273

    
274
%/VegBIEN.csv: %/map.full.csv $(coreMap)
275
	$(bin)/join <$+|$(bin)/sort_map >$@
276
maps += $(autogenMaps)
277

    
278
maps: $(createOnlyMaps) $(maps) _always ;
279

    
280
all += $(maps)
281

    
282
##### Maps validation
283

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

    
288
include $(root)/lib/mappings.Makefile
289

    
290
##### External dependencies
291

    
292
$(root)/%: _always
293
	+$(subMake)
294
.PRECIOUS: $(root)/% # let ext. dir's Makefile decide whether to delete on error
295

    
296
##### Mapping
297

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

    
305
##### Import to VegBIEN
306

    
307
profileTest = $(if $(profile),$(if $(test),1))
308
profileOnly = -env profile_to=/dev/fd/3 $(map2db) 3>&1 1>&2|\
309
$(bin)/profile_stats /dev/fd/0
310

    
311
log_ = $*/logs/$(if $(n),n=$(n).,)$(date).log.sql
312
trace = $(log_:.log.sql=.trace)
313
import = -$(if $(profileTest),$(profileOnly),(set -x; "time" env commit=1\
314
$(if $(profile),profile_to=$(trace)) $(map2db)) $(if $(log),\
315
$(if $(n),,&>$(log_)))$(if $(log),$(if $(n), 2>&1|tee -a $(log_))))
316
# don't abort on import errors, which often relate to invalid input data
317

    
318
import: $(tables:%=%/import) _always ;
319

    
320
%/import: %/VegBIEN.csv _always
321
	$(import)
322
# default:
323
%/import: _always ;
324

    
325
##### Log files from import
326

    
327
logs := $(wildcard */logs/*.log.sql */logs/*.trace)
328

    
329
rm_logs: _always
330
	$(RM) $(logs)
331

    
332
##### Verification of import
333

    
334
verify: $(tables:%=%/verify) _always ;
335

    
336
%/verify: verify/%.ref verify/%.out _always
337
	-$(diffVerbose) $(+_)
338
# don't abort on verification errors, which are expected during development
339
# default:
340
%/verify: verify/%.out _always
341
	$(if $(shell test -e $< && echo t),cat $<)
342
# don't run if verify/%.out's default do-nothing action was used
343
# can't use $(wildcard) because it won't recheck file after verify/%.out is run
344

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

    
349
verify/%.out: $(mappings)/verify.%.sql _always
350
	$(verify)
351
# default:
352
verify/%.out: _always ;
353

    
354
all += $(wildcard verify/*.out)
355

    
356
%.ref: %.ref.sql
357
	($(inDatasrc); cat $<)|$(psqlExport) >$@
358

    
359
##### Editing import
360

    
361
rotate: _always
362
	echo "UPDATE party SET organizationname = organizationname||'.$(date)'\
363
WHERE organizationname = '$(datasrc)';"|$(psqlAsBien)
364

    
365
rm: _always
366
	echo "DELETE FROM party WHERE organizationname = '$(datasrc)';"|\
367
$(psqlAsBien)
368

    
369
##### Testing
370

    
371
testRefOutput = $(subst .by_col,,$(1))
372
testRef = $(testRefOutput).ref
373
hasOwnRef = $(filter $@,$(call testRefOutput,$@))
374
# filter returns non-empty if they are equal
375

    
376
# `rm $@`: Remove outputs of successful tests to reduce clutter
377
# `$(foreach use_staged...)`: Run with use_staged=1
378
define runTest
379
@echo "Testing $(abspath $@)..."
380
>$@ env test=1 n=$(test_n) $(1) $(foreach use_staged,1,$(map2db))
381
@(set -x; $(diffIgnoreSpace) $(call testRef,$@) $@) 2>&1 && rm $@ || { e=$$?;\
382
$(if $(wildcard $(call testRef,$@)),,cat $@;)\
383
$(if $(hasOwnRef),\
384
{\
385
read -p $(emph)'Accept new test output? (y/n)'$(endEmph) REPLY;\
386
if test "$$REPLY" = y; then\
387
(set -x; $(MAKE) $@-ok --directory=$(realpath .) --makefile=../input.Makefile);\
388
exit 0;\
389
fi;\
390
};,\
391
echo $(emph)"Note: The preceding failed test is compared to another test's\
392
output"$(endEmph);\
393
echo $(emph)"When it fails, this always indicates a bug"$(endEmph);\
394
)\
395
exit $$e;}
396
endef
397

    
398
tests :=
399

    
400
# Requires staging tables. To create them, run `make inputs/<datasrc>/install`.
401
# Non-flat-file inputs fall back to mimicking a successful test
402
%/test.xml: %/VegBIEN.csv _always
403
	$(if $(isCsv),$(call runTest,by_col=))
404
tests += %/test.xml
405

    
406
%/test.by_col.xml: %/VegBIEN.csv _always
407
	-$(if $(isCsv),$(call runTest,by_col=1))
408
# Don't abort tester if only by-column test fails
409

    
410
# Only run column-based tests if column-based mode enabled, because these tests
411
# are much slower than the row-based tests for small numbers of rows
412
ifneq ($(by_col),)
413
tests += %/test.by_col.xml
414
endif
415

    
416
testOutputs := $(foreach test,$(tests),$(tables:%=$(test)))
417

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

    
420
test: _always $(testOutputs) ;
421

    
422
all += $(wildcard %/test*.xml)
423

    
424
# Accepts a test output: make <test_output_path>-ok
425
%-ok: _always
426
	mv $* $(call testRef,$*)
427

    
428
accept-all: _always
429
	+yes|$(selfMake) test
430

    
431
##### Documentation
432

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

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