demo.vala 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  1. using Invercargill.DataStructures;
  2. using InvercargillSql;
  3. using InvercargillSql.Orm;
  4. using InvercargillSql.Orm.Projections;
  5. using InvercargillSql.Migrations;
  6. using InvercargillSql.Dialects;
  7. /**
  8. * Invercargill-Sql ORM Demo Application
  9. *
  10. * This demo showcases the main features of the Invercargill-Sql ORM:
  11. * - Database migrations
  12. * - Entity mapping and CRUD operations
  13. * - Projection queries (simple, join, aggregate)
  14. */
  15. public int main(string[] args) {
  16. print("=== Invercargill-Sql ORM Demo ===\n\n");
  17. // Allow optional connection string argument
  18. string connection_string = args.length > 1
  19. ? args[1]
  20. : "sqlite::memory:";
  21. try {
  22. // Create and open database connection
  23. var conn = ConnectionFactory.create_and_open(connection_string);
  24. var dialect = new SqliteDialect();
  25. var registry = new TypeRegistry();
  26. // --- Running Migrations ---
  27. print("--- Running Migrations ---\n");
  28. run_migrations(conn, dialect);
  29. // --- Registering Entity Mappers ---
  30. print("\n--- Registering Entity Mappers ---\n");
  31. register_entities(registry, conn, dialect);
  32. // --- Registering Projection Definitions ---
  33. print("Registering projection definitions...\n");
  34. register_projections(registry);
  35. // Create session with registry
  36. var session = new OrmSession(conn, registry, dialect);
  37. // --- Inserting Data ---
  38. print("\n--- Inserting Data ---\n");
  39. insert_sample_data(session);
  40. // --- Querying Entities ---
  41. print("\n--- Querying Entities ---\n");
  42. demonstrate_entity_queries(session);
  43. // --- Updating Data ---
  44. print("\n--- Updating Data ---\n");
  45. demonstrate_update(session);
  46. // --- Deleting Data ---
  47. print("\n--- Deleting Data ---\n");
  48. demonstrate_delete(session);
  49. // --- Querying Projections ---
  50. print("\n--- Querying Projections ---\n");
  51. demonstrate_projection_queries(session);
  52. print("\n=== Demo Complete ===\n");
  53. conn.close();
  54. return 0;
  55. } catch (Error e) {
  56. printerr("\n=== Demo failed: %s ===\n", e.message);
  57. return 1;
  58. }
  59. }
  60. void run_migrations(Connection conn, SqlDialect dialect) throws SqlError {
  61. var runner = new MigrationRunner(conn, dialect);
  62. // Register migrations
  63. runner.register_migration(new V001_CreateUsers());
  64. runner.register_migration(new V002_CreateProducts());
  65. runner.register_migration(new V003_CreateOrders());
  66. // Run all pending migrations
  67. runner.migrate_to_latest();
  68. // Get applied migrations count
  69. var applied = runner.get_applied_migrations();
  70. print("Applied %d migrations\n", (int)applied.length);
  71. }
  72. void register_entities(TypeRegistry registry, Connection conn, SqlDialect dialect) throws SqlError {
  73. // Register User entity with schema introspection
  74. registry.register_with_schema<User>("users", conn, dialect, User.configure_mapper);
  75. print("Registered User entity\n");
  76. // Register Product entity with schema introspection
  77. registry.register_with_schema<Product>("products", conn, dialect, Product.configure_mapper);
  78. print("Registered Product entity\n");
  79. // Register Order entity with schema introspection
  80. registry.register_with_schema<Order>("orders", conn, dialect, Order.configure_mapper);
  81. print("Registered Order entity\n");
  82. }
  83. void register_projections(TypeRegistry registry) throws ProjectionError {
  84. // Register projections using static configure_projection methods
  85. var user_summary_builder = new ProjectionBuilder<UserSummary>(registry);
  86. UserSummary.configure_projection(user_summary_builder);
  87. registry.register_projection<UserSummary>(user_summary_builder.build());
  88. var order_detail_builder = new ProjectionBuilder<OrderDetail>(registry);
  89. OrderDetail.configure_projection(order_detail_builder);
  90. registry.register_projection<OrderDetail>(order_detail_builder.build());
  91. var sales_report_builder = new ProjectionBuilder<SalesReport>(registry);
  92. SalesReport.configure_projection(sales_report_builder);
  93. registry.register_projection<SalesReport>(sales_report_builder.build());
  94. }
  95. void insert_sample_data(OrmSession session) throws SqlError {
  96. // Insert users
  97. var alice = new User();
  98. alice.name = "Alice";
  99. alice.email = "alice@example.com";
  100. alice.age = 30;
  101. alice.is_active = true;
  102. session.insert(alice);
  103. print("Inserted user: %s (ID: %lld)\n", alice.name, alice.id);
  104. var bob = new User();
  105. bob.name = "Bob";
  106. bob.email = "bob@example.com";
  107. bob.age = 22;
  108. bob.is_active = true;
  109. session.insert(bob);
  110. print("Inserted user: %s (ID: %lld)\n", bob.name, bob.id);
  111. var charlie = new User();
  112. charlie.name = "Charlie";
  113. charlie.email = "charlie@example.com";
  114. charlie.age = 35;
  115. charlie.is_active = false;
  116. session.insert(charlie);
  117. print("Inserted user: %s (ID: %lld)\n", charlie.name, charlie.id);
  118. // Insert products
  119. var widget = new Product();
  120. widget.name = "Widget";
  121. widget.category = "Electronics";
  122. widget.price = 29.99;
  123. widget.stock = 100;
  124. session.insert(widget);
  125. print("Inserted product: %s (ID: %lld)\n", widget.name, widget.id);
  126. var gadget = new Product();
  127. gadget.name = "Gadget";
  128. gadget.category = "Electronics";
  129. gadget.price = 49.99;
  130. gadget.stock = 50;
  131. session.insert(gadget);
  132. print("Inserted product: %s (ID: %lld)\n", gadget.name, gadget.id);
  133. var doohickey = new Product();
  134. doohickey.name = "Doohickey";
  135. doohickey.category = "Accessories";
  136. doohickey.price = 9.99;
  137. doohickey.stock = 200;
  138. session.insert(doohickey);
  139. print("Inserted product: %s (ID: %lld)\n", doohickey.name, doohickey.id);
  140. // Insert orders
  141. int order_count = 0;
  142. // Alice orders 2 Widgets
  143. var order1 = create_order(alice.id, widget.id, 2, 59.98, "completed");
  144. session.insert(order1);
  145. order_count++;
  146. // Alice orders 1 Gadget
  147. var order2 = create_order(alice.id, gadget.id, 1, 49.99, "completed");
  148. session.insert(order2);
  149. order_count++;
  150. // Bob orders 3 Doohickeys
  151. var order3 = create_order(bob.id, doohickey.id, 3, 29.97, "pending");
  152. session.insert(order3);
  153. order_count++;
  154. // Charlie orders 1 Widget and 2 Gadgets
  155. var order4 = create_order(charlie.id, widget.id, 1, 29.99, "completed");
  156. session.insert(order4);
  157. order_count++;
  158. var order5 = create_order(charlie.id, gadget.id, 2, 99.98, "completed");
  159. session.insert(order5);
  160. order_count++;
  161. print("Inserted %d orders\n", order_count);
  162. }
  163. Order create_order(int64 user_id, int64 product_id, int64 quantity, double total, string status) {
  164. var order = new Order();
  165. order.user_id = user_id;
  166. order.product_id = product_id;
  167. order.quantity = quantity;
  168. order.total = total;
  169. order.status = status;
  170. order.created_at = new DateTime.now_utc();
  171. return order;
  172. }
  173. void demonstrate_entity_queries(OrmSession session) throws SqlError {
  174. // Query all users
  175. var all_users = session.query<User>().materialise();
  176. print("All users: %d\n", (int)all_users.length);
  177. // Query users over 25
  178. var users_over_25 = session.query<User>()
  179. .where("age > 25")
  180. .materialise();
  181. print("Users over 25: %d\n", (int)users_over_25.length);
  182. // Query active users ordered by age
  183. var active_users = session.query<User>()
  184. .where("is_active == 1")
  185. .order_by("age")
  186. .materialise();
  187. print("Active users ordered by age: ");
  188. var first = true;
  189. foreach (var user in active_users) {
  190. if (!first) print(", ");
  191. print("%s(%lld)", user.name, user.age);
  192. first = false;
  193. }
  194. print("\n");
  195. // Query with pagination
  196. var paged_users = session.query<User>()
  197. .order_by("id")
  198. .limit(2)
  199. .offset(1)
  200. .materialise();
  201. print("Users (page 2, size 2): %d\n", (int)paged_users.length);
  202. }
  203. void demonstrate_update(OrmSession session) throws SqlError {
  204. // Find Alice by ID
  205. var alice = session.query<User>()
  206. .where("id == 1")
  207. .first();
  208. if (alice != null) {
  209. // Update Alice's age
  210. alice.age = 31;
  211. session.update(alice);
  212. print("Updated %s's age to %lld\n", alice.name, alice.age);
  213. // Verify the update
  214. var verified = session.query<User>()
  215. .where("id == 1")
  216. .first();
  217. print("Verified update: %s is now %lld\n", verified.name, verified.age);
  218. }
  219. }
  220. void demonstrate_delete(OrmSession session) throws SqlError {
  221. // Find Bob by name (using age as a proxy since string comparison in expressions may not work)
  222. var bob = session.query<User>()
  223. .where("age == 22")
  224. .first();
  225. if (bob != null) {
  226. print("Deleted user: %s\n", bob.name);
  227. session.delete(bob);
  228. // Verify deletion
  229. var remaining = session.query<User>().materialise();
  230. print("Remaining users: %d\n", (int)remaining.length);
  231. }
  232. }
  233. void demonstrate_projection_queries(OrmSession session) throws SqlError, ProjectionError {
  234. // Simple projection - User summaries
  235. print("\n--- User Summaries ---\n");
  236. var user_summaries = session.query<UserSummary>()
  237. .order_by("user_name")
  238. .materialise();
  239. foreach (var summary in user_summaries) {
  240. print(" [%lld] %s <%s>\n", summary.user_id, summary.user_name, summary.email);
  241. }
  242. print("Total user summaries: %d\n", (int)user_summaries.length);
  243. // Join projection - Order details
  244. print("\n--- Order Details ---\n");
  245. var order_details = session.query<OrderDetail>()
  246. .order_by("order_id")
  247. .materialise();
  248. foreach (var detail in order_details) {
  249. print(" [%lld] %s ordered %dx %s ($%.2f) - %s\n",
  250. detail.order_id, detail.user_name, detail.quantity,
  251. detail.product_name, detail.total, detail.status);
  252. }
  253. print("Total order details: %d\n", (int)order_details.length);
  254. // Aggregate projection - Sales by category
  255. print("\n--- Sales by Category ---\n");
  256. var sales_reports = session.query<SalesReport>()
  257. .order_by_desc("total_revenue")
  258. .materialise();
  259. foreach (var report in sales_reports) {
  260. print(" %s: %lld orders, $%.2f revenue, $%.2f avg\n",
  261. report.category, report.total_orders,
  262. report.total_revenue, report.avg_order_value);
  263. }
  264. print("Total categories: %d\n", (int)sales_reports.length);
  265. // Projection with where clause
  266. print("\n--- Completed Orders ---\n");
  267. var completed_orders = session.query<OrderDetail>()
  268. .where("status == 'completed'")
  269. .materialise();
  270. print("Completed orders: %d\n", (int)completed_orders.length);
  271. }