@@ -6,15 +6,12 @@ namespace BotSharp.Plugin.ExcelHandler.Services;
66public class SqliteService : IDbService
77{
88 private readonly IServiceProvider _services ;
9- private readonly ILogger < SqliteService > _logger ;
9+ private readonly ILogger _logger ;
1010 private readonly ExcelHandlerSettings _settings ;
1111
12- private string _dbFilePath = string . Empty ;
13- private SqliteConnection _inMemoryDbConnection = null ;
1412 private double _excelRowSize = 0 ;
1513 private double _excelColumnSize = 0 ;
1614 private string _tableName = "tempTable" ;
17- private string _currentFileName = string . Empty ;
1815 private List < string > _headerColumns = new List < string > ( ) ;
1916 private List < string > _columnTypes = new List < string > ( ) ;
2017
@@ -38,24 +35,23 @@ public IEnumerable<SqlContextOut> WriteExcelDataToDB(IWorkbook workbook)
3835 for ( int sheetIdx = 0 ; sheetIdx < numTables ; sheetIdx ++ )
3936 {
4037 ISheet sheet = workbook . GetSheetAt ( sheetIdx ) ;
38+
39+ // create table
4140 var ( isCreateSuccess , message ) = SqlCreateTableFn ( sheet ) ;
4241
43- if ( ! isCreateSuccess )
42+ results . Add ( new SqlContextOut
4443 {
45- results . Add ( new SqlContextOut
46- {
47- isSuccessful = isCreateSuccess ,
48- Message = message ,
49- FileName = _currentFileName
50- } ) ;
51- continue ;
52- }
44+ IsSuccessful = isCreateSuccess ,
45+ Message = message
46+ } ) ;
47+
48+ // insert data
5349 var ( isInsertSuccess , insertMessage ) = SqlInsertDataFn ( sheet ) ;
50+
5451 results . Add ( new SqlContextOut
5552 {
56- isSuccessful = isInsertSuccess ,
57- Message = insertMessage ,
58- FileName = _currentFileName
53+ IsSuccessful = isInsertSuccess ,
54+ Message = insertMessage
5955 } ) ;
6056 }
6157 return results ;
@@ -69,13 +65,17 @@ public IEnumerable<SqlContextOut> WriteExcelDataToDB(IWorkbook workbook)
6965 {
7066 string dataSql = ParseSheetData ( sheet ) ;
7167 string insertDataSql = ProcessInsertSqlQuery ( dataSql ) ;
72- ExecuteSqlQueryForInsertion ( insertDataSql ) ;
68+ var insertedRowCount = ExecuteSqlQueryForInsertion ( insertDataSql ) ;
7369
74- return ( true , $ "{ _currentFileName } : \r \n { _excelRowSize } records have been successfully inserted into `{ _tableName } ` table") ;
70+ // List top 3 rows
71+ var top3rows = dataSql . Split ( "\r " ) . Take ( 3 ) ;
72+ var dataSample = string . Join ( "\r " , dataSql . Split ( "\r " ) . Take ( 3 ) ) . Trim ( ',' , ' ' ) ;
73+
74+ return ( true , $ "{ insertedRowCount } records have been successfully inserted into `{ _tableName } ` table. Top { top3rows . Count ( ) } rows:\r \n { dataSample } ") ;
7575 }
7676 catch ( Exception ex )
7777 {
78- return ( false , $ "{ _currentFileName } : Failed to parse excel data into `{ _tableName } ` table. ####Error: { ex . Message } ") ;
78+ return ( false , $ "Failed to parse excel data into `{ _tableName } ` table. ####Error: { ex . Message } ") ;
7979 }
8080 }
8181
@@ -86,8 +86,10 @@ public IEnumerable<SqlContextOut> WriteExcelDataToDB(IWorkbook workbook)
8686 _tableName = sheet . SheetName ;
8787 _headerColumns = ParseSheetColumn ( sheet ) ;
8888 string createTableSql = CreateDBTableSqlString ( _tableName , _headerColumns , null ) ;
89- ExecuteSqlQueryForInsertion ( createTableSql ) ;
90- return ( true , $ "{ _tableName } has been successfully created.") ;
89+ var rowCount = ExecuteSqlQueryForInsertion ( createTableSql ) ;
90+ // Get table schema using sqlite query
91+ var schema = GenerateTableSchema ( ) ;
92+ return ( true , $ "Table `{ _tableName } ` has been successfully created in { Provider } . Table schema:\r \n { schema } ") ;
9193 }
9294 catch ( Exception ex )
9395 {
@@ -166,25 +168,19 @@ private string ProcessInsertSqlQuery(string dataSql)
166168 {
167169 var wrapUpCols = _headerColumns . Select ( x => $ "`{ x } `") . ToList ( ) ;
168170 var transferedCols = '(' + string . Join ( ',' , wrapUpCols ) + ')' ;
169- string insertSqlQuery = $ "Insert into { _tableName } { transferedCols } Values { dataSql } ";
171+ string insertSqlQuery = $ "INSERT INTO { _tableName } { transferedCols } VALUES { dataSql } ";
170172 return insertSqlQuery ;
171173 }
172174
173- private void ExecuteSqlQueryForInsertion ( string query )
175+ private int ExecuteSqlQueryForInsertion ( string query )
174176 {
175- var physicalDbConnection = GetPhysicalDbConnection ( ) ;
176- var inMemoryDbConnection = GetInMemoryDbConnection ( ) ;
177+ using var conn = GetDbConnection ( ) ;
177178
178- physicalDbConnection . BackupDatabase ( inMemoryDbConnection , "main" , "main" ) ;
179- physicalDbConnection . Close ( ) ;
179+ using var command = new SqliteCommand ( ) ;
180+ command . CommandText = query ;
181+ command . Connection = conn ;
180182
181- using ( var command = new SqliteCommand ( ) )
182- {
183- command . CommandText = query ;
184- command . Connection = inMemoryDbConnection ;
185- command . ExecuteNonQuery ( ) ;
186- }
187- inMemoryDbConnection . BackupDatabase ( physicalDbConnection ) ;
183+ return command . ExecuteNonQuery ( ) ;
188184 }
189185
190186 private void DeleteTableSqlQuery ( )
@@ -198,8 +194,8 @@ private void DeleteTableSqlQuery()
198194 type = 'table' AND
199195 name NOT LIKE 'sqlite_%'
200196 " ;
201- var physicalDbConnection = GetPhysicalDbConnection ( ) ;
202- using var selectCmd = new SqliteCommand ( deleteTableSql , physicalDbConnection ) ;
197+ using var conn = GetDbConnection ( ) ;
198+ using var selectCmd = new SqliteCommand ( deleteTableSql , conn ) ;
203199 using var reader = selectCmd . ExecuteReader ( ) ;
204200 if ( reader . HasRows )
205201 {
@@ -212,11 +208,11 @@ name NOT LIKE 'sqlite_%'
212208 }
213209 dropTableQueries . ForEach ( query =>
214210 {
215- using var dropTableCommand = new SqliteCommand ( query , physicalDbConnection ) ;
211+ using var dropTableCommand = new SqliteCommand ( query , conn ) ;
216212 dropTableCommand . ExecuteNonQuery ( ) ;
217213 } ) ;
218214 }
219- physicalDbConnection . Close ( ) ;
215+ conn . Close ( ) ;
220216 }
221217
222218 private string GenerateTableSchema ( )
@@ -237,26 +233,30 @@ private string GenerateTableSchema()
237233 #endregion
238234
239235 #region Db connection
240- private SqliteConnection GetInMemoryDbConnection ( )
236+ private SqliteConnection GetDbConnection ( )
241237 {
242- if ( _inMemoryDbConnection == null )
243- {
244- _logger . LogInformation ( $ "Init in-memory Sqlite database connection") ;
245-
246- _inMemoryDbConnection = new SqliteConnection ( "Data Source=:memory:;Mode=ReadWrite" ) ;
247- _inMemoryDbConnection . Open ( ) ;
248- }
249- return _inMemoryDbConnection ;
250- }
238+ var connectionString = _settings . Database . ConnectionString ;
239+
240+ // Extract the database file path from the connection string
241+ var builder = new SqliteConnectionStringBuilder ( connectionString ) ;
242+ var dbFilePath = builder . DataSource ;
251243
252- private SqliteConnection GetPhysicalDbConnection ( )
253- {
254- if ( string . IsNullOrEmpty ( _dbFilePath ) )
244+ _logger . LogInformation ( "Database file path: {DbFilePath}" , dbFilePath ) ;
245+
246+ // If it's not an in-memory database, ensure the directory exists
247+ if ( ! string . IsNullOrEmpty ( dbFilePath ) &&
248+ ! dbFilePath . Equals ( ":memory:" , StringComparison . OrdinalIgnoreCase ) )
255249 {
256- _dbFilePath = _settings . Database . ConnectionString ;
250+ var directory = Path . GetDirectoryName ( dbFilePath ) ;
251+ if ( ! string . IsNullOrEmpty ( directory ) && ! Directory . Exists ( directory ) )
252+ {
253+ Directory . CreateDirectory ( directory ) ;
254+ _logger . LogInformation ( "Created directory: {Directory}" , directory ) ;
255+ }
257256 }
258-
259- var dbConnection = new SqliteConnection ( $ "Data Source={ _dbFilePath } ;Mode=ReadWrite") ;
257+
258+ // SQLite automatically creates the database file when opening the connection
259+ var dbConnection = new SqliteConnection ( connectionString ) ;
260260 dbConnection . Open ( ) ;
261261 return dbConnection ;
262262 }
0 commit comments