orm-session.vala 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  1. using Invercargill.DataStructures;
  2. using Invercargill.Expressions;
  3. using InvercargillSql.Dialects;
  4. using InvercargillSql.Expressions;
  5. using InvercargillSql.Orm.Projections;
  6. namespace InvercargillSql.Orm {
  7. /**
  8. * Main entry point for ORM operations.
  9. *
  10. * OrmSession coordinates entity mappers, database connections, and SQL dialects
  11. * to provide a high-level API for database operations.
  12. *
  13. * Example usage:
  14. * {{{
  15. * var registry = new TypeRegistry();
  16. * // Register types with registry first...
  17. * var session = new OrmSession(connection, registry, new SqliteDialect());
  18. *
  19. * var users = session.query<User>()
  20. * .where("name LIKE 'A%'")
  21. * .materialise();
  22. * }}}
  23. */
  24. public class OrmSession : Object {
  25. private Connection _connection;
  26. private SqlDialect _dialect;
  27. private TypeProvider _type_provider;
  28. /**
  29. * Creates a new OrmSession.
  30. *
  31. * @param connection The database connection to use
  32. * @param type_provider The type provider for entity mappers and projections
  33. * @param dialect The SQL dialect to use (defaults to SqliteDialect if null)
  34. */
  35. public OrmSession(Connection connection, TypeProvider type_provider, SqlDialect? dialect = null) {
  36. _connection = connection;
  37. _type_provider = type_provider;
  38. _dialect = dialect ?? new SqliteDialect();
  39. }
  40. /**
  41. * Creates a new query for type T.
  42. *
  43. * Returns EntityQuery<T> if T is a registered entity type.
  44. * Returns ProjectionQuery<T> if T is a registered projection type.
  45. *
  46. * @return A new Query<T> instance appropriate for type T
  47. * @throws SqlError.GENERAL_ERROR if T is neither a registered entity nor projection
  48. */
  49. public Query<T> query<T>() throws Error {
  50. var type = typeof(T);
  51. // Check if it's a registered entity
  52. var mapper = _type_provider.get_mapper_for_type(type);
  53. if (mapper != null) {
  54. return new EntityQuery<T>(this);
  55. }
  56. // Check if it's a registered projection
  57. var projection_def = _type_provider.get_projection_for_type(type);
  58. if (projection_def != null) {
  59. var sql_builder = new ProjectionSqlBuilder(projection_def, _dialect);
  60. return new ProjectionQuery<T>(this, projection_def, sql_builder);
  61. }
  62. throw new SqlError.GENERAL_ERROR(
  63. "Type %s is not registered as an entity or projection".printf(type.name())
  64. );
  65. }
  66. /**
  67. * Inserts an entity into the database.
  68. *
  69. * @param entity The entity to insert
  70. * @throws SqlError if insertion fails
  71. */
  72. public void insert<T>(T entity) throws Error {
  73. var mapper = get_mapper<T>();
  74. Invercargill.Properties properties;
  75. try {
  76. properties = mapper.map_from(entity);
  77. } catch (Error e) {
  78. throw new SqlError.GENERAL_ERROR("Failed to map entity: %s".printf(e.message));
  79. }
  80. // Build column list, excluding auto-increment columns (discovered via schema introspection)
  81. var columns = new Vector<string>();
  82. foreach (var col in mapper.columns) {
  83. if (!mapper.is_auto_increment(col.name)) {
  84. columns.add(col.name);
  85. }
  86. }
  87. var sql = _dialect.build_insert_sql(mapper.table_name, columns);
  88. var command = _connection.create_command(sql);
  89. // Add parameters in column order (excluding auto-increment)
  90. foreach (var col in mapper.columns) {
  91. if (mapper.is_auto_increment(col.name)) {
  92. continue; // Skip auto-increment columns
  93. }
  94. var value = properties.get(col.name);
  95. if (value != null) {
  96. command.with_parameter<Invercargill.Element>(col.name, value);
  97. } else {
  98. command.with_null(col.name);
  99. }
  100. }
  101. command.execute_non_query();
  102. // Back-populate the generated primary key
  103. var pk_column = mapper.get_effective_primary_key();
  104. if (pk_column != null && mapper.is_auto_increment(pk_column)) {
  105. int64 generated_id = _connection.last_insert_rowid;
  106. try {
  107. mapper.set_property_value(entity, pk_column, generated_id);
  108. } catch (Error e) {
  109. throw new SqlError.GENERAL_ERROR("Failed to back-populate primary key: %s".printf(e.message));
  110. }
  111. }
  112. }
  113. /**
  114. * Inserts an entity into the database asynchronously.
  115. *
  116. * This method performs the same operation as insert() but in a non-blocking
  117. * manner, allowing the main loop to process other events while waiting
  118. * for the database operation to complete.
  119. *
  120. * After insertion, if the entity has an auto-increment primary key,
  121. * the key value is back-populated into the entity.
  122. *
  123. * @param entity The entity to insert
  124. * @throws SqlError if insertion fails
  125. */
  126. public async void insert_async<T>(T entity) throws Error {
  127. var mapper = get_mapper<T>();
  128. Invercargill.Properties properties;
  129. try {
  130. properties = mapper.map_from(entity);
  131. } catch (Error e) {
  132. throw new SqlError.GENERAL_ERROR("Failed to map entity: %s".printf(e.message));
  133. }
  134. // Build column list, excluding auto-increment columns
  135. var columns = new Vector<string>();
  136. foreach (var col in mapper.columns) {
  137. if (!mapper.is_auto_increment(col.name)) {
  138. columns.add(col.name);
  139. }
  140. }
  141. var sql = _dialect.build_insert_sql(mapper.table_name, columns);
  142. var command = _connection.create_command(sql);
  143. // Add parameters in column order (excluding auto-increment)
  144. foreach (var col in mapper.columns) {
  145. if (mapper.is_auto_increment(col.name)) {
  146. continue; // Skip auto-increment columns
  147. }
  148. var value = properties.get(col.name);
  149. if (value != null) {
  150. command.with_parameter<Invercargill.Element>(col.name, value);
  151. } else {
  152. command.with_null(col.name);
  153. }
  154. }
  155. // Execute asynchronously
  156. yield command.execute_non_query_async();
  157. // Back-populate the generated primary key
  158. var pk_column = mapper.get_effective_primary_key();
  159. if (pk_column != null && mapper.is_auto_increment(pk_column)) {
  160. int64 generated_id = _connection.last_insert_rowid;
  161. try {
  162. mapper.set_property_value(entity, pk_column, generated_id);
  163. } catch (Error e) {
  164. throw new SqlError.GENERAL_ERROR("Failed to back-populate primary key: %s".printf(e.message));
  165. }
  166. }
  167. }
  168. /**
  169. * Updates an entity in the database.
  170. *
  171. * @param entity The entity to update
  172. * @throws SqlError if update fails
  173. */
  174. public void update<T>(T entity) throws Error {
  175. var mapper = get_mapper<T>();
  176. Invercargill.Properties properties;
  177. try {
  178. properties = mapper.map_from(entity);
  179. } catch (Error e) {
  180. throw new SqlError.GENERAL_ERROR("Failed to map entity: %s".printf(e.message));
  181. }
  182. var columns = new Vector<string>();
  183. foreach (var col in mapper.columns) {
  184. columns.add(col.name);
  185. }
  186. var pk_column = mapper.get_effective_primary_key();
  187. var sql = _dialect.build_update_sql(mapper.table_name, columns, pk_column);
  188. var command = _connection.create_command(sql);
  189. // Add parameters for SET clause
  190. foreach (var col in mapper.columns) {
  191. var value = properties.get(col.name);
  192. if (value != null) {
  193. command.with_parameter<Invercargill.Element>(col.name, value);
  194. } else {
  195. command.with_null(col.name);
  196. }
  197. }
  198. // Add primary key parameter for WHERE clause
  199. var pk_value = properties.get(pk_column);
  200. if (pk_value != null) {
  201. command.with_parameter<Invercargill.Element>(pk_column, pk_value);
  202. } else {
  203. command.with_null(pk_column);
  204. }
  205. command.execute_non_query();
  206. }
  207. /**
  208. * Updates an entity in the database asynchronously.
  209. *
  210. * This method performs the same operation as update() but in a non-blocking
  211. * manner, allowing the main loop to process other events while waiting
  212. * for the database operation to complete.
  213. *
  214. * The entity is identified by its primary key.
  215. *
  216. * @param entity The entity to update
  217. * @throws SqlError if update fails
  218. */
  219. public async void update_async<T>(T entity) throws Error {
  220. var mapper = get_mapper<T>();
  221. Invercargill.Properties properties;
  222. try {
  223. properties = mapper.map_from(entity);
  224. } catch (Error e) {
  225. throw new SqlError.GENERAL_ERROR("Failed to map entity: %s".printf(e.message));
  226. }
  227. var columns = new Vector<string>();
  228. foreach (var col in mapper.columns) {
  229. columns.add(col.name);
  230. }
  231. var pk_column = mapper.get_effective_primary_key();
  232. var sql = _dialect.build_update_sql(mapper.table_name, columns, pk_column);
  233. var command = _connection.create_command(sql);
  234. // Add parameters for SET clause
  235. foreach (var col in mapper.columns) {
  236. var value = properties.get(col.name);
  237. if (value != null) {
  238. command.with_parameter<Invercargill.Element>(col.name, value);
  239. } else {
  240. command.with_null(col.name);
  241. }
  242. }
  243. // Add primary key parameter for WHERE clause
  244. var pk_value = properties.get(pk_column);
  245. if (pk_value != null) {
  246. command.with_parameter<Invercargill.Element>(pk_column, pk_value);
  247. } else {
  248. command.with_null(pk_column);
  249. }
  250. // Execute asynchronously
  251. yield command.execute_non_query_async();
  252. }
  253. /**
  254. * Deletes an entity from the database.
  255. *
  256. * @param entity The entity to delete
  257. * @throws SqlError if deletion fails
  258. */
  259. public void delete<T>(T entity) throws Error {
  260. var mapper = get_mapper<T>();
  261. Invercargill.Properties properties;
  262. try {
  263. properties = mapper.map_from(entity);
  264. } catch (Error e) {
  265. throw new SqlError.GENERAL_ERROR("Failed to map entity: %s".printf(e.message));
  266. }
  267. var pk_column = mapper.get_effective_primary_key();
  268. var sql = _dialect.build_delete_sql(mapper.table_name, pk_column);
  269. var command = _connection.create_command(sql);
  270. var pk_value = properties.get(pk_column);
  271. if (pk_value != null) {
  272. command.with_parameter<Invercargill.Element>(pk_column, pk_value);
  273. } else {
  274. command.with_null(pk_column);
  275. }
  276. command.execute_non_query();
  277. }
  278. /**
  279. * Deletes an entity from the database asynchronously.
  280. *
  281. * This method performs the same operation as delete() but in a non-blocking
  282. * manner, allowing the main loop to process other events while waiting
  283. * for the database operation to complete.
  284. *
  285. * The entity is identified by its primary key.
  286. *
  287. * @param entity The entity to delete
  288. * @throws SqlError if deletion fails
  289. */
  290. public async void delete_async<T>(T entity) throws Error {
  291. var mapper = get_mapper<T>();
  292. Invercargill.Properties properties;
  293. try {
  294. properties = mapper.map_from(entity);
  295. } catch (Error e) {
  296. throw new SqlError.GENERAL_ERROR("Failed to map entity: %s".printf(e.message));
  297. }
  298. var pk_column = mapper.get_effective_primary_key();
  299. var sql = _dialect.build_delete_sql(mapper.table_name, pk_column);
  300. var command = _connection.create_command(sql);
  301. var pk_value = properties.get(pk_column);
  302. if (pk_value != null) {
  303. command.with_parameter<Invercargill.Element>(pk_column, pk_value);
  304. } else {
  305. command.with_null(pk_column);
  306. }
  307. // Execute asynchronously
  308. yield command.execute_non_query_async();
  309. }
  310. /**
  311. * Gets the SQL dialect for internal use.
  312. * Used by EntityQuery and ProjectionQuery to build SQL.
  313. *
  314. * @return The SQL dialect
  315. */
  316. internal SqlDialect get_dialect() {
  317. return _dialect;
  318. }
  319. /**
  320. * Gets the entity mapper for type T.
  321. *
  322. * This method is useful for testing and advanced scenarios where
  323. * you need direct access to the entity mapper.
  324. *
  325. * @return The EntityMapper<T> for type T
  326. * @throws SqlError if no mapper is registered for type T
  327. */
  328. public EntityMapper<T> get_mapper<T>() throws Error {
  329. return _type_provider.get_mapper<T>();
  330. }
  331. /**
  332. * Gets the entity mapper for a specific type.
  333. *
  334. * @param type The entity type to look up
  335. * @return The EntityMapper for the type, or null if not registered
  336. */
  337. public EntityMapper? get_mapper_for_type(Type type) throws Error {
  338. return _type_provider.get_mapper_for_type(type);
  339. }
  340. /**
  341. * Gets the projection definition for a type.
  342. *
  343. * @return The ProjectionDefinition for the type, or null if not registered
  344. */
  345. public ProjectionDefinition? get_projection_definition<TProjection>() throws Error
  346. {
  347. return _type_provider.get_projection<TProjection>();
  348. }
  349. /**
  350. * Gets the projection definition by type.
  351. *
  352. * @param type The projection type to look up
  353. * @return The ProjectionDefinition for the type, or null if not registered
  354. */
  355. public ProjectionDefinition? get_projection_definition_for_type(Type type) throws Error {
  356. return _type_provider.get_projection_for_type(type);
  357. }
  358. /**
  359. * Gets the connection for internal use.
  360. * Used by ProjectionQuery to execute queries.
  361. *
  362. * @return The database connection
  363. */
  364. internal Connection get_connection() {
  365. return _connection;
  366. }
  367. }
  368. }