-
Notifications
You must be signed in to change notification settings - Fork 19
/
Snippet.cs
87 lines (78 loc) · 3.2 KB
/
Snippet.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
using System;
using System.Data;
using System.Data.SQLite;
namespace Ketarin
{
/// <summary>
/// Represents a piece of code that can be re-used for any commands.
/// </summary>
public class Snippet
{
/// <summary>
/// Gets or sets the GUID of the snippet.
/// </summary>
public Guid Guid { get; set; }
/// <summary>
/// Gets or sets the name of the snippet.
/// </summary>
public string Name { get; set; }
/// <summary>
/// Gets or sets the language/type of the snippet.
/// </summary>
public ScriptType Type { get; set; }
/// <summary>
/// Gets or sets the content of the snippet.
/// </summary>
public string Text { get; set; }
/// <summary>
/// Saves the snippet to the database.
/// </summary>
public void Save()
{
if (this.Guid == Guid.Empty)
{
this.Guid = Guid.NewGuid();
// Overwrite existing names
using (IDbCommand command = DbManager.Connection.CreateCommand())
{
command.CommandText = @"SELECT SnippetGuid FROM snippets WHERE Name = @Name AND Type = @Type";
command.Parameters.Add(new SQLiteParameter("@Name", Name));
command.Parameters.Add(new SQLiteParameter("@Type", Type.ToString()));
string existingGuid = command.ExecuteScalar() as string;
if (existingGuid != null)
{
this.Guid = new Guid(existingGuid);
}
}
}
using (IDbCommand command = DbManager.Connection.CreateCommand())
{
command.CommandText = @"INSERT OR REPLACE INTO snippets (SnippetGuid, Name, Type, Text) VALUES (@SnippetGuid, @Name, @Type, @Text)";
command.Parameters.Add(new SQLiteParameter("@SnippetGuid", DbManager.FormatGuid(this.Guid)));
command.Parameters.Add(new SQLiteParameter("@Name", Name));
command.Parameters.Add(new SQLiteParameter("@Type", Type.ToString()));
command.Parameters.Add(new SQLiteParameter("@Text", Text));
command.ExecuteNonQuery();
}
}
internal void Hydrate(IDataReader reader)
{
this.Name = reader["Name"] as string;
this.Type = Command.ConvertToScriptType(reader["Type"] as string);
this.Text = reader["Text"] as string;
this.Guid = new Guid(reader["SnippetGuid"] as string);
}
/// <summary>
/// Removes a snippet from the database.
/// </summary>
internal void Delete()
{
using (IDbCommand command = DbManager.Connection.CreateCommand())
{
command.CommandText = @"DELETE FROM snippets WHERE SnippetGuid = @SnippetGuid";
command.Parameters.Add(new SQLiteParameter("@SnippetGuid", DbManager.FormatGuid(this.Guid)));
command.ExecuteNonQuery();
}
}
}
}