SQLiteConfig.java

package jasper.config;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.DestructionAwareBeanPostProcessor;
import org.springframework.boot.context.properties.bind.Binder;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.datasource.DelegatingDataSource;
import org.springframework.jdbc.datasource.LazyConnectionDataSourceProxy;
import org.sqlite.Function;
import org.sqlite.SQLiteConnection;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Registers custom SQLite functions that emulate PostgreSQL JSONB functions
 * used in native queries. Only active when the "sqlite" profile is enabled.
 *
 * Wraps the DataSource via BeanPostProcessor so that UDFs are registered on
 * every connection obtained from the pool, surviving connection recycling.
 *
 * SQLite allows a single writer, but in WAL mode readers never block it. The
 * configured Hikari pool (one connection) is kept for writes, and read-only
 * transactions get their own pool of {@code jasper.sqlite-read-pool-size}
 * query-only connections, so a slow read doesn't stall the whole server.
 */
@Configuration
@Profile("sqlite")
public class SQLiteConfig implements DestructionAwareBeanPostProcessor, EnvironmentAware {
	private static final Logger logger = LoggerFactory.getLogger(SQLiteConfig.class);
	private static final ObjectMapper om = new ObjectMapper();
	/**
	 * Same pattern as the tag_value_num PostgreSQL function.
	 */
	private static final Pattern DECIMAL = Pattern.compile("[0-9]{1,30}(?:[.][0-9]{1,30})?");
	/**
	 * Same pattern as the tag_value_dur PostgreSQL function.
	 */
	private static final Pattern ISO_DURATION = Pattern.compile(
		"P(?=[0-9]|T[0-9])(?:([0-9]{1,6})Y)?(?:([0-9]{1,6})M)?(?:([0-9]{1,6})W)?(?:([0-9]{1,6})D)?(?:T(?=[0-9])(?:([0-9]{1,6})H)?(?:([0-9]{1,6})M)?(?:([0-9]{1,9}(?:[.][0-9]{1,9})?)S)?)?");

	private int readPoolSize = 10;
	/**
	 * Spring only destroys the original write pool bean, so close the read pools alongside it.
	 */
	private final Map<HikariDataSource, ReadWriteDataSource> readWrite = new ConcurrentHashMap<>();

	@Override
	public void setEnvironment(Environment env) {
		readPoolSize = Binder.get(env).bind("jasper.sqlite-read-pool-size", Integer.class).orElse(10);
	}

	@Override
	public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
		if (bean instanceof SQLiteUdfDataSource || bean instanceof ReadWriteDataSource) return bean;
		if (bean instanceof HikariDataSource write && readPoolSize > 0) {
			if (isInMemory(write.getJdbcUrl())) {
				logger.info("Not using SQLite read connections with an in-memory database");
			} else {
				logger.info("Using {} SQLite read connections and a single write connection", readPoolSize);
				var ds = new ReadWriteDataSource(write, readPoolSize);
				readWrite.put(write, ds);
				return ds;
			}
		}
		if (bean instanceof DataSource ds) {
			logger.info("Wrapping DataSource to register SQLite UDFs on every connection");
			return new SQLiteUdfDataSource(ds);
		}
		return bean;
	}

	@Override
	public boolean requiresDestruction(Object bean) {
		return bean instanceof HikariDataSource ds && readWrite.containsKey(ds);
	}

	@Override
	public void postProcessBeforeDestruction(Object bean, String beanName) throws BeansException {
		if (bean instanceof HikariDataSource ds) {
			var rw = readWrite.remove(ds);
			if (rw != null) rw.getReadPool().close();
		}
	}

	/**
	 * In-memory databases either aren't shared between connections, or use a
	 * shared cache with table locks instead of WAL, so readers would block the writer.
	 */
	static boolean isInMemory(String url) {
		if (url == null) return false;
		var u = url.toLowerCase();
		return u.contains(":memory:") || u.contains("mode=memory");
	}

	/**
	 * Routes read-only transactions to a separate pool of query-only connections
	 * and everything else to the single write connection.
	 */
	static class ReadWriteDataSource extends LazyConnectionDataSourceProxy implements AutoCloseable {
		private final HikariDataSource write;
		private final HikariDataSource read;

		ReadWriteDataSource(HikariDataSource write, int readPoolSize) {
			this.write = write;
			var config = new HikariConfig();
			write.copyStateTo(config);
			config.setPoolName((write.getPoolName() == null ? "Hikari" : write.getPoolName()) + "-read");
			config.setMaximumPoolSize(readPoolSize);
			// sqlite-jdbc can't change the read-only flag after opening, so guard writes with a pragma instead
			config.setReadOnly(false);
			config.setConnectionInitSql("PRAGMA query_only = true");
			this.read = new HikariDataSource(config);
			setTargetDataSource(new SQLiteUdfDataSource(write));
			setReadOnlyDataSource(new SQLiteUdfDataSource(read));
			setDefaultAutoCommit(write.isAutoCommit());
			setDefaultTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);
			afterPropertiesSet();
		}

		HikariDataSource getReadPool() {
			return read;
		}

		@Override
		public void close() {
			read.close();
			write.close();
		}
	}

	/**
	 * DataSource wrapper that registers custom SQLite UDFs on every connection
	 * obtained from the pool. Function.create is idempotent, so re-registering
	 * on reused pooled connections is safe.
	 */
	private static class SQLiteUdfDataSource extends DelegatingDataSource {
		SQLiteUdfDataSource(DataSource delegate) {
			super(delegate);
		}

		@Override
		public Connection getConnection() throws SQLException {
			var conn = super.getConnection();
			registerFunctionsOnConnection(conn);
			return conn;
		}

		@Override
		public Connection getConnection(String username, String password) throws SQLException {
			var conn = super.getConnection(username, password);
			registerFunctionsOnConnection(conn);
			return conn;
		}
	}

	/**
	 * Register all custom functions on the given connection.
	 */
	static void registerFunctionsOnConnection(Connection conn) throws SQLException {
		var sqliteConn = conn.unwrap(SQLiteConnection.class);
		registerJsonbExists(sqliteConn);
		registerIsoDurationSeconds(sqliteConn);
		registerDecimalValue(sqliteConn);
		registerGeoFunctions(sqliteConn);
	}

	/**
	 * Registers decimal_value(text) function for SQLite.
	 * Returns the value of an unsigned decimal number (e.g. "37" or "2.5"), or null if it cannot be parsed.
	 */
	private static void registerDecimalValue(SQLiteConnection conn) throws SQLException {
		Function.create(conn, "decimal_value", new Function() {
			@Override
			protected void xFunc() throws SQLException {
				var value = args() < 1 ? null : value_text(0);
				if (value == null || !DECIMAL.matcher(value).matches()) {
					result();
				} else {
					result(Double.parseDouble(value));
				}
			}
		}, Function.FLAG_DETERMINISTIC);
	}

	/**
	 * Registers iso_duration_seconds(text) function for SQLite.
	 * Returns the number of seconds in a case-insensitive ISO-8601 duration (e.g. "pt10m25s"),
	 * or null if it cannot be parsed. Matches PostgreSQL's extract(epoch from interval):
	 * years are 365.25 days and months are 30 days.
	 */
	private static void registerIsoDurationSeconds(SQLiteConnection conn) throws SQLException {
		Function.create(conn, "iso_duration_seconds", new Function() {
			@Override
			protected void xFunc() throws SQLException {
				var seconds = args() < 1 ? null : isoDurationSeconds(value_text(0));
				if (seconds == null) {
					result();
				} else {
					result(seconds);
				}
			}
		}, Function.FLAG_DETERMINISTIC);
	}

	public static Double isoDurationSeconds(String value) {
		if (value == null) return null;
		var m = ISO_DURATION.matcher(value.toUpperCase());
		if (!m.matches()) return null;
		var months = group(m, 1) * 12 + group(m, 2);
		return (months / 12) * 365.25 * 86400
			+ (months % 12) * 30 * 86400
			+ (group(m, 3) * 7 + group(m, 4)) * 86400
			+ group(m, 5) * 3600
			+ group(m, 6) * 60
			+ (m.group(7) == null ? 0 : Double.parseDouble(m.group(7)));
	}

	private static long group(Matcher m, int group) {
		return m.group(group) == null ? 0 : Long.parseLong(m.group(group));
	}

	/**
	 * Registers jsonb_exists(json, key) function for SQLite.
	 * For JSON arrays: returns true if the array contains the key as a value.
	 * For JSON objects: returns true if the object has the key as a field name.
	 */
	private static void registerJsonbExists(SQLiteConnection conn) throws SQLException {
		Function.create(conn, "jsonb_exists", new Function() {
			@Override
			protected void xFunc() throws SQLException {
				if (args() < 2) {
					result(0);
					return;
				}
				var json = value_text(0);
				var key = value_text(1);
				if (json == null || key == null) {
					result(0);
					return;
				}
				try {
					var node = om.readTree(json);
					if (node.isArray()) {
						for (var elem : node) {
							if (elem.isTextual() && elem.asText().equals(key)) {
								result(1);
								return;
							}
						}
					} else if (node.isObject()) {
						if (node.has(key)) {
							result(1);
							return;
						}
					}
					result(0);
				} catch (Exception e) {
					result(0);
				}
			}
		});
	}

	private static final double EARTH_RADIUS_M = 6_371_008.7714; // PostGIS sphere (WGS84 mean radius)

	/**
	 * Registers geo_bbox, geo_near and geo_distance for SQLite, matching PostGIS safe_geom behavior.
	 */
	private static void registerGeoFunctions(SQLiteConnection conn) throws SQLException {
		Function.create(conn, "geo_bbox", new Function() {
			@Override
			protected void xFunc() throws SQLException {
				if (args() < 5) {
					result(0);
					return;
				}
				var geom = parseGeo(value_text(0));
				if (geom == null) {
					result(0);
					return;
				}
				var minLon = value_double(1);
				var minLat = value_double(2);
				var maxLon = value_double(3);
				var maxLat = value_double(4);
				result(geom.intersectsBbox(minLon, minLat, maxLon, maxLat) ? 1 : 0);
			}
		}, Function.FLAG_DETERMINISTIC);

		Function.create(conn, "geo_near", new Function() {
			@Override
			protected void xFunc() throws SQLException {
				if (args() < 4) {
					result(0);
					return;
				}
				var geom = parseGeo(value_text(0));
				if (geom == null) {
					result(0);
					return;
				}
				var dist = geom.distanceMeters(value_double(1), value_double(2));
				result(dist <= value_double(3) ? 1 : 0);
			}
		}, Function.FLAG_DETERMINISTIC);

		Function.create(conn, "geo_distance", new Function() {
			@Override
			protected void xFunc() throws SQLException {
				if (args() < 3) {
					result();
					return;
				}
				var geom = parseGeo(value_text(0));
				if (geom == null) {
					result();
					return;
				}
				result(geom.distanceMeters(value_double(1), value_double(2)));
			}
		}, Function.FLAG_DETERMINISTIC);
	}

	/**
	 * Geometry parsed like PostGIS safe_geom. Containment is planar in degrees and distances to edges are
	 * great-circle on a sphere, an approximation of PostGIS.
	 */
	private record ParsedGeo(List<double[]> points, List<List<double[]>> lines, List<List<List<double[]>>> polygons) {
		boolean intersectsBbox(double minLon, double minLat, double maxLon, double maxLat) {
			for (var p : points) {
				if (inBox(p, minLon, minLat, maxLon, maxLat)) return true;
			}
			for (var line : lines) {
				if (inBox(line.getFirst(), minLon, minLat, maxLon, maxLat)) return true;
				for (int i = 1; i < line.size(); i++) {
					if (segmentIntersectsBox(line.get(i - 1), line.get(i), minLon, minLat, maxLon, maxLat)) return true;
				}
			}
			for (var polygon : polygons) {
				for (var ring : polygon) {
					for (int i = 0, j = ring.size() - 1; i < ring.size(); j = i++) {
						if (segmentIntersectsBox(ring.get(j), ring.get(i), minLon, minLat, maxLon, maxLat)) return true;
					}
				}
				if (inPolygon(minLon, minLat, polygon)) return true;
			}
			return false;
		}

		double distanceMeters(double lon, double lat) {
			for (var polygon : polygons) {
				if (inPolygon(lon, lat, polygon)) return 0.0;
			}
			var p = unit(lon, lat);
			var min = Double.POSITIVE_INFINITY;
			for (var q : points) min = Math.min(min, angle(p, unit(q[0], q[1])));
			for (var line : lines) {
				if (line.size() == 1) min = Math.min(min, angle(p, unit(line.getFirst()[0], line.getFirst()[1])));
				for (int i = 1; i < line.size(); i++) min = Math.min(min, segmentAngle(p, line.get(i - 1), line.get(i)));
			}
			for (var polygon : polygons) {
				for (var ring : polygon) {
					for (int i = 0, j = ring.size() - 1; i < ring.size(); j = i++) min = Math.min(min, segmentAngle(p, ring.get(j), ring.get(i)));
				}
			}
			return min * EARTH_RADIUS_M;
		}
	}

	private static final Set<String> GEOJSON_TYPES = Set.of("Point", "LineString", "Polygon", "MultiPoint", "MultiLineString", "MultiPolygon", "GeometryCollection");

	private static ParsedGeo parseGeo(String json) {
		if (json == null) return null;
		try {
			var geo = new ParsedGeo(new ArrayList<>(), new ArrayList<>(), new ArrayList<>());
			if (!parseGeo(om.readTree(json), geo)) return null;
			if (geo.points.isEmpty() && geo.lines.isEmpty() && geo.polygons.isEmpty()) return null;
			return geo;
		} catch (Exception e) {
			return null;
		}
	}

	private static boolean parseGeo(JsonNode node, ParsedGeo geo) {
		if (node == null || !node.isObject()) return false;
		var type = node.path("type").asText(null);
		if ("FeatureCollection".equals(type)) {
			var features = node.get("features");
			if (features == null || !features.isArray()) return false;
			for (var f : features) {
				// Like ST_Collect, skip features without a usable geometry
				var feature = new ParsedGeo(new ArrayList<>(), new ArrayList<>(), new ArrayList<>());
				if (!parseGeo(f, feature)) continue;
				geo.points.addAll(feature.points);
				geo.lines.addAll(feature.lines);
				geo.polygons.addAll(feature.polygons);
			}
			return true;
		}
		if ("Feature".equals(type)) {
			node = node.get("geometry");
			if (node == null || !node.isObject()) return false;
			type = node.path("type").asText(null);
		}
		if (type != null && GEOJSON_TYPES.contains(type)) {
			// [0, 0] is the unset default of a Point
			if ("Point".equals(type) && node.path("coordinates").path(0).asDouble(1) == 0 && node.path("coordinates").path(1).asDouble(1) == 0) return false;
			return extractGeoJson(node, type, geo);
		}
		// First fully numeric pair, in the same order as safe_geom
		for (var keys : new String[][]{{"lat", "lng"}, {"lat", "lon"}, {"latitude", "longitude"}}) {
			var latNode = node.path(keys[0]);
			var lonNode = node.path(keys[1]);
			if (!latNode.isNumber() || !lonNode.isNumber()) continue;
			var lon = lonNode.asDouble();
			var lat = latNode.asDouble();
			if (!validCoord(lon, lat)) return false;
			geo.points.add(new double[]{lon, lat});
			return true;
		}
		return false;
	}

	private static boolean extractGeoJson(JsonNode node, String type, ParsedGeo geo) {
		var coords = node.get("coordinates");
		return switch (type) {
			case "Point" -> {
				var p = coord(coords);
				if (p == null) yield false;
				geo.points.add(p);
				yield true;
			}
			case "MultiPoint" -> {
				var ps = coords(coords);
				if (ps == null) yield false;
				geo.points.addAll(ps);
				yield true;
			}
			case "LineString" -> {
				var line = coords(coords);
				if (line == null) yield false;
				if (!line.isEmpty()) geo.lines.add(line);
				yield true;
			}
			case "MultiLineString" -> {
				if (coords == null || !coords.isArray()) yield false;
				for (var c : coords) {
					var line = coords(c);
					if (line == null) yield false;
					if (!line.isEmpty()) geo.lines.add(line);
				}
				yield true;
			}
			case "Polygon" -> addPolygon(coords, geo);
			case "MultiPolygon" -> {
				if (coords == null || !coords.isArray()) yield false;
				for (var poly : coords) {
					if (!addPolygon(poly, geo)) yield false;
				}
				yield true;
			}
			case "GeometryCollection" -> {
				var geoms = node.get("geometries");
				if (geoms == null || !geoms.isArray()) yield false;
				for (var g : geoms) {
					if (!g.isObject() || !extractGeoJson(g, g.path("type").asText(""), geo)) yield false;
				}
				yield true;
			}
			default -> false;
		};
	}

	private static boolean addPolygon(JsonNode arr, ParsedGeo geo) {
		if (arr == null || !arr.isArray()) return false;
		var polygon = new ArrayList<List<double[]>>();
		for (var c : arr) {
			var ring = coords(c);
			if (ring == null) return false;
			if (!ring.isEmpty()) polygon.add(ring);
		}
		if (!polygon.isEmpty()) geo.polygons.add(polygon);
		return true;
	}

	private static double[] coord(JsonNode coord) {
		if (coord == null || !coord.isArray() || coord.size() < 2) return null;
		if (!coord.get(0).isNumber() || !coord.get(1).isNumber()) return null;
		var lon = coord.get(0).asDouble();
		var lat = coord.get(1).asDouble();
		if (!validCoord(lon, lat)) return null;
		return new double[]{lon, lat};
	}

	private static List<double[]> coords(JsonNode arr) {
		if (arr == null || !arr.isArray()) return null;
		var result = new ArrayList<double[]>();
		for (var c : arr) {
			var p = coord(c);
			if (p == null) return null;
			result.add(p);
		}
		return result;
	}

	private static boolean validCoord(double lon, double lat) {
		return Double.isFinite(lon) && Double.isFinite(lat)
			&& lon >= -180.0 && lon <= 180.0 && lat >= -90.0 && lat <= 90.0;
	}

	private static boolean inBox(double[] p, double minLon, double minLat, double maxLon, double maxLat) {
		return p[0] >= minLon && p[0] <= maxLon && p[1] >= minLat && p[1] <= maxLat;
	}

	/**
	 * Liang-Barsky clipping of segment a-b against the box.
	 */
	private static boolean segmentIntersectsBox(double[] a, double[] b, double minLon, double minLat, double maxLon, double maxLat) {
		double t0 = 0, t1 = 1;
		double dx = b[0] - a[0], dy = b[1] - a[1];
		double[] p = {-dx, dx, -dy, dy};
		double[] q = {a[0] - minLon, maxLon - a[0], a[1] - minLat, maxLat - a[1]};
		for (int i = 0; i < 4; i++) {
			if (p[i] == 0) {
				if (q[i] < 0) return false;
			} else {
				var t = q[i] / p[i];
				if (p[i] < 0) t0 = Math.max(t0, t);
				else t1 = Math.min(t1, t);
				if (t0 > t1) return false;
			}
		}
		return true;
	}

	/**
	 * Inside the exterior ring and outside every hole.
	 */
	private static boolean inPolygon(double x, double y, List<List<double[]>> polygon) {
		if (!pointInRing(x, y, polygon.getFirst())) return false;
		for (int i = 1; i < polygon.size(); i++) {
			if (pointInRing(x, y, polygon.get(i))) return false;
		}
		return true;
	}

	private static boolean pointInRing(double x, double y, List<double[]> ring) {
		boolean inside = false;
		for (int i = 0, j = ring.size() - 1; i < ring.size(); j = i++) {
			double xi = ring.get(i)[0], yi = ring.get(i)[1];
			double xj = ring.get(j)[0], yj = ring.get(j)[1];
			if (((yi > y) != (yj > y)) && (x < (xj - xi) * (y - yi) / (yj - yi) + xi)) {
				inside = !inside;
			}
		}
		return inside;
	}

	private static double[] unit(double lon, double lat) {
		double phi = Math.toRadians(lat), lambda = Math.toRadians(lon);
		return new double[]{Math.cos(phi) * Math.cos(lambda), Math.cos(phi) * Math.sin(lambda), Math.sin(phi)};
	}

	private static double[] cross(double[] a, double[] b) {
		return new double[]{a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]};
	}

	private static double dot(double[] a, double[] b) {
		return a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
	}

	private static double norm(double[] a) {
		return Math.sqrt(dot(a, a));
	}

	/**
	 * Central angle between unit vectors.
	 */
	private static double angle(double[] a, double[] b) {
		return Math.atan2(norm(cross(a, b)), dot(a, b));
	}

	/**
	 * Central angle from p to the great-circle arc a-b.
	 */
	private static double segmentAngle(double[] p, double[] a, double[] b) {
		var ua = unit(a[0], a[1]);
		var ub = unit(b[0], b[1]);
		var endpoints = Math.min(angle(p, ua), angle(p, ub));
		var n = cross(ua, ub);
		var len = norm(n);
		if (len < 1e-15) return endpoints;
		// p projects inside the arc when it lies between the planes through a and b perpendicular to the arc
		if (dot(cross(ua, p), n) < 0 || dot(cross(p, ub), n) < 0) return endpoints;
		return Math.min(endpoints, Math.abs(Math.asin(Math.max(-1, Math.min(1, dot(p, n) / len)))));
	}
}