#5 Offer SQL function as an option to count-bits

Merged
fox merged 7 commits from rodneys_mission/Add_alternate_bitcount_SQL_function into fox/master 1 year ago
3 changed files with 20 additions and 9 deletions
  1. 5 1
      README.txt
  2. 12 8
      init.php
  3. 3 0
      sql/bitcount_funcdef_pgsql.sql

+ 5 - 1
README.txt

@@ -3,4 +3,8 @@ This plugin filters duplicate images using perceptual image hashing.
 Hashing library: https://github.com/jenssegers/imagehash
 Count bits extension for PostgreSQL: https://github.com/sldab/count-bits
 
-Git clone to (tt-rss)/plugins.local/af_zz_img_phash
+Git clone to (tt-rss)/plugins.local/af_zz_img_phash
+
+Note: an alternative to the 'Count bits extension' is to install the SQL function in "sql/bitcount_funcdef_pgsql.sql" and add to config.php:
+	define('IMG_HASH_SQL_FUNCTION', true);
+	// Alternative to compiling/installing the count-bits extenstion.

+ 12 - 8
init.php

@@ -80,10 +80,14 @@ class Af_Zz_Img_Phash extends Plugin {
 			title=\"<i class='material-icons'>photo</i> ".$this->__( 'Filter similar images (af_zz_img_phash)')."\">";
 
 		if (DB_TYPE == "pgsql") {
-			$res = $this->pdo->query("select 'unique_1bits'::regproc");
-
-			if (!$res->fetch()) {
-				print_error("Required function from count_bits extension not found.");
+			if (true === IMG_HASH_SQL_FUNCTION) {
+				print_error("Using SQL implementation of bit_count; UI performance may not be as responsive as installing extension 'https://github.com/sldab/count-bits'. See README.txt");
+			}
+			else {
+				try { $res = $this->pdo->query("select 'unique_1bits'::regproc"); } catch (PDOException $e) { ; }
+				if (!$res || !$res->fetch()) {
+					print_error("Required function from count_bits extension not found.");
+				}
 			}
 		}
 
@@ -394,9 +398,9 @@ class Af_Zz_Img_Phash extends Plugin {
 
 	function hook_render_article_cdm($article, $api_mode = false) {
 
-		if (DB_TYPE == "pgsql") {
-			$res = $this->pdo->query("select 'unique_1bits'::regproc");
-			if (!$res->fetch()) return $article;
+		if (DB_TYPE == "pgsql" && true !== IMG_HASH_SQL_FUNCTION) {
+			try { $res = $this->pdo->query("select 'unique_1bits'::regproc"); } catch (PDOException $e) { ; }
+			if (!$res || !$res->fetch()) return $article;
 		}
 
 		$owner_uid = $_SESSION["uid"];
@@ -641,7 +645,7 @@ class Af_Zz_Img_Phash extends Plugin {
 
 	private function bitcount_func($phash) {
 		if (DB_TYPE == "pgsql") {
-			return "unique_1bits('$phash', phash)";
+			return true === IMG_HASH_SQL_FUNCTION ? "bit_count('$phash' # phash)" : "unique_1bits('$phash', phash)";
 		} else {
 			return "bit_count('$phash' ^ phash)";
 		}

+ 3 - 0
sql/bitcount_funcdef_pgsql.sql

@@ -0,0 +1,3 @@
+CREATE OR REPLACE FUNCTION bit_count(bigint) RETURNS integer AS $$
+	SELECT length(replace($1::bit(64)::text, '0', '')); $$
+LANGUAGE SQL IMMUTABLE STRICT;