Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

Generator.java 10.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  1. package com.rthoni.intellij.codefromds.business;
  2. import com.intellij.database.psi.DbDataSource;
  3. import com.intellij.openapi.project.Project;
  4. import com.rthoni.intellij.codefromds.dbo.options.*;
  5. import com.rthoni.intellij.codefromds.dbo.template.*;
  6. import groovy.json.StringEscapeUtils;
  7. import org.json.JSONArray;
  8. import org.json.JSONObject;
  9. import org.jtwig.JtwigModel;
  10. import org.jtwig.JtwigTemplate;
  11. import org.jtwig.environment.EnvironmentConfiguration;
  12. import org.jtwig.environment.EnvironmentConfigurationBuilder;
  13. import org.jtwig.functions.FunctionRequest;
  14. import org.jtwig.functions.SimpleJtwigFunction;
  15. import java.io.File;
  16. import java.io.FileOutputStream;
  17. import java.io.IOException;
  18. import java.util.HashMap;
  19. import java.util.List;
  20. import java.util.Vector;
  21. /**
  22. * Created by robin on 11/15/16.
  23. */
  24. public abstract class Generator {
  25. public static void saveOptions(GenerateOptions options) throws Exception
  26. {
  27. HashMap<String, Object> map = options.toMap();
  28. JSONObject obj = new JSONObject(map);
  29. FileOutputStream file = new FileOutputStream(options.getConfigAbsolutePath());
  30. file.write(obj.toString(4).getBytes());
  31. file.close();
  32. }
  33. public static GenerateOptions loadOptions(String configPath) throws Exception
  34. {
  35. String data = Helper.readFile(configPath);
  36. JSONObject obj = new JSONObject(data);
  37. String src = obj.getJSONObject("selection").getString("source");
  38. DbDataSource dataSource = Helper.findDataSource(src);
  39. if (dataSource == null) {
  40. throw new Exception("Data source " + src + " not found");
  41. }
  42. GenerateOptions options = new GenerateOptions(DataSourcesBusiness.getDataSourceDbo(src), configPath);
  43. options.setConfigAbsolutePath(configPath);
  44. options.fromJson(obj);
  45. return options;
  46. }
  47. public static String escapeReservedWords(String id, TypesCastOptions options)
  48. {
  49. if (options.getReservedWords().contains(id)) {
  50. return "_" + id;
  51. }
  52. return id;
  53. }
  54. public static String escapeString(String str)
  55. {
  56. return StringEscapeUtils.escapeJava(str);
  57. }
  58. public static void convertSqlType(SqlTypeDbo type, TypesCastOptions options, DataSourceDbo dataSourceDbo)
  59. {
  60. if (type == null) {
  61. return;
  62. }
  63. boolean isArray = type.getType().endsWith("[]");
  64. boolean isSetOf = type.getType().startsWith("setof ");
  65. String sqlTypeName = isArray ? type.getType().substring(0, type.getType().length() - 2) : type.getType();
  66. if (isSetOf)
  67. {
  68. sqlTypeName = sqlTypeName.substring(6);
  69. }
  70. String typeName = null;
  71. HashMap<String, HashMap<String, String>> types = options.getTypes();
  72. if (types.containsKey(sqlTypeName)) {
  73. HashMap<String, String> subtype = types.get(sqlTypeName);
  74. if (subtype.containsKey(type.getVagueArg())) {
  75. typeName = subtype.get(type.getVagueArg());
  76. }
  77. else if (subtype.containsKey("*")) {
  78. typeName = subtype.get("*");
  79. }
  80. }
  81. if (typeName == null) {
  82. TableDataSourceDbo table = dataSourceDbo.findTable(sqlTypeName);
  83. if (table == null) {
  84. typeName = types.get("*").get("*");
  85. }
  86. else {
  87. typeName = table.getName();
  88. }
  89. }
  90. if (isArray) {
  91. typeName = options.getArrayTemplate().replace("%t", typeName);
  92. }
  93. if (isSetOf) {
  94. typeName = options.getSetOfTemplate().replace("%t", typeName);
  95. }
  96. type.setLanguageType(typeName);
  97. type.setLanguageTypeNotNull(options.getNonNullableTypes().contains(typeName));
  98. }
  99. // public static boolean isUnionSame(List<ColumnDataSourceDbo> part1, List<ColumnDataSourceDbo> part2, List<ColumnDataSourceDbo> list2)
  100. // {
  101. // List<ColumnDataSourceDbo> list1 = new Vector<>(part1);
  102. // for (ColumnDataSourceDbo col : part2) {
  103. // if (!list1.contains(col)) {
  104. // list1.add(col);
  105. // }
  106. // }
  107. // if (list1.size() != list2.size()) {
  108. // return false;
  109. // }
  110. // list1.sort((o1, o2) -> o1.getName().compareTo(o2.getName()));
  111. // list2.sort((o1, o2) -> o1.getName().compareTo(o2.getName()));
  112. // return list1.equals(list2);
  113. // }
  114. public static void convertOptions(GenerateOptions options, TypesCastOptions types)
  115. {
  116. for (TableDataSourceDbo table : options.getDataSource().getTables())
  117. {
  118. for (ColumnDataSourceDbo column : table.getColumns())
  119. {
  120. convertSqlType(column.getSqlType(), types, options.getDataSource());
  121. }
  122. }
  123. for (StoredProcedureDbo spDbo : options.getDataSource().getStoredProcedures())
  124. {
  125. convertSqlType(spDbo.getSqlType(), types, options.getDataSource());
  126. for (StoredProcedureArgDbo arg : spDbo.getArguments()) {
  127. convertSqlType(arg.getSqlType(), types, options.getDataSource());
  128. }
  129. }
  130. }
  131. public static TypesCastOptions loadTypesCast(String file) throws IOException
  132. {
  133. TypesCastOptions dbo = new TypesCastOptions();
  134. String data = Helper.readFile(file);
  135. JSONObject obj = new JSONObject(data);
  136. JSONObject objTypes = obj.getJSONObject("types");
  137. HashMap<String, HashMap<String, String>> map = new HashMap<>();
  138. for (String key : objTypes.keySet()) {
  139. HashMap<String, String> typeMap = new HashMap<>();
  140. String type = objTypes.optString(key);
  141. JSONObject typeObject = objTypes.optJSONObject(key);
  142. if (typeObject != null) {
  143. for (String subtype : typeObject.keySet()) {
  144. typeMap.put(subtype, typeObject.getString(subtype));
  145. }
  146. }
  147. else if (type != null) {
  148. typeMap.put("*", type);
  149. }
  150. map.put(key, typeMap);
  151. }
  152. dbo.setTypes(map);
  153. List<String> nonNullableTypes = new Vector<>();
  154. JSONArray array = obj.getJSONArray("non-nullable-types");
  155. for (int i = 0; i < array.length(); ++i) {
  156. nonNullableTypes.add(array.getString(i));
  157. }
  158. dbo.setNonNullableTypes(nonNullableTypes);
  159. List<String> reservedWords = new Vector<>();
  160. array = obj.getJSONArray("reserved-words");
  161. for (int i = 0; i < array.length(); ++i) {
  162. reservedWords.add(array.getString(i));
  163. }
  164. dbo.setReservedWords(reservedWords);
  165. dbo.setArrayTemplate(obj.getString("arrayTemplate"));
  166. dbo.setSetOfTemplate(obj.getString("setOfTemplate"));
  167. return dbo;
  168. }
  169. public static void generateFile(String templatePath, String outputFile, DataSourceDbo dataSource,
  170. TableDataSourceDbo table, TypesCastOptions options) throws IOException
  171. {
  172. String data = Helper.readFile(templatePath);
  173. FileOutputStream file = new FileOutputStream(outputFile);
  174. final SimpleJtwigFunction escapeReservedWords = new SimpleJtwigFunction() {
  175. @Override
  176. public String name() {
  177. return "escapeReservedWords";
  178. }
  179. @Override
  180. public Object execute(FunctionRequest functionRequest) {
  181. Object obj = functionRequest.get(0);
  182. if (obj == null)
  183. {
  184. return null;
  185. }
  186. String arg = (String) obj;
  187. String v = escapeReservedWords(arg, options);
  188. return v;
  189. }
  190. };
  191. final SimpleJtwigFunction escapeString = new SimpleJtwigFunction() {
  192. @Override
  193. public String name() {
  194. return "escapeString";
  195. }
  196. @Override
  197. public Object execute(FunctionRequest functionRequest) {
  198. Object obj = functionRequest.get(0);
  199. if (obj == null)
  200. {
  201. return null;
  202. }
  203. String arg = (String) obj;
  204. String v = escapeString(arg);
  205. return v;
  206. }
  207. };
  208. final EnvironmentConfiguration configuration = EnvironmentConfigurationBuilder
  209. .configuration()
  210. .functions()
  211. .add(escapeReservedWords)
  212. .add(escapeString)
  213. .and()
  214. .build();
  215. JtwigTemplate template = JtwigTemplate.inlineTemplate(data, configuration);
  216. JtwigModel model = JtwigModel.newModel()
  217. .with("dataSource", dataSource)
  218. .with("table", table);
  219. template.render(model, file);
  220. file.close();
  221. }
  222. public static void generate(GenerateOptions options, Project project) throws IOException
  223. {
  224. DataSourcesBusiness.getDataSourcesDbo();
  225. String modelsAbsolutePath = Helper.getAbsolutePath(project, options.getModelsRelativePath());
  226. String dataSourceTemplateAbsolutePath = Helper.getAbsolutePath(project, options.getDataSourceTemplateRelativePath());
  227. String modelsTemplateAbsolutePath = Helper.getAbsolutePath(project, options.getModelsTemplateRelativePath());
  228. String typesCastAbsolutePath = Helper.getAbsolutePath(project, options.getCastFileRelativePath());
  229. String dataSourceAbsolutePath = Helper.getAbsolutePath(project, options.getDataSourceRelativePath());
  230. TypesCastOptions types = loadTypesCast(typesCastAbsolutePath);
  231. convertOptions(options, types);
  232. generateFile(dataSourceTemplateAbsolutePath, dataSourceAbsolutePath, options.getDataSource(), null, types);
  233. for (TableDataSourceDbo table : options.getDataSource().getTables()) {
  234. if (table.hasAny()) {
  235. String filename = modelsAbsolutePath + File.separator + table.getName() + "." + options.getFilesExtension();
  236. generateFile(modelsTemplateAbsolutePath, filename, options.getDataSource(), table, types);
  237. }
  238. }
  239. }
  240. }