private async Task <bool> InsertOrUpdateAsync(InfoHashModel model, IDbTransaction transaction) { var updateSql = new StringBuilder(); var list = new List <DbParameter> { new NpgsqlParameter("updatetime", DateTime.Now), new NpgsqlParameter("infohash", model.InfoHash) }; updateSql.Append("updatetime = @updatetime,"); if (model.CreateTime != default(DateTime)) { list.Add(new NpgsqlParameter("createtime", model.CreateTime)); } if (model.IsDanger) { list.Add(new NpgsqlParameter("isdanger", model.IsDanger)); updateSql.Append("isdanger = @isdanger,"); } if (model.DownNum > 0) { list.Add(new NpgsqlParameter("downnum", model.DownNum)); updateSql.Append("downnum = ti.downnum +@downnum,"); } if (model.FileNum > 0) { list.Add(new NpgsqlParameter("filenum", model.FileNum)); updateSql.Append("filenum = @filenum,"); } if (model.FileSize > 0) { list.Add(new NpgsqlParameter("filesize", model.FileSize)); updateSql.Append("filesize = @filesize,"); } if (!model.Files.IsEmpty()) { list.Add(new NpgsqlParameter("hasfile", true)); updateSql.Append("hasfile = True,"); } if (model.Name != null) { list.Add(new NpgsqlParameter("name", model.Name)); updateSql.Append("name = @name,"); } if (transaction != null) { return(await DoInsert(model, transaction, list, updateSql)); } if (Connection.State != ConnectionState.Open) { Connection.Open(); } using (transaction = Connection.BeginTransaction()) { return(await DoInsert(model, transaction, list, updateSql)); } }
private async Task InsertHashFile(InfoHashModel model, IDbTransaction transaction) { IList <DbParameter> fileParams = new DbParameter[] { new NpgsqlParameter("files", NpgsqlDbType.Jsonb) { Value = model.Files.ToJson() }, new NpgsqlParameter("hashId", DbType.Int64) { Value = model.Id }, }; await Connection.ExecuteAsync("INSERT INTO t_infohash_file (info_hash_id, files) VALUES (@hashId,@files) ON CONFLICT (info_hash_id) DO UPDATE SET files=@files;", new InfoHashParamter(fileParams), transaction); }
private async Task <bool> DoInsert(InfoHashModel model, IDbTransaction transaction, List <DbParameter> list, StringBuilder updateSql) { var hashId = await Connection.ExecuteScalarAsync <long>( string.Format( "INSERT INTO t_infohash AS ti ({0}) VALUES ({1}) ON CONFLICT (infohash) DO UPDATE SET {2} RETURNING id", string.Join(",", list.Select(l => l.ParameterName)), string.Join(",", list.Select(l => "@" + l.ParameterName)), updateSql.ToString().TrimEnd(',')), new InfoHashParamter(list), transaction); if (hashId <= 0) { return(false); } model.Id = hashId; if (model.Files.IsEmpty()) { return(true); } await InsertHashFile(model, transaction); return(true); }
public async Task <bool> InsertOrUpdateAsync(InfoHashModel model) { return(await InsertOrUpdateAsync(model, null)); }