如何从命令行将 html-template 文件插入到 postgresql 字段中

How can I insert an html-template file into postgresql field from command line

我在 postgresql table 中有一个 html 模板,我需要从 cmdline 获取和更新它。

我的想法是使用 Makefile 来更新字段。

我想,我可以使用这个命令来获取文件,使用 Makefile 中的一个函数。

psql_conn=psql -U ${pg_user} -p $(pg_port_staging) -h $(pg_host) -d $(pg_database)
psql_shell=--tuples-only -P format=unaligned

fetch: ## fetch a given template id=XX
ifndef id
    @echo "Missing id=XX"
    @$(MAKE) list
    @exit 1
else
    $(call fetch_template,$(id),$(call fetch_name,$(id)))
endif

define fetch_template
    $(shell echo "SELECT template FROM pdf_templates WHERE id = $(1)" | ${psql_conn} $(psql_shell} > $(2).html)
endef

define fetch_name
  ...
endef

但是,我在编辑后再次将此模板插入 table 时遇到问题。

示例模板文件可能是这样的,因此它将包含 + { $ 和 UTF8 字符。

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" xml:lang="en" lang="en">
<head>
    <style type="text/css" th:inline="text">
        body { margin: 0; font-family: Verdana, Geneva, sans-serif; font-size: 11px; }
        a { text-decoration: none; }
</style>
</head
<body>
<div th:if="${hasAddresses}">
            <h2>Adresser:</h2>
            <article th:each="offerElement: ${offer.getElementsWithData().?[specification?.get('elementType') == 'fiber']}">
                <div th:with="address=${offerElement.getParsedData().get()}">
                    <br /><span th:text="${address['deliveryStreet']}"></span> <span th:text="${address['deliveryHouseNumber']}"></span>
                    <span th:text="${address['deliveryFloor']}"></span> <span th:text="${address['deliveryDoor']}"></span>
                    <br /><span th:text="${address['deliveryZipCode']}"></span> <span th:text="${address['deliveryCity']}"></span>
                    <br /><span th:text="${address['deliveryCountry']}"></span>
                </div>
            </article>
        </div>
</body>
</html>

这是一个远程服务器,我没有 shell 访问权限。所以它不是使用 pg_read_file

的选项

我已经有了使用 \lo_import File.html 将文件上传到服务器的想法,但无法弄清楚如何将内容写入 table,而不仅仅是显示在 LargeObject table 中。

另一种解决方案可能是使用 Ruby 或 Python,但我希望它尽可能简单。

psql 版本 i 9.4 但是服务器是 运行 postgresql server 10.4。

通过将内容转换为 base64 找到解决方案

define write_template
$(shell echo "UPDATE table SET template = convert_from(decode('$(shell base64 $(1))', 'base64'),'UTF8') WHERE name = '$(2)'" | ${psql_input})
endef

所以从base64 filename.html中取出内容并使用postgresql中的convert_from( decode($content , 'base64'),'UTF8')函数首先将内容解码为bytestring,然后将其转换为UTF-8格式。

${psql_input} 只是 psql 和 user/host 个参数。