Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 

Firebird ALinq Provider - 날짜 필드에 대한 낙관적 동시성 쿼리 오류

문제 재현을 위해 아래와 같은 정도의 Linq Table 개체를 하나 정의하고,

[Table(Name = "Agents")]
public class Agent
{
    public Agent()
    {
    }

    [Column(IsPrimaryKey = true, DbType = "Char(38)")]
    public string Guid { get; set; }

    [Column(DbType = "TIMESTAMP")] // 날짜 필드가 Firebird에서는 TIMESTAMP 형식으로 정의되어 있습니다.
    public DateTime? Created { get; set; }

    [Column(DbType = "VarChar(50)")]
    public string Name { get; set; }

    ...[생략]...
}

다음과 같이 Linq 쿼리를 작성하였는데 오류가 발생한 것입니다.

var items = from record in db.Agents
            where record.Guid == agent.Guid
            select record;

if (items.Count() == 1)
{
    items.First().Name = "...[변경]...";
    db.SubmitChanges();
}

오류 메시지는 아래와 같습니다.

System.ServiceModel.FaultException<System.ServiceModel.ExceptionDetail> was caught
  Message=conversion error from string "2011-05-25 오전 8:53:43"
  Source=mscorlib
  StackTrace:
    Server stack trace: 
       at System.ServiceModel.Channels.ServiceChannel.ThrowIfFaultUnderstood(Message reply, MessageFault fault, String action, MessageVersion version, FaultConverter faultConverter)
       at System.ServiceModel.Channels.ServiceChannel.HandleReply(ProxyOperationRuntime operation, ProxyRpc& rpc)
       at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
       at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
       at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)
    Exception rethrown at [0]: 
       at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
       at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
       at AgentServiceTest.ServiceReference1.IAgentWebService.Register(Agent agent)
       at AgentServiceTest.ServiceReference1.AgentWebServiceClient.Register(Agent agent) in D:\...[생략]...\Reference.cs:line 271
       at AgentServiceTest.Program.RegisterService(String addr, String agentId, String agentName, String version) in D:\...[생략]...\Program.cs:line 77
       at AgentServiceTest.Program.Main(String[] args) in D:\...[생략]...\Program.cs:line 29
  InnerException: 

Linq to SQL의 DataContext.Log를 이용하여 생성된 쿼리를 확인해 보니,

UPDATE Agents
SET Name = @p1
WHERE (Guid = @p0) AND ...[낙관적 동시성에 따른 기존 값 나열]... AND (Created = '2011-05-25 오전 8:53:43')

SET에 "Name = @p1"만 있는 것은 변경된 필드 값이 그것 하나이기 때문에 당연한 것이고, WHERE 구문 다음에 개별 값들에 대해서 기존 값을 지정함으로써 낙관적 동시성을 이용한 충돌을 방지하는 것도... 이해할 만한 수준입니다.

그런데, 하필 기존 값들이 'Parameterized Query'로 넘어가는 것이 아니고 직접 문자열 연결 쿼리로 구성하는 것이 문제가 되어버렸고, 게다가 한글 윈도우라서 DateTime 필드 값이 Localization 된 것이 결정적인 오류 원인이 되었습니다.

Firebird에서 허용되는 TIMESTAMP 값 형식은 아래의 글에 자세하게 소개되고 있습니다.

DATE, TIME AND TIMESTAMP LITERALS
; http://www.janus-software.com/fbmanual/manual.php?book=psql&topic=41

"For the TIMESTAMP form: 'mm/dd/yyyy hh:mm:ss'"라고 알려주듯이, ALinq provider의 SQL로 변환된 Linq 쿼리에 있는 TIMESTAMP 값의 문자열 형식하고는 완전히 다릅니다. 오류가 나는 것이 지극히 정상인 상황입니다. ^^




이를 가지고 ALinq 측에 문의를 했고, 다음은 제가 받은 응답니다. (역시 빠른 답변을 받을 수 있었습니다.)

Yes, We can use the parameter instead the text value, but that will cause another problem white you use complex query. (We will try to fix this problem in later)

Now I can provide you a solution: 
I do not think the the Created filed is necessary in the filter, so it can be ignore. you can set the UpdateCheck property of the Column Attribute as UpdateCheck.Never, now the Created property becomes:
[Column(DbType = "TIMESTAMP", UpdateCheck=UpdateCheck.Never)]
public DateTime? Created { get; set; }

And I suggest you only use the primary key value in the filter. it's say append  UpdateCheck=UpdateCheck.Never  to all the properties except primary key property.
That the SQL will become just like below
Update XXX
Set XXX
Where  Guid = @p0

PS: ALinq support update query, that means you can update the data directly, without select the data first.
For example:
db.Orders.Update(o => new Order { OrderID = 10, OrderDate = DateTime.Now },
                          o => o.OrderID == 1 & o.EmployeeID == 1)
for more details, you can see the sample which is in the ALinq install directory.

고민이군요. UpdateCheck를 해제할까 하다가 제 경우에는 Name 필드 값 변경이 그다지 특별한 동시성 체크를 요구하는 것은 아니었기 때문에 후자의 방법을 도입했습니다.

db.Agents.Update(
    o => new Agent { Name = agent.Name }
    o => o.Guid == agent.Guid);

==> 변환된 SQL 쿼리
UPDATE Agents SET Name = @p1 WHERE Guid = @p0

참고로, 원래의 System.Data.Linq에서 제공되는 Table<> 타입에는 Update 메서드가 제공되지 않습니다. 아마도 ALinq 측에서는 이런 문제를 대비해서 별도의 메서드를 제공한 것 같습니다.




SQL Server에 대한 System.Data.Linq의 기본 동작은 어떻게 되어 있을까요? 예상할 수 있는 것처럼 낙관적 동시성을 위한 조건문의 필드 값들이 전부 'parameterized query'로 처리되어 있습니다.

사실, 바로 이런 난관들이 3rd-party 라이브러리를 도입했을 때의 문제입니다. 해당 제품의 '홈페이지 설명문' 정도만 봐서는 실제 구현에 들어갔을 때 발생할 수 있는 문제를 예측할 수 없는데, 이런 때 중요한 것이 바로 '기술지원'입니다. 제 생각에는 ALinq는 '기술지원' 수준에서 충분히 합격점이라고 봅니다. ^^ (물론 System.Data.Linq와 완전히 동일하게 구현해 주면 더 좋겠지만... 저 스스로가 개발자이기 때문에 이런 부분은 이해해 줄 수 있습니다.)



[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]







[최초 등록일: ]
[최종 수정일: 8/7/2021]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 




... [16]  17  18  19  20  21  22  23  24  25  26  27  28  29  30  ...
NoWriterDateCnt.TitleFile(s)
13251정성태2/8/20234752스크립트: 44. 파이썬의 3가지 스레드 ID
13250정성태2/8/20236642오류 유형: 843. System.InvalidOperationException - Unable to configure HTTPS endpoint
13249정성태2/7/20235471오류 유형: 842. 리눅스 - You must wait longer to change your password
13248정성태2/7/20234381오류 유형: 841. 리눅스 - [사용자 계정] is not in the sudoers file. This incident will be reported.
13247정성태2/7/20235276VS.NET IDE: 180. Visual Studio - 닷넷 소스 코드 디버깅 중 "Decompile source code"가 동작하는 않는 문제
13246정성태2/6/20234473개발 환경 구성: 664. Hyper-V에 설치한 리눅스 VM의 VHD 크기 늘리는 방법 - 두 번째 이야기
13245정성태2/6/20235081.NET Framework: 2093. C# - PEM 파일을 이용한 RSA 개인키/공개키 설정 방법파일 다운로드1
13244정성태2/5/20234467VS.NET IDE: 179. Visual Studio - External Tools에 Shell 내장 명령어 등록
13243정성태2/5/20235291디버깅 기술: 190. windbg - Win32 API 호출 시점에 BP 거는 방법 [1]
13242정성태2/4/20234745디버깅 기술: 189. ASP.NET Web Application (.NET Framework) 프로젝트의 숨겨진 예외 - System.UnauthorizedAccessException
13241정성태2/3/20234141디버깅 기술: 188. ASP.NET Web Application (.NET Framework) 프로젝트의 숨겨진 예외 - System.IO.FileNotFoundException
13240정성태2/1/20234295디버깅 기술: 187. ASP.NET Web Application (.NET Framework) 프로젝트의 숨겨진 예외 - System.Web.HttpException
13239정성태2/1/20233983디버깅 기술: 186. C# - CacheDependency의 숨겨진 예외 - System.Web.HttpException
13238정성태1/31/20236152.NET Framework: 2092. IIS 웹 사이트를 TLS 1.2 또는 TLS 1.3 프로토콜로만 운영하는 방법
13237정성태1/30/20235850.NET Framework: 2091. C# - 웹 사이트가 어떤 버전의 TLS/SSL을 지원하는지 확인하는 방법
13236정성태1/29/20235271개발 환경 구성: 663. openssl을 이용해 인트라넷 IIS 사이트의 SSL 인증서 생성
13235정성태1/29/20234957개발 환경 구성: 662. openssl - 윈도우 환경의 명령행에서 SAN 적용하는 방법
13234정성태1/28/20236070개발 환경 구성: 661. dnSpy를 이용해 소스 코드가 없는 .NET 어셈블리의 코드를 변경하는 방법 [1]
13233정성태1/28/20237424오류 유형: 840. C# - WebClient로 https 호출 시 "The request was aborted: Could not create SSL/TLS secure channel" 예외 발생
13232정성태1/27/20235037스크립트: 43. uwsgi의 --processes와 --threads 옵션
13231정성태1/27/20234103오류 유형: 839. python - TypeError: '...' object is not callable
13230정성태1/26/20234497개발 환경 구성: 660. WSL 2 내부로부터 호스트 측의 네트워크로 UDP 데이터가 1개의 패킷으로만 제한되는 문제
13229정성태1/25/20235534.NET Framework: 2090. C# - UDP Datagram의 최대 크기
13228정성태1/24/20235664.NET Framework: 2089. C# - WMI 논리 디스크가 속한 물리 디스크의 정보를 얻는 방법 [2]파일 다운로드1
13227정성태1/23/20235267개발 환경 구성: 659. Windows - IP MTU 값을 바꿀 수 있을까요? [1]
13226정성태1/23/20234965.NET Framework: 2088. .NET 5부터 지원하는 GetRawSocketOption 사용 시 주의할 점
... [16]  17  18  19  20  21  22  23  24  25  26  27  28  29  30  ...