Skip to content

Commit

Permalink
เพิ่ม comment คำสั่ง SQL เพื่อเปรียบเทียบคำสั่ง SQL กับ JOOQ
Browse files Browse the repository at this point in the history
rushmi0 committed Apr 12, 2024
1 parent 5d57e97 commit 450fdf4
Showing 6 changed files with 324 additions and 131 deletions.
Original file line number Diff line number Diff line change
@@ -27,10 +27,9 @@ import java.time.OffsetDateTime
@Introspected
class DogWalkBookingsServiceImpl @Inject constructor(
private val query: DSLContext,
taskDispatcher: CoroutineDispatcher?
private val dispatcher: CoroutineDispatcher = Dispatchers.IO
) : DogWalkBookingsService {

private val dispatcher: CoroutineDispatcher = taskDispatcher ?: Dispatchers.IO

override suspend fun bookingsAll(): List<DogWalkBookingsField> {
return withContext(dispatcher) {
@@ -40,6 +39,10 @@ class DogWalkBookingsServiceImpl @Inject constructor(
val data = query.select()
.from(DOGWALKBOOKINGS)

/**
* SELECT *
* FROM dogwalkbookings;
*/
LOG.info("\n${data.fetch()}")

val result = data.map { record ->
@@ -59,27 +62,32 @@ class DogWalkBookingsServiceImpl @Inject constructor(
}

if (result.isNotEmpty()) {
LOG.info("Retrieve bookings operation successful on thread [${Thread.currentThread().name}]")
LOG.info("Retrieve bookings operation successful")
} else {
LOG.warn("No bookings found on thread [${Thread.currentThread().name}]")
LOG.warn("No bookings found")
}

return@withContext result
} catch (e: Exception) {
LOG.error("Error during retrieve bookings operation on thread [${Thread.currentThread().name}]", e)
LOG.error("Error during retrieve bookings operation", e)
emptyList()
}
}
}



override suspend fun insert(userID: Int, payload: DogWalkBookings): Boolean {
return withContext(dispatcher) {
val currentThreadName = Thread.currentThread().name

try {
LOG.info("Insert operation started on thread [$currentThreadName]")

LOG.info("Insert operation started")

/**
* INSERT INTO dogwalkbookings
* (walker_id, user_id, dog_id, booking_date, time_start, time_end)
* VALUES
* (:payload.walkerID, :userID, :payload.dogID, :payload.bookingDate, :payload.timeStart, :payload.timeEnd);
*/
val result = query.insertInto(
DOGWALKBOOKINGS,
DOGWALKBOOKINGS.WALKER_ID,
@@ -100,20 +108,21 @@ class DogWalkBookingsServiceImpl @Inject constructor(
.execute()

if (result > 0) {
LOG.info("Insert successful on thread [$currentThreadName]")
LOG.info("Insert successful")
} else {
LOG.warn("Insert did not affect any rows on thread [$currentThreadName]")
LOG.warn("Insert did not affect any rows")
}

return@withContext result > 0
} catch (e: Exception) {
LOG.error("Error during insert operation on thread [$currentThreadName]", e)
LOG.error("Error during insert operation", e)
false
}
}
}



override suspend fun updateSingleField(id: Int, fieldName: String, newValue: String): Boolean {
return withContext(dispatcher) {
try {
@@ -164,29 +173,34 @@ class DogWalkBookingsServiceImpl @Inject constructor(

override suspend fun delete(id: Int): Boolean {
return withContext(dispatcher) {
val currentThreadName = Thread.currentThread().name
val stackTrace = Thread.currentThread().stackTrace
try {
LOG.info("Delete operation started on thread [$currentThreadName]")
LOG.info("Delete operation started from [$stackTrace]")

/**
* DELETE FROM dogwalkbookings
* WHERE booking_id = :id;
*/
val deletedRows = query.deleteFrom(DOGWALKBOOKINGS)
.where(DOGWALKBOOKINGS.BOOKING_ID.eq(DSL.`val`(id)))
.execute()

if (deletedRows > 0) {
LOG.info("Delete successful for booking with ID [$id] on thread [$currentThreadName]")
LOG.info("Delete successful for booking with ID [$id]")
} else {
LOG.warn("Delete did not affect any rows for booking with ID [$id] on thread [$currentThreadName]")
LOG.warn("Delete did not affect any rows for booking with ID [$id] from [$stackTrace]")
}

return@withContext deletedRows > 0
} catch (e: Exception) {
LOG.error("Error during delete operation for booking with ID [$id] on thread [$currentThreadName]", e)
LOG.error("Error during delete operation for booking with ID [$id] from [$stackTrace]", e)
false
}
}
}



companion object {
private val LOG: Logger = LoggerFactory.getLogger(DogWalkBookingsServiceImpl::class.java)
}
Original file line number Diff line number Diff line change
@@ -24,18 +24,20 @@ import org.slf4j.LoggerFactory
@Introspected
class DogWalkerReviewServiceImpl @Inject constructor(
private val query: DSLContext,
taskDispatcher: CoroutineDispatcher?
private val dispatcher: CoroutineDispatcher = Dispatchers.IO
) : DogWalkerReviewService {

private val dispatcher: CoroutineDispatcher = taskDispatcher ?: Dispatchers.IO

override suspend fun dogWalkerReviewAll(): List<DogWalkerReviewField> {
return withContext(dispatcher) {
val currentThreadName = Thread.currentThread().name
val stackTrace = Thread.currentThread().stackTrace

try {
LOG.info("Retrieve dog walker reviews operation started on thread [$currentThreadName]")
LOG.info("Retrieve dog walker reviews operation started")

/**
* SELECT * FROM dogwalkerreviews;
*/
val data = query.select()
.from(DOGWALKERREVIEWS)

@@ -50,26 +52,31 @@ class DogWalkerReviewServiceImpl @Inject constructor(
}

if (result.isNotEmpty()) {
LOG.info("Retrieve dog walker reviews operation successful on thread [$currentThreadName]")
LOG.info("Retrieve dog walker reviews operation successful")
} else {
LOG.warn("No dog walker reviews found on thread [$currentThreadName]")
LOG.warn("No dog walker reviews found from [$stackTrace]")
}

return@withContext result
} catch (e: Exception) {
LOG.error("Error during retrieve dog walker reviews operation on thread [$currentThreadName]", e)
LOG.error("Error during retrieve dog walker reviews operation from [$stackTrace]", e)
return@withContext emptyList()
}
}
}


override suspend fun insert(payload: DogWalkerReviewForm): Boolean {
return withContext(dispatcher) {
val currentThreadName = Thread.currentThread().name
val stackTrace = Thread.currentThread().stackTrace

try {
LOG.info("Insert dog walker review operation started on thread [$currentThreadName]")
LOG.info("Insert dog walker review operation started")

/**
* INSERT INTO dogwalkerreviews (walker_id, user_id, rating, review_text)
* VALUES (:walkerID, :userID, :rating, :reviewText);
*/
val result = query.insertInto(
DOGWALKERREVIEWS,
DOGWALKERREVIEWS.WALKER_ID,
@@ -86,20 +93,21 @@ class DogWalkerReviewServiceImpl @Inject constructor(
.execute()

if (result > 0) {
LOG.info("Insert dog walker review successful on thread [$currentThreadName]")
LOG.info("Insert dog walker review successful")
} else {
LOG.warn("Insert dog walker review did not affect any rows on thread [$currentThreadName]")
LOG.warn("Insert dog walker review did not affect any rows from [$stackTrace]")
}

return@withContext result > 0
} catch (e: Exception) {
LOG.error("Error during insert dog walker review operation on thread [$currentThreadName]", e)
LOG.error("Error during insert dog walker review operation from [$stackTrace]", e)
return@withContext false
}
}
}



override suspend fun updateSingleField(id: Int, fieldName: String, newValue: String): Boolean {
return withContext(dispatcher) {
try {
@@ -147,25 +155,29 @@ class DogWalkerReviewServiceImpl @Inject constructor(

override suspend fun delete(id: Int): Boolean {
return withContext(dispatcher) {
val currentThreadName = Thread.currentThread().name
val stackTrace = Thread.currentThread().stackTrace

try {
LOG.info("Delete dog walker review operation started on thread [$currentThreadName]")
LOG.info("Delete dog walker review operation started")

/**
* DELETE FROM dogwalkerreviews
* WHERE review_id = :id;
*/
val result = query.deleteFrom(DOGWALKERREVIEWS)
.where(DOGWALKERREVIEWS.REVIEW_ID.eq(DSL.`val`(id))) // ใช้ DSL.`val` เพื่อทำเป็น bind parameter
.where(DOGWALKERREVIEWS.REVIEW_ID.eq(DSL.`val`(id)))
.execute()

if (result > 0) {
LOG.info("Delete dog walker review successful for Dog Walker Review ID [$id] on thread [$currentThreadName]")
LOG.info("Delete dog walker review successful for Dog Walker Review ID [$id]")
} else {
LOG.warn("Delete dog walker review did not affect any rows for Dog Walker Review ID [$id] on thread [$currentThreadName]")
LOG.warn("Delete dog walker review did not affect any rows for Dog Walker Review ID [$id] from [$stackTrace]")
}

return@withContext result > 0
} catch (e: Exception) {
LOG.error(
"Error during delete dog walker review operation for Dog Walker Review ID [$id] on thread [$currentThreadName]",
"Error during delete dog walker review operation for Dog Walker Review ID [$id] from [$stackTrace]",
e
)
return@withContext false
@@ -174,6 +186,7 @@ class DogWalkerReviewServiceImpl @Inject constructor(
}



companion object {
private val LOG: Logger = LoggerFactory.getLogger(DogWalkerReviewServiceImpl::class.java)
}
Original file line number Diff line number Diff line change
@@ -30,16 +30,21 @@ import win.rushmi0.jungmha.utils.ShiftTo.toFileName
@Introspected
class DogsServiceImpl @Inject constructor(
private val query: DSLContext,
coroutineDispatcher: CoroutineDispatcher?
private val dispatcher: CoroutineDispatcher = Dispatchers.IO
) : DogsService {

private val dispatcher: CoroutineDispatcher = coroutineDispatcher ?: Dispatchers.IO


override suspend fun findDog(dogID: Int): DogField? {
return try {
val currentThreadName = Thread.currentThread().name
LOG.info("Thread $currentThreadName executing findDog")

/**
* SELECT *
* FROM dogs
* WHERE dogs.dog_id = :dogID;
*/
val record: Record? = withContext(dispatcher) {
query.select()
.from(DOGS)
@@ -82,6 +87,10 @@ class DogsServiceImpl @Inject constructor(
try {
LOG.info("Retrieve dogs operation started on thread [$currentThreadName]")

/**
* SELECT *
* FROM dogs;
*/
val data = query.select()
.from(DOGS)

@@ -111,13 +120,18 @@ class DogsServiceImpl @Inject constructor(
}



override suspend fun insert(payload: DogForm): Boolean {
return withContext(dispatcher) {
val currentThreadName = Thread.currentThread().name

try {
LOG.info("Insert dog operation started on thread [$currentThreadName]")

/**
* INSERT INTO dogs (dog_image, breed_name, size)
* VALUES (dogImage, breedName, size);
*/
val result = query.insertInto(
DOGS,
DOGS.DOG_IMAGE,
@@ -146,6 +160,7 @@ class DogsServiceImpl @Inject constructor(
}



override suspend fun updateSingleField(id: Int, fieldName: String, newValue: String): Boolean {
return withContext(dispatcher) {
try {
@@ -159,6 +174,13 @@ class DogsServiceImpl @Inject constructor(
}
}

LOG.info("Update operation started for field [$fieldName] with new value [$newValue] for Dog ID [$id]")

/**
* UPDATE dogs
* SET $fieldName = :newValue
* WHERE dog_id = :id;
*/
val affectedRows = query.update(DOGS)
.set(field, DSL.`val`(newValue))
.where(DOGS.DOG_ID.eq(id)).execute()
@@ -178,13 +200,18 @@ class DogsServiceImpl @Inject constructor(
}



override suspend fun delete(id: Int): Boolean {
return withContext(dispatcher) {
val currentThreadName = Thread.currentThread().name

try {
LOG.info("Delete dog operation started on thread [$currentThreadName]")

/**
* DELETE FROM dogs
* WHERE dog_id = :id;
*/
val result = query.deleteFrom(DOGS)
.where(DOGS.DOG_ID.eq(id))
.execute()
@@ -203,6 +230,7 @@ class DogsServiceImpl @Inject constructor(
}
}


companion object {
private val LOG: Logger = LoggerFactory.getLogger(DogsServiceImpl::class.java)
}
Original file line number Diff line number Diff line change
@@ -14,6 +14,7 @@ import org.jooq.impl.DSL
import win.rushmi0.jungmha.constants.BaseEndpoint.BASE_URL_USER
import win.rushmi0.jungmha.database.field.DogWalkerField
import win.rushmi0.jungmha.database.record.*
import win.rushmi0.jungmha.database.service.DogsWalkersService
import win.rushmi0.jungmha.infra.database.tables.Dogs.DOGS
import win.rushmi0.jungmha.infra.database.tables.Dogwalkbookings.DOGWALKBOOKINGS
import win.rushmi0.jungmha.infra.database.tables.Dogwalkerreviews.DOGWALKERREVIEWS
@@ -31,10 +32,9 @@ import org.slf4j.LoggerFactory
@Introspected
class DogsWalkersServiceImpl @Inject constructor(
private val query: DSLContext,
taskDispatcher: CoroutineDispatcher?
) : win.rushmi0.jungmha.database.service.DogsWalkersService {
private val dispatcher: CoroutineDispatcher = Dispatchers.IO
) : DogsWalkersService {

private val dispatcher: CoroutineDispatcher = taskDispatcher ?: Dispatchers.IO

override suspend fun getSingleDogWalkersInfo(id: Int): DogWalkerField? {
return withContext(dispatcher) {
@@ -105,47 +105,29 @@ class DogsWalkersServiceImpl @Inject constructor(
val d = DOGS.`as`("d")
val dwb = DOGWALKBOOKINGS.`as`("dwb")

val subQuery = query
.select(
dwb.BOOKING_ID,
up.USERNAME.`as`("user_name"),
d.BREED_NAME,
d.SIZE,
dwb.BOOKING_DATE,
dwb.TIME_START,
dwb.TIME_END,
dwb.DURATION,
dwb.TOTAL,
dwb.STATUS,
dwb.TIMESTAMP,
dwb.SERVICE_STATUS
)
.from(dwb)
.join(dw)
.on(dwb.WALKER_ID.eq(dw.WALKER_ID))
.join(up)
.on(dw.USER_ID.eq(up.USER_ID))
.join(d)
.on(dwb.DOG_ID.eq(d.DOG_ID))
.where(up.USERNAME.eq(DSL.`val`(accountName)))

val subQueryResult = subQuery.fetch { subRecord ->
BookingList(
subRecord[dwb.BOOKING_ID],
subRecord["user_name"].toString(),
subRecord[d.BREED_NAME],
subRecord[d.SIZE],
subRecord[dwb.STATUS],
subRecord[dwb.BOOKING_DATE],
subRecord[dwb.TIME_START],
subRecord[dwb.TIME_END],
subRecord[dwb.DURATION],
subRecord[dwb.TOTAL],
subRecord[dwb.TIMESTAMP],
subRecord[dwb.SERVICE_STATUS]
)
}

/**
* SELECT dw.walker_id,
* up.image_profile,
* up.username,
* up.first_name,
* up.last_name,
* up.email,
* up.phone_number,
* up.user_type,
* dw.count_used,
* dw.count_review,
* dw.total_review,
* dw.location_name,
* dw.verification,
* dw.price_small,
* dw.price_medium,
* dw.price_big,
* dw.id_card_number
* FROM userprofiles up
* JOIN dogwalkers dw ON up.user_id = dw.user_id
* WHERE up.username = :accountName
* AND up.user_type = 'DogWalkers';
*/
val mainQuery = query.select(
dw.WALKER_ID,
up.IMAGE_PROFILE,
@@ -166,8 +148,7 @@ class DogsWalkersServiceImpl @Inject constructor(
dw.ID_CARD_NUMBER
)
.from(up)
.join(dw)
.on(up.USER_ID.eq(dw.USER_ID))
.join(dw).on(up.USER_ID.eq(dw.USER_ID))
.where(
up.USERNAME.eq(DSL.`val`(accountName))
)
@@ -201,14 +182,71 @@ class DogsWalkersServiceImpl @Inject constructor(
)
),

booking = subQueryResult
booking = emptyList()
)
}

/**
* SELECT dwb.booking_id,
* up.username AS user_name,
* d.breed_name,
* d.size,
* dwb.status,
* dwb.booking_date,
* dwb.time_start,
* dwb.time_end,
* dwb.duration,
* dwb.total,
* dwb.timestamp,
* dwb.service_status
* FROM dogwalkbookings dwb
* JOIN dogwalkers dw ON dwb.walker_id = dw.walker_id
* JOIN userprofiles up ON dw.user_id = up.user_id
* JOIN dogs d ON dwb.dog_id = d.dog_id
* WHERE up.username = :accountName;
*/
val subQuery = query
.select(
dwb.BOOKING_ID,
up.USERNAME.`as`("user_name"),
d.BREED_NAME,
d.SIZE,
dwb.STATUS,
dwb.BOOKING_DATE,
dwb.TIME_START,
dwb.TIME_END,
dwb.DURATION,
dwb.TOTAL,
dwb.TIMESTAMP,
dwb.SERVICE_STATUS
)
.from(dwb)
.join(dw).on(dwb.WALKER_ID.eq(dw.WALKER_ID))
.join(up).on(dw.USER_ID.eq(up.USER_ID))
.join(d).on(dwb.DOG_ID.eq(d.DOG_ID))
.where(up.USERNAME.eq(DSL.`val`(accountName)))

val subQueryResult = subQuery.fetch { subRecord ->
BookingList(
subRecord[dwb.BOOKING_ID],
subRecord["user_name"].toString(),
subRecord[d.BREED_NAME],
subRecord[d.SIZE],
subRecord[dwb.STATUS],
subRecord[dwb.BOOKING_DATE],
subRecord[dwb.TIME_START],
subRecord[dwb.TIME_END],
subRecord[dwb.DURATION],
subRecord[dwb.TOTAL],
subRecord[dwb.TIMESTAMP],
subRecord[dwb.SERVICE_STATUS]
)
}

LOG.info("\n${mainQuery.fetchOne()}")
LOG.info("\n${subQuery.fetch()}")

return@withContext mainQueryResult.firstOrNull()
return@withContext mainQueryResult.firstOrNull()?.copy(booking = subQueryResult)

} catch (e: Exception) {
LOG.error("Error in getDogWalkersInfo: ${e.message}", e)
@@ -218,6 +256,7 @@ class DogsWalkersServiceImpl @Inject constructor(
}



override suspend fun publicDogWalkersAll(): List<PublicDogWalkerInfo> {
return withContext(dispatcher) {
try {
@@ -226,6 +265,22 @@ class DogsWalkersServiceImpl @Inject constructor(
val dw = DOGWALKERS
val up = USERPROFILES

/**
* SELECT dw.walker_id,
* up.username,
* up.image_profile,
* dw.verification,
* dw.total_review,
* dw.location_name,
* dw.price_small,
* dw.price_medium,
* dw.price_big,
* up.email,
* up.phone_number
* FROM dogwalkers dw
* JOIN userprofiles up ON dw.user_id = up.user_id
* WHERE up.user_type = 'DogWalkers';
*/
return@withContext query.select(
dw.WALKER_ID,
up.USERNAME,
@@ -272,6 +327,7 @@ class DogsWalkersServiceImpl @Inject constructor(
}



override suspend fun privateDogWalkersAll(): List<PrivateDogWalkerInfo> {
return withContext(dispatcher) {
try {
@@ -281,6 +337,26 @@ class DogsWalkersServiceImpl @Inject constructor(
val up = USERPROFILES
val dwr = DOGWALKERREVIEWS

/**
* SELECT dw.walker_id,
* up.username,
* dw.verification,
* dw.count_used,
* dw.count_review,
* dw.total_review,
* dw.location_name,
* dw.price_small,
* dw.price_medium,
* dw.price_big,
* up.email,
* up.phone_number,
* up.user_id,
* up.username,
* up.image_profile
* FROM dogwalkers dw
* JOIN userprofiles up ON dw.user_id = up.user_id
* WHERE up.user_type = 'DogWalkers';
*/
val mainQuery = query.select(
dw.WALKER_ID,
up.USERNAME,
@@ -304,6 +380,13 @@ class DogsWalkersServiceImpl @Inject constructor(

val result = mainQuery.fetch { record ->

/**
* SELECT dwr.user_id,
* dwr.rating,
* dwr.review_text
* FROM dogwalkerreviews dwr
* WHERE dwr.walker_id = :walkerID;
*/
val subQuery = query
.select(
dwr.USER_ID,
@@ -359,18 +442,23 @@ class DogsWalkersServiceImpl @Inject constructor(
return@withContext result

} catch (e: Exception) {
LOG.error("Error retrieving public dog walkers from the database", e)
LOG.error("Error retrieving private dog walkers from the database", e)
return@withContext emptyList()
}
}
}



override suspend fun insert(id: Int): Boolean {
return withContext(dispatcher) {
try {
LOG.info("Thread ${Thread.currentThread().name} executing insert for Dog Walker")

/**
* INSERT INTO dogwalkers (user_id)
* VALUES (:id);
*/
val result = query.insertInto(
DOGWALKERS,
DOGWALKERS.USER_ID,
@@ -380,7 +468,7 @@ class DogsWalkersServiceImpl @Inject constructor(
)
.execute()

val success: Boolean = result > 0 // ตรวจสอบว่ามีการเพิ่มข้อมูลลงในฐานข้อมูลหรือไม่
val success: Boolean = result > 0

if (success) {
LOG.info("Insert successful for walker with User ID [$id]")
@@ -397,12 +485,14 @@ class DogsWalkersServiceImpl @Inject constructor(
}



override suspend fun updateSingleField(id: Int, fieldName: String, newValue: String): Boolean {
return withContext(dispatcher) {
try {
LOG.info("Thread ${Thread.currentThread().name} executing update for Dog Walker")


// สร้างคำสั่ง SQL UPDATE โดยให้ fieldName เป็นชื่อคอลัมน์ที่ต้องการอัปเดต
// และให้ newValue เป็นค่าใหม่ที่ต้องการให้คอลัมน์นั้นมี
val updateRows = when (fieldName) {
"userID" -> query.update(DOGWALKERS)
.set(DOGWALKERS.USER_ID, DSL.`val`(Integer.valueOf(newValue)))
@@ -431,7 +521,10 @@ class DogsWalkersServiceImpl @Inject constructor(
}
}

// กำหนดเงื่อนไขว่าต้องอัปเดตแถวใดๆ ที่มี walker_id เท่ากับ id ที่ระบุ
val affectedRows = updateRows.where(DOGWALKERS.WALKER_ID.eq(id))

// ประมวลผลคำสั่ง SQL UPDATE และนับแถวที่ได้รับผลกระทบ
val result = affectedRows.execute()

if (result > 0) {
@@ -450,11 +543,16 @@ class DogsWalkersServiceImpl @Inject constructor(
}



override suspend fun delete(id: Int): Boolean {
return withContext(dispatcher) {
try {
LOG.info("Thread ${Thread.currentThread().name} executing delete")

/**
* DELETE FROM dogwalkers
* WHERE walker_id = :id;
*/
val deletedRows = query.deleteFrom(DOGWALKERS)
.where(DOGWALKERS.WALKER_ID.eq(DSL.`val`(id)))
.execute()
@@ -474,6 +572,7 @@ class DogsWalkersServiceImpl @Inject constructor(
}



companion object {
private val LOG: Logger = LoggerFactory.getLogger(DogsWalkersServiceImpl::class.java)
}
Original file line number Diff line number Diff line change
@@ -17,11 +17,9 @@ import org.slf4j.LoggerFactory
@Introspected
class SignatureServiceImpl @Inject constructor(
private val query: DSLContext,
taskDispatcher: CoroutineDispatcher?
private val dispatcher: CoroutineDispatcher = Dispatchers.IO
) : SignatureService {

private val dispatcher: CoroutineDispatcher = taskDispatcher ?: Dispatchers.IO

override suspend fun signAll(): List<SignatureField> {
TODO("Not yet implemented")
}
@@ -32,6 +30,12 @@ class SignatureServiceImpl @Inject constructor(
val st = SIGNATURE
val u = USERPROFILES

/**
* SELECT signature
* FROM signature s
* JOIN userprofiles u ON u.user_id = s.user_id
* WHERE u.username = :userName AND s.signature = :signature;
*/
val records = query.select(
st.SIGNATURE_
)
@@ -41,7 +45,6 @@ class SignatureServiceImpl @Inject constructor(
.where(u.USERNAME.eq(userName).and(st.SIGNATURE_.eq(DSL.`val`(signature))))
.fetch()


LOG.info("\n$records")

// ตรวจสอบว่าไม่มี signature ใดที่ signature ตรงกับที่รับเข้ามา
@@ -54,9 +57,15 @@ class SignatureServiceImpl @Inject constructor(
}



override suspend fun insert(payload: SignatureForm): Boolean {
return withContext(dispatcher) {
try {

/**
* INSERT INTO signature (user_id, signature)
* VALUES (:userID, :signature);
*/
val record = query.insertInto(
SIGNATURE,
SIGNATURE.USER_ID,
@@ -78,7 +87,7 @@ class SignatureServiceImpl @Inject constructor(
LOG.warn("No rows inserted for User ID: ${payload.userID}")
}

success
return@withContext success
} catch (e: Exception) {
LOG.error("Error inserting Signature: $e")
false
@@ -87,6 +96,7 @@ class SignatureServiceImpl @Inject constructor(
}



companion object {
val LOG: Logger = LoggerFactory.getLogger(SignatureServiceImpl::class.java)
}
Original file line number Diff line number Diff line change
@@ -39,25 +39,29 @@ import org.slf4j.LoggerFactory
@Introspected
class UserServiceImpl @Inject constructor(
private val query: DSLContext,
taskDispatcher: CoroutineDispatcher?
private val dispatcher: CoroutineDispatcher = Dispatchers.IO
) : UserService {

private val dispatcher: CoroutineDispatcher = taskDispatcher ?: Dispatchers.IO

override suspend fun getUserInfo(accountName: String): NormalInfo? {
return withContext(dispatcher) {

LOG.info("Current Class: ${Thread.currentThread().stackTrace[1].className}")
LOG.info("Executing Method: ${Thread.currentThread().stackTrace[1].methodName}")
LOG.info("Thread ${Thread.currentThread().name} [ID: ${Thread.currentThread().id}] in state ${Thread.currentThread().state}. Is Alive: ${Thread.currentThread().isAlive}")

val up = USERPROFILES.`as`("up")
val dw = DOGWALKERS.`as`("dw")
val d = DOGS.`as`("d")
val up2 = USERPROFILES.`as`("up2")
val dk = DOGWALKBOOKINGS.`as`("dk")


/**
* SELECT dk.BOOKING_ID, up2.USERNAME AS walker_name, d.BREED_NAME, d.SIZE, dk.BOOKING_DATE,
* dk.TIME_START, dk.TIME_END, dk.DURATION, dk.TOTAL, dk.STATUS, dk.TIMESTAMP, dk.SERVICE_STATUS
* FROM dogwalkbookings dk
* JOIN userprofiles up ON up.USER_ID = dk.USER_ID
* JOIN dogwalkers dw ON dw.WALKER_ID = dk.WALKER_ID
* JOIN userprofiles up2 ON up2.USER_ID = dw.USER_ID
* JOIN dogs d ON d.DOG_ID = dk.DOG_ID
* WHERE up.USERNAME = :accountName
*/
val subQuery = query.select(
dk.BOOKING_ID,
up2.USERNAME.`as`("walker_name"),
@@ -83,7 +87,12 @@ class UserServiceImpl @Inject constructor(
.on(d.DOG_ID.eq(dk.DOG_ID))
.where(up.USERNAME.eq(DSL.`val`(accountName)))


/**
* SELECT up.USER_ID, up.USERNAME, up.IMAGE_PROFILE, up.FIRST_NAME, up.LAST_NAME, up.EMAIL,
* up.PHONE_NUMBER, up.USER_TYPE
* FROM userprofiles up
* WHERE up.USERNAME = :accountName
*/
val mainQuery = query.select(
up.USER_ID,
up.USERNAME,
@@ -136,28 +145,33 @@ class UserServiceImpl @Inject constructor(

if (result == null) {
LOG.warn("User not found for Account Name: $accountName")
LOG.info("Current Class: ${Thread.currentThread().stackTrace[1].className}")
LOG.info("Executing Method: ${Thread.currentThread().stackTrace[1].methodName}")
return@withContext null
}

if (result.booking == null) {
result.copy(booking = emptyList())
} else {
LOG.info("Current Class: ${Thread.currentThread().stackTrace[1].className}")
LOG.info("Executing Method: ${Thread.currentThread().stackTrace[1].methodName}")
result
}
}
}



override suspend fun findUser(accountName: String): UserProfileField? {
return withContext(dispatcher) {
val currentThreadName = Thread.currentThread().name
val stackTrace = Thread.currentThread().stackTrace

try {
LOG.info("Current Class: ${Thread.currentThread().stackTrace[1].className}")
LOG.info("Executing Method: ${Thread.currentThread().stackTrace[1].methodName}")
LOG.info("Thread ${Thread.currentThread().name} [ID: ${Thread.currentThread().id}] in state ${Thread.currentThread().state}. Is Alive: ${Thread.currentThread().isAlive}")


/**
* SELECT * FROM userprofiles
* WHERE userprofiles.USERNAME = :accountName
*/
val result: Record? = query.select()
.from(USERPROFILES)
.where(USERPROFILES.USERNAME.eq(DSL.`val`(accountName).coerce(String::class.java)))
@@ -166,7 +180,7 @@ class UserServiceImpl @Inject constructor(
LOG.info("\n$result")

return@withContext if (result != null) {
LOG.info("User found with account name [$accountName] on thread [$currentThreadName]")
LOG.info("User found with account name [$accountName]")

UserProfileField(
result[USERPROFILES.USER_ID],
@@ -182,18 +196,18 @@ class UserServiceImpl @Inject constructor(
result[USERPROFILES.USER_TYPE]
)
} else {
LOG.info("User not found with account name [$accountName] on thread [$currentThreadName]")
LOG.info("User not found with account name [$accountName] from [$stackTrace]")
null
}
} catch (e: DataAccessException) {
LOG.error(
"Error accessing data while finding user with account name [$accountName] on thread [$currentThreadName]",
"Error accessing data while finding user with account name [$accountName] from [$stackTrace]",
e.message
)
null
} catch (e: Exception) {
LOG.error(
"An unexpected error occurred while finding user with account name [$accountName] on thread [$currentThreadName]",
"An unexpected error occurred while finding user with account name [$accountName] from [$stackTrace]",
e.message
)
null
@@ -202,6 +216,7 @@ class UserServiceImpl @Inject constructor(
}



override suspend fun userAll(): List<UserProfileField> {
return withContext(dispatcher) {
try {
@@ -239,11 +254,12 @@ class UserServiceImpl @Inject constructor(
override suspend fun insert(payload: IdentityForm): Boolean {
return withContext(dispatcher) {
try {
LOG.info("Current Class: ${Thread.currentThread().stackTrace[1].className}")
LOG.info("Executing Method: ${Thread.currentThread().stackTrace[1].methodName}")
LOG.info("Thread ${Thread.currentThread().name} [ID: ${Thread.currentThread().id}] in state ${Thread.currentThread().state}. Is Alive: ${Thread.currentThread().isAlive}")


/**
* INSERT INTO userprofiles
* (userprofiles.USERNAME, userprofiles.AUTHEN_KEY, userprofiles.SHARE_KEY)
* VALUES (:payload.userName, :payload.authenKey, :payload.shareKey)
*/
val record = query.insertInto(
USERPROFILES,
USERPROFILES.USERNAME,
@@ -256,7 +272,6 @@ class UserServiceImpl @Inject constructor(
DSL.value(payload.shareKey).coerce(String::class.java)
)


val result = record.execute()
val success = result > 0

@@ -276,14 +291,22 @@ class UserServiceImpl @Inject constructor(
}



override suspend fun updateMultiField(userName: String, payload: UserProfileForm): Boolean {
return withContext(dispatcher) {
val currentThreadName = Thread.currentThread().name
val stackTrace = Thread.currentThread().stackTrace
try {
LOG.info("Current Class: ${Thread.currentThread().stackTrace[1].className}")
LOG.info("Executing Method: ${Thread.currentThread().stackTrace[1].methodName}")
LOG.info("Thread ${Thread.currentThread().name} [ID: ${Thread.currentThread().id}] in state ${Thread.currentThread().state}. Is Alive: ${Thread.currentThread().isAlive}")

/**
* UPDATE userprofiles
* SET
* userprofiles.FIRST_NAME = :payload.firstName,
* userprofiles.LAST_NAME = :payload.lastName,
* userprofiles.EMAIL = :payload.email,
* userprofiles.PHONE_NUMBER = :payload.phoneNumber,
* userprofiles.USER_TYPE = :payload.userType
* WHERE userprofiles.USERNAME = :userName
*/
val updateRows = query.update(USERPROFILES)
.set(USERPROFILES.FIRST_NAME, payload.firstName)
.set(USERPROFILES.LAST_NAME, payload.lastName)
@@ -295,16 +318,16 @@ class UserServiceImpl @Inject constructor(
val result = updateRows.execute()

if (result > 0) {
LOG.info("Update successful for user [$userName] on thread [$currentThreadName]")
LOG.info("Update successful for user [$userName] ")
} else {
LOG.warn("Update did not affect any rows for user [$userName] on thread [$currentThreadName]")
LOG.warn("Update did not affect any rows for user [$userName] from [$stackTrace]")
}
LOG.info("\n$updateRows")

return@withContext result > 0
} catch (e: Exception) {
LOG.error(
"An error occurred during update for user [$userName] on thread [$currentThreadName]",
"An error occurred during update for user [$userName] from [$stackTrace]",
e.message
)
return@withContext false
@@ -313,20 +336,23 @@ class UserServiceImpl @Inject constructor(
}


// *************************************************************************************************** \\

override suspend fun updateSingleField(id: Int, fieldName: String, newValue: String): Boolean {
return withContext(dispatcher) {
try {
LOG.info("Current Class: ${Thread.currentThread().stackTrace[1].className}")
LOG.info("Executing Method: ${Thread.currentThread().stackTrace[1].methodName}")
LOG.info("Thread ${Thread.currentThread().name} [ID: ${Thread.currentThread().id}] in state ${Thread.currentThread().state}. Is Alive: ${Thread.currentThread().isAlive}")


val field = getField(fieldName)
if (field == null) {
LOG.error("Field name [$fieldName] not found!!!")
return@withContext false
}

/**
* UPDATE userprofiles
* SET <field> = :newValue
* WHERE userprofiles.USER_ID = :id
*/
val updateRows = query.update(USERPROFILES)
.set(field, DSL.value(newValue).coerce(String::class.java))
.where(USERPROFILES.USER_ID.eq(id))
@@ -348,7 +374,6 @@ class UserServiceImpl @Inject constructor(
}
}


// สร้างเมทอดเพิ่มเติมเพื่อ map ชื่อฟิลด์กับคอลัมน์ใน JOOQ
private fun getField(fieldName: String): TableField<UserprofilesRecord, String>? {
return when (fieldName) {
@@ -360,14 +385,17 @@ class UserServiceImpl @Inject constructor(
}


// *************************************************************************************************** \\


override suspend fun delete(id: Int): Boolean {
return withContext(dispatcher) {
try {
LOG.info("Current Class: ${Thread.currentThread().stackTrace[1].className}")
LOG.info("Executing Method: ${Thread.currentThread().stackTrace[1].methodName}")
LOG.info("Thread ${Thread.currentThread().name} [ID: ${Thread.currentThread().id}] in state ${Thread.currentThread().state}. Is Alive: ${Thread.currentThread().isAlive}")


/**
* DELETE FROM userprofiles
* WHERE userprofiles.USER_ID = :id
*/
val deletedRows = query.deleteFrom(USERPROFILES)
.where(USERPROFILES.USER_ID.eq(DSL.`val`(id)))
.execute()
@@ -386,6 +414,7 @@ class UserServiceImpl @Inject constructor(
}
}


companion object {
val LOG: Logger = LoggerFactory.getLogger(UserServiceImpl::class.java)
}

0 comments on commit 450fdf4

Please sign in to comment.