Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save damulhan/4c6753f39c09b8e3170708cbe1dbb7d0 to your computer and use it in GitHub Desktop.
Save damulhan/4c6753f39c09b8e3170708cbe1dbb7d0 to your computer and use it in GitHub Desktop.
(ns example.update
(:require [clojure.set :as set]
[clojure.walk :as walk]))
;; 두 해시맵에서 값이 다른 키들을 찾는 함수
(defn diff-keys [old new]
(filter (fn [k] (not= (get old k) (get new k)))
(set/union (set (keys old)) (set (keys new)))))
;; SQL UPDATE 쿼리를 생성하는 함수
(defn generate-update-query [table old new]
(let [diff-keys (diff-keys old new)
set-clause (map (fn [k]
(str (name k) " = :" (name k)))
diff-keys)
query (str "UPDATE " table " SET "
(clojure.string/join ", " set-clause)
" WHERE id = :id")]
{:query query
:params (select-keys new (cons :id diff-keys))}))
;; 예제 데이터
(def old-hash {:id 1 :name "Alice" :age 30 :city "New York"})
(def new-hash {:id 1 :name "Alice" :age 31 :city "San Francisco"})
;; 업데이트 쿼리 생성
(def result (generate-update-query "users" old-hash new-hash))
;; 결과 출력
(println (:query result))
(println (:params result))
;; After executing:
;; UPDATE users SET age = :age, city = :city WHERE id = :id
;; {:id 1, :age 31, :city "San Francisco"}
;;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment