Skip to content

Add ".sql" scripted importers #76

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jun 28, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
".csv" files can be imported as SQLite database assets by changing the importer to `SQLite.Editor.Csv.SQLiteAssetCsvImporter` in the Inspector.
- `SQLiteConnection.SerializeToAsset` extension method for serializing a database to an instance of `SQLiteAsset`.
- `SQLiteConnection.ImportCsvToTable` extension method for importing a CSV text stream as a new table inside the database.
- Support for importing ".sql" files as either a `TextAsset` or a `SQLiteAsset`.
- `SQLiteConnection.ExecuteScript` extension method for executing a SQL script with multiple statements with a single call.

### Changed
- Update SQLite to 3.50.1
Expand Down
56 changes: 56 additions & 0 deletions Editor/SQLAssetDatabaseImporter.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
/*
* Copyright (c) 2025 Gil Barbosa Reis
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
using System.IO;
using UnityEditor.AssetImporters;
using UnityEngine;

namespace SQLite.Editor
{
[ScriptedImporter(0, null, new[] { "sql" })]
public class SQLAssetDatabaseImporter : ScriptedImporter
{
[Header("SQLite asset options")]
[Tooltip("Flags controlling how the SQLite connection should be opened. 'ReadWrite' and 'Create' flags will be ignored, since SQLite assets are read-only.")]
[SerializeField] private SQLiteOpenFlags _openFlags = SQLiteOpenFlags.ReadOnly;

[Tooltip("Whether to store DateTime properties as ticks (true) or strings (false).")]
[SerializeField] private bool _storeDateTimeAsTicks = true;

[Tooltip("Name of the file created for the database inside Streaming Assets folder during builds.\n\n"
+ "If empty, the database bytes will be stored in the asset itself.\n\n"
+ "Loading databases from Streaming Assets is not supported in Android and WebGL platforms.")]
[SerializeField] private string _streamingAssetsPath;

public override void OnImportAsset(AssetImportContext ctx)
{
SQLiteAsset asset;
using (var tempDb = new SQLiteConnection(""))
{
string contents = File.ReadAllText(assetPath);
tempDb.ExecuteScript(contents);
asset = tempDb.SerializeToAsset(null, _openFlags, _storeDateTimeAsTicks, _streamingAssetsPath);
}
ctx.AddObjectToAsset("main", asset);
ctx.SetMainObject(asset);
}
}
}
11 changes: 11 additions & 0 deletions Editor/SQLAssetDatabaseImporter.cs.meta

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

39 changes: 39 additions & 0 deletions Editor/SQLAssetTextImporter.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
/*
* Copyright (c) 2025 Gil Barbosa Reis
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
using System.IO;
using UnityEditor.AssetImporters;
using UnityEngine;

namespace SQLite.Editor
{
[ScriptedImporter(0, "sql")]
public class SQLAssetTextImporter : ScriptedImporter
{
public override void OnImportAsset(AssetImportContext ctx)
{
string contents = File.ReadAllText(assetPath);
TextAsset asset = new(contents);
ctx.AddObjectToAsset("main", asset);
ctx.SetMainObject(asset);
}
}
}
11 changes: 11 additions & 0 deletions Editor/SQLAssetTextImporter.cs.meta

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ This package provides the excelent [SQLite-net](https://github.com/praeclarum/sq
- [SQLiteAsset](Runtime/SQLiteAsset.cs): read-only SQLite database Unity assets.
+ Files with the extensions ".sqlite", ".sqlite2" and ".sqlite3" will be imported as SQLite database assets.
+ ".csv" files can be imported as SQLite database assets by changing the importer to `SQLite.Editor.Csv.SQLiteAssetCsvImporter` in the Inspector.
+ ".sql" files are imported as Text assets by default, but can be imported as SQLite database assets by changing the importer to `SQLite.Editor.SQLAssetDatabaseImporter`.
+ Use the `CreateConnection()` method for connecting to the database provided by the asset.
Make sure to `Dispose()` of any connections you create.
+ SQLite assets may be loaded from Streaming Assets folder or from memory, depending on the value of their "Streaming Assets Path" property.
Expand Down
9 changes: 9 additions & 0 deletions Runtime/SQLiteConnectionExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,15 @@ public static SQLiteConnection Deserialize(this SQLiteConnection db, ReadOnlySpa
return db;
}

public static void ExecuteScript(this SQLiteConnection db, string sql)
{
SQLite3.Result result = SQLite3.Exec(db.Handle, sql, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero);
if (result != SQLite3.Result.OK)
{
throw SQLiteException.New(result, SQLite3.GetErrmsg(db.Handle));
}
}

/// <summary>
/// Import a CSV data stream into the table named <paramref name="tableName"/> inside the database.
/// The table will be created if it doesn't exist yet.
Expand Down
3 changes: 3 additions & 0 deletions Runtime/SQLiteExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,9 @@ public enum DeserializeFlags : uint
[DllImport(LibraryPath, EntryPoint = "sqlite3_column_bytes16", CallingConvention = CallingConvention.Cdecl)]
public static extern int ColumnBytes16(IntPtr stmt, int index);

[DllImport(LibraryPath, EntryPoint = "sqlite3_exec", CallingConvention = CallingConvention.Cdecl)]
public static extern Result Exec(IntPtr db, [MarshalAs(UnmanagedType.LPStr)] string sql, IntPtr callback, IntPtr userdata, IntPtr errorMessagePtr);

#if UNITY_WEBGL && !UNITY_EDITOR
[DllImport(LibraryPath, CallingConvention = CallingConvention.Cdecl)]
public static extern int idbvfs_register(int makeDefault);
Expand Down