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);
44 DEFINE_GUID( CLSID_MsiDatabase, 0x000c1084, 0x0000, 0x0000,
45 0xc0,0x00,0x00,0x00,0x00,0x00,0x00,0x46);
46 DEFINE_GUID( CLSID_MsiPatch, 0x000c1086, 0x0000, 0x0000,
47 0xc0,0x00,0x00,0x00,0x00,0x00,0x00,0x46);
52 * An .msi file is a structured storage file.
53 * It contains a number of streams.
54 * A stream for each table in the database.
55 * Two streams for the string table in the database.
56 * Any binary data in a table is a reference to a stream.
59 static VOID MSI_CloseDatabase( MSIOBJECTHDR *arg )
61 MSIDATABASE *db = (MSIDATABASE *) arg;
64 free_cached_tables( db );
65 msi_free_transforms( db );
66 msi_destroy_stringtable( db->strings );
67 IStorage_Release( db->storage );
70 DeleteFileW( db->deletefile );
71 msi_free( db->deletefile );
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 backslash[] = {'\\',0};
87 static const WCHAR szTables[] = { '_','T','a','b','l','e','s',0 };
89 TRACE("%s %s\n",debugstr_w(szDBPath),debugstr_w(szPersist) );
92 return ERROR_INVALID_PARAMETER;
94 if (szPersist - MSIDBOPEN_PATCHFILE >= MSIDBOPEN_READONLY &&
95 szPersist - MSIDBOPEN_PATCHFILE <= MSIDBOPEN_CREATEDIRECT)
97 TRACE("Database is a patch\n");
98 szPersist -= MSIDBOPEN_PATCHFILE;
101 save_path = szDBPath;
103 if( HIWORD( szPersist ) )
105 if (!CopyFileW( szDBPath, szPersist, FALSE ))
106 return ERROR_OPEN_FAILED;
108 szDBPath = szPersist;
109 szPersist = MSIDBOPEN_TRANSACT;
113 if( szPersist == MSIDBOPEN_READONLY )
115 r = StgOpenStorage( szDBPath, NULL,
116 STGM_DIRECT|STGM_READ|STGM_SHARE_DENY_WRITE, NULL, 0, &stg);
118 else if( szPersist == MSIDBOPEN_CREATE || szPersist == MSIDBOPEN_CREATEDIRECT )
120 /* FIXME: MSIDBOPEN_CREATE should case STGM_TRANSACTED flag to be
122 r = StgCreateDocfile( szDBPath,
123 STGM_CREATE|STGM_DIRECT|STGM_READWRITE|STGM_SHARE_EXCLUSIVE, 0, &stg);
124 if( r == ERROR_SUCCESS )
126 IStorage_SetClass( stg, &CLSID_MsiDatabase );
127 /* create the _Tables stream */
128 r = write_stream_data(stg, szTables, NULL, 0, TRUE);
130 r = msi_init_string_table( stg );
134 else if( szPersist == MSIDBOPEN_TRANSACT )
136 /* FIXME: MSIDBOPEN_TRANSACT should case STGM_TRANSACTED flag to be
138 r = StgOpenStorage( szDBPath, NULL,
139 STGM_DIRECT|STGM_READWRITE|STGM_SHARE_EXCLUSIVE, NULL, 0, &stg);
141 else if( szPersist == MSIDBOPEN_DIRECT )
143 r = StgOpenStorage( szDBPath, NULL,
144 STGM_DIRECT|STGM_READWRITE|STGM_SHARE_EXCLUSIVE, NULL, 0, &stg);
148 ERR("unknown flag %p\n",szPersist);
149 return ERROR_INVALID_PARAMETER;
152 if( FAILED( r ) || !stg )
154 FIXME("open failed r = %08x for %s\n", r, debugstr_w(szDBPath));
155 return ERROR_FUNCTION_FAILED;
158 r = IStorage_Stat( stg, &stat, STATFLAG_NONAME );
161 FIXME("Failed to stat storage\n");
165 if ( !IsEqualGUID( &stat.clsid, &CLSID_MsiDatabase ) &&
166 !IsEqualGUID( &stat.clsid, &CLSID_MsiPatch ) )
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, backslash );
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 );
200 db->deletefile = NULL;
201 list_init( &db->tables );
202 list_init( &db->transforms );
204 db->strings = msi_load_string_table( stg, &db->bytes_per_strref );
210 msiobj_addref( &db->hdr );
211 IStorage_AddRef( stg );
216 msiobj_release( &db->hdr );
218 IStorage_Release( stg );
223 UINT WINAPI MsiOpenDatabaseW(LPCWSTR szDBPath, LPCWSTR szPersist, MSIHANDLE *phDB)
228 TRACE("%s %s %p\n",debugstr_w(szDBPath),debugstr_w(szPersist), phDB);
230 ret = MSI_OpenDatabaseW( szDBPath, szPersist, &db );
231 if( ret == ERROR_SUCCESS )
233 *phDB = alloc_msihandle( &db->hdr );
235 ret = ERROR_NOT_ENOUGH_MEMORY;
236 msiobj_release( &db->hdr );
242 UINT WINAPI MsiOpenDatabaseA(LPCSTR szDBPath, LPCSTR szPersist, MSIHANDLE *phDB)
244 HRESULT r = ERROR_FUNCTION_FAILED;
245 LPWSTR szwDBPath = NULL, szwPersist = NULL;
247 TRACE("%s %s %p\n", debugstr_a(szDBPath), debugstr_a(szPersist), phDB);
251 szwDBPath = strdupAtoW( szDBPath );
256 if( HIWORD(szPersist) )
258 szwPersist = strdupAtoW( szPersist );
263 szwPersist = (LPWSTR)(DWORD_PTR)szPersist;
265 r = MsiOpenDatabaseW( szwDBPath, szwPersist, phDB );
268 if( HIWORD(szPersist) )
269 msi_free( szwPersist );
270 msi_free( szwDBPath );
275 static LPWSTR msi_read_text_archive(LPCWSTR path)
280 DWORD read, size = 0;
282 file = CreateFileW( path, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL );
283 if (file == INVALID_HANDLE_VALUE)
286 size = GetFileSize( file, NULL );
287 data = msi_alloc( size + 1 );
291 if (!ReadFile( file, data, size, &read, NULL ))
295 wdata = strdupAtoW( data );
303 static void msi_parse_line(LPWSTR *line, LPWSTR **entries, DWORD *num_entries)
305 LPWSTR ptr = *line, save;
310 /* stay on this line */
311 while (*ptr && *ptr != '\n')
313 /* entries are separated by tabs */
320 *entries = msi_alloc(count * sizeof(LPWSTR));
324 /* store pointers into the data */
325 for (i = 0, ptr = *line; i < count; i++)
327 while (*ptr && *ptr == '\r') ptr++;
330 while (*ptr && *ptr != '\t' && *ptr != '\n' && *ptr != '\r') ptr++;
332 /* NULL-separate the data */
333 if (*ptr == '\n' || *ptr == '\r')
335 while (*ptr == '\n' || *ptr == '\r')
341 (*entries)[i] = save;
344 /* move to the next line if there's more, else EOF */
348 *num_entries = count;
351 static LPWSTR msi_build_createsql_prelude(LPWSTR table)
356 static const WCHAR create_fmt[] = {'C','R','E','A','T','E',' ','T','A','B','L','E',' ','`','%','s','`',' ','(',' ',0};
358 size = sizeof(create_fmt)/sizeof(create_fmt[0]) + lstrlenW(table) - 2;
359 prelude = msi_alloc(size * sizeof(WCHAR));
363 sprintfW(prelude, create_fmt, table);
367 static LPWSTR msi_build_createsql_columns(LPWSTR *columns_data, LPWSTR *types, DWORD num_columns)
371 DWORD sql_size = 1, i, len;
372 WCHAR expanded[128], *ptr;
373 WCHAR size[10], comma[2], extra[30];
375 static const WCHAR column_fmt[] = {'`','%','s','`',' ','%','s','%','s','%','s','%','s',' ',0};
376 static const WCHAR size_fmt[] = {'(','%','s',')',0};
377 static const WCHAR type_char[] = {'C','H','A','R',0};
378 static const WCHAR type_int[] = {'I','N','T',0};
379 static const WCHAR type_long[] = {'L','O','N','G',0};
380 static const WCHAR type_object[] = {'O','B','J','E','C','T',0};
381 static const WCHAR type_notnull[] = {' ','N','O','T',' ','N','U','L','L',0};
382 static const WCHAR localizable[] = {' ','L','O','C','A','L','I','Z','A','B','L','E',0};
384 columns = msi_alloc_zero(sql_size * sizeof(WCHAR));
388 for (i = 0; i < num_columns; i++)
391 comma[1] = size[0] = extra[0] = '\0';
393 if (i == num_columns - 1)
405 lstrcpyW(extra, type_notnull);
407 lstrcatW(extra, localizable);
409 sprintfW(size, size_fmt, ptr);
412 lstrcpyW(extra, type_notnull);
415 sprintfW(size, size_fmt, ptr);
418 lstrcpyW(extra, type_notnull);
426 lstrcpyW(extra, type_notnull);
431 ERR("Unknown type: %c\n", types[i][0]);
436 sprintfW(expanded, column_fmt, columns_data[i], type, size, extra, comma);
437 sql_size += lstrlenW(expanded);
439 p = msi_realloc(columns, sql_size * sizeof(WCHAR));
447 lstrcatW(columns, expanded);
453 static LPWSTR msi_build_createsql_postlude(LPWSTR *primary_keys, DWORD num_keys)
455 LPWSTR postlude, keys, ptr;
456 DWORD size, key_size, i;
458 static const WCHAR key_fmt[] = {'`','%','s','`',',',' ',0};
459 static const WCHAR postlude_fmt[] = {'P','R','I','M','A','R','Y',' ','K','E','Y',' ','%','s',')',0};
461 for (i = 0, size = 1; i < num_keys; i++)
462 size += lstrlenW(key_fmt) + lstrlenW(primary_keys[i]) - 2;
464 keys = msi_alloc(size * sizeof(WCHAR));
468 for (i = 0, ptr = keys; i < num_keys; i++)
470 key_size = lstrlenW(key_fmt) + lstrlenW(primary_keys[i]) -2;
471 sprintfW(ptr, key_fmt, primary_keys[i]);
475 /* remove final ', ' */
478 size = lstrlenW(postlude_fmt) + size - 1;
479 postlude = msi_alloc(size * sizeof(WCHAR));
483 sprintfW(postlude, postlude_fmt, keys);
490 static UINT msi_add_table_to_db(MSIDATABASE *db, LPWSTR *columns, LPWSTR *types, LPWSTR *labels, DWORD num_labels, DWORD num_columns)
496 LPWSTR prelude, columns_sql, postlude;
498 prelude = msi_build_createsql_prelude(labels[0]);
499 columns_sql = msi_build_createsql_columns(columns, types, num_columns);
500 postlude = msi_build_createsql_postlude(labels + 1, num_labels - 1); /* skip over table name */
502 if (!prelude || !columns_sql || !postlude)
503 return ERROR_OUTOFMEMORY;
505 size = lstrlenW(prelude) + lstrlenW(columns_sql) + lstrlenW(postlude) + 1;
506 create_sql = msi_alloc(size * sizeof(WCHAR));
508 return ERROR_OUTOFMEMORY;
510 lstrcpyW(create_sql, prelude);
511 lstrcatW(create_sql, columns_sql);
512 lstrcatW(create_sql, postlude);
515 msi_free(columns_sql);
518 r = MSI_DatabaseOpenViewW( db, create_sql, &view );
519 msi_free(create_sql);
521 if (r != ERROR_SUCCESS)
524 r = MSI_ViewExecute(view, NULL);
526 msiobj_release(&view->hdr);
531 static LPWSTR msi_import_stream_filename(LPCWSTR path, LPCWSTR name)
534 LPWSTR fullname, ptr;
536 len = lstrlenW(path) + lstrlenW(name) + 1;
537 fullname = msi_alloc(len*sizeof(WCHAR));
541 lstrcpyW( fullname, path );
543 /* chop off extension from path */
544 ptr = strrchrW(fullname, '.');
551 lstrcpyW( ptr, name );
555 static UINT construct_record(DWORD num_columns, LPWSTR *types,
556 LPWSTR *data, LPWSTR path, MSIRECORD **rec)
560 *rec = MSI_CreateRecord(num_columns);
562 return ERROR_OUTOFMEMORY;
564 for (i = 0; i < num_columns; i++)
568 case 'L': case 'l': case 'S': case 's':
569 MSI_RecordSetStringW(*rec, i + 1, data[i]);
573 MSI_RecordSetInteger(*rec, i + 1, atoiW(data[i]));
579 LPWSTR file = msi_import_stream_filename(path, data[i]);
581 return ERROR_FUNCTION_FAILED;
583 r = MSI_RecordSetStreamFromFileW(*rec, i + 1, file);
585 if (r != ERROR_SUCCESS)
586 return ERROR_FUNCTION_FAILED;
590 ERR("Unhandled column type: %c\n", types[i][0]);
591 msiobj_release(&(*rec)->hdr);
592 return ERROR_FUNCTION_FAILED;
596 return ERROR_SUCCESS;
599 static UINT msi_add_records_to_table(MSIDATABASE *db, LPWSTR *columns, LPWSTR *types,
600 LPWSTR *labels, LPWSTR **records,
601 int num_columns, int num_records,
609 static const WCHAR select[] = {
610 'S','E','L','E','C','T',' ','*',' ',
611 'F','R','O','M',' ','`','%','s','`',0
614 r = MSI_OpenQuery(db, &view, select, labels[0]);
615 if (r != ERROR_SUCCESS)
618 while (MSI_ViewFetch(view, &rec) != ERROR_NO_MORE_ITEMS)
620 r = MSI_ViewModify(view, MSIMODIFY_DELETE, rec);
621 if (r != ERROR_SUCCESS)
625 for (i = 0; i < num_records; i++)
627 r = construct_record(num_columns, types, records[i], path, &rec);
628 if (r != ERROR_SUCCESS)
631 r = MSI_ViewModify(view, MSIMODIFY_INSERT, rec);
632 if (r != ERROR_SUCCESS)
634 msiobj_release(&rec->hdr);
638 msiobj_release(&rec->hdr);
642 msiobj_release(&view->hdr);
646 static UINT MSI_DatabaseImport(MSIDATABASE *db, LPCWSTR folder, LPCWSTR file)
650 DWORD num_labels, num_types;
651 DWORD num_columns, num_records = 0;
652 LPWSTR *columns, *types, *labels;
653 LPWSTR path, ptr, data;
654 LPWSTR **records = NULL;
655 LPWSTR **temp_records;
657 static const WCHAR backslash[] = {'\\',0};
658 static const WCHAR suminfo[] =
659 {'_','S','u','m','m','a','r','y','I','n','f','o','r','m','a','t','i','o','n',0};
661 TRACE("%p %s %s\n", db, debugstr_w(folder), debugstr_w(file) );
663 if( folder == NULL || file == NULL )
664 return ERROR_INVALID_PARAMETER;
666 len = lstrlenW(folder) + lstrlenW(backslash) + lstrlenW(file) + 1;
667 path = msi_alloc( len * sizeof(WCHAR) );
669 return ERROR_OUTOFMEMORY;
671 lstrcpyW( path, folder );
672 lstrcatW( path, backslash );
673 lstrcatW( path, file );
675 data = msi_read_text_archive( path );
678 msi_parse_line( &ptr, &columns, &num_columns );
679 msi_parse_line( &ptr, &types, &num_types );
680 msi_parse_line( &ptr, &labels, &num_labels );
682 if (num_columns != num_types)
684 r = ERROR_FUNCTION_FAILED;
688 records = msi_alloc(sizeof(LPWSTR *));
691 r = ERROR_OUTOFMEMORY;
695 /* read in the table records */
698 msi_parse_line( &ptr, &records[num_records], NULL );
701 temp_records = msi_realloc(records, (num_records + 1) * sizeof(LPWSTR *));
704 r = ERROR_OUTOFMEMORY;
707 records = temp_records;
710 if (!strcmpW(labels[0], suminfo))
712 r = msi_add_suminfo( db, records, num_records, num_columns );
713 if (r != ERROR_SUCCESS)
715 r = ERROR_FUNCTION_FAILED;
721 if (!TABLE_Exists(db, labels[0]))
723 r = msi_add_table_to_db( db, columns, types, labels, num_labels, num_columns );
724 if (r != ERROR_SUCCESS)
726 r = ERROR_FUNCTION_FAILED;
731 r = msi_add_records_to_table( db, columns, types, labels, records, num_columns, num_records, path );
741 for (i = 0; i < num_records; i++)
742 msi_free(records[i]);
749 UINT WINAPI MsiDatabaseImportW(MSIHANDLE handle, LPCWSTR szFolder, LPCWSTR szFilename)
754 TRACE("%x %s %s\n",handle,debugstr_w(szFolder), debugstr_w(szFilename));
756 db = msihandle2msiinfo( handle, MSIHANDLETYPE_DATABASE );
759 IWineMsiRemoteDatabase *remote_database;
761 remote_database = (IWineMsiRemoteDatabase *)msi_get_remote( handle );
762 if ( !remote_database )
763 return ERROR_INVALID_HANDLE;
765 IWineMsiRemoteDatabase_Release( remote_database );
766 WARN("MsiDatabaseImport not allowed during a custom action!\n");
768 return ERROR_SUCCESS;
771 r = MSI_DatabaseImport( db, szFolder, szFilename );
772 msiobj_release( &db->hdr );
776 UINT WINAPI MsiDatabaseImportA( MSIHANDLE handle,
777 LPCSTR szFolder, LPCSTR szFilename )
779 LPWSTR path = NULL, file = NULL;
780 UINT r = ERROR_OUTOFMEMORY;
782 TRACE("%x %s %s\n", handle, debugstr_a(szFolder), debugstr_a(szFilename));
786 path = strdupAtoW( szFolder );
793 file = strdupAtoW( szFilename );
798 r = MsiDatabaseImportW( handle, path, file );
807 static UINT msi_export_record( HANDLE handle, MSIRECORD *row, UINT start )
809 UINT i, count, len, r = ERROR_SUCCESS;
815 buffer = msi_alloc( len );
817 return ERROR_OUTOFMEMORY;
819 count = MSI_RecordGetFieldCount( row );
820 for ( i=start; i<=count; i++ )
823 r = MSI_RecordGetStringA( row, i, buffer, &sz );
824 if (r == ERROR_MORE_DATA)
826 char *p = msi_realloc( buffer, sz + 1 );
833 r = MSI_RecordGetStringA( row, i, buffer, &sz );
834 if (r != ERROR_SUCCESS)
837 if (!WriteFile( handle, buffer, sz, &sz, NULL ))
839 r = ERROR_FUNCTION_FAILED;
843 sep = (i < count) ? "\t" : "\r\n";
844 if (!WriteFile( handle, sep, strlen(sep), &sz, NULL ))
846 r = ERROR_FUNCTION_FAILED;
854 static UINT msi_export_row( MSIRECORD *row, void *arg )
856 return msi_export_record( arg, row, 1 );
859 static UINT msi_export_forcecodepage( HANDLE handle )
863 static const char data[] = "\r\n\r\n0\t_ForceCodepage\r\n";
865 FIXME("Read the codepage from the strings table!\n");
867 sz = lstrlenA(data) + 1;
868 if (!WriteFile(handle, data, sz, &sz, NULL))
869 return ERROR_FUNCTION_FAILED;
871 return ERROR_SUCCESS;
874 static UINT MSI_DatabaseExport( MSIDATABASE *db, LPCWSTR table,
875 LPCWSTR folder, LPCWSTR file )
877 static const WCHAR query[] = {
878 's','e','l','e','c','t',' ','*',' ','f','r','o','m',' ','%','s',0 };
879 static const WCHAR szbs[] = { '\\', 0 };
880 static const WCHAR forcecodepage[] = {
881 '_','F','o','r','c','e','C','o','d','e','p','a','g','e',0 };
882 MSIRECORD *rec = NULL;
883 MSIQUERY *view = NULL;
888 TRACE("%p %s %s %s\n", db, debugstr_w(table),
889 debugstr_w(folder), debugstr_w(file) );
891 if( folder == NULL || file == NULL )
892 return ERROR_INVALID_PARAMETER;
894 len = lstrlenW(folder) + lstrlenW(file) + 2;
895 filename = msi_alloc(len * sizeof (WCHAR));
897 return ERROR_OUTOFMEMORY;
899 lstrcpyW( filename, folder );
900 lstrcatW( filename, szbs );
901 lstrcatW( filename, file );
903 handle = CreateFileW( filename, GENERIC_READ | GENERIC_WRITE, 0,
904 NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );
905 msi_free( filename );
906 if (handle == INVALID_HANDLE_VALUE)
907 return ERROR_FUNCTION_FAILED;
909 if (!lstrcmpW( table, forcecodepage ))
911 r = msi_export_forcecodepage( handle );
915 r = MSI_OpenQuery( db, &view, query, table );
916 if (r == ERROR_SUCCESS)
918 /* write out row 1, the column names */
919 r = MSI_ViewGetColumnInfo(view, MSICOLINFO_NAMES, &rec);
920 if (r == ERROR_SUCCESS)
922 msi_export_record( handle, rec, 1 );
923 msiobj_release( &rec->hdr );
926 /* write out row 2, the column types */
927 r = MSI_ViewGetColumnInfo(view, MSICOLINFO_TYPES, &rec);
928 if (r == ERROR_SUCCESS)
930 msi_export_record( handle, rec, 1 );
931 msiobj_release( &rec->hdr );
934 /* write out row 3, the table name + keys */
935 r = MSI_DatabaseGetPrimaryKeys( db, table, &rec );
936 if (r == ERROR_SUCCESS)
938 MSI_RecordSetStringW( rec, 0, table );
939 msi_export_record( handle, rec, 0 );
940 msiobj_release( &rec->hdr );
943 /* write out row 4 onwards, the data */
944 r = MSI_IterateRecords( view, 0, msi_export_row, handle );
945 msiobj_release( &view->hdr );
949 CloseHandle( handle );
953 /***********************************************************************
954 * MsiExportDatabaseW [MSI.@]
956 * Writes a file containing the table data as tab separated ASCII.
958 * The format is as follows:
960 * row1 : colname1 <tab> colname2 <tab> .... colnameN <cr> <lf>
961 * row2 : coltype1 <tab> coltype2 <tab> .... coltypeN <cr> <lf>
962 * row3 : tablename <tab> key1 <tab> key2 <tab> ... keyM <cr> <lf>
964 * Followed by the data, starting at row 1 with one row per line
966 * row4 : data <tab> data <tab> data <tab> ... data <cr> <lf>
968 UINT WINAPI MsiDatabaseExportW( MSIHANDLE handle, LPCWSTR szTable,
969 LPCWSTR szFolder, LPCWSTR szFilename )
974 TRACE("%x %s %s %s\n", handle, debugstr_w(szTable),
975 debugstr_w(szFolder), debugstr_w(szFilename));
977 db = msihandle2msiinfo( handle, MSIHANDLETYPE_DATABASE );
980 IWineMsiRemoteDatabase *remote_database;
982 remote_database = (IWineMsiRemoteDatabase *)msi_get_remote( handle );
983 if ( !remote_database )
984 return ERROR_INVALID_HANDLE;
986 IWineMsiRemoteDatabase_Release( remote_database );
987 WARN("MsiDatabaseExport not allowed during a custom action!\n");
989 return ERROR_SUCCESS;
992 r = MSI_DatabaseExport( db, szTable, szFolder, szFilename );
993 msiobj_release( &db->hdr );
997 UINT WINAPI MsiDatabaseExportA( MSIHANDLE handle, LPCSTR szTable,
998 LPCSTR szFolder, LPCSTR szFilename )
1000 LPWSTR path = NULL, file = NULL, table = NULL;
1001 UINT r = ERROR_OUTOFMEMORY;
1003 TRACE("%x %s %s %s\n", handle, debugstr_a(szTable),
1004 debugstr_a(szFolder), debugstr_a(szFilename));
1008 table = strdupAtoW( szTable );
1015 path = strdupAtoW( szFolder );
1022 file = strdupAtoW( szFilename );
1027 r = MsiDatabaseExportW( handle, table, path, file );
1037 UINT WINAPI MsiDatabaseMergeA(MSIHANDLE hDatabase, MSIHANDLE hDatabaseMerge,
1043 TRACE("(%d, %d, %s)\n", hDatabase, hDatabaseMerge,
1044 debugstr_a(szTableName));
1046 table = strdupAtoW(szTableName);
1047 r = MsiDatabaseMergeW(hDatabase, hDatabaseMerge, table);
1053 typedef struct _tagMERGETABLE
1067 typedef struct _tagMERGEROW
1073 typedef struct _tagMERGEDATA
1077 MERGETABLE *curtable;
1079 struct list *tabledata;
1082 static UINT merge_verify_colnames(MSIQUERY *dbview, MSIQUERY *mergeview)
1084 MSIRECORD *dbrec, *mergerec;
1087 r = MSI_ViewGetColumnInfo(dbview, MSICOLINFO_NAMES, &dbrec);
1088 if (r != ERROR_SUCCESS)
1091 r = MSI_ViewGetColumnInfo(mergeview, MSICOLINFO_NAMES, &mergerec);
1092 if (r != ERROR_SUCCESS)
1095 count = MSI_RecordGetFieldCount(dbrec);
1096 for (i = 1; i <= count; i++)
1098 if (!MSI_RecordGetString(mergerec, i))
1101 if (lstrcmpW(MSI_RecordGetString(dbrec, i),
1102 MSI_RecordGetString(mergerec, i)))
1104 r = ERROR_DATATYPE_MISMATCH;
1109 msiobj_release(&dbrec->hdr);
1110 msiobj_release(&mergerec->hdr);
1111 dbrec = mergerec = NULL;
1113 r = MSI_ViewGetColumnInfo(dbview, MSICOLINFO_TYPES, &dbrec);
1114 if (r != ERROR_SUCCESS)
1117 r = MSI_ViewGetColumnInfo(mergeview, MSICOLINFO_TYPES, &mergerec);
1118 if (r != ERROR_SUCCESS)
1121 count = MSI_RecordGetFieldCount(dbrec);
1122 for (i = 1; i <= count; i++)
1124 if (!MSI_RecordGetString(mergerec, i))
1127 if (lstrcmpW(MSI_RecordGetString(dbrec, i),
1128 MSI_RecordGetString(mergerec, i)))
1130 r = ERROR_DATATYPE_MISMATCH;
1136 msiobj_release(&dbrec->hdr);
1137 msiobj_release(&mergerec->hdr);
1142 static UINT merge_verify_primary_keys(MSIDATABASE *db, MSIDATABASE *mergedb,
1145 MSIRECORD *dbrec, *mergerec = NULL;
1148 r = MSI_DatabaseGetPrimaryKeys(db, table, &dbrec);
1149 if (r != ERROR_SUCCESS)
1152 r = MSI_DatabaseGetPrimaryKeys(mergedb, table, &mergerec);
1153 if (r != ERROR_SUCCESS)
1156 count = MSI_RecordGetFieldCount(dbrec);
1157 if (count != MSI_RecordGetFieldCount(mergerec))
1159 r = ERROR_DATATYPE_MISMATCH;
1163 for (i = 1; i <= count; i++)
1165 if (lstrcmpW(MSI_RecordGetString(dbrec, i),
1166 MSI_RecordGetString(mergerec, i)))
1168 r = ERROR_DATATYPE_MISMATCH;
1174 msiobj_release(&dbrec->hdr);
1175 msiobj_release(&mergerec->hdr);
1180 static LPWSTR get_key_value(MSIQUERY *view, LPCWSTR key, MSIRECORD *rec)
1182 MSIRECORD *colnames;
1184 UINT r, i = 0, sz = 0;
1187 r = MSI_ViewGetColumnInfo(view, MSICOLINFO_NAMES, &colnames);
1188 if (r != ERROR_SUCCESS)
1193 str = msi_dup_record_field(colnames, ++i);
1194 cmp = lstrcmpW(key, str);
1198 msiobj_release(&colnames->hdr);
1200 r = MSI_RecordGetStringW(rec, i, NULL, &sz);
1201 if (r != ERROR_SUCCESS)
1205 if (MSI_RecordGetString(rec, i)) /* check record field is a string */
1207 /* quote string record fields */
1208 const WCHAR szQuote[] = {'\'', 0};
1210 val = msi_alloc(sz*sizeof(WCHAR));
1214 lstrcpyW(val, szQuote);
1215 r = MSI_RecordGetStringW(rec, i, val+1, &sz);
1216 lstrcpyW(val+1+sz, szQuote);
1220 /* do not quote integer record fields */
1221 val = msi_alloc(sz*sizeof(WCHAR));
1225 r = MSI_RecordGetStringW(rec, i, val, &sz);
1228 if (r != ERROR_SUCCESS)
1230 ERR("failed to get string!\n");
1238 static LPWSTR create_diff_row_query(MSIDATABASE *merge, MSIQUERY *view,
1239 LPWSTR table, MSIRECORD *rec)
1241 LPWSTR query = NULL, clause = NULL;
1242 LPWSTR ptr = NULL, val;
1244 DWORD size = 1, oldsize;
1249 static const WCHAR keyset[] = {
1250 '`','%','s','`',' ','=',' ','%','s',' ','A','N','D',' ',0};
1251 static const WCHAR lastkeyset[] = {
1252 '`','%','s','`',' ','=',' ','%','s',' ',0};
1253 static const WCHAR fmt[] = {'S','E','L','E','C','T',' ','*',' ',
1254 'F','R','O','M',' ','`','%','s','`',' ',
1255 'W','H','E','R','E',' ','%','s',0};
1257 r = MSI_DatabaseGetPrimaryKeys(merge, table, &keys);
1258 if (r != ERROR_SUCCESS)
1261 clause = msi_alloc_zero(size * sizeof(WCHAR));
1266 count = MSI_RecordGetFieldCount(keys);
1267 for (i = 1; i <= count; i++)
1269 key = MSI_RecordGetString(keys, i);
1270 val = get_key_value(view, key, rec);
1273 setptr = lastkeyset;
1278 size += lstrlenW(setptr) + lstrlenW(key) + lstrlenW(val) - 4;
1279 clause = msi_realloc(clause, size * sizeof (WCHAR));
1286 ptr = clause + oldsize - 1;
1287 sprintfW(ptr, setptr, key, val);
1291 size = lstrlenW(fmt) + lstrlenW(table) + lstrlenW(clause) + 1;
1292 query = msi_alloc(size * sizeof(WCHAR));
1296 sprintfW(query, fmt, table, clause);
1300 msiobj_release(&keys->hdr);
1304 static UINT merge_diff_row(MSIRECORD *rec, LPVOID param)
1306 MERGEDATA *data = param;
1307 MERGETABLE *table = data->curtable;
1309 MSIQUERY *dbview = NULL;
1310 MSIRECORD *row = NULL;
1311 LPWSTR query = NULL;
1312 UINT r = ERROR_SUCCESS;
1314 if (TABLE_Exists(data->db, table->name))
1316 query = create_diff_row_query(data->merge, data->curview, table->name, rec);
1318 return ERROR_OUTOFMEMORY;
1320 r = MSI_DatabaseOpenViewW(data->db, query, &dbview);
1321 if (r != ERROR_SUCCESS)
1324 r = MSI_ViewExecute(dbview, NULL);
1325 if (r != ERROR_SUCCESS)
1328 r = MSI_ViewFetch(dbview, &row);
1329 if (r == ERROR_SUCCESS && !MSI_RecordsAreEqual(rec, row))
1331 table->numconflicts++;
1334 else if (r != ERROR_NO_MORE_ITEMS)
1338 mergerow = msi_alloc(sizeof(MERGEROW));
1341 r = ERROR_OUTOFMEMORY;
1345 mergerow->data = MSI_CloneRecord(rec);
1346 if (!mergerow->data)
1348 r = ERROR_OUTOFMEMORY;
1353 list_add_tail(&table->rows, &mergerow->entry);
1357 msiobj_release(&row->hdr);
1358 msiobj_release(&dbview->hdr);
1362 static UINT msi_get_table_labels(MSIDATABASE *db, LPCWSTR table, LPWSTR **labels, DWORD *numlabels)
1365 MSIRECORD *prec = NULL;
1367 r = MSI_DatabaseGetPrimaryKeys(db, table, &prec);
1368 if (r != ERROR_SUCCESS)
1371 count = MSI_RecordGetFieldCount(prec);
1372 *numlabels = count + 1;
1373 *labels = msi_alloc((*numlabels)*sizeof(LPWSTR));
1376 r = ERROR_OUTOFMEMORY;
1380 (*labels)[0] = strdupW(table);
1381 for (i=1; i<=count; i++ )
1383 (*labels)[i] = strdupW(MSI_RecordGetString(prec, i));
1387 msiobj_release( &prec->hdr );
1391 static UINT msi_get_query_columns(MSIQUERY *query, LPWSTR **columns, DWORD *numcolumns)
1394 MSIRECORD *prec = NULL;
1396 r = MSI_ViewGetColumnInfo(query, MSICOLINFO_NAMES, &prec);
1397 if (r != ERROR_SUCCESS)
1400 count = MSI_RecordGetFieldCount(prec);
1401 *columns = msi_alloc(count*sizeof(LPWSTR));
1404 r = ERROR_OUTOFMEMORY;
1408 for (i=1; i<=count; i++ )
1410 (*columns)[i-1] = strdupW(MSI_RecordGetString(prec, i));
1413 *numcolumns = count;
1416 msiobj_release( &prec->hdr );
1420 static UINT msi_get_query_types(MSIQUERY *query, LPWSTR **types, DWORD *numtypes)
1423 MSIRECORD *prec = NULL;
1425 r = MSI_ViewGetColumnInfo(query, MSICOLINFO_TYPES, &prec);
1426 if (r != ERROR_SUCCESS)
1429 count = MSI_RecordGetFieldCount(prec);
1430 *types = msi_alloc(count*sizeof(LPWSTR));
1433 r = ERROR_OUTOFMEMORY;
1437 for (i=1; i<=count; i++ )
1439 (*types)[i-1] = strdupW(MSI_RecordGetString(prec, i));
1443 msiobj_release( &prec->hdr );
1447 static void merge_free_rows(MERGETABLE *table)
1449 struct list *item, *cursor;
1451 LIST_FOR_EACH_SAFE(item, cursor, &table->rows)
1453 MERGEROW *row = LIST_ENTRY(item, MERGEROW, entry);
1455 list_remove(&row->entry);
1456 msiobj_release(&row->data->hdr);
1461 static void free_merge_table(MERGETABLE *table)
1465 if (table->labels != NULL)
1467 for (i = 0; i < table->numlabels; i++)
1468 msi_free(table->labels[i]);
1469 msi_free(table->labels);
1472 if (table->columns != NULL)
1474 for (i = 0; i < table->numcolumns; i++)
1475 msi_free(table->columns[i]);
1476 msi_free(table->columns);
1479 if (table->types != NULL)
1481 for (i = 0; i < table->numtypes; i++)
1482 msi_free(table->types[i]);
1483 msi_free(table->types);
1485 msi_free(table->name);
1486 merge_free_rows(table);
1491 static UINT msi_get_merge_table (MSIDATABASE *db, LPCWSTR name, MERGETABLE **ptable)
1495 MSIQUERY *mergeview = NULL;
1497 static const WCHAR query[] = {'S','E','L','E','C','T',' ','*',' ',
1498 'F','R','O','M',' ','`','%','s','`',0};
1500 table = msi_alloc_zero(sizeof(MERGETABLE));
1504 return ERROR_OUTOFMEMORY;
1507 r = msi_get_table_labels(db, name, &table->labels, &table->numlabels);
1508 if (r != ERROR_SUCCESS)
1511 r = MSI_OpenQuery(db, &mergeview, query, name);
1512 if (r != ERROR_SUCCESS)
1515 r = msi_get_query_columns(mergeview, &table->columns, &table->numcolumns);
1516 if (r != ERROR_SUCCESS)
1519 r = msi_get_query_types(mergeview, &table->types, &table->numtypes);
1520 if (r != ERROR_SUCCESS)
1523 list_init(&table->rows);
1525 table->name = strdupW(name);
1526 table->numconflicts = 0;
1528 msiobj_release(&mergeview->hdr);
1530 return ERROR_SUCCESS;
1533 msiobj_release(&mergeview->hdr);
1534 free_merge_table(table);
1539 static UINT merge_diff_tables(MSIRECORD *rec, LPVOID param)
1541 MERGEDATA *data = param;
1543 MSIQUERY *dbview = NULL;
1544 MSIQUERY *mergeview = NULL;
1548 static const WCHAR query[] = {'S','E','L','E','C','T',' ','*',' ',
1549 'F','R','O','M',' ','`','%','s','`',0};
1551 name = MSI_RecordGetString(rec, 1);
1553 r = MSI_OpenQuery(data->merge, &mergeview, query, name);
1554 if (r != ERROR_SUCCESS)
1557 if (TABLE_Exists(data->db, name))
1559 r = MSI_OpenQuery(data->db, &dbview, query, name);
1560 if (r != ERROR_SUCCESS)
1563 r = merge_verify_colnames(dbview, mergeview);
1564 if (r != ERROR_SUCCESS)
1567 r = merge_verify_primary_keys(data->db, data->merge, name);
1568 if (r != ERROR_SUCCESS)
1572 r = msi_get_merge_table(data->merge, name, &table);
1573 if (r != ERROR_SUCCESS)
1576 data->curtable = table;
1577 data->curview = mergeview;
1578 r = MSI_IterateRecords(mergeview, NULL, merge_diff_row, data);
1579 if (r != ERROR_SUCCESS)
1581 free_merge_table(table);
1585 list_add_tail(data->tabledata, &table->entry);
1588 msiobj_release(&dbview->hdr);
1589 msiobj_release(&mergeview->hdr);
1593 static UINT gather_merge_data(MSIDATABASE *db, MSIDATABASE *merge,
1594 struct list *tabledata)
1600 static const WCHAR query[] = {'S','E','L','E','C','T',' ','*',' ',
1601 'F','R','O','M',' ','`','_','T','a','b','l','e','s','`',0};
1603 r = MSI_DatabaseOpenViewW(merge, query, &view);
1604 if (r != ERROR_SUCCESS)
1609 data.tabledata = tabledata;
1610 r = MSI_IterateRecords(view, NULL, merge_diff_tables, &data);
1612 msiobj_release(&view->hdr);
1616 static UINT merge_table(MSIDATABASE *db, MERGETABLE *table)
1622 if (!TABLE_Exists(db, table->name))
1624 r = msi_add_table_to_db(db, table->columns, table->types,
1625 table->labels, table->numlabels, table->numcolumns);
1626 if (r != ERROR_SUCCESS)
1627 return ERROR_FUNCTION_FAILED;
1630 LIST_FOR_EACH_ENTRY(row, &table->rows, MERGEROW, entry)
1632 r = TABLE_CreateView(db, table->name, &tv);
1633 if (r != ERROR_SUCCESS)
1636 r = tv->ops->insert_row(tv, row->data, -1, FALSE);
1637 tv->ops->delete(tv);
1639 if (r != ERROR_SUCCESS)
1643 return ERROR_SUCCESS;
1646 static UINT update_merge_errors(MSIDATABASE *db, LPCWSTR error,
1647 LPWSTR table, DWORD numconflicts)
1652 static const WCHAR create[] = {
1653 'C','R','E','A','T','E',' ','T','A','B','L','E',' ',
1654 '`','%','s','`',' ','(','`','T','a','b','l','e','`',' ',
1655 'C','H','A','R','(','2','5','5',')',' ','N','O','T',' ',
1656 'N','U','L','L',',',' ','`','N','u','m','R','o','w','M','e','r','g','e',
1657 'C','o','n','f','l','i','c','t','s','`',' ','S','H','O','R','T',' ',
1658 'N','O','T',' ','N','U','L','L',' ','P','R','I','M','A','R','Y',' ',
1659 'K','E','Y',' ','`','T','a','b','l','e','`',')',0};
1660 static const WCHAR insert[] = {
1661 'I','N','S','E','R','T',' ','I','N','T','O',' ',
1662 '`','%','s','`',' ','(','`','T','a','b','l','e','`',',',' ',
1663 '`','N','u','m','R','o','w','M','e','r','g','e',
1664 'C','o','n','f','l','i','c','t','s','`',')',' ','V','A','L','U','E','S',
1665 ' ','(','\'','%','s','\'',',',' ','%','d',')',0};
1667 if (!TABLE_Exists(db, error))
1669 r = MSI_OpenQuery(db, &view, create, error);
1670 if (r != ERROR_SUCCESS)
1673 r = MSI_ViewExecute(view, NULL);
1674 msiobj_release(&view->hdr);
1675 if (r != ERROR_SUCCESS)
1679 r = MSI_OpenQuery(db, &view, insert, error, table, numconflicts);
1680 if (r != ERROR_SUCCESS)
1683 r = MSI_ViewExecute(view, NULL);
1684 msiobj_release(&view->hdr);
1688 UINT WINAPI MsiDatabaseMergeW(MSIHANDLE hDatabase, MSIHANDLE hDatabaseMerge,
1689 LPCWSTR szTableName)
1691 struct list tabledata = LIST_INIT(tabledata);
1692 struct list *item, *cursor;
1693 MSIDATABASE *db, *merge;
1698 TRACE("(%d, %d, %s)\n", hDatabase, hDatabaseMerge,
1699 debugstr_w(szTableName));
1701 if (szTableName && !*szTableName)
1702 return ERROR_INVALID_TABLE;
1704 db = msihandle2msiinfo(hDatabase, MSIHANDLETYPE_DATABASE);
1705 merge = msihandle2msiinfo(hDatabaseMerge, MSIHANDLETYPE_DATABASE);
1708 r = ERROR_INVALID_HANDLE;
1712 r = gather_merge_data(db, merge, &tabledata);
1713 if (r != ERROR_SUCCESS)
1717 LIST_FOR_EACH_ENTRY(table, &tabledata, MERGETABLE, entry)
1719 if (table->numconflicts)
1723 r = update_merge_errors(db, szTableName, table->name,
1724 table->numconflicts);
1725 if (r != ERROR_SUCCESS)
1730 r = merge_table(db, table);
1731 if (r != ERROR_SUCCESS)
1736 LIST_FOR_EACH_SAFE(item, cursor, &tabledata)
1738 MERGETABLE *table = LIST_ENTRY(item, MERGETABLE, entry);
1740 list_remove(&table->entry);
1741 free_merge_table(table);
1745 r = ERROR_FUNCTION_FAILED;
1748 msiobj_release(&db->hdr);
1749 msiobj_release(&merge->hdr);
1753 MSIDBSTATE WINAPI MsiGetDatabaseState( MSIHANDLE handle )
1755 MSIDBSTATE ret = MSIDBSTATE_READ;
1758 TRACE("%d\n", handle);
1760 db = msihandle2msiinfo( handle, MSIHANDLETYPE_DATABASE );
1763 IWineMsiRemoteDatabase *remote_database;
1765 remote_database = (IWineMsiRemoteDatabase *)msi_get_remote( handle );
1766 if ( !remote_database )
1767 return MSIDBSTATE_ERROR;
1769 IWineMsiRemoteDatabase_Release( remote_database );
1770 WARN("MsiGetDatabaseState not allowed during a custom action!\n");
1772 return MSIDBSTATE_READ;
1775 if (db->mode != MSIDBOPEN_READONLY )
1776 ret = MSIDBSTATE_WRITE;
1777 msiobj_release( &db->hdr );
1782 typedef struct _msi_remote_database_impl {
1783 const IWineMsiRemoteDatabaseVtbl *lpVtbl;
1786 } msi_remote_database_impl;
1788 static inline msi_remote_database_impl* mrd_from_IWineMsiRemoteDatabase( IWineMsiRemoteDatabase* iface )
1790 return (msi_remote_database_impl *)iface;
1793 static HRESULT WINAPI mrd_QueryInterface( IWineMsiRemoteDatabase *iface,
1794 REFIID riid,LPVOID *ppobj)
1796 if( IsEqualCLSID( riid, &IID_IUnknown ) ||
1797 IsEqualCLSID( riid, &IID_IWineMsiRemoteDatabase ) )
1799 IUnknown_AddRef( iface );
1804 return E_NOINTERFACE;
1807 static ULONG WINAPI mrd_AddRef( IWineMsiRemoteDatabase *iface )
1809 msi_remote_database_impl* This = mrd_from_IWineMsiRemoteDatabase( iface );
1811 return InterlockedIncrement( &This->refs );
1814 static ULONG WINAPI mrd_Release( IWineMsiRemoteDatabase *iface )
1816 msi_remote_database_impl* This = mrd_from_IWineMsiRemoteDatabase( iface );
1819 r = InterlockedDecrement( &This->refs );
1822 MsiCloseHandle( This->database );
1828 static HRESULT WINAPI mrd_IsTablePersistent( IWineMsiRemoteDatabase *iface,
1829 BSTR table, MSICONDITION *persistent )
1831 msi_remote_database_impl *This = mrd_from_IWineMsiRemoteDatabase( iface );
1832 *persistent = MsiDatabaseIsTablePersistentW(This->database, table);
1836 static HRESULT WINAPI mrd_GetPrimaryKeys( IWineMsiRemoteDatabase *iface,
1837 BSTR table, MSIHANDLE *keys )
1839 msi_remote_database_impl *This = mrd_from_IWineMsiRemoteDatabase( iface );
1840 UINT r = MsiDatabaseGetPrimaryKeysW(This->database, table, keys);
1841 return HRESULT_FROM_WIN32(r);
1844 static HRESULT WINAPI mrd_GetSummaryInformation( IWineMsiRemoteDatabase *iface,
1845 UINT updatecount, MSIHANDLE *suminfo )
1847 msi_remote_database_impl *This = mrd_from_IWineMsiRemoteDatabase( iface );
1848 UINT r = MsiGetSummaryInformationW(This->database, NULL, updatecount, suminfo);
1849 return HRESULT_FROM_WIN32(r);
1852 static HRESULT WINAPI mrd_OpenView( IWineMsiRemoteDatabase *iface,
1853 BSTR query, MSIHANDLE *view )
1855 msi_remote_database_impl *This = mrd_from_IWineMsiRemoteDatabase( iface );
1856 UINT r = MsiDatabaseOpenViewW(This->database, query, view);
1857 return HRESULT_FROM_WIN32(r);
1860 static HRESULT WINAPI mrd_SetMsiHandle( IWineMsiRemoteDatabase *iface, MSIHANDLE handle )
1862 msi_remote_database_impl* This = mrd_from_IWineMsiRemoteDatabase( iface );
1863 This->database = handle;
1867 static const IWineMsiRemoteDatabaseVtbl msi_remote_database_vtbl =
1872 mrd_IsTablePersistent,
1874 mrd_GetSummaryInformation,
1879 HRESULT create_msi_remote_database( IUnknown *pOuter, LPVOID *ppObj )
1881 msi_remote_database_impl *This;
1883 This = msi_alloc( sizeof *This );
1885 return E_OUTOFMEMORY;
1887 This->lpVtbl = &msi_remote_database_vtbl;