push 8b07bf1f08b23b9893a622b47d2be359556765b1
[wine/hacks.git] / dlls / msi / database.c
blob4db7c01041e07aea3607c02e5a02e5476ae3672f
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);
45 * .MSI file format
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;
58 msi_free(db->path);
59 free_cached_tables( db );
60 msi_free_transforms( db );
61 msi_destroy_stringtable( db->strings );
62 IStorage_Release( db->storage );
63 if (db->deletefile)
65 DeleteFileW( db->deletefile );
66 msi_free( db->deletefile );
70 UINT MSI_OpenDatabaseW(LPCWSTR szDBPath, LPCWSTR szPersist, MSIDATABASE **pdb)
72 IStorage *stg = NULL;
73 HRESULT r;
74 MSIDATABASE *db = NULL;
75 UINT ret = ERROR_FUNCTION_FAILED;
76 LPCWSTR szMode, save_path;
77 STATSTG stat;
78 BOOL created = FALSE;
79 WCHAR path[MAX_PATH];
81 static const WCHAR szTables[] = { '_','T','a','b','l','e','s',0 };
83 TRACE("%s %s\n",debugstr_w(szDBPath),debugstr_w(szPersist) );
85 if( !pdb )
86 return ERROR_INVALID_PARAMETER;
88 if (szPersist - MSIDBOPEN_PATCHFILE >= MSIDBOPEN_READONLY &&
89 szPersist - MSIDBOPEN_PATCHFILE <= MSIDBOPEN_CREATEDIRECT)
91 TRACE("Database is a patch\n");
92 szPersist -= MSIDBOPEN_PATCHFILE;
95 save_path = szDBPath;
96 szMode = szPersist;
97 if( HIWORD( szPersist ) )
99 if (!CopyFileW( szDBPath, szPersist, FALSE ))
100 return ERROR_OPEN_FAILED;
102 szDBPath = szPersist;
103 szPersist = MSIDBOPEN_TRANSACT;
104 created = TRUE;
107 if( szPersist == MSIDBOPEN_READONLY )
109 r = StgOpenStorage( szDBPath, NULL,
110 STGM_DIRECT|STGM_READ|STGM_SHARE_DENY_WRITE, NULL, 0, &stg);
112 else if( szPersist == MSIDBOPEN_CREATE || szPersist == MSIDBOPEN_CREATEDIRECT )
114 /* FIXME: MSIDBOPEN_CREATE should case STGM_TRANSACTED flag to be
115 * used here: */
116 r = StgCreateDocfile( szDBPath,
117 STGM_CREATE|STGM_DIRECT|STGM_READWRITE|STGM_SHARE_EXCLUSIVE, 0, &stg);
118 if( r == ERROR_SUCCESS )
120 IStorage_SetClass( stg, &CLSID_MsiDatabase );
121 /* create the _Tables stream */
122 r = write_stream_data(stg, szTables, NULL, 0, TRUE);
123 if (SUCCEEDED(r))
124 r = msi_init_string_table( stg );
126 created = TRUE;
128 else if( szPersist == MSIDBOPEN_TRANSACT )
130 /* FIXME: MSIDBOPEN_TRANSACT should case STGM_TRANSACTED flag to be
131 * used here: */
132 r = StgOpenStorage( szDBPath, NULL,
133 STGM_DIRECT|STGM_READWRITE|STGM_SHARE_EXCLUSIVE, NULL, 0, &stg);
135 else if( szPersist == MSIDBOPEN_DIRECT )
137 r = StgOpenStorage( szDBPath, NULL,
138 STGM_DIRECT|STGM_READWRITE|STGM_SHARE_EXCLUSIVE, NULL, 0, &stg);
140 else
142 ERR("unknown flag %p\n",szPersist);
143 return ERROR_INVALID_PARAMETER;
146 if( FAILED( r ) || !stg )
148 FIXME("open failed r = %08x for %s\n", r, debugstr_w(szDBPath));
149 return ERROR_FUNCTION_FAILED;
152 r = IStorage_Stat( stg, &stat, STATFLAG_NONAME );
153 if( FAILED( r ) )
155 FIXME("Failed to stat storage\n");
156 goto end;
159 if ( !IsEqualGUID( &stat.clsid, &CLSID_MsiDatabase ) &&
160 !IsEqualGUID( &stat.clsid, &CLSID_MsiPatch ) &&
161 !IsEqualGUID( &stat.clsid, &CLSID_MsiTransform ) )
163 ERR("storage GUID is not a MSI database GUID %s\n",
164 debugstr_guid(&stat.clsid) );
165 goto end;
168 db = alloc_msiobject( MSIHANDLETYPE_DATABASE, sizeof (MSIDATABASE),
169 MSI_CloseDatabase );
170 if( !db )
172 FIXME("Failed to allocate a handle\n");
173 goto end;
176 if (!strchrW( save_path, '\\' ))
178 GetCurrentDirectoryW( MAX_PATH, path );
179 lstrcatW( path, szBackSlash );
180 lstrcatW( path, save_path );
182 else
183 lstrcpyW( path, save_path );
185 db->path = strdupW( path );
187 if( TRACE_ON( msi ) )
188 enum_stream_names( stg );
190 db->storage = stg;
191 db->mode = szMode;
192 if (created)
193 db->deletefile = strdupW( szDBPath );
194 else
195 db->deletefile = NULL;
196 list_init( &db->tables );
197 list_init( &db->transforms );
199 db->strings = msi_load_string_table( stg, &db->bytes_per_strref );
200 if( !db->strings )
201 goto end;
203 ret = ERROR_SUCCESS;
205 msiobj_addref( &db->hdr );
206 IStorage_AddRef( stg );
207 *pdb = db;
209 end:
210 if( db )
211 msiobj_release( &db->hdr );
212 if( stg )
213 IStorage_Release( stg );
215 return ret;
218 UINT WINAPI MsiOpenDatabaseW(LPCWSTR szDBPath, LPCWSTR szPersist, MSIHANDLE *phDB)
220 MSIDATABASE *db;
221 UINT ret;
223 TRACE("%s %s %p\n",debugstr_w(szDBPath),debugstr_w(szPersist), phDB);
225 ret = MSI_OpenDatabaseW( szDBPath, szPersist, &db );
226 if( ret == ERROR_SUCCESS )
228 *phDB = alloc_msihandle( &db->hdr );
229 if (! *phDB)
230 ret = ERROR_NOT_ENOUGH_MEMORY;
231 msiobj_release( &db->hdr );
234 return ret;
237 UINT WINAPI MsiOpenDatabaseA(LPCSTR szDBPath, LPCSTR szPersist, MSIHANDLE *phDB)
239 HRESULT r = ERROR_FUNCTION_FAILED;
240 LPWSTR szwDBPath = NULL, szwPersist = NULL;
242 TRACE("%s %s %p\n", debugstr_a(szDBPath), debugstr_a(szPersist), phDB);
244 if( szDBPath )
246 szwDBPath = strdupAtoW( szDBPath );
247 if( !szwDBPath )
248 goto end;
251 if( HIWORD(szPersist) )
253 szwPersist = strdupAtoW( szPersist );
254 if( !szwPersist )
255 goto end;
257 else
258 szwPersist = (LPWSTR)(DWORD_PTR)szPersist;
260 r = MsiOpenDatabaseW( szwDBPath, szwPersist, phDB );
262 end:
263 if( HIWORD(szPersist) )
264 msi_free( szwPersist );
265 msi_free( szwDBPath );
267 return r;
270 static LPWSTR msi_read_text_archive(LPCWSTR path)
272 HANDLE file;
273 LPSTR data = NULL;
274 LPWSTR wdata = NULL;
275 DWORD read, size = 0;
277 file = CreateFileW( path, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL );
278 if (file == INVALID_HANDLE_VALUE)
279 return NULL;
281 size = GetFileSize( file, NULL );
282 data = msi_alloc( size + 1 );
283 if (!data)
284 goto done;
286 if (!ReadFile( file, data, size, &read, NULL ))
287 goto done;
289 data[size] = '\0';
290 wdata = strdupAtoW( data );
292 done:
293 CloseHandle( file );
294 msi_free( data );
295 return wdata;
298 static void msi_parse_line(LPWSTR *line, LPWSTR **entries, DWORD *num_entries)
300 LPWSTR ptr = *line, save;
301 DWORD i, count = 1;
303 *entries = NULL;
305 /* stay on this line */
306 while (*ptr && *ptr != '\n')
308 /* entries are separated by tabs */
309 if (*ptr == '\t')
310 count++;
312 ptr++;
315 *entries = msi_alloc(count * sizeof(LPWSTR));
316 if (!*entries)
317 return;
319 /* store pointers into the data */
320 for (i = 0, ptr = *line; i < count; i++)
322 while (*ptr && *ptr == '\r') ptr++;
323 save = ptr;
325 while (*ptr && *ptr != '\t' && *ptr != '\n' && *ptr != '\r') ptr++;
327 /* NULL-separate the data */
328 if (*ptr == '\n' || *ptr == '\r')
330 while (*ptr == '\n' || *ptr == '\r')
331 *(ptr++) = '\0';
333 else if (*ptr)
334 *ptr++ = '\0';
336 (*entries)[i] = save;
339 /* move to the next line if there's more, else EOF */
340 *line = ptr;
342 if (num_entries)
343 *num_entries = count;
346 static LPWSTR msi_build_createsql_prelude(LPWSTR table)
348 LPWSTR prelude;
349 DWORD size;
351 static const WCHAR create_fmt[] = {'C','R','E','A','T','E',' ','T','A','B','L','E',' ','`','%','s','`',' ','(',' ',0};
353 size = sizeof(create_fmt)/sizeof(create_fmt[0]) + lstrlenW(table) - 2;
354 prelude = msi_alloc(size * sizeof(WCHAR));
355 if (!prelude)
356 return NULL;
358 sprintfW(prelude, create_fmt, table);
359 return prelude;
362 static LPWSTR msi_build_createsql_columns(LPWSTR *columns_data, LPWSTR *types, DWORD num_columns)
364 LPWSTR columns, p;
365 LPCWSTR type;
366 DWORD sql_size = 1, i, len;
367 WCHAR expanded[128], *ptr;
368 WCHAR size[10], comma[2], extra[30];
370 static const WCHAR column_fmt[] = {'`','%','s','`',' ','%','s','%','s','%','s','%','s',' ',0};
371 static const WCHAR size_fmt[] = {'(','%','s',')',0};
372 static const WCHAR type_char[] = {'C','H','A','R',0};
373 static const WCHAR type_int[] = {'I','N','T',0};
374 static const WCHAR type_long[] = {'L','O','N','G',0};
375 static const WCHAR type_object[] = {'O','B','J','E','C','T',0};
376 static const WCHAR type_notnull[] = {' ','N','O','T',' ','N','U','L','L',0};
377 static const WCHAR localizable[] = {' ','L','O','C','A','L','I','Z','A','B','L','E',0};
379 columns = msi_alloc_zero(sql_size * sizeof(WCHAR));
380 if (!columns)
381 return NULL;
383 for (i = 0; i < num_columns; i++)
385 type = NULL;
386 comma[1] = size[0] = extra[0] = '\0';
388 if (i == num_columns - 1)
389 comma[0] = '\0';
390 else
391 comma[0] = ',';
393 ptr = &types[i][1];
394 len = atolW(ptr);
395 extra[0] = '\0';
397 switch (types[i][0])
399 case 'l':
400 lstrcpyW(extra, type_notnull);
401 case 'L':
402 lstrcatW(extra, localizable);
403 type = type_char;
404 sprintfW(size, size_fmt, ptr);
405 break;
406 case 's':
407 lstrcpyW(extra, type_notnull);
408 case 'S':
409 type = type_char;
410 sprintfW(size, size_fmt, ptr);
411 break;
412 case 'i':
413 lstrcpyW(extra, type_notnull);
414 case 'I':
415 if (len <= 2)
416 type = type_int;
417 else if (len == 4)
418 type = type_long;
419 else
421 WARN("invalid int width %u\n", len);
422 msi_free(columns);
423 return NULL;
425 break;
426 case 'v':
427 lstrcpyW(extra, type_notnull);
428 case 'V':
429 type = type_object;
430 break;
431 default:
432 ERR("Unknown type: %c\n", types[i][0]);
433 msi_free(columns);
434 return NULL;
437 sprintfW(expanded, column_fmt, columns_data[i], type, size, extra, comma);
438 sql_size += lstrlenW(expanded);
440 p = msi_realloc(columns, sql_size * sizeof(WCHAR));
441 if (!p)
443 msi_free(columns);
444 return NULL;
446 columns = p;
448 lstrcatW(columns, expanded);
451 return columns;
454 static LPWSTR msi_build_createsql_postlude(LPWSTR *primary_keys, DWORD num_keys)
456 LPWSTR postlude, keys, ptr;
457 DWORD size, key_size, i;
459 static const WCHAR key_fmt[] = {'`','%','s','`',',',' ',0};
460 static const WCHAR postlude_fmt[] = {'P','R','I','M','A','R','Y',' ','K','E','Y',' ','%','s',')',0};
462 for (i = 0, size = 1; i < num_keys; i++)
463 size += lstrlenW(key_fmt) + lstrlenW(primary_keys[i]) - 2;
465 keys = msi_alloc(size * sizeof(WCHAR));
466 if (!keys)
467 return NULL;
469 for (i = 0, ptr = keys; i < num_keys; i++)
471 key_size = lstrlenW(key_fmt) + lstrlenW(primary_keys[i]) -2;
472 sprintfW(ptr, key_fmt, primary_keys[i]);
473 ptr += key_size;
476 /* remove final ', ' */
477 *(ptr - 2) = '\0';
479 size = lstrlenW(postlude_fmt) + size - 1;
480 postlude = msi_alloc(size * sizeof(WCHAR));
481 if (!postlude)
482 goto done;
484 sprintfW(postlude, postlude_fmt, keys);
486 done:
487 msi_free(keys);
488 return postlude;
491 static UINT msi_add_table_to_db(MSIDATABASE *db, LPWSTR *columns, LPWSTR *types, LPWSTR *labels, DWORD num_labels, DWORD num_columns)
493 UINT r;
494 DWORD size;
495 MSIQUERY *view;
496 LPWSTR create_sql;
497 LPWSTR prelude, columns_sql, postlude;
499 prelude = msi_build_createsql_prelude(labels[0]);
500 columns_sql = msi_build_createsql_columns(columns, types, num_columns);
501 postlude = msi_build_createsql_postlude(labels + 1, num_labels - 1); /* skip over table name */
503 if (!prelude || !columns_sql || !postlude)
504 return ERROR_OUTOFMEMORY;
506 size = lstrlenW(prelude) + lstrlenW(columns_sql) + lstrlenW(postlude) + 1;
507 create_sql = msi_alloc(size * sizeof(WCHAR));
508 if (!create_sql)
509 return ERROR_OUTOFMEMORY;
511 lstrcpyW(create_sql, prelude);
512 lstrcatW(create_sql, columns_sql);
513 lstrcatW(create_sql, postlude);
515 msi_free(prelude);
516 msi_free(columns_sql);
517 msi_free(postlude);
519 r = MSI_DatabaseOpenViewW( db, create_sql, &view );
520 msi_free(create_sql);
522 if (r != ERROR_SUCCESS)
523 return r;
525 r = MSI_ViewExecute(view, NULL);
526 MSI_ViewClose(view);
527 msiobj_release(&view->hdr);
529 return r;
532 static LPWSTR msi_import_stream_filename(LPCWSTR path, LPCWSTR name)
534 DWORD len;
535 LPWSTR fullname, ptr;
537 len = lstrlenW(path) + lstrlenW(name) + 1;
538 fullname = msi_alloc(len*sizeof(WCHAR));
539 if (!fullname)
540 return NULL;
542 lstrcpyW( fullname, path );
544 /* chop off extension from path */
545 ptr = strrchrW(fullname, '.');
546 if (!ptr)
548 msi_free (fullname);
549 return NULL;
551 *ptr++ = '\\';
552 lstrcpyW( ptr, name );
553 return fullname;
556 static UINT construct_record(DWORD num_columns, LPWSTR *types,
557 LPWSTR *data, LPWSTR path, MSIRECORD **rec)
559 UINT i;
561 *rec = MSI_CreateRecord(num_columns);
562 if (!*rec)
563 return ERROR_OUTOFMEMORY;
565 for (i = 0; i < num_columns; i++)
567 switch (types[i][0])
569 case 'L': case 'l': case 'S': case 's':
570 MSI_RecordSetStringW(*rec, i + 1, data[i]);
571 break;
572 case 'I': case 'i':
573 if (*data[i])
574 MSI_RecordSetInteger(*rec, i + 1, atoiW(data[i]));
575 break;
576 case 'V': case 'v':
577 if (*data[i])
579 UINT r;
580 LPWSTR file = msi_import_stream_filename(path, data[i]);
581 if (!file)
582 return ERROR_FUNCTION_FAILED;
584 r = MSI_RecordSetStreamFromFileW(*rec, i + 1, file);
585 msi_free (file);
586 if (r != ERROR_SUCCESS)
587 return ERROR_FUNCTION_FAILED;
589 break;
590 default:
591 ERR("Unhandled column type: %c\n", types[i][0]);
592 msiobj_release(&(*rec)->hdr);
593 return ERROR_FUNCTION_FAILED;
597 return ERROR_SUCCESS;
600 static UINT msi_add_records_to_table(MSIDATABASE *db, LPWSTR *columns, LPWSTR *types,
601 LPWSTR *labels, LPWSTR **records,
602 int num_columns, int num_records,
603 LPWSTR path)
605 UINT r;
606 int i;
607 MSIQUERY *view;
608 MSIRECORD *rec;
610 static const WCHAR select[] = {
611 'S','E','L','E','C','T',' ','*',' ',
612 'F','R','O','M',' ','`','%','s','`',0
615 r = MSI_OpenQuery(db, &view, select, labels[0]);
616 if (r != ERROR_SUCCESS)
617 return r;
619 while (MSI_ViewFetch(view, &rec) != ERROR_NO_MORE_ITEMS)
621 r = MSI_ViewModify(view, MSIMODIFY_DELETE, rec);
622 if (r != ERROR_SUCCESS)
623 goto done;
626 for (i = 0; i < num_records; i++)
628 r = construct_record(num_columns, types, records[i], path, &rec);
629 if (r != ERROR_SUCCESS)
630 goto done;
632 r = MSI_ViewModify(view, MSIMODIFY_INSERT, rec);
633 if (r != ERROR_SUCCESS)
635 msiobj_release(&rec->hdr);
636 goto done;
639 msiobj_release(&rec->hdr);
642 done:
643 msiobj_release(&view->hdr);
644 return r;
647 static UINT MSI_DatabaseImport(MSIDATABASE *db, LPCWSTR folder, LPCWSTR file)
649 UINT r;
650 DWORD len, i;
651 DWORD num_labels, num_types;
652 DWORD num_columns, num_records = 0;
653 LPWSTR *columns, *types, *labels;
654 LPWSTR path, ptr, data;
655 LPWSTR **records = NULL;
656 LPWSTR **temp_records;
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(szBackSlash) + lstrlenW(file) + 1;
667 path = msi_alloc( len * sizeof(WCHAR) );
668 if (!path)
669 return ERROR_OUTOFMEMORY;
671 lstrcpyW( path, folder );
672 lstrcatW( path, szBackSlash );
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 forcecodepage[] = {
880 '_','F','o','r','c','e','C','o','d','e','p','a','g','e',0 };
881 MSIRECORD *rec = NULL;
882 MSIQUERY *view = NULL;
883 LPWSTR filename;
884 HANDLE handle;
885 UINT len, r;
887 TRACE("%p %s %s %s\n", db, debugstr_w(table),
888 debugstr_w(folder), debugstr_w(file) );
890 if( folder == NULL || file == NULL )
891 return ERROR_INVALID_PARAMETER;
893 len = lstrlenW(folder) + lstrlenW(file) + 2;
894 filename = msi_alloc(len * sizeof (WCHAR));
895 if (!filename)
896 return ERROR_OUTOFMEMORY;
898 lstrcpyW( filename, folder );
899 lstrcatW( filename, szBackSlash );
900 lstrcatW( filename, file );
902 handle = CreateFileW( filename, GENERIC_READ | GENERIC_WRITE, 0,
903 NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );
904 msi_free( filename );
905 if (handle == INVALID_HANDLE_VALUE)
906 return ERROR_FUNCTION_FAILED;
908 if (!lstrcmpW( table, forcecodepage ))
910 r = msi_export_forcecodepage( handle );
911 goto done;
914 r = MSI_OpenQuery( db, &view, query, table );
915 if (r == ERROR_SUCCESS)
917 /* write out row 1, the column names */
918 r = MSI_ViewGetColumnInfo(view, MSICOLINFO_NAMES, &rec);
919 if (r == ERROR_SUCCESS)
921 msi_export_record( handle, rec, 1 );
922 msiobj_release( &rec->hdr );
925 /* write out row 2, the column types */
926 r = MSI_ViewGetColumnInfo(view, MSICOLINFO_TYPES, &rec);
927 if (r == ERROR_SUCCESS)
929 msi_export_record( handle, rec, 1 );
930 msiobj_release( &rec->hdr );
933 /* write out row 3, the table name + keys */
934 r = MSI_DatabaseGetPrimaryKeys( db, table, &rec );
935 if (r == ERROR_SUCCESS)
937 MSI_RecordSetStringW( rec, 0, table );
938 msi_export_record( handle, rec, 0 );
939 msiobj_release( &rec->hdr );
942 /* write out row 4 onwards, the data */
943 r = MSI_IterateRecords( view, 0, msi_export_row, handle );
944 msiobj_release( &view->hdr );
947 done:
948 CloseHandle( handle );
949 return r;
952 /***********************************************************************
953 * MsiExportDatabaseW [MSI.@]
955 * Writes a file containing the table data as tab separated ASCII.
957 * The format is as follows:
959 * row1 : colname1 <tab> colname2 <tab> .... colnameN <cr> <lf>
960 * row2 : coltype1 <tab> coltype2 <tab> .... coltypeN <cr> <lf>
961 * row3 : tablename <tab> key1 <tab> key2 <tab> ... keyM <cr> <lf>
963 * Followed by the data, starting at row 1 with one row per line
965 * row4 : data <tab> data <tab> data <tab> ... data <cr> <lf>
967 UINT WINAPI MsiDatabaseExportW( MSIHANDLE handle, LPCWSTR szTable,
968 LPCWSTR szFolder, LPCWSTR szFilename )
970 MSIDATABASE *db;
971 UINT r;
973 TRACE("%x %s %s %s\n", handle, debugstr_w(szTable),
974 debugstr_w(szFolder), debugstr_w(szFilename));
976 db = msihandle2msiinfo( handle, MSIHANDLETYPE_DATABASE );
977 if( !db )
979 IWineMsiRemoteDatabase *remote_database;
981 remote_database = (IWineMsiRemoteDatabase *)msi_get_remote( handle );
982 if ( !remote_database )
983 return ERROR_INVALID_HANDLE;
985 IWineMsiRemoteDatabase_Release( remote_database );
986 WARN("MsiDatabaseExport not allowed during a custom action!\n");
988 return ERROR_SUCCESS;
991 r = MSI_DatabaseExport( db, szTable, szFolder, szFilename );
992 msiobj_release( &db->hdr );
993 return r;
996 UINT WINAPI MsiDatabaseExportA( MSIHANDLE handle, LPCSTR szTable,
997 LPCSTR szFolder, LPCSTR szFilename )
999 LPWSTR path = NULL, file = NULL, table = NULL;
1000 UINT r = ERROR_OUTOFMEMORY;
1002 TRACE("%x %s %s %s\n", handle, debugstr_a(szTable),
1003 debugstr_a(szFolder), debugstr_a(szFilename));
1005 if( szTable )
1007 table = strdupAtoW( szTable );
1008 if( !table )
1009 goto end;
1012 if( szFolder )
1014 path = strdupAtoW( szFolder );
1015 if( !path )
1016 goto end;
1019 if( szFilename )
1021 file = strdupAtoW( szFilename );
1022 if( !file )
1023 goto end;
1026 r = MsiDatabaseExportW( handle, table, path, file );
1028 end:
1029 msi_free( table );
1030 msi_free( path );
1031 msi_free( file );
1033 return r;
1036 UINT WINAPI MsiDatabaseMergeA(MSIHANDLE hDatabase, MSIHANDLE hDatabaseMerge,
1037 LPCSTR szTableName)
1039 UINT r;
1040 LPWSTR table;
1042 TRACE("(%d, %d, %s)\n", hDatabase, hDatabaseMerge,
1043 debugstr_a(szTableName));
1045 table = strdupAtoW(szTableName);
1046 r = MsiDatabaseMergeW(hDatabase, hDatabaseMerge, table);
1048 msi_free(table);
1049 return r;
1052 typedef struct _tagMERGETABLE
1054 struct list entry;
1055 struct list rows;
1056 LPWSTR name;
1057 DWORD numconflicts;
1058 LPWSTR *columns;
1059 DWORD numcolumns;
1060 LPWSTR *types;
1061 DWORD numtypes;
1062 LPWSTR *labels;
1063 DWORD numlabels;
1064 } MERGETABLE;
1066 typedef struct _tagMERGEROW
1068 struct list entry;
1069 MSIRECORD *data;
1070 } MERGEROW;
1072 typedef struct _tagMERGEDATA
1074 MSIDATABASE *db;
1075 MSIDATABASE *merge;
1076 MERGETABLE *curtable;
1077 MSIQUERY *curview;
1078 struct list *tabledata;
1079 } MERGEDATA;
1081 static UINT merge_verify_colnames(MSIQUERY *dbview, MSIQUERY *mergeview)
1083 MSIRECORD *dbrec, *mergerec;
1084 UINT r, i, count;
1086 r = MSI_ViewGetColumnInfo(dbview, MSICOLINFO_NAMES, &dbrec);
1087 if (r != ERROR_SUCCESS)
1088 return r;
1090 r = MSI_ViewGetColumnInfo(mergeview, MSICOLINFO_NAMES, &mergerec);
1091 if (r != ERROR_SUCCESS)
1092 return r;
1094 count = MSI_RecordGetFieldCount(dbrec);
1095 for (i = 1; i <= count; i++)
1097 if (!MSI_RecordGetString(mergerec, i))
1098 break;
1100 if (lstrcmpW(MSI_RecordGetString(dbrec, i),
1101 MSI_RecordGetString(mergerec, i)))
1103 r = ERROR_DATATYPE_MISMATCH;
1104 goto done;
1108 msiobj_release(&dbrec->hdr);
1109 msiobj_release(&mergerec->hdr);
1110 dbrec = mergerec = NULL;
1112 r = MSI_ViewGetColumnInfo(dbview, MSICOLINFO_TYPES, &dbrec);
1113 if (r != ERROR_SUCCESS)
1114 return r;
1116 r = MSI_ViewGetColumnInfo(mergeview, MSICOLINFO_TYPES, &mergerec);
1117 if (r != ERROR_SUCCESS)
1118 return r;
1120 count = MSI_RecordGetFieldCount(dbrec);
1121 for (i = 1; i <= count; i++)
1123 if (!MSI_RecordGetString(mergerec, i))
1124 break;
1126 if (lstrcmpW(MSI_RecordGetString(dbrec, i),
1127 MSI_RecordGetString(mergerec, i)))
1129 r = ERROR_DATATYPE_MISMATCH;
1130 break;
1134 done:
1135 msiobj_release(&dbrec->hdr);
1136 msiobj_release(&mergerec->hdr);
1138 return r;
1141 static UINT merge_verify_primary_keys(MSIDATABASE *db, MSIDATABASE *mergedb,
1142 LPCWSTR table)
1144 MSIRECORD *dbrec, *mergerec = NULL;
1145 UINT r, i, count;
1147 r = MSI_DatabaseGetPrimaryKeys(db, table, &dbrec);
1148 if (r != ERROR_SUCCESS)
1149 return r;
1151 r = MSI_DatabaseGetPrimaryKeys(mergedb, table, &mergerec);
1152 if (r != ERROR_SUCCESS)
1153 goto done;
1155 count = MSI_RecordGetFieldCount(dbrec);
1156 if (count != MSI_RecordGetFieldCount(mergerec))
1158 r = ERROR_DATATYPE_MISMATCH;
1159 goto done;
1162 for (i = 1; i <= count; i++)
1164 if (lstrcmpW(MSI_RecordGetString(dbrec, i),
1165 MSI_RecordGetString(mergerec, i)))
1167 r = ERROR_DATATYPE_MISMATCH;
1168 goto done;
1172 done:
1173 msiobj_release(&dbrec->hdr);
1174 msiobj_release(&mergerec->hdr);
1176 return r;
1179 static LPWSTR get_key_value(MSIQUERY *view, LPCWSTR key, MSIRECORD *rec)
1181 MSIRECORD *colnames;
1182 LPWSTR str, val;
1183 UINT r, i = 0, sz = 0;
1184 int cmp;
1186 r = MSI_ViewGetColumnInfo(view, MSICOLINFO_NAMES, &colnames);
1187 if (r != ERROR_SUCCESS)
1188 return NULL;
1192 str = msi_dup_record_field(colnames, ++i);
1193 cmp = lstrcmpW(key, str);
1194 msi_free(str);
1195 } while (cmp);
1197 msiobj_release(&colnames->hdr);
1199 r = MSI_RecordGetStringW(rec, i, NULL, &sz);
1200 if (r != ERROR_SUCCESS)
1201 return NULL;
1202 sz++;
1204 if (MSI_RecordGetString(rec, i)) /* check record field is a string */
1206 /* quote string record fields */
1207 const WCHAR szQuote[] = {'\'', 0};
1208 sz += 2;
1209 val = msi_alloc(sz*sizeof(WCHAR));
1210 if (!val)
1211 return NULL;
1213 lstrcpyW(val, szQuote);
1214 r = MSI_RecordGetStringW(rec, i, val+1, &sz);
1215 lstrcpyW(val+1+sz, szQuote);
1217 else
1219 /* do not quote integer record fields */
1220 val = msi_alloc(sz*sizeof(WCHAR));
1221 if (!val)
1222 return NULL;
1224 r = MSI_RecordGetStringW(rec, i, val, &sz);
1227 if (r != ERROR_SUCCESS)
1229 ERR("failed to get string!\n");
1230 msi_free(val);
1231 return NULL;
1234 return val;
1237 static LPWSTR create_diff_row_query(MSIDATABASE *merge, MSIQUERY *view,
1238 LPWSTR table, MSIRECORD *rec)
1240 LPWSTR query = NULL, clause = NULL;
1241 LPWSTR ptr = NULL, val;
1242 LPCWSTR setptr;
1243 DWORD size = 1, oldsize;
1244 LPCWSTR key;
1245 MSIRECORD *keys;
1246 UINT r, i, count;
1248 static const WCHAR keyset[] = {
1249 '`','%','s','`',' ','=',' ','%','s',' ','A','N','D',' ',0};
1250 static const WCHAR lastkeyset[] = {
1251 '`','%','s','`',' ','=',' ','%','s',' ',0};
1252 static const WCHAR fmt[] = {'S','E','L','E','C','T',' ','*',' ',
1253 'F','R','O','M',' ','`','%','s','`',' ',
1254 'W','H','E','R','E',' ','%','s',0};
1256 r = MSI_DatabaseGetPrimaryKeys(merge, table, &keys);
1257 if (r != ERROR_SUCCESS)
1258 return NULL;
1260 clause = msi_alloc_zero(size * sizeof(WCHAR));
1261 if (!clause)
1262 goto done;
1264 ptr = clause;
1265 count = MSI_RecordGetFieldCount(keys);
1266 for (i = 1; i <= count; i++)
1268 key = MSI_RecordGetString(keys, i);
1269 val = get_key_value(view, key, rec);
1271 if (i == count)
1272 setptr = lastkeyset;
1273 else
1274 setptr = keyset;
1276 oldsize = size;
1277 size += lstrlenW(setptr) + lstrlenW(key) + lstrlenW(val) - 4;
1278 clause = msi_realloc(clause, size * sizeof (WCHAR));
1279 if (!clause)
1281 msi_free(val);
1282 goto done;
1285 ptr = clause + oldsize - 1;
1286 sprintfW(ptr, setptr, key, val);
1287 msi_free(val);
1290 size = lstrlenW(fmt) + lstrlenW(table) + lstrlenW(clause) + 1;
1291 query = msi_alloc(size * sizeof(WCHAR));
1292 if (!query)
1293 goto done;
1295 sprintfW(query, fmt, table, clause);
1297 done:
1298 msi_free(clause);
1299 msiobj_release(&keys->hdr);
1300 return query;
1303 static UINT merge_diff_row(MSIRECORD *rec, LPVOID param)
1305 MERGEDATA *data = param;
1306 MERGETABLE *table = data->curtable;
1307 MERGEROW *mergerow;
1308 MSIQUERY *dbview = NULL;
1309 MSIRECORD *row = NULL;
1310 LPWSTR query = NULL;
1311 UINT r = ERROR_SUCCESS;
1313 if (TABLE_Exists(data->db, table->name))
1315 query = create_diff_row_query(data->merge, data->curview, table->name, rec);
1316 if (!query)
1317 return ERROR_OUTOFMEMORY;
1319 r = MSI_DatabaseOpenViewW(data->db, query, &dbview);
1320 if (r != ERROR_SUCCESS)
1321 goto done;
1323 r = MSI_ViewExecute(dbview, NULL);
1324 if (r != ERROR_SUCCESS)
1325 goto done;
1327 r = MSI_ViewFetch(dbview, &row);
1328 if (r == ERROR_SUCCESS && !MSI_RecordsAreEqual(rec, row))
1330 table->numconflicts++;
1331 goto done;
1333 else if (r != ERROR_NO_MORE_ITEMS)
1334 goto done;
1337 mergerow = msi_alloc(sizeof(MERGEROW));
1338 if (!mergerow)
1340 r = ERROR_OUTOFMEMORY;
1341 goto done;
1344 mergerow->data = MSI_CloneRecord(rec);
1345 if (!mergerow->data)
1347 r = ERROR_OUTOFMEMORY;
1348 msi_free(mergerow);
1349 goto done;
1352 list_add_tail(&table->rows, &mergerow->entry);
1354 done:
1355 msi_free(query);
1356 msiobj_release(&row->hdr);
1357 msiobj_release(&dbview->hdr);
1358 return r;
1361 static UINT msi_get_table_labels(MSIDATABASE *db, LPCWSTR table, LPWSTR **labels, DWORD *numlabels)
1363 UINT r, i, count;
1364 MSIRECORD *prec = NULL;
1366 r = MSI_DatabaseGetPrimaryKeys(db, table, &prec);
1367 if (r != ERROR_SUCCESS)
1368 return r;
1370 count = MSI_RecordGetFieldCount(prec);
1371 *numlabels = count + 1;
1372 *labels = msi_alloc((*numlabels)*sizeof(LPWSTR));
1373 if (!*labels)
1375 r = ERROR_OUTOFMEMORY;
1376 goto end;
1379 (*labels)[0] = strdupW(table);
1380 for (i=1; i<=count; i++ )
1382 (*labels)[i] = strdupW(MSI_RecordGetString(prec, i));
1385 end:
1386 msiobj_release( &prec->hdr );
1387 return r;
1390 static UINT msi_get_query_columns(MSIQUERY *query, LPWSTR **columns, DWORD *numcolumns)
1392 UINT r, i, count;
1393 MSIRECORD *prec = NULL;
1395 r = MSI_ViewGetColumnInfo(query, MSICOLINFO_NAMES, &prec);
1396 if (r != ERROR_SUCCESS)
1397 return r;
1399 count = MSI_RecordGetFieldCount(prec);
1400 *columns = msi_alloc(count*sizeof(LPWSTR));
1401 if (!*columns)
1403 r = ERROR_OUTOFMEMORY;
1404 goto end;
1407 for (i=1; i<=count; i++ )
1409 (*columns)[i-1] = strdupW(MSI_RecordGetString(prec, i));
1412 *numcolumns = count;
1414 end:
1415 msiobj_release( &prec->hdr );
1416 return r;
1419 static UINT msi_get_query_types(MSIQUERY *query, LPWSTR **types, DWORD *numtypes)
1421 UINT r, i, count;
1422 MSIRECORD *prec = NULL;
1424 r = MSI_ViewGetColumnInfo(query, MSICOLINFO_TYPES, &prec);
1425 if (r != ERROR_SUCCESS)
1426 return r;
1428 count = MSI_RecordGetFieldCount(prec);
1429 *types = msi_alloc(count*sizeof(LPWSTR));
1430 if (!*types)
1432 r = ERROR_OUTOFMEMORY;
1433 goto end;
1436 for (i=1; i<=count; i++ )
1438 (*types)[i-1] = strdupW(MSI_RecordGetString(prec, i));
1441 end:
1442 msiobj_release( &prec->hdr );
1443 return r;
1446 static void merge_free_rows(MERGETABLE *table)
1448 struct list *item, *cursor;
1450 LIST_FOR_EACH_SAFE(item, cursor, &table->rows)
1452 MERGEROW *row = LIST_ENTRY(item, MERGEROW, entry);
1454 list_remove(&row->entry);
1455 msiobj_release(&row->data->hdr);
1456 msi_free(row);
1460 static void free_merge_table(MERGETABLE *table)
1462 UINT i;
1464 if (table->labels != NULL)
1466 for (i = 0; i < table->numlabels; i++)
1467 msi_free(table->labels[i]);
1468 msi_free(table->labels);
1471 if (table->columns != NULL)
1473 for (i = 0; i < table->numcolumns; i++)
1474 msi_free(table->columns[i]);
1475 msi_free(table->columns);
1478 if (table->types != NULL)
1480 for (i = 0; i < table->numtypes; i++)
1481 msi_free(table->types[i]);
1482 msi_free(table->types);
1484 msi_free(table->name);
1485 merge_free_rows(table);
1487 msi_free(table);
1490 static UINT msi_get_merge_table (MSIDATABASE *db, LPCWSTR name, MERGETABLE **ptable)
1492 UINT r;
1493 MERGETABLE *table;
1494 MSIQUERY *mergeview = NULL;
1496 static const WCHAR query[] = {'S','E','L','E','C','T',' ','*',' ',
1497 'F','R','O','M',' ','`','%','s','`',0};
1499 table = msi_alloc_zero(sizeof(MERGETABLE));
1500 if (!table)
1502 *ptable = NULL;
1503 return ERROR_OUTOFMEMORY;
1506 r = msi_get_table_labels(db, name, &table->labels, &table->numlabels);
1507 if (r != ERROR_SUCCESS)
1508 goto err;
1510 r = MSI_OpenQuery(db, &mergeview, query, name);
1511 if (r != ERROR_SUCCESS)
1512 goto err;
1514 r = msi_get_query_columns(mergeview, &table->columns, &table->numcolumns);
1515 if (r != ERROR_SUCCESS)
1516 goto err;
1518 r = msi_get_query_types(mergeview, &table->types, &table->numtypes);
1519 if (r != ERROR_SUCCESS)
1520 goto err;
1522 list_init(&table->rows);
1524 table->name = strdupW(name);
1525 table->numconflicts = 0;
1527 msiobj_release(&mergeview->hdr);
1528 *ptable = table;
1529 return ERROR_SUCCESS;
1531 err:
1532 msiobj_release(&mergeview->hdr);
1533 free_merge_table(table);
1534 *ptable = NULL;
1535 return r;
1538 static UINT merge_diff_tables(MSIRECORD *rec, LPVOID param)
1540 MERGEDATA *data = param;
1541 MERGETABLE *table;
1542 MSIQUERY *dbview = NULL;
1543 MSIQUERY *mergeview = NULL;
1544 LPCWSTR name;
1545 UINT r;
1547 static const WCHAR query[] = {'S','E','L','E','C','T',' ','*',' ',
1548 'F','R','O','M',' ','`','%','s','`',0};
1550 name = MSI_RecordGetString(rec, 1);
1552 r = MSI_OpenQuery(data->merge, &mergeview, query, name);
1553 if (r != ERROR_SUCCESS)
1554 goto done;
1556 if (TABLE_Exists(data->db, name))
1558 r = MSI_OpenQuery(data->db, &dbview, query, name);
1559 if (r != ERROR_SUCCESS)
1560 goto done;
1562 r = merge_verify_colnames(dbview, mergeview);
1563 if (r != ERROR_SUCCESS)
1564 goto done;
1566 r = merge_verify_primary_keys(data->db, data->merge, name);
1567 if (r != ERROR_SUCCESS)
1568 goto done;
1571 r = msi_get_merge_table(data->merge, name, &table);
1572 if (r != ERROR_SUCCESS)
1573 goto done;
1575 data->curtable = table;
1576 data->curview = mergeview;
1577 r = MSI_IterateRecords(mergeview, NULL, merge_diff_row, data);
1578 if (r != ERROR_SUCCESS)
1580 free_merge_table(table);
1581 goto done;
1584 list_add_tail(data->tabledata, &table->entry);
1586 done:
1587 msiobj_release(&dbview->hdr);
1588 msiobj_release(&mergeview->hdr);
1589 return r;
1592 static UINT gather_merge_data(MSIDATABASE *db, MSIDATABASE *merge,
1593 struct list *tabledata)
1595 UINT r;
1596 MSIQUERY *view;
1597 MERGEDATA data;
1599 static const WCHAR query[] = {'S','E','L','E','C','T',' ','*',' ',
1600 'F','R','O','M',' ','`','_','T','a','b','l','e','s','`',0};
1602 r = MSI_DatabaseOpenViewW(merge, query, &view);
1603 if (r != ERROR_SUCCESS)
1604 return r;
1606 data.db = db;
1607 data.merge = merge;
1608 data.tabledata = tabledata;
1609 r = MSI_IterateRecords(view, NULL, merge_diff_tables, &data);
1611 msiobj_release(&view->hdr);
1612 return r;
1615 static UINT merge_table(MSIDATABASE *db, MERGETABLE *table)
1617 UINT r;
1618 MERGEROW *row;
1619 MSIVIEW *tv;
1621 if (!TABLE_Exists(db, table->name))
1623 r = msi_add_table_to_db(db, table->columns, table->types,
1624 table->labels, table->numlabels, table->numcolumns);
1625 if (r != ERROR_SUCCESS)
1626 return ERROR_FUNCTION_FAILED;
1629 LIST_FOR_EACH_ENTRY(row, &table->rows, MERGEROW, entry)
1631 r = TABLE_CreateView(db, table->name, &tv);
1632 if (r != ERROR_SUCCESS)
1633 return r;
1635 r = tv->ops->insert_row(tv, row->data, -1, FALSE);
1636 tv->ops->delete(tv);
1638 if (r != ERROR_SUCCESS)
1639 return r;
1642 return ERROR_SUCCESS;
1645 static UINT update_merge_errors(MSIDATABASE *db, LPCWSTR error,
1646 LPWSTR table, DWORD numconflicts)
1648 UINT r;
1649 MSIQUERY *view;
1651 static const WCHAR create[] = {
1652 'C','R','E','A','T','E',' ','T','A','B','L','E',' ',
1653 '`','%','s','`',' ','(','`','T','a','b','l','e','`',' ',
1654 'C','H','A','R','(','2','5','5',')',' ','N','O','T',' ',
1655 'N','U','L','L',',',' ','`','N','u','m','R','o','w','M','e','r','g','e',
1656 'C','o','n','f','l','i','c','t','s','`',' ','S','H','O','R','T',' ',
1657 'N','O','T',' ','N','U','L','L',' ','P','R','I','M','A','R','Y',' ',
1658 'K','E','Y',' ','`','T','a','b','l','e','`',')',0};
1659 static const WCHAR insert[] = {
1660 'I','N','S','E','R','T',' ','I','N','T','O',' ',
1661 '`','%','s','`',' ','(','`','T','a','b','l','e','`',',',' ',
1662 '`','N','u','m','R','o','w','M','e','r','g','e',
1663 'C','o','n','f','l','i','c','t','s','`',')',' ','V','A','L','U','E','S',
1664 ' ','(','\'','%','s','\'',',',' ','%','d',')',0};
1666 if (!TABLE_Exists(db, error))
1668 r = MSI_OpenQuery(db, &view, create, error);
1669 if (r != ERROR_SUCCESS)
1670 return r;
1672 r = MSI_ViewExecute(view, NULL);
1673 msiobj_release(&view->hdr);
1674 if (r != ERROR_SUCCESS)
1675 return r;
1678 r = MSI_OpenQuery(db, &view, insert, error, table, numconflicts);
1679 if (r != ERROR_SUCCESS)
1680 return r;
1682 r = MSI_ViewExecute(view, NULL);
1683 msiobj_release(&view->hdr);
1684 return r;
1687 UINT WINAPI MsiDatabaseMergeW(MSIHANDLE hDatabase, MSIHANDLE hDatabaseMerge,
1688 LPCWSTR szTableName)
1690 struct list tabledata = LIST_INIT(tabledata);
1691 struct list *item, *cursor;
1692 MSIDATABASE *db, *merge;
1693 MERGETABLE *table;
1694 BOOL conflicts;
1695 UINT r;
1697 TRACE("(%d, %d, %s)\n", hDatabase, hDatabaseMerge,
1698 debugstr_w(szTableName));
1700 if (szTableName && !*szTableName)
1701 return ERROR_INVALID_TABLE;
1703 db = msihandle2msiinfo(hDatabase, MSIHANDLETYPE_DATABASE);
1704 merge = msihandle2msiinfo(hDatabaseMerge, MSIHANDLETYPE_DATABASE);
1705 if (!db || !merge)
1707 r = ERROR_INVALID_HANDLE;
1708 goto done;
1711 r = gather_merge_data(db, merge, &tabledata);
1712 if (r != ERROR_SUCCESS)
1713 goto done;
1715 conflicts = FALSE;
1716 LIST_FOR_EACH_ENTRY(table, &tabledata, MERGETABLE, entry)
1718 if (table->numconflicts)
1720 conflicts = TRUE;
1722 r = update_merge_errors(db, szTableName, table->name,
1723 table->numconflicts);
1724 if (r != ERROR_SUCCESS)
1725 break;
1727 else
1729 r = merge_table(db, table);
1730 if (r != ERROR_SUCCESS)
1731 break;
1735 LIST_FOR_EACH_SAFE(item, cursor, &tabledata)
1737 MERGETABLE *table = LIST_ENTRY(item, MERGETABLE, entry);
1739 list_remove(&table->entry);
1740 free_merge_table(table);
1743 if (conflicts)
1744 r = ERROR_FUNCTION_FAILED;
1746 done:
1747 msiobj_release(&db->hdr);
1748 msiobj_release(&merge->hdr);
1749 return r;
1752 MSIDBSTATE WINAPI MsiGetDatabaseState( MSIHANDLE handle )
1754 MSIDBSTATE ret = MSIDBSTATE_READ;
1755 MSIDATABASE *db;
1757 TRACE("%d\n", handle);
1759 db = msihandle2msiinfo( handle, MSIHANDLETYPE_DATABASE );
1760 if( !db )
1762 IWineMsiRemoteDatabase *remote_database;
1764 remote_database = (IWineMsiRemoteDatabase *)msi_get_remote( handle );
1765 if ( !remote_database )
1766 return MSIDBSTATE_ERROR;
1768 IWineMsiRemoteDatabase_Release( remote_database );
1769 WARN("MsiGetDatabaseState not allowed during a custom action!\n");
1771 return MSIDBSTATE_READ;
1774 if (db->mode != MSIDBOPEN_READONLY )
1775 ret = MSIDBSTATE_WRITE;
1776 msiobj_release( &db->hdr );
1778 return ret;
1781 typedef struct _msi_remote_database_impl {
1782 const IWineMsiRemoteDatabaseVtbl *lpVtbl;
1783 MSIHANDLE database;
1784 LONG refs;
1785 } msi_remote_database_impl;
1787 static inline msi_remote_database_impl* mrd_from_IWineMsiRemoteDatabase( IWineMsiRemoteDatabase* iface )
1789 return (msi_remote_database_impl *)iface;
1792 static HRESULT WINAPI mrd_QueryInterface( IWineMsiRemoteDatabase *iface,
1793 REFIID riid,LPVOID *ppobj)
1795 if( IsEqualCLSID( riid, &IID_IUnknown ) ||
1796 IsEqualCLSID( riid, &IID_IWineMsiRemoteDatabase ) )
1798 IUnknown_AddRef( iface );
1799 *ppobj = iface;
1800 return S_OK;
1803 return E_NOINTERFACE;
1806 static ULONG WINAPI mrd_AddRef( IWineMsiRemoteDatabase *iface )
1808 msi_remote_database_impl* This = mrd_from_IWineMsiRemoteDatabase( iface );
1810 return InterlockedIncrement( &This->refs );
1813 static ULONG WINAPI mrd_Release( IWineMsiRemoteDatabase *iface )
1815 msi_remote_database_impl* This = mrd_from_IWineMsiRemoteDatabase( iface );
1816 ULONG r;
1818 r = InterlockedDecrement( &This->refs );
1819 if (r == 0)
1821 MsiCloseHandle( This->database );
1822 msi_free( This );
1824 return r;
1827 static HRESULT WINAPI mrd_IsTablePersistent( IWineMsiRemoteDatabase *iface,
1828 BSTR table, MSICONDITION *persistent )
1830 msi_remote_database_impl *This = mrd_from_IWineMsiRemoteDatabase( iface );
1831 *persistent = MsiDatabaseIsTablePersistentW(This->database, table);
1832 return S_OK;
1835 static HRESULT WINAPI mrd_GetPrimaryKeys( IWineMsiRemoteDatabase *iface,
1836 BSTR table, MSIHANDLE *keys )
1838 msi_remote_database_impl *This = mrd_from_IWineMsiRemoteDatabase( iface );
1839 UINT r = MsiDatabaseGetPrimaryKeysW(This->database, table, keys);
1840 return HRESULT_FROM_WIN32(r);
1843 static HRESULT WINAPI mrd_GetSummaryInformation( IWineMsiRemoteDatabase *iface,
1844 UINT updatecount, MSIHANDLE *suminfo )
1846 msi_remote_database_impl *This = mrd_from_IWineMsiRemoteDatabase( iface );
1847 UINT r = MsiGetSummaryInformationW(This->database, NULL, updatecount, suminfo);
1848 return HRESULT_FROM_WIN32(r);
1851 static HRESULT WINAPI mrd_OpenView( IWineMsiRemoteDatabase *iface,
1852 BSTR query, MSIHANDLE *view )
1854 msi_remote_database_impl *This = mrd_from_IWineMsiRemoteDatabase( iface );
1855 UINT r = MsiDatabaseOpenViewW(This->database, query, view);
1856 return HRESULT_FROM_WIN32(r);
1859 static HRESULT WINAPI mrd_SetMsiHandle( IWineMsiRemoteDatabase *iface, MSIHANDLE handle )
1861 msi_remote_database_impl* This = mrd_from_IWineMsiRemoteDatabase( iface );
1862 This->database = handle;
1863 return S_OK;
1866 static const IWineMsiRemoteDatabaseVtbl msi_remote_database_vtbl =
1868 mrd_QueryInterface,
1869 mrd_AddRef,
1870 mrd_Release,
1871 mrd_IsTablePersistent,
1872 mrd_GetPrimaryKeys,
1873 mrd_GetSummaryInformation,
1874 mrd_OpenView,
1875 mrd_SetMsiHandle,
1878 HRESULT create_msi_remote_database( IUnknown *pOuter, LPVOID *ppObj )
1880 msi_remote_database_impl *This;
1882 This = msi_alloc( sizeof *This );
1883 if (!This)
1884 return E_OUTOFMEMORY;
1886 This->lpVtbl = &msi_remote_database_vtbl;
1887 This->database = 0;
1888 This->refs = 1;
1890 *ppObj = This;
1892 return S_OK;