Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> MySQL

ฟังก์ชัน whoami ใน MySQL - ใช้ USER() หรือ CURRENT_USER() แทน

MySQL ไม่มี whoami() แต่มี USER() และ CURRENT_USER()

คำสั่ง whoami ใน Unix/Linux ใช้ดู User ปัจจุบัน ใน MySQL ใช้ฟังก์ชัน 2 ตัวนี้

1. CURRENT_USER() - User ที่ Authentication ผ่าน

SELECT CURRENT_USER();

ผลลัพธ์: root@%

คืนค่า User account ที่ใช้ Authenticate เข้ามา (จาก mysql.user) รวม Host ที่อนุญาต

2. USER() - User ที่ Client ส่งมา + Host จริง

SELECT USER();

ผลลัพธ์: root@localhost

คืนค่า User ที่ Client ระบุ + Host ที่เชื่อมต่อจริง (อาจต่างจาก CURRENT_USER ถ้า Proxy/SSL)

ความแตกต่างสำคัญ

ฟังก์ชันแหล่งที่มาใช้เมื่อไหร่
CURRENT_USER()Authentication context (mysql.user)ตรวจสอบสิทธิ์จริง, Stored Routine DEFINER
USER()Client connection infoAudit log, Debug connection source

ตัวอย่าง: ใน Stored Procedure ที่มี DEFINER

CREATE DEFINER = 'admin'@'%' PROCEDURE test_whoami()
BEGIN
    SELECT USER() AS client_user, CURRENT_USER() AS definer_user;
END;

-- เรียกโดย user 'app'@'localhost'
CALL test_whoami();

ผลลัพธ์:

client_userdefiner_user
app@localhostadmin@%

สรุป: ใช้ CURRENT_USER() สำหรับ Permission/Definer context, ใช้ USER() สำหรับ Connection audit