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)
13453정성태11/23/20232654오류 유형: 879. docker desktop 설치 시 "Invalid JSON string. (Exception from HRESULT: 0x83750007)"
13452정성태11/22/20232717닷넷: 2166. C# - Azure OpenAI API를 이용해 사용자가 제공하는 정보를 대상으로 검색하는 방법파일 다운로드1
13451정성태11/21/20232871닷넷: 2165. C# - Azure OpenAI API를 이용해 ChatGPT처럼 동작하는 콘솔 응용 프로그램 제작파일 다운로드1
13450정성태11/21/20232680닷넷: 2164. C# - Octokit을 이용한 GitHub Issue 검색파일 다운로드1
13449정성태11/21/20232847개발 환경 구성: 688. Azure OpenAI 서비스 신청 방법
13448정성태11/20/20233101닷넷: 2163. .NET 8 - Dynamic PGO를 결합한 성능 향상파일 다운로드1
13447정성태11/16/20233069닷넷: 2162. ASP.NET Core 웹 사이트의 SSL 설정을 코드로 하는 방법
13446정성태11/16/20232994닷넷: 2161. .NET Conf 2023 - Day 1 Blazor 개요 정리
13445정성태11/15/20233249Linux: 62. 리눅스/WSL에서 CA 인증서를 저장하는 방법
13444정성태11/15/20233018닷넷: 2160. C# 12 - Experimental 특성 지원
13443정성태11/14/20232902개발 환경 구성: 687. OpenSSL로 생성한 사용자 인증서를 ASP.NET Core 웹 사이트에 적용하는 방법
13442정성태11/13/20232671개발 환경 구성: 686. 비주얼 스튜디오로 실행한 ASP.NET Core 사이트를 WSL 2 인스턴스에서 https로 접속하는 방법
13441정성태11/12/20233110닷넷: 2159. C# - ASP.NET Core 프로젝트에서 서버 Socket을 직접 생성하는 방법파일 다운로드1
13440정성태11/11/20232658Windows: 253. 소켓 Listen 시 방화벽의 Public/Private 제어 기능이 비활성화된 경우
13439정성태11/10/20233320닷넷: 2158. C# - 소켓 포트를 미리 시스템에 등록/예약해 사용하는 방법(Port Exclusion Ranges)파일 다운로드1
13438정성태11/9/20232924닷넷: 2157. C# - WinRT 기능을 이용해 윈도우에서 실행 중인 Media App 제어
13437정성태11/8/20233079닷넷: 2156. .NET 7 이상의 콘솔 프로그램을 (dockerfile 없이) 로컬 docker에 배포하는 방법
13436정성태11/7/20233294닷넷: 2155. C# - .NET 8 런타임부터 (Reflection 없이) 특성을 이용해 public이 아닌 멤버 호출 가능
13435정성태11/6/20233238닷넷: 2154. C# - 네이티브 자원을 포함한 관리 개체(예: 스레드)의 GC 정리
13434정성태11/1/20233041스크립트: 62. 파이썬 - class의 정적 함수를 동적으로 교체
13433정성태11/1/20232614스크립트: 61. 파이썬 - 함수 오버로딩 미지원
13432정성태10/31/20232842오류 유형: 878. 탐색기의 WSL 디렉터리 접근 시 "Attempt to access invalid address." 오류 발생
13431정성태10/31/20233229스크립트: 60. 파이썬 - 비동기 FastAPI 앱을 gunicorn으로 호스팅
13430정성태10/30/20233028닷넷: 2153. C# - 사용자가 빌드한 ICU dll 파일을 사용하는 방법
13429정성태10/27/20233231닷넷: 2152. Win32 Interop - C/C++ DLL로부터 이중 포인터 버퍼를 C#으로 받는 예제파일 다운로드1
13428정성태10/25/20233414닷넷: 2151. C# 12 - ref readonly 매개변수
1  2  3  4  5  6  7  [8]  9  10  11  12  13  14  15  ...