From c587133afe772adc56311bc03483093dc2410531 Mon Sep 17 00:00:00 2001 From: vabenil Date: Sat, 12 Nov 2022 19:00:43 +0200 Subject: [PATCH 1/2] Make find work as advertised --- database_generation.d | 20 +++++++++++++++----- 1 file changed, 15 insertions(+), 5 deletions(-) diff --git a/database_generation.d b/database_generation.d index 40ff734..0a7abe7 100644 --- a/database_generation.d +++ b/database_generation.d @@ -394,14 +394,24 @@ class RecordNotFoundException : Exception { If you just give a type, it assumes the relevant index is "id". +/ -auto find(alias T)(Database db, int id) { - - // FIXME: if T is an index, search by it. +static auto find(alias T)(Database db, int id) { + // FIXME: // if it is unique, return an individual item. // if not, return the array + static if (!is(T)) { + static const string fieldName = T.stringof; + alias FType = typeof(T); // field type + alias TType = __traits(parent, T); // Table type + } + else { + static const string fieldName = "id"; + alias FType = int; + alias TType = T; + } - foreach(record; db.query("SELECT * FROM " ~ tableNameFor!T() ~ " WHERE id = ?", id)) { - T t; + string q = "SELECT * FROM " ~ tableNameFor!TType() ~ " WHERE " ~ fieldName ~ " = ?"; + foreach(record; db.query(q, id)) { + TType t; populateFromDbRow(t, record); return t; From 95f5f42129158b93fc40fe17a60765a9c3b9bd8c Mon Sep 17 00:00:00 2001 From: vabenil Date: Sat, 12 Nov 2022 19:59:06 +0200 Subject: [PATCH 2/2] Add integral field check to find --- database_generation.d | 3 +++ 1 file changed, 3 insertions(+) diff --git a/database_generation.d b/database_generation.d index 0a7abe7..ea14387 100644 --- a/database_generation.d +++ b/database_generation.d @@ -409,6 +409,9 @@ static auto find(alias T)(Database db, int id) { alias TType = T; } + static assert(is(FType : int), + TType.stringof ~ "." ~ fieldName ~ " should be an Integral field"); + string q = "SELECT * FROM " ~ tableNameFor!TType() ~ " WHERE " ~ fieldName ~ " = ?"; foreach(record; db.query(q, id)) { TType t;