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 if (r != ERROR_SUCCESS)
629 for (i = 0; i < num_records; i++)
631 r = construct_record(num_columns, types, records[i], path, &rec);
632 if (r != ERROR_SUCCESS)
635 r = MSI_ViewModify(view, MSIMODIFY_INSERT, rec);
636 if (r != ERROR_SUCCESS)
638 msiobj_release(&rec->hdr);
642 msiobj_release(&rec->hdr);
646 msiobj_release(&view->hdr);
650 static UINT MSI_DatabaseImport(MSIDATABASE *db, LPCWSTR folder, LPCWSTR file)
654 DWORD num_labels, num_types;
655 DWORD num_columns, num_records = 0;
656 LPWSTR *columns, *types, *labels;
657 LPWSTR path, ptr, data;
658 LPWSTR **records = NULL;
659 LPWSTR **temp_records;
661 static const WCHAR suminfo[] =
662 {'_','S','u','m','m','a','r','y','I','n','f','o','r','m','a','t','i','o','n',0};
664 TRACE("%p %s %s\n", db, debugstr_w(folder), debugstr_w(file) );
666 if( folder == NULL || file == NULL )
667 return ERROR_INVALID_PARAMETER;
669 len = lstrlenW(folder) + lstrlenW(szBackSlash) + lstrlenW(file) + 1;
670 path = msi_alloc( len * sizeof(WCHAR) );
672 return ERROR_OUTOFMEMORY;
674 lstrcpyW( path, folder );
675 lstrcatW( path, szBackSlash );
676 lstrcatW( path, file );
678 data = msi_read_text_archive( path );
681 msi_parse_line( &ptr, &columns, &num_columns );
682 msi_parse_line( &ptr, &types, &num_types );
683 msi_parse_line( &ptr, &labels, &num_labels );
685 if (num_columns != num_types)
687 r = ERROR_FUNCTION_FAILED;
691 records = msi_alloc(sizeof(LPWSTR *));
694 r = ERROR_OUTOFMEMORY;
698 /* read in the table records */
701 msi_parse_line( &ptr, &records[num_records], NULL );
704 temp_records = msi_realloc(records, (num_records + 1) * sizeof(LPWSTR *));
707 r = ERROR_OUTOFMEMORY;
710 records = temp_records;
713 if (!strcmpW(labels[0], suminfo))
715 r = msi_add_suminfo( db, records, num_records, num_columns );
716 if (r != ERROR_SUCCESS)
718 r = ERROR_FUNCTION_FAILED;
724 if (!TABLE_Exists(db, labels[0]))
726 r = msi_add_table_to_db( db, columns, types, labels, num_labels, num_columns );
727 if (r != ERROR_SUCCESS)
729 r = ERROR_FUNCTION_FAILED;
734 r = msi_add_records_to_table( db, columns, types, labels, records, num_columns, num_records, path );
744 for (i = 0; i < num_records; i++)
745 msi_free(records[i]);
752 UINT WINAPI MsiDatabaseImportW(MSIHANDLE handle, LPCWSTR szFolder, LPCWSTR szFilename)
757 TRACE("%x %s %s\n",handle,debugstr_w(szFolder), debugstr_w(szFilename));
759 db = msihandle2msiinfo( handle, MSIHANDLETYPE_DATABASE );
762 IWineMsiRemoteDatabase *remote_database;
764 remote_database = (IWineMsiRemoteDatabase *)msi_get_remote( handle );
765 if ( !remote_database )
766 return ERROR_INVALID_HANDLE;
768 IWineMsiRemoteDatabase_Release( remote_database );
769 WARN("MsiDatabaseImport not allowed during a custom action!\n");
771 return ERROR_SUCCESS;
774 r = MSI_DatabaseImport( db, szFolder, szFilename );
775 msiobj_release( &db->hdr );
779 UINT WINAPI MsiDatabaseImportA( MSIHANDLE handle,
780 LPCSTR szFolder, LPCSTR szFilename )
782 LPWSTR path = NULL, file = NULL;
783 UINT r = ERROR_OUTOFMEMORY;
785 TRACE("%x %s %s\n", handle, debugstr_a(szFolder), debugstr_a(szFilename));
789 path = strdupAtoW( szFolder );
796 file = strdupAtoW( szFilename );
801 r = MsiDatabaseImportW( handle, path, file );
810 static UINT msi_export_record( HANDLE handle, MSIRECORD *row, UINT start )
812 UINT i, count, len, r = ERROR_SUCCESS;
818 buffer = msi_alloc( len );
820 return ERROR_OUTOFMEMORY;
822 count = MSI_RecordGetFieldCount( row );
823 for ( i=start; i<=count; i++ )
826 r = MSI_RecordGetStringA( row, i, buffer, &sz );
827 if (r == ERROR_MORE_DATA)
829 char *p = msi_realloc( buffer, sz + 1 );
836 r = MSI_RecordGetStringA( row, i, buffer, &sz );
837 if (r != ERROR_SUCCESS)
840 if (!WriteFile( handle, buffer, sz, &sz, NULL ))
842 r = ERROR_FUNCTION_FAILED;
846 sep = (i < count) ? "\t" : "\r\n";
847 if (!WriteFile( handle, sep, strlen(sep), &sz, NULL ))
849 r = ERROR_FUNCTION_FAILED;
857 static UINT msi_export_row( MSIRECORD *row, void *arg )
859 return msi_export_record( arg, row, 1 );
862 static UINT msi_export_forcecodepage( HANDLE handle )
866 static const char data[] = "\r\n\r\n0\t_ForceCodepage\r\n";
868 FIXME("Read the codepage from the strings table!\n");
870 sz = lstrlenA(data) + 1;
871 if (!WriteFile(handle, data, sz, &sz, NULL))
872 return ERROR_FUNCTION_FAILED;
874 return ERROR_SUCCESS;
877 static UINT MSI_DatabaseExport( MSIDATABASE *db, LPCWSTR table,
878 LPCWSTR folder, LPCWSTR file )
880 static const WCHAR query[] = {
881 's','e','l','e','c','t',' ','*',' ','f','r','o','m',' ','%','s',0 };
882 static const WCHAR forcecodepage[] = {
883 '_','F','o','r','c','e','C','o','d','e','p','a','g','e',0 };
884 MSIRECORD *rec = NULL;
885 MSIQUERY *view = NULL;
890 TRACE("%p %s %s %s\n", db, debugstr_w(table),
891 debugstr_w(folder), debugstr_w(file) );
893 if( folder == NULL || file == NULL )
894 return ERROR_INVALID_PARAMETER;
896 len = lstrlenW(folder) + lstrlenW(file) + 2;
897 filename = msi_alloc(len * sizeof (WCHAR));
899 return ERROR_OUTOFMEMORY;
901 lstrcpyW( filename, folder );
902 lstrcatW( filename, szBackSlash );
903 lstrcatW( filename, file );
905 handle = CreateFileW( filename, GENERIC_READ | GENERIC_WRITE, 0,
906 NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );
907 msi_free( filename );
908 if (handle == INVALID_HANDLE_VALUE)
909 return ERROR_FUNCTION_FAILED;
911 if (!lstrcmpW( table, forcecodepage ))
913 r = msi_export_forcecodepage( handle );
917 r = MSI_OpenQuery( db, &view, query, table );
918 if (r == ERROR_SUCCESS)
920 /* write out row 1, the column names */
921 r = MSI_ViewGetColumnInfo(view, MSICOLINFO_NAMES, &rec);
922 if (r == ERROR_SUCCESS)
924 msi_export_record( handle, rec, 1 );
925 msiobj_release( &rec->hdr );
928 /* write out row 2, the column types */
929 r = MSI_ViewGetColumnInfo(view, MSICOLINFO_TYPES, &rec);
930 if (r == ERROR_SUCCESS)
932 msi_export_record( handle, rec, 1 );
933 msiobj_release( &rec->hdr );
936 /* write out row 3, the table name + keys */
937 r = MSI_DatabaseGetPrimaryKeys( db, table, &rec );
938 if (r == ERROR_SUCCESS)
940 MSI_RecordSetStringW( rec, 0, table );
941 msi_export_record( handle, rec, 0 );
942 msiobj_release( &rec->hdr );
945 /* write out row 4 onwards, the data */
946 r = MSI_IterateRecords( view, 0, msi_export_row, handle );
947 msiobj_release( &view->hdr );
951 CloseHandle( handle );
955 /***********************************************************************
956 * MsiExportDatabaseW [MSI.@]
958 * Writes a file containing the table data as tab separated ASCII.
960 * The format is as follows:
962 * row1 : colname1 <tab> colname2 <tab> .... colnameN <cr> <lf>
963 * row2 : coltype1 <tab> coltype2 <tab> .... coltypeN <cr> <lf>
964 * row3 : tablename <tab> key1 <tab> key2 <tab> ... keyM <cr> <lf>
966 * Followed by the data, starting at row 1 with one row per line
968 * row4 : data <tab> data <tab> data <tab> ... data <cr> <lf>
970 UINT WINAPI MsiDatabaseExportW( MSIHANDLE handle, LPCWSTR szTable,
971 LPCWSTR szFolder, LPCWSTR szFilename )
976 TRACE("%x %s %s %s\n", handle, debugstr_w(szTable),
977 debugstr_w(szFolder), debugstr_w(szFilename));
979 db = msihandle2msiinfo( handle, MSIHANDLETYPE_DATABASE );
982 IWineMsiRemoteDatabase *remote_database;
984 remote_database = (IWineMsiRemoteDatabase *)msi_get_remote( handle );
985 if ( !remote_database )
986 return ERROR_INVALID_HANDLE;
988 IWineMsiRemoteDatabase_Release( remote_database );
989 WARN("MsiDatabaseExport not allowed during a custom action!\n");
991 return ERROR_SUCCESS;
994 r = MSI_DatabaseExport( db, szTable, szFolder, szFilename );
995 msiobj_release( &db->hdr );
999 UINT WINAPI MsiDatabaseExportA( MSIHANDLE handle, LPCSTR szTable,
1000 LPCSTR szFolder, LPCSTR szFilename )
1002 LPWSTR path = NULL, file = NULL, table = NULL;
1003 UINT r = ERROR_OUTOFMEMORY;
1005 TRACE("%x %s %s %s\n", handle, debugstr_a(szTable),
1006 debugstr_a(szFolder), debugstr_a(szFilename));
1010 table = strdupAtoW( szTable );
1017 path = strdupAtoW( szFolder );
1024 file = strdupAtoW( szFilename );
1029 r = MsiDatabaseExportW( handle, table, path, file );
1039 UINT WINAPI MsiDatabaseMergeA(MSIHANDLE hDatabase, MSIHANDLE hDatabaseMerge,
1045 TRACE("(%d, %d, %s)\n", hDatabase, hDatabaseMerge,
1046 debugstr_a(szTableName));
1048 table = strdupAtoW(szTableName);
1049 r = MsiDatabaseMergeW(hDatabase, hDatabaseMerge, table);
1055 typedef struct _tagMERGETABLE
1069 typedef struct _tagMERGEROW
1075 typedef struct _tagMERGEDATA
1079 MERGETABLE *curtable;
1081 struct list *tabledata;
1084 static BOOL merge_type_match(LPCWSTR type1, LPCWSTR type2)
1086 if (((type1[0] == 'l') || (type1[0] == 's')) &&
1087 ((type2[0] == 'l') || (type2[0] == 's')))
1090 if (((type1[0] == 'L') || (type1[0] == 'S')) &&
1091 ((type2[0] == 'L') || (type2[0] == 'S')))
1094 return !lstrcmpW(type1, type2);
1097 static UINT merge_verify_colnames(MSIQUERY *dbview, MSIQUERY *mergeview)
1099 MSIRECORD *dbrec, *mergerec;
1102 r = MSI_ViewGetColumnInfo(dbview, MSICOLINFO_NAMES, &dbrec);
1103 if (r != ERROR_SUCCESS)
1106 r = MSI_ViewGetColumnInfo(mergeview, MSICOLINFO_NAMES, &mergerec);
1107 if (r != ERROR_SUCCESS)
1110 count = MSI_RecordGetFieldCount(dbrec);
1111 for (i = 1; i <= count; i++)
1113 if (!MSI_RecordGetString(mergerec, i))
1116 if (lstrcmpW(MSI_RecordGetString(dbrec, i),
1117 MSI_RecordGetString(mergerec, i)))
1119 r = ERROR_DATATYPE_MISMATCH;
1124 msiobj_release(&dbrec->hdr);
1125 msiobj_release(&mergerec->hdr);
1126 dbrec = mergerec = NULL;
1128 r = MSI_ViewGetColumnInfo(dbview, MSICOLINFO_TYPES, &dbrec);
1129 if (r != ERROR_SUCCESS)
1132 r = MSI_ViewGetColumnInfo(mergeview, MSICOLINFO_TYPES, &mergerec);
1133 if (r != ERROR_SUCCESS)
1136 count = MSI_RecordGetFieldCount(dbrec);
1137 for (i = 1; i <= count; i++)
1139 if (!MSI_RecordGetString(mergerec, i))
1142 if (!merge_type_match(MSI_RecordGetString(dbrec, i),
1143 MSI_RecordGetString(mergerec, i)))
1145 r = ERROR_DATATYPE_MISMATCH;
1151 msiobj_release(&dbrec->hdr);
1152 msiobj_release(&mergerec->hdr);
1157 static UINT merge_verify_primary_keys(MSIDATABASE *db, MSIDATABASE *mergedb,
1160 MSIRECORD *dbrec, *mergerec = NULL;
1163 r = MSI_DatabaseGetPrimaryKeys(db, table, &dbrec);
1164 if (r != ERROR_SUCCESS)
1167 r = MSI_DatabaseGetPrimaryKeys(mergedb, table, &mergerec);
1168 if (r != ERROR_SUCCESS)
1171 count = MSI_RecordGetFieldCount(dbrec);
1172 if (count != MSI_RecordGetFieldCount(mergerec))
1174 r = ERROR_DATATYPE_MISMATCH;
1178 for (i = 1; i <= count; i++)
1180 if (lstrcmpW(MSI_RecordGetString(dbrec, i),
1181 MSI_RecordGetString(mergerec, i)))
1183 r = ERROR_DATATYPE_MISMATCH;
1189 msiobj_release(&dbrec->hdr);
1190 msiobj_release(&mergerec->hdr);
1195 static LPWSTR get_key_value(MSIQUERY *view, LPCWSTR key, MSIRECORD *rec)
1197 MSIRECORD *colnames;
1199 UINT r, i = 0, sz = 0;
1202 r = MSI_ViewGetColumnInfo(view, MSICOLINFO_NAMES, &colnames);
1203 if (r != ERROR_SUCCESS)
1208 str = msi_dup_record_field(colnames, ++i);
1209 cmp = lstrcmpW(key, str);
1213 msiobj_release(&colnames->hdr);
1215 r = MSI_RecordGetStringW(rec, i, NULL, &sz);
1216 if (r != ERROR_SUCCESS)
1220 if (MSI_RecordGetString(rec, i)) /* check record field is a string */
1222 /* quote string record fields */
1223 const WCHAR szQuote[] = {'\'', 0};
1225 val = msi_alloc(sz*sizeof(WCHAR));
1229 lstrcpyW(val, szQuote);
1230 r = MSI_RecordGetStringW(rec, i, val+1, &sz);
1231 lstrcpyW(val+1+sz, szQuote);
1235 /* do not quote integer record fields */
1236 val = msi_alloc(sz*sizeof(WCHAR));
1240 r = MSI_RecordGetStringW(rec, i, val, &sz);
1243 if (r != ERROR_SUCCESS)
1245 ERR("failed to get string!\n");
1253 static LPWSTR create_diff_row_query(MSIDATABASE *merge, MSIQUERY *view,
1254 LPWSTR table, MSIRECORD *rec)
1256 LPWSTR query = NULL, clause = NULL;
1257 LPWSTR ptr = NULL, val;
1259 DWORD size = 1, oldsize;
1264 static const WCHAR keyset[] = {
1265 '`','%','s','`',' ','=',' ','%','s',' ','A','N','D',' ',0};
1266 static const WCHAR lastkeyset[] = {
1267 '`','%','s','`',' ','=',' ','%','s',' ',0};
1268 static const WCHAR fmt[] = {'S','E','L','E','C','T',' ','*',' ',
1269 'F','R','O','M',' ','`','%','s','`',' ',
1270 'W','H','E','R','E',' ','%','s',0};
1272 r = MSI_DatabaseGetPrimaryKeys(merge, table, &keys);
1273 if (r != ERROR_SUCCESS)
1276 clause = msi_alloc_zero(size * sizeof(WCHAR));
1281 count = MSI_RecordGetFieldCount(keys);
1282 for (i = 1; i <= count; i++)
1284 key = MSI_RecordGetString(keys, i);
1285 val = get_key_value(view, key, rec);
1288 setptr = lastkeyset;
1293 size += lstrlenW(setptr) + lstrlenW(key) + lstrlenW(val) - 4;
1294 clause = msi_realloc(clause, size * sizeof (WCHAR));
1301 ptr = clause + oldsize - 1;
1302 sprintfW(ptr, setptr, key, val);
1306 size = lstrlenW(fmt) + lstrlenW(table) + lstrlenW(clause) + 1;
1307 query = msi_alloc(size * sizeof(WCHAR));
1311 sprintfW(query, fmt, table, clause);
1315 msiobj_release(&keys->hdr);
1319 static UINT merge_diff_row(MSIRECORD *rec, LPVOID param)
1321 MERGEDATA *data = param;
1322 MERGETABLE *table = data->curtable;
1324 MSIQUERY *dbview = NULL;
1325 MSIRECORD *row = NULL;
1326 LPWSTR query = NULL;
1327 UINT r = ERROR_SUCCESS;
1329 if (TABLE_Exists(data->db, table->name))
1331 query = create_diff_row_query(data->merge, data->curview, table->name, rec);
1333 return ERROR_OUTOFMEMORY;
1335 r = MSI_DatabaseOpenViewW(data->db, query, &dbview);
1336 if (r != ERROR_SUCCESS)
1339 r = MSI_ViewExecute(dbview, NULL);
1340 if (r != ERROR_SUCCESS)
1343 r = MSI_ViewFetch(dbview, &row);
1344 if (r == ERROR_SUCCESS && !MSI_RecordsAreEqual(rec, row))
1346 table->numconflicts++;
1349 else if (r != ERROR_NO_MORE_ITEMS)
1355 mergerow = msi_alloc(sizeof(MERGEROW));
1358 r = ERROR_OUTOFMEMORY;
1362 mergerow->data = MSI_CloneRecord(rec);
1363 if (!mergerow->data)
1365 r = ERROR_OUTOFMEMORY;
1370 list_add_tail(&table->rows, &mergerow->entry);
1374 msiobj_release(&row->hdr);
1375 msiobj_release(&dbview->hdr);
1379 static UINT msi_get_table_labels(MSIDATABASE *db, LPCWSTR table, LPWSTR **labels, DWORD *numlabels)
1382 MSIRECORD *prec = NULL;
1384 r = MSI_DatabaseGetPrimaryKeys(db, table, &prec);
1385 if (r != ERROR_SUCCESS)
1388 count = MSI_RecordGetFieldCount(prec);
1389 *numlabels = count + 1;
1390 *labels = msi_alloc((*numlabels)*sizeof(LPWSTR));
1393 r = ERROR_OUTOFMEMORY;
1397 (*labels)[0] = strdupW(table);
1398 for (i=1; i<=count; i++ )
1400 (*labels)[i] = strdupW(MSI_RecordGetString(prec, i));
1404 msiobj_release( &prec->hdr );
1408 static UINT msi_get_query_columns(MSIQUERY *query, LPWSTR **columns, DWORD *numcolumns)
1411 MSIRECORD *prec = NULL;
1413 r = MSI_ViewGetColumnInfo(query, MSICOLINFO_NAMES, &prec);
1414 if (r != ERROR_SUCCESS)
1417 count = MSI_RecordGetFieldCount(prec);
1418 *columns = msi_alloc(count*sizeof(LPWSTR));
1421 r = ERROR_OUTOFMEMORY;
1425 for (i=1; i<=count; i++ )
1427 (*columns)[i-1] = strdupW(MSI_RecordGetString(prec, i));
1430 *numcolumns = count;
1433 msiobj_release( &prec->hdr );
1437 static UINT msi_get_query_types(MSIQUERY *query, LPWSTR **types, DWORD *numtypes)
1440 MSIRECORD *prec = NULL;
1442 r = MSI_ViewGetColumnInfo(query, MSICOLINFO_TYPES, &prec);
1443 if (r != ERROR_SUCCESS)
1446 count = MSI_RecordGetFieldCount(prec);
1447 *types = msi_alloc(count*sizeof(LPWSTR));
1450 r = ERROR_OUTOFMEMORY;
1454 for (i=1; i<=count; i++ )
1456 (*types)[i-1] = strdupW(MSI_RecordGetString(prec, i));
1460 msiobj_release( &prec->hdr );
1464 static void merge_free_rows(MERGETABLE *table)
1466 struct list *item, *cursor;
1468 LIST_FOR_EACH_SAFE(item, cursor, &table->rows)
1470 MERGEROW *row = LIST_ENTRY(item, MERGEROW, entry);
1472 list_remove(&row->entry);
1473 msiobj_release(&row->data->hdr);
1478 static void free_merge_table(MERGETABLE *table)
1482 if (table->labels != NULL)
1484 for (i = 0; i < table->numlabels; i++)
1485 msi_free(table->labels[i]);
1486 msi_free(table->labels);
1489 if (table->columns != NULL)
1491 for (i = 0; i < table->numcolumns; i++)
1492 msi_free(table->columns[i]);
1493 msi_free(table->columns);
1496 if (table->types != NULL)
1498 for (i = 0; i < table->numtypes; i++)
1499 msi_free(table->types[i]);
1500 msi_free(table->types);
1502 msi_free(table->name);
1503 merge_free_rows(table);
1508 static UINT msi_get_merge_table (MSIDATABASE *db, LPCWSTR name, MERGETABLE **ptable)
1512 MSIQUERY *mergeview = NULL;
1514 static const WCHAR query[] = {'S','E','L','E','C','T',' ','*',' ',
1515 'F','R','O','M',' ','`','%','s','`',0};
1517 table = msi_alloc_zero(sizeof(MERGETABLE));
1521 return ERROR_OUTOFMEMORY;
1524 r = msi_get_table_labels(db, name, &table->labels, &table->numlabels);
1525 if (r != ERROR_SUCCESS)
1528 r = MSI_OpenQuery(db, &mergeview, query, name);
1529 if (r != ERROR_SUCCESS)
1532 r = msi_get_query_columns(mergeview, &table->columns, &table->numcolumns);
1533 if (r != ERROR_SUCCESS)
1536 r = msi_get_query_types(mergeview, &table->types, &table->numtypes);
1537 if (r != ERROR_SUCCESS)
1540 list_init(&table->rows);
1542 table->name = strdupW(name);
1543 table->numconflicts = 0;
1545 msiobj_release(&mergeview->hdr);
1547 return ERROR_SUCCESS;
1550 msiobj_release(&mergeview->hdr);
1551 free_merge_table(table);
1556 static UINT merge_diff_tables(MSIRECORD *rec, LPVOID param)
1558 MERGEDATA *data = param;
1560 MSIQUERY *dbview = NULL;
1561 MSIQUERY *mergeview = NULL;
1565 static const WCHAR query[] = {'S','E','L','E','C','T',' ','*',' ',
1566 'F','R','O','M',' ','`','%','s','`',0};
1568 name = MSI_RecordGetString(rec, 1);
1570 r = MSI_OpenQuery(data->merge, &mergeview, query, name);
1571 if (r != ERROR_SUCCESS)
1574 if (TABLE_Exists(data->db, name))
1576 r = MSI_OpenQuery(data->db, &dbview, query, name);
1577 if (r != ERROR_SUCCESS)
1580 r = merge_verify_colnames(dbview, mergeview);
1581 if (r != ERROR_SUCCESS)
1584 r = merge_verify_primary_keys(data->db, data->merge, name);
1585 if (r != ERROR_SUCCESS)
1589 r = msi_get_merge_table(data->merge, name, &table);
1590 if (r != ERROR_SUCCESS)
1593 data->curtable = table;
1594 data->curview = mergeview;
1595 r = MSI_IterateRecords(mergeview, NULL, merge_diff_row, data);
1596 if (r != ERROR_SUCCESS)
1598 free_merge_table(table);
1602 list_add_tail(data->tabledata, &table->entry);
1605 msiobj_release(&dbview->hdr);
1606 msiobj_release(&mergeview->hdr);
1610 static UINT gather_merge_data(MSIDATABASE *db, MSIDATABASE *merge,
1611 struct list *tabledata)
1617 static const WCHAR query[] = {'S','E','L','E','C','T',' ','*',' ',
1618 'F','R','O','M',' ','`','_','T','a','b','l','e','s','`',0};
1620 r = MSI_DatabaseOpenViewW(merge, query, &view);
1621 if (r != ERROR_SUCCESS)
1626 data.tabledata = tabledata;
1627 r = MSI_IterateRecords(view, NULL, merge_diff_tables, &data);
1629 msiobj_release(&view->hdr);
1633 static UINT merge_table(MSIDATABASE *db, MERGETABLE *table)
1639 if (!TABLE_Exists(db, table->name))
1641 r = msi_add_table_to_db(db, table->columns, table->types,
1642 table->labels, table->numlabels, table->numcolumns);
1643 if (r != ERROR_SUCCESS)
1644 return ERROR_FUNCTION_FAILED;
1647 LIST_FOR_EACH_ENTRY(row, &table->rows, MERGEROW, entry)
1649 r = TABLE_CreateView(db, table->name, &tv);
1650 if (r != ERROR_SUCCESS)
1653 r = tv->ops->insert_row(tv, row->data, -1, FALSE);
1654 tv->ops->delete(tv);
1656 if (r != ERROR_SUCCESS)
1660 return ERROR_SUCCESS;
1663 static UINT update_merge_errors(MSIDATABASE *db, LPCWSTR error,
1664 LPWSTR table, DWORD numconflicts)
1669 static const WCHAR create[] = {
1670 'C','R','E','A','T','E',' ','T','A','B','L','E',' ',
1671 '`','%','s','`',' ','(','`','T','a','b','l','e','`',' ',
1672 'C','H','A','R','(','2','5','5',')',' ','N','O','T',' ',
1673 'N','U','L','L',',',' ','`','N','u','m','R','o','w','M','e','r','g','e',
1674 'C','o','n','f','l','i','c','t','s','`',' ','S','H','O','R','T',' ',
1675 'N','O','T',' ','N','U','L','L',' ','P','R','I','M','A','R','Y',' ',
1676 'K','E','Y',' ','`','T','a','b','l','e','`',')',0};
1677 static const WCHAR insert[] = {
1678 'I','N','S','E','R','T',' ','I','N','T','O',' ',
1679 '`','%','s','`',' ','(','`','T','a','b','l','e','`',',',' ',
1680 '`','N','u','m','R','o','w','M','e','r','g','e',
1681 'C','o','n','f','l','i','c','t','s','`',')',' ','V','A','L','U','E','S',
1682 ' ','(','\'','%','s','\'',',',' ','%','d',')',0};
1684 if (!TABLE_Exists(db, error))
1686 r = MSI_OpenQuery(db, &view, create, error);
1687 if (r != ERROR_SUCCESS)
1690 r = MSI_ViewExecute(view, NULL);
1691 msiobj_release(&view->hdr);
1692 if (r != ERROR_SUCCESS)
1696 r = MSI_OpenQuery(db, &view, insert, error, table, numconflicts);
1697 if (r != ERROR_SUCCESS)
1700 r = MSI_ViewExecute(view, NULL);
1701 msiobj_release(&view->hdr);
1705 UINT WINAPI MsiDatabaseMergeW(MSIHANDLE hDatabase, MSIHANDLE hDatabaseMerge,
1706 LPCWSTR szTableName)
1708 struct list tabledata = LIST_INIT(tabledata);
1709 struct list *item, *cursor;
1710 MSIDATABASE *db, *merge;
1715 TRACE("(%d, %d, %s)\n", hDatabase, hDatabaseMerge,
1716 debugstr_w(szTableName));
1718 if (szTableName && !*szTableName)
1719 return ERROR_INVALID_TABLE;
1721 db = msihandle2msiinfo(hDatabase, MSIHANDLETYPE_DATABASE);
1722 merge = msihandle2msiinfo(hDatabaseMerge, MSIHANDLETYPE_DATABASE);
1725 r = ERROR_INVALID_HANDLE;
1729 r = gather_merge_data(db, merge, &tabledata);
1730 if (r != ERROR_SUCCESS)
1734 LIST_FOR_EACH_ENTRY(table, &tabledata, MERGETABLE, entry)
1736 if (table->numconflicts)
1740 r = update_merge_errors(db, szTableName, table->name,
1741 table->numconflicts);
1742 if (r != ERROR_SUCCESS)
1747 r = merge_table(db, table);
1748 if (r != ERROR_SUCCESS)
1753 LIST_FOR_EACH_SAFE(item, cursor, &tabledata)
1755 MERGETABLE *table = LIST_ENTRY(item, MERGETABLE, entry);
1757 list_remove(&table->entry);
1758 free_merge_table(table);
1762 r = ERROR_FUNCTION_FAILED;
1765 msiobj_release(&db->hdr);
1766 msiobj_release(&merge->hdr);
1770 MSIDBSTATE WINAPI MsiGetDatabaseState( MSIHANDLE handle )
1772 MSIDBSTATE ret = MSIDBSTATE_READ;
1775 TRACE("%d\n", handle);
1777 db = msihandle2msiinfo( handle, MSIHANDLETYPE_DATABASE );
1780 IWineMsiRemoteDatabase *remote_database;
1782 remote_database = (IWineMsiRemoteDatabase *)msi_get_remote( handle );
1783 if ( !remote_database )
1784 return MSIDBSTATE_ERROR;
1786 IWineMsiRemoteDatabase_Release( remote_database );
1787 WARN("MsiGetDatabaseState not allowed during a custom action!\n");
1789 return MSIDBSTATE_READ;
1792 if (db->mode != MSIDBOPEN_READONLY )
1793 ret = MSIDBSTATE_WRITE;
1794 msiobj_release( &db->hdr );
1799 typedef struct _msi_remote_database_impl {
1800 const IWineMsiRemoteDatabaseVtbl *lpVtbl;
1803 } msi_remote_database_impl;
1805 static inline msi_remote_database_impl* mrd_from_IWineMsiRemoteDatabase( IWineMsiRemoteDatabase* iface )
1807 return (msi_remote_database_impl *)iface;
1810 static HRESULT WINAPI mrd_QueryInterface( IWineMsiRemoteDatabase *iface,
1811 REFIID riid,LPVOID *ppobj)
1813 if( IsEqualCLSID( riid, &IID_IUnknown ) ||
1814 IsEqualCLSID( riid, &IID_IWineMsiRemoteDatabase ) )
1816 IUnknown_AddRef( iface );
1821 return E_NOINTERFACE;
1824 static ULONG WINAPI mrd_AddRef( IWineMsiRemoteDatabase *iface )
1826 msi_remote_database_impl* This = mrd_from_IWineMsiRemoteDatabase( iface );
1828 return InterlockedIncrement( &This->refs );
1831 static ULONG WINAPI mrd_Release( IWineMsiRemoteDatabase *iface )
1833 msi_remote_database_impl* This = mrd_from_IWineMsiRemoteDatabase( iface );
1836 r = InterlockedDecrement( &This->refs );
1839 MsiCloseHandle( This->database );
1845 static HRESULT WINAPI mrd_IsTablePersistent( IWineMsiRemoteDatabase *iface,
1846 BSTR table, MSICONDITION *persistent )
1848 msi_remote_database_impl *This = mrd_from_IWineMsiRemoteDatabase( iface );
1849 *persistent = MsiDatabaseIsTablePersistentW(This->database, table);
1853 static HRESULT WINAPI mrd_GetPrimaryKeys( IWineMsiRemoteDatabase *iface,
1854 BSTR table, MSIHANDLE *keys )
1856 msi_remote_database_impl *This = mrd_from_IWineMsiRemoteDatabase( iface );
1857 UINT r = MsiDatabaseGetPrimaryKeysW(This->database, table, keys);
1858 return HRESULT_FROM_WIN32(r);
1861 static HRESULT WINAPI mrd_GetSummaryInformation( IWineMsiRemoteDatabase *iface,
1862 UINT updatecount, MSIHANDLE *suminfo )
1864 msi_remote_database_impl *This = mrd_from_IWineMsiRemoteDatabase( iface );
1865 UINT r = MsiGetSummaryInformationW(This->database, NULL, updatecount, suminfo);
1866 return HRESULT_FROM_WIN32(r);
1869 static HRESULT WINAPI mrd_OpenView( IWineMsiRemoteDatabase *iface,
1870 BSTR query, MSIHANDLE *view )
1872 msi_remote_database_impl *This = mrd_from_IWineMsiRemoteDatabase( iface );
1873 UINT r = MsiDatabaseOpenViewW(This->database, query, view);
1874 return HRESULT_FROM_WIN32(r);
1877 static HRESULT WINAPI mrd_SetMsiHandle( IWineMsiRemoteDatabase *iface, MSIHANDLE handle )
1879 msi_remote_database_impl* This = mrd_from_IWineMsiRemoteDatabase( iface );
1880 This->database = handle;
1884 static const IWineMsiRemoteDatabaseVtbl msi_remote_database_vtbl =
1889 mrd_IsTablePersistent,
1891 mrd_GetSummaryInformation,
1896 HRESULT create_msi_remote_database( IUnknown *pOuter, LPVOID *ppObj )
1898 msi_remote_database_impl *This;
1900 This = msi_alloc( sizeof *This );
1902 return E_OUTOFMEMORY;
1904 This->lpVtbl = &msi_remote_database_vtbl;