| 1 |
# frozen_string_literal: true |
| 2 |
|
| 3 |
require 'digest/md5' |
| 4 |
|
| 5 |
# @summary This function escapes a string using [Dollar Quoting](https://www.postgresql.org/docs/12/sql-syntax-lexical.html#SQL-SYNTAX-DOLLAR-QUOTING) using a randomly generated tag if required. |
| 6 |
Puppet::Functions.create_function(:'postgresql::postgresql_escape') do |
| 7 |
# @param input_string |
| 8 |
# The unescaped string you want to escape using `dollar quoting` |
| 9 |
# |
| 10 |
# @return [String] |
| 11 |
# A `Dollar Quoted` string |
| 12 |
dispatch :default_impl do |
| 13 |
param 'String[1]', :input_string |
| 14 |
end |
| 15 |
|
| 16 |
def default_impl(input_string) |
| 17 |
# Where allowed, just return the original string wrapped in `$$` |
| 18 |
return "$$#{input_string}$$" unless tag_needed?(input_string) |
| 19 |
|
| 20 |
# Keep generating possible values for tag until we find one that doesn't appear in the input string |
| 21 |
tag = Digest::MD5.hexdigest(input_string)[0..5].gsub(%r{\d}, '') |
| 22 |
tag = Digest::MD5.hexdigest(tag)[0..5].gsub(%r{\d}, '') until input_string !~ %r{#{tag}} |
| 23 |
|
| 24 |
"$#{tag}$#{input_string}$#{tag}$" |
| 25 |
end |
| 26 |
|
| 27 |
def tag_needed?(input_string) |
| 28 |
input_string.include?('$$') || input_string.end_with?('$') |
| 29 |
end |
| 30 |
end |