2 * Implementation of the Microsoft Installer (msi.dll)
4 * Copyright 2002,2003,2004,2005 Mike McCormack for CodeWeavers
6 * This library is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU Lesser General Public
8 * License as published by the Free Software Foundation; either
9 * version 2.1 of the License, or (at your option) any later version.
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * Lesser General Public License for more details.
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
24 #define NONAMELESSUNION
30 #include "wine/debug.h"
31 #include "wine/unicode.h"
37 #include "msiserver.h"
42 WINE_DEFAULT_DEBUG_CHANNEL(msi);
47 * An .msi file is a structured storage file.
48 * It contains a number of streams.
49 * A stream for each table in the database.
50 * Two streams for the string table in the database.
51 * Any binary data in a table is a reference to a stream.
54 static VOID MSI_CloseDatabase( MSIOBJECTHDR *arg )
56 MSIDATABASE *db = (MSIDATABASE *) arg;
59 free_cached_tables( db );
60 msi_free_transforms( db );
61 msi_destroy_stringtable( db->strings );
62 IStorage_Release( db->storage );
65 DeleteFileW( db->deletefile );
66 msi_free( db->deletefile );
70 DeleteFileW( db->localfile );
71 msi_free( db->localfile );
75 UINT MSI_OpenDatabaseW(LPCWSTR szDBPath, LPCWSTR szPersist, MSIDATABASE **pdb)
79 MSIDATABASE *db = NULL;
80 UINT ret = ERROR_FUNCTION_FAILED;
81 LPCWSTR szMode, save_path;
86 static const WCHAR szTables[] = { '_','T','a','b','l','e','s',0 };
88 TRACE("%s %s\n",debugstr_w(szDBPath),debugstr_w(szPersist) );
91 return ERROR_INVALID_PARAMETER;
93 if (szPersist - MSIDBOPEN_PATCHFILE >= MSIDBOPEN_READONLY &&
94 szPersist - MSIDBOPEN_PATCHFILE <= MSIDBOPEN_CREATEDIRECT)
96 TRACE("Database is a patch\n");
97 szPersist -= MSIDBOPEN_PATCHFILE;
100 save_path = szDBPath;
102 if( HIWORD( szPersist ) )
104 if (!CopyFileW( szDBPath, szPersist, FALSE ))
105 return ERROR_OPEN_FAILED;
107 szDBPath = szPersist;
108 szPersist = MSIDBOPEN_TRANSACT;
112 if( szPersist == MSIDBOPEN_READONLY )
114 r = StgOpenStorage( szDBPath, NULL,
115 STGM_DIRECT|STGM_READ|STGM_SHARE_DENY_WRITE, NULL, 0, &stg);
117 else if( szPersist == MSIDBOPEN_CREATE || szPersist == MSIDBOPEN_CREATEDIRECT )
119 /* FIXME: MSIDBOPEN_CREATE should case STGM_TRANSACTED flag to be
121 r = StgCreateDocfile( szDBPath,
122 STGM_CREATE|STGM_DIRECT|STGM_READWRITE|STGM_SHARE_EXCLUSIVE, 0, &stg);
123 if( r == ERROR_SUCCESS )
125 IStorage_SetClass( stg, &CLSID_MsiDatabase );
126 /* create the _Tables stream */
127 r = write_stream_data(stg, szTables, NULL, 0, TRUE);
129 r = msi_init_string_table( stg );
133 else if( szPersist == MSIDBOPEN_TRANSACT )
135 /* FIXME: MSIDBOPEN_TRANSACT should case STGM_TRANSACTED flag to be
137 r = StgOpenStorage( szDBPath, NULL,
138 STGM_DIRECT|STGM_READWRITE|STGM_SHARE_EXCLUSIVE, NULL, 0, &stg);
140 else if( szPersist == MSIDBOPEN_DIRECT )
142 r = StgOpenStorage( szDBPath, NULL,
143 STGM_DIRECT|STGM_READWRITE|STGM_SHARE_EXCLUSIVE, NULL, 0, &stg);
147 ERR("unknown flag %p\n",szPersist);
148 return ERROR_INVALID_PARAMETER;
151 if( FAILED( r ) || !stg )
153 FIXME("open failed r = %08x for %s\n", r, debugstr_w(szDBPath));
154 return ERROR_FUNCTION_FAILED;
157 r = IStorage_Stat( stg, &stat, STATFLAG_NONAME );
160 FIXME("Failed to stat storage\n");
164 if ( !IsEqualGUID( &stat.clsid, &CLSID_MsiDatabase ) &&
165 !IsEqualGUID( &stat.clsid, &CLSID_MsiPatch ) &&
166 !IsEqualGUID( &stat.clsid, &CLSID_MsiTransform ) )
168 ERR("storage GUID is not a MSI database GUID %s\n",
169 debugstr_guid(&stat.clsid) );
173 db = alloc_msiobject( MSIHANDLETYPE_DATABASE, sizeof (MSIDATABASE),
177 FIXME("Failed to allocate a handle\n");
181 if (!strchrW( save_path, '\\' ))
183 GetCurrentDirectoryW( MAX_PATH, path );
184 lstrcatW( path, szBackSlash );
185 lstrcatW( path, save_path );
188 lstrcpyW( path, save_path );
190 db->path = strdupW( path );
192 if( TRACE_ON( msi ) )
193 enum_stream_names( stg );
198 db->deletefile = strdupW( szDBPath );
199 list_init( &db->tables );
200 list_init( &db->transforms );
202 db->strings = msi_load_string_table( stg, &db->bytes_per_strref );
208 msiobj_addref( &db->hdr );
209 IStorage_AddRef( stg );
214 msiobj_release( &db->hdr );
216 IStorage_Release( stg );
221 UINT WINAPI MsiOpenDatabaseW(LPCWSTR szDBPath, LPCWSTR szPersist, MSIHANDLE *phDB)
226 TRACE("%s %s %p\n",debugstr_w(szDBPath),debugstr_w(szPersist), phDB);
228 ret = MSI_OpenDatabaseW( szDBPath, szPersist, &db );
229 if( ret == ERROR_SUCCESS )
231 *phDB = alloc_msihandle( &db->hdr );
233 ret = ERROR_NOT_ENOUGH_MEMORY;
234 msiobj_release( &db->hdr );
240 UINT WINAPI MsiOpenDatabaseA(LPCSTR szDBPath, LPCSTR szPersist, MSIHANDLE *phDB)
242 HRESULT r = ERROR_FUNCTION_FAILED;
243 LPWSTR szwDBPath = NULL, szwPersist = NULL;
245 TRACE("%s %s %p\n", debugstr_a(szDBPath), debugstr_a(szPersist), phDB);
249 szwDBPath = strdupAtoW( szDBPath );
254 if( HIWORD(szPersist) )
256 szwPersist = strdupAtoW( szPersist );
261 szwPersist = (LPWSTR)(DWORD_PTR)szPersist;
263 r = MsiOpenDatabaseW( szwDBPath, szwPersist, phDB );
266 if( HIWORD(szPersist) )
267 msi_free( szwPersist );
268 msi_free( szwDBPath );
273 static LPWSTR msi_read_text_archive(LPCWSTR path)
278 DWORD read, size = 0;
280 file = CreateFileW( path, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL );
281 if (file == INVALID_HANDLE_VALUE)
284 size = GetFileSize( file, NULL );
285 data = msi_alloc( size + 1 );
289 if (!ReadFile( file, data, size, &read, NULL ))
293 wdata = strdupAtoW( data );
301 static void msi_parse_line(LPWSTR *line, LPWSTR **entries, DWORD *num_entries)
303 LPWSTR ptr = *line, save;
308 /* stay on this line */
309 while (*ptr && *ptr != '\n')
311 /* entries are separated by tabs */
318 *entries = msi_alloc(count * sizeof(LPWSTR));
322 /* store pointers into the data */
323 for (i = 0, ptr = *line; i < count; i++)
325 while (*ptr && *ptr == '\r') ptr++;
328 while (*ptr && *ptr != '\t' && *ptr != '\n' && *ptr != '\r') ptr++;
330 /* NULL-separate the data */
331 if (*ptr == '\n' || *ptr == '\r')
333 while (*ptr == '\n' || *ptr == '\r')
339 (*entries)[i] = save;
342 /* move to the next line if there's more, else EOF */
346 *num_entries = count;
349 static LPWSTR msi_build_createsql_prelude(LPWSTR table)
354 static const WCHAR create_fmt[] = {'C','R','E','A','T','E',' ','T','A','B','L','E',' ','`','%','s','`',' ','(',' ',0};
356 size = sizeof(create_fmt)/sizeof(create_fmt[0]) + lstrlenW(table) - 2;
357 prelude = msi_alloc(size * sizeof(WCHAR));
361 sprintfW(prelude, create_fmt, table);
365 static LPWSTR msi_build_createsql_columns(LPWSTR *columns_data, LPWSTR *types, DWORD num_columns)
369 DWORD sql_size = 1, i, len;
370 WCHAR expanded[128], *ptr;
371 WCHAR size[10], comma[2], extra[30];
373 static const WCHAR column_fmt[] = {'`','%','s','`',' ','%','s','%','s','%','s','%','s',' ',0};
374 static const WCHAR size_fmt[] = {'(','%','s',')',0};
375 static const WCHAR type_char[] = {'C','H','A','R',0};
376 static const WCHAR type_int[] = {'I','N','T',0};
377 static const WCHAR type_long[] = {'L','O','N','G',0};
378 static const WCHAR type_object[] = {'O','B','J','E','C','T',0};
379 static const WCHAR type_notnull[] = {' ','N','O','T',' ','N','U','L','L',0};
380 static const WCHAR localizable[] = {' ','L','O','C','A','L','I','Z','A','B','L','E',0};
382 columns = msi_alloc_zero(sql_size * sizeof(WCHAR));
386 for (i = 0; i < num_columns; i++)
389 comma[1] = size[0] = extra[0] = '\0';
391 if (i == num_columns - 1)
403 lstrcpyW(extra, type_notnull);
405 lstrcatW(extra, localizable);
407 sprintfW(size, size_fmt, ptr);
410 lstrcpyW(extra, type_notnull);
413 sprintfW(size, size_fmt, ptr);
416 lstrcpyW(extra, type_notnull);
424 WARN("invalid int width %u\n", len);
430 lstrcpyW(extra, type_notnull);
435 ERR("Unknown type: %c\n", types[i][0]);
440 sprintfW(expanded, column_fmt, columns_data[i], type, size, extra, comma);
441 sql_size += lstrlenW(expanded);
443 p = msi_realloc(columns, sql_size * sizeof(WCHAR));
451 lstrcatW(columns, expanded);
457 static LPWSTR msi_build_createsql_postlude(LPWSTR *primary_keys, DWORD num_keys)
459 LPWSTR postlude, keys, ptr;
460 DWORD size, key_size, i;
462 static const WCHAR key_fmt[] = {'`','%','s','`',',',' ',0};
463 static const WCHAR postlude_fmt[] = {'P','R','I','M','A','R','Y',' ','K','E','Y',' ','%','s',')',0};
465 for (i = 0, size = 1; i < num_keys; i++)
466 size += lstrlenW(key_fmt) + lstrlenW(primary_keys[i]) - 2;
468 keys = msi_alloc(size * sizeof(WCHAR));
472 for (i = 0, ptr = keys; i < num_keys; i++)
474 key_size = lstrlenW(key_fmt) + lstrlenW(primary_keys[i]) -2;
475 sprintfW(ptr, key_fmt, primary_keys[i]);
479 /* remove final ', ' */
482 size = lstrlenW(postlude_fmt) + size - 1;
483 postlude = msi_alloc(size * sizeof(WCHAR));
487 sprintfW(postlude, postlude_fmt, keys);
494 static UINT msi_add_table_to_db(MSIDATABASE *db, LPWSTR *columns, LPWSTR *types, LPWSTR *labels, DWORD num_labels, DWORD num_columns)
500 LPWSTR prelude, columns_sql, postlude;
502 prelude = msi_build_createsql_prelude(labels[0]);
503 columns_sql = msi_build_createsql_columns(columns, types, num_columns);
504 postlude = msi_build_createsql_postlude(labels + 1, num_labels - 1); /* skip over table name */
506 if (!prelude || !columns_sql || !postlude)
507 return ERROR_OUTOFMEMORY;
509 size = lstrlenW(prelude) + lstrlenW(columns_sql) + lstrlenW(postlude) + 1;
510 create_sql = msi_alloc(size * sizeof(WCHAR));
512 return ERROR_OUTOFMEMORY;
514 lstrcpyW(create_sql, prelude);
515 lstrcatW(create_sql, columns_sql);
516 lstrcatW(create_sql, postlude);
519 msi_free(columns_sql);
522 r = MSI_DatabaseOpenViewW( db, create_sql, &view );
523 msi_free(create_sql);
525 if (r != ERROR_SUCCESS)
528 r = MSI_ViewExecute(view, NULL);
530 msiobj_release(&view->hdr);
535 static LPWSTR msi_import_stream_filename(LPCWSTR path, LPCWSTR name)
538 LPWSTR fullname, ptr;
540 len = lstrlenW(path) + lstrlenW(name) + 1;
541 fullname = msi_alloc(len*sizeof(WCHAR));
545 lstrcpyW( fullname, path );
547 /* chop off extension from path */
548 ptr = strrchrW(fullname, '.');
555 lstrcpyW( ptr, name );
559 static UINT construct_record(DWORD num_columns, LPWSTR *types,
560 LPWSTR *data, LPWSTR path, MSIRECORD **rec)
564 *rec = MSI_CreateRecord(num_columns);
566 return ERROR_OUTOFMEMORY;
568 for (i = 0; i < num_columns; i++)
572 case 'L': case 'l': case 'S': case 's':
573 MSI_RecordSetStringW(*rec, i + 1, data[i]);
577 MSI_RecordSetInteger(*rec, i + 1, atoiW(data[i]));
583 LPWSTR file = msi_import_stream_filename(path, data[i]);
585 return ERROR_FUNCTION_FAILED;
587 r = MSI_RecordSetStreamFromFileW(*rec, i + 1, file);
589 if (r != ERROR_SUCCESS)
590 return ERROR_FUNCTION_FAILED;
594 ERR("Unhandled column type: %c\n", types[i][0]);
595 msiobj_release(&(*rec)->hdr);
596 return ERROR_FUNCTION_FAILED;
600 return ERROR_SUCCESS;
603 static UINT msi_add_records_to_table(MSIDATABASE *db, LPWSTR *columns, LPWSTR *types,
604 LPWSTR *labels, LPWSTR **records,
605 int num_columns, int num_records,
613 static const WCHAR select[] = {
614 'S','E','L','E','C','T',' ','*',' ',
615 'F','R','O','M',' ','`','%','s','`',0
618 r = MSI_OpenQuery(db, &view, select, labels[0]);
619 if (r != ERROR_SUCCESS)
622 while (MSI_ViewFetch(view, &rec) != ERROR_NO_MORE_ITEMS)
624 r = MSI_ViewModify(view, MSIMODIFY_DELETE, rec);
625 msiobj_release(&rec->hdr);
626 if (r != ERROR_SUCCESS)
630 for (i = 0; i < num_records; i++)
632 r = construct_record(num_columns, types, records[i], path, &rec);
633 if (r != ERROR_SUCCESS)
636 r = MSI_ViewModify(view, MSIMODIFY_INSERT, rec);
637 if (r != ERROR_SUCCESS)
639 msiobj_release(&rec->hdr);
643 msiobj_release(&rec->hdr);
647 msiobj_release(&view->hdr);
651 static UINT MSI_DatabaseImport(MSIDATABASE *db, LPCWSTR folder, LPCWSTR file)
655 DWORD num_labels, num_types;
656 DWORD num_columns, num_records = 0;
657 LPWSTR *columns, *types, *labels;
658 LPWSTR path, ptr, data;
659 LPWSTR **records = NULL;
660 LPWSTR **temp_records;
662 static const WCHAR suminfo[] =
663 {'_','S','u','m','m','a','r','y','I','n','f','o','r','m','a','t','i','o','n',0};
665 TRACE("%p %s %s\n", db, debugstr_w(folder), debugstr_w(file) );
667 if( folder == NULL || file == NULL )
668 return ERROR_INVALID_PARAMETER;
670 len = lstrlenW(folder) + lstrlenW(szBackSlash) + lstrlenW(file) + 1;
671 path = msi_alloc( len * sizeof(WCHAR) );
673 return ERROR_OUTOFMEMORY;
675 lstrcpyW( path, folder );
676 lstrcatW( path, szBackSlash );
677 lstrcatW( path, file );
679 data = msi_read_text_archive( path );
682 msi_parse_line( &ptr, &columns, &num_columns );
683 msi_parse_line( &ptr, &types, &num_types );
684 msi_parse_line( &ptr, &labels, &num_labels );
686 if (num_columns != num_types)
688 r = ERROR_FUNCTION_FAILED;
692 records = msi_alloc(sizeof(LPWSTR *));
695 r = ERROR_OUTOFMEMORY;
699 /* read in the table records */
702 msi_parse_line( &ptr, &records[num_records], NULL );
705 temp_records = msi_realloc(records, (num_records + 1) * sizeof(LPWSTR *));
708 r = ERROR_OUTOFMEMORY;
711 records = temp_records;
714 if (!strcmpW(labels[0], suminfo))
716 r = msi_add_suminfo( db, records, num_records, num_columns );
717 if (r != ERROR_SUCCESS)
719 r = ERROR_FUNCTION_FAILED;
725 if (!TABLE_Exists(db, labels[0]))
727 r = msi_add_table_to_db( db, columns, types, labels, num_labels, num_columns );
728 if (r != ERROR_SUCCESS)
730 r = ERROR_FUNCTION_FAILED;
735 r = msi_add_records_to_table( db, columns, types, labels, records, num_columns, num_records, path );
745 for (i = 0; i < num_records; i++)
746 msi_free(records[i]);
753 UINT WINAPI MsiDatabaseImportW(MSIHANDLE handle, LPCWSTR szFolder, LPCWSTR szFilename)
758 TRACE("%x %s %s\n",handle,debugstr_w(szFolder), debugstr_w(szFilename));
760 db = msihandle2msiinfo( handle, MSIHANDLETYPE_DATABASE );
763 IWineMsiRemoteDatabase *remote_database;
765 remote_database = (IWineMsiRemoteDatabase *)msi_get_remote( handle );
766 if ( !remote_database )
767 return ERROR_INVALID_HANDLE;
769 IWineMsiRemoteDatabase_Release( remote_database );
770 WARN("MsiDatabaseImport not allowed during a custom action!\n");
772 return ERROR_SUCCESS;
775 r = MSI_DatabaseImport( db, szFolder, szFilename );
776 msiobj_release( &db->hdr );
780 UINT WINAPI MsiDatabaseImportA( MSIHANDLE handle,
781 LPCSTR szFolder, LPCSTR szFilename )
783 LPWSTR path = NULL, file = NULL;
784 UINT r = ERROR_OUTOFMEMORY;
786 TRACE("%x %s %s\n", handle, debugstr_a(szFolder), debugstr_a(szFilename));
790 path = strdupAtoW( szFolder );
797 file = strdupAtoW( szFilename );
802 r = MsiDatabaseImportW( handle, path, file );
811 static UINT msi_export_record( HANDLE handle, MSIRECORD *row, UINT start )
813 UINT i, count, len, r = ERROR_SUCCESS;
819 buffer = msi_alloc( len );
821 return ERROR_OUTOFMEMORY;
823 count = MSI_RecordGetFieldCount( row );
824 for ( i=start; i<=count; i++ )
827 r = MSI_RecordGetStringA( row, i, buffer, &sz );
828 if (r == ERROR_MORE_DATA)
830 char *p = msi_realloc( buffer, sz + 1 );
837 r = MSI_RecordGetStringA( row, i, buffer, &sz );
838 if (r != ERROR_SUCCESS)
841 if (!WriteFile( handle, buffer, sz, &sz, NULL ))
843 r = ERROR_FUNCTION_FAILED;
847 sep = (i < count) ? "\t" : "\r\n";
848 if (!WriteFile( handle, sep, strlen(sep), &sz, NULL ))
850 r = ERROR_FUNCTION_FAILED;
858 static UINT msi_export_row( MSIRECORD *row, void *arg )
860 return msi_export_record( arg, row, 1 );
863 static UINT msi_export_forcecodepage( HANDLE handle )
867 static const char data[] = "\r\n\r\n0\t_ForceCodepage\r\n";
869 FIXME("Read the codepage from the strings table!\n");
871 sz = lstrlenA(data) + 1;
872 if (!WriteFile(handle, data, sz, &sz, NULL))
873 return ERROR_FUNCTION_FAILED;
875 return ERROR_SUCCESS;
878 static UINT MSI_DatabaseExport( MSIDATABASE *db, LPCWSTR table,
879 LPCWSTR folder, LPCWSTR file )
881 static const WCHAR query[] = {
882 's','e','l','e','c','t',' ','*',' ','f','r','o','m',' ','%','s',0 };
883 static const WCHAR forcecodepage[] = {
884 '_','F','o','r','c','e','C','o','d','e','p','a','g','e',0 };
885 MSIRECORD *rec = NULL;
886 MSIQUERY *view = NULL;
891 TRACE("%p %s %s %s\n", db, debugstr_w(table),
892 debugstr_w(folder), debugstr_w(file) );
894 if( folder == NULL || file == NULL )
895 return ERROR_INVALID_PARAMETER;
897 len = lstrlenW(folder) + lstrlenW(file) + 2;
898 filename = msi_alloc(len * sizeof (WCHAR));
900 return ERROR_OUTOFMEMORY;
902 lstrcpyW( filename, folder );
903 lstrcatW( filename, szBackSlash );
904 lstrcatW( filename, file );
906 handle = CreateFileW( filename, GENERIC_READ | GENERIC_WRITE, 0,
907 NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );
908 msi_free( filename );
909 if (handle == INVALID_HANDLE_VALUE)
910 return ERROR_FUNCTION_FAILED;
912 if (!lstrcmpW( table, forcecodepage ))
914 r = msi_export_forcecodepage( handle );
918 r = MSI_OpenQuery( db, &view, query, table );
919 if (r == ERROR_SUCCESS)
921 /* write out row 1, the column names */
922 r = MSI_ViewGetColumnInfo(view, MSICOLINFO_NAMES, &rec);
923 if (r == ERROR_SUCCESS)
925 msi_export_record( handle, rec, 1 );
926 msiobj_release( &rec->hdr );
929 /* write out row 2, the column types */
930 r = MSI_ViewGetColumnInfo(view, MSICOLINFO_TYPES, &rec);
931 if (r == ERROR_SUCCESS)
933 msi_export_record( handle, rec, 1 );
934 msiobj_release( &rec->hdr );
937 /* write out row 3, the table name + keys */
938 r = MSI_DatabaseGetPrimaryKeys( db, table, &rec );
939 if (r == ERROR_SUCCESS)
941 MSI_RecordSetStringW( rec, 0, table );
942 msi_export_record( handle, rec, 0 );
943 msiobj_release( &rec->hdr );
946 /* write out row 4 onwards, the data */
947 r = MSI_IterateRecords( view, 0, msi_export_row, handle );
948 msiobj_release( &view->hdr );
952 CloseHandle( handle );
956 /***********************************************************************
957 * MsiExportDatabaseW [MSI.@]
959 * Writes a file containing the table data as tab separated ASCII.
961 * The format is as follows:
963 * row1 : colname1 <tab> colname2 <tab> .... colnameN <cr> <lf>
964 * row2 : coltype1 <tab> coltype2 <tab> .... coltypeN <cr> <lf>
965 * row3 : tablename <tab> key1 <tab> key2 <tab> ... keyM <cr> <lf>
967 * Followed by the data, starting at row 1 with one row per line
969 * row4 : data <tab> data <tab> data <tab> ... data <cr> <lf>
971 UINT WINAPI MsiDatabaseExportW( MSIHANDLE handle, LPCWSTR szTable,
972 LPCWSTR szFolder, LPCWSTR szFilename )
977 TRACE("%x %s %s %s\n", handle, debugstr_w(szTable),
978 debugstr_w(szFolder), debugstr_w(szFilename));
980 db = msihandle2msiinfo( handle, MSIHANDLETYPE_DATABASE );
983 IWineMsiRemoteDatabase *remote_database;
985 remote_database = (IWineMsiRemoteDatabase *)msi_get_remote( handle );
986 if ( !remote_database )
987 return ERROR_INVALID_HANDLE;
989 IWineMsiRemoteDatabase_Release( remote_database );
990 WARN("MsiDatabaseExport not allowed during a custom action!\n");
992 return ERROR_SUCCESS;
995 r = MSI_DatabaseExport( db, szTable, szFolder, szFilename );
996 msiobj_release( &db->hdr );
1000 UINT WINAPI MsiDatabaseExportA( MSIHANDLE handle, LPCSTR szTable,
1001 LPCSTR szFolder, LPCSTR szFilename )
1003 LPWSTR path = NULL, file = NULL, table = NULL;
1004 UINT r = ERROR_OUTOFMEMORY;
1006 TRACE("%x %s %s %s\n", handle, debugstr_a(szTable),
1007 debugstr_a(szFolder), debugstr_a(szFilename));
1011 table = strdupAtoW( szTable );
1018 path = strdupAtoW( szFolder );
1025 file = strdupAtoW( szFilename );
1030 r = MsiDatabaseExportW( handle, table, path, file );
1040 UINT WINAPI MsiDatabaseMergeA(MSIHANDLE hDatabase, MSIHANDLE hDatabaseMerge,
1046 TRACE("(%d, %d, %s)\n", hDatabase, hDatabaseMerge,
1047 debugstr_a(szTableName));
1049 table = strdupAtoW(szTableName);
1050 r = MsiDatabaseMergeW(hDatabase, hDatabaseMerge, table);
1056 typedef struct _tagMERGETABLE
1070 typedef struct _tagMERGEROW
1076 typedef struct _tagMERGEDATA
1080 MERGETABLE *curtable;
1082 struct list *tabledata;
1085 static BOOL merge_type_match(LPCWSTR type1, LPCWSTR type2)
1087 if (((type1[0] == 'l') || (type1[0] == 's')) &&
1088 ((type2[0] == 'l') || (type2[0] == 's')))
1091 if (((type1[0] == 'L') || (type1[0] == 'S')) &&
1092 ((type2[0] == 'L') || (type2[0] == 'S')))
1095 return !lstrcmpW(type1, type2);
1098 static UINT merge_verify_colnames(MSIQUERY *dbview, MSIQUERY *mergeview)
1100 MSIRECORD *dbrec, *mergerec;
1103 r = MSI_ViewGetColumnInfo(dbview, MSICOLINFO_NAMES, &dbrec);
1104 if (r != ERROR_SUCCESS)
1107 r = MSI_ViewGetColumnInfo(mergeview, MSICOLINFO_NAMES, &mergerec);
1108 if (r != ERROR_SUCCESS)
1111 count = MSI_RecordGetFieldCount(dbrec);
1112 for (i = 1; i <= count; i++)
1114 if (!MSI_RecordGetString(mergerec, i))
1117 if (lstrcmpW(MSI_RecordGetString(dbrec, i),
1118 MSI_RecordGetString(mergerec, i)))
1120 r = ERROR_DATATYPE_MISMATCH;
1125 msiobj_release(&dbrec->hdr);
1126 msiobj_release(&mergerec->hdr);
1127 dbrec = mergerec = NULL;
1129 r = MSI_ViewGetColumnInfo(dbview, MSICOLINFO_TYPES, &dbrec);
1130 if (r != ERROR_SUCCESS)
1133 r = MSI_ViewGetColumnInfo(mergeview, MSICOLINFO_TYPES, &mergerec);
1134 if (r != ERROR_SUCCESS)
1137 count = MSI_RecordGetFieldCount(dbrec);
1138 for (i = 1; i <= count; i++)
1140 if (!MSI_RecordGetString(mergerec, i))
1143 if (!merge_type_match(MSI_RecordGetString(dbrec, i),
1144 MSI_RecordGetString(mergerec, i)))
1146 r = ERROR_DATATYPE_MISMATCH;
1152 msiobj_release(&dbrec->hdr);
1153 msiobj_release(&mergerec->hdr);
1158 static UINT merge_verify_primary_keys(MSIDATABASE *db, MSIDATABASE *mergedb,
1161 MSIRECORD *dbrec, *mergerec = NULL;
1164 r = MSI_DatabaseGetPrimaryKeys(db, table, &dbrec);
1165 if (r != ERROR_SUCCESS)
1168 r = MSI_DatabaseGetPrimaryKeys(mergedb, table, &mergerec);
1169 if (r != ERROR_SUCCESS)
1172 count = MSI_RecordGetFieldCount(dbrec);
1173 if (count != MSI_RecordGetFieldCount(mergerec))
1175 r = ERROR_DATATYPE_MISMATCH;
1179 for (i = 1; i <= count; i++)
1181 if (lstrcmpW(MSI_RecordGetString(dbrec, i),
1182 MSI_RecordGetString(mergerec, i)))
1184 r = ERROR_DATATYPE_MISMATCH;
1190 msiobj_release(&dbrec->hdr);
1191 msiobj_release(&mergerec->hdr);
1196 static LPWSTR get_key_value(MSIQUERY *view, LPCWSTR key, MSIRECORD *rec)
1198 MSIRECORD *colnames;
1200 UINT r, i = 0, sz = 0;
1203 r = MSI_ViewGetColumnInfo(view, MSICOLINFO_NAMES, &colnames);
1204 if (r != ERROR_SUCCESS)
1209 str = msi_dup_record_field(colnames, ++i);
1210 cmp = lstrcmpW(key, str);
1214 msiobj_release(&colnames->hdr);
1216 r = MSI_RecordGetStringW(rec, i, NULL, &sz);
1217 if (r != ERROR_SUCCESS)
1221 if (MSI_RecordGetString(rec, i)) /* check record field is a string */
1223 /* quote string record fields */
1224 const WCHAR szQuote[] = {'\'', 0};
1226 val = msi_alloc(sz*sizeof(WCHAR));
1230 lstrcpyW(val, szQuote);
1231 r = MSI_RecordGetStringW(rec, i, val+1, &sz);
1232 lstrcpyW(val+1+sz, szQuote);
1236 /* do not quote integer record fields */
1237 val = msi_alloc(sz*sizeof(WCHAR));
1241 r = MSI_RecordGetStringW(rec, i, val, &sz);
1244 if (r != ERROR_SUCCESS)
1246 ERR("failed to get string!\n");
1254 static LPWSTR create_diff_row_query(MSIDATABASE *merge, MSIQUERY *view,
1255 LPWSTR table, MSIRECORD *rec)
1257 LPWSTR query = NULL, clause = NULL;
1258 LPWSTR ptr = NULL, val;
1260 DWORD size = 1, oldsize;
1265 static const WCHAR keyset[] = {
1266 '`','%','s','`',' ','=',' ','%','s',' ','A','N','D',' ',0};
1267 static const WCHAR lastkeyset[] = {
1268 '`','%','s','`',' ','=',' ','%','s',' ',0};
1269 static const WCHAR fmt[] = {'S','E','L','E','C','T',' ','*',' ',
1270 'F','R','O','M',' ','`','%','s','`',' ',
1271 'W','H','E','R','E',' ','%','s',0};
1273 r = MSI_DatabaseGetPrimaryKeys(merge, table, &keys);
1274 if (r != ERROR_SUCCESS)
1277 clause = msi_alloc_zero(size * sizeof(WCHAR));
1282 count = MSI_RecordGetFieldCount(keys);
1283 for (i = 1; i <= count; i++)
1285 key = MSI_RecordGetString(keys, i);
1286 val = get_key_value(view, key, rec);
1289 setptr = lastkeyset;
1294 size += lstrlenW(setptr) + lstrlenW(key) + lstrlenW(val) - 4;
1295 clause = msi_realloc(clause, size * sizeof (WCHAR));
1302 ptr = clause + oldsize - 1;
1303 sprintfW(ptr, setptr, key, val);
1307 size = lstrlenW(fmt) + lstrlenW(table) + lstrlenW(clause) + 1;
1308 query = msi_alloc(size * sizeof(WCHAR));
1312 sprintfW(query, fmt, table, clause);
1316 msiobj_release(&keys->hdr);
1320 static UINT merge_diff_row(MSIRECORD *rec, LPVOID param)
1322 MERGEDATA *data = param;
1323 MERGETABLE *table = data->curtable;
1325 MSIQUERY *dbview = NULL;
1326 MSIRECORD *row = NULL;
1327 LPWSTR query = NULL;
1328 UINT r = ERROR_SUCCESS;
1330 if (TABLE_Exists(data->db, table->name))
1332 query = create_diff_row_query(data->merge, data->curview, table->name, rec);
1334 return ERROR_OUTOFMEMORY;
1336 r = MSI_DatabaseOpenViewW(data->db, query, &dbview);
1337 if (r != ERROR_SUCCESS)
1340 r = MSI_ViewExecute(dbview, NULL);
1341 if (r != ERROR_SUCCESS)
1344 r = MSI_ViewFetch(dbview, &row);
1345 if (r == ERROR_SUCCESS && !MSI_RecordsAreEqual(rec, row))
1347 table->numconflicts++;
1350 else if (r != ERROR_NO_MORE_ITEMS)
1356 mergerow = msi_alloc(sizeof(MERGEROW));
1359 r = ERROR_OUTOFMEMORY;
1363 mergerow->data = MSI_CloneRecord(rec);
1364 if (!mergerow->data)
1366 r = ERROR_OUTOFMEMORY;
1371 list_add_tail(&table->rows, &mergerow->entry);
1375 msiobj_release(&row->hdr);
1376 msiobj_release(&dbview->hdr);
1380 static UINT msi_get_table_labels(MSIDATABASE *db, LPCWSTR table, LPWSTR **labels, DWORD *numlabels)
1383 MSIRECORD *prec = NULL;
1385 r = MSI_DatabaseGetPrimaryKeys(db, table, &prec);
1386 if (r != ERROR_SUCCESS)
1389 count = MSI_RecordGetFieldCount(prec);
1390 *numlabels = count + 1;
1391 *labels = msi_alloc((*numlabels)*sizeof(LPWSTR));
1394 r = ERROR_OUTOFMEMORY;
1398 (*labels)[0] = strdupW(table);
1399 for (i=1; i<=count; i++ )
1401 (*labels)[i] = strdupW(MSI_RecordGetString(prec, i));
1405 msiobj_release( &prec->hdr );
1409 static UINT msi_get_query_columns(MSIQUERY *query, LPWSTR **columns, DWORD *numcolumns)
1412 MSIRECORD *prec = NULL;
1414 r = MSI_ViewGetColumnInfo(query, MSICOLINFO_NAMES, &prec);
1415 if (r != ERROR_SUCCESS)
1418 count = MSI_RecordGetFieldCount(prec);
1419 *columns = msi_alloc(count*sizeof(LPWSTR));
1422 r = ERROR_OUTOFMEMORY;
1426 for (i=1; i<=count; i++ )
1428 (*columns)[i-1] = strdupW(MSI_RecordGetString(prec, i));
1431 *numcolumns = count;
1434 msiobj_release( &prec->hdr );
1438 static UINT msi_get_query_types(MSIQUERY *query, LPWSTR **types, DWORD *numtypes)
1441 MSIRECORD *prec = NULL;
1443 r = MSI_ViewGetColumnInfo(query, MSICOLINFO_TYPES, &prec);
1444 if (r != ERROR_SUCCESS)
1447 count = MSI_RecordGetFieldCount(prec);
1448 *types = msi_alloc(count*sizeof(LPWSTR));
1451 r = ERROR_OUTOFMEMORY;
1456 for (i=1; i<=count; i++ )
1458 (*types)[i-1] = strdupW(MSI_RecordGetString(prec, i));
1462 msiobj_release( &prec->hdr );
1466 static void merge_free_rows(MERGETABLE *table)
1468 struct list *item, *cursor;
1470 LIST_FOR_EACH_SAFE(item, cursor, &table->rows)
1472 MERGEROW *row = LIST_ENTRY(item, MERGEROW, entry);
1474 list_remove(&row->entry);
1475 msiobj_release(&row->data->hdr);
1480 static void free_merge_table(MERGETABLE *table)
1484 if (table->labels != NULL)
1486 for (i = 0; i < table->numlabels; i++)
1487 msi_free(table->labels[i]);
1489 msi_free(table->labels);
1492 if (table->columns != NULL)
1494 for (i = 0; i < table->numcolumns; i++)
1495 msi_free(table->columns[i]);
1497 msi_free(table->columns);
1500 if (table->types != NULL)
1502 for (i = 0; i < table->numtypes; i++)
1503 msi_free(table->types[i]);
1505 msi_free(table->types);
1508 msi_free(table->name);
1509 merge_free_rows(table);
1514 static UINT msi_get_merge_table (MSIDATABASE *db, LPCWSTR name, MERGETABLE **ptable)
1518 MSIQUERY *mergeview = NULL;
1520 static const WCHAR query[] = {'S','E','L','E','C','T',' ','*',' ',
1521 'F','R','O','M',' ','`','%','s','`',0};
1523 table = msi_alloc_zero(sizeof(MERGETABLE));
1527 return ERROR_OUTOFMEMORY;
1530 r = msi_get_table_labels(db, name, &table->labels, &table->numlabels);
1531 if (r != ERROR_SUCCESS)
1534 r = MSI_OpenQuery(db, &mergeview, query, name);
1535 if (r != ERROR_SUCCESS)
1538 r = msi_get_query_columns(mergeview, &table->columns, &table->numcolumns);
1539 if (r != ERROR_SUCCESS)
1542 r = msi_get_query_types(mergeview, &table->types, &table->numtypes);
1543 if (r != ERROR_SUCCESS)
1546 list_init(&table->rows);
1548 table->name = strdupW(name);
1549 table->numconflicts = 0;
1551 msiobj_release(&mergeview->hdr);
1553 return ERROR_SUCCESS;
1556 msiobj_release(&mergeview->hdr);
1557 free_merge_table(table);
1562 static UINT merge_diff_tables(MSIRECORD *rec, LPVOID param)
1564 MERGEDATA *data = param;
1566 MSIQUERY *dbview = NULL;
1567 MSIQUERY *mergeview = NULL;
1571 static const WCHAR query[] = {'S','E','L','E','C','T',' ','*',' ',
1572 'F','R','O','M',' ','`','%','s','`',0};
1574 name = MSI_RecordGetString(rec, 1);
1576 r = MSI_OpenQuery(data->merge, &mergeview, query, name);
1577 if (r != ERROR_SUCCESS)
1580 if (TABLE_Exists(data->db, name))
1582 r = MSI_OpenQuery(data->db, &dbview, query, name);
1583 if (r != ERROR_SUCCESS)
1586 r = merge_verify_colnames(dbview, mergeview);
1587 if (r != ERROR_SUCCESS)
1590 r = merge_verify_primary_keys(data->db, data->merge, name);
1591 if (r != ERROR_SUCCESS)
1595 r = msi_get_merge_table(data->merge, name, &table);
1596 if (r != ERROR_SUCCESS)
1599 data->curtable = table;
1600 data->curview = mergeview;
1601 r = MSI_IterateRecords(mergeview, NULL, merge_diff_row, data);
1602 if (r != ERROR_SUCCESS)
1604 free_merge_table(table);
1608 list_add_tail(data->tabledata, &table->entry);
1611 msiobj_release(&dbview->hdr);
1612 msiobj_release(&mergeview->hdr);
1616 static UINT gather_merge_data(MSIDATABASE *db, MSIDATABASE *merge,
1617 struct list *tabledata)
1623 static const WCHAR query[] = {'S','E','L','E','C','T',' ','*',' ',
1624 'F','R','O','M',' ','`','_','T','a','b','l','e','s','`',0};
1626 r = MSI_DatabaseOpenViewW(merge, query, &view);
1627 if (r != ERROR_SUCCESS)
1632 data.tabledata = tabledata;
1633 r = MSI_IterateRecords(view, NULL, merge_diff_tables, &data);
1635 msiobj_release(&view->hdr);
1639 static UINT merge_table(MSIDATABASE *db, MERGETABLE *table)
1645 if (!TABLE_Exists(db, table->name))
1647 r = msi_add_table_to_db(db, table->columns, table->types,
1648 table->labels, table->numlabels, table->numcolumns);
1649 if (r != ERROR_SUCCESS)
1650 return ERROR_FUNCTION_FAILED;
1653 LIST_FOR_EACH_ENTRY(row, &table->rows, MERGEROW, entry)
1655 r = TABLE_CreateView(db, table->name, &tv);
1656 if (r != ERROR_SUCCESS)
1659 r = tv->ops->insert_row(tv, row->data, -1, FALSE);
1660 tv->ops->delete(tv);
1662 if (r != ERROR_SUCCESS)
1666 return ERROR_SUCCESS;
1669 static UINT update_merge_errors(MSIDATABASE *db, LPCWSTR error,
1670 LPWSTR table, DWORD numconflicts)
1675 static const WCHAR create[] = {
1676 'C','R','E','A','T','E',' ','T','A','B','L','E',' ',
1677 '`','%','s','`',' ','(','`','T','a','b','l','e','`',' ',
1678 'C','H','A','R','(','2','5','5',')',' ','N','O','T',' ',
1679 'N','U','L','L',',',' ','`','N','u','m','R','o','w','M','e','r','g','e',
1680 'C','o','n','f','l','i','c','t','s','`',' ','S','H','O','R','T',' ',
1681 'N','O','T',' ','N','U','L','L',' ','P','R','I','M','A','R','Y',' ',
1682 'K','E','Y',' ','`','T','a','b','l','e','`',')',0};
1683 static const WCHAR insert[] = {
1684 'I','N','S','E','R','T',' ','I','N','T','O',' ',
1685 '`','%','s','`',' ','(','`','T','a','b','l','e','`',',',' ',
1686 '`','N','u','m','R','o','w','M','e','r','g','e',
1687 'C','o','n','f','l','i','c','t','s','`',')',' ','V','A','L','U','E','S',
1688 ' ','(','\'','%','s','\'',',',' ','%','d',')',0};
1690 if (!TABLE_Exists(db, error))
1692 r = MSI_OpenQuery(db, &view, create, error);
1693 if (r != ERROR_SUCCESS)
1696 r = MSI_ViewExecute(view, NULL);
1697 msiobj_release(&view->hdr);
1698 if (r != ERROR_SUCCESS)
1702 r = MSI_OpenQuery(db, &view, insert, error, table, numconflicts);
1703 if (r != ERROR_SUCCESS)
1706 r = MSI_ViewExecute(view, NULL);
1707 msiobj_release(&view->hdr);
1711 UINT WINAPI MsiDatabaseMergeW(MSIHANDLE hDatabase, MSIHANDLE hDatabaseMerge,
1712 LPCWSTR szTableName)
1714 struct list tabledata = LIST_INIT(tabledata);
1715 struct list *item, *cursor;
1716 MSIDATABASE *db, *merge;
1721 TRACE("(%d, %d, %s)\n", hDatabase, hDatabaseMerge,
1722 debugstr_w(szTableName));
1724 if (szTableName && !*szTableName)
1725 return ERROR_INVALID_TABLE;
1727 db = msihandle2msiinfo(hDatabase, MSIHANDLETYPE_DATABASE);
1728 merge = msihandle2msiinfo(hDatabaseMerge, MSIHANDLETYPE_DATABASE);
1731 r = ERROR_INVALID_HANDLE;
1735 r = gather_merge_data(db, merge, &tabledata);
1736 if (r != ERROR_SUCCESS)
1740 LIST_FOR_EACH_ENTRY(table, &tabledata, MERGETABLE, entry)
1742 if (table->numconflicts)
1746 r = update_merge_errors(db, szTableName, table->name,
1747 table->numconflicts);
1748 if (r != ERROR_SUCCESS)
1753 r = merge_table(db, table);
1754 if (r != ERROR_SUCCESS)
1759 LIST_FOR_EACH_SAFE(item, cursor, &tabledata)
1761 MERGETABLE *table = LIST_ENTRY(item, MERGETABLE, entry);
1762 list_remove(&table->entry);
1763 free_merge_table(table);
1767 r = ERROR_FUNCTION_FAILED;
1770 msiobj_release(&db->hdr);
1771 msiobj_release(&merge->hdr);
1775 MSIDBSTATE WINAPI MsiGetDatabaseState( MSIHANDLE handle )
1777 MSIDBSTATE ret = MSIDBSTATE_READ;
1780 TRACE("%d\n", handle);
1782 db = msihandle2msiinfo( handle, MSIHANDLETYPE_DATABASE );
1785 IWineMsiRemoteDatabase *remote_database;
1787 remote_database = (IWineMsiRemoteDatabase *)msi_get_remote( handle );
1788 if ( !remote_database )
1789 return MSIDBSTATE_ERROR;
1791 IWineMsiRemoteDatabase_Release( remote_database );
1792 WARN("MsiGetDatabaseState not allowed during a custom action!\n");
1794 return MSIDBSTATE_READ;
1797 if (db->mode != MSIDBOPEN_READONLY )
1798 ret = MSIDBSTATE_WRITE;
1799 msiobj_release( &db->hdr );
1804 typedef struct _msi_remote_database_impl {
1805 const IWineMsiRemoteDatabaseVtbl *lpVtbl;
1808 } msi_remote_database_impl;
1810 static inline msi_remote_database_impl* mrd_from_IWineMsiRemoteDatabase( IWineMsiRemoteDatabase* iface )
1812 return (msi_remote_database_impl *)iface;
1815 static HRESULT WINAPI mrd_QueryInterface( IWineMsiRemoteDatabase *iface,
1816 REFIID riid,LPVOID *ppobj)
1818 if( IsEqualCLSID( riid, &IID_IUnknown ) ||
1819 IsEqualCLSID( riid, &IID_IWineMsiRemoteDatabase ) )
1821 IUnknown_AddRef( iface );
1826 return E_NOINTERFACE;
1829 static ULONG WINAPI mrd_AddRef( IWineMsiRemoteDatabase *iface )
1831 msi_remote_database_impl* This = mrd_from_IWineMsiRemoteDatabase( iface );
1833 return InterlockedIncrement( &This->refs );
1836 static ULONG WINAPI mrd_Release( IWineMsiRemoteDatabase *iface )
1838 msi_remote_database_impl* This = mrd_from_IWineMsiRemoteDatabase( iface );
1841 r = InterlockedDecrement( &This->refs );
1844 MsiCloseHandle( This->database );
1850 static HRESULT WINAPI mrd_IsTablePersistent( IWineMsiRemoteDatabase *iface,
1851 BSTR table, MSICONDITION *persistent )
1853 msi_remote_database_impl *This = mrd_from_IWineMsiRemoteDatabase( iface );
1854 *persistent = MsiDatabaseIsTablePersistentW(This->database, table);
1858 static HRESULT WINAPI mrd_GetPrimaryKeys( IWineMsiRemoteDatabase *iface,
1859 BSTR table, MSIHANDLE *keys )
1861 msi_remote_database_impl *This = mrd_from_IWineMsiRemoteDatabase( iface );
1862 UINT r = MsiDatabaseGetPrimaryKeysW(This->database, table, keys);
1863 return HRESULT_FROM_WIN32(r);
1866 static HRESULT WINAPI mrd_GetSummaryInformation( IWineMsiRemoteDatabase *iface,
1867 UINT updatecount, MSIHANDLE *suminfo )
1869 msi_remote_database_impl *This = mrd_from_IWineMsiRemoteDatabase( iface );
1870 UINT r = MsiGetSummaryInformationW(This->database, NULL, updatecount, suminfo);
1871 return HRESULT_FROM_WIN32(r);
1874 static HRESULT WINAPI mrd_OpenView( IWineMsiRemoteDatabase *iface,
1875 BSTR query, MSIHANDLE *view )
1877 msi_remote_database_impl *This = mrd_from_IWineMsiRemoteDatabase( iface );
1878 UINT r = MsiDatabaseOpenViewW(This->database, query, view);
1879 return HRESULT_FROM_WIN32(r);
1882 static HRESULT WINAPI mrd_SetMsiHandle( IWineMsiRemoteDatabase *iface, MSIHANDLE handle )
1884 msi_remote_database_impl* This = mrd_from_IWineMsiRemoteDatabase( iface );
1885 This->database = handle;
1889 static const IWineMsiRemoteDatabaseVtbl msi_remote_database_vtbl =
1894 mrd_IsTablePersistent,
1896 mrd_GetSummaryInformation,
1901 HRESULT create_msi_remote_database( IUnknown *pOuter, LPVOID *ppObj )
1903 msi_remote_database_impl *This;
1905 This = msi_alloc( sizeof *This );
1907 return E_OUTOFMEMORY;
1909 This->lpVtbl = &msi_remote_database_vtbl;