2 Module : Gargantext.Database.Node.Document.Insert
3 Description : Importing context of texts (documents)
4 Copyright : (c) CNRS, 2017-Present
5 License : AGPL + CECILL v3
6 Maintainer : team@gargantext.org
7 Stability : experimental
10 * Purpose of this module
12 Enabling "common goods" of text data and respecting privacy.
14 Gargantext shares as "common good" the links between context of texts
15 and terms / words / ngrams.
17 Basically a context of text can be defined as a document (see 'Gargantext.Core.Text').
19 Issue to tackle in that module: each global document of Gargantext has
20 to be unique, then shared, but how to respect privacy if needed ?
23 * Methodology to get uniqueness and privacy by design
25 As a consequence, when importing/inserting a new document in Gargantext,
26 a policy for the uniqueness of the inserted docuemnts has to be defined.
28 That is the purpose of this module which defines its main concepts.
30 Unique identifier in database is of a 3-tuple of 3 policies that
31 together define uniqueness:
33 - Design policy: type of node is needed as TypenameId, that is a
34 Document or Individual or something else;
36 - Privacy policy: with ParentId, parent becomes unique, then it enables
37 users to get their own copy without sharing it with all the users of the
38 database (in others words parent_id is necessary to preserve privacy for
41 - Hash policy: this UniqId is a sha256 uniq id which is the result of
42 the concatenation of the parameters defined by @shaParameters@.
45 > insertTest :: FromRow r => CorpusId -> [Node HyperdataDocument] -> IO [r]
46 > insertTest :: IO [ReturnId]
47 > insertTest = runCmdDev $ insertDocuments 1 452162 hyperdataDocuments
50 ------------------------------------------------------------------------
51 {-# LANGUAGE QuasiQuotes #-}
52 {-# LANGUAGE TypeSynonymInstances #-}
53 ------------------------------------------------------------------------
54 module Gargantext.Database.Query.Table.Node.Document.Insert
57 import Control.Lens (set, view)
58 import Control.Lens.Cons
59 import Control.Lens.Prism
60 import Data.Aeson (toJSON{-, ToJSON-})
61 import Data.Maybe (maybe)
62 import Data.Text (Text)
63 -- import Data.ByteString (ByteString)
64 import Data.Time.Segment (jour)
65 import Database.PostgreSQL.Simple (FromRow, Query, Only(..))
66 import Database.PostgreSQL.Simple.FromRow (fromRow, field)
67 -- import Database.PostgreSQL.Simple.ToRow (toRow, ToRow)
68 import Database.PostgreSQL.Simple.SqlQQ
69 import Database.PostgreSQL.Simple.ToField (toField, Action)
70 import Database.PostgreSQL.Simple.Types (Values(..), QualifiedIdentifier(..))
71 import GHC.Generics (Generic)
72 import Gargantext.Database.Admin.Config (nodeTypeId)
73 import Gargantext.Database.Admin.Types.Hyperdata
74 import Gargantext.Database.Admin.Types.Node
75 import Gargantext.Database.Prelude (Cmd, runPGSQuery{-, formatPGSQuery-})
76 import Gargantext.Prelude
77 import Gargantext.Prelude.Crypto.Hash (hash)
78 import qualified Data.Text as DT (pack, concat, take)
80 -- TODO : the import of Document constructor below does not work
81 -- import Gargantext.Database.Types.Node (Document)
82 --import Gargantext.Database.Types.Node (docExample, hyperdataDocument, HyperdataDocument(..)
83 -- , hyperdataDocument_uniqId
84 -- , hyperdataDocument_title
85 -- , hyperdataDocument_abstract
86 -- , hyperdataDocument_source
87 -- , Node(..), node_typename
89 -- , node_parentId, node_name, node_hyperdata, hyperdataDocuments
92 {-| To Print result query
93 import Data.ByteString.Internal (ByteString)
94 import Database.PostgreSQL.Simple (formatQuery)
97 ---------------------------------------------------------------------------
98 -- * Main Insert functions
100 -- | Insert Document main function
101 -- UserId : user who is inserting the documents
102 -- ParentId : folder ID which is parent of the inserted documents
103 -- Administrator of the database has to create a uniq index as following SQL command:
104 -- `create unique index on nodes (typename, parent_id, (hyperdata ->> 'uniqId'));`
105 insertDb :: InsertDb a => UserId -> ParentId -> [a] -> Cmd err [ReturnId]
106 insertDb u p = runPGSQuery queryInsert . Only . Values fields . map (insertDb' u p)
108 fields = map (\t-> QualifiedIdentifier Nothing t) inputSqlTypes
112 insertDb' :: UserId -> ParentId -> a -> [Action]
115 instance InsertDb HyperdataDocument
117 insertDb' u p h = [ toField $ nodeTypeId NodeDocument
120 , toField $ maybe "No Title" (DT.take 255) (_hd_title h)
121 , toField $ _hd_publication_date h -- TODO USE UTCTime
122 , (toField . toJSON) h
125 instance InsertDb HyperdataContact
127 insertDb' u p h = [ toField $ nodeTypeId NodeContact
130 , toField $ maybe "Contact" (DT.take 255) (Just "Name") -- (_hc_name h)
131 , toField $ jour 0 1 1 -- TODO put default date
132 , (toField . toJSON) h
135 -- | Debug SQL function
137 -- to print rendered query (Debug purpose) use @formatQuery@ function.
139 insertDocuments_Debug :: (Hyperdata a, ToJSON a, ToRow a, InsertDb [a])
140 => UserId -> ParentId -> [a] -> Cmd err ByteString
141 insertDocuments_Debug uId pId hs = formatPGSQuery queryInsert (Only $ Values fields inputData)
143 fields = map (\t-> QualifiedIdentifier Nothing t) inputSqlTypes
144 inputData = insertDb' uId pId hs
147 -- | Input Tables: types of the tables
148 inputSqlTypes :: [Text]
149 inputSqlTypes = map DT.pack ["int4","int4","int4","text","date","jsonb"]
151 -- | SQL query to insert documents inside the database
154 WITH input_rows(typename,user_id,parent_id,name,date,hyperdata) AS (?)
156 INSERT INTO nodes (typename,user_id,parent_id,name,date,hyperdata)
157 SELECT * FROM input_rows
158 ON CONFLICT ((hyperdata ->> 'uniqIdBdd')) DO NOTHING -- on unique index -- this does not return the ids
159 -- ON CONFLICT ((hyperdata ->> 'uniqIdBdd')) DO UPDATE SET user_id=EXCLUDED.user_id -- on unique index
160 RETURNING id,hyperdata
163 SELECT true AS source -- true for 'newly inserted'
165 , hyperdata ->> 'uniqIdBdd' as doi
168 SELECT false AS source -- false for 'not inserted'
170 , hyperdata ->> 'uniqIdBdd' as doi
172 JOIN nodes c USING (hyperdata); -- columns of unique index
175 ------------------------------------------------------------------------
179 -- | When documents are inserted
180 -- ReturnType after insertion
181 data ReturnId = ReturnId { reInserted :: Bool -- if the document is inserted (True: is new, False: is not new)
182 , reId :: NodeId -- always return the id of the document (even new or not new)
183 -- this is the uniq id in the database
184 , reUniqId :: Text -- Hash Id with concatenation of sha parameters
185 } deriving (Show, Generic)
187 instance FromRow ReturnId where
188 fromRow = ReturnId <$> field <*> field <*> field
190 ---------------------------------------------------------------------------
191 -- * Uniqueness of document definition
197 instance AddUniqId HyperdataDocument
199 addUniqId = addUniqIdsDoc
201 addUniqIdsDoc :: HyperdataDocument -> HyperdataDocument
202 addUniqIdsDoc doc = set hd_uniqIdBdd (Just shaBdd)
203 $ set hd_uniqId (Just shaUni) doc
205 shaUni = hash $ DT.concat $ map ($ doc) shaParametersDoc
206 shaBdd = hash $ DT.concat $ map ($ doc) ([(\d -> maybeText (_hd_bdd d))] <> shaParametersDoc)
208 shaParametersDoc :: [(HyperdataDocument -> Text)]
209 shaParametersDoc = [ \d -> maybeText (_hd_title d)
210 , \d -> maybeText (_hd_abstract d)
211 , \d -> maybeText (_hd_source d)
212 , \d -> maybeText (_hd_publication_date d)
215 ---------------------------------------------------------------------------
216 -- * Uniqueness of document definition
217 -- TODO factorize with above (use the function below for tests)
219 instance AddUniqId HyperdataContact
221 addUniqId = addUniqIdsContact
223 addUniqIdsContact :: HyperdataContact -> HyperdataContact
224 addUniqIdsContact hc = set (hc_uniqIdBdd) (Just shaBdd)
225 $ set (hc_uniqId ) (Just shaUni) hc
227 shaUni = hash $ DT.concat $ map ($ hc) shaParametersContact
228 shaBdd = hash $ DT.concat $ map ($ hc) ([\d -> maybeText (view hc_bdd d)] <> shaParametersContact)
230 -- | TODO add more shaparameters
231 shaParametersContact :: [(HyperdataContact -> Text)]
232 shaParametersContact = [ \d -> maybeText $ view (hc_who . _Just . cw_firstName ) d
233 , \d -> maybeText $ view (hc_who . _Just . cw_lastName ) d
234 , \d -> maybeText $ view (hc_where . _head . cw_touch . _Just . ct_mail) d
237 maybeText :: Maybe Text -> Text
238 maybeText = maybe (DT.pack "") identity
240 ---------------------------------------------------------------------------