Skip to content

Database insert function taking Phel map #4

@jasalt

Description

@jasalt

It would be nice to have a simple function that inserts a map representing column names with their row values into DB. I'm not fully sure how it should be secured against injection attacks and such but prepared statements seem to offer some protection. Quick example how it might work:

(defn pdo-insert-map
    [conn table m]
    (let [m-keys (keys m)
         column-names (str/join ", " (map name m-keys))
         placeholders (str/join ", " m-keys)
         stmt-sql (str "INSERT INTO " table " (" column-names ") "
                       "VALUES (" placeholders ")")
         stmt (pdo/prepare pdo-conn stmt-sql)]

		 (dofor [[k v] :pairs m]
				(statement/bind-value stmt k v))

		 (php/-> (stmt :stmt) (execute))))

(pdo-insert-map pdo-conn "my_table"
                {:uuid   "testuuid11"
                :create_date "2024-01-01 11:11:11"          
                :order_id   234
                :product_id 345
                :qty        5
                })

It does not allow re-using same statement over multiple calls and does not set types explicitly (if needed?) but maybe it could be split up into parts that would simplify the insertion process while helping with security.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions