projection-mapper.vala 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465
  1. using Invercargill.DataStructures;
  2. namespace InvercargillSql.Orm.Projections {
  3. /**
  4. * Materializes projection results from database rows.
  5. *
  6. * ProjectionMapper takes the results of a projection query (as Properties collections)
  7. * and materializes them into projection objects. It handles:
  8. * - Simple scalar properties (int, string, double, etc.)
  9. * - Nested projection objects (select_one) - limited support
  10. * - Collection properties (select_many) - placeholder for future implementation
  11. *
  12. * The mapper uses the ProjectionDefinition to determine how to map each column
  13. * to the corresponding property on the projection type.
  14. *
  15. * Example usage:
  16. * {{{
  17. * var mapper = new ProjectionMapper<UserStats>(definition);
  18. * var results = mapper.map_all(query_results);
  19. * }}}
  20. *
  21. * @param TProjection The projection result type
  22. */
  23. public class ProjectionMapper<TProjection> : Object {
  24. /**
  25. * The projection definition containing selection mappings.
  26. */
  27. private ProjectionDefinition _mapper_definition;
  28. /**
  29. * Creates a new ProjectionMapper for the given definition.
  30. *
  31. * @param definition The ProjectionDefinition describing how to map results
  32. */
  33. public ProjectionMapper(ProjectionDefinition definition) {
  34. _mapper_definition = definition;
  35. }
  36. /**
  37. * Creates a new instance of the projection type.
  38. *
  39. * Uses GObject's Object.new() to create instances.
  40. *
  41. * @return A new TProjection instance
  42. * @throws ProjectionError if instance creation fails
  43. */
  44. public TProjection create_instance() throws ProjectionError {
  45. var type = typeof(TProjection);
  46. if (type.is_object()) {
  47. var obj = Object.new(type);
  48. // In Vala, we can't use 'as TProjection' directly for generics
  49. // Instead, we return the object and rely on the type system
  50. return (TProjection)obj;
  51. }
  52. throw new ProjectionError.NESTED_RESOLUTION_FAILED(
  53. @"Failed to create instance of type $(type.name())"
  54. );
  55. }
  56. /**
  57. * Maps a single database row to a projection instance.
  58. *
  59. * This method takes a Properties collection (representing a database row)
  60. * and creates a new TProjection instance with all properties populated.
  61. *
  62. * @param row The Properties collection from a database query
  63. * @return A new TProjection instance
  64. * @throws ProjectionError if mapping fails
  65. */
  66. public TProjection map_row(Invercargill.Properties row) throws ProjectionError {
  67. var instance = create_instance();
  68. var obj = instance as Object;
  69. if (obj == null) {
  70. throw new ProjectionError.NESTED_RESOLUTION_FAILED(
  71. "Projection instance is not a GObject"
  72. );
  73. }
  74. // Map each selection from the definition
  75. foreach (var selection in _mapper_definition.selections) {
  76. map_selection_to_object(obj, selection, row);
  77. }
  78. return instance;
  79. }
  80. /**
  81. * Maps all rows to projection instances.
  82. *
  83. * This method iterates through all rows in the result set and
  84. * materializes each one as a TProjection instance.
  85. *
  86. * For projections with collections (select_many), this method also
  87. * performs client-side grouping to consolidate related rows.
  88. *
  89. * @param results An Enumerable of Properties collections
  90. * @return A Vector of TProjection instances
  91. * @throws ProjectionError if mapping fails
  92. */
  93. public Vector<TProjection> map_all(Invercargill.Enumerable<Invercargill.Properties> results)
  94. throws ProjectionError {
  95. var mapped_results = new Vector<TProjection>();
  96. // Check if we have any collection selections that need grouping
  97. bool needs_grouping = false;
  98. foreach (var selection in _mapper_definition.selections) {
  99. if (selection is CollectionProjectionSelection) {
  100. needs_grouping = true;
  101. break;
  102. }
  103. }
  104. if (needs_grouping) {
  105. // For now, use simple mapping without grouping
  106. // TODO: Implement proper grouping when needed
  107. foreach (var row in results) {
  108. mapped_results.add(map_row(row));
  109. }
  110. } else {
  111. // Simple case: each row maps to one projection
  112. foreach (var row in results) {
  113. mapped_results.add(map_row(row));
  114. }
  115. }
  116. return mapped_results;
  117. }
  118. /**
  119. * Maps a selection to a generic Object instance.
  120. *
  121. * This method dispatches to the appropriate handler based on the
  122. * selection type (ScalarSelection, NestedProjectionSelection, or
  123. * CollectionProjectionSelection).
  124. *
  125. * @param instance The Object instance to populate
  126. * @param selection The selection definition
  127. * @param row The database row data
  128. * @throws ProjectionError if mapping fails
  129. */
  130. private void map_selection_to_object(
  131. Object instance,
  132. SelectionDefinition selection,
  133. Invercargill.Properties row
  134. ) throws ProjectionError {
  135. // Check if this is a scalar selection (has value_type that's not a projection)
  136. var nested_type = selection.nested_projection_type;
  137. if (nested_type == null) {
  138. // Scalar selection
  139. map_scalar_selection(instance, selection, row);
  140. } else {
  141. // Check if it's a collection or nested projection
  142. // For now, treat all nested types as scalar objects
  143. map_scalar_selection(instance, selection, row);
  144. }
  145. }
  146. /**
  147. * Maps a scalar selection to a property.
  148. *
  149. * Scalar selections represent simple values like int, string, double, etc.
  150. * The value is extracted from the row, converted to the appropriate type,
  151. * and set on the projection instance.
  152. *
  153. * @param instance The Object instance
  154. * @param selection The selection definition
  155. * @param row The database row data
  156. * @throws ProjectionError if mapping fails
  157. */
  158. private void map_scalar_selection(
  159. Object instance,
  160. SelectionDefinition selection,
  161. Invercargill.Properties row
  162. ) throws ProjectionError {
  163. string column_name = selection.friendly_name;
  164. // Try to get the value from the row
  165. var element = row.get(column_name);
  166. if (element == null) {
  167. // Value not present in row - could be null or missing column
  168. return;
  169. }
  170. // Get the value from the element
  171. Value? val = extract_value_from_element(element, selection.value_type);
  172. if (val == null) {
  173. return;
  174. }
  175. // Set the property on the instance
  176. set_property_on_object(instance, selection.friendly_name, val);
  177. }
  178. /**
  179. * Extracts a value from an Element, converting to the target type.
  180. *
  181. * Uses the Element's try_get_as<T>() method for type-safe extraction.
  182. *
  183. * @param element The Element containing the value
  184. * @param target_type The target Vala type
  185. * @return The converted Value, or null if conversion fails
  186. */
  187. private Value? extract_value_from_element(
  188. Invercargill.Element element,
  189. Type target_type
  190. ) {
  191. if (element.is_null()) {
  192. return null;
  193. }
  194. Value result = Value(target_type);
  195. // Use try_get_as for type-safe extraction
  196. if (target_type == typeof(int64)) {
  197. int64? val = null;
  198. if (element.try_get_as<int64?>(out val) && val != null) {
  199. result.set_int64(val);
  200. return result;
  201. }
  202. } else if (target_type == typeof(int)) {
  203. int? val = null;
  204. if (element.try_get_as<int>(out val) && val != null) {
  205. result.set_int(val);
  206. return result;
  207. }
  208. } else if (target_type == typeof(long)) {
  209. long? val = null;
  210. if (element.try_get_as<long>(out val) && val != null) {
  211. result.set_long(val);
  212. return result;
  213. }
  214. } else if (target_type == typeof(double)) {
  215. double? val = null;
  216. if (element.try_get_as<double?>(out val) && val != null) {
  217. result.set_double(val);
  218. return result;
  219. }
  220. } else if (target_type == typeof(float)) {
  221. float? val = null;
  222. if (element.try_get_as<float?>(out val) && val != null) {
  223. result.set_float(val);
  224. return result;
  225. }
  226. } else if (target_type == typeof(string)) {
  227. string? val = null;
  228. if (element.try_get_as<string>(out val) && val != null) {
  229. result.set_string(val);
  230. return result;
  231. }
  232. } else if (target_type == typeof(bool)) {
  233. bool? val = null;
  234. if (element.try_get_as<bool>(out val) && val != null) {
  235. result.set_boolean(val);
  236. return result;
  237. }
  238. } else if (target_type == typeof(DateTime)) {
  239. DateTime? val = null;
  240. if (element.try_get_as<DateTime>(out val) && val != null) {
  241. result.set_boxed(val);
  242. return result;
  243. }
  244. } else if (target_type == typeof(Invercargill.BinaryData)) {
  245. Invercargill.BinaryData? val = null;
  246. if (element.try_get_as<Invercargill.BinaryData>(out val) && val != null) {
  247. result.set_object(val as Object);
  248. return result;
  249. }
  250. } else if (target_type.is_object()) {
  251. // For other object types, try direct object extraction
  252. Object? val = null;
  253. if (element.try_get_as<Object>(out val) && val != null) {
  254. result.set_object(val);
  255. return result;
  256. }
  257. }
  258. // Fallback: could not convert
  259. return null;
  260. }
  261. /**
  262. * Converts a value to the target type.
  263. *
  264. * This is a secondary conversion method for when we already have a Value
  265. * but need it in a different type.
  266. *
  267. * @param raw_value The raw value
  268. * @param target_type The target Vala type
  269. * @return The converted Value
  270. */
  271. private Value convert_value(Value raw_value, Type target_type) {
  272. Value result = Value(target_type);
  273. if (target_type == typeof(int64)) {
  274. if (raw_value.type() == typeof(int64)) {
  275. result.set_int64(raw_value.get_int64());
  276. } else if (raw_value.type() == typeof(int)) {
  277. result.set_int64((int64)raw_value.get_int());
  278. } else if (raw_value.type() == typeof(long)) {
  279. result.set_int64((int64)raw_value.get_long());
  280. } else if (raw_value.type() == typeof(string)) {
  281. int64 parsed = 0;
  282. if (int64.try_parse(raw_value.get_string(), out parsed)) {
  283. result.set_int64(parsed);
  284. }
  285. } else {
  286. result.set_int64(raw_value.get_int64());
  287. }
  288. } else if (target_type == typeof(int)) {
  289. if (raw_value.type() == typeof(int64)) {
  290. result.set_int((int)raw_value.get_int64());
  291. } else if (raw_value.type() == typeof(int)) {
  292. result.set_int(raw_value.get_int());
  293. } else {
  294. result.set_int((int)raw_value.get_int64());
  295. }
  296. } else if (target_type == typeof(double)) {
  297. if (raw_value.type() == typeof(double)) {
  298. result.set_double(raw_value.get_double());
  299. } else if (raw_value.type() == typeof(float)) {
  300. result.set_double((double)raw_value.get_float());
  301. } else if (raw_value.type() == typeof(string)) {
  302. double parsed = 0.0;
  303. if (double.try_parse(raw_value.get_string(), out parsed)) {
  304. result.set_double(parsed);
  305. }
  306. } else {
  307. result.set_double(raw_value.get_double());
  308. }
  309. } else if (target_type == typeof(float)) {
  310. if (raw_value.type() == typeof(double)) {
  311. result.set_float((float)raw_value.get_double());
  312. } else if (raw_value.type() == typeof(float)) {
  313. result.set_float(raw_value.get_float());
  314. } else {
  315. result.set_float((float)raw_value.get_double());
  316. }
  317. } else if (target_type == typeof(string)) {
  318. if (raw_value.type() == typeof(string)) {
  319. result.set_string(raw_value.get_string());
  320. } else if (raw_value.type() == typeof(int64)) {
  321. result.set_string(raw_value.get_int64().to_string());
  322. } else if (raw_value.type() == typeof(double)) {
  323. result.set_string(raw_value.get_double().to_string());
  324. } else if (raw_value.type() == typeof(bool)) {
  325. result.set_string(raw_value.get_boolean() ? "true" : "false");
  326. }
  327. } else if (target_type == typeof(bool)) {
  328. if (raw_value.type() == typeof(int64)) {
  329. result.set_boolean(raw_value.get_int64() != 0);
  330. } else if (raw_value.type() == typeof(int)) {
  331. result.set_boolean(raw_value.get_int() != 0);
  332. } else if (raw_value.type() == typeof(bool)) {
  333. result.set_boolean(raw_value.get_boolean());
  334. } else {
  335. result.set_boolean(raw_value.get_boolean());
  336. }
  337. } else if (target_type.is_object()) {
  338. result.set_object(raw_value.get_object());
  339. } else {
  340. result = raw_value;
  341. }
  342. return result;
  343. }
  344. /**
  345. * Sets a property value on a generic Object instance.
  346. *
  347. * @param instance The Object instance
  348. * @param property_name The property name
  349. * @param value The value to set
  350. */
  351. private void set_property_on_object(Object instance, string property_name, Value value) {
  352. string gobject_name = friendly_name_to_property_name_for_type(
  353. instance.get_type(),
  354. property_name
  355. );
  356. var obj_class = (ObjectClass)instance.get_type().class_ref();
  357. var spec = obj_class.find_property(gobject_name);
  358. if (spec != null) {
  359. Value converted = convert_value(value, spec.value_type);
  360. instance.set_property(gobject_name, converted);
  361. }
  362. }
  363. /**
  364. * Converts a friendly_name to a GObject property name for a specific type.
  365. *
  366. * @param type The GObject type
  367. * @param friendly_name The friendly name
  368. * @return The GObject property name
  369. */
  370. private string friendly_name_to_property_name_for_type(Type type, string friendly_name) {
  371. var obj_class = (ObjectClass)type.class_ref();
  372. // Try as-is
  373. if (obj_class.find_property(friendly_name) != null) {
  374. return friendly_name;
  375. }
  376. // Try kebab-case
  377. string kebab_case = friendly_name.replace("_", "-");
  378. if (obj_class.find_property(kebab_case) != null) {
  379. return kebab_case;
  380. }
  381. // Try camelCase
  382. string camel_case = snake_to_camel(friendly_name);
  383. if (obj_class.find_property(camel_case) != null) {
  384. return camel_case;
  385. }
  386. return friendly_name;
  387. }
  388. /**
  389. * Converts a snake_case string to camelCase.
  390. *
  391. * @param snake The snake_case string
  392. * @return The camelCase version
  393. */
  394. private string snake_to_camel(string snake) {
  395. var result = new StringBuilder();
  396. bool capitalize_next = false;
  397. for (int i = 0; i < snake.length; i++) {
  398. char c = snake[i];
  399. if (c == '_') {
  400. capitalize_next = true;
  401. } else {
  402. if (capitalize_next) {
  403. result.append_c(c.toupper());
  404. capitalize_next = false;
  405. } else {
  406. result.append_c(c);
  407. }
  408. }
  409. }
  410. return result.str;
  411. }
  412. /**
  413. * Gets the projection definition.
  414. *
  415. * @return The ProjectionDefinition
  416. */
  417. internal ProjectionDefinition definition {
  418. get { return _mapper_definition; }
  419. set { _mapper_definition = value; }
  420. }
  421. }
  422. }