Page 1 of 1

Support for views - Patch

Posted: 2025-06-01 22:17
by gregk
Hi all.

I have been using AppGini for many years. One of my use cases involves an appgini UI that sits on top of an existing app - as a back-end tool to do things. One of the things used is a view that combines an EAV table into a flat table to make it easier to work with.

This worked well in earlier versions of AppGini, but more recently, there is a function getPKFieldName which is used to find the primary key in a table, which is then used to generate the query to find a record when you click it in table view. But views of course dont really have a primary key. So I investigated adding a patch to getPKFieldName which would find my pseudo-key.

In my case, my views have numeric ID's for most views. In a few other tables, I have a string key. The function below will basically find the first int field in a table, and failover to the first not-null mandatory field. Update this function in ./admin/incFunctions.php and detail view of tables that are built on views will work again.

Code: Select all

function getPKFieldName($tn) {
   // Get primary key field name of a table, or fallback to first int or default-not-null field
   static $pk = [];
   if(isset($pk[$tn])) return $pk[$tn];

   $stn = makeSafe($tn, false);
   $eo = ['silentErrors' => true];
   if(!$res = sql("SHOW FIELDS FROM `$stn`", $eo)) return $pk[$tn] = false;

   $fallbackField = false;

   while($row = db_fetch_assoc($res)) {
       // Priority 1: Explicit primary key
       if($row['Key'] === 'PRI') {
           return $pk[$tn] = $row['Field'];
       }

       // Priority 2: First integer or default-not-null field
       if(!$fallbackField) {
           $isInt = preg_match('/int/i', $row['Type']);
           $hasDefault = $row['Default'] !== null;
           if($isInt || $hasDefault) {
               $fallbackField = $row['Field'];
           }
       }
   }

   // Return fallback or false if nothing suitable
   return $pk[$tn] = $fallbackField ?: false;
}