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

비밀번호

댓글 작성자
 




[1]  2  3  4  5  6  7  8  9  10  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13616정성태5/3/2024116닷넷: 2256. ASP.NET Core 웹 사이트의 HTTP/HTTPS + Dual mode Socket (IPv4/IPv6) 지원 방법파일 다운로드1
13615정성태5/3/2024118닷넷: 2255. C# 배열을 Numpy ndarray 배열과 상호 변환
13614정성태5/2/2024203닷넷: 2254. C# - COM 인터페이스의 상속 시 중복으로 메서드를 선언
13613정성태5/1/2024450닷넷: 2253. C# - Video Capture 장치(Camera) 열거 및 지원 포맷 조회파일 다운로드1
13612정성태4/30/2024434오류 유형: 902. Visual Studio - error MSB3021: Unable to copy file
13611정성태4/29/2024684닷넷: 2252. C# - GUID 타입 전용의 UnmanagedType.LPStruct - 두 번째 이야기파일 다운로드1
13610정성태4/28/2024759닷넷: 2251. C# - 제네릭 인자를 가진 타입을 생성하는 방법 - 두 번째 이야기
13609정성태4/27/2024857닷넷: 2250. PInvoke 호출 시 참조 타입(class)을 마샬링하는 [IN], [OUT] 특성파일 다운로드1
13608정성태4/26/20241039닷넷: 2249. C# - 부모의 필드/프로퍼티에 대해 서로 다른 자식 클래스 간에 Reflection 접근이 동작할까요?파일 다운로드1
13607정성태4/25/20241056닷넷: 2248. C# - 인터페이스 타입의 다중 포인터를 인자로 갖는 C/C++ 함수 연동
13606정성태4/24/20241003닷넷: 2247. C# - tensorflow 연동 (MNIST 예제)파일 다운로드1
13605정성태4/23/2024979닷넷: 2246. C# - Python.NET을 이용한 파이썬 소스코드 연동파일 다운로드1
13604정성태4/22/2024986오류 유형: 901. Visual Studio - Unable to set the next statement. Set next statement cannot be used in '[Exception]' call stack frames.
13603정성태4/21/20241036닷넷: 2245. C# - IronPython을 이용한 파이썬 소스코드 연동파일 다운로드1
13602정성태4/20/20241015닷넷: 2244. C# - PCM 오디오 데이터를 연속(Streaming) 재생 (Windows Multimedia)파일 다운로드1
13601정성태4/19/20241034닷넷: 2243. C# - PCM 사운드 재생(NAudio)파일 다운로드1
13600정성태4/18/20241075닷넷: 2242. C# - 관리 스레드와 비관리 스레드
13599정성태4/17/2024978닷넷: 2241. C# - WAV 파일의 PCM 사운드 재생(Windows Multimedia)파일 다운로드1
13598정성태4/16/20241030닷넷: 2240. C# - WAV 파일 포맷 + LIST 헤더파일 다운로드2
13597정성태4/15/20241059닷넷: 2239. C# - WAV 파일의 PCM 데이터 생성 및 출력파일 다운로드1
13596정성태4/14/20241136닷넷: 2238. C# - WAV 기본 파일 포맷파일 다운로드1
13595정성태4/13/20241087닷넷: 2237. C# - Audio 장치 열기 (Windows Multimedia, NAudio)파일 다운로드1
13594정성태4/12/20241112닷넷: 2236. C# - Audio 장치 열람 (Windows Multimedia, NAudio)파일 다운로드1
13593정성태4/8/20241129닷넷: 2235. MSBuild - AccelerateBuildsInVisualStudio 옵션
13592정성태4/2/20241545C/C++: 165. CLion으로 만든 Rust Win32 DLL을 C#과 연동 [1]
[1]  2  3  4  5  6  7  8  9  10  11  12  13  14  15  ...