push cc8bc80451cc24f4d7cf75168b569f0ebfe19547
[wine/hacks.git] / dlls / msi / database.c
blobbc9319e33dbcf300f77aa331626d9d9421c1d8d4
1 /*
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
21 #include <stdarg.h>
23 #define COBJMACROS
24 #define NONAMELESSUNION
26 #include "windef.h"
27 #include "winbase.h"
28 #include "winreg.h"
29 #include "winnls.h"
30 #include "wine/debug.h"
31 #include "wine/unicode.h"
32 #include "msi.h"
33 #include "msiquery.h"
34 #include "msipriv.h"
35 #include "objidl.h"
36 #include "objbase.h"
37 #include "msiserver.h"
38 #include "query.h"
40 #include "initguid.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);
50 * .MSI file format
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;
63 msi_free(db->path);
64 free_cached_tables( db );
65 msi_free_transforms( db );
66 msi_destroy_stringtable( db->strings );
67 IStorage_Release( db->storage );
68 if (db->deletefile)
70 DeleteFileW( db->deletefile );
71 msi_free( db->deletefile );
75 UINT MSI_OpenDatabaseW(LPCWSTR szDBPath, LPCWSTR szPersist, MSIDATABASE **pdb)
77 IStorage *stg = NULL;
78 HRESULT r;
79 MSIDATABASE *db = NULL;
80 UINT ret = ERROR_FUNCTION_FAILED;
81 LPCWSTR szMode, save_path;
82 STATSTG stat;
83 BOOL created = FALSE;
84 WCHAR path[MAX_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) );
91 if( !pdb )
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;
102 szMode = szPersist;
103 if( HIWORD( szPersist ) )
105 if (!CopyFileW( szDBPath, szPersist, FALSE ))
106 return ERROR_OPEN_FAILED;
108 szDBPath = szPersist;
109 szPersist = MSIDBOPEN_TRANSACT;
110 created = TRUE;
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
121 * used here: */
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);
129 if (SUCCEEDED(r))
130 r = msi_init_string_table( stg );
132 created = TRUE;
134 else if( szPersist == MSIDBOPEN_TRANSACT )
136 /* FIXME: MSIDBOPEN_TRANSACT should case STGM_TRANSACTED flag to be
137 * used here: */
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);
146 else
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 );
159 if( FAILED( r ) )
161 FIXME("Failed to stat storage\n");
162 goto end;
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) );
170 goto end;
173 db = alloc_msiobject( MSIHANDLETYPE_DATABASE, sizeof (MSIDATABASE),
174 MSI_CloseDatabase );
175 if( !db )
177 FIXME("Failed to allocate a handle\n");
178 goto end;
181 if (!strchrW( save_path, '\\' ))
183 GetCurrentDirectoryW( MAX_PATH, path );
184 lstrcatW( path, backslash );
185 lstrcatW( path, save_path );
187 else
188 lstrcpyW( path, save_path );
190 db->path = strdupW( path );
192 if( TRACE_ON( msi ) )
193 enum_stream_names( stg );
195 db->storage = stg;
196 db->mode = szMode;
197 if (created)
198 db->deletefile = strdupW( szDBPath );
199 else
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 );
205 if( !db->strings )
206 goto end;
208 ret = ERROR_SUCCESS;
210 msiobj_addref( &db->hdr );
211 IStorage_AddRef( stg );
212 *pdb = db;
214 end:
215 if( db )
216 msiobj_release( &db->hdr );
217 if( stg )
218 IStorage_Release( stg );
220 return ret;
223 UINT WINAPI MsiOpenDatabaseW(LPCWSTR szDBPath, LPCWSTR szPersist, MSIHANDLE *phDB)
225 MSIDATABASE *db;
226 UINT ret;
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 );
234 if (! *phDB)
235 ret = ERROR_NOT_ENOUGH_MEMORY;
236 msiobj_release( &db->hdr );
239 return ret;
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);
249 if( szDBPath )
251 szwDBPath = strdupAtoW( szDBPath );
252 if( !szwDBPath )
253 goto end;
256 if( HIWORD(szPersist) )
258 szwPersist = strdupAtoW( szPersist );
259 if( !szwPersist )
260 goto end;
262 else
263 szwPersist = (LPWSTR)(DWORD_PTR)szPersist;
265 r = MsiOpenDatabaseW( szwDBPath, szwPersist, phDB );
267 end:
268 if( HIWORD(szPersist) )
269 msi_free( szwPersist );
270 msi_free( szwDBPath );
272 return r;
275 static LPWSTR msi_read_text_archive(LPCWSTR path)
277 HANDLE file;
278 LPSTR data = NULL;
279 LPWSTR wdata = NULL;
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)
284 return NULL;
286 size = GetFileSize( file, NULL );
287 data = msi_alloc( size + 1 );
288 if (!data)
289 goto done;
291 if (!ReadFile( file, data, size, &read, NULL ))
292 goto done;
294 data[size] = '\0';
295 wdata = strdupAtoW( data );
297 done:
298 CloseHandle( file );
299 msi_free( data );
300 return wdata;
303 static void msi_parse_line(LPWSTR *line, LPWSTR **entries, DWORD *num_entries)
305 LPWSTR ptr = *line, save;
306 DWORD i, count = 1;
308 *entries = NULL;
310 /* stay on this line */
311 while (*ptr && *ptr != '\n')
313 /* entries are separated by tabs */
314 if (*ptr == '\t')
315 count++;
317 ptr++;
320 *entries = msi_alloc(count * sizeof(LPWSTR));
321 if (!*entries)
322 return;
324 /* store pointers into the data */
325 for (i = 0, ptr = *line; i < count; i++)
327 while (*ptr && *ptr == '\r') ptr++;
328 save = 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')
336 *(ptr++) = '\0';
338 else if (*ptr)
339 *ptr++ = '\0';
341 (*entries)[i] = save;
344 /* move to the next line if there's more, else EOF */
345 *line = ptr;
347 if (num_entries)
348 *num_entries = count;
351 static LPWSTR msi_build_createsql_prelude(LPWSTR table)
353 LPWSTR prelude;
354 DWORD size;
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));
360 if (!prelude)
361 return NULL;
363 sprintfW(prelude, create_fmt, table);
364 return prelude;
367 static LPWSTR msi_build_createsql_columns(LPWSTR *columns_data, LPWSTR *types, DWORD num_columns)
369 LPWSTR columns, p;
370 LPCWSTR type;
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));
385 if (!columns)
386 return NULL;
388 for (i = 0; i < num_columns; i++)
390 type = NULL;
391 comma[1] = size[0] = extra[0] = '\0';
393 if (i == num_columns - 1)
394 comma[0] = '\0';
395 else
396 comma[0] = ',';
398 ptr = &types[i][1];
399 len = atolW(ptr);
400 extra[0] = '\0';
402 switch (types[i][0])
404 case 'l':
405 lstrcpyW(extra, type_notnull);
406 case 'L':
407 lstrcatW(extra, localizable);
408 type = type_char;
409 sprintfW(size, size_fmt, ptr);
410 break;
411 case 's':
412 lstrcpyW(extra, type_notnull);
413 case 'S':
414 type = type_char;
415 sprintfW(size, size_fmt, ptr);
416 break;
417 case 'i':
418 lstrcpyW(extra, type_notnull);
419 case 'I':
420 if (len == 2)
421 type = type_int;
422 else
423 type = type_long;
424 break;
425 case 'v':
426 lstrcpyW(extra, type_notnull);
427 case 'V':
428 type = type_object;
429 break;
430 default:
431 ERR("Unknown type: %c\n", types[i][0]);
432 msi_free(columns);
433 return NULL;
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));
440 if (!p)
442 msi_free(columns);
443 return NULL;
445 columns = p;
447 lstrcatW(columns, expanded);
450 return columns;
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));
465 if (!keys)
466 return NULL;
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]);
472 ptr += key_size;
475 /* remove final ', ' */
476 *(ptr - 2) = '\0';
478 size = lstrlenW(postlude_fmt) + size - 1;
479 postlude = msi_alloc(size * sizeof(WCHAR));
480 if (!postlude)
481 goto done;
483 sprintfW(postlude, postlude_fmt, keys);
485 done:
486 msi_free(keys);
487 return postlude;
490 static UINT msi_add_table_to_db(MSIDATABASE *db, LPWSTR *columns, LPWSTR *types, LPWSTR *labels, DWORD num_labels, DWORD num_columns)
492 UINT r;
493 DWORD size;
494 MSIQUERY *view;
495 LPWSTR create_sql;
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));
507 if (!create_sql)
508 return ERROR_OUTOFMEMORY;
510 lstrcpyW(create_sql, prelude);
511 lstrcatW(create_sql, columns_sql);
512 lstrcatW(create_sql, postlude);
514 msi_free(prelude);
515 msi_free(columns_sql);
516 msi_free(postlude);
518 r = MSI_DatabaseOpenViewW( db, create_sql, &view );
519 msi_free(create_sql);
521 if (r != ERROR_SUCCESS)
522 return r;
524 r = MSI_ViewExecute(view, NULL);
525 MSI_ViewClose(view);
526 msiobj_release(&view->hdr);
528 return r;
531 static LPWSTR msi_import_stream_filename(LPCWSTR path, LPCWSTR name)
533 DWORD len;
534 LPWSTR fullname, ptr;
536 len = lstrlenW(path) + lstrlenW(name) + 1;
537 fullname = msi_alloc(len*sizeof(WCHAR));
538 if (!fullname)
539 return NULL;
541 lstrcpyW( fullname, path );
543 /* chop off extension from path */
544 ptr = strrchrW(fullname, '.');
545 if (!ptr)
547 msi_free (fullname);
548 return NULL;
550 *ptr++ = '\\';
551 lstrcpyW( ptr, name );
552 return fullname;
555 static UINT construct_record(DWORD num_columns, LPWSTR *types,
556 LPWSTR *data, LPWSTR path, MSIRECORD **rec)
558 UINT i;
560 *rec = MSI_CreateRecord(num_columns);
561 if (!*rec)
562 return ERROR_OUTOFMEMORY;
564 for (i = 0; i < num_columns; i++)
566 switch (types[i][0])
568 case 'L': case 'l': case 'S': case 's':
569 MSI_RecordSetStringW(*rec, i + 1, data[i]);
570 break;
571 case 'I': case 'i':
572 if (*data[i])
573 MSI_RecordSetInteger(*rec, i + 1, atoiW(data[i]));
574 break;
575 case 'V': case 'v':
576 if (*data[i])
578 UINT r;
579 LPWSTR file = msi_import_stream_filename(path, data[i]);
580 if (!file)
581 return ERROR_FUNCTION_FAILED;
583 r = MSI_RecordSetStreamFromFileW(*rec, i + 1, file);
584 msi_free (file);
585 if (r != ERROR_SUCCESS)
586 return ERROR_FUNCTION_FAILED;
588 break;
589 default:
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,
602 LPWSTR path)
604 UINT r;
605 int i;
606 MSIQUERY *view;
607 MSIRECORD *rec;
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)
616 return r;
618 while (MSI_ViewFetch(view, &rec) != ERROR_NO_MORE_ITEMS)
620 r = MSI_ViewModify(view, MSIMODIFY_DELETE, rec);
621 if (r != ERROR_SUCCESS)
622 goto done;
625 for (i = 0; i < num_records; i++)
627 r = construct_record(num_columns, types, records[i], path, &rec);
628 if (r != ERROR_SUCCESS)
629 goto done;
631 r = MSI_ViewModify(view, MSIMODIFY_INSERT, rec);
632 if (r != ERROR_SUCCESS)
634 msiobj_release(&rec->hdr);
635 goto done;
638 msiobj_release(&rec->hdr);
641 done:
642 msiobj_release(&view->hdr);
643 return r;
646 static UINT MSI_DatabaseImport(MSIDATABASE *db, LPCWSTR folder, LPCWSTR file)
648 UINT r;
649 DWORD len, i;
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) );
668 if (!path)
669 return ERROR_OUTOFMEMORY;
671 lstrcpyW( path, folder );
672 lstrcatW( path, backslash );
673 lstrcatW( path, file );
675 data = msi_read_text_archive( path );
677 ptr = data;
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;
685 goto done;
688 records = msi_alloc(sizeof(LPWSTR *));
689 if (!records)
691 r = ERROR_OUTOFMEMORY;
692 goto done;
695 /* read in the table records */
696 while (*ptr)
698 msi_parse_line( &ptr, &records[num_records], NULL );
700 num_records++;
701 temp_records = msi_realloc(records, (num_records + 1) * sizeof(LPWSTR *));
702 if (!temp_records)
704 r = ERROR_OUTOFMEMORY;
705 goto done;
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;
716 goto done;
719 else
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;
727 goto done;
731 r = msi_add_records_to_table( db, columns, types, labels, records, num_columns, num_records, path );
734 done:
735 msi_free(path);
736 msi_free(data);
737 msi_free(columns);
738 msi_free(types);
739 msi_free(labels);
741 for (i = 0; i < num_records; i++)
742 msi_free(records[i]);
744 msi_free(records);
746 return r;
749 UINT WINAPI MsiDatabaseImportW(MSIHANDLE handle, LPCWSTR szFolder, LPCWSTR szFilename)
751 MSIDATABASE *db;
752 UINT r;
754 TRACE("%x %s %s\n",handle,debugstr_w(szFolder), debugstr_w(szFilename));
756 db = msihandle2msiinfo( handle, MSIHANDLETYPE_DATABASE );
757 if( !db )
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 );
773 return r;
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));
784 if( szFolder )
786 path = strdupAtoW( szFolder );
787 if( !path )
788 goto end;
791 if( szFilename )
793 file = strdupAtoW( szFilename );
794 if( !file )
795 goto end;
798 r = MsiDatabaseImportW( handle, path, file );
800 end:
801 msi_free( path );
802 msi_free( file );
804 return r;
807 static UINT msi_export_record( HANDLE handle, MSIRECORD *row, UINT start )
809 UINT i, count, len, r = ERROR_SUCCESS;
810 const char *sep;
811 char *buffer;
812 DWORD sz;
814 len = 0x100;
815 buffer = msi_alloc( len );
816 if ( !buffer )
817 return ERROR_OUTOFMEMORY;
819 count = MSI_RecordGetFieldCount( row );
820 for ( i=start; i<=count; i++ )
822 sz = len;
823 r = MSI_RecordGetStringA( row, i, buffer, &sz );
824 if (r == ERROR_MORE_DATA)
826 char *p = msi_realloc( buffer, sz + 1 );
827 if (!p)
828 break;
829 len = sz + 1;
830 buffer = p;
832 sz = len;
833 r = MSI_RecordGetStringA( row, i, buffer, &sz );
834 if (r != ERROR_SUCCESS)
835 break;
837 if (!WriteFile( handle, buffer, sz, &sz, NULL ))
839 r = ERROR_FUNCTION_FAILED;
840 break;
843 sep = (i < count) ? "\t" : "\r\n";
844 if (!WriteFile( handle, sep, strlen(sep), &sz, NULL ))
846 r = ERROR_FUNCTION_FAILED;
847 break;
850 msi_free( buffer );
851 return r;
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 )
861 DWORD sz;
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;
884 LPWSTR filename;
885 HANDLE handle;
886 UINT len, r;
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));
896 if (!filename)
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 );
912 goto done;
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 );
948 done:
949 CloseHandle( handle );
950 return r;
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 )
971 MSIDATABASE *db;
972 UINT r;
974 TRACE("%x %s %s %s\n", handle, debugstr_w(szTable),
975 debugstr_w(szFolder), debugstr_w(szFilename));
977 db = msihandle2msiinfo( handle, MSIHANDLETYPE_DATABASE );
978 if( !db )
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 );
994 return r;
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));
1006 if( szTable )
1008 table = strdupAtoW( szTable );
1009 if( !table )
1010 goto end;
1013 if( szFolder )
1015 path = strdupAtoW( szFolder );
1016 if( !path )
1017 goto end;
1020 if( szFilename )
1022 file = strdupAtoW( szFilename );
1023 if( !file )
1024 goto end;
1027 r = MsiDatabaseExportW( handle, table, path, file );
1029 end:
1030 msi_free( table );
1031 msi_free( path );
1032 msi_free( file );
1034 return r;
1037 UINT WINAPI MsiDatabaseMergeA(MSIHANDLE hDatabase, MSIHANDLE hDatabaseMerge,
1038 LPCSTR szTableName)
1040 UINT r;
1041 LPWSTR table;
1043 TRACE("(%d, %d, %s)\n", hDatabase, hDatabaseMerge,
1044 debugstr_a(szTableName));
1046 table = strdupAtoW(szTableName);
1047 r = MsiDatabaseMergeW(hDatabase, hDatabaseMerge, table);
1049 msi_free(table);
1050 return r;
1053 typedef struct _tagMERGETABLE
1055 struct list entry;
1056 struct list rows;
1057 LPWSTR name;
1058 DWORD numconflicts;
1059 LPWSTR *columns;
1060 DWORD numcolumns;
1061 LPWSTR *types;
1062 DWORD numtypes;
1063 LPWSTR *labels;
1064 DWORD numlabels;
1065 } MERGETABLE;
1067 typedef struct _tagMERGEROW
1069 struct list entry;
1070 MSIRECORD *data;
1071 } MERGEROW;
1073 typedef struct _tagMERGEDATA
1075 MSIDATABASE *db;
1076 MSIDATABASE *merge;
1077 MERGETABLE *curtable;
1078 MSIQUERY *curview;
1079 struct list *tabledata;
1080 } MERGEDATA;
1082 static UINT merge_verify_colnames(MSIQUERY *dbview, MSIQUERY *mergeview)
1084 MSIRECORD *dbrec, *mergerec;
1085 UINT r, i, count;
1087 r = MSI_ViewGetColumnInfo(dbview, MSICOLINFO_NAMES, &dbrec);
1088 if (r != ERROR_SUCCESS)
1089 return r;
1091 r = MSI_ViewGetColumnInfo(mergeview, MSICOLINFO_NAMES, &mergerec);
1092 if (r != ERROR_SUCCESS)
1093 return r;
1095 count = MSI_RecordGetFieldCount(dbrec);
1096 for (i = 1; i <= count; i++)
1098 if (!MSI_RecordGetString(mergerec, i))
1099 break;
1101 if (lstrcmpW(MSI_RecordGetString(dbrec, i),
1102 MSI_RecordGetString(mergerec, i)))
1104 r = ERROR_DATATYPE_MISMATCH;
1105 goto done;
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)
1115 return r;
1117 r = MSI_ViewGetColumnInfo(mergeview, MSICOLINFO_TYPES, &mergerec);
1118 if (r != ERROR_SUCCESS)
1119 return r;
1121 count = MSI_RecordGetFieldCount(dbrec);
1122 for (i = 1; i <= count; i++)
1124 if (!MSI_RecordGetString(mergerec, i))
1125 break;
1127 if (lstrcmpW(MSI_RecordGetString(dbrec, i),
1128 MSI_RecordGetString(mergerec, i)))
1130 r = ERROR_DATATYPE_MISMATCH;
1131 break;
1135 done:
1136 msiobj_release(&dbrec->hdr);
1137 msiobj_release(&mergerec->hdr);
1139 return r;
1142 static UINT merge_verify_primary_keys(MSIDATABASE *db, MSIDATABASE *mergedb,
1143 LPCWSTR table)
1145 MSIRECORD *dbrec, *mergerec = NULL;
1146 UINT r, i, count;
1148 r = MSI_DatabaseGetPrimaryKeys(db, table, &dbrec);
1149 if (r != ERROR_SUCCESS)
1150 return r;
1152 r = MSI_DatabaseGetPrimaryKeys(mergedb, table, &mergerec);
1153 if (r != ERROR_SUCCESS)
1154 goto done;
1156 count = MSI_RecordGetFieldCount(dbrec);
1157 if (count != MSI_RecordGetFieldCount(mergerec))
1159 r = ERROR_DATATYPE_MISMATCH;
1160 goto done;
1163 for (i = 1; i <= count; i++)
1165 if (lstrcmpW(MSI_RecordGetString(dbrec, i),
1166 MSI_RecordGetString(mergerec, i)))
1168 r = ERROR_DATATYPE_MISMATCH;
1169 goto done;
1173 done:
1174 msiobj_release(&dbrec->hdr);
1175 msiobj_release(&mergerec->hdr);
1177 return r;
1180 static LPWSTR get_key_value(MSIQUERY *view, LPCWSTR key, MSIRECORD *rec)
1182 MSIRECORD *colnames;
1183 LPWSTR str, val;
1184 UINT r, i = 0, sz = 0;
1185 int cmp;
1187 r = MSI_ViewGetColumnInfo(view, MSICOLINFO_NAMES, &colnames);
1188 if (r != ERROR_SUCCESS)
1189 return NULL;
1193 str = msi_dup_record_field(colnames, ++i);
1194 cmp = lstrcmpW(key, str);
1195 msi_free(str);
1196 } while (cmp);
1198 msiobj_release(&colnames->hdr);
1200 r = MSI_RecordGetStringW(rec, i, NULL, &sz);
1201 if (r != ERROR_SUCCESS)
1202 return NULL;
1203 sz++;
1205 if (MSI_RecordGetString(rec, i)) /* check record field is a string */
1207 /* quote string record fields */
1208 const WCHAR szQuote[] = {'\'', 0};
1209 sz += 2;
1210 val = msi_alloc(sz*sizeof(WCHAR));
1211 if (!val)
1212 return NULL;
1214 lstrcpyW(val, szQuote);
1215 r = MSI_RecordGetStringW(rec, i, val+1, &sz);
1216 lstrcpyW(val+1+sz, szQuote);
1218 else
1220 /* do not quote integer record fields */
1221 val = msi_alloc(sz*sizeof(WCHAR));
1222 if (!val)
1223 return NULL;
1225 r = MSI_RecordGetStringW(rec, i, val, &sz);
1228 if (r != ERROR_SUCCESS)
1230 ERR("failed to get string!\n");
1231 msi_free(val);
1232 return NULL;
1235 return val;
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;
1243 LPCWSTR setptr;
1244 DWORD size = 1, oldsize;
1245 LPCWSTR key;
1246 MSIRECORD *keys;
1247 UINT r, i, count;
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)
1259 return NULL;
1261 clause = msi_alloc_zero(size * sizeof(WCHAR));
1262 if (!clause)
1263 goto done;
1265 ptr = clause;
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);
1272 if (i == count)
1273 setptr = lastkeyset;
1274 else
1275 setptr = keyset;
1277 oldsize = size;
1278 size += lstrlenW(setptr) + lstrlenW(key) + lstrlenW(val) - 4;
1279 clause = msi_realloc(clause, size * sizeof (WCHAR));
1280 if (!clause)
1282 msi_free(val);
1283 goto done;
1286 ptr = clause + oldsize - 1;
1287 sprintfW(ptr, setptr, key, val);
1288 msi_free(val);
1291 size = lstrlenW(fmt) + lstrlenW(table) + lstrlenW(clause) + 1;
1292 query = msi_alloc(size * sizeof(WCHAR));
1293 if (!query)
1294 goto done;
1296 sprintfW(query, fmt, table, clause);
1298 done:
1299 msi_free(clause);
1300 msiobj_release(&keys->hdr);
1301 return query;
1304 static UINT merge_diff_row(MSIRECORD *rec, LPVOID param)
1306 MERGEDATA *data = param;
1307 MERGETABLE *table = data->curtable;
1308 MERGEROW *mergerow;
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);
1317 if (!query)
1318 return ERROR_OUTOFMEMORY;
1320 r = MSI_DatabaseOpenViewW(data->db, query, &dbview);
1321 if (r != ERROR_SUCCESS)
1322 goto done;
1324 r = MSI_ViewExecute(dbview, NULL);
1325 if (r != ERROR_SUCCESS)
1326 goto done;
1328 r = MSI_ViewFetch(dbview, &row);
1329 if (r == ERROR_SUCCESS && !MSI_RecordsAreEqual(rec, row))
1331 table->numconflicts++;
1332 goto done;
1334 else if (r != ERROR_NO_MORE_ITEMS)
1335 goto done;
1338 mergerow = msi_alloc(sizeof(MERGEROW));
1339 if (!mergerow)
1341 r = ERROR_OUTOFMEMORY;
1342 goto done;
1345 mergerow->data = MSI_CloneRecord(rec);
1346 if (!mergerow->data)
1348 r = ERROR_OUTOFMEMORY;
1349 msi_free(mergerow);
1350 goto done;
1353 list_add_tail(&table->rows, &mergerow->entry);
1355 done:
1356 msi_free(query);
1357 msiobj_release(&row->hdr);
1358 msiobj_release(&dbview->hdr);
1359 return r;
1362 static UINT msi_get_table_labels(MSIDATABASE *db, LPCWSTR table, LPWSTR **labels, DWORD *numlabels)
1364 UINT r, i, count;
1365 MSIRECORD *prec = NULL;
1367 r = MSI_DatabaseGetPrimaryKeys(db, table, &prec);
1368 if (r != ERROR_SUCCESS)
1369 return r;
1371 count = MSI_RecordGetFieldCount(prec);
1372 *numlabels = count + 1;
1373 *labels = msi_alloc((*numlabels)*sizeof(LPWSTR));
1374 if (!*labels)
1376 r = ERROR_OUTOFMEMORY;
1377 goto end;
1380 (*labels)[0] = strdupW(table);
1381 for (i=1; i<=count; i++ )
1383 (*labels)[i] = strdupW(MSI_RecordGetString(prec, i));
1386 end:
1387 msiobj_release( &prec->hdr );
1388 return r;
1391 static UINT msi_get_query_columns(MSIQUERY *query, LPWSTR **columns, DWORD *numcolumns)
1393 UINT r, i, count;
1394 MSIRECORD *prec = NULL;
1396 r = MSI_ViewGetColumnInfo(query, MSICOLINFO_NAMES, &prec);
1397 if (r != ERROR_SUCCESS)
1398 return r;
1400 count = MSI_RecordGetFieldCount(prec);
1401 *columns = msi_alloc(count*sizeof(LPWSTR));
1402 if (!*columns)
1404 r = ERROR_OUTOFMEMORY;
1405 goto end;
1408 for (i=1; i<=count; i++ )
1410 (*columns)[i-1] = strdupW(MSI_RecordGetString(prec, i));
1413 *numcolumns = count;
1415 end:
1416 msiobj_release( &prec->hdr );
1417 return r;
1420 static UINT msi_get_query_types(MSIQUERY *query, LPWSTR **types, DWORD *numtypes)
1422 UINT r, i, count;
1423 MSIRECORD *prec = NULL;
1425 r = MSI_ViewGetColumnInfo(query, MSICOLINFO_TYPES, &prec);
1426 if (r != ERROR_SUCCESS)
1427 return r;
1429 count = MSI_RecordGetFieldCount(prec);
1430 *types = msi_alloc(count*sizeof(LPWSTR));
1431 if (!*types)
1433 r = ERROR_OUTOFMEMORY;
1434 goto end;
1437 for (i=1; i<=count; i++ )
1439 (*types)[i-1] = strdupW(MSI_RecordGetString(prec, i));
1442 end:
1443 msiobj_release( &prec->hdr );
1444 return r;
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);
1457 msi_free(row);
1461 static void free_merge_table(MERGETABLE *table)
1463 UINT i;
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);
1488 msi_free(table);
1491 static UINT msi_get_merge_table (MSIDATABASE *db, LPCWSTR name, MERGETABLE **ptable)
1493 UINT r;
1494 MERGETABLE *table;
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));
1501 if (!table)
1503 *ptable = NULL;
1504 return ERROR_OUTOFMEMORY;
1507 r = msi_get_table_labels(db, name, &table->labels, &table->numlabels);
1508 if (r != ERROR_SUCCESS)
1509 goto err;
1511 r = MSI_OpenQuery(db, &mergeview, query, name);
1512 if (r != ERROR_SUCCESS)
1513 goto err;
1515 r = msi_get_query_columns(mergeview, &table->columns, &table->numcolumns);
1516 if (r != ERROR_SUCCESS)
1517 goto err;
1519 r = msi_get_query_types(mergeview, &table->types, &table->numtypes);
1520 if (r != ERROR_SUCCESS)
1521 goto err;
1523 list_init(&table->rows);
1525 table->name = strdupW(name);
1526 table->numconflicts = 0;
1528 msiobj_release(&mergeview->hdr);
1529 *ptable = table;
1530 return ERROR_SUCCESS;
1532 err:
1533 msiobj_release(&mergeview->hdr);
1534 free_merge_table(table);
1535 *ptable = NULL;
1536 return r;
1539 static UINT merge_diff_tables(MSIRECORD *rec, LPVOID param)
1541 MERGEDATA *data = param;
1542 MERGETABLE *table;
1543 MSIQUERY *dbview = NULL;
1544 MSIQUERY *mergeview = NULL;
1545 LPCWSTR name;
1546 UINT r;
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)
1555 goto done;
1557 if (TABLE_Exists(data->db, name))
1559 r = MSI_OpenQuery(data->db, &dbview, query, name);
1560 if (r != ERROR_SUCCESS)
1561 goto done;
1563 r = merge_verify_colnames(dbview, mergeview);
1564 if (r != ERROR_SUCCESS)
1565 goto done;
1567 r = merge_verify_primary_keys(data->db, data->merge, name);
1568 if (r != ERROR_SUCCESS)
1569 goto done;
1572 r = msi_get_merge_table(data->merge, name, &table);
1573 if (r != ERROR_SUCCESS)
1574 goto done;
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);
1582 goto done;
1585 list_add_tail(data->tabledata, &table->entry);
1587 done:
1588 msiobj_release(&dbview->hdr);
1589 msiobj_release(&mergeview->hdr);
1590 return r;
1593 static UINT gather_merge_data(MSIDATABASE *db, MSIDATABASE *merge,
1594 struct list *tabledata)
1596 UINT r;
1597 MSIQUERY *view;
1598 MERGEDATA data;
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)
1605 return r;
1607 data.db = db;
1608 data.merge = merge;
1609 data.tabledata = tabledata;
1610 r = MSI_IterateRecords(view, NULL, merge_diff_tables, &data);
1612 msiobj_release(&view->hdr);
1613 return r;
1616 static UINT merge_table(MSIDATABASE *db, MERGETABLE *table)
1618 UINT r;
1619 MERGEROW *row;
1620 MSIVIEW *tv;
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)
1634 return r;
1636 r = tv->ops->insert_row(tv, row->data, -1, FALSE);
1637 tv->ops->delete(tv);
1639 if (r != ERROR_SUCCESS)
1640 return r;
1643 return ERROR_SUCCESS;
1646 static UINT update_merge_errors(MSIDATABASE *db, LPCWSTR error,
1647 LPWSTR table, DWORD numconflicts)
1649 UINT r;
1650 MSIQUERY *view;
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)
1671 return r;
1673 r = MSI_ViewExecute(view, NULL);
1674 msiobj_release(&view->hdr);
1675 if (r != ERROR_SUCCESS)
1676 return r;
1679 r = MSI_OpenQuery(db, &view, insert, error, table, numconflicts);
1680 if (r != ERROR_SUCCESS)
1681 return r;
1683 r = MSI_ViewExecute(view, NULL);
1684 msiobj_release(&view->hdr);
1685 return r;
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;
1694 MERGETABLE *table;
1695 BOOL conflicts;
1696 UINT r;
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);
1706 if (!db || !merge)
1708 r = ERROR_INVALID_HANDLE;
1709 goto done;
1712 r = gather_merge_data(db, merge, &tabledata);
1713 if (r != ERROR_SUCCESS)
1714 goto done;
1716 conflicts = FALSE;
1717 LIST_FOR_EACH_ENTRY(table, &tabledata, MERGETABLE, entry)
1719 if (table->numconflicts)
1721 conflicts = TRUE;
1723 r = update_merge_errors(db, szTableName, table->name,
1724 table->numconflicts);
1725 if (r != ERROR_SUCCESS)
1726 break;
1728 else
1730 r = merge_table(db, table);
1731 if (r != ERROR_SUCCESS)
1732 break;
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);
1744 if (conflicts)
1745 r = ERROR_FUNCTION_FAILED;
1747 done:
1748 msiobj_release(&db->hdr);
1749 msiobj_release(&merge->hdr);
1750 return r;
1753 MSIDBSTATE WINAPI MsiGetDatabaseState( MSIHANDLE handle )
1755 MSIDBSTATE ret = MSIDBSTATE_READ;
1756 MSIDATABASE *db;
1758 TRACE("%d\n", handle);
1760 db = msihandle2msiinfo( handle, MSIHANDLETYPE_DATABASE );
1761 if( !db )
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 );
1779 return ret;
1782 typedef struct _msi_remote_database_impl {
1783 const IWineMsiRemoteDatabaseVtbl *lpVtbl;
1784 MSIHANDLE database;
1785 LONG refs;
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 );
1800 *ppobj = iface;
1801 return S_OK;
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 );
1817 ULONG r;
1819 r = InterlockedDecrement( &This->refs );
1820 if (r == 0)
1822 MsiCloseHandle( This->database );
1823 msi_free( This );
1825 return r;
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);
1833 return S_OK;
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;
1864 return S_OK;
1867 static const IWineMsiRemoteDatabaseVtbl msi_remote_database_vtbl =
1869 mrd_QueryInterface,
1870 mrd_AddRef,
1871 mrd_Release,
1872 mrd_IsTablePersistent,
1873 mrd_GetPrimaryKeys,
1874 mrd_GetSummaryInformation,
1875 mrd_OpenView,
1876 mrd_SetMsiHandle,
1879 HRESULT create_msi_remote_database( IUnknown *pOuter, LPVOID *ppObj )
1881 msi_remote_database_impl *This;
1883 This = msi_alloc( sizeof *This );
1884 if (!This)
1885 return E_OUTOFMEMORY;
1887 This->lpVtbl = &msi_remote_database_vtbl;
1888 This->database = 0;
1889 This->refs = 1;
1891 *ppObj = This;
1893 return S_OK;