From 200c3636b600ac2f997316612f1b1321112496cd Mon Sep 17 00:00:00 2001
From: Dan Goodliffe <dan.goodliffe@octal.co.uk>
Date: Tue, 5 May 2026 12:24:11 +0100
Subject: Only call entity insert handler if detail is null

Improves handling of entity inserts where the entity already exists and
already has detail; does not call the onInsert handler. This avoids
repeatedly fetching UA detail every time the UA is first seen by a
process.
---
 src/schema.sql | 22 +++++++++++++++++-----
 1 file changed, 17 insertions(+), 5 deletions(-)

(limited to 'src/schema.sql')

diff --git a/src/schema.sql b/src/schema.sql
index 698ea3e..056f7ac 100644
--- a/src/schema.sql
+++ b/src/schema.sql
@@ -43,14 +43,20 @@ CREATE TABLE entities(
 CREATE UNIQUE INDEX uni_entities_value ON entities(MD5(value));
 
 CREATE OR REPLACE FUNCTION entity(newValue text, newType entity)
-	RETURNS integer
+	RETURNS TABLE(
+		id integer,
+		nulldetail boolean
+	)
 	AS $$
 DECLARE
 	now timestamp without time zone;
 	recid integer;
+	nulldetail boolean;
 BEGIN
 	IF newValue IS NULL THEN
-		RETURN NULL;
+		RETURN query
+	VALUES (NULL,
+		NULL);
 	END IF;
 	INSERT INTO entities(value, type)
 	SELECT
@@ -66,16 +72,22 @@ BEGIN
 	ON CONFLICT
 		DO NOTHING
 	RETURNING
-		id INTO recid;
+		entities.id,
+		entities.detail IS NULL INTO recid,
+		nulldetail;
 	IF recid IS NULL THEN
+		RETURN query
 		SELECT
-			id INTO recid
+			id,
+			detail IS NULL
 		FROM
 			entities
 		WHERE
 			md5(value) = md5(newValue);
 	END IF;
-	RETURN recid;
+	RETURN query
+VALUES (recid,
+	nulldetail);
 END;
 $$
 LANGUAGE plpgSQL
-- 
cgit v1.3

