Temp Table Creation improvements
[cps.git] / cps-ri / src / main / java / org / onap / cps / spi / repository / TempTableCreator.java
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2022 Nordix Foundation.
4  * ================================================================================
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *      http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  *
17  * SPDX-License-Identifier: Apache-2.0
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.cps.spi.repository;
22
23 import java.util.Arrays;
24 import java.util.Collection;
25 import java.util.HashSet;
26 import java.util.Iterator;
27 import java.util.List;
28 import java.util.UUID;
29 import javax.persistence.EntityManager;
30 import javax.persistence.PersistenceContext;
31 import lombok.AllArgsConstructor;
32 import lombok.extern.slf4j.Slf4j;
33 import org.springframework.stereotype.Component;
34 import org.springframework.transaction.annotation.Transactional;
35
36 @Slf4j
37 @Transactional
38 @AllArgsConstructor
39 @Component
40 public class TempTableCreator {
41
42     @PersistenceContext
43     private EntityManager entityManager;
44
45     /**
46      * Create a uniquely named temporary table.
47      *
48      * @param prefix      prefix for the table name (so you can recognize it)
49      * @param sqlData     data to insert (strings only) the inner List present a row of data
50      * @param columnNames column names (in same order as data in rows in sqlData)
51      * @return a unique temporary table name with given prefix
52      */
53     public String createTemporaryTable(final String prefix,
54                                        final Collection<List<String>> sqlData,
55                                        final String... columnNames) {
56         final String tempTableName = prefix + UUID.randomUUID().toString().replace("-", "");
57         final StringBuilder sqlStringBuilder = new StringBuilder("CREATE TEMPORARY TABLE ");
58         sqlStringBuilder.append(tempTableName);
59         defineColumns(sqlStringBuilder, columnNames);
60         insertData(sqlStringBuilder, tempTableName, columnNames, sqlData);
61         entityManager.createNativeQuery(sqlStringBuilder.toString()).executeUpdate();
62         return tempTableName;
63     }
64
65     private static void defineColumns(final StringBuilder sqlStringBuilder, final String[] columnNames) {
66         sqlStringBuilder.append('(');
67         final Iterator<String> it = Arrays.stream(columnNames).iterator();
68         while (it.hasNext()) {
69             final String columnName = it.next();
70             sqlStringBuilder.append(" ");
71             sqlStringBuilder.append(columnName);
72             sqlStringBuilder.append(" varchar NOT NULL");
73             if (it.hasNext()) {
74                 sqlStringBuilder.append(",");
75             }
76         }
77         sqlStringBuilder.append(");");
78     }
79
80     private static void insertData(final StringBuilder sqlStringBuilder,
81                                    final String tempTableName,
82                                    final String[] columnNames,
83                                    final Collection<List<String>> sqlData) {
84         final Collection<String> sqlInserts = new HashSet<>(sqlData.size());
85         for (final Collection<String> row : sqlData) {
86             sqlInserts.add("('" + String.join("','", row) + "')");
87         }
88         sqlStringBuilder.append("INSERT INTO ");
89         sqlStringBuilder.append(tempTableName);
90         sqlStringBuilder.append(" (");
91         sqlStringBuilder.append(String.join(",", columnNames));
92         sqlStringBuilder.append(") VALUES ");
93         sqlStringBuilder.append(String.join(",", sqlInserts));
94         sqlStringBuilder.append(";");
95     }
96
97 }