-- Protect against this script being sourced by psql.
\echo Use "CREATE EXTENSION" to load this file. \quit


CREATE TYPE image;       -- create an empty "shell" type.

CREATE FUNCTION image_in(cstring) RETURNS image
    STRICT IMMUTABLE
    AS 'MODULE_PATHNAME', 'pg_image_in' LANGUAGE C;

CREATE FUNCTION image_out(image) RETURNS cstring
    STRICT IMMUTABLE
    AS 'MODULE_PATHNAME', 'pg_image_out' LANGUAGE C;

CREATE FUNCTION image_in_text(text) RETURNS image
    STRICT IMMUTABLE
    AS 'MODULE_PATHNAME', 'pg_image_in_text' LANGUAGE C;

CREATE FUNCTION image_out_text(image) RETURNS text
    STRICT IMMUTABLE
    AS 'MODULE_PATHNAME', 'pg_image_out_text' LANGUAGE C;

CREATE FUNCTION image(data BYTEA, mimetype TEXT) RETURNS image
    STRICT IMMUTABLE
    AS 'MODULE_PATHNAME', 'pg_image_from_bytea' LANGUAGE C;

CREATE TYPE image (
    INPUT = image_in,
    OUTPUT = image_out,
    INTERNALLENGTH = VARIABLE,
    ALIGNMENT = int4,
    STORAGE = EXTERNAL          /* Is TOASTable, but do not try to compress. */
);

-- Info functions for IMAGE type.

CREATE FUNCTION width(image) RETURNS int
    STRICT IMMUTABLE
    AS 'MODULE_PATHNAME', 'pg_image_width' LANGUAGE C;

CREATE FUNCTION height(image) RETURNS int
    STRICT IMMUTABLE
    AS 'MODULE_PATHNAME', 'pg_image_height' LANGUAGE C;

CREATE FUNCTION filesize(image) RETURNS int
    STRICT IMMUTABLE
    AS 'MODULE_PATHNAME', 'pg_image_filesize' LANGUAGE C;

CREATE FUNCTION mimetype(image) RETURNS text
    STRICT IMMUTABLE
    AS 'MODULE_PATHNAME', 'pg_image_mimetype' LANGUAGE C;

CREATE FUNCTION imagedata(image) RETURNS bytea
    STRICT IMMUTABLE
    AS 'MODULE_PATHNAME', 'pg_image_imagedata' LANGUAGE C;

-- Comparison functions and operators for IMAGE type.

CREATE FUNCTION image_eq(image, image) RETURNS bool
    STRICT IMMUTABLE
    AS 'MODULE_PATHNAME', 'pg_image_eq' LANGUAGE C;

CREATE FUNCTION image_ne(image, image) RETURNS bool
    STRICT IMMUTABLE
    AS 'MODULE_PATHNAME', 'pg_image_ne' LANGUAGE C;

CREATE FUNCTION image_hash(image) RETURNS int4
    STRICT IMMUTABLE
    AS 'MODULE_PATHNAME', 'pg_image_hash' LANGUAGE C;

CREATE OPERATOR = (
    LEFTARG = image,
    RIGHTARG = image,
    NEGATOR = <>,
    PROCEDURE = image_eq,
    COMMUTATOR = =,
    RESTRICT = eqsel,
    JOIN = eqjoinsel,
    MERGES,
    HASHES
);

CREATE OPERATOR <> (
    LEFTARG = image,
    RIGHTARG = image,
    NEGATOR = =,
    PROCEDURE = image_ne
);

CREATE OPERATOR CLASS image_ops
    DEFAULT FOR TYPE image
    USING hash AS
        OPERATOR    1   = (image, image),
        FUNCTION    1   image_hash(image);
