1 package com.github.davidmoten.rx.jdbc;
2
3 import static com.github.davidmoten.rx.RxUtil.concatButIgnoreFirstSequence;
4 import static com.github.davidmoten.rx.jdbc.Util.TO_EMPTY_PARAMETER_LIST;
5
6 import java.util.ArrayList;
7 import java.util.Arrays;
8 import java.util.List;
9 import java.util.Map;
10 import java.util.Map.Entry;
11
12 import rx.Observable;
13 import rx.functions.Func1;
14
15
16
17
18 final class Queries {
19
20 private static final Func1<Parameter, Observable<Parameter>> FLATTEN_NAMED_MAPS = new Func1<Parameter, Observable<Parameter>>() {
21
22 @SuppressWarnings("unchecked")
23 @Override
24 public Observable<Parameter> call(Parameter p) {
25 if (p.value() instanceof Map) {
26 List<Parameter> list = new ArrayList<Parameter>();
27 for (Entry<String, ?> entry : ((Map<String, ?>) p.value()).entrySet()) {
28 list.add(new Parameter(entry.getKey(), entry.getValue()));
29 }
30 return Observable.from(list);
31 } else
32 return Observable.from(Arrays.asList(p));
33 }
34 };
35
36
37
38
39 private Queries() {
40
41 }
42
43
44
45
46
47
48
49
50 static int numParamsPerQuery(Query query) {
51 return Util.parametersCount(query);
52 }
53
54
55
56
57
58
59
60 static Observable<Parameter> parametersAfterDependencies(Query query) {
61 return concatButIgnoreFirstSequence(query.depends(), query.parameters());
62 }
63
64
65
66
67
68
69
70
71
72 static Observable<Integer> singleIntegerAfterDependencies(Query query) {
73 return concatButIgnoreFirstSequence(query.depends(), Observable.just(1));
74 }
75
76
77
78
79
80
81
82
83
84
85 static Observable<List<Parameter>> bufferedParameters(Query query) {
86 int numParamsPerQuery = numParamsPerQuery(query);
87 if (numParamsPerQuery > 0)
88
89
90 return parametersAfterDependencies(query)
91 .concatMap(FLATTEN_NAMED_MAPS)
92 .buffer(numParamsPerQuery);
93 else
94 return singleIntegerAfterDependencies(query).map(TO_EMPTY_PARAMETER_LIST);
95 }
96
97 }