services: Check for services without lpBinaryPathName in get_winedevice_process.
[wine.git] / dlls / msi / database.c
blob32e5a6353506f091b21bb9fe84cafece52c0abb3
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>
22 #include <stdio.h>
24 #define COBJMACROS
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 #define IS_INTMSIDBOPEN(x) (((ULONG_PTR)(x) >> 16) == 0)
56 static void free_transforms( MSIDATABASE *db )
58 while( !list_empty( &db->transforms ) )
60 MSITRANSFORM *t = LIST_ENTRY( list_head( &db->transforms ), MSITRANSFORM, entry );
61 list_remove( &t->entry );
62 IStorage_Release( t->stg );
63 msi_free( t );
67 static void free_streams( MSIDATABASE *db )
69 UINT i;
70 for (i = 0; i < db->num_streams; i++)
72 if (db->streams[i].stream) IStream_Release( db->streams[i].stream );
74 msi_free( db->streams );
77 void append_storage_to_db( MSIDATABASE *db, IStorage *stg )
79 MSITRANSFORM *t;
81 t = msi_alloc( sizeof *t );
82 t->stg = stg;
83 IStorage_AddRef( stg );
84 list_add_head( &db->transforms, &t->entry );
87 static VOID MSI_CloseDatabase( MSIOBJECTHDR *arg )
89 MSIDATABASE *db = (MSIDATABASE *) arg;
91 msi_free(db->path);
92 free_streams( db );
93 free_cached_tables( db );
94 free_transforms( db );
95 if (db->strings) msi_destroy_stringtable( db->strings );
96 IStorage_Release( db->storage );
97 if (db->deletefile)
99 DeleteFileW( db->deletefile );
100 msi_free( db->deletefile );
102 msi_free( db->tempfolder );
105 static HRESULT db_initialize( IStorage *stg, const GUID *clsid )
107 static const WCHAR szTables[] = { '_','T','a','b','l','e','s',0 };
108 HRESULT hr;
110 hr = IStorage_SetClass( stg, clsid );
111 if (FAILED( hr ))
113 WARN("failed to set class id 0x%08x\n", hr);
114 return hr;
117 /* create the _Tables stream */
118 hr = write_stream_data( stg, szTables, NULL, 0, TRUE );
119 if (FAILED( hr ))
121 WARN("failed to create _Tables stream 0x%08x\n", hr);
122 return hr;
125 hr = msi_init_string_table( stg );
126 if (FAILED( hr ))
128 WARN("failed to initialize string table 0x%08x\n", hr);
129 return hr;
132 hr = IStorage_Commit( stg, 0 );
133 if (FAILED( hr ))
135 WARN("failed to commit changes 0x%08x\n", hr);
136 return hr;
139 return S_OK;
142 UINT MSI_OpenDatabaseW(LPCWSTR szDBPath, LPCWSTR szPersist, MSIDATABASE **pdb)
144 IStorage *stg = NULL;
145 HRESULT r;
146 MSIDATABASE *db = NULL;
147 UINT ret = ERROR_FUNCTION_FAILED;
148 LPCWSTR szMode, save_path;
149 STATSTG stat;
150 BOOL created = FALSE, patch = FALSE;
151 WCHAR path[MAX_PATH];
153 TRACE("%s %s\n",debugstr_w(szDBPath),debugstr_w(szPersist) );
155 if( !pdb )
156 return ERROR_INVALID_PARAMETER;
158 if (szPersist - MSIDBOPEN_PATCHFILE <= MSIDBOPEN_CREATEDIRECT)
160 TRACE("Database is a patch\n");
161 szPersist -= MSIDBOPEN_PATCHFILE;
162 patch = TRUE;
165 save_path = szDBPath;
166 szMode = szPersist;
167 if( !IS_INTMSIDBOPEN(szPersist) )
169 if (!CopyFileW( szDBPath, szPersist, FALSE ))
170 return ERROR_OPEN_FAILED;
172 szDBPath = szPersist;
173 szPersist = MSIDBOPEN_TRANSACT;
174 created = TRUE;
177 if( szPersist == MSIDBOPEN_READONLY )
179 r = StgOpenStorage( szDBPath, NULL,
180 STGM_DIRECT|STGM_READ|STGM_SHARE_DENY_WRITE, NULL, 0, &stg);
182 else if( szPersist == MSIDBOPEN_CREATE )
184 r = StgCreateDocfile( szDBPath,
185 STGM_CREATE|STGM_TRANSACTED|STGM_READWRITE|STGM_SHARE_EXCLUSIVE, 0, &stg );
187 if( SUCCEEDED(r) )
188 r = db_initialize( stg, patch ? &CLSID_MsiPatch : &CLSID_MsiDatabase );
189 created = TRUE;
191 else if( szPersist == MSIDBOPEN_CREATEDIRECT )
193 r = StgCreateDocfile( szDBPath,
194 STGM_CREATE|STGM_DIRECT|STGM_READWRITE|STGM_SHARE_EXCLUSIVE, 0, &stg );
196 if( SUCCEEDED(r) )
197 r = db_initialize( stg, patch ? &CLSID_MsiPatch : &CLSID_MsiDatabase );
198 created = TRUE;
200 else if( szPersist == MSIDBOPEN_TRANSACT )
202 r = StgOpenStorage( szDBPath, NULL,
203 STGM_TRANSACTED|STGM_READWRITE|STGM_SHARE_DENY_WRITE, NULL, 0, &stg);
205 else if( szPersist == MSIDBOPEN_DIRECT )
207 r = StgOpenStorage( szDBPath, NULL,
208 STGM_DIRECT|STGM_READWRITE|STGM_SHARE_EXCLUSIVE, NULL, 0, &stg);
210 else
212 ERR("unknown flag %p\n",szPersist);
213 return ERROR_INVALID_PARAMETER;
216 if( FAILED( r ) || !stg )
218 WARN("open failed r = %08x for %s\n", r, debugstr_w(szDBPath));
219 return ERROR_FUNCTION_FAILED;
222 r = IStorage_Stat( stg, &stat, STATFLAG_NONAME );
223 if( FAILED( r ) )
225 FIXME("Failed to stat storage\n");
226 goto end;
229 if ( !IsEqualGUID( &stat.clsid, &CLSID_MsiDatabase ) &&
230 !IsEqualGUID( &stat.clsid, &CLSID_MsiPatch ) &&
231 !IsEqualGUID( &stat.clsid, &CLSID_MsiTransform ) )
233 ERR("storage GUID is not a MSI database GUID %s\n",
234 debugstr_guid(&stat.clsid) );
235 goto end;
238 if ( patch && !IsEqualGUID( &stat.clsid, &CLSID_MsiPatch ) )
240 ERR("storage GUID is not the MSI patch GUID %s\n",
241 debugstr_guid(&stat.clsid) );
242 ret = ERROR_OPEN_FAILED;
243 goto end;
246 db = alloc_msiobject( MSIHANDLETYPE_DATABASE, sizeof (MSIDATABASE),
247 MSI_CloseDatabase );
248 if( !db )
250 FIXME("Failed to allocate a handle\n");
251 goto end;
254 if (!strchrW( save_path, '\\' ))
256 GetCurrentDirectoryW( MAX_PATH, path );
257 lstrcatW( path, szBackSlash );
258 lstrcatW( path, save_path );
260 else
261 lstrcpyW( path, save_path );
263 db->path = strdupW( path );
264 db->media_transform_offset = MSI_INITIAL_MEDIA_TRANSFORM_OFFSET;
265 db->media_transform_disk_id = MSI_INITIAL_MEDIA_TRANSFORM_DISKID;
267 if( TRACE_ON( msi ) )
268 enum_stream_names( stg );
270 db->storage = stg;
271 db->mode = szMode;
272 if (created)
273 db->deletefile = strdupW( szDBPath );
274 list_init( &db->tables );
275 list_init( &db->transforms );
277 db->strings = msi_load_string_table( stg, &db->bytes_per_strref );
278 if( !db->strings )
279 goto end;
281 ret = ERROR_SUCCESS;
283 msiobj_addref( &db->hdr );
284 IStorage_AddRef( stg );
285 *pdb = db;
287 end:
288 if( db )
289 msiobj_release( &db->hdr );
290 if( stg )
291 IStorage_Release( stg );
293 return ret;
296 UINT WINAPI MsiOpenDatabaseW(LPCWSTR szDBPath, LPCWSTR szPersist, MSIHANDLE *phDB)
298 MSIDATABASE *db;
299 UINT ret;
301 TRACE("%s %s %p\n",debugstr_w(szDBPath),debugstr_w(szPersist), phDB);
303 ret = MSI_OpenDatabaseW( szDBPath, szPersist, &db );
304 if( ret == ERROR_SUCCESS )
306 *phDB = alloc_msihandle( &db->hdr );
307 if (! *phDB)
308 ret = ERROR_NOT_ENOUGH_MEMORY;
309 msiobj_release( &db->hdr );
312 return ret;
315 UINT WINAPI MsiOpenDatabaseA(LPCSTR szDBPath, LPCSTR szPersist, MSIHANDLE *phDB)
317 HRESULT r = ERROR_FUNCTION_FAILED;
318 LPWSTR szwDBPath = NULL, szwPersist = NULL;
320 TRACE("%s %s %p\n", debugstr_a(szDBPath), debugstr_a(szPersist), phDB);
322 if( szDBPath )
324 szwDBPath = strdupAtoW( szDBPath );
325 if( !szwDBPath )
326 goto end;
329 if( !IS_INTMSIDBOPEN(szPersist) )
331 szwPersist = strdupAtoW( szPersist );
332 if( !szwPersist )
333 goto end;
335 else
336 szwPersist = (LPWSTR)(DWORD_PTR)szPersist;
338 r = MsiOpenDatabaseW( szwDBPath, szwPersist, phDB );
340 end:
341 if( !IS_INTMSIDBOPEN(szPersist) )
342 msi_free( szwPersist );
343 msi_free( szwDBPath );
345 return r;
348 static LPWSTR msi_read_text_archive(LPCWSTR path, DWORD *len)
350 HANDLE file;
351 LPSTR data = NULL;
352 LPWSTR wdata = NULL;
353 DWORD read, size = 0;
355 file = CreateFileW( path, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL );
356 if (file == INVALID_HANDLE_VALUE)
357 return NULL;
359 size = GetFileSize( file, NULL );
360 if (!(data = msi_alloc( size ))) goto done;
362 if (!ReadFile( file, data, size, &read, NULL ) || read != size) goto done;
364 while (!data[size - 1]) size--;
365 *len = MultiByteToWideChar( CP_ACP, 0, data, size, NULL, 0 );
366 if ((wdata = msi_alloc( (*len + 1) * sizeof(WCHAR) )))
368 MultiByteToWideChar( CP_ACP, 0, data, size, wdata, *len );
369 wdata[*len] = 0;
372 done:
373 CloseHandle( file );
374 msi_free( data );
375 return wdata;
378 static void msi_parse_line(LPWSTR *line, LPWSTR **entries, DWORD *num_entries, DWORD *len)
380 LPWSTR ptr = *line, save;
381 DWORD i, count = 1, chars_left = *len;
383 *entries = NULL;
385 /* stay on this line */
386 while (chars_left && *ptr != '\n')
388 /* entries are separated by tabs */
389 if (*ptr == '\t')
390 count++;
392 ptr++;
393 chars_left--;
396 *entries = msi_alloc(count * sizeof(LPWSTR));
397 if (!*entries)
398 return;
400 /* store pointers into the data */
401 chars_left = *len;
402 for (i = 0, ptr = *line; i < count; i++)
404 while (chars_left && *ptr == '\r')
406 ptr++;
407 chars_left--;
409 save = ptr;
411 while (chars_left && *ptr != '\t' && *ptr != '\n' && *ptr != '\r')
413 if (!*ptr) *ptr = '\n'; /* convert embedded nulls to \n */
414 if (ptr > *line && *ptr == '\x19' && *(ptr - 1) == '\x11')
416 *ptr = '\n';
417 *(ptr - 1) = '\r';
419 ptr++;
420 chars_left--;
423 /* NULL-separate the data */
424 if (*ptr == '\n' || *ptr == '\r')
426 while (chars_left && (*ptr == '\n' || *ptr == '\r'))
428 *(ptr++) = 0;
429 chars_left--;
432 else if (*ptr)
434 *(ptr++) = 0;
435 chars_left--;
437 (*entries)[i] = save;
440 /* move to the next line if there's more, else EOF */
441 *line = ptr;
442 *len = chars_left;
443 if (num_entries)
444 *num_entries = count;
447 static LPWSTR msi_build_createsql_prelude(LPWSTR table)
449 LPWSTR prelude;
450 DWORD size;
452 static const WCHAR create_fmt[] = {'C','R','E','A','T','E',' ','T','A','B','L','E',' ','`','%','s','`',' ','(',' ',0};
454 size = sizeof(create_fmt)/sizeof(create_fmt[0]) + lstrlenW(table) - 2;
455 prelude = msi_alloc(size * sizeof(WCHAR));
456 if (!prelude)
457 return NULL;
459 sprintfW(prelude, create_fmt, table);
460 return prelude;
463 static LPWSTR msi_build_createsql_columns(LPWSTR *columns_data, LPWSTR *types, DWORD num_columns)
465 LPWSTR columns, p;
466 LPCWSTR type;
467 DWORD sql_size = 1, i, len;
468 WCHAR expanded[128], *ptr;
469 WCHAR size[10], comma[2], extra[30];
471 static const WCHAR column_fmt[] = {'`','%','s','`',' ','%','s','%','s','%','s','%','s',' ',0};
472 static const WCHAR size_fmt[] = {'(','%','s',')',0};
473 static const WCHAR type_char[] = {'C','H','A','R',0};
474 static const WCHAR type_int[] = {'I','N','T',0};
475 static const WCHAR type_long[] = {'L','O','N','G',0};
476 static const WCHAR type_object[] = {'O','B','J','E','C','T',0};
477 static const WCHAR type_notnull[] = {' ','N','O','T',' ','N','U','L','L',0};
478 static const WCHAR localizable[] = {' ','L','O','C','A','L','I','Z','A','B','L','E',0};
480 columns = msi_alloc_zero(sql_size * sizeof(WCHAR));
481 if (!columns)
482 return NULL;
484 for (i = 0; i < num_columns; i++)
486 type = NULL;
487 comma[1] = size[0] = extra[0] = '\0';
489 if (i == num_columns - 1)
490 comma[0] = '\0';
491 else
492 comma[0] = ',';
494 ptr = &types[i][1];
495 len = atolW(ptr);
496 extra[0] = '\0';
498 switch (types[i][0])
500 case 'l':
501 lstrcpyW(extra, type_notnull);
502 /* fall through */
503 case 'L':
504 lstrcatW(extra, localizable);
505 type = type_char;
506 sprintfW(size, size_fmt, ptr);
507 break;
508 case 's':
509 lstrcpyW(extra, type_notnull);
510 /* fall through */
511 case 'S':
512 type = type_char;
513 sprintfW(size, size_fmt, ptr);
514 break;
515 case 'i':
516 lstrcpyW(extra, type_notnull);
517 /* fall through */
518 case 'I':
519 if (len <= 2)
520 type = type_int;
521 else if (len == 4)
522 type = type_long;
523 else
525 WARN("invalid int width %u\n", len);
526 msi_free(columns);
527 return NULL;
529 break;
530 case 'v':
531 lstrcpyW(extra, type_notnull);
532 /* fall through */
533 case 'V':
534 type = type_object;
535 break;
536 default:
537 ERR("Unknown type: %c\n", types[i][0]);
538 msi_free(columns);
539 return NULL;
542 sprintfW(expanded, column_fmt, columns_data[i], type, size, extra, comma);
543 sql_size += lstrlenW(expanded);
545 p = msi_realloc(columns, sql_size * sizeof(WCHAR));
546 if (!p)
548 msi_free(columns);
549 return NULL;
551 columns = p;
553 lstrcatW(columns, expanded);
556 return columns;
559 static LPWSTR msi_build_createsql_postlude(LPWSTR *primary_keys, DWORD num_keys)
561 LPWSTR postlude, keys, ptr;
562 DWORD size, key_size, i;
564 static const WCHAR key_fmt[] = {'`','%','s','`',',',' ',0};
565 static const WCHAR postlude_fmt[] = {'P','R','I','M','A','R','Y',' ','K','E','Y',' ','%','s',')',0};
567 for (i = 0, size = 1; i < num_keys; i++)
568 size += lstrlenW(key_fmt) + lstrlenW(primary_keys[i]) - 2;
570 keys = msi_alloc(size * sizeof(WCHAR));
571 if (!keys)
572 return NULL;
574 for (i = 0, ptr = keys; i < num_keys; i++)
576 key_size = lstrlenW(key_fmt) + lstrlenW(primary_keys[i]) -2;
577 sprintfW(ptr, key_fmt, primary_keys[i]);
578 ptr += key_size;
581 /* remove final ', ' */
582 *(ptr - 2) = '\0';
584 size = lstrlenW(postlude_fmt) + size - 1;
585 postlude = msi_alloc(size * sizeof(WCHAR));
586 if (!postlude)
587 goto done;
589 sprintfW(postlude, postlude_fmt, keys);
591 done:
592 msi_free(keys);
593 return postlude;
596 static UINT msi_add_table_to_db(MSIDATABASE *db, LPWSTR *columns, LPWSTR *types, LPWSTR *labels, DWORD num_labels, DWORD num_columns)
598 UINT r = ERROR_OUTOFMEMORY;
599 DWORD size;
600 MSIQUERY *view;
601 LPWSTR create_sql = NULL;
602 LPWSTR prelude, columns_sql, postlude;
604 prelude = msi_build_createsql_prelude(labels[0]);
605 columns_sql = msi_build_createsql_columns(columns, types, num_columns);
606 postlude = msi_build_createsql_postlude(labels + 1, num_labels - 1); /* skip over table name */
608 if (!prelude || !columns_sql || !postlude)
609 goto done;
611 size = lstrlenW(prelude) + lstrlenW(columns_sql) + lstrlenW(postlude) + 1;
612 create_sql = msi_alloc(size * sizeof(WCHAR));
613 if (!create_sql)
614 goto done;
616 lstrcpyW(create_sql, prelude);
617 lstrcatW(create_sql, columns_sql);
618 lstrcatW(create_sql, postlude);
620 r = MSI_DatabaseOpenViewW( db, create_sql, &view );
621 if (r != ERROR_SUCCESS)
622 goto done;
624 r = MSI_ViewExecute(view, NULL);
625 MSI_ViewClose(view);
626 msiobj_release(&view->hdr);
628 done:
629 msi_free(prelude);
630 msi_free(columns_sql);
631 msi_free(postlude);
632 msi_free(create_sql);
633 return r;
636 static LPWSTR msi_import_stream_filename(LPCWSTR path, LPCWSTR name)
638 DWORD len;
639 LPWSTR fullname, ptr;
641 len = lstrlenW(path) + lstrlenW(name) + 1;
642 fullname = msi_alloc(len*sizeof(WCHAR));
643 if (!fullname)
644 return NULL;
646 lstrcpyW( fullname, path );
648 /* chop off extension from path */
649 ptr = strrchrW(fullname, '.');
650 if (!ptr)
652 msi_free (fullname);
653 return NULL;
655 *ptr++ = '\\';
656 lstrcpyW( ptr, name );
657 return fullname;
660 static UINT construct_record(DWORD num_columns, LPWSTR *types,
661 LPWSTR *data, LPWSTR path, MSIRECORD **rec)
663 UINT i;
665 *rec = MSI_CreateRecord(num_columns);
666 if (!*rec)
667 return ERROR_OUTOFMEMORY;
669 for (i = 0; i < num_columns; i++)
671 switch (types[i][0])
673 case 'L': case 'l': case 'S': case 's':
674 MSI_RecordSetStringW(*rec, i + 1, data[i]);
675 break;
676 case 'I': case 'i':
677 if (*data[i])
678 MSI_RecordSetInteger(*rec, i + 1, atoiW(data[i]));
679 break;
680 case 'V': case 'v':
681 if (*data[i])
683 UINT r;
684 LPWSTR file = msi_import_stream_filename(path, data[i]);
685 if (!file)
686 return ERROR_FUNCTION_FAILED;
688 r = MSI_RecordSetStreamFromFileW(*rec, i + 1, file);
689 msi_free (file);
690 if (r != ERROR_SUCCESS)
691 return ERROR_FUNCTION_FAILED;
693 break;
694 default:
695 ERR("Unhandled column type: %c\n", types[i][0]);
696 msiobj_release(&(*rec)->hdr);
697 return ERROR_FUNCTION_FAILED;
701 return ERROR_SUCCESS;
704 static UINT msi_add_records_to_table(MSIDATABASE *db, LPWSTR *columns, LPWSTR *types,
705 LPWSTR *labels, LPWSTR **records,
706 int num_columns, int num_records,
707 LPWSTR path)
709 UINT r;
710 int i;
711 MSIQUERY *view;
712 MSIRECORD *rec;
714 static const WCHAR select[] = {
715 'S','E','L','E','C','T',' ','*',' ',
716 'F','R','O','M',' ','`','%','s','`',0
719 r = MSI_OpenQuery(db, &view, select, labels[0]);
720 if (r != ERROR_SUCCESS)
721 return r;
723 while (MSI_ViewFetch(view, &rec) != ERROR_NO_MORE_ITEMS)
725 r = MSI_ViewModify(view, MSIMODIFY_DELETE, rec);
726 msiobj_release(&rec->hdr);
727 if (r != ERROR_SUCCESS)
728 goto done;
731 for (i = 0; i < num_records; i++)
733 r = construct_record(num_columns, types, records[i], path, &rec);
734 if (r != ERROR_SUCCESS)
735 goto done;
737 r = MSI_ViewModify(view, MSIMODIFY_INSERT, rec);
738 if (r != ERROR_SUCCESS)
740 msiobj_release(&rec->hdr);
741 goto done;
744 msiobj_release(&rec->hdr);
747 done:
748 msiobj_release(&view->hdr);
749 return r;
752 static UINT MSI_DatabaseImport(MSIDATABASE *db, LPCWSTR folder, LPCWSTR file)
754 UINT r;
755 DWORD len, i;
756 DWORD num_labels, num_types;
757 DWORD num_columns, num_records = 0;
758 LPWSTR *columns, *types, *labels;
759 LPWSTR path, ptr, data;
760 LPWSTR **records = NULL;
761 LPWSTR **temp_records;
763 static const WCHAR suminfo[] =
764 {'_','S','u','m','m','a','r','y','I','n','f','o','r','m','a','t','i','o','n',0};
765 static const WCHAR forcecodepage[] =
766 {'_','F','o','r','c','e','C','o','d','e','p','a','g','e',0};
768 TRACE("%p %s %s\n", db, debugstr_w(folder), debugstr_w(file) );
770 if( folder == NULL || file == NULL )
771 return ERROR_INVALID_PARAMETER;
773 len = lstrlenW(folder) + lstrlenW(szBackSlash) + lstrlenW(file) + 1;
774 path = msi_alloc( len * sizeof(WCHAR) );
775 if (!path)
776 return ERROR_OUTOFMEMORY;
778 lstrcpyW( path, folder );
779 lstrcatW( path, szBackSlash );
780 lstrcatW( path, file );
782 data = msi_read_text_archive( path, &len );
784 ptr = data;
785 msi_parse_line( &ptr, &columns, &num_columns, &len );
786 msi_parse_line( &ptr, &types, &num_types, &len );
787 msi_parse_line( &ptr, &labels, &num_labels, &len );
789 if (num_columns == 1 && !columns[0][0] && num_labels == 1 && !labels[0][0] &&
790 num_types == 2 && !strcmpW( types[1], forcecodepage ))
792 r = msi_set_string_table_codepage( db->strings, atoiW( types[0] ) );
793 goto done;
796 if (num_columns != num_types)
798 r = ERROR_FUNCTION_FAILED;
799 goto done;
802 records = msi_alloc(sizeof(LPWSTR *));
803 if (!records)
805 r = ERROR_OUTOFMEMORY;
806 goto done;
809 /* read in the table records */
810 while (len)
812 msi_parse_line( &ptr, &records[num_records], NULL, &len );
814 num_records++;
815 temp_records = msi_realloc(records, (num_records + 1) * sizeof(LPWSTR *));
816 if (!temp_records)
818 r = ERROR_OUTOFMEMORY;
819 goto done;
821 records = temp_records;
824 if (!strcmpW(labels[0], suminfo))
826 r = msi_add_suminfo( db, records, num_records, num_columns );
827 if (r != ERROR_SUCCESS)
829 r = ERROR_FUNCTION_FAILED;
830 goto done;
833 else
835 if (!TABLE_Exists(db, labels[0]))
837 r = msi_add_table_to_db( db, columns, types, labels, num_labels, num_columns );
838 if (r != ERROR_SUCCESS)
840 r = ERROR_FUNCTION_FAILED;
841 goto done;
845 r = msi_add_records_to_table( db, columns, types, labels, records, num_columns, num_records, path );
848 done:
849 msi_free(path);
850 msi_free(data);
851 msi_free(columns);
852 msi_free(types);
853 msi_free(labels);
855 for (i = 0; i < num_records; i++)
856 msi_free(records[i]);
858 msi_free(records);
860 return r;
863 UINT WINAPI MsiDatabaseImportW(MSIHANDLE handle, LPCWSTR szFolder, LPCWSTR szFilename)
865 MSIDATABASE *db;
866 UINT r;
868 TRACE("%x %s %s\n",handle,debugstr_w(szFolder), debugstr_w(szFilename));
870 db = msihandle2msiinfo( handle, MSIHANDLETYPE_DATABASE );
871 if( !db )
873 IWineMsiRemoteDatabase *remote_database;
875 remote_database = (IWineMsiRemoteDatabase *)msi_get_remote( handle );
876 if ( !remote_database )
877 return ERROR_INVALID_HANDLE;
879 IWineMsiRemoteDatabase_Release( remote_database );
880 WARN("MsiDatabaseImport not allowed during a custom action!\n");
882 return ERROR_SUCCESS;
885 r = MSI_DatabaseImport( db, szFolder, szFilename );
886 msiobj_release( &db->hdr );
887 return r;
890 UINT WINAPI MsiDatabaseImportA( MSIHANDLE handle,
891 LPCSTR szFolder, LPCSTR szFilename )
893 LPWSTR path = NULL, file = NULL;
894 UINT r = ERROR_OUTOFMEMORY;
896 TRACE("%x %s %s\n", handle, debugstr_a(szFolder), debugstr_a(szFilename));
898 if( szFolder )
900 path = strdupAtoW( szFolder );
901 if( !path )
902 goto end;
905 if( szFilename )
907 file = strdupAtoW( szFilename );
908 if( !file )
909 goto end;
912 r = MsiDatabaseImportW( handle, path, file );
914 end:
915 msi_free( path );
916 msi_free( file );
918 return r;
921 static UINT msi_export_record( HANDLE handle, MSIRECORD *row, UINT start )
923 UINT i, count, len, r = ERROR_SUCCESS;
924 const char *sep;
925 char *buffer;
926 DWORD sz;
928 len = 0x100;
929 buffer = msi_alloc( len );
930 if ( !buffer )
931 return ERROR_OUTOFMEMORY;
933 count = MSI_RecordGetFieldCount( row );
934 for ( i=start; i<=count; i++ )
936 sz = len;
937 r = MSI_RecordGetStringA( row, i, buffer, &sz );
938 if (r == ERROR_MORE_DATA)
940 char *p = msi_realloc( buffer, sz + 1 );
941 if (!p)
942 break;
943 len = sz + 1;
944 buffer = p;
946 sz = len;
947 r = MSI_RecordGetStringA( row, i, buffer, &sz );
948 if (r != ERROR_SUCCESS)
949 break;
951 if (!WriteFile( handle, buffer, sz, &sz, NULL ))
953 r = ERROR_FUNCTION_FAILED;
954 break;
957 sep = (i < count) ? "\t" : "\r\n";
958 if (!WriteFile( handle, sep, strlen(sep), &sz, NULL ))
960 r = ERROR_FUNCTION_FAILED;
961 break;
964 msi_free( buffer );
965 return r;
968 static UINT msi_export_row( MSIRECORD *row, void *arg )
970 return msi_export_record( arg, row, 1 );
973 static UINT msi_export_forcecodepage( HANDLE handle, UINT codepage )
975 static const char fmt[] = "\r\n\r\n%u\t_ForceCodepage\r\n";
976 char data[sizeof(fmt) + 10];
977 DWORD sz;
979 sprintf( data, fmt, codepage );
981 sz = lstrlenA(data) + 1;
982 if (!WriteFile(handle, data, sz, &sz, NULL))
983 return ERROR_FUNCTION_FAILED;
985 return ERROR_SUCCESS;
988 static UINT MSI_DatabaseExport( MSIDATABASE *db, LPCWSTR table,
989 LPCWSTR folder, LPCWSTR file )
991 static const WCHAR query[] = {
992 's','e','l','e','c','t',' ','*',' ','f','r','o','m',' ','%','s',0 };
993 static const WCHAR forcecodepage[] = {
994 '_','F','o','r','c','e','C','o','d','e','p','a','g','e',0 };
995 MSIRECORD *rec = NULL;
996 MSIQUERY *view = NULL;
997 LPWSTR filename;
998 HANDLE handle;
999 UINT len, r;
1001 TRACE("%p %s %s %s\n", db, debugstr_w(table),
1002 debugstr_w(folder), debugstr_w(file) );
1004 if( folder == NULL || file == NULL )
1005 return ERROR_INVALID_PARAMETER;
1007 len = lstrlenW(folder) + lstrlenW(file) + 2;
1008 filename = msi_alloc(len * sizeof (WCHAR));
1009 if (!filename)
1010 return ERROR_OUTOFMEMORY;
1012 lstrcpyW( filename, folder );
1013 lstrcatW( filename, szBackSlash );
1014 lstrcatW( filename, file );
1016 handle = CreateFileW( filename, GENERIC_READ | GENERIC_WRITE, 0,
1017 NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );
1018 msi_free( filename );
1019 if (handle == INVALID_HANDLE_VALUE)
1020 return ERROR_FUNCTION_FAILED;
1022 if (!strcmpW( table, forcecodepage ))
1024 UINT codepage = msi_get_string_table_codepage( db->strings );
1025 r = msi_export_forcecodepage( handle, codepage );
1026 goto done;
1029 r = MSI_OpenQuery( db, &view, query, table );
1030 if (r == ERROR_SUCCESS)
1032 /* write out row 1, the column names */
1033 r = MSI_ViewGetColumnInfo(view, MSICOLINFO_NAMES, &rec);
1034 if (r == ERROR_SUCCESS)
1036 msi_export_record( handle, rec, 1 );
1037 msiobj_release( &rec->hdr );
1040 /* write out row 2, the column types */
1041 r = MSI_ViewGetColumnInfo(view, MSICOLINFO_TYPES, &rec);
1042 if (r == ERROR_SUCCESS)
1044 msi_export_record( handle, rec, 1 );
1045 msiobj_release( &rec->hdr );
1048 /* write out row 3, the table name + keys */
1049 r = MSI_DatabaseGetPrimaryKeys( db, table, &rec );
1050 if (r == ERROR_SUCCESS)
1052 MSI_RecordSetStringW( rec, 0, table );
1053 msi_export_record( handle, rec, 0 );
1054 msiobj_release( &rec->hdr );
1057 /* write out row 4 onwards, the data */
1058 r = MSI_IterateRecords( view, 0, msi_export_row, handle );
1059 msiobj_release( &view->hdr );
1062 done:
1063 CloseHandle( handle );
1064 return r;
1067 /***********************************************************************
1068 * MsiExportDatabaseW [MSI.@]
1070 * Writes a file containing the table data as tab separated ASCII.
1072 * The format is as follows:
1074 * row1 : colname1 <tab> colname2 <tab> .... colnameN <cr> <lf>
1075 * row2 : coltype1 <tab> coltype2 <tab> .... coltypeN <cr> <lf>
1076 * row3 : tablename <tab> key1 <tab> key2 <tab> ... keyM <cr> <lf>
1078 * Followed by the data, starting at row 1 with one row per line
1080 * row4 : data <tab> data <tab> data <tab> ... data <cr> <lf>
1082 UINT WINAPI MsiDatabaseExportW( MSIHANDLE handle, LPCWSTR szTable,
1083 LPCWSTR szFolder, LPCWSTR szFilename )
1085 MSIDATABASE *db;
1086 UINT r;
1088 TRACE("%x %s %s %s\n", handle, debugstr_w(szTable),
1089 debugstr_w(szFolder), debugstr_w(szFilename));
1091 db = msihandle2msiinfo( handle, MSIHANDLETYPE_DATABASE );
1092 if( !db )
1094 IWineMsiRemoteDatabase *remote_database;
1096 remote_database = (IWineMsiRemoteDatabase *)msi_get_remote( handle );
1097 if ( !remote_database )
1098 return ERROR_INVALID_HANDLE;
1100 IWineMsiRemoteDatabase_Release( remote_database );
1101 WARN("MsiDatabaseExport not allowed during a custom action!\n");
1103 return ERROR_SUCCESS;
1106 r = MSI_DatabaseExport( db, szTable, szFolder, szFilename );
1107 msiobj_release( &db->hdr );
1108 return r;
1111 UINT WINAPI MsiDatabaseExportA( MSIHANDLE handle, LPCSTR szTable,
1112 LPCSTR szFolder, LPCSTR szFilename )
1114 LPWSTR path = NULL, file = NULL, table = NULL;
1115 UINT r = ERROR_OUTOFMEMORY;
1117 TRACE("%x %s %s %s\n", handle, debugstr_a(szTable),
1118 debugstr_a(szFolder), debugstr_a(szFilename));
1120 if( szTable )
1122 table = strdupAtoW( szTable );
1123 if( !table )
1124 goto end;
1127 if( szFolder )
1129 path = strdupAtoW( szFolder );
1130 if( !path )
1131 goto end;
1134 if( szFilename )
1136 file = strdupAtoW( szFilename );
1137 if( !file )
1138 goto end;
1141 r = MsiDatabaseExportW( handle, table, path, file );
1143 end:
1144 msi_free( table );
1145 msi_free( path );
1146 msi_free( file );
1148 return r;
1151 UINT WINAPI MsiDatabaseMergeA(MSIHANDLE hDatabase, MSIHANDLE hDatabaseMerge,
1152 LPCSTR szTableName)
1154 UINT r;
1155 LPWSTR table;
1157 TRACE("(%d, %d, %s)\n", hDatabase, hDatabaseMerge,
1158 debugstr_a(szTableName));
1160 table = strdupAtoW(szTableName);
1161 r = MsiDatabaseMergeW(hDatabase, hDatabaseMerge, table);
1163 msi_free(table);
1164 return r;
1167 typedef struct _tagMERGETABLE
1169 struct list entry;
1170 struct list rows;
1171 LPWSTR name;
1172 DWORD numconflicts;
1173 LPWSTR *columns;
1174 DWORD numcolumns;
1175 LPWSTR *types;
1176 DWORD numtypes;
1177 LPWSTR *labels;
1178 DWORD numlabels;
1179 } MERGETABLE;
1181 typedef struct _tagMERGEROW
1183 struct list entry;
1184 MSIRECORD *data;
1185 } MERGEROW;
1187 typedef struct _tagMERGEDATA
1189 MSIDATABASE *db;
1190 MSIDATABASE *merge;
1191 MERGETABLE *curtable;
1192 MSIQUERY *curview;
1193 struct list *tabledata;
1194 } MERGEDATA;
1196 static BOOL merge_type_match(LPCWSTR type1, LPCWSTR type2)
1198 if (((type1[0] == 'l') || (type1[0] == 's')) &&
1199 ((type2[0] == 'l') || (type2[0] == 's')))
1200 return TRUE;
1202 if (((type1[0] == 'L') || (type1[0] == 'S')) &&
1203 ((type2[0] == 'L') || (type2[0] == 'S')))
1204 return TRUE;
1206 return !strcmpW( type1, type2 );
1209 static UINT merge_verify_colnames(MSIQUERY *dbview, MSIQUERY *mergeview)
1211 MSIRECORD *dbrec, *mergerec;
1212 UINT r, i, count;
1214 r = MSI_ViewGetColumnInfo(dbview, MSICOLINFO_NAMES, &dbrec);
1215 if (r != ERROR_SUCCESS)
1216 return r;
1218 r = MSI_ViewGetColumnInfo(mergeview, MSICOLINFO_NAMES, &mergerec);
1219 if (r != ERROR_SUCCESS)
1221 msiobj_release(&dbrec->hdr);
1222 return r;
1225 count = MSI_RecordGetFieldCount(dbrec);
1226 for (i = 1; i <= count; i++)
1228 if (!MSI_RecordGetString(mergerec, i))
1229 break;
1231 if (strcmpW( MSI_RecordGetString( dbrec, i ), MSI_RecordGetString( mergerec, i ) ))
1233 r = ERROR_DATATYPE_MISMATCH;
1234 goto done;
1238 msiobj_release(&dbrec->hdr);
1239 msiobj_release(&mergerec->hdr);
1240 dbrec = mergerec = NULL;
1242 r = MSI_ViewGetColumnInfo(dbview, MSICOLINFO_TYPES, &dbrec);
1243 if (r != ERROR_SUCCESS)
1244 return r;
1246 r = MSI_ViewGetColumnInfo(mergeview, MSICOLINFO_TYPES, &mergerec);
1247 if (r != ERROR_SUCCESS)
1249 msiobj_release(&dbrec->hdr);
1250 return r;
1253 count = MSI_RecordGetFieldCount(dbrec);
1254 for (i = 1; i <= count; i++)
1256 if (!MSI_RecordGetString(mergerec, i))
1257 break;
1259 if (!merge_type_match(MSI_RecordGetString(dbrec, i),
1260 MSI_RecordGetString(mergerec, i)))
1262 r = ERROR_DATATYPE_MISMATCH;
1263 break;
1267 done:
1268 msiobj_release(&dbrec->hdr);
1269 msiobj_release(&mergerec->hdr);
1271 return r;
1274 static UINT merge_verify_primary_keys(MSIDATABASE *db, MSIDATABASE *mergedb,
1275 LPCWSTR table)
1277 MSIRECORD *dbrec, *mergerec = NULL;
1278 UINT r, i, count;
1280 r = MSI_DatabaseGetPrimaryKeys(db, table, &dbrec);
1281 if (r != ERROR_SUCCESS)
1282 return r;
1284 r = MSI_DatabaseGetPrimaryKeys(mergedb, table, &mergerec);
1285 if (r != ERROR_SUCCESS)
1286 goto done;
1288 count = MSI_RecordGetFieldCount(dbrec);
1289 if (count != MSI_RecordGetFieldCount(mergerec))
1291 r = ERROR_DATATYPE_MISMATCH;
1292 goto done;
1295 for (i = 1; i <= count; i++)
1297 if (strcmpW( MSI_RecordGetString( dbrec, i ), MSI_RecordGetString( mergerec, i ) ))
1299 r = ERROR_DATATYPE_MISMATCH;
1300 goto done;
1304 done:
1305 msiobj_release(&dbrec->hdr);
1306 msiobj_release(&mergerec->hdr);
1308 return r;
1311 static LPWSTR get_key_value(MSIQUERY *view, LPCWSTR key, MSIRECORD *rec)
1313 MSIRECORD *colnames;
1314 LPWSTR str, val;
1315 UINT r, i = 0, sz = 0;
1316 int cmp;
1318 r = MSI_ViewGetColumnInfo(view, MSICOLINFO_NAMES, &colnames);
1319 if (r != ERROR_SUCCESS)
1320 return NULL;
1324 str = msi_dup_record_field(colnames, ++i);
1325 cmp = strcmpW( key, str );
1326 msi_free(str);
1327 } while (cmp);
1329 msiobj_release(&colnames->hdr);
1331 r = MSI_RecordGetStringW(rec, i, NULL, &sz);
1332 if (r != ERROR_SUCCESS)
1333 return NULL;
1334 sz++;
1336 if (MSI_RecordGetString(rec, i)) /* check record field is a string */
1338 /* quote string record fields */
1339 const WCHAR szQuote[] = {'\'', 0};
1340 sz += 2;
1341 val = msi_alloc(sz*sizeof(WCHAR));
1342 if (!val)
1343 return NULL;
1345 lstrcpyW(val, szQuote);
1346 r = MSI_RecordGetStringW(rec, i, val+1, &sz);
1347 lstrcpyW(val+1+sz, szQuote);
1349 else
1351 /* do not quote integer record fields */
1352 val = msi_alloc(sz*sizeof(WCHAR));
1353 if (!val)
1354 return NULL;
1356 r = MSI_RecordGetStringW(rec, i, val, &sz);
1359 if (r != ERROR_SUCCESS)
1361 ERR("failed to get string!\n");
1362 msi_free(val);
1363 return NULL;
1366 return val;
1369 static LPWSTR create_diff_row_query(MSIDATABASE *merge, MSIQUERY *view,
1370 LPWSTR table, MSIRECORD *rec)
1372 LPWSTR query = NULL, clause = NULL, val;
1373 LPCWSTR setptr, key;
1374 DWORD size, oldsize;
1375 MSIRECORD *keys;
1376 UINT r, i, count;
1378 static const WCHAR keyset[] = {
1379 '`','%','s','`',' ','=',' ','%','s',' ','A','N','D',' ',0};
1380 static const WCHAR lastkeyset[] = {
1381 '`','%','s','`',' ','=',' ','%','s',' ',0};
1382 static const WCHAR fmt[] = {'S','E','L','E','C','T',' ','*',' ',
1383 'F','R','O','M',' ','`','%','s','`',' ',
1384 'W','H','E','R','E',' ','%','s',0};
1386 r = MSI_DatabaseGetPrimaryKeys(merge, table, &keys);
1387 if (r != ERROR_SUCCESS)
1388 return NULL;
1390 clause = msi_alloc_zero(sizeof(WCHAR));
1391 if (!clause)
1392 goto done;
1394 size = 1;
1395 count = MSI_RecordGetFieldCount(keys);
1396 for (i = 1; i <= count; i++)
1398 key = MSI_RecordGetString(keys, i);
1399 val = get_key_value(view, key, rec);
1401 if (i == count)
1402 setptr = lastkeyset;
1403 else
1404 setptr = keyset;
1406 oldsize = size;
1407 size += lstrlenW(setptr) + lstrlenW(key) + lstrlenW(val) - 4;
1408 clause = msi_realloc(clause, size * sizeof (WCHAR));
1409 if (!clause)
1411 msi_free(val);
1412 goto done;
1415 sprintfW(clause + oldsize - 1, setptr, key, val);
1416 msi_free(val);
1419 size = lstrlenW(fmt) + lstrlenW(table) + lstrlenW(clause) + 1;
1420 query = msi_alloc(size * sizeof(WCHAR));
1421 if (!query)
1422 goto done;
1424 sprintfW(query, fmt, table, clause);
1426 done:
1427 msi_free(clause);
1428 msiobj_release(&keys->hdr);
1429 return query;
1432 static UINT merge_diff_row(MSIRECORD *rec, LPVOID param)
1434 MERGEDATA *data = param;
1435 MERGETABLE *table = data->curtable;
1436 MERGEROW *mergerow;
1437 MSIQUERY *dbview = NULL;
1438 MSIRECORD *row = NULL;
1439 LPWSTR query = NULL;
1440 UINT r = ERROR_SUCCESS;
1442 if (TABLE_Exists(data->db, table->name))
1444 query = create_diff_row_query(data->merge, data->curview, table->name, rec);
1445 if (!query)
1446 return ERROR_OUTOFMEMORY;
1448 r = MSI_DatabaseOpenViewW(data->db, query, &dbview);
1449 if (r != ERROR_SUCCESS)
1450 goto done;
1452 r = MSI_ViewExecute(dbview, NULL);
1453 if (r != ERROR_SUCCESS)
1454 goto done;
1456 r = MSI_ViewFetch(dbview, &row);
1457 if (r == ERROR_SUCCESS && !MSI_RecordsAreEqual(rec, row))
1459 table->numconflicts++;
1460 goto done;
1462 else if (r != ERROR_NO_MORE_ITEMS)
1463 goto done;
1465 r = ERROR_SUCCESS;
1468 mergerow = msi_alloc(sizeof(MERGEROW));
1469 if (!mergerow)
1471 r = ERROR_OUTOFMEMORY;
1472 goto done;
1475 mergerow->data = MSI_CloneRecord(rec);
1476 if (!mergerow->data)
1478 r = ERROR_OUTOFMEMORY;
1479 msi_free(mergerow);
1480 goto done;
1483 list_add_tail(&table->rows, &mergerow->entry);
1485 done:
1486 msi_free(query);
1487 msiobj_release(&row->hdr);
1488 msiobj_release(&dbview->hdr);
1489 return r;
1492 static UINT msi_get_table_labels(MSIDATABASE *db, LPCWSTR table, LPWSTR **labels, DWORD *numlabels)
1494 UINT r, i, count;
1495 MSIRECORD *prec = NULL;
1497 r = MSI_DatabaseGetPrimaryKeys(db, table, &prec);
1498 if (r != ERROR_SUCCESS)
1499 return r;
1501 count = MSI_RecordGetFieldCount(prec);
1502 *numlabels = count + 1;
1503 *labels = msi_alloc((*numlabels)*sizeof(LPWSTR));
1504 if (!*labels)
1506 r = ERROR_OUTOFMEMORY;
1507 goto end;
1510 (*labels)[0] = strdupW(table);
1511 for (i=1; i<=count; i++ )
1513 (*labels)[i] = strdupW(MSI_RecordGetString(prec, i));
1516 end:
1517 msiobj_release( &prec->hdr );
1518 return r;
1521 static UINT msi_get_query_columns(MSIQUERY *query, LPWSTR **columns, DWORD *numcolumns)
1523 UINT r, i, count;
1524 MSIRECORD *prec = NULL;
1526 r = MSI_ViewGetColumnInfo(query, MSICOLINFO_NAMES, &prec);
1527 if (r != ERROR_SUCCESS)
1528 return r;
1530 count = MSI_RecordGetFieldCount(prec);
1531 *columns = msi_alloc(count*sizeof(LPWSTR));
1532 if (!*columns)
1534 r = ERROR_OUTOFMEMORY;
1535 goto end;
1538 for (i=1; i<=count; i++ )
1540 (*columns)[i-1] = strdupW(MSI_RecordGetString(prec, i));
1543 *numcolumns = count;
1545 end:
1546 msiobj_release( &prec->hdr );
1547 return r;
1550 static UINT msi_get_query_types(MSIQUERY *query, LPWSTR **types, DWORD *numtypes)
1552 UINT r, i, count;
1553 MSIRECORD *prec = NULL;
1555 r = MSI_ViewGetColumnInfo(query, MSICOLINFO_TYPES, &prec);
1556 if (r != ERROR_SUCCESS)
1557 return r;
1559 count = MSI_RecordGetFieldCount(prec);
1560 *types = msi_alloc(count*sizeof(LPWSTR));
1561 if (!*types)
1563 r = ERROR_OUTOFMEMORY;
1564 goto end;
1567 *numtypes = count;
1568 for (i=1; i<=count; i++ )
1570 (*types)[i-1] = strdupW(MSI_RecordGetString(prec, i));
1573 end:
1574 msiobj_release( &prec->hdr );
1575 return r;
1578 static void merge_free_rows(MERGETABLE *table)
1580 struct list *item, *cursor;
1582 LIST_FOR_EACH_SAFE(item, cursor, &table->rows)
1584 MERGEROW *row = LIST_ENTRY(item, MERGEROW, entry);
1586 list_remove(&row->entry);
1587 msiobj_release(&row->data->hdr);
1588 msi_free(row);
1592 static void free_merge_table(MERGETABLE *table)
1594 UINT i;
1596 if (table->labels != NULL)
1598 for (i = 0; i < table->numlabels; i++)
1599 msi_free(table->labels[i]);
1601 msi_free(table->labels);
1604 if (table->columns != NULL)
1606 for (i = 0; i < table->numcolumns; i++)
1607 msi_free(table->columns[i]);
1609 msi_free(table->columns);
1612 if (table->types != NULL)
1614 for (i = 0; i < table->numtypes; i++)
1615 msi_free(table->types[i]);
1617 msi_free(table->types);
1620 msi_free(table->name);
1621 merge_free_rows(table);
1623 msi_free(table);
1626 static UINT msi_get_merge_table (MSIDATABASE *db, LPCWSTR name, MERGETABLE **ptable)
1628 UINT r;
1629 MERGETABLE *table;
1630 MSIQUERY *mergeview = NULL;
1632 static const WCHAR query[] = {'S','E','L','E','C','T',' ','*',' ',
1633 'F','R','O','M',' ','`','%','s','`',0};
1635 table = msi_alloc_zero(sizeof(MERGETABLE));
1636 if (!table)
1638 *ptable = NULL;
1639 return ERROR_OUTOFMEMORY;
1642 r = msi_get_table_labels(db, name, &table->labels, &table->numlabels);
1643 if (r != ERROR_SUCCESS)
1644 goto err;
1646 r = MSI_OpenQuery(db, &mergeview, query, name);
1647 if (r != ERROR_SUCCESS)
1648 goto err;
1650 r = msi_get_query_columns(mergeview, &table->columns, &table->numcolumns);
1651 if (r != ERROR_SUCCESS)
1652 goto err;
1654 r = msi_get_query_types(mergeview, &table->types, &table->numtypes);
1655 if (r != ERROR_SUCCESS)
1656 goto err;
1658 list_init(&table->rows);
1660 table->name = strdupW(name);
1661 table->numconflicts = 0;
1663 msiobj_release(&mergeview->hdr);
1664 *ptable = table;
1665 return ERROR_SUCCESS;
1667 err:
1668 msiobj_release(&mergeview->hdr);
1669 free_merge_table(table);
1670 *ptable = NULL;
1671 return r;
1674 static UINT merge_diff_tables(MSIRECORD *rec, LPVOID param)
1676 MERGEDATA *data = param;
1677 MERGETABLE *table;
1678 MSIQUERY *dbview = NULL;
1679 MSIQUERY *mergeview = NULL;
1680 LPCWSTR name;
1681 UINT r;
1683 static const WCHAR query[] = {'S','E','L','E','C','T',' ','*',' ',
1684 'F','R','O','M',' ','`','%','s','`',0};
1686 name = MSI_RecordGetString(rec, 1);
1688 r = MSI_OpenQuery(data->merge, &mergeview, query, name);
1689 if (r != ERROR_SUCCESS)
1690 goto done;
1692 if (TABLE_Exists(data->db, name))
1694 r = MSI_OpenQuery(data->db, &dbview, query, name);
1695 if (r != ERROR_SUCCESS)
1696 goto done;
1698 r = merge_verify_colnames(dbview, mergeview);
1699 if (r != ERROR_SUCCESS)
1700 goto done;
1702 r = merge_verify_primary_keys(data->db, data->merge, name);
1703 if (r != ERROR_SUCCESS)
1704 goto done;
1707 r = msi_get_merge_table(data->merge, name, &table);
1708 if (r != ERROR_SUCCESS)
1709 goto done;
1711 data->curtable = table;
1712 data->curview = mergeview;
1713 r = MSI_IterateRecords(mergeview, NULL, merge_diff_row, data);
1714 if (r != ERROR_SUCCESS)
1716 free_merge_table(table);
1717 goto done;
1720 list_add_tail(data->tabledata, &table->entry);
1722 done:
1723 msiobj_release(&dbview->hdr);
1724 msiobj_release(&mergeview->hdr);
1725 return r;
1728 static UINT gather_merge_data(MSIDATABASE *db, MSIDATABASE *merge,
1729 struct list *tabledata)
1731 static const WCHAR query[] = {
1732 'S','E','L','E','C','T',' ','*',' ','F','R','O','M',' ',
1733 '`','_','T','a','b','l','e','s','`',0};
1734 MSIQUERY *view;
1735 MERGEDATA data;
1736 UINT r;
1738 r = MSI_DatabaseOpenViewW(merge, query, &view);
1739 if (r != ERROR_SUCCESS)
1740 return r;
1742 data.db = db;
1743 data.merge = merge;
1744 data.tabledata = tabledata;
1745 r = MSI_IterateRecords(view, NULL, merge_diff_tables, &data);
1746 msiobj_release(&view->hdr);
1747 return r;
1750 static UINT merge_table(MSIDATABASE *db, MERGETABLE *table)
1752 UINT r;
1753 MERGEROW *row;
1754 MSIVIEW *tv;
1756 if (!TABLE_Exists(db, table->name))
1758 r = msi_add_table_to_db(db, table->columns, table->types,
1759 table->labels, table->numlabels, table->numcolumns);
1760 if (r != ERROR_SUCCESS)
1761 return ERROR_FUNCTION_FAILED;
1764 LIST_FOR_EACH_ENTRY(row, &table->rows, MERGEROW, entry)
1766 r = TABLE_CreateView(db, table->name, &tv);
1767 if (r != ERROR_SUCCESS)
1768 return r;
1770 r = tv->ops->insert_row(tv, row->data, -1, FALSE);
1771 tv->ops->delete(tv);
1773 if (r != ERROR_SUCCESS)
1774 return r;
1777 return ERROR_SUCCESS;
1780 static UINT update_merge_errors(MSIDATABASE *db, LPCWSTR error,
1781 LPWSTR table, DWORD numconflicts)
1783 UINT r;
1784 MSIQUERY *view;
1786 static const WCHAR create[] = {
1787 'C','R','E','A','T','E',' ','T','A','B','L','E',' ',
1788 '`','%','s','`',' ','(','`','T','a','b','l','e','`',' ',
1789 'C','H','A','R','(','2','5','5',')',' ','N','O','T',' ',
1790 'N','U','L','L',',',' ','`','N','u','m','R','o','w','M','e','r','g','e',
1791 'C','o','n','f','l','i','c','t','s','`',' ','S','H','O','R','T',' ',
1792 'N','O','T',' ','N','U','L','L',' ','P','R','I','M','A','R','Y',' ',
1793 'K','E','Y',' ','`','T','a','b','l','e','`',')',0};
1794 static const WCHAR insert[] = {
1795 'I','N','S','E','R','T',' ','I','N','T','O',' ',
1796 '`','%','s','`',' ','(','`','T','a','b','l','e','`',',',' ',
1797 '`','N','u','m','R','o','w','M','e','r','g','e',
1798 'C','o','n','f','l','i','c','t','s','`',')',' ','V','A','L','U','E','S',
1799 ' ','(','\'','%','s','\'',',',' ','%','d',')',0};
1801 if (!TABLE_Exists(db, error))
1803 r = MSI_OpenQuery(db, &view, create, error);
1804 if (r != ERROR_SUCCESS)
1805 return r;
1807 r = MSI_ViewExecute(view, NULL);
1808 msiobj_release(&view->hdr);
1809 if (r != ERROR_SUCCESS)
1810 return r;
1813 r = MSI_OpenQuery(db, &view, insert, error, table, numconflicts);
1814 if (r != ERROR_SUCCESS)
1815 return r;
1817 r = MSI_ViewExecute(view, NULL);
1818 msiobj_release(&view->hdr);
1819 return r;
1822 UINT WINAPI MsiDatabaseMergeW(MSIHANDLE hDatabase, MSIHANDLE hDatabaseMerge,
1823 LPCWSTR szTableName)
1825 struct list tabledata = LIST_INIT(tabledata);
1826 struct list *item, *cursor;
1827 MSIDATABASE *db, *merge;
1828 MERGETABLE *table;
1829 BOOL conflicts;
1830 UINT r;
1832 TRACE("(%d, %d, %s)\n", hDatabase, hDatabaseMerge,
1833 debugstr_w(szTableName));
1835 if (szTableName && !*szTableName)
1836 return ERROR_INVALID_TABLE;
1838 db = msihandle2msiinfo(hDatabase, MSIHANDLETYPE_DATABASE);
1839 merge = msihandle2msiinfo(hDatabaseMerge, MSIHANDLETYPE_DATABASE);
1840 if (!db || !merge)
1842 r = ERROR_INVALID_HANDLE;
1843 goto done;
1846 r = gather_merge_data(db, merge, &tabledata);
1847 if (r != ERROR_SUCCESS)
1848 goto done;
1850 conflicts = FALSE;
1851 LIST_FOR_EACH_ENTRY(table, &tabledata, MERGETABLE, entry)
1853 if (table->numconflicts)
1855 conflicts = TRUE;
1857 r = update_merge_errors(db, szTableName, table->name,
1858 table->numconflicts);
1859 if (r != ERROR_SUCCESS)
1860 break;
1862 else
1864 r = merge_table(db, table);
1865 if (r != ERROR_SUCCESS)
1866 break;
1870 LIST_FOR_EACH_SAFE(item, cursor, &tabledata)
1872 MERGETABLE *table = LIST_ENTRY(item, MERGETABLE, entry);
1873 list_remove(&table->entry);
1874 free_merge_table(table);
1877 if (conflicts)
1878 r = ERROR_FUNCTION_FAILED;
1880 done:
1881 msiobj_release(&db->hdr);
1882 msiobj_release(&merge->hdr);
1883 return r;
1886 MSIDBSTATE WINAPI MsiGetDatabaseState( MSIHANDLE handle )
1888 MSIDBSTATE ret = MSIDBSTATE_READ;
1889 MSIDATABASE *db;
1891 TRACE("%d\n", handle);
1893 db = msihandle2msiinfo( handle, MSIHANDLETYPE_DATABASE );
1894 if( !db )
1896 IWineMsiRemoteDatabase *remote_database;
1898 remote_database = (IWineMsiRemoteDatabase *)msi_get_remote( handle );
1899 if ( !remote_database )
1900 return MSIDBSTATE_ERROR;
1902 IWineMsiRemoteDatabase_Release( remote_database );
1903 WARN("MsiGetDatabaseState not allowed during a custom action!\n");
1905 return MSIDBSTATE_READ;
1908 if (db->mode != MSIDBOPEN_READONLY )
1909 ret = MSIDBSTATE_WRITE;
1910 msiobj_release( &db->hdr );
1912 return ret;
1915 typedef struct _msi_remote_database_impl {
1916 IWineMsiRemoteDatabase IWineMsiRemoteDatabase_iface;
1917 MSIHANDLE database;
1918 LONG refs;
1919 } msi_remote_database_impl;
1921 static inline msi_remote_database_impl *impl_from_IWineMsiRemoteDatabase( IWineMsiRemoteDatabase *iface )
1923 return CONTAINING_RECORD(iface, msi_remote_database_impl, IWineMsiRemoteDatabase_iface);
1926 static HRESULT WINAPI mrd_QueryInterface( IWineMsiRemoteDatabase *iface,
1927 REFIID riid,LPVOID *ppobj)
1929 if( IsEqualCLSID( riid, &IID_IUnknown ) ||
1930 IsEqualCLSID( riid, &IID_IWineMsiRemoteDatabase ) )
1932 IWineMsiRemoteDatabase_AddRef( iface );
1933 *ppobj = iface;
1934 return S_OK;
1937 return E_NOINTERFACE;
1940 static ULONG WINAPI mrd_AddRef( IWineMsiRemoteDatabase *iface )
1942 msi_remote_database_impl* This = impl_from_IWineMsiRemoteDatabase( iface );
1944 return InterlockedIncrement( &This->refs );
1947 static ULONG WINAPI mrd_Release( IWineMsiRemoteDatabase *iface )
1949 msi_remote_database_impl* This = impl_from_IWineMsiRemoteDatabase( iface );
1950 ULONG r;
1952 r = InterlockedDecrement( &This->refs );
1953 if (r == 0)
1955 MsiCloseHandle( This->database );
1956 msi_free( This );
1958 return r;
1961 static HRESULT WINAPI mrd_IsTablePersistent( IWineMsiRemoteDatabase *iface,
1962 LPCWSTR table, MSICONDITION *persistent )
1964 msi_remote_database_impl *This = impl_from_IWineMsiRemoteDatabase( iface );
1965 *persistent = MsiDatabaseIsTablePersistentW(This->database, table);
1966 return S_OK;
1969 static HRESULT WINAPI mrd_GetPrimaryKeys( IWineMsiRemoteDatabase *iface,
1970 LPCWSTR table, MSIHANDLE *keys )
1972 msi_remote_database_impl *This = impl_from_IWineMsiRemoteDatabase( iface );
1973 UINT r = MsiDatabaseGetPrimaryKeysW(This->database, table, keys);
1974 return HRESULT_FROM_WIN32(r);
1977 static HRESULT WINAPI mrd_GetSummaryInformation( IWineMsiRemoteDatabase *iface,
1978 UINT updatecount, MSIHANDLE *suminfo )
1980 msi_remote_database_impl *This = impl_from_IWineMsiRemoteDatabase( iface );
1981 UINT r = MsiGetSummaryInformationW(This->database, NULL, updatecount, suminfo);
1982 return HRESULT_FROM_WIN32(r);
1985 static HRESULT WINAPI mrd_OpenView( IWineMsiRemoteDatabase *iface,
1986 LPCWSTR query, MSIHANDLE *view )
1988 msi_remote_database_impl *This = impl_from_IWineMsiRemoteDatabase( iface );
1989 UINT r = MsiDatabaseOpenViewW(This->database, query, view);
1990 return HRESULT_FROM_WIN32(r);
1993 static HRESULT WINAPI mrd_SetMsiHandle( IWineMsiRemoteDatabase *iface, MSIHANDLE handle )
1995 msi_remote_database_impl* This = impl_from_IWineMsiRemoteDatabase( iface );
1996 This->database = handle;
1997 return S_OK;
2000 static const IWineMsiRemoteDatabaseVtbl msi_remote_database_vtbl =
2002 mrd_QueryInterface,
2003 mrd_AddRef,
2004 mrd_Release,
2005 mrd_IsTablePersistent,
2006 mrd_GetPrimaryKeys,
2007 mrd_GetSummaryInformation,
2008 mrd_OpenView,
2009 mrd_SetMsiHandle,
2012 HRESULT create_msi_remote_database( IUnknown *pOuter, LPVOID *ppObj )
2014 msi_remote_database_impl *This;
2016 This = msi_alloc( sizeof *This );
2017 if (!This)
2018 return E_OUTOFMEMORY;
2020 This->IWineMsiRemoteDatabase_iface.lpVtbl = &msi_remote_database_vtbl;
2021 This->database = 0;
2022 This->refs = 1;
2024 *ppObj = &This->IWineMsiRemoteDatabase_iface;
2026 return S_OK;