GRANT SELECT ON unit_prefixes, unit_units TO PUBLIC;

CREATE OR REPLACE FUNCTION unit_load()
	RETURNS VOID
	LANGUAGE plpgsql
	AS $$BEGIN
DELETE FROM unit_prefixes WHERE dump IS NOT TRUE;
CREATE TEMP TABLE tmp_prefixes (LIKE unit_prefixes) ON COMMIT DROP;
COPY tmp_prefixes (prefix, factor, definition, dump) FROM '@MODULEDIR@/unit_prefixes.data';
INSERT INTO unit_prefixes
	SELECT * FROM tmp_prefixes t WHERE NOT EXISTS
		(SELECT prefix FROM unit_prefixes u WHERE u.prefix = t.prefix);
DROP TABLE tmp_prefixes;

DELETE FROM unit_units WHERE dump IS NOT TRUE;
CREATE TEMP TABLE tmp_units (LIKE unit_units) ON COMMIT DROP;
COPY tmp_units (name, unit, shift, definition, dump) FROM '@MODULEDIR@/unit_units.data';
INSERT INTO unit_units
	SELECT * FROM tmp_units t WHERE NOT EXISTS
		(SELECT name FROM unit_units u WHERE u.name = t.name);
DROP TABLE tmp_units;
END;$$;

COMMENT ON FUNCTION unit_load() IS 'Loads/upgrades the unit_units and unit_prefixes contents from the data files on disk';

SELECT unit_load();

CREATE FUNCTION unit_at_double(unit, text)
	RETURNS double precision
	SET search_path = @extschema@
	AS '$libdir/unit', 'unit_at_double'
	LANGUAGE C IMMUTABLE STRICT;

CREATE OPERATOR @@ (
	leftarg = unit,
	rightarg = text,
	procedure = unit_at_double
);
