1+ // -----------------------------------------------------------------------
2+ // <copyright file="IntListJsonType.cs" company="Build">
3+ // Copyright (c) Build. All rights reserved.
4+ // Licensed under the MIT license.
5+ // </copyright>
6+ // -----------------------------------------------------------------------
7+
8+ namespace BaroBot . Database . UserTypes ;
9+
10+ using System . Data . Common ;
11+ using System . Text . Json ;
12+ using NHibernate ;
13+ using NHibernate . Engine ;
14+ using NHibernate . SqlTypes ;
15+ using NHibernate . UserTypes ;
16+
17+ /// <summary>
18+ /// Defines how a list of int should be serialized into json.
19+ /// </summary>
20+ public class IntListJsonType : IUserType
21+ {
22+ /// <inheritdoc />
23+ public SqlType [ ] SqlTypes => [ new ( System . Data . DbType . String ) ] ;
24+
25+ /// <inheritdoc />
26+ public Type ReturnedType => typeof ( List < int > ) ;
27+
28+ /// <inheritdoc />
29+ public bool IsMutable => true ;
30+
31+ /// <inheritdoc />
32+ public void NullSafeSet ( DbCommand cmd , object value , int index , ISessionImplementor session )
33+ {
34+ var json = JsonSerializer . Serialize ( value ?? new List < int > ( ) ) ;
35+ NHibernateUtil . String . NullSafeSet ( cmd , json , index , session ) ;
36+ }
37+
38+ /// <inheritdoc />
39+ public object DeepCopy ( object value ) =>
40+ value is List < int > list ? new List < int > ( list ) : new List < int > ( ) ;
41+
42+ /// <inheritdoc />
43+ public object Replace ( object original , object target , object owner ) => DeepCopy ( original ) ;
44+
45+ /// <inheritdoc />
46+ public object Assemble ( object cached , object owner ) => DeepCopy ( cached ) ;
47+
48+ /// <inheritdoc />
49+ public object Disassemble ( object value ) => DeepCopy ( value ) ;
50+
51+ /// <inheritdoc />
52+ public new bool Equals ( object x , object y ) =>
53+ JsonSerializer . Serialize ( x ) == JsonSerializer . Serialize ( y ) ;
54+
55+ /// <inheritdoc />
56+ public int GetHashCode ( object x ) => JsonSerializer . Serialize ( x ) . GetHashCode ( ) ;
57+
58+ /// <inheritdoc />
59+ public object ? NullSafeGet ( DbDataReader rs , string [ ] names , ISessionImplementor session , object owner )
60+ {
61+ var obj = NHibernateUtil . String . NullSafeGet ( rs , names [ 0 ] , session , owner ) as string ;
62+ return string . IsNullOrEmpty ( obj ) ? new List < int > ( ) : JsonSerializer . Deserialize < List < int > > ( obj ) ;
63+ }
64+ }
0 commit comments